Spaces:
Runtime error

File size: 4,945 Bytes
e99563f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef216c
 
 
 
 
e99563f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, UploadFile, File, HTTPException
from ..services.vector_store import add_document_chunks, get_collection_stats
from ..services.doc_store import save_metadata, count_documents, DOC_LIMIT
from ..utils.text_processing import extract_pdf_text, chunk_text, clean_text
import uuid
import os
import logging

logger = logging.getLogger("rag-pipeline.upload")
router = APIRouter(prefix="/upload", tags=["Document Upload"])

@router.post("")
async def upload_document(file: UploadFile = File(...)):
    """Upload and process a PDF document with limits enforcement"""
    
    # Check document limit
    current_count = count_documents()
    if current_count >= DOC_LIMIT:
        logger.warning(f"Upload blocked: Document limit ({DOC_LIMIT}) reached.")
        raise HTTPException(
            status_code=400, 
            detail=f"Document limit reached. Maximum {DOC_LIMIT} documents allowed. Currently have {current_count} documents."
        )
    
    # Validate file type
    if not file.filename.endswith('.pdf'):
        logger.warning(f"Upload blocked: Invalid file type {file.filename}")
        raise HTTPException(status_code=400, detail="Only PDF files are supported")
    
    # Validate file size (max 50MB)
    file_content = await file.read()
    if len(file_content) > 50 * 1024 * 1024:  # 50MB
        logger.warning(f"Upload blocked: File too large ({len(file_content)} bytes)")
        raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB")
    
    try:
        # Generate unique document ID
        doc_id = str(uuid.uuid4())
        logger.info(f"Processing upload: {file.filename} (ID: {doc_id})")
        
        # Save file temporarily
        temp_path = f"/app/uploads/{doc_id}_{file.filename}"
        os.makedirs("/app/uploads", exist_ok=True)
        
        with open(temp_path, "wb") as f:
            f.write(file_content)
        
        # Extract text from PDF
        text_content = extract_pdf_text(temp_path)
        
        if not text_content:
            logger.error(f"Text extraction failed for {file.filename}")
            raise HTTPException(status_code=400, detail="Could not extract text from PDF")
        
        # Count pages (approximate based on text length)
        estimated_pages = max(1, len(text_content) // 2000)
        
        # Check page limit
        if estimated_pages > 1000:
            logger.warning(f"Upload blocked: Too many pages (~{estimated_pages})")
            raise HTTPException(
                status_code=400, 
                detail=f"Document too large. Maximum 1000 pages allowed. This document has approximately {estimated_pages} pages."
            )
        
        # Clean and chunk the text
        cleaned_text = clean_text(text_content)
        chunks = chunk_text(cleaned_text)
        
        if not chunks:
            logger.error(f"No chunks created for {file.filename}")
            raise HTTPException(status_code=400, detail="No text content found in document")
        
        # Add chunks to vector database
        try:
            add_document_chunks(doc_id, chunks)
        except Exception as e:
            logger.error(f"Vector store indexing failed for {doc_id}: {str(e)}")
            raise HTTPException(status_code=500, detail=f"Failed to process document in vector store: {str(e)}")
        
        # Save metadata to database
        metadata_saved = save_metadata(
            doc_id=doc_id,
            filename=file.filename,
            pages=estimated_pages,
            chunks=len(chunks),
            text_length=len(cleaned_text)
        )
        
        if not metadata_saved:
            logger.warning(f"Failed to save metadata for document {doc_id}")
        
        # Clean up temporary file
        if os.path.exists(temp_path):
            os.remove(temp_path)
        
        logger.info(f"Upload successful: {file.filename} ({len(chunks)} chunks)")
        return {
            "document_id": doc_id,
            "filename": file.filename,
            "chunks_created": len(chunks),
            "text_length": len(cleaned_text),
            "estimated_pages": estimated_pages,
            "status": "success"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.exception(f"Unexpected error during upload of {file.filename}")
        # Clean up temp file if it exists
        if 'temp_path' in locals() and os.path.exists(temp_path):
            os.remove(temp_path)
        
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")

@router.get("/stats")
async def get_upload_stats():
    """Get statistics about uploaded documents"""
    from ..services.doc_store import get_document_stats
    
    stats = get_document_stats()
    vector_stats = get_collection_stats()
    
    return {
        **stats,
        "vector_chunks": vector_stats.get("total_chunks", 0)
    }