File size: 3,143 Bytes
3beae3d
 
 
 
 
 
 
 
f07d3b7
3beae3d
4bb4b7e
3beae3d
4bb4b7e
f07d3b7
 
3beae3d
 
 
 
 
 
 
 
 
 
 
 
4bb4b7e
3beae3d
 
f07d3b7
 
3beae3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3520ce1
3beae3d
 
 
 
 
 
 
 
 
 
 
 
f07d3b7
 
 
 
3beae3d
4bb4b7e
3beae3d
 
 
 
 
 
 
 
04f8d73
3beae3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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()  # Add prefix here

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"}