main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. from fastapi import FastAPI, UploadFile, File, Header, HTTPException, status
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from typing import Optional
  5. from services.openai_service import extract_receipt_data
  6. from schemas import ExtractionResponse
  7. from dotenv import load_dotenv
  8. load_dotenv()
  9. app = FastAPI(title="AI-Assisted Data Entry API")
  10. # Configure CORS
  11. app.add_middleware(
  12. CORSMiddleware,
  13. allow_origins=["*"], # Adjust as needed for Angular frontend
  14. allow_credentials=True,
  15. allow_methods=["*"],
  16. allow_headers=["*"],
  17. )
  18. @app.get("/health")
  19. async def health_check():
  20. return {"status": "healthy"}
  21. @app.post("/api/v1/extract", response_model=ExtractionResponse)
  22. async def extract_receipt(
  23. file: UploadFile = File(...),
  24. user_id: Optional[str] = Header(None),
  25. user_name: str = "Unknown Employee",
  26. department: str = "Unknown Department"
  27. ):
  28. if not file.content_type.startswith("image/"):
  29. raise HTTPException(
  30. status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
  31. detail="File provided is not an image."
  32. )
  33. try:
  34. content = await file.read()
  35. extraction_result = await extract_receipt_data(content, user_name, department)
  36. if extraction_result is None:
  37. raise HTTPException(
  38. status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
  39. detail="Could not extract data from the provided image."
  40. )
  41. return extraction_result
  42. except Exception as e:
  43. raise HTTPException(
  44. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  45. detail=f"An error occurred during extraction: {str(e)}"
  46. )
  47. if __name__ == "__main__":
  48. import uvicorn
  49. uvicorn.run(app, host="0.0.0.0", port=8000)