Spaces:
Sleeping
Sleeping
Download src/main.py from low-key-007/financial-analyst-api: direct link, hf CLI and curl.
- Browser
- Download file 1.78 kB
-
https://huggingface.co/spaces/low-key-007/financial-analyst-api/resolve/main/src/main.py
- Command line
-
hf download hf://spaces/low-key-007/financial-analyst-api/src/main.py
-
curl -L -o main.py https://huggingface.co/spaces/low-key-007/financial-analyst-api/resolve/main/src/main.py
1.78 kB
| from fastapi import FastAPI, UploadFile, File, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from typing import List | |
| from pydantic import BaseModel | |
| from src.config import conf | |
| from src.ingestion import DocumentProcessor | |
| from src.rag_engine import engine | |
| app = FastAPI(title=conf.APP_NAME, version=conf.VERSION) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class QueryRequest(BaseModel): | |
| question: str | |
| def health_check(): | |
| return {"status": "operational", "system": conf.APP_NAME} | |
| async def ingest_documents(files: List[UploadFile] = File(...)): | |
| """Uploads PDFs, extracts text, and rebuilds the vector index.""" | |
| if not files: | |
| raise HTTPException(400, "No files uploaded") | |
| try: | |
| # 1. Extraction | |
| raw_text = DocumentProcessor.extract_text(files) | |
| if not raw_text.strip(): | |
| raise HTTPException(400, "No text extracted from documents") | |
| # 2. Chunking | |
| chunks = DocumentProcessor.chunk_text(raw_text) | |
| # 3. Vectorization | |
| engine.ingest(chunks) | |
| return {"status": "success", "chunks_processed": len(chunks)} | |
| except Exception as e: | |
| raise HTTPException(500, f"Ingestion failed: {str(e)}") | |
| async def ask_question(req: QueryRequest): | |
| """Queries the RAG engine.""" | |
| try: | |
| answer = engine.query(req.question) | |
| return {"question": req.question, "answer": answer} | |
| except ValueError: | |
| raise HTTPException(400, "Please upload documents first via /ingest") | |
| except Exception as e: | |
| raise HTTPException(500, f"Inference failed: {str(e)}") |