File size: 3,837 Bytes
f3997d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from typing import List

from app.database.connection import get_db
from app.database.models import User
from app.schemas.document import DocumentResponse, DocumentListResponse
from app.services.document_service import DocumentService
from app.middleware.auth import get_current_user

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


@router.post("/upload", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
async def upload_document(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Upload a document for processing.
    
    Args:
        file: Uploaded file
        db: Database session
        current_user: Current authenticated user
        
    Returns:
        Created document metadata
        
    Raises:
        HTTPException: If file validation fails
    """
    try:
        # Upload document
        document = DocumentService.upload_document(
            db=db,
            file=file.file,
            user_id=current_user.id,
            filename=file.filename
        )
        
        # Extract and process text content
        from app.utils.document_extractor import document_extractor
        
        try:
            # Extract text from the uploaded file
            content = document_extractor.extract_text(
                file_path=document.file_path,
                file_type=document.file_type
            )
            
            # Process with RAG service
            num_chunks = DocumentService.process_document_content(
                db, 
                document.id, 
                content
            )
            
            print(f"Document {document.filename} processed: {num_chunks} chunks created")
            
        except Exception as e:
            print(f"Error processing document content: {e}")
            # Document is uploaded but not processed for RAG
            # You might want to mark this in the database
        
        return DocumentResponse.from_orm(document)
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        print(f"Error uploading document: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Error uploading document"
        )


@router.get("", response_model=DocumentListResponse)
async def get_user_documents(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Get all documents for the current user.
    
    Args:
        db: Database session
        current_user: Current authenticated user
        
    Returns:
        List of user documents
    """
    documents = DocumentService.get_user_documents(db, current_user.id)
    
    return DocumentListResponse(
        documents=[DocumentResponse.from_orm(doc) for doc in documents],
        total=len(documents)
    )


@router.delete("/{document_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_document(
    document_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Delete a document and its vector embeddings.
    
    Args:
        document_id: Document ID
        db: Database session
        current_user: Current authenticated user
        
    Raises:
        HTTPException: If document not found
    """
    success = DocumentService.delete_document(db, document_id)
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found"
        )