lzytools-OCR 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: lzytools_OCR
3
+ Version: 0.1.0
4
+ Summary: Python自用包-OCR相关方法
5
+ Home-page: https://github.com/PPJUST/lzytools
6
+ Author: PPJUST
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Dynamic: author
10
+ Dynamic: description
11
+ Dynamic: description-content-type
12
+ Dynamic: home-page
13
+ Dynamic: requires-python
14
+ Dynamic: summary
15
+
16
+ Python自用包-OCR相关方法
@@ -0,0 +1,154 @@
1
+ # lzytools_OCR
2
+
3
+ `lzytools_OCR` 是一个个人使用的轻量 Python OCR 库,提供统一的图片输入、本地 OCR 模型调用、文块后处理和结果导出接口。
4
+
5
+ ## 设计思路
6
+
7
+ 库的处理链路是:
8
+
9
+ 1. 本地 OCR 引擎识别图片,输出若干文块:`{"text", "score", "box"}`
10
+ 2. 后处理模块执行忽略区域与排版解析,为每个文块补充 `end` 结束符
11
+ 3. 结果层按需返回文块字典或拼接后的纯文本
12
+
13
+ 内置引擎:
14
+
15
+ - `rapid`:本地 RapidOCR,自动兼容新版 `rapidocr` 和旧版 `rapidocr_onnxruntime`
16
+
17
+ ## 安装
18
+
19
+ ```bash
20
+ python -m pip install -e .
21
+ ```
22
+
23
+ 安装本地 RapidOCR 引擎(二选一):
24
+
25
+ ```bash
26
+ python -m pip install -e ".[rapid]"
27
+ # 或旧版:
28
+ python -m pip install -e ".[rapid-legacy]"
29
+ ```
30
+
31
+ ## 快速开始
32
+
33
+ ```python
34
+ from lzytools_OCR import OCR
35
+
36
+ ocr = OCR() # 默认本地 RapidOCR,parser="multi_para",limit_side_len=960
37
+
38
+ result = ocr.recognize("demo.png")
39
+ print(result.code) # 100 成功,101 无文字
40
+ print(result.text) # 按排版解析拼接后的全文
41
+ print(result.mean_score) # 平均置信度
42
+
43
+ # 只取文本
44
+ text = ocr.recognize_text("demo.png")
45
+
46
+ # 直接把 OCR 实例当函数调用
47
+ text = ocr("demo.png")
48
+ ```
49
+
50
+ ## 常用参数
51
+
52
+ ```python
53
+ from pathlib import Path
54
+ from lzytools_OCR import OCR
55
+
56
+ ocr = OCR(
57
+ parser="single_line", # 排版解析方案
58
+ limit_side_len=2880, # 图像最长边限制,0 表示不限制
59
+ ignore_area=[ # 忽略区域,区域内部完整文块会被丢弃
60
+ [[0, 0], [200, 60]],
61
+ ],
62
+ )
63
+
64
+ result = ocr.recognize(Path("demo.png"))
65
+ result.save("demo.json") # 也可保存为 demo.txt
66
+ ```
67
+
68
+ 支持的 `parser`:
69
+
70
+ | 方案 | 说明 |
71
+ | --- | --- |
72
+ | `none` | 不做处理,保留引擎返回的文块顺序 |
73
+ | `single_line` | 单栏,总是换行 |
74
+ | `single_none` | 单栏,不换行 |
75
+ | `single_para` | 单栏,按行间距近似自然段 |
76
+ | `single_code` | 单栏,尽量保留空格缩进 |
77
+ | `multi_line` | 多栏,总是换行 |
78
+ | `multi_none` | 多栏,不换行 |
79
+ | `multi_para` | 多栏,按行间距近似自然段 |
80
+
81
+ > 多栏方案使用基于列间距的轻量启发式实现。
82
+
83
+ ## 输入类型
84
+
85
+ `recognize()` 支持:
86
+
87
+ - 图片路径:`str` / `pathlib.Path`
88
+ - 图片字节:`bytes` / `bytearray` / `memoryview`
89
+ - `PIL.Image.Image`
90
+ - `numpy.ndarray`(RGB 或灰度)
91
+
92
+ base64 图片建议使用专用方法:
93
+
94
+ ```python
95
+ result = ocr.recognize_base64(base64_string) # 兼容 data URI 前缀
96
+ ```
97
+
98
+ 批量识别:
99
+
100
+ ```python
101
+ results = ocr.recognize_many(["a.png", "b.png"])
102
+ for item in results:
103
+ print(item.text)
104
+ ```
105
+
106
+ ## 结果结构
107
+
108
+ `OCRResult` 主要属性:
109
+
110
+ | 属性 | 说明 |
111
+ | --- | --- |
112
+ | `code` | `100` 成功,`101` 无文字,其他值由引擎异常体现 |
113
+ | `blocks` | `TextBlock` 列表,每项含 `text`、`score`、`box`、`end` |
114
+ | `text` | 按 `end` 拼接后的全文 |
115
+ | `mean_score` | 平均置信度 |
116
+ | `elapsed` / `timestamp` | 耗时秒数 / 任务开始时间戳 |
117
+ | `raw` | 引擎原始返回,便于调试 |
118
+
119
+ 字典输出:
120
+
121
+ ```python
122
+ result.to_dict() # data 为文块字典列表
123
+ result.to_dict("text") # data 为纯文本
124
+ ```
125
+
126
+ ## 自定义本地引擎
127
+
128
+ 任何实现 `recognize(image) -> (blocks, elapsed)` 的对象都可以作为本地引擎:
129
+
130
+ ```python
131
+ from lzytools_OCR import OCR, BaseEngine
132
+
133
+ class MyEngine(BaseEngine):
134
+ name = "my-engine"
135
+
136
+ def recognize(self, image):
137
+ return [
138
+ {
139
+ "text": "Hello",
140
+ "score": 0.99,
141
+ "box": [[0, 0], [50, 0], [50, 20], [0, 20]],
142
+ }
143
+ ], 0.01
144
+
145
+ ocr = OCR(engine=MyEngine(), parser="none")
146
+ print(ocr.recognize_text("demo.png"))
147
+ ```
148
+
149
+ ## 测试
150
+
151
+ ```bash
152
+ python -m pip install -e .
153
+ python -m unittest discover -s tests -p "test_lzytools_OCR.py" -v
154
+ ```
@@ -0,0 +1,26 @@
1
+ """lzytools_OCR:个人使用的轻量 Python OCR 库。"""
2
+
3
+ from .engines import BaseEngine, RapidOCREngine, create_engine
4
+ from .exceptions import (
5
+ ConfigurationError,
6
+ EngineError,
7
+ LzytoolsOcrError,
8
+ UnsupportedSourceError,
9
+ )
10
+ from .models import OCRResult, TextBlock
11
+ from .ocr import OCR
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "BaseEngine",
17
+ "ConfigurationError",
18
+ "EngineError",
19
+ "LzytoolsOcrError",
20
+ "OCR",
21
+ "OCRResult",
22
+ "RapidOCREngine",
23
+ "TextBlock",
24
+ "UnsupportedSourceError",
25
+ "create_engine",
26
+ ]
@@ -0,0 +1,135 @@
1
+ """OCR 引擎适配层。
2
+
3
+ 本库只使用本地 OCR 模型:RapidOCR(自动适配新版 ``rapidocr`` 与旧版
4
+ ``rapidocr_onnxruntime``)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import Any, Dict, List, Optional, Tuple
11
+
12
+ from .exceptions import ConfigurationError, EngineError
13
+
14
+ RawBlock = Dict[str, Any]
15
+
16
+
17
+ def _elapsed_to_float(value: Any) -> float:
18
+ """兼容 float 耗时与旧版 [det, cls, rec] 耗时列表。"""
19
+ if isinstance(value, (list, tuple)):
20
+ return sum(float(item) for item in value if isinstance(item, (int, float)))
21
+ try:
22
+ return float(value or 0.0)
23
+ except (TypeError, ValueError):
24
+ return 0.0
25
+
26
+
27
+ class BaseEngine(ABC):
28
+ """OCR 引擎的统一接口。"""
29
+
30
+ name = "base"
31
+
32
+ @abstractmethod
33
+ def recognize(self, image: Any) -> Tuple[List[RawBlock], float]:
34
+ """输入 RGB numpy 数组,返回 (文块列表, 引擎耗时秒)。"""
35
+
36
+ def close(self) -> None:
37
+ """可选的资源释放。"""
38
+
39
+
40
+ class RapidOCREngine(BaseEngine):
41
+ """本地 RapidOCR 引擎。"""
42
+
43
+ name = "rapid"
44
+
45
+ def __init__(self, **engine_kwargs: Any):
46
+ self._backend = ""
47
+ rapid_cls = None
48
+
49
+ try:
50
+ from rapidocr import RapidOCR # type: ignore
51
+
52
+ rapid_cls = RapidOCR
53
+ self._backend = "new"
54
+ except ImportError:
55
+ try:
56
+ from rapidocr_onnxruntime import RapidOCR # type: ignore
57
+
58
+ rapid_cls = RapidOCR
59
+ self._backend = "legacy"
60
+ except ImportError as exc:
61
+ raise EngineError(
62
+ "未安装本地 OCR 引擎。请安装 rapidocr>=2.0 "
63
+ "或旧版 rapidocr-onnxruntime>=1.4。"
64
+ ) from exc
65
+
66
+ try:
67
+ self._engine = rapid_cls(**engine_kwargs)
68
+ except Exception as exc:
69
+ raise EngineError(f"RapidOCR 初始化失败: {exc}") from exc
70
+
71
+ @staticmethod
72
+ def _normalize_new(result: Any) -> Optional[Tuple[List[RawBlock], float]]:
73
+ boxes = getattr(result, "boxes", None)
74
+ texts = getattr(result, "txts", None)
75
+ if boxes is None or texts is None:
76
+ return None
77
+
78
+ scores = getattr(result, "scores", None)
79
+ elapsed = _elapsed_to_float(getattr(result, "elapse", 0.0))
80
+ blocks: List[RawBlock] = []
81
+
82
+ for index, text in enumerate(texts):
83
+ if index >= len(boxes):
84
+ break
85
+ box = [[float(point[0]), float(point[1])] for point in boxes[index]]
86
+ score = float(scores[index]) if scores is not None and index < len(scores) else 0.0
87
+ blocks.append({"text": str(text), "score": score, "box": box})
88
+
89
+ return blocks, elapsed
90
+
91
+ @staticmethod
92
+ def _normalize_legacy(result: Any) -> Optional[Tuple[List[RawBlock], float]]:
93
+ if not isinstance(result, (tuple, list)) or len(result) < 2:
94
+ return None
95
+
96
+ raw, elapsed_value = result[0], result[1]
97
+ elapsed = _elapsed_to_float(elapsed_value)
98
+ if raw is None:
99
+ return [], elapsed
100
+
101
+ blocks: List[RawBlock] = []
102
+ for row in raw:
103
+ if len(row) < 3:
104
+ continue
105
+ points, text, score = row[0], row[1], row[2]
106
+ box = [[float(point[0]), float(point[1])] for point in points]
107
+ blocks.append({"text": str(text), "score": float(score), "box": box})
108
+ return blocks, elapsed
109
+
110
+ def recognize(self, image: Any) -> Tuple[List[RawBlock], float]:
111
+ try:
112
+ result = self._engine(image)
113
+ except Exception as exc:
114
+ raise EngineError(f"RapidOCR 识别失败: {exc}") from exc
115
+
116
+ normalized = self._normalize_new(result)
117
+ if normalized is None:
118
+ normalized = self._normalize_legacy(result)
119
+ if normalized is None:
120
+ raise EngineError(f"无法解析 RapidOCR 返回结构: {type(result).__name__}")
121
+ return normalized
122
+
123
+
124
+ def create_engine(name: str, **kwargs: Any) -> BaseEngine:
125
+ """按名称创建本地引擎。"""
126
+ registry = {
127
+ "rapid": RapidOCREngine,
128
+ "rapidocr": RapidOCREngine,
129
+ }
130
+ key = (name or "").lower()
131
+ if key not in registry:
132
+ raise ConfigurationError(
133
+ f"未知引擎 {name!r},可选: {', '.join(sorted(registry))}"
134
+ )
135
+ return registry[key](**kwargs)
@@ -0,0 +1,17 @@
1
+ """lzytools_OCR 的异常类型。"""
2
+
3
+
4
+ class LzytoolsOcrError(Exception):
5
+ """库的基础异常。"""
6
+
7
+
8
+ class ConfigurationError(LzytoolsOcrError, ValueError):
9
+ """配置参数不合法。"""
10
+
11
+
12
+ class EngineError(LzytoolsOcrError, RuntimeError):
13
+ """OCR 引擎初始化或识别失败。"""
14
+
15
+
16
+ class UnsupportedSourceError(LzytoolsOcrError, TypeError):
17
+ """输入不是受支持的图片来源。"""
@@ -0,0 +1,87 @@
1
+ """图片输入归一化:路径 / 字节 / base64 / PIL / numpy 统一转为 RGB numpy 数组。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import io
8
+ from pathlib import Path
9
+ from typing import Union
10
+
11
+ import numpy as np
12
+ from PIL import Image, ImageOps
13
+
14
+ from .exceptions import UnsupportedSourceError
15
+
16
+ ImageSource = Union[str, Path, bytes, bytearray, memoryview, Image.Image, np.ndarray]
17
+
18
+ _RESAMPLING = getattr(Image, "Resampling", Image).LANCZOS
19
+
20
+
21
+ def _limit_side(image: Image.Image, limit_side_len: int | float) -> Image.Image:
22
+ if limit_side_len and limit_side_len > 0 and max(image.size) > limit_side_len:
23
+ image = image.copy()
24
+ image.thumbnail((int(limit_side_len), int(limit_side_len)), _RESAMPLING)
25
+ return image
26
+
27
+
28
+ def _ndarray_to_pil(array: np.ndarray) -> Image.Image:
29
+ array = np.asarray(array)
30
+ if array.ndim == 2:
31
+ return Image.fromarray(array)
32
+ if array.ndim == 3:
33
+ if array.shape[2] == 1:
34
+ return Image.fromarray(array[:, :, 0])
35
+ if array.shape[2] == 3:
36
+ return Image.fromarray(array)
37
+ if array.shape[2] == 4:
38
+ return Image.fromarray(array).convert("RGB")
39
+ raise UnsupportedSourceError(f"不支持的 numpy 图片形状: {array.shape}")
40
+
41
+
42
+ def to_numpy(source: ImageSource, limit_side_len: int | float = 0) -> np.ndarray:
43
+ """将支持的图片来源转成 RGB numpy 数组。"""
44
+ if isinstance(source, np.ndarray):
45
+ pil = _ndarray_to_pil(source)
46
+ elif isinstance(source, Image.Image):
47
+ pil = source
48
+ elif isinstance(source, (bytes, bytearray, memoryview)):
49
+ try:
50
+ pil = Image.open(io.BytesIO(bytes(source)))
51
+ except Exception as exc:
52
+ raise UnsupportedSourceError(f"无法从字节流解析图片: {exc}") from exc
53
+ elif isinstance(source, (str, Path)):
54
+ path = Path(source)
55
+ if not path.is_file():
56
+ raise UnsupportedSourceError(f"图片路径不存在或不是文件: {path}")
57
+ try:
58
+ pil = Image.open(path)
59
+ except Exception as exc:
60
+ raise UnsupportedSourceError(f"无法打开图片 {path}: {exc}") from exc
61
+ else:
62
+ raise UnsupportedSourceError(
63
+ "输入需为图片路径、bytes、base64、PIL.Image 或 numpy.ndarray,"
64
+ f"当前类型: {type(source).__name__}"
65
+ )
66
+
67
+ try:
68
+ pil = ImageOps.exif_transpose(pil).convert("RGB")
69
+ pil = _limit_side(pil, limit_side_len)
70
+ return np.asarray(pil)
71
+ except Exception as exc:
72
+ raise UnsupportedSourceError(f"图片预处理失败: {exc}") from exc
73
+
74
+
75
+ def base64_to_numpy(data: str, limit_side_len: int | float = 0) -> np.ndarray:
76
+ """将 base64 图片字符串转成 RGB numpy 数组,兼容 data URI 前缀。"""
77
+ if not isinstance(data, str):
78
+ raise UnsupportedSourceError("base64 图片必须是字符串")
79
+ if data.startswith("data:"):
80
+ data = data.split(",", 1)[-1]
81
+ try:
82
+ raw = base64.b64decode(data, validate=False)
83
+ except (binascii.Error, ValueError) as exc:
84
+ raise UnsupportedSourceError(f"base64 解码失败: {exc}") from exc
85
+ if not raw:
86
+ raise UnsupportedSourceError("base64 图片内容为空")
87
+ return to_numpy(raw, limit_side_len)
@@ -0,0 +1,130 @@
1
+ """识别结果的数据模型。
2
+
3
+ 字段采用通用的 ``code/data/time/timestamp`` 结构,文块包含
4
+ ``text/score/box/end``。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Sequence, Union
14
+
15
+ Number = Union[int, float]
16
+ Point = Sequence[Number]
17
+ Box = Sequence[Point]
18
+
19
+
20
+ @dataclass
21
+ class TextBlock:
22
+ """一个文本块。"""
23
+
24
+ text: str
25
+ score: float = 0.0
26
+ box: List[List[float]] = field(default_factory=list)
27
+ end: str = ""
28
+
29
+ @classmethod
30
+ def from_dict(cls, item: Dict[str, Any]) -> "TextBlock":
31
+ """由引擎/API 返回的字典创建文本块。"""
32
+ box: List[List[float]] = []
33
+ for point in item.get("box") or []:
34
+ if len(point) < 2:
35
+ raise ValueError(f"文本框坐标至少需要两个值: {point}")
36
+ box.append([float(point[0]), float(point[1])])
37
+
38
+ return cls(
39
+ text=str(item.get("text", "") or ""),
40
+ score=float(item.get("score", 0.0) or 0.0),
41
+ box=box,
42
+ end=str(item.get("end", "") or ""),
43
+ )
44
+
45
+ def to_dict(self) -> Dict[str, Any]:
46
+ """转为普通字典。"""
47
+ return {
48
+ "text": self.text,
49
+ "score": round(self.score, 6),
50
+ "box": [[round(x, 2), round(y, 2)] for x, y in self.box],
51
+ "end": self.end,
52
+ }
53
+
54
+
55
+ @dataclass
56
+ class OCRResult:
57
+ """一次识别的完整结果。"""
58
+
59
+ code: int
60
+ blocks: List[TextBlock] = field(default_factory=list)
61
+ elapsed: float = 0.0
62
+ timestamp: float = field(default_factory=time.time)
63
+ raw: Any = None
64
+
65
+ @property
66
+ def success(self) -> bool:
67
+ return self.code == 100
68
+
69
+ @property
70
+ def no_text(self) -> bool:
71
+ return self.code == 101
72
+
73
+ @property
74
+ def text(self) -> str:
75
+ """按每个文本块的 end 结束符拼接全文。"""
76
+ if not self.blocks:
77
+ return ""
78
+ parts: List[str] = []
79
+ for index, block in enumerate(self.blocks):
80
+ parts.append(block.text)
81
+ if index < len(self.blocks) - 1:
82
+ parts.append(block.end or "")
83
+ return "".join(parts)
84
+
85
+ @property
86
+ def mean_score(self) -> float:
87
+ """所有文本块的平均置信度。"""
88
+ if not self.blocks:
89
+ return 0.0
90
+ return sum(block.score for block in self.blocks) / len(self.blocks)
91
+
92
+ def to_dict(self, format: str = "dict") -> Dict[str, Any]:
93
+ """转为字典。
94
+
95
+ ``format="text"`` 时 ``data`` 为拼接后的纯文本,否则为文块列表。
96
+ """
97
+ if format not in ("dict", "text"):
98
+ raise ValueError('format 只支持 "dict" 或 "text"')
99
+
100
+ data: Any = self.text if format == "text" else [b.to_dict() for b in self.blocks]
101
+ return {
102
+ "code": self.code,
103
+ "data": data,
104
+ "score": round(self.mean_score, 6),
105
+ "time": round(self.elapsed, 6),
106
+ "timestamp": self.timestamp,
107
+ }
108
+
109
+ def save(self, path: Union[str, Path], *, format: str | None = None) -> Path:
110
+ """保存结果。默认根据后缀选择 txt 或 json。"""
111
+ target = Path(path)
112
+ target.parent.mkdir(parents=True, exist_ok=True)
113
+ output_format = format or ("txt" if target.suffix.lower() == ".txt" else "json")
114
+
115
+ if output_format == "txt":
116
+ target.write_text(self.text, encoding="utf-8")
117
+ elif output_format == "json":
118
+ target.write_text(
119
+ json.dumps(self.to_dict(), ensure_ascii=False, indent=2),
120
+ encoding="utf-8",
121
+ )
122
+ else:
123
+ raise ValueError('format 只支持 "txt" 或 "json"')
124
+ return target
125
+
126
+ def __len__(self) -> int:
127
+ return len(self.blocks)
128
+
129
+ def __iter__(self):
130
+ return iter(self.blocks)
@@ -0,0 +1,150 @@
1
+ """lzytools_OCR 的主调用入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Iterable, List, Optional, Union
7
+
8
+ from .engines import BaseEngine, create_engine
9
+ from .exceptions import ConfigurationError
10
+ from .image import ImageSource, base64_to_numpy, to_numpy
11
+ from .models import OCRResult, TextBlock
12
+ from .tbpu import process_blocks
13
+
14
+ PARSERS = (
15
+ "none",
16
+ "multi_para",
17
+ "multi_line",
18
+ "multi_none",
19
+ "single_para",
20
+ "single_line",
21
+ "single_none",
22
+ "single_code",
23
+ )
24
+
25
+
26
+ class OCR:
27
+ """一个简单的 OCR 调用封装。
28
+
29
+ 示例::
30
+
31
+ from lzytools_OCR import OCR
32
+
33
+ ocr = OCR()
34
+ result = ocr.recognize("demo.png")
35
+ print(result.text)
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ engine: Union[str, BaseEngine, None] = None,
41
+ *,
42
+ parser: str = "multi_para",
43
+ limit_side_len: int = 960,
44
+ ignore_area: Optional[List[Any]] = None,
45
+ ):
46
+ if isinstance(engine, str):
47
+ engine = create_engine(engine)
48
+ elif engine is None:
49
+ engine = create_engine("rapid")
50
+ elif not callable(getattr(engine, "recognize", None)):
51
+ raise ConfigurationError("engine 必须实现 recognize(image) 方法")
52
+
53
+ if parser not in PARSERS:
54
+ raise ConfigurationError(f"未知排版解析方案 {parser!r},可选: {', '.join(PARSERS)}")
55
+
56
+ self.engine = engine
57
+ self.parser = parser
58
+ self.limit_side_len = limit_side_len
59
+ self.ignore_area = ignore_area
60
+
61
+ def recognize(
62
+ self,
63
+ source: ImageSource,
64
+ *,
65
+ parser: Optional[str] = None,
66
+ ignore_area: Optional[List[Any]] = None,
67
+ limit_side_len: Optional[int] = None,
68
+ ) -> OCRResult:
69
+ """识别一张图片,返回 :class:`OCRResult`。"""
70
+ limit = self.limit_side_len if limit_side_len is None else limit_side_len
71
+ image = to_numpy(source, limit or 0)
72
+ return self._run(image, parser=parser, ignore_area=ignore_area)
73
+
74
+ def recognize_text(
75
+ self,
76
+ source: ImageSource,
77
+ *,
78
+ parser: Optional[str] = None,
79
+ ignore_area: Optional[List[Any]] = None,
80
+ limit_side_len: Optional[int] = None,
81
+ ) -> str:
82
+ """识别一张图片,只返回拼接后的文本。"""
83
+ return self.recognize(
84
+ source,
85
+ parser=parser,
86
+ ignore_area=ignore_area,
87
+ limit_side_len=limit_side_len,
88
+ ).text
89
+
90
+ def recognize_base64(
91
+ self,
92
+ data: str,
93
+ *,
94
+ parser: Optional[str] = None,
95
+ ignore_area: Optional[List[Any]] = None,
96
+ limit_side_len: Optional[int] = None,
97
+ ) -> OCRResult:
98
+ """识别 base64 编码的图片。"""
99
+ limit = self.limit_side_len if limit_side_len is None else limit_side_len
100
+ image = base64_to_numpy(data, limit or 0)
101
+ return self._run(image, parser=parser, ignore_area=ignore_area)
102
+
103
+ def recognize_many(self, sources: Iterable[ImageSource]) -> List[OCRResult]:
104
+ """批量识别,顺序与输入一致。"""
105
+ return [self.recognize(source) for source in sources]
106
+
107
+ def _run(
108
+ self,
109
+ image: Any,
110
+ *,
111
+ parser: Optional[str],
112
+ ignore_area: Optional[List[Any]],
113
+ ) -> OCRResult:
114
+ wall_start = time.time()
115
+ perf_start = time.perf_counter()
116
+ raw_blocks, engine_elapsed = self.engine.recognize(image)
117
+ elapsed = engine_elapsed if engine_elapsed > 0 else time.perf_counter() - perf_start
118
+
119
+ selected_parser = parser or self.parser
120
+ if selected_parser not in PARSERS:
121
+ raise ConfigurationError(
122
+ f"未知排版解析方案 {selected_parser!r},可选: {', '.join(PARSERS)}"
123
+ )
124
+
125
+ selected_area = self.ignore_area if ignore_area is None else ignore_area
126
+ blocks_dict = process_blocks(raw_blocks or [], selected_parser, selected_area)
127
+ blocks = [TextBlock.from_dict(block) for block in blocks_dict if block.get("text")]
128
+ code = 100 if blocks else 101
129
+
130
+ return OCRResult(
131
+ code=code,
132
+ blocks=blocks,
133
+ elapsed=elapsed,
134
+ timestamp=wall_start,
135
+ raw=raw_blocks,
136
+ )
137
+
138
+ def close(self) -> None:
139
+ close = getattr(self.engine, "close", None)
140
+ if callable(close):
141
+ close()
142
+
143
+ def __call__(self, source: ImageSource) -> str:
144
+ return self.recognize_text(source)
145
+
146
+ def __enter__(self) -> "OCR":
147
+ return self
148
+
149
+ def __exit__(self, *args: Any) -> None:
150
+ self.close()
@@ -0,0 +1,270 @@
1
+ """文块后处理(tbpu)。
2
+
3
+ 引擎先返回零散的 ``{"text", "score", "box"}`` 文块,再经过忽略区域和
4
+ 排版解析,为每个文块补充 ``end`` 结束符。多栏方案采用基于列间距的
5
+ 轻量启发式实现。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import unicodedata
11
+ from statistics import median
12
+ from typing import Any, Dict, Iterable, List, Sequence, Tuple
13
+
14
+ from .exceptions import ConfigurationError
15
+
16
+ Block = Dict[str, Any]
17
+ BBox = Tuple[float, float, float, float]
18
+
19
+ _CJK_RANGES = (
20
+ (0x4E00, 0x9FFF),
21
+ (0x3040, 0x30FF),
22
+ (0x1100, 0x11FF),
23
+ (0x3130, 0x318F),
24
+ (0xAC00, 0xD7AF),
25
+ (0x3000, 0x303F),
26
+ (0xFE30, 0xFE4F),
27
+ (0xFF00, 0xFFEF),
28
+ )
29
+
30
+
31
+ def _is_cjk(character: str) -> bool:
32
+ code = ord(character)
33
+ return any(start <= code <= end for start, end in _CJK_RANGES)
34
+
35
+
36
+ def word_separator(left: str, right: str) -> str:
37
+ """根据前后字符决定两个文本块之间是否需要空格。"""
38
+ if not left or not right:
39
+ return ""
40
+ if _is_cjk(left) and _is_cjk(right):
41
+ return ""
42
+ if left == "-":
43
+ return ""
44
+ if unicodedata.category(right).startswith("P"):
45
+ return ""
46
+ return " "
47
+
48
+
49
+ def _copy_blocks(blocks: Iterable[Dict[str, Any]]) -> List[Block]:
50
+ """复制并规范化文块,跳过空文本。"""
51
+ result: List[Block] = []
52
+ for raw in blocks:
53
+ text = str(raw.get("text", "") or "")
54
+ if not text.strip():
55
+ continue
56
+
57
+ box: List[List[float]] = []
58
+ for point in raw.get("box") or []:
59
+ if len(point) < 2:
60
+ raise ConfigurationError(f"文本框坐标至少需要两个值: {point}")
61
+ box.append([float(point[0]), float(point[1])])
62
+
63
+ result.append(
64
+ {
65
+ "text": text,
66
+ "score": float(raw.get("score", 0.0) or 0.0),
67
+ "box": box,
68
+ "end": str(raw.get("end", "") or ""),
69
+ }
70
+ )
71
+ return result
72
+
73
+
74
+ def _bbox(block: Block) -> BBox:
75
+ box = block["box"]
76
+ xs = [point[0] for point in box]
77
+ ys = [point[1] for point in box]
78
+ return min(xs), min(ys), max(xs), max(ys)
79
+
80
+
81
+ def _normalize_area(area: Sequence[Any]) -> Tuple[float, float, float, float]:
82
+ """把 ``[[x1,y1],[x2,y2]]``、四点框或平铺四元组统一成边界框。"""
83
+ try:
84
+ if len(area) == 4 and all(isinstance(v, (int, float)) for v in area):
85
+ x1, y1, x2, y2 = area
86
+ elif len(area) == 2:
87
+ x1, y1 = area[0][0], area[0][1]
88
+ x2, y2 = area[1][0], area[1][1]
89
+ elif len(area) >= 4:
90
+ x1, y1 = area[0][0], area[0][1]
91
+ x2, y2 = area[2][0], area[2][1]
92
+ else:
93
+ raise ValueError("区域格式无法识别")
94
+ return (
95
+ min(float(x1), float(x2)),
96
+ min(float(y1), float(y2)),
97
+ max(float(x1), float(x2)),
98
+ max(float(y1), float(y2)),
99
+ )
100
+ except Exception as exc:
101
+ raise ConfigurationError(
102
+ "忽略区域格式应为 [[x1,y1],[x2,y2]],当前值不合法: "
103
+ f"{area}"
104
+ ) from exc
105
+
106
+
107
+ def apply_ignore_area(blocks: List[Block], areas: Sequence[Sequence[Any]]) -> List[Block]:
108
+ """删除完全落在任意忽略区域内的文本块。"""
109
+ normalized = [_normalize_area(area) for area in areas]
110
+ result: List[Block] = []
111
+ for block in blocks:
112
+ left, top, right, bottom = _bbox(block)
113
+ ignored = any(
114
+ ax1 <= left and ay1 <= top and ax2 >= right and ay2 >= bottom
115
+ for ax1, ay1, ax2, ay2 in normalized
116
+ )
117
+ if not ignored:
118
+ result.append(block)
119
+ return result
120
+
121
+
122
+ def _group_lines(blocks: List[Block]) -> List[List[Block]]:
123
+ """按高度、垂直中心位置把文本块聚成行。"""
124
+ items = [(block, _bbox(block)) for block in blocks if block["text"]]
125
+ if not items:
126
+ return []
127
+ items.sort(key=lambda item: (item[1][1], item[1][0]))
128
+
129
+ used = [False] * len(items)
130
+ lines: List[List[Block]] = []
131
+
132
+ for index, (block, (_, top, _, bottom)) in enumerate(items):
133
+ if used[index]:
134
+ continue
135
+ used[index] = True
136
+ height = max(1.0, bottom - top)
137
+ center = (top + bottom) / 2
138
+ line = [block]
139
+
140
+ for other_index in range(index + 1, len(items)):
141
+ if used[other_index]:
142
+ continue
143
+ other, (_, other_top, _, other_bottom) = items[other_index]
144
+ other_height = max(1.0, other_bottom - other_top)
145
+ other_center = (other_top + other_bottom) / 2
146
+
147
+ if abs(center - other_center) > max(height, other_height) * 0.6:
148
+ continue
149
+ if abs(height - other_height) > max(height, other_height) * 0.8:
150
+ continue
151
+
152
+ used[other_index] = True
153
+ line.append(other)
154
+
155
+ line.sort(key=lambda item: _bbox(item)[0])
156
+ lines.append(line)
157
+
158
+ lines.sort(key=lambda line: min(_bbox(block)[1] for block in line))
159
+ return lines
160
+
161
+
162
+ def _set_line_ends(lines: List[List[Block]], *, code_mode: bool = False) -> None:
163
+ """设置同一行内相邻文块的结束符,行末默认换行。"""
164
+ for line in lines:
165
+ for index, block in enumerate(line):
166
+ if index == len(line) - 1:
167
+ block["end"] = "\n"
168
+ continue
169
+
170
+ next_block = line[index + 1]
171
+ _, _, right, bottom = _bbox(block)
172
+ next_left, _, _, _ = _bbox(next_block)
173
+ height = max(1.0, bottom - _bbox(block)[1])
174
+ gap = next_left - right
175
+
176
+ if gap > height * (0.3 if code_mode else 1.2):
177
+ block["end"] = " "
178
+ else:
179
+ block["end"] = word_separator(block["text"][-1], next_block["text"][0])
180
+
181
+
182
+ def _apply_single(blocks: List[Block], mode: str) -> List[Block]:
183
+ out = _copy_blocks(blocks)
184
+ if mode == "none":
185
+ for block in out:
186
+ block["end"] = "\n"
187
+ return out
188
+
189
+ if mode not in ("single_line", "single_none", "single_para", "single_code"):
190
+ for block in out:
191
+ block["end"] = "\n"
192
+ return out
193
+
194
+ lines = _group_lines(out)
195
+ if not lines:
196
+ return out
197
+ _set_line_ends(lines, code_mode=(mode == "single_code"))
198
+
199
+ ordered = [block for line in lines for block in line]
200
+
201
+ if mode == "single_none":
202
+ for index, block in enumerate(ordered[:-1]):
203
+ if block["end"] == "\n":
204
+ block["end"] = word_separator(block["text"][-1], ordered[index + 1]["text"][0])
205
+ ordered[-1]["end"] = ""
206
+ elif mode == "single_para":
207
+ for index, line in enumerate(lines[:-1]):
208
+ last = line[-1]
209
+ next_first = lines[index + 1][0]
210
+ _, top, _, bottom = _bbox(last)
211
+ _, next_top, _, _ = _bbox(next_first)
212
+ height = max(1.0, bottom - top)
213
+ if next_top - bottom > height * 1.2:
214
+ last["end"] = "\n\n"
215
+
216
+ return ordered
217
+
218
+
219
+ def _group_columns(blocks: List[Block]) -> List[List[Block]]:
220
+ """用列间距做轻量分栏。"""
221
+ items = [(block, _bbox(block)) for block in blocks if block["text"]]
222
+ if not items:
223
+ return []
224
+
225
+ heights = [max(1.0, box[3] - box[1]) for _, box in items]
226
+ gap_threshold = median(heights) * 1.8
227
+ items.sort(key=lambda item: item[1][0])
228
+
229
+ columns: List[List[Block]] = []
230
+ current: List[Block] = []
231
+ right_edge: float | None = None
232
+
233
+ for block, (left, _, right, _) in items:
234
+ if current and right_edge is not None and left > right_edge + gap_threshold:
235
+ columns.append(current)
236
+ current = []
237
+ right_edge = None
238
+ current.append(block)
239
+ right_edge = right if right_edge is None else max(right_edge, right)
240
+
241
+ if current:
242
+ columns.append(current)
243
+
244
+ columns.sort(key=lambda column: min(_bbox(block)[0] for block in column))
245
+ return columns
246
+
247
+
248
+ def _apply_multi(blocks: List[Block], suffix: str) -> List[Block]:
249
+ if suffix not in ("line", "none", "para"):
250
+ suffix = "line"
251
+ result: List[Block] = []
252
+ for column in _group_columns(blocks):
253
+ result.extend(_apply_single(column, f"single_{suffix}"))
254
+ return result
255
+
256
+
257
+ def process_blocks(
258
+ blocks: Iterable[Dict[str, Any]],
259
+ parser: str = "none",
260
+ ignore_area: Sequence[Sequence[Any]] | None = None,
261
+ ) -> List[Block]:
262
+ """执行忽略区域与排版解析,返回新的文块列表。"""
263
+ out = _copy_blocks(blocks)
264
+ if ignore_area:
265
+ out = apply_ignore_area(out, ignore_area)
266
+
267
+ parser = (parser or "none").lower()
268
+ if parser.startswith("multi_"):
269
+ return _apply_multi(out, parser[len("multi_") :])
270
+ return _apply_single(out, parser)
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: lzytools_OCR
3
+ Version: 0.1.0
4
+ Summary: Python自用包-OCR相关方法
5
+ Home-page: https://github.com/PPJUST/lzytools
6
+ Author: PPJUST
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Dynamic: author
10
+ Dynamic: description
11
+ Dynamic: description-content-type
12
+ Dynamic: home-page
13
+ Dynamic: requires-python
14
+ Dynamic: summary
15
+
16
+ Python自用包-OCR相关方法
@@ -0,0 +1,13 @@
1
+ README.md
2
+ setup.py
3
+ lzytools_OCR/__init__.py
4
+ lzytools_OCR/engines.py
5
+ lzytools_OCR/exceptions.py
6
+ lzytools_OCR/image.py
7
+ lzytools_OCR/models.py
8
+ lzytools_OCR/ocr.py
9
+ lzytools_OCR/tbpu.py
10
+ lzytools_OCR.egg-info/PKG-INFO
11
+ lzytools_OCR.egg-info/SOURCES.txt
12
+ lzytools_OCR.egg-info/dependency_links.txt
13
+ lzytools_OCR.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ lzytools_OCR
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ import setuptools
2
+
3
+ setuptools.setup(
4
+ name="lzytools_OCR", # 项目名称
5
+ version="0.1.0", # 版本号
6
+ author="PPJUST", # 作者
7
+ description="Python自用包-OCR相关方法", # 描述
8
+ long_description='Python自用包-OCR相关方法', # 长描述
9
+ long_description_content_type="text/markdown", # 长描述语法 markdown
10
+ url="https://github.com/PPJUST/lzytools", # 项目地址
11
+ packages=setuptools.find_packages(),
12
+ python_requires='>=3.9',
13
+ )