Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,40 +3,74 @@ from fastapi.responses import JSONResponse
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
import easyocr
|
| 5 |
import io
|
| 6 |
-
import base64
|
| 7 |
from PIL import Image
|
| 8 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 9 |
from business_card import llm_calling
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
-
# Initialize EasyOCR
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
|
|
|
| 16 |
class ImageBase64Payload(BaseModel):
|
| 17 |
image: str # base64 string of image
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
@app.post("/extract")
|
| 20 |
async def extract_business_card(request: Request, file: UploadFile = File(None)):
|
| 21 |
try:
|
| 22 |
-
# Case 1:
|
| 23 |
if file:
|
| 24 |
image_data = await file.read()
|
| 25 |
else:
|
| 26 |
-
# Case 2: Base64
|
| 27 |
json_data = await request.json()
|
| 28 |
base64_str = json_data.get("image", "")
|
| 29 |
-
|
| 30 |
if not base64_str:
|
| 31 |
return JSONResponse(
|
| 32 |
status_code=400,
|
| 33 |
content={"status": "error", "message": "'image' field is required in JSON payload"},
|
| 34 |
)
|
| 35 |
-
|
| 36 |
-
# Remove data:image/...;base64, prefix if exists
|
| 37 |
if "," in base64_str:
|
| 38 |
base64_str = base64_str.split(",")[1]
|
| 39 |
-
|
| 40 |
try:
|
| 41 |
image_data = base64.b64decode(base64_str)
|
| 42 |
except Exception:
|
|
@@ -45,21 +79,25 @@ async def extract_business_card(request: Request, file: UploadFile = File(None))
|
|
| 45 |
content={"status": "error", "message": "Invalid base64 string"},
|
| 46 |
)
|
| 47 |
|
| 48 |
-
#
|
| 49 |
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
| 50 |
image_np = np.array(image)
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
ocr_result = reader.readtext(image_np, detail=0)
|
| 54 |
full_text = " ".join(ocr_result)
|
| 55 |
|
| 56 |
-
# Call LLM
|
| 57 |
extracted_data = llm_calling(full_text)
|
| 58 |
|
| 59 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
except Exception as e:
|
| 62 |
return JSONResponse(
|
| 63 |
status_code=500,
|
| 64 |
-
content={"status": "error", "message": str(e)},
|
| 65 |
)
|
|
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
import easyocr
|
| 5 |
import io
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
import numpy as np
|
| 8 |
+
import base64
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
from business_card import llm_calling
|
| 12 |
|
| 13 |
app = FastAPI()
|
| 14 |
|
| 15 |
+
# Initialize EasyOCR with fallback directories
|
| 16 |
+
def initialize_reader():
|
| 17 |
+
possible_dirs = [
|
| 18 |
+
"/tmp/.EasyOCR", # Writable temp directory
|
| 19 |
+
os.path.join(os.getcwd(), ".EasyOCR"), # Current working directory
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
for model_dir in possible_dirs:
|
| 23 |
+
try:
|
| 24 |
+
Path(model_dir).mkdir(parents=True, exist_ok=True)
|
| 25 |
+
reader = easyocr.Reader(
|
| 26 |
+
['en', 'th'],
|
| 27 |
+
gpu=False,
|
| 28 |
+
model_storage_directory=model_dir,
|
| 29 |
+
user_network_directory=model_dir,
|
| 30 |
+
download_enabled=True
|
| 31 |
+
)
|
| 32 |
+
print(f"EasyOCR initialized successfully in {model_dir}")
|
| 33 |
+
return reader
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"Failed to initialize in {model_dir}: {str(e)}")
|
| 36 |
+
continue
|
| 37 |
+
|
| 38 |
+
raise RuntimeError("Could not find a writable directory for EasyOCR")
|
| 39 |
+
|
| 40 |
+
reader = initialize_reader()
|
| 41 |
|
| 42 |
+
# Optional: for future use or documentation
|
| 43 |
class ImageBase64Payload(BaseModel):
|
| 44 |
image: str # base64 string of image
|
| 45 |
|
| 46 |
+
@app.get("/")
|
| 47 |
+
def root():
|
| 48 |
+
return {"message": "Hello from Hugging Face FastAPI!"}
|
| 49 |
+
|
| 50 |
+
@app.get("/health")
|
| 51 |
+
async def health_check():
|
| 52 |
+
return {"status": "healthy"}
|
| 53 |
+
|
| 54 |
@app.post("/extract")
|
| 55 |
async def extract_business_card(request: Request, file: UploadFile = File(None)):
|
| 56 |
try:
|
| 57 |
+
# Case 1: Image uploaded as a file
|
| 58 |
if file:
|
| 59 |
image_data = await file.read()
|
| 60 |
else:
|
| 61 |
+
# Case 2: Base64 string in JSON body
|
| 62 |
json_data = await request.json()
|
| 63 |
base64_str = json_data.get("image", "")
|
| 64 |
+
|
| 65 |
if not base64_str:
|
| 66 |
return JSONResponse(
|
| 67 |
status_code=400,
|
| 68 |
content={"status": "error", "message": "'image' field is required in JSON payload"},
|
| 69 |
)
|
| 70 |
+
|
|
|
|
| 71 |
if "," in base64_str:
|
| 72 |
base64_str = base64_str.split(",")[1]
|
| 73 |
+
|
| 74 |
try:
|
| 75 |
image_data = base64.b64decode(base64_str)
|
| 76 |
except Exception:
|
|
|
|
| 79 |
content={"status": "error", "message": "Invalid base64 string"},
|
| 80 |
)
|
| 81 |
|
| 82 |
+
# Decode image into NumPy format
|
| 83 |
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
| 84 |
image_np = np.array(image)
|
| 85 |
|
| 86 |
+
# Perform OCR
|
| 87 |
+
ocr_result = reader.readtext(image_np, detail=0)
|
| 88 |
full_text = " ".join(ocr_result)
|
| 89 |
|
| 90 |
+
# Call LLM to extract structured info
|
| 91 |
extracted_data = llm_calling(full_text)
|
| 92 |
|
| 93 |
+
return {
|
| 94 |
+
"status": "success",
|
| 95 |
+
"data": extracted_data,
|
| 96 |
+
"ocr_text": full_text # Optional for debugging
|
| 97 |
+
}
|
| 98 |
|
| 99 |
except Exception as e:
|
| 100 |
return JSONResponse(
|
| 101 |
status_code=500,
|
| 102 |
+
content={"status": "error", "message": str(e), "type": type(e).__name__},
|
| 103 |
)
|