dcorcoran commited on
Commit
df9c25c
·
1 Parent(s): 14a26aa

Added try/except to catch main.py errors"

Browse files
Files changed (1) hide show
  1. app/main.py +25 -23
app/main.py CHANGED
@@ -1,5 +1,7 @@
1
  from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
 
 
3
  from contextlib import asynccontextmanager
4
  from PIL import Image
5
  import io
@@ -50,29 +52,29 @@ def health():
50
 
51
  @app.post("/predict", response_model=CardResponse)
52
  async def predict(file: UploadFile = File(...)):
53
- image_bytes = await file.read()
54
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
55
-
56
- # Generate embedding and find similar cards first
57
- embedding = app.state.embedding_service.embed(image)
58
- similar_cards = app.state.similarity_service.search(embedding, top_k=5)
59
-
60
- # Use OCR for extraction
61
- ocr_data = app.state.ocr_service.extract(image)
62
-
63
- # If top match is very confident, use its metadata to fill in OCR gaps
64
- if similar_cards and similar_cards[0]["score"] > 0.99:
65
- top_match = similar_cards[0]
66
- ocr_data["name"] = ocr_data["name"] or top_match["name"]
67
- ocr_data["types"] = ocr_data["types"] or top_match["types"]
68
-
69
- return CardResponse(
70
- name=ocr_data.get("name"),
71
- hp=ocr_data.get("hp"),
72
- types=ocr_data.get("types"),
73
- moves=ocr_data.get("moves"),
74
- similar_cards=similar_cards
75
- )
76
 
77
 
78
  import uvicorn
 
1
  from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
+
5
  from contextlib import asynccontextmanager
6
  from PIL import Image
7
  import io
 
52
 
53
  @app.post("/predict", response_model=CardResponse)
54
  async def predict(file: UploadFile = File(...)):
55
+ try:
56
+ image_bytes = await file.read()
57
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
58
+
59
+ embedding = app.state.embedding_service.embed(image)
60
+ similar_cards = app.state.similarity_service.search(embedding, top_k=5)
61
+
62
+ ocr_data = app.state.ocr_service.extract(image)
63
+
64
+ if similar_cards and similar_cards[0]["score"] > 0.99:
65
+ top_match = similar_cards[0]
66
+ ocr_data["name"] = ocr_data["name"] or top_match["name"]
67
+ ocr_data["types"] = ocr_data["types"] or top_match["types"]
68
+
69
+ return CardResponse(
70
+ name=ocr_data.get("name"),
71
+ hp=ocr_data.get("hp"),
72
+ types=ocr_data.get("types"),
73
+ moves=ocr_data.get("moves"),
74
+ similar_cards=similar_cards
75
+ )
76
+ except Exception as e:
77
+ return JSONResponse(status_code=500, content={"error": str(e)})
78
 
79
 
80
  import uvicorn