feat: add return_word_box option and simplify progress checkpoints
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
return_word_box=settings.return_word_box,
|
||||
)
|
||||
|
||||
tasks = OCRTaskQueue(create_ocr, worker_count=settings.ocr_workers)
|
||||
|
||||
@@ -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
|
||||
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
|
||||
|
||||
+67
-14
@@ -49,6 +49,7 @@ class OCRService:
|
||||
text_recognition_batch_size: int = 1,
|
||||
cpu_threads: int | str = 10,
|
||||
enable_mkldnn: bool = False,
|
||||
return_word_box: bool = False,
|
||||
) -> None:
|
||||
self.lang = lang
|
||||
self.device = device
|
||||
@@ -64,6 +65,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._return_word_box = bool(return_word_box)
|
||||
self._engine: Any | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._inference_lock = threading.Lock()
|
||||
@@ -165,6 +167,7 @@ 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 引擎加载完成")
|
||||
@@ -233,8 +236,8 @@ class OCRService:
|
||||
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, "文字识别完成")
|
||||
self._hook_model(inner, "text_det_model", 50, "框识别完成")
|
||||
self._hook_model(inner, "text_rec_model", 80, "文本识别完成")
|
||||
|
||||
@staticmethod
|
||||
def _inner_pipeline(engine: Any) -> Any | None:
|
||||
@@ -269,9 +272,9 @@ class OCRService:
|
||||
with self._inference_lock:
|
||||
self._progress_callback = on_progress
|
||||
self._progress_reached = 0
|
||||
self._emit_progress(5, "开始推理")
|
||||
self._emit_progress(5, "任务开始")
|
||||
engine = self._get_engine()
|
||||
self._emit_progress(10, "模型已就绪")
|
||||
self._emit_progress(10, "模型就绪")
|
||||
|
||||
# Passing an ndarray avoids PaddleX treating Windows paths as URLs.
|
||||
import numpy as np
|
||||
@@ -279,9 +282,12 @@ class OCRService:
|
||||
|
||||
with Image.open(image_path) as image:
|
||||
image_array = np.ascontiguousarray(image.convert("RGB"))
|
||||
self._emit_progress(20, "图片已解码,开始文字检测")
|
||||
self._emit_progress(20, "图片就绪")
|
||||
try:
|
||||
results = engine.predict(input=image_array)
|
||||
results = engine.predict(
|
||||
input=image_array,
|
||||
return_word_box=self._return_word_box,
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
if self._enable_mkldnn:
|
||||
import paddle
|
||||
@@ -293,7 +299,7 @@ class OCRService:
|
||||
) from exc
|
||||
raise
|
||||
lines = self._parse_results(results)
|
||||
self._emit_progress(80, "文字识别完成")
|
||||
self._emit_progress(80, "文本识别完成")
|
||||
return lines
|
||||
|
||||
def _parse_results(self, results: Any) -> list[dict[str, Any]]:
|
||||
@@ -303,18 +309,65 @@ 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 []
|
||||
lines.append(
|
||||
{
|
||||
"text": str(text),
|
||||
"confidence": score,
|
||||
"polygon": self._to_polygon(polygon),
|
||||
}
|
||||
)
|
||||
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)
|
||||
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,6 +51,7 @@ class OCRTextBox(BaseModel):
|
||||
Location: OCRLocation
|
||||
line: int
|
||||
paragraphs: int
|
||||
words: list[list[list[float]]] | None = None
|
||||
|
||||
|
||||
class OCRDocument(BaseModel):
|
||||
|
||||
@@ -135,7 +135,7 @@ class OCRTaskQueue:
|
||||
logger.info(
|
||||
"file_id=%s 开始处理 image=%s", task.file_id, task.image_path.name
|
||||
)
|
||||
report(5, "任务开始,准备推理")
|
||||
report(5, "任务开始")
|
||||
try:
|
||||
recognized = ocr.recognize(task.image_path, on_progress=report)
|
||||
document = self.build_document(recognized)
|
||||
@@ -143,7 +143,7 @@ class OCRTaskQueue:
|
||||
task.result = document
|
||||
task.progress = 100
|
||||
task.status = "completed"
|
||||
logger.info("file_id=%s 进度 100%% 识别完成", task.file_id)
|
||||
logger.info("file_id=%s 进度 100%% 完成", task.file_id)
|
||||
except Exception as exc:
|
||||
logger.exception("file_id=%s OCR 识别失败", task.file_id)
|
||||
with task._lock:
|
||||
@@ -220,6 +220,7 @@ 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)
|
||||
|
||||
Reference in New Issue
Block a user