EasyOCR

vntocr_easyocr.py
# Integração VNTranslator OCR com o mecanismo EasyOCR
# Versão: 1.0
# Autor: Fazx - GarudaMods | https://www.patreon.com/vntranslator

"""
# ==================================================================
# EasyOCR: https://github.com/JaidedAI/EasyOCR
# Requisitos: python 3.10+ e PyTorch
# Instale com: pip install easyocr
# ==================================================================
# Execute este script com: python vntocr_easyocr.py
# No VNTranslator use Motor Personalizado - HTTP POST com a configuração:
# -- URL: http://127.0.0.1:5353
# -- Tipo de conteúdo: application/json
# -- Cabeçalhos: {}
# -- Corpo: {"image":"$IMAGE_BASE64", "langs": ["ja"]}
# -- Tipo de resposta: JSON
# -- Consulta de resposta: fullText
# ==================================================================
# Idiomas (código ISO de duas letras) https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
# -- Japonês = ja
# -- Inglês = 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("A string Base64 está vazia ou ausente")

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

    try:
        image_decode = base64.b64decode(base64_string)
        print("Decodificação Base64 bem-sucedida")

        # abra a imagem com PIL
        image = Image.open(BytesIO(image_decode))
        print(f"Formato da imagem: {image.format}, tamanho: {image.size}")

        # converte a imagem PIL para array NumPy
        image_np = np.array(image)
        print(f"Imagem convertida para array NumPy com shape: {image_np.shape}")

        return image_np
    except Exception as e:
        raise ValueError(f"Falha na decodificação da imagem: {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=== Requisição OCR ===")
        print(f"Método: {request.method}")
        print(f"Cabeçalhos: {dict(request.headers)}")
        
        if not request.is_json:
            print("A requisição não é JSON")
            return jsonify({"error": "A requisição deve ser JSON"}), 400
        
        data = request.get_json()

        # registrar payload
        print(f"Chaves JSON da requisição: {list(data.keys())}")

        # verificar imagem
        if "image" not in data:
            print("Sem dados de imagem")
            return jsonify({"error": "Sem dados de imagem"}), 400
        
        # decodificar imagem base64
        try:            
            image = base64_to_numpy(data["image"])
        except Exception as e:
            print(f"Falha na decodificação da imagem: {e}")
            return jsonify({"error": f"Falha na decodificação da imagem: {str(e)}"}), 400

        # verificar idiomas
        langs = data.get("langs", ["ja"])
        try:
            if langs != default_langs:
                default_langs = langs
                reader = easyocr.Reader(default_langs)
        except Exception as e:
            print(f"Falha ao carregar o modelo: {e}")
            return jsonify({"error": f"Falha ao carregar o modelo: {str(e)}"}), 400
        print(f"idiomas: {langs}")

        # verificar desenhar caixa delimitadora
        draw_bounding_box = data.get("draw_bounding_box", False)
        print(f"desenhar_caixa_delimitadora: {draw_bounding_box}")

        # executar OCR
        # https://github.com/JaidedAI/EasyOCR?tab=readme-ov-file#usage
        result = reader.readtext(image)
        print(f"OCR concluído com sucesso: {result}")

        # analisar resultado
        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"Erro na requisição: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    print(f"=== Iniciando servidor OCR {APP_HOST} na porta {APP_PORT} ===")
    app.run(debug=APP_DEBUG, host=APP_HOST, port=APP_PORT)