main.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os
  2. import uuid
  3. from datetime import datetime
  4. from fastapi import FastAPI, UploadFile, File, Header, HTTPException, status, Form
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from typing import Optional, List
  7. from backend.services.openai_service import extract_receipt_data
  8. from backend.schemas import ExtractionResponse, ClaimRecord
  9. from dotenv import load_dotenv
  10. load_dotenv()
  11. app = FastAPI(title="AI-Assisted Data Entry API")
  12. # Configure CORS
  13. app.add_middleware(
  14. CORSMiddleware,
  15. allow_origins=["*"], # Adjust as needed for Angular frontend
  16. allow_credentials=True,
  17. allow_methods=["*"],
  18. allow_headers=["*"],
  19. )
  20. # In-memory database for claims
  21. CLAIMS_DB: List[ClaimRecord] = []
  22. @app.get("/health")
  23. async def health_check():
  24. return {"status": "healthy"}
  25. @app.post("/api/v1/extract", response_model=ExtractionResponse)
  26. async def extract_receipt(
  27. file: UploadFile = File(...),
  28. user_name: str = Form("Unknown Employee"),
  29. department: str = Form("Unknown Department")
  30. ):
  31. if not file.content_type.startswith("image/"):
  32. raise HTTPException(
  33. status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
  34. detail="File provided is not an image."
  35. )
  36. try:
  37. content = await file.read()
  38. extraction_result = await extract_receipt_data(content, user_name, department)
  39. if extraction_result is None:
  40. raise HTTPException(
  41. status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
  42. detail="Could not extract data from the provided image."
  43. )
  44. return extraction_result
  45. except Exception as e:
  46. raise HTTPException(
  47. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  48. detail=f"An error occurred during extraction: {str(e)}"
  49. )
  50. @app.post("/api/v1/claims", response_model=ClaimRecord)
  51. async def submit_claim(
  52. extraction_data: ExtractionResponse,
  53. user_name: str = Header(...),
  54. department: str = Header(...)
  55. ):
  56. claim = ClaimRecord(
  57. id=str(uuid.uuid4()),
  58. timestamp=datetime.now().isoformat(),
  59. submitted_by=user_name,
  60. department=department,
  61. extraction_data=extraction_data
  62. )
  63. CLAIMS_DB.append(claim)
  64. return claim
  65. @app.get("/api/v1/claims", response_model=List[ClaimRecord])
  66. async def get_claims():
  67. return CLAIMS_DB
  68. if __name__ == "__main__":
  69. import uvicorn
  70. uvicorn.run(app, host="0.0.0.0", port=8000)