# -*- coding: utf-8 -*-
"""OCR wrapper for 叮当工具箱.

Uses RapidOCR (ONNX Runtime) for text recognition.
Outputs JSON to stdout.

Usage:
  python run_ocr.py <image_path>

Requires: pip install rapidocr-onnxruntime
"""
import json
import os
import sys
import traceback

try:
    from rapidocr_onnxruntime import RapidOCR
    engine = None

    def get_engine():
        global engine
        if engine is None:
            engine = RapidOCR()
        return engine

    def main():
        if len(sys.argv) < 2:
            print(json.dumps({"success": False, "error": "请指定图片路径"}))
            return

        path = sys.argv[1]
        if not os.path.exists(path):
            print(json.dumps({"success": False, "error": f"图片文件不存在: {path}"}))
            return

        try:
            ocr = get_engine()
            result, elapse = ocr(path)

            if not result:
                print(json.dumps({"success": True, "text": "", "lines": []}, ensure_ascii=False))
                return

            lines = []
            for item in result:
                box = item[0]
                text = item[1]
                confidence = item[2]
                lines.append({"text": text, "confidence": round(float(confidence), 4)})

            full_text = "\n".join([l["text"] for l in lines])
            print(json.dumps({"success": True, "text": full_text, "lines": lines}, ensure_ascii=False))
        except Exception as e:
            print(json.dumps({"success": False, "error": str(e), "traceback": traceback.format_exc()}, ensure_ascii=False))

except ImportError:
    print(json.dumps({"success": False, "error": "RapidOCR 未安装，请运行: pip install rapidocr-onnxruntime"}))
    sys.exit(0)

if __name__ == "__main__":
    main()
