EasyOCR
# Integración VNTranslator OCR con el motor EasyOCR
# Versión: 1.0
# Autor: Fazx - GarudaMods | https://www.patreon.com/vntranslator
"""
# ==================================================================
# EasyOCR: https://github.com/JaidedAI/EasyOCR
# Requerido: python 3.10+ y PyTorch
# Instalar con: pip install easyocr
# ==================================================================
# Ejecuta este script con: python vntocr_easyocr.py
# En VNTranslator usa Motor Personalizado - HTTP POST con la configuración:
# -- URL: http://127.0.0.1:5353
# -- Tipo de contenido: application/json
# -- Encabezados: {}
# -- Cuerpo: {"image":"$IMAGE_BASE64", "langs": ["ja"]}
# -- Tipo de respuesta: JSON
# -- Consulta de respuesta: fullText
# ==================================================================
# Idiomas (código ISO de dos 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("La cadena Base64 está vacía o falta")
if "," in base64_string:
base64_string = base64_string.split(",")[1]
try:
image_decode = base64.b64decode(base64_string)
print("Decodificación Base64 exitosa")
# abrir la imagen con PIL
image = Image.open(BytesIO(image_decode))
print(f"Formato de imagen: {image.format}, tamaño: {image.size}")
# convertir imagen PIL a arreglo NumPy
image_np = np.array(image)
print(f"Imagen convertida a arreglo NumPy con forma: {image_np.shape}")
return image_np
except Exception as e:
raise ValueError(f"Error al decodificar la imagen: {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=== Solicitud OCR ===")
print(f"Método: {request.method}")
print(f"Encabezados: {dict(request.headers)}")
if not request.is_json:
print("La solicitud no es JSON")
return jsonify({"error": "La solicitud debe ser JSON"}), 400
data = request.get_json()
# registrar payload
print(f"Claves JSON de la solicitud: {list(data.keys())}")
# verificar imagen
if "image" not in data:
print("No hay datos de imagen")
return jsonify({"error": "No hay datos de imagen"}), 400
# decodificar imagen base64
try:
image = base64_to_numpy(data["image"])
except Exception as e:
print(f"Fallo al decodificar la imagen: {e}")
return jsonify({"error": f"Fallo al decodificar la imagen: {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"Fallo al cargar el modelo: {e}")
return jsonify({"error": f"Fallo al cargar el modelo: {str(e)}"}), 400
print(f"idiomas: {langs}")
# verificar dibujar cuadro delimitador
draw_bounding_box = data.get("draw_bounding_box", False)
print(f"dibujar_cuadro_delimitador: {draw_bounding_box}")
# ejecutar OCR
# https://github.com/JaidedAI/EasyOCR?tab=readme-ov-file#usage
result = reader.readtext(image)
print(f"OCR completado correctamente: {result}")
# analizar 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"Error en la solicitud: {e}")
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
print(f"=== Iniciando servidor OCR {APP_HOST} en el puerto {APP_PORT} ===")
app.run(debug=APP_DEBUG, host=APP_HOST, port=APP_PORT)