KoSett commited on
Commit
dd12f7e
·
verified ·
1 Parent(s): a8d33c5

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +55 -31
main.py CHANGED
@@ -1,31 +1,55 @@
1
- from fastapi import FastAPI, File, UploadFile
2
- import easyocr
3
- import io
4
- from PIL import Image
5
- import numpy as np
6
- from business_card import llm_calling
7
-
8
- app = FastAPI()
9
-
10
- # Initialize EasyOCR reader
11
- reader = easyocr.Reader(['en', 'th'], gpu=False, model_storage_directory="./.EasyOCR")
12
-
13
- @app.post("/extract")
14
- async def extract_business_card(file: UploadFile = File(...)):
15
- try:
16
- # Read and decode image
17
- image_data = await file.read()
18
- image = Image.open(io.BytesIO(image_data))
19
- image_np = np.array(image)
20
-
21
- # OCR
22
- ocr_result = reader.readtext(image_np, detail=0)
23
- full_text = " ".join(ocr_result)
24
-
25
- # Gemini LLM Extraction
26
- extracted_data = llm_calling(full_text)
27
-
28
- return {"status": "success", "data": extracted_data}
29
-
30
- except Exception as e:
31
- return {"status": "error", "message": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import FastAPI, File, UploadFile, HTTPException
3
+ import easyocr
4
+ import io
5
+ from PIL import Image
6
+ import numpy as np
7
+ from business_card import llm_calling
8
+ from pathlib import Path
9
+
10
+ app = FastAPI(title="Business Card OCR Processor")
11
+
12
+ # Create a writable directory path
13
+ model_dir = os.path.join(os.getcwd(), "model_storage")
14
+ os.makedirs(model_dir, exist_ok=True)
15
+
16
+ # Initialize EasyOCR reader (with error handling)
17
+ try:
18
+ reader = easyocr.Reader(
19
+ ['en', 'th'],
20
+ gpu=False,
21
+ model_storage_directory=model_dir,
22
+ download_enabled=True
23
+ )
24
+ except Exception as e:
25
+ raise RuntimeError(f"Failed to initialize EasyOCR: {str(e)}")
26
+
27
+ @app.post("/extract")
28
+ async def extract_business_card(file: UploadFile = File(...)):
29
+ try:
30
+ # Validate file type
31
+ if not file.content_type.startswith('image/'):
32
+ raise HTTPException(status_code=400, detail="File must be an image")
33
+
34
+ # Read and decode image
35
+ image_data = await file.read()
36
+ image = Image.open(io.BytesIO(image_data))
37
+ image_np = np.array(image)
38
+
39
+ # OCR processing
40
+ ocr_result = reader.readtext(image_np, detail=0)
41
+ full_text = " ".join(ocr_result)
42
+
43
+ # Gemini LLM Extraction
44
+ extracted_data = llm_calling(full_text)
45
+
46
+ return {"status": "success", "data": extracted_data}
47
+
48
+ except HTTPException:
49
+ raise
50
+ except Exception as e:
51
+ raise HTTPException(status_code=500, detail=str(e))
52
+
53
+ @app.get("/health")
54
+ async def health_check():
55
+ return {"status": "healthy"}