| from fastapi import APIRouter, HTTPException |
| from fastapi.responses import FileResponse |
| from pydantic import BaseModel |
| from typing import Dict, Optional |
| import json |
| import os |
| from datetime import datetime |
| import uuid |
| import tempfile |
|
|
| router = APIRouter() |
|
|
| BASE_URL = "https://pvanand-doc-maker.hf.space/api/v1" |
| DOCS_DIR = os.path.join(tempfile.gettempdir(), "doc_maker_documents") |
|
|
| class DocumentPart(BaseModel): |
| pageNo: int |
| content: str |
| docId: Optional[str] = None |
|
|
| class DocumentResponse(BaseModel): |
| docId: str |
| message: str |
| totalPages: int |
| download_url: Optional[str] = None |
|
|
| def get_download_url(file_id: str) -> str: |
| return f"{BASE_URL}/download/{file_id}" |
|
|
| def get_document_path(doc_id: str) -> str: |
| os.makedirs(DOCS_DIR, exist_ok=True) |
| return os.path.join(DOCS_DIR, f"{doc_id}.json") |
|
|
| def update_document(doc_id: str, page_no: int, content: str) -> Dict: |
| filepath = get_document_path(doc_id) |
| |
| if os.path.exists(filepath): |
| with open(filepath, 'r', encoding='utf-8') as f: |
| doc = json.load(f) |
| doc['updatedAt'] = datetime.utcnow().isoformat() |
| else: |
| doc = { |
| 'docId': doc_id, |
| 'createdAt': datetime.utcnow().isoformat(), |
| 'updatedAt': datetime.utcnow().isoformat(), |
| 'content': {} |
| } |
| |
| doc['content'][str(page_no)] = content |
| |
| with open(filepath, 'w', encoding='utf-8') as f: |
| json.dump(doc, f, ensure_ascii=False, indent=2) |
| |
| return doc |
|
|
| @router.post("/document/update", response_model=DocumentResponse) |
| async def add_document_part(part: DocumentPart): |
| doc_id = part.docId or str(uuid.uuid4()) |
| |
| try: |
| doc = update_document(doc_id, part.pageNo, part.content) |
| return DocumentResponse( |
| docId=doc_id, |
| message=f"Page {part.pageNo} added successfully", |
| totalPages=len(doc['content']), |
| download_url=get_download_url(doc_id) |
| ) |
| except Exception as e: |
| raise HTTPException( |
| status_code=500, |
| detail=f"Error updating document: {str(e)}" |
| ) |
|
|
| @router.get("/document/{doc_id}") |
| async def get_document(doc_id: str): |
| filepath = get_document_path(doc_id) |
| if not os.path.exists(filepath): |
| raise HTTPException(status_code=404, detail="Document not found") |
| |
| with open(filepath, 'r', encoding='utf-8') as f: |
| return json.load(f) |
|
|
| @router.get("/download/{doc_id}") |
| async def download_document(doc_id: str): |
| filepath = get_document_path(doc_id) |
| if not os.path.exists(filepath): |
| raise HTTPException(status_code=404, detail="Document not found") |
| |
| return FileResponse( |
| filepath, |
| media_type='application/json', |
| filename=f"document_{doc_id}.json" |
| ) |
|
|
| @router.delete("/document/{doc_id}") |
| async def delete_document(doc_id: str): |
| filepath = get_document_path(doc_id) |
| if not os.path.exists(filepath): |
| raise HTTPException(status_code=404, detail="Document not found") |
| |
| os.remove(filepath) |
| return {"message": "Document deleted successfully"} |