revert: remove enable_detection and return_word_box options
按需求移除两个开关: - enable_detection:跳过检测直接识别,实测只对单行图有效,多行文档会返回空结果 - return_word_box:字/词级坐标,默认即关闭且开销在噪声内,无实际收益 恢复正常的两段式链路:文本检测 → 文本识别。 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -37,8 +37,6 @@ 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,
|
||||
)
|
||||
|
||||
tasks = OCRTaskQueue(create_ocr, worker_count=settings.ocr_workers)
|
||||
|
||||
@@ -104,8 +104,6 @@ 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: [":", ":"])
|
||||
extract_include_empty: bool = False
|
||||
|
||||
+20
-143
@@ -49,8 +49,6 @@ 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
|
||||
self.device = device
|
||||
@@ -66,8 +64,6 @@ 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()
|
||||
self._inference_lock = threading.Lock()
|
||||
@@ -145,13 +141,12 @@ class OCRService:
|
||||
with self._process_model_lock:
|
||||
logger.info(
|
||||
"加载 OCR 引擎: det=%s rec=%s device=%s cpu_threads=%d "
|
||||
"enable_mkldnn=%s enable_detection=%s model_dir=%s",
|
||||
"enable_mkldnn=%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()
|
||||
@@ -170,7 +165,6 @@ class OCRService:
|
||||
text_rec_score_thresh=self._text_rec_score_thresh,
|
||||
text_recognition_batch_size=self._text_recognition_batch_size,
|
||||
cpu_threads=self._cpu_threads,
|
||||
return_word_box=self._return_word_box,
|
||||
)
|
||||
self._install_progress_hooks(self._engine)
|
||||
logger.info("OCR 引擎加载完成")
|
||||
@@ -286,92 +280,22 @@ class OCRService:
|
||||
with Image.open(image_path) as image:
|
||||
image_array = np.ascontiguousarray(image.convert("RGB"))
|
||||
self._emit_progress(20, "图片就绪")
|
||||
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
|
||||
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)
|
||||
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)
|
||||
)
|
||||
# 没有检测框,但必须给出坐标:文本区域就是整张图。
|
||||
# 否则 build_document 会丢弃无坐标的片段,导致结果里有字却返回空。
|
||||
height, width = int(image_array.shape[0]), int(image_array.shape[1])
|
||||
whole_image = [
|
||||
[0.0, 0.0],
|
||||
[float(width), 0.0],
|
||||
[float(width), float(height)],
|
||||
[0.0, float(height)],
|
||||
]
|
||||
lines = self._parse_recognition_output(outputs, polygon=whole_image)
|
||||
if not lines:
|
||||
logger.warning(
|
||||
"跳过检测后没有识别出任何文字。该模式要求图片本身是单行文本;"
|
||||
"如果是多行图片,请把 enable_detection 改回 true。"
|
||||
)
|
||||
return lines
|
||||
|
||||
@staticmethod
|
||||
def _parse_recognition_output(
|
||||
outputs: Any, polygon: list[list[float]] | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
"""解析识别模型(无检测)的输出。单次输入只会返回一个结果。
|
||||
|
||||
``polygon`` 是无检测模式下的兜底坐标(整张图),缺了它后续 build_document
|
||||
会因为「没有坐标」而丢弃该片段。
|
||||
"""
|
||||
fallback = polygon or []
|
||||
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": list(fallback)}
|
||||
)
|
||||
return lines
|
||||
|
||||
def _parse_results(self, results: Any) -> list[dict[str, Any]]:
|
||||
lines: list[dict[str, Any]] = []
|
||||
for result in results:
|
||||
@@ -379,65 +303,18 @@ class OCRService:
|
||||
texts = payload.get("rec_texts", [])
|
||||
scores = payload.get("rec_scores", [])
|
||||
boxes = payload.get("rec_polys", payload.get("dt_polys", []))
|
||||
word_boxes = payload.get("text_word_boxes", [])
|
||||
word_regions = payload.get("text_word_region", [])
|
||||
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 []
|
||||
item: dict[str, Any] = {
|
||||
"text": str(text),
|
||||
"confidence": score,
|
||||
"polygon": self._to_polygon(polygon),
|
||||
}
|
||||
if self._return_word_box:
|
||||
words = word_boxes[index] if index < len(word_boxes) else []
|
||||
if (words is None or len(words) == 0) and index < len(word_regions):
|
||||
words = word_regions[index]
|
||||
item["words"] = self._to_word_boxes(words)
|
||||
lines.append(item)
|
||||
lines.append(
|
||||
{
|
||||
"text": str(text),
|
||||
"confidence": score,
|
||||
"polygon": self._to_polygon(polygon),
|
||||
}
|
||||
)
|
||||
return lines
|
||||
|
||||
@staticmethod
|
||||
def _to_word_boxes(value: Any) -> list[list[list[float]]]:
|
||||
"""把 Paddle 的字/词框规范成 [word][point][x/y]。
|
||||
|
||||
PaddleOCR 的 ``text_word_boxes`` 返回矩形数组
|
||||
``[xtop, ytop, xbottom, ybottom]``,而 ``text_word_region`` 返回
|
||||
四点 polygon;这里统一成响应中的四点 polygon。
|
||||
"""
|
||||
if value is None:
|
||||
return []
|
||||
result: list[list[list[float]]] = []
|
||||
try:
|
||||
for box in value:
|
||||
numbers = list(box)
|
||||
if len(numbers) == 4 and all(
|
||||
not hasattr(item, "__len__") for item in numbers
|
||||
):
|
||||
left, top, right, bottom = (float(item) for item in numbers)
|
||||
result.append(
|
||||
[[left, top], [right, top], [right, bottom], [left, bottom]]
|
||||
)
|
||||
continue
|
||||
if len(numbers) == 8 and all(
|
||||
not hasattr(item, "__len__") for item in numbers
|
||||
):
|
||||
result.append(
|
||||
[
|
||||
[float(numbers[index]), float(numbers[index + 1])]
|
||||
for index in range(0, 8, 2)
|
||||
]
|
||||
)
|
||||
continue
|
||||
polygon = [
|
||||
[float(point[0]), float(point[1])] for point in numbers
|
||||
]
|
||||
if polygon:
|
||||
result.append(polygon)
|
||||
except (IndexError, TypeError, ValueError):
|
||||
return []
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _result_payload(result: Any) -> dict[str, Any]:
|
||||
if isinstance(result, dict):
|
||||
|
||||
@@ -51,7 +51,6 @@ class OCRTextBox(BaseModel):
|
||||
Location: OCRLocation
|
||||
line: int
|
||||
paragraphs: int
|
||||
words: list[list[list[float]]] | None = None
|
||||
|
||||
|
||||
class OCRDocument(BaseModel):
|
||||
|
||||
@@ -220,7 +220,6 @@ class OCRTaskQueue:
|
||||
),
|
||||
line=line_number,
|
||||
paragraphs=paragraph_number,
|
||||
words=segment.get("words") if segment.get("words") else None,
|
||||
)
|
||||
|
||||
return OCRDocument(text="\n\n".join(paragraph_texts), polygon=polygon)
|
||||
@@ -240,13 +239,8 @@ class OCRTaskQueue:
|
||||
@classmethod
|
||||
def filter_document(cls, document: OCRDocument, min_confidence: float) -> OCRDocument:
|
||||
# The compact response is intentionally rebuilt from its own polygon map.
|
||||
# words 必须一并带上:这个函数在每次 i2t 请求里都会被调用(即使
|
||||
# min_confidence 为 0),漏掉就会让 return_word_box 的结果全部丢失。
|
||||
selected: list[dict[str, Any]] = []
|
||||
for item in document.polygon.values():
|
||||
if item.confidence < min_confidence:
|
||||
continue
|
||||
segment: dict[str, Any] = {
|
||||
selected = [
|
||||
{
|
||||
"text": item.text,
|
||||
"confidence": item.confidence,
|
||||
"polygon": [
|
||||
@@ -256,9 +250,9 @@ class OCRTaskQueue:
|
||||
[item.Location.xtop, item.Location.ybottom],
|
||||
],
|
||||
}
|
||||
if item.words:
|
||||
segment["words"] = item.words
|
||||
selected.append(segment)
|
||||
for item in document.polygon.values()
|
||||
if item.confidence >= min_confidence
|
||||
]
|
||||
return cls.build_document(selected)
|
||||
|
||||
@classmethod
|
||||
|
||||
Reference in New Issue
Block a user