feat: add enable_detection switch to skip text detection

enable_detection: false 跳过检测模型,直接把整图当一行文本送识别。
实测:单行图可正确识别;多行整图因识别模型固定缩放到高 48px 会返回空结果,已加告警。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
zimoyin
2026-10-13 15:59:25 +08:00
parent 6821d0d137
commit a7d4ff6454
8 changed files with 162 additions and 16 deletions
+1
View File
@@ -37,6 +37,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
text_recognition_batch_size=settings.text_recognition_batch_size,
cpu_threads=settings.cpu_threads_resolved,
enable_mkldnn=settings.enable_mkldnn,
enable_detection=settings.enable_detection,
return_word_box=settings.return_word_box,
)
+1
View File
@@ -104,6 +104,7 @@ class Settings(BaseModel):
text_recognition_batch_size: int = Field(default=1, ge=1, le=64)
cpu_threads: int | str = 10
enable_mkldnn: bool = False
enable_detection: bool = True
return_word_box: bool = False
extract_fields: list[FieldPreset] = Field(default_factory=list)
extract_separators: list[str] = Field(default_factory=lambda: [":", ":"])
+68 -16
View File
@@ -49,6 +49,7 @@ class OCRService:
text_recognition_batch_size: int = 1,
cpu_threads: int | str = 10,
enable_mkldnn: bool = False,
enable_detection: bool = True,
return_word_box: bool = False,
) -> None:
self.lang = lang
@@ -65,6 +66,7 @@ class OCRService:
self._text_recognition_batch_size = text_recognition_batch_size
self._cpu_threads = resolve_cpu_threads(cpu_threads)
self._enable_mkldnn = bool(enable_mkldnn)
self._enable_detection = bool(enable_detection)
self._return_word_box = bool(return_word_box)
self._engine: Any | None = None
self._lock = threading.Lock()
@@ -143,12 +145,13 @@ class OCRService:
with self._process_model_lock:
logger.info(
"加载 OCR 引擎: det=%s rec=%s device=%s cpu_threads=%d "
"enable_mkldnn=%s model_dir=%s",
"enable_mkldnn=%s enable_detection=%s model_dir=%s",
self._det_model_name,
self._rec_model_name,
self.device,
self._cpu_threads,
self._enable_mkldnn,
self._enable_detection,
self.model_dir,
)
self._warn_if_mkldnn_unsupported()
@@ -283,25 +286,74 @@ class OCRService:
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,
return_word_box=self._return_word_box,
)
except NotImplementedError as exc:
if self._enable_mkldnn:
import paddle
if not self._enable_detection:
lines = self._recognize_directly(engine, image_array)
else:
try:
results = engine.predict(
input=image_array,
return_word_box=self._return_word_box,
)
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)
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 _recognize_directly(
self, engine: Any, image_array: Any
) -> list[dict[str, Any]]:
"""跳过文本框检测,直接把整张图当作一行文本送识别模型。
⚠️ 识别模型会把输入统一缩放到高约 48px。整张多行图会被压扁、读不出内容,
因此该模式**只适用于本身就是单行文本的图片**。检测关闭后,
``text_det_limit_side_len`` 等检测参数不再生效。
"""
inner = self._inner_pipeline(engine)
if inner is None or not hasattr(inner, "text_rec_model"):
raise OCRNotAvailable("当前 OCR 引擎不支持跳过检测的识别模式")
self._emit_progress(50, "跳过框识别")
outputs = list(
inner.text_rec_model([image_array], return_word_box=self._return_word_box)
)
lines = self._parse_recognition_output(outputs)
if not lines:
logger.warning(
"跳过检测后没有识别出任何文字。该模式要求图片本身是单行文本;"
"如果是多行图片,请把 enable_detection 改回 true。"
)
return lines
@staticmethod
def _parse_recognition_output(outputs: Any) -> list[dict[str, Any]]:
"""解析识别模型(无检测)的输出。单次输入只会返回一个结果。"""
lines: list[dict[str, Any]] = []
for output in outputs:
if not isinstance(output, dict):
continue
texts = output.get("rec_text") or []
scores = output.get("rec_score") or []
if not isinstance(texts, (list, tuple)):
texts = [texts]
if not isinstance(scores, (list, tuple)):
scores = [scores]
for index, text in enumerate(texts):
# return_word_box 打开时识别结果是 (文本, 附加信息) 元组
value = text[0] if isinstance(text, (list, tuple)) and text else text
if not value:
continue
score = float(scores[index]) if index < len(scores) else 0.0
lines.append({"text": str(value), "confidence": score, "polygon": []})
return lines
def _parse_results(self, results: Any) -> list[dict[str, Any]]:
lines: list[dict[str, Any]] = []
for result in results: