File size: 1,499 Bytes
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
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)}"