from fastapi import FastAPI, HTTPException from pydantic import BaseModel from openai import OpenAI import os app = FastAPI(title="Receipt OCR API", version="1.0") # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) class ReceiptRequest(BaseModel): image_url: str @app.post("/extract") def extract_data(data: ReceiptRequest): """ Extract amount, transaction ID, and session ID from a receipt image URL. """ try: response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are an OCR assistant for receipts."}, { "role": "user", "content": [ { "type": "text", "text": ( "Extract the following details from this receipt image:\n" "- Amount paid-rmove comma and make it .2f\n" "- Transaction ID or Reference Number or any referrence number on the reciept as transaction, then if none available, use the date and time written together in yyyymmddhhmmss as transaction id \n" "- Session ID (if available)\n\n" "- sender name\n" "- transaction date written together yyyymmddhhmmss \n" "Return the result as a JSON object with these keys: " "`amount`, `transaction_id`, `session_id`,'sender','transaction date'." ), }, {"type": "image_url", "image_url": {"url": data.image_url}}, ], }, ], ) result = response.choices[0].message.content return {"status": "success", "data": result} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # from fastapi import FastAPI # app = FastAPI() # @app.get("/") # def greet_json(): # return {"Hello": "World!"}