openai_service.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import os
  2. import base64
  3. import io
  4. import logging
  5. from openai import AsyncOpenAI
  6. from dotenv import load_dotenv
  7. from PIL import Image
  8. from backend.schemas import ExtractionResponse
  9. load_dotenv()
  10. # Setup logging
  11. logging.basicConfig(level=logging.INFO)
  12. logger = logging.getLogger(__name__)
  13. client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
  14. MAX_IMAGE_SIZE = (2000, 2000)
  15. IMAGE_QUALITY = 85
  16. def compress_image(image_content: bytes) -> bytes:
  17. """Resizes and compresses the image to reduce upload size."""
  18. img = Image.open(io.BytesIO(image_content))
  19. # Convert to RGB if necessary (to save as JPEG)
  20. if img.mode in ("RGBA", "P"):
  21. img = img.convert("RGB")
  22. # Resize if larger than max dimensions
  23. img.thumbnail(MAX_IMAGE_SIZE, Image.Resampling.LANCZOS)
  24. # Save to bytes
  25. output_buffer = io.BytesIO()
  26. img.save(output_buffer, format="JPEG", quality=IMAGE_QUALITY, optimize=True)
  27. return output_buffer.getvalue()
  28. async def extract_receipt_data(image_content: bytes, user_name: str, department: str) -> ExtractionResponse:
  29. # 1. Compress Image
  30. compressed_content = compress_image(image_content)
  31. base64_image = base64.b64encode(compressed_content).decode("utf-8")
  32. # 2. Refined Prompt
  33. prompt = (
  34. f"You are an HR data entry assistant helping an employee in Malaysia. "
  35. f"Extract the requested fields from the provided medical receipt image. "
  36. f"The employee submitting this is {user_name} from {department}. "
  37. f"IMPORTANT: The context is Malaysia (MYR). Extract the total amount and assume it is in MYR. "
  38. f"If the date is missing, use the 'Transaction Date' or 'Payment Date' as a fallback. "
  39. f"Analyze the receipt for authenticity. Set `needs_manual_review` to `true` and provide a low `confidence_score` if: "
  40. f"1. The 'Total' does not match the sum of the individual items. "
  41. f"2. The receipt looks hand-written and lacks an official stamp. "
  42. f"3. The provider name is missing or the amount looks altered. "
  43. f"4. The user's name ({user_name}) is not clearly visible on the receipt. "
  44. f"If the document is a Tax Invoice, extract the Invoice Number and add it to the `items` list."
  45. )
  46. # 3. Async Extraction
  47. completion = await client.beta.chat.completions.parse(
  48. model="gpt-4o-mini",
  49. messages=[
  50. {
  51. "role": "system",
  52. "content": "You are an HR data entry assistant. Extract medical receipt data accurately into structured JSON."
  53. },
  54. {
  55. "role": "user",
  56. "content": [
  57. {"type": "text", "text": prompt},
  58. {
  59. "type": "image_url",
  60. "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
  61. },
  62. ],
  63. }
  64. ],
  65. response_format=ExtractionResponse,
  66. )
  67. result = completion.choices[0].message.parsed
  68. # 4. Logging for Demo
  69. if result:
  70. logger.info(f"Extraction complete for {user_name}. Confidence Score: {result.confidence_score}")
  71. if result.needs_manual_review:
  72. logger.warning(f"Manual review required for receipt submitted by {user_name}")
  73. return result