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>
This commit is contained in:
+31
-1
@@ -1,18 +1,25 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, File, HTTPException, UploadFile, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ocr_server.config import Settings
|
||||
from ocr_server.fields import build_specs, extract_fields
|
||||
from ocr_server.logging_setup import configure_logging
|
||||
from ocr_server.ocr import OCRService
|
||||
from ocr_server.schemas import ApiResponse, I2TData, I2TRequest
|
||||
from ocr_server.storage import ImageStore, InvalidImage
|
||||
from ocr_server.task_queue import OCRTaskQueue
|
||||
|
||||
logger = logging.getLogger("ocr_server.app")
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
settings = settings or Settings()
|
||||
configure_logging(settings.log_level)
|
||||
store = ImageStore(settings)
|
||||
field_specs = build_specs(settings.extract_fields)
|
||||
field_separators = tuple(settings.extract_separators or (":", ":"))
|
||||
|
||||
def create_ocr() -> OCRService:
|
||||
return OCRService(
|
||||
@@ -28,7 +35,8 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
text_det_unclip_ratio=settings.text_det_unclip_ratio,
|
||||
text_rec_score_thresh=settings.text_rec_score_thresh,
|
||||
text_recognition_batch_size=settings.text_recognition_batch_size,
|
||||
cpu_threads=settings.cpu_threads,
|
||||
cpu_threads=settings.cpu_threads_resolved,
|
||||
enable_mkldnn=settings.enable_mkldnn,
|
||||
)
|
||||
|
||||
tasks = OCRTaskQueue(create_ocr, worker_count=settings.ocr_workers)
|
||||
@@ -116,6 +124,27 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
if result is None:
|
||||
raise HTTPException(status_code=500, detail="OCR 结果为空")
|
||||
filtered = OCRTaskQueue.filter_document(result, request.min_confidence)
|
||||
extracted = (
|
||||
extract_fields(
|
||||
filtered.text,
|
||||
field_specs,
|
||||
field_separators,
|
||||
rows=OCRTaskQueue.document_rows(filtered),
|
||||
include_empty=settings.extract_include_empty,
|
||||
)
|
||||
if field_specs
|
||||
else None
|
||||
)
|
||||
if field_specs:
|
||||
# 默认不打 INFO 级日志:字段值里可能含姓名等敏感信息。
|
||||
# 调 log_level: DEBUG 可以看到抽取明细,便于排查取值错乱。
|
||||
logger.debug(
|
||||
"字段抽取 file_id=%s min_confidence=%.2f 命中=%s 未命中=%s",
|
||||
request.file_id,
|
||||
request.min_confidence,
|
||||
extracted,
|
||||
[spec.name for spec in field_specs if spec.name not in (extracted or {})],
|
||||
)
|
||||
return ApiResponse(
|
||||
data=I2TData(
|
||||
file_id=request.file_id,
|
||||
@@ -125,6 +154,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
ocr_finished_at=ocr_finished_at,
|
||||
ocr_elapsed_ms=ocr_elapsed_ms,
|
||||
result=filtered,
|
||||
fields=extracted,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
CPU_THREADS_MAX = "max"
|
||||
|
||||
|
||||
def _runtime_root() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
@@ -18,6 +22,67 @@ def _runtime_root() -> Path:
|
||||
CONFIG_FILE = _runtime_root() / "config.yaml"
|
||||
|
||||
|
||||
def resolve_cpu_threads(value: int | str) -> int:
|
||||
"""把 cpu_threads 配置解析成具体线程数。
|
||||
|
||||
`max` 表示吃满所有逻辑核心,例如 20 线程机器上解析为 20。
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
if value.strip().lower() != CPU_THREADS_MAX:
|
||||
raise ValueError(f"cpu_threads 必须是正整数或 {CPU_THREADS_MAX}")
|
||||
return max(1, os.cpu_count() or 1)
|
||||
return int(value)
|
||||
|
||||
|
||||
class FieldPreset(BaseModel):
|
||||
"""一个待抽取字段的预设。"""
|
||||
|
||||
name: str
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
|
||||
# 值处理
|
||||
compact: bool = False
|
||||
pattern: str | None = None
|
||||
end_pattern: str | None = None
|
||||
max_length: int | None = None
|
||||
multiline: bool = False
|
||||
|
||||
# 匹配行为
|
||||
occurrence: Literal["first", "last"] = "first"
|
||||
separator_optional: bool = False
|
||||
label_linebreak: bool = False
|
||||
row: int = -1
|
||||
|
||||
@field_validator("pattern", "end_pattern")
|
||||
@classmethod
|
||||
def _validate_regex(cls, value: str | None) -> str | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
re.compile(value)
|
||||
except re.error as exc:
|
||||
raise ValueError(f"正则表达式无效 {value!r}: {exc}") from exc
|
||||
return value
|
||||
|
||||
@field_validator("max_length")
|
||||
@classmethod
|
||||
def _validate_max_length(cls, value: int | None) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
||||
raise ValueError("max_length 必须是 >= 1 的整数")
|
||||
return value
|
||||
|
||||
@field_validator("row")
|
||||
@classmethod
|
||||
def _validate_row(cls, value: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError("row 必须是整数,-1 表示不限定行")
|
||||
if value < -1 or value == 0:
|
||||
raise ValueError("row 必须是 -1(不限定)或 >= 1 的行号")
|
||||
return value
|
||||
|
||||
|
||||
class Settings(BaseModel):
|
||||
host: str = "127.0.0.1"
|
||||
port: int = Field(default=8000, ge=1, le=65535)
|
||||
@@ -37,7 +102,11 @@ class Settings(BaseModel):
|
||||
text_det_unclip_ratio: float = Field(default=1.5, ge=0.1, le=5.0)
|
||||
text_rec_score_thresh: float = Field(default=0.0, ge=0.0, le=1.0)
|
||||
text_recognition_batch_size: int = Field(default=1, ge=1, le=64)
|
||||
cpu_threads: int = Field(default=10, ge=1, le=64)
|
||||
cpu_threads: int | str = 10
|
||||
enable_mkldnn: bool = False
|
||||
extract_fields: list[FieldPreset] = Field(default_factory=list)
|
||||
extract_separators: list[str] = Field(default_factory=lambda: [":", ":"])
|
||||
extract_include_empty: bool = False
|
||||
log_level: str = "INFO"
|
||||
|
||||
def __init__(self, **overrides: Any) -> None:
|
||||
@@ -48,6 +117,24 @@ class Settings(BaseModel):
|
||||
values[name] = path if path.is_absolute() else _runtime_root() / path
|
||||
super().__init__(**values)
|
||||
|
||||
@field_validator("cpu_threads")
|
||||
@classmethod
|
||||
def _validate_cpu_threads(cls, value: Any) -> int | str:
|
||||
if isinstance(value, str):
|
||||
if value.strip().lower() == CPU_THREADS_MAX:
|
||||
return CPU_THREADS_MAX
|
||||
raise ValueError(f"cpu_threads 必须是正整数或 {CPU_THREADS_MAX}")
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"cpu_threads 必须是正整数或 {CPU_THREADS_MAX}")
|
||||
if not 1 <= value <= 256:
|
||||
raise ValueError("cpu_threads 取值范围为 1~256")
|
||||
return value
|
||||
|
||||
@property
|
||||
def cpu_threads_resolved(self) -> int:
|
||||
"""实际传给 Paddle 的线程数;`max` 在这里展开成核心数。"""
|
||||
return resolve_cpu_threads(self.cpu_threads)
|
||||
|
||||
@property
|
||||
def max_upload_bytes(self) -> int:
|
||||
return self.max_upload_mb * 1024 * 1024
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
"""按预设标签从 OCR 文本中抽取结构化字段。
|
||||
|
||||
匹配模型
|
||||
--------
|
||||
一个字段由「标签 + 分隔符 + 值」组成,例如 ``姓名:万镭``。抽取时按下面的顺序
|
||||
确定值的边界:
|
||||
|
||||
1. 下一个**已配置标签**的开始位置(保证同一行的多个字段能互相切分);
|
||||
2. ``end_pattern`` 命中的位置(终止符,不含匹配到的字符);
|
||||
3. 换行(除非 ``multiline`` 为真);
|
||||
4. 文本结尾。
|
||||
|
||||
之后依次应用 ``pattern``(值内容正则,从值起始处匹配,只取匹配部分)、清洗、
|
||||
``max_length`` 截断。
|
||||
|
||||
坐标与行编组
|
||||
------------
|
||||
``row`` 参数支持按「行」限定取值。行是由识别结果的**坐标**算出来的(同一行的
|
||||
文本框纵向重叠,会被分到同一个行号),因此这里的「换行」是真实换行,而不是
|
||||
简单的字符拼接。``row=-1`` 表示不限定行。
|
||||
|
||||
设计要点(来自真实票据/报告的实测需求)
|
||||
----------------------------------------
|
||||
- 标签内部可能有空格:OCR 会把「姓名」识别成「姓 名」,因此标签匹配时允许
|
||||
字符之间插入空白;``label_linebreak`` 打开后还允许最多一个换行。
|
||||
- 同一行可能有多个字段:``检查号:26100830064姓名:万镭`` 需要切成两个字段。
|
||||
- 值需要清洗:去掉零宽字符、首尾空白与残留标点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from typing import NamedTuple, Sequence
|
||||
|
||||
DEFAULT_SEPARATORS = (":", ":")
|
||||
OCCURRENCE_CHOICES = ("first", "last")
|
||||
|
||||
# 标签内部允许的空白与零宽字符(不含换行)
|
||||
_LABEL_GAP = " \t "
|
||||
_LABEL_GAP_RE = re.escape(_LABEL_GAP)
|
||||
_ZERO_WIDTH = "".join(char for char in _LABEL_GAP if char not in " \t ")
|
||||
|
||||
_LEADING_NOISE = re.compile(r"^[\s::、,,\.。]+")
|
||||
_TRAILING_NOISE = re.compile(r"[;;,,、\s]+$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FieldSpec:
|
||||
"""一个待抽取字段的规则。"""
|
||||
|
||||
name: str
|
||||
aliases: tuple[str, ...] = field(default_factory=tuple)
|
||||
|
||||
# 值处理
|
||||
compact: bool = False
|
||||
pattern: str | None = None
|
||||
end_pattern: str | None = None
|
||||
max_length: int | None = None
|
||||
multiline: bool = False
|
||||
|
||||
# 匹配行为
|
||||
occurrence: str = "first"
|
||||
separator_optional: bool = False
|
||||
label_linebreak: bool = False
|
||||
row: int = -1
|
||||
|
||||
_value_re: re.Pattern[str] | None = field(
|
||||
default=None, init=False, repr=False, compare=False
|
||||
)
|
||||
_end_re: re.Pattern[str] | None = field(
|
||||
default=None, init=False, repr=False, compare=False
|
||||
)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.pattern:
|
||||
object.__setattr__(self, "_value_re", re.compile(self.pattern))
|
||||
if self.end_pattern:
|
||||
object.__setattr__(self, "_end_re", re.compile(self.end_pattern))
|
||||
if self.occurrence not in OCCURRENCE_CHOICES:
|
||||
raise ValueError(
|
||||
f"occurrence 只能是 {OCCURRENCE_CHOICES},收到 {self.occurrence!r}"
|
||||
)
|
||||
|
||||
@property
|
||||
def labels(self) -> tuple[str, ...]:
|
||||
"""去重后的标签列表,长标签优先(避免短标签抢先命中)。"""
|
||||
seen: set[str] = set()
|
||||
ordered: list[str] = []
|
||||
for candidate in (self.name, *self.aliases):
|
||||
label = (candidate or "").strip()
|
||||
key = _normalize(label)
|
||||
if label and key not in seen:
|
||||
seen.add(key)
|
||||
ordered.append(label)
|
||||
return tuple(sorted(ordered, key=len, reverse=True))
|
||||
|
||||
|
||||
class _Match(NamedTuple):
|
||||
start: int
|
||||
end: int
|
||||
label: str
|
||||
|
||||
|
||||
def _normalize(text: str) -> str:
|
||||
"""去掉空白(含换行)与零宽字符,用于标签比对。
|
||||
|
||||
必须连换行一起去掉:``label_linebreak`` 打开时,命中的标签文本可能是
|
||||
``'姓\\n名'``,只有归一化后才能和配置里的 ``'姓名'`` 对上。
|
||||
"""
|
||||
for char in _LABEL_GAP + "\r\n":
|
||||
text = text.replace(char, "")
|
||||
return text.casefold()
|
||||
|
||||
|
||||
def _label_pattern(label: str, *, allow_linebreak: bool) -> str:
|
||||
"""把标签编译成正则片段,允许字符之间插入空白(可选一个换行)。"""
|
||||
chars = [re.escape(char) for char in label if _normalize(char)]
|
||||
if not chars:
|
||||
return ""
|
||||
if allow_linebreak:
|
||||
gap = f"[{_LABEL_GAP_RE}]*(?:\\n[{_LABEL_GAP_RE}]*)?"
|
||||
else:
|
||||
gap = f"[{_LABEL_GAP_RE}]*"
|
||||
return gap.join(chars)
|
||||
|
||||
|
||||
def _build_matcher(
|
||||
specs: Sequence[FieldSpec],
|
||||
separators: Sequence[str],
|
||||
*,
|
||||
separator_required: bool,
|
||||
allow_linebreak: bool,
|
||||
) -> re.Pattern[str] | None:
|
||||
"""为同一组开关的字段编译一个匹配器。"""
|
||||
alternatives: list[str] = []
|
||||
for spec in specs:
|
||||
for label in spec.labels:
|
||||
pattern = _label_pattern(label, allow_linebreak=allow_linebreak)
|
||||
if pattern:
|
||||
alternatives.append(pattern)
|
||||
if not alternatives:
|
||||
return None
|
||||
|
||||
separator = "|".join(re.escape(item) for item in separators)
|
||||
body = "(?:" + "|".join(dict.fromkeys(alternatives)) + ")"
|
||||
gap = f"[{_LABEL_GAP_RE}]*"
|
||||
if separator_required:
|
||||
tail = f"{gap}(?:{separator}){gap}"
|
||||
else:
|
||||
tail = f"{gap}(?:(?:{separator}){gap})?"
|
||||
return re.compile(f"(?P<label>{body}){tail}")
|
||||
|
||||
|
||||
def _cut_at_newline(text: str) -> str:
|
||||
for newline in ("\r\n", "\n", "\r"):
|
||||
index = text.find(newline)
|
||||
if index != -1:
|
||||
text = text[:index]
|
||||
return text
|
||||
|
||||
|
||||
def clean_value(value: str, compact: bool = False) -> str:
|
||||
"""清洗字段值:去零宽字符,空白(含换行)归一成单空格,去掉首尾噪声标点。"""
|
||||
for char in _ZERO_WIDTH:
|
||||
value = value.replace(char, "")
|
||||
value = value.replace(" ", " ").replace(" ", " ")
|
||||
value = re.sub(r"\s+", " ", value)
|
||||
value = _LEADING_NOISE.sub("", value)
|
||||
value = _TRAILING_NOISE.sub("", value)
|
||||
value = value.strip()
|
||||
if compact:
|
||||
value = re.sub(r"\s+", "", value)
|
||||
return value
|
||||
|
||||
|
||||
def _extract_value(region: str, spec: FieldSpec) -> str:
|
||||
"""在值区间内按字段规则求值。"""
|
||||
if not spec.multiline:
|
||||
region = _cut_at_newline(region)
|
||||
|
||||
if spec._end_re is not None:
|
||||
found = spec._end_re.search(region)
|
||||
if found:
|
||||
region = region[: found.start()]
|
||||
|
||||
region = region.lstrip(_LABEL_GAP + "\r\n")
|
||||
|
||||
if spec._value_re is not None:
|
||||
found = spec._value_re.match(region)
|
||||
if not found:
|
||||
return ""
|
||||
region = found.group(0)
|
||||
|
||||
value = clean_value(region, compact=spec.compact)
|
||||
if spec.max_length is not None and len(value) > spec.max_length:
|
||||
value = value[: spec.max_length]
|
||||
return value
|
||||
|
||||
|
||||
def _collect_matches(
|
||||
text: str, specs: Sequence[FieldSpec], separators: Sequence[str]
|
||||
) -> list[_Match]:
|
||||
"""收集标签命中并按位置排序,解决不同匹配器之间的重叠。
|
||||
|
||||
字段的 ``separator_optional`` / ``label_linebreak`` 不同,需要分别编译匹配器;
|
||||
重叠时「起点更早」优先,起点相同时「标签更长」优先,与单个匹配器的行为一致。
|
||||
"""
|
||||
groups: dict[tuple[bool, bool], list[FieldSpec]] = defaultdict(list)
|
||||
for spec in specs:
|
||||
groups[(not spec.separator_optional, spec.label_linebreak)].append(spec)
|
||||
|
||||
candidates: list[_Match] = []
|
||||
for (separator_required, allow_linebreak), group in groups.items():
|
||||
matcher = _build_matcher(
|
||||
group,
|
||||
separators,
|
||||
separator_required=separator_required,
|
||||
allow_linebreak=allow_linebreak,
|
||||
)
|
||||
if matcher is None:
|
||||
continue
|
||||
for found in matcher.finditer(text):
|
||||
candidates.append(_Match(found.start(), found.end(), found.group("label")))
|
||||
|
||||
candidates.sort(key=lambda item: (item.start, -(item.end - item.start)))
|
||||
accepted: list[_Match] = []
|
||||
last_end = -1
|
||||
for candidate in candidates:
|
||||
if candidate.start < last_end:
|
||||
continue
|
||||
accepted.append(candidate)
|
||||
last_end = candidate.end
|
||||
return accepted
|
||||
|
||||
|
||||
def _extract_from(
|
||||
text: str, specs: Sequence[FieldSpec], separators: Sequence[str]
|
||||
) -> dict[str, str]:
|
||||
"""在给定文本(整篇或某一行)上抽取字段。"""
|
||||
if not text or not specs:
|
||||
return {}
|
||||
|
||||
matches = _collect_matches(text, specs, separators)
|
||||
if not matches:
|
||||
return {}
|
||||
|
||||
lookup: dict[str, FieldSpec] = {}
|
||||
for spec in specs:
|
||||
for label in spec.labels:
|
||||
lookup.setdefault(_normalize(label), spec)
|
||||
|
||||
results: dict[str, str] = {}
|
||||
total = len(matches)
|
||||
for index, match in enumerate(matches):
|
||||
spec = lookup.get(_normalize(match.label))
|
||||
if spec is None:
|
||||
continue
|
||||
# occurrence=first 保留首次命中的值;last 用后续命中覆盖
|
||||
if spec.occurrence == "first" and spec.name in results:
|
||||
continue
|
||||
end = matches[index + 1].start if index + 1 < total else len(text)
|
||||
value = _extract_value(text[match.end : end], spec)
|
||||
if value:
|
||||
results[spec.name] = value
|
||||
return results
|
||||
|
||||
|
||||
def extract_fields(
|
||||
text: str,
|
||||
specs: Sequence[FieldSpec],
|
||||
separators: Sequence[str] = DEFAULT_SEPARATORS,
|
||||
*,
|
||||
rows: Sequence[str] | None = None,
|
||||
include_empty: bool = False,
|
||||
) -> dict[str, str]:
|
||||
"""抽取字段。
|
||||
|
||||
Args:
|
||||
text: 整篇识别文本。
|
||||
specs: 字段规则。
|
||||
separators: 标签与值之间的分隔符。
|
||||
rows: 由坐标算出的行文本(每行一个字符串)。字段设置了 ``row`` 时只用它定位。
|
||||
include_empty: 为真时,未命中的字段返回空串,便于调用方用固定 schema 消费。
|
||||
"""
|
||||
if not specs:
|
||||
return {}
|
||||
|
||||
results: dict[str, str] = {}
|
||||
row_specs: dict[int, list[FieldSpec]] = defaultdict(list)
|
||||
free_specs: list[FieldSpec] = []
|
||||
for spec in specs:
|
||||
if spec.row and spec.row > 0:
|
||||
row_specs[spec.row].append(spec)
|
||||
else:
|
||||
free_specs.append(spec)
|
||||
|
||||
if free_specs:
|
||||
results.update(_extract_from(text, free_specs, separators))
|
||||
|
||||
for row_index, group in row_specs.items():
|
||||
if not rows or row_index > len(rows):
|
||||
continue
|
||||
results.update(_extract_from(rows[row_index - 1], group, separators))
|
||||
|
||||
if include_empty:
|
||||
for spec in specs:
|
||||
results.setdefault(spec.name, "")
|
||||
return results
|
||||
|
||||
|
||||
def build_specs(items: Sequence[object]) -> list[FieldSpec]:
|
||||
"""把配置项转成 FieldSpec,并做启动期校验。
|
||||
|
||||
校验在服务启动时执行,避免配置错误拖到请求时才暴露:
|
||||
|
||||
- 字段名重复:后一个会覆盖前一个;
|
||||
- 标签被多个字段共用:同一标签被两个字段争抢,必然取错;
|
||||
- 正则语法、max_length、occurrence、row 的取值合法性。
|
||||
"""
|
||||
specs: list[FieldSpec] = []
|
||||
for item in items:
|
||||
name = getattr(item, "name", None)
|
||||
if not name:
|
||||
continue
|
||||
specs.append(
|
||||
FieldSpec(
|
||||
name=str(name),
|
||||
aliases=tuple(str(a) for a in getattr(item, "aliases", ()) or ()),
|
||||
compact=bool(getattr(item, "compact", False)),
|
||||
pattern=getattr(item, "pattern", None) or None,
|
||||
end_pattern=getattr(item, "end_pattern", None) or None,
|
||||
max_length=getattr(item, "max_length", None) or None,
|
||||
multiline=bool(getattr(item, "multiline", False)),
|
||||
occurrence=str(getattr(item, "occurrence", "first") or "first"),
|
||||
separator_optional=bool(
|
||||
getattr(item, "separator_optional", False)
|
||||
),
|
||||
label_linebreak=bool(getattr(item, "label_linebreak", False)),
|
||||
row=int(getattr(item, "row", -1) or -1),
|
||||
)
|
||||
)
|
||||
|
||||
names: set[str] = set()
|
||||
label_owner: dict[str, str] = {}
|
||||
for spec in specs:
|
||||
if spec.name in names:
|
||||
raise ValueError(f"extract_fields 中存在重复的字段名:{spec.name!r}")
|
||||
names.add(spec.name)
|
||||
for label in spec.labels:
|
||||
key = _normalize(label)
|
||||
owner = label_owner.get(key)
|
||||
if owner is not None and owner != spec.name:
|
||||
raise ValueError(
|
||||
f"标签 {label!r} 同时被字段 {owner!r} 和 {spec.name!r} 使用,"
|
||||
f"会导致取值错乱,请把其中一个改为 aliases 或使用更精确的标签"
|
||||
)
|
||||
label_owner[key] = spec.name
|
||||
return specs
|
||||
@@ -12,17 +12,34 @@ LOG_LEVELS = {
|
||||
"DEBUG": logging.DEBUG,
|
||||
}
|
||||
|
||||
APP_LOGGER_NAME = "ocr_server"
|
||||
|
||||
|
||||
def resolve_level(name: str) -> int:
|
||||
return LOG_LEVELS.get(str(name).upper(), logging.INFO)
|
||||
|
||||
|
||||
def configure_logging(level: str | int = "INFO") -> None:
|
||||
"""Configure plain newline-terminated logs (never carriage-return progress bars)."""
|
||||
"""配置普通换行日志(不使用 \\r 覆盖式进度条)。
|
||||
|
||||
处理器挂在 `ocr_server` 这个 logger 上,而不是 root,并显式设定级别、
|
||||
关闭向 root 传播。原因:Paddle 在初始化推理引擎时会把 root logger 的
|
||||
级别改成 WARNING,导致其后所有 INFO 日志被静默过滤(实测会造成进度
|
||||
日志从「加载引擎」之后整段消失)。挂在自己的 logger 上就不受这个影响。
|
||||
"""
|
||||
resolved = resolve_level(level) if isinstance(level, str) else level
|
||||
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(LOG_FORMAT, DATE_FORMAT))
|
||||
handler.terminator = "\n"
|
||||
handler.setLevel(resolved)
|
||||
|
||||
app_logger = logging.getLogger(APP_LOGGER_NAME)
|
||||
app_logger.setLevel(resolved)
|
||||
app_logger.handlers = [handler]
|
||||
app_logger.propagate = False
|
||||
|
||||
# root 也配置一份,便于第三方库日志;Paddle 可能改写它,因此不影响上面的应用日志。
|
||||
root = logging.getLogger()
|
||||
root.setLevel(resolved)
|
||||
root.handlers = [handler]
|
||||
|
||||
+45
-5
@@ -7,10 +7,16 @@ 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
|
||||
@@ -41,7 +47,8 @@ class OCRService:
|
||||
text_det_unclip_ratio: float = 1.5,
|
||||
text_rec_score_thresh: float = 0.0,
|
||||
text_recognition_batch_size: int = 1,
|
||||
cpu_threads: int = 10,
|
||||
cpu_threads: int | str = 10,
|
||||
enable_mkldnn: bool = False,
|
||||
) -> None:
|
||||
self.lang = lang
|
||||
self.device = device
|
||||
@@ -55,7 +62,8 @@ class OCRService:
|
||||
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 = cpu_threads
|
||||
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()
|
||||
@@ -132,20 +140,23 @@ class OCRService:
|
||||
) from exc
|
||||
with self._process_model_lock:
|
||||
logger.info(
|
||||
"加载 OCR 引擎: det=%s rec=%s device=%s cpu_threads=%d model_dir=%s",
|
||||
"加载 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=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,
|
||||
@@ -159,6 +170,24 @@ class OCRService:
|
||||
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()
|
||||
@@ -251,7 +280,18 @@ class OCRService:
|
||||
with Image.open(image_path) as image:
|
||||
image_array = np.ascontiguousarray(image.convert("RGB"))
|
||||
self._emit_progress(20, "图片已解码,开始文字检测")
|
||||
results = engine.predict(input=image_array)
|
||||
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
|
||||
|
||||
@@ -67,4 +67,5 @@ class I2TData(BaseModel):
|
||||
ocr_finished_at: datetime | None = None
|
||||
ocr_elapsed_ms: float | None = None
|
||||
result: OCRDocument | None = None
|
||||
fields: dict[str, str] | None = None
|
||||
error: str | None = None
|
||||
|
||||
@@ -224,6 +224,18 @@ class OCRTaskQueue:
|
||||
|
||||
return OCRDocument(text="\n\n".join(paragraph_texts), polygon=polygon)
|
||||
|
||||
@classmethod
|
||||
def document_rows(cls, document: OCRDocument) -> list[str]:
|
||||
"""把识别结果按行归并成文本行列表。
|
||||
|
||||
行号来自坐标分组(bbox 纵向重叠的文本框属于同一行),因此这里的「行」
|
||||
是真实的视觉行,不是简单的字符拼接结果。供字段抽取的 row 选项使用。
|
||||
"""
|
||||
grouped: dict[int, list[dict[str, Any]]] = {}
|
||||
for item in document.polygon.values():
|
||||
grouped.setdefault(item.line, []).append({"text": item.text})
|
||||
return [cls._join_text(grouped[key]) for key in sorted(grouped)]
|
||||
|
||||
@classmethod
|
||||
def filter_document(cls, document: OCRDocument, min_confidence: float) -> OCRDocument:
|
||||
# The compact response is intentionally rebuilt from its own polygon map.
|
||||
|
||||
Reference in New Issue
Block a user