import os import uuid from datetime import datetime from fastapi import FastAPI, UploadFile, File, Header, HTTPException, status, Form from fastapi.middleware.cors import CORSMiddleware from typing import Optional, List from backend.services.openai_service import extract_receipt_data from backend.schemas import ExtractionResponse, ClaimRecord from dotenv import load_dotenv load_dotenv() app = FastAPI(title="AI-Assisted Data Entry API") # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], # Adjust as needed for Angular frontend allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # In-memory database for claims CLAIMS_DB: List[ClaimRecord] = [] @app.get("/health") async def health_check(): return {"status": "healthy"} @app.post("/api/v1/extract", response_model=ExtractionResponse) async def extract_receipt( file: UploadFile = File(...), user_name: str = Form("Unknown Employee"), department: str = Form("Unknown Department") ): if not file.content_type.startswith("image/"): raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="File provided is not an image." ) try: content = await file.read() extraction_result = await extract_receipt_data(content, user_name, department) if extraction_result is None: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Could not extract data from the provided image." ) return extraction_result except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"An error occurred during extraction: {str(e)}" ) @app.post("/api/v1/claims", response_model=ClaimRecord) async def submit_claim( extraction_data: ExtractionResponse, user_name: str = Header(...), department: str = Header(...) ): claim = ClaimRecord( id=str(uuid.uuid4()), timestamp=datetime.now().isoformat(), submitted_by=user_name, department=department, extraction_data=extraction_data ) CLAIMS_DB.append(claim) return claim @app.get("/api/v1/claims", response_model=List[ClaimRecord]) async def get_claims(): return CLAIMS_DB if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)