File size: 2,542 Bytes
64d7fdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, HTTPException, UploadFile, File
from app.models.schemas import DocumentResponse
from app.services.document_service import document_service
from app.utils.logger import logger
from app.utils.errors import DocumentProcessingError
from typing import List
from datetime import datetime

router = APIRouter(prefix="/documents", tags=["documents"])


@router.post("/upload", response_model=DocumentResponse)
async def upload_document(file: UploadFile = File(...)):
    try:
        content = await file.read()
        file_path = document_service.save_uploaded_file(content, file.filename)
        
        result = await document_service.process_document(file_path)
        
        document_service.delete_file(file_path)
        
        return DocumentResponse(
            id=result["doc_id"],
            filename=result["file_name"],
            chunk_count=result["num_chunks"],
            status="success",
            created_at=datetime.utcnow()
        )
        
    except DocumentProcessingError as e:
        logger.error(f"Processing error: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Upload error: {str(e)}")
        raise HTTPException(status_code=500, detail="Upload failed")


@router.get("/", response_model=List[dict])
async def list_documents():
    try:
        documents = await document_service.get_all_documents()
        
        for doc in documents:
            doc["_id"] = str(doc["_id"])
        
        return documents
        
    except Exception as e:
        logger.error(f"List error: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to list documents")


@router.get("/stats")
async def get_stats():
    try:
        stats = await document_service.get_document_stats()
        return stats
    except Exception as e:
        logger.error(f"Stats error: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to get stats")


@router.delete("/{doc_id}")
async def delete_document(doc_id: str):
    try:
        success = await document_service.delete_document(doc_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="Document not found")
        
        return {"message": "Document deleted successfully", "doc_id": doc_id}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Delete error: {str(e)}")
        raise HTTPException(status_code=500, detail="Delete failed")