Spaces:
Running
Running
import requests | |
import os | |
from dotenv import load_dotenv | |
load_dotenv() | |
ocr_api_key = os.getenv("OCR_SPACE_API_KEY") | |
def extract_text_from_image(image_input): | |
try: | |
if not ocr_api_key or not ocr_api_key.strip(): | |
return "❌ OCR API anahtarı eksik." | |
# Hugging Face -> Gradio upload: image_input bir dosya yoludur (str) | |
# Local test: image_input file-like olabilir | |
if hasattr(image_input, "read"): | |
image_data = image_input.read() | |
elif isinstance(image_input, str) and os.path.exists(image_input): | |
with open(image_input, 'rb') as f: | |
image_data = f.read() | |
else: | |
return "❌ Geçersiz görsel girdisi." | |
response = requests.post( | |
url='https://api.ocr.space/parse/image', | |
files={'file': ('image.png', image_data)}, | |
data={ | |
'apikey': ocr_api_key.strip(), | |
'language': 'eng', | |
'isOverlayRequired': False, | |
'OCREngine': 2 | |
} | |
) | |
# JSON dönüşüm kontrolü | |
try: | |
result = response.json() | |
except Exception: | |
return f"❌ API yanıtı JSON değil:\n{response.text}" | |
if not isinstance(result, dict): | |
return f"❌ API çıktısı sözlük değil:\n{result}" | |
if result.get("IsErroredOnProcessing"): | |
return f"❌ OCR Hatası: {result.get('ErrorMessage', ['Bilinmeyen hata'])[0]}" | |
parsed_results = result.get("ParsedResults") | |
if not parsed_results or not isinstance(parsed_results, list): | |
return "❌ OCR sonucu boş veya biçimsiz." | |
return parsed_results[0].get('ParsedText', '').strip() | |
except Exception as e: | |
return f"❌ Sistemsel Hata: {str(e)}" | |