Spaces:
Sleeping
Sleeping
Update ocr_utils.py
Browse files- ocr_utils.py +13 -7
ocr_utils.py
CHANGED
|
@@ -1,19 +1,25 @@
|
|
| 1 |
import requests
|
| 2 |
|
| 3 |
def extract_text_from_image(file_path, api_key):
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
try:
|
| 8 |
url = "https://api.ocr.space/parse/image"
|
| 9 |
with open(file_path, "rb") as f:
|
| 10 |
r = requests.post(
|
| 11 |
url,
|
| 12 |
files={"file": f},
|
| 13 |
-
data={"apikey": api_key, "language": "eng"}
|
| 14 |
)
|
|
|
|
| 15 |
result = r.json()
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
except Exception as e:
|
| 18 |
-
|
| 19 |
-
return ""
|
|
|
|
| 1 |
import requests
|
| 2 |
|
| 3 |
def extract_text_from_image(file_path, api_key):
|
| 4 |
+
"""Extract text from image using OCR.space API with better error handling"""
|
| 5 |
+
if not api_key:
|
| 6 |
+
return "OCR API Key missing. Please check secrets."
|
| 7 |
+
|
| 8 |
try:
|
| 9 |
url = "https://api.ocr.space/parse/image"
|
| 10 |
with open(file_path, "rb") as f:
|
| 11 |
r = requests.post(
|
| 12 |
url,
|
| 13 |
files={"file": f},
|
| 14 |
+
data={"apikey": api_key, "language": "eng", "isOverlayRequired": False}
|
| 15 |
)
|
| 16 |
+
|
| 17 |
result = r.json()
|
| 18 |
+
if result.get("OCRExitCode") == 1:
|
| 19 |
+
parsed_text = result['ParsedResults'][0]['ParsedText']
|
| 20 |
+
return parsed_text if parsed_text else "No text found in image."
|
| 21 |
+
else:
|
| 22 |
+
return f"OCR Error: {result.get('ErrorMessage', 'Unknown error')}"
|
| 23 |
+
|
| 24 |
except Exception as e:
|
| 25 |
+
return f"System Error: {str(e)}"
|
|
|