Nexus_Post_AI / ocr_utils.py
krishbaresha's picture
Update ocr_utils.py
46e2233 verified
raw
history blame contribute delete
916 Bytes
import requests
def extract_text_from_image(file_path, api_key):
"""Extract text from image using OCR.space API with better error handling"""
if not api_key:
return "OCR API Key missing. Please check secrets."
try:
url = "https://api.ocr.space/parse/image"
with open(file_path, "rb") as f:
r = requests.post(
url,
files={"file": f},
data={"apikey": api_key, "language": "eng", "isOverlayRequired": False}
)
result = r.json()
if result.get("OCRExitCode") == 1:
parsed_text = result['ParsedResults'][0]['ParsedText']
return parsed_text if parsed_text else "No text found in image."
else:
return f"OCR Error: {result.get('ErrorMessage', 'Unknown error')}"
except Exception as e:
return f"System Error: {str(e)}"