Files
ocr-server/src/ocr_server/ocr.py
T
zimoyin e32ad664f1 feat(fields): 字段抽取支持按行锁定与多项匹配开关,修复进度日志被吞
字段抽取 src/ocr_server/fields.py
- 新增 row:只从第 N 行取值,行号由 bbox 纵向重叠的坐标分组得出,-1 表示不限定;
  用于排除正文/页眉里同名标签造成的误取
- 新增 separator_optional(标签后无冒号也抽,默认关闭)
  与 label_linebreak(标签内部跨行,如 姓 + 名:,默认关闭)
- 新增 occurrence(first/last,正副本、页眉页脚重复打印时取最后一个)
  与全局 extract_include_empty(未命中的字段返回空串,便于固定 schema)
- 修复:跨行命中的标签文本包含换行,归一化时未去换行导致匹配不到字段规则、
  取到的值被丢弃
- build_specs 在服务启动时校验:字段名重复、同一标签被多个字段共用、
  正则语法、max_length / occurrence / row 取值合法性

日志 src/ocr_server/logging_setup.py
- handler 改挂到 ocr_server logger 并关闭向 root 传播:Paddle 初始化会把 root
  级别改成 WARNING,依赖 root 会导致其后所有 INFO 日志(含 10/20/50/80/100
  进度行)被静默过滤,看起来像任务卡死

引擎配置
- enable_mkldnn 由写死的 False 改为可配置;cpu_threads 支持 max(吃满逻辑核心)
- pyproject 固定 paddlepaddle>=3.2,<3.3:3.3.x 的 PIR + oneDNN 组合会直接推理失败

打包
- 移除多余的 scripts 目录打包;新增 -DistPath 便于 dist 被占用时改址构建;
  构建结束输出 exe SHA256(避免再拿到旧产物)
- Ubuntu 脚本同步更新,并输出二进制 SHA256

文档
- README / config.yaml 注释按实测修订:行结构、模型档位对比、oneDNN 与版本差异、
  汉字字符类的范围与缺口、防止取错的机制与建议

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-12 14:37:03 +08:00

342 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import importlib
import logging
import os
import sys
import shutil
import threading
from pathlib import Path
from typing import Any, Callable
from ocr_server.config import resolve_cpu_threads
logger = logging.getLogger("ocr_server.ocr")
ProgressCallback = Callable[[int, str], None]
# PaddlePaddle 3.3.x 在 PIR + oneDNN 组合下有已知缺陷:启用 oneDNN 后推理会抛
# NotImplementedError(ConvertPirAttribute2RuntimeAttribute not support)。
KNOWN_MKLDNN_BROKEN_PREFIXES = ("3.3.",)
class OCRNotAvailable(RuntimeError):
pass
class OCRService:
"""Process-local PaddleOCR runner; model initialization is lazy and thread-safe."""
_process_model_lock = threading.Lock()
_MODEL_FILES = (
"config.json",
"inference.yml",
"inference.pdiparams",
"inference.json",
)
def __init__(
self,
lang: str = "ch",
device: str = "cpu",
model_dir: Path | str = "models",
det_model_name: str = "PP-OCRv5_server_det",
rec_model_name: str = "PP-OCRv5_server_rec",
text_det_limit_side_len: int = 960,
text_det_limit_type: str = "max",
text_det_thresh: float = 0.3,
text_det_box_thresh: float = 0.6,
text_det_unclip_ratio: float = 1.5,
text_rec_score_thresh: float = 0.0,
text_recognition_batch_size: int = 1,
cpu_threads: int | str = 10,
enable_mkldnn: bool = False,
) -> None:
self.lang = lang
self.device = device
self.model_dir = Path(model_dir).resolve()
self._det_model_name = det_model_name
self._rec_model_name = rec_model_name
self._text_det_limit_side_len = text_det_limit_side_len
self._text_det_limit_type = text_det_limit_type
self._text_det_thresh = text_det_thresh
self._text_det_box_thresh = text_det_box_thresh
self._text_det_unclip_ratio = text_det_unclip_ratio
self._text_rec_score_thresh = text_rec_score_thresh
self._text_recognition_batch_size = text_recognition_batch_size
self._cpu_threads = resolve_cpu_threads(cpu_threads)
self._enable_mkldnn = bool(enable_mkldnn)
self._engine: Any | None = None
self._lock = threading.Lock()
self._inference_lock = threading.Lock()
self._progress_callback: ProgressCallback | None = None
self._progress_reached = 0
def _get_engine(self) -> Any:
if self._engine is None:
with self._lock:
if self._engine is None:
self.model_dir.mkdir(parents=True, exist_ok=True)
self._remove_incomplete_models()
# PaddleX stores downloaded official models below this directory.
# Set it before importing PaddleOCR because PaddleX reads it at import time.
os.environ["PADDLE_PDX_CACHE_HOME"] = str(self.model_dir)
try:
# PaddleX checks optional extras through package metadata. A
# frozen bundle has the OCR-core modules but may not expose
# distribution metadata in the normal location. Patch the
# dependency gate before importing PaddleOCR, because the OCR
# pipeline decorator captures this module at import time.
import paddlex.utils.deps as paddlex_deps
paddlex_deps.require_deps = lambda *args, **kwargs: None
paddlex_deps.require_extra = lambda *args, **kwargs: None
original_is_dep_available = paddlex_deps.is_dep_available
paddlex_deps.is_dep_available = lambda dep, /, **kwargs: (
True
if dep
in {
"imagesize",
"opencv-contrib-python",
"pyclipper",
"pypdfium2",
"python-bidi",
"shapely",
}
else original_is_dep_available(dep, **kwargs)
)
paddlex_deps.is_extra_available = lambda *args, **kwargs: True
paddlex_deps.pipeline_requires_extra = lambda *args, **kwargs: (
lambda cls: cls
)
paddlex_deps.EXTRAS = {
"ocr": {},
"ocr-core": {},
}
from paddleocr import PaddleOCR
import pyclipper
processors = importlib.import_module(
"paddlex.inference.models.text_detection.processors"
)
# The detector imports pyclipper conditionally based on
# package metadata; bind it explicitly in every loaded
# module instance used by the frozen pipeline.
processors.pyclipper = pyclipper
sys.modules[processors.__name__].pyclipper = pyclipper
if getattr(sys, "frozen", False):
import paddlex.inference.pipelines.base as pipeline_base
pipeline_base.DependencyError = type(
"DependencyError", (Exception,), {}
)
paddlex_pipeline_base = importlib.import_module(
"paddleocr._pipelines.base"
)
paddlex_pipeline_base.DependencyError = type(
"DependencyError", (Exception,), {}
)
except ImportError as exc:
raise OCRNotAvailable(
"PaddleOCR 未安装,请先安装项目依赖"
) from exc
with self._process_model_lock:
logger.info(
"加载 OCR 引擎: det=%s rec=%s device=%s cpu_threads=%d "
"enable_mkldnn=%s model_dir=%s",
self._det_model_name,
self._rec_model_name,
self.device,
self._cpu_threads,
self._enable_mkldnn,
self.model_dir,
)
self._warn_if_mkldnn_unsupported()
self._engine = PaddleOCR(
**self._model_arguments(),
device=self.device,
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
enable_mkldnn=self._enable_mkldnn,
text_det_limit_side_len=self._text_det_limit_side_len,
text_det_limit_type=self._text_det_limit_type,
text_det_thresh=self._text_det_thresh,
text_det_box_thresh=self._text_det_box_thresh,
text_det_unclip_ratio=self._text_det_unclip_ratio,
text_rec_score_thresh=self._text_rec_score_thresh,
text_recognition_batch_size=self._text_recognition_batch_size,
cpu_threads=self._cpu_threads,
)
self._install_progress_hooks(self._engine)
logger.info("OCR 引擎加载完成")
return self._engine
def _warn_if_mkldnn_unsupported(self) -> None:
"""oneDNN 在部分 PaddlePaddle 版本上不可用,提前给出可读告警。"""
if not self._enable_mkldnn:
return
try:
import paddle
except ImportError:
return
version = getattr(paddle, "__version__", "")
logger.info("PaddlePaddle 版本 %s,oneDNN 已启用", version)
if version.startswith(KNOWN_MKLDNN_BROKEN_PREFIXES):
logger.warning(
"PaddlePaddle %s 在 PIR + oneDNN 组合下有已知缺陷,启用 oneDNN 会导致推理失败"
"(ConvertPirAttribute2RuntimeAttribute not support)。"
"请改用 paddlepaddle 3.2.x,或把 enable_mkldnn 设为 false。",
version,
)
def prepare(self) -> None:
"""Load local models or download only the missing model packages."""
self._get_engine()
def _model_arguments(self) -> dict[str, str]:
arguments: dict[str, str] = {
"text_detection_model_name": self._det_model_name,
"text_recognition_model_name": self._rec_model_name,
}
for argument_name, model_name in (
("text_detection_model_dir", self._det_model_name),
("text_recognition_model_dir", self._rec_model_name),
):
local_path = self.model_dir / "official_models" / model_name
if self._is_complete_model(local_path):
arguments[argument_name] = str(local_path)
return arguments
@classmethod
def _is_complete_model(cls, model_path: Path) -> bool:
return model_path.is_dir() and all(
(model_path / filename).is_file() for filename in cls._MODEL_FILES
)
def _remove_incomplete_models(self) -> None:
for model_name in (self._det_model_name, self._rec_model_name):
model_path = self.model_dir / "official_models" / model_name
if model_path.exists() and not self._is_complete_model(model_path):
shutil.rmtree(model_path)
def _emit_progress(self, percent: int, message: str) -> None:
"""Report monotonic progress; never emits a lower percent than already reached."""
if percent <= self._progress_reached:
return
self._progress_reached = percent
logger.debug("OCR 进度 %3d%% %s", percent, message)
callback = self._progress_callback
if callback is not None:
callback(percent, message)
def _install_progress_hooks(self, engine: Any) -> None:
inner = self._inner_pipeline(engine)
if inner is None:
logger.debug("未找到内部 OCR pipeline,跳过进度挂钩")
return
self._hook_model(inner, "text_det_model", 50, "文字检测完成")
self._hook_model(inner, "text_rec_model", 80, "文字识别完成")
@staticmethod
def _inner_pipeline(engine: Any) -> Any | None:
try:
wrapper = engine.paddlex_pipeline
except AttributeError:
return None
return getattr(wrapper, "_pipeline", None)
def _hook_model(
self, owner: Any, attribute: str, percent: int, message: str
) -> None:
model = getattr(owner, attribute, None)
if model is None or getattr(model, "_ocr_progress_hooked", False):
return
def wrapped(*args: Any, **kwargs: Any) -> Any:
def generate() -> Any:
yield from model(*args, **kwargs)
self._emit_progress(percent, message)
return generate()
wrapped._ocr_progress_hooked = True
setattr(owner, attribute, wrapped)
def recognize(
self,
image_path: Path,
on_progress: ProgressCallback | None = None,
) -> list[dict[str, Any]]:
with self._inference_lock:
self._progress_callback = on_progress
self._progress_reached = 0
self._emit_progress(5, "开始推理")
engine = self._get_engine()
self._emit_progress(10, "模型已就绪")
# Passing an ndarray avoids PaddleX treating Windows paths as URLs.
import numpy as np
from PIL import Image
with Image.open(image_path) as image:
image_array = np.ascontiguousarray(image.convert("RGB"))
self._emit_progress(20, "图片已解码,开始文字检测")
try:
results = engine.predict(input=image_array)
except NotImplementedError as exc:
if self._enable_mkldnn:
import paddle
raise RuntimeError(
"oneDNN 推理失败:当前 PaddlePaddle %s 与 oneDNN 不兼容。"
"请改用 paddlepaddle 3.2.x,或在配置中把 enable_mkldnn 设为 false。"
% getattr(paddle, "__version__", "unknown")
) from exc
raise
lines = self._parse_results(results)
self._emit_progress(80, "文字识别完成")
return lines
def _parse_results(self, results: Any) -> list[dict[str, Any]]:
lines: list[dict[str, Any]] = []
for result in results:
payload = self._result_payload(result)
texts = payload.get("rec_texts", [])
scores = payload.get("rec_scores", [])
boxes = payload.get("rec_polys", payload.get("dt_polys", []))
for index, text in enumerate(texts):
score = float(scores[index]) if index < len(scores) else 0.0
polygon = boxes[index] if index < len(boxes) else []
lines.append(
{
"text": str(text),
"confidence": score,
"polygon": self._to_polygon(polygon),
}
)
return lines
@staticmethod
def _result_payload(result: Any) -> dict[str, Any]:
if isinstance(result, dict):
return result
json_value = getattr(result, "json", None)
if callable(json_value):
json_value = json_value()
if isinstance(json_value, str):
import json
json_value = json.loads(json_value)
if isinstance(json_value, dict):
# PaddleOCR 3.x may wrap the actual result under ``res``.
nested = json_value.get("res")
return nested if isinstance(nested, dict) else json_value
data = getattr(result, "data", None)
return data if isinstance(data, dict) else {}
@staticmethod
def _to_polygon(value: Any) -> list[list[float]]:
try:
return [[float(point[0]), float(point[1])] for point in value]
except (IndexError, TypeError, ValueError):
return []