File size: 2,125 Bytes
755023e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""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,
        }