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에서 Custom Engine - 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: {langs}")

        # 경계 상자 그리기 확인
        draw_bounding_box = data.get("draw_bounding_box", False)
        print(f"draw_bounding_box: {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)