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_path): | |
try: | |
if not isinstance(image_path, str) or not os.path.exists(image_path): | |
return "❌ Geçersiz dosya yolu." | |
with open(image_path, 'rb') as image_file: | |
image_data = image_file.read() | |
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 formatında 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)}" | |