|
| 1 | +from fastapi import APIRouter, UploadFile, Depends, HTTPException |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from app.config import UPLOAD_DIR, VECTOR_DIR |
| 5 | +from app.deps import get_session_id, get_gemini_key |
| 6 | +from app.utils.pdf_loader import extract_text_from_pdf |
| 7 | +from app.utils.text_splitter import split_text |
| 8 | +from app.utils.gemini import get_client, embed_texts |
| 9 | +from app.utils.vector_store import create_or_load_index, add_vectors, save_index |
| 10 | +import json |
| 11 | + |
| 12 | + |
| 13 | +router = APIRouter() |
| 14 | + |
| 15 | + |
| 16 | +@router.post("/upload") |
| 17 | +async def upload_file( |
| 18 | + file: UploadFile, |
| 19 | + session_id: str = Depends(get_session_id), |
| 20 | + api_key: str = Depends(get_gemini_key), |
| 21 | +): |
| 22 | + # 1. Validate file |
| 23 | + if not file.filename.lower().endswith(".pdf"): |
| 24 | + raise HTTPException(status_code=415, detail="Only PDF supported") |
| 25 | + |
| 26 | + # 2. Create Gemini client (per request) |
| 27 | + client = get_client(api_key) |
| 28 | + |
| 29 | + # 3. Save file |
| 30 | + session_upload = UPLOAD_DIR / session_id |
| 31 | + session_upload.mkdir(parents=True, exist_ok=True) |
| 32 | + |
| 33 | + file_path = session_upload / file.filename |
| 34 | + with open(file_path, "wb") as f: |
| 35 | + f.write(await file.read()) |
| 36 | + |
| 37 | + # 4. Extract + split text |
| 38 | + text = extract_text_from_pdf(str(file_path)) |
| 39 | + chunks = split_text(text) |
| 40 | + |
| 41 | + if not chunks: |
| 42 | + raise HTTPException(status_code=400, detail="No text found in PDF") |
| 43 | + |
| 44 | + # 5. Generate embeddings |
| 45 | + embeddings = embed_texts(chunks, client) |
| 46 | + |
| 47 | + # 6. Create / append vector store |
| 48 | + session_vector = VECTOR_DIR / session_id |
| 49 | + session_vector.mkdir(parents=True, exist_ok=True) |
| 50 | + |
| 51 | + index_path = session_vector / "index.faiss" |
| 52 | + index = create_or_load_index(index_path, len(embeddings[0])) |
| 53 | + |
| 54 | + add_vectors(index, embeddings) |
| 55 | + save_index(index, index_path) |
| 56 | + |
| 57 | + # ✅ SAVE CHUNK TEXT (REQUIRED FOR RAG) |
| 58 | + chunk_map = {str(i): chunk for i, chunk in enumerate(chunks)} |
| 59 | + |
| 60 | + with open(session_vector / "chunks.json", "w", encoding="utf-8") as f: |
| 61 | + json.dump(chunk_map, f, ensure_ascii=False, indent=2) |
| 62 | + |
| 63 | + |
| 64 | + return { |
| 65 | + "status": "READY", |
| 66 | + "filename": file.filename, |
| 67 | + "chunks": len(chunks), |
| 68 | + } |
| 69 | + |
| 70 | + |
0 commit comments