File size: 1,815 Bytes
cc21f11
 
 
 
 
 
 
0303b9b
cc21f11
0303b9b
 
 
 
 
 
 
 
 
 
 
 
cc21f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0303b9b
cc21f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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)}"