wolf1997 commited on
Commit
d0c1517
·
verified ·
1 Parent(s): 5e89945

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -25
app.py CHANGED
@@ -1,12 +1,9 @@
1
- from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  import base64
5
- import io
6
- from PIL import Image
7
  import uvicorn
8
  import os
9
- import json
10
  from dotenv import load_dotenv
11
  from typing import List
12
 
@@ -18,6 +15,7 @@ app = FastAPI(
18
  title="Receipt Scanner API",
19
  root_path="/" if not HF_SPACE_URL else HF_SPACE_URL
20
  )
 
21
  # Configure CORS to allow requests from your React app
22
  app.add_middleware(
23
  CORSMiddleware,
@@ -27,10 +25,6 @@ app.add_middleware(
27
  allow_headers=["*"],
28
  )
29
 
30
- # Data model for the request
31
- class ImageRequest(BaseModel):
32
- images: List[str] # Changed from single image to list of images
33
-
34
  # Data model for the response
35
  class ReceiptItem(BaseModel):
36
  name: str
@@ -43,6 +37,9 @@ class ReceiptResponse(BaseModel):
43
  total: float
44
  items: list[ReceiptItem]
45
 
 
 
 
46
  # Initialize the receipt agent
47
  receipt_scanner = receipt_agent()
48
 
@@ -51,9 +48,6 @@ def format_receipt_data(agent_response):
51
  """
52
  Format the receipt data from the LangGraph agent to match our API response format
53
  """
54
- # Create directory for storing receipt data if it doesn't exist
55
- # os.makedirs('new_receipt_data', exist_ok=True)
56
-
57
  # Ensure we have values for all our fields
58
  store = agent_response.get('loc_name', '')
59
  date = agent_response.get('date', '')
@@ -104,24 +98,36 @@ def scan_receipt(images):
104
  }
105
 
106
  @app.post("/api/scan")
107
- async def process_receipt(request: ImageRequest):
 
 
 
108
  try:
109
- # Process each image in the list
110
- processed_images = []
111
- for image_data in request.images:
112
- if "base64," in image_data:
113
- image_data = image_data.split(",")[1]
114
- processed_images.append(image_data)
115
-
116
- # Process all images with the LangGraph receipt scanner
117
- result = scan_receipt(processed_images)
 
 
 
 
 
 
118
 
119
  # Return the result
120
  return result
121
 
122
  except Exception as e:
123
  print(f"API error: {str(e)}")
124
- raise HTTPException(status_code=500, detail=f"Error processing images: {str(e)}")
 
 
 
125
  @app.get("/")
126
  async def root():
127
  return {
@@ -131,6 +137,8 @@ async def root():
131
  "health": "/health"
132
  }
133
  }
 
 
134
  # Health check endpoint
135
  @app.get("/health")
136
  async def health_check():
@@ -142,9 +150,6 @@ if not os.getenv('google_api_key'):
142
  print("WARNING: google_api_key not found in environment variables")
143
  print("Please ensure you have set up your .env file with the Google API key")
144
 
145
- # Create directory for storing receipt data if it doesn't exist
146
- # os.makedirs('new_receipt_data', exist_ok=True)
147
-
148
  if __name__ == "__main__":
149
  # Get port from environment variable or default to 8000
150
  port = int(os.environ.get("PORT", 8000))
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File, Form
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  import base64
 
 
5
  import uvicorn
6
  import os
 
7
  from dotenv import load_dotenv
8
  from typing import List
9
 
 
15
  title="Receipt Scanner API",
16
  root_path="/" if not HF_SPACE_URL else HF_SPACE_URL
17
  )
18
+ # app = FastAPI()
19
  # Configure CORS to allow requests from your React app
20
  app.add_middleware(
21
  CORSMiddleware,
 
25
  allow_headers=["*"],
26
  )
27
 
 
 
 
 
28
  # Data model for the response
29
  class ReceiptItem(BaseModel):
30
  name: str
 
37
  total: float
38
  items: list[ReceiptItem]
39
 
40
+ class ImageData(BaseModel):
41
+ images: List[str]
42
+
43
  # Initialize the receipt agent
44
  receipt_scanner = receipt_agent()
45
 
 
48
  """
49
  Format the receipt data from the LangGraph agent to match our API response format
50
  """
 
 
 
51
  # Ensure we have values for all our fields
52
  store = agent_response.get('loc_name', '')
53
  date = agent_response.get('date', '')
 
98
  }
99
 
100
  @app.post("/api/scan")
101
+ async def process_receipt(
102
+ images: list[UploadFile] = File(...)
103
+
104
+ ):
105
  try:
106
+ base64_images = []
107
+ for i in images:
108
+ print(f"Processing file: {i.filename}")
109
+ # Read the file content
110
+ contents = await i.read()
111
+ print(f"File size: {len(contents)} bytes")
112
+
113
+ # Convert to base64 without trying to decode as UTF-8
114
+ base64_image = base64.b64encode(contents).decode('utf-8')
115
+ base64_images.append(base64_image)
116
+
117
+ print("Sending image to receipt scanner...")
118
+ # Process image with the LangGraph receipt scanner
119
+ result = scan_receipt(base64_images)
120
+ print("Receipt scanning completed successfully")
121
 
122
  # Return the result
123
  return result
124
 
125
  except Exception as e:
126
  print(f"API error: {str(e)}")
127
+ import traceback
128
+ print(f"Traceback: {traceback.format_exc()}")
129
+ raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
130
+
131
  @app.get("/")
132
  async def root():
133
  return {
 
137
  "health": "/health"
138
  }
139
  }
140
+
141
+
142
  # Health check endpoint
143
  @app.get("/health")
144
  async def health_check():
 
150
  print("WARNING: google_api_key not found in environment variables")
151
  print("Please ensure you have set up your .env file with the Google API key")
152
 
 
 
 
153
  if __name__ == "__main__":
154
  # Get port from environment variable or default to 8000
155
  port = int(os.environ.get("PORT", 8000))