File size: 916 Bytes
7c4d00d
 
 
46e2233
 
 
 
7c4d00d
026399a
 
 
 
 
46e2233
026399a
46e2233
026399a
46e2233
 
 
 
 
 
026399a
46e2233
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)}"