EasyOCR

vntocr_easyocr.py
# تكامل VNTranslator OCR مع محرك EasyOCR
# الإصدار: 1.0
# المؤلف: Fazx - GarudaMods | https://www.patreon.com/vntranslator

"""
# ==================================================================
# EasyOCR: https://github.com/JaidedAI/EasyOCR
# المتطلبات: python 3.10+ و PyTorch
# التثبيت عبر: pip install easyocr
# ==================================================================
# شغّل هذا السكربت عبر: python vntocr_easyocr.py
# في VNTranslator استخدم المحرك المخصص - HTTP POST مع الإعدادات:
# -- URL: http://127.0.0.1:5353
# -- نوع المحتوى: application/json
# -- رؤوس: {}
# -- المحتوى: {"image":"$IMAGE_BASE64", "langs": ["ja"]}
# -- نوع الاستجابة: JSON
# -- استعلام الاستجابة: fullText
# ==================================================================
# اللغات (رموز ISO ذات حرفين) https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
# -- اليابانية = ja
# -- الإنجليزية = en
# ==================================================================
"""

from flask import Flask, request, jsonify
from PIL import Image
from io import BytesIO
import base64
import re
import json
import numpy as np
import easyocr

APP_HOST = "localhost"
APP_PORT = 5353
APP_DEBUG = True

def parse_ocr_result(easyocr_result):
    full_text = ""
    lines = []

    for entry in easyocr_result:
        polygon = entry[0]
        text = entry[1]
        confidence = entry[2]
        x_min = int(min(point[0] for point in polygon))
        y_min = int(min(point[1] for point in polygon))
        x_max = int(max(point[0] for point in polygon))
        y_max = int(max(point[1] for point in polygon))
        w = x_max - x_min
        h = y_max - y_min
        x = x_min
        y = y_min
        lines.append({
            "text": text,
            "w": int(w),
            "h": int(h),
            "x": int(x),
            "y": int(y),
            "confidence": float(confidence)
        })
        full_text += text + " "

    full_text = full_text.strip()
    return {
        "fullText": full_text,
        "lines": lines
    }

def base64_to_numpy(base64_string):
    if not base64_string:
        raise ValueError("سلسلة Base64 فارغة أو مفقودة")

    if "," in base64_string:
        base64_string = base64_string.split(",")[1]

    try:
        image_decode = base64.b64decode(base64_string)
        print("تم فك ترميز Base64 بنجاح")

        # افتح الصورة باستخدام PIL
        image = Image.open(BytesIO(image_decode))
        print(f"تنسيق الصورة: {image.format}, الحجم: {image.size}")

        # حول صورة PIL إلى مصفوفة NumPy
        image_np = np.array(image)
        print(f"تم تحويل الصورة إلى مصفوفة NumPy بالشكل: {image_np.shape}")

        return image_np
    except Exception as e:
        raise ValueError(f"فشل فك ترميز الصورة: {e}")

############################################################

app = Flask(__name__)
default_langs = ["ja"]
reader = easyocr.Reader(default_langs)

@app.route("/", methods=["POST"])
def ocr_endpoint(): 
    global default_langs, reader

    try:
        print("\n\n=== طلب OCR ===")
        print(f"الطريقة: {request.method}")
        print(f"الرؤوس: {dict(request.headers)}")
        
        if not request.is_json:
            print("الطلب ليس JSON")
            return jsonify({"error": "يجب أن يكون الطلب بصيغة JSON"}), 400
        
        data = request.get_json()

        # سجل الحمولة
        print(f"مفاتيح JSON للطلب: {list(data.keys())}")

        # تحقق من الصورة
        if "image" not in data:
            print("لا توجد بيانات صورة")
            return jsonify({"error": "لا توجد بيانات صورة"}), 400
        
        # فك ترميز صورة base64
        try:            
            image = base64_to_numpy(data["image"])
        except Exception as e:
            print(f"فشل فك ترميز الصورة: {e}")
            return jsonify({"error": f"فشل فك ترميز الصورة: {str(e)}"}), 400

        # تحقق من اللغات
        langs = data.get("langs", ["ja"])
        try:
            if langs != default_langs:
                default_langs = langs
                reader = easyocr.Reader(default_langs)
        except Exception as e:
            print(f"فشل تحميل النموذج: {e}")
            return jsonify({"error": f"فشل تحميل النموذج: {str(e)}"}), 400
        print(f"اللغات: {langs}")

        # تحقق من رسم مربع الإحاطة
        draw_bounding_box = data.get("draw_bounding_box", False)
        print(f"رسم مربع الإحاطة: {draw_bounding_box}")

        # شغّل OCR
        # https://github.com/JaidedAI/EasyOCR?tab=readme-ov-file#usage
        result = reader.readtext(image)
        print(f"تم إكمال OCR بنجاح: {result}")

        # حلّل النتيجة
        parsed_result = parse_ocr_result(result)       
        parsed_result["draw_bounding_box"] = draw_bounding_box
        json_result = json.dumps(parsed_result, indent=4, ensure_ascii=False)
        return json_result

    except Exception as e:
        print(f"خطأ في الطلب: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    print(f"=== بدء خادم OCR على {APP_HOST} على المنفذ {APP_PORT} ===")
    app.run(debug=APP_DEBUG, host=APP_HOST, port=APP_PORT)