"""Engine: изображение → текст (OCR, PP-OCRv4). Веса ONNX загружаются локально из model/ (self-contained), а не из site-packages. Инференс через onnxruntime — torch не нужен. """ from __future__ import annotations from pathlib import Path from typing import Any, Dict, List, Optional, Union from rapidocr_onnxruntime import RapidOCR DEFAULT_MODEL_DIR = Path(__file__).resolve().parent.parent / "model" class ImageEngine: """Извлечение текста из изображений (китай + латиница).""" def __init__( self, model_dir: Optional[Union[str, Path]] = None, text_score: float = 0.5, ) -> None: model_dir = Path(model_dir or DEFAULT_MODEL_DIR) det = model_dir / "ch_PP-OCRv4_det_infer.onnx" rec = model_dir / "ch_PP-OCRv4_rec_infer.onnx" cls = model_dir / "ch_ppocr_mobile_v2.0_cls_infer.onnx" kwargs: Dict[str, Any] = {"text_score": text_score} if det.exists() and rec.exists() and cls.exists(): # локальные веса (самодостаточный пакет) kwargs.update( det_model_path=str(det), rec_model_path=str(rec), cls_model_path=str(cls), ) self._ocr = RapidOCR(**kwargs) self.text_score = text_score def ocr(self, image: Union[str, Path]) -> Dict[str, Any]: """Извлечь текст. Возвращает {text, lines: [{text, score, box}]}.""" result, _elapse = self._ocr(str(image)) lines: List[Dict[str, Any]] = [] if result: for box, text, score in result: lines.append( { "text": text, "score": round(float(score), 4), "box": [[round(float(x), 1), round(float(y), 1)] for x, y in box], } ) return { "text": "\n".join(line["text"] for line in lines), "lines": lines, }