Files
ocr-server/tests/test_queue.py
T
zimoyin 932f1a8b13 fix: give whole-image polygon in skip-detection mode
无检测模式下没有检测框,原先 polygon 为空,build_document 会丢弃无坐标的片段,
导致识别其实成功但响应 segments=0。改为用整张图的矩形作为兜底坐标。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-13 16:03:51 +08:00

249 lines
8.9 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.
from pathlib import Path
from uuid import uuid4
from ocr_server.task_queue import OCRTaskQueue
class FakeOCR:
"""Fake engine that mirrors OCRService.recognize and reports progress."""
def __init__(self) -> None:
self.progress: list[int] = []
def recognize(self, _: Path, on_progress=None) -> list[dict]:
for percent, message in (
(5, "任务开始"),
(10, "模型就绪"),
(20, "图片就绪"),
(50, "框识别完成"),
(80, "文本识别完成"),
):
self.progress.append(percent)
if on_progress is not None:
on_progress(percent, message)
return [
{"text": "Hello", "confidence": 0.95, "polygon": [[0, 0], [40, 0], [40, 10], [0, 10]]},
{"text": "世界", "confidence": 0.85, "polygon": [[45, 0], [85, 0], [85, 10], [45, 10]]},
{"text": "下一行", "confidence": 0.92, "polygon": [[0, 20], [50, 20], [50, 30], [0, 30]]},
]
def test_build_document_groups_segments_into_lines_and_paragraphs() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
assert document.text == "Hello世界\n下一行"
assert list(document.polygon) == ["text1", "text2", "text3"]
assert document.polygon["text1"].line == 1
assert document.polygon["text1"].paragraphs == 1
assert document.polygon["text3"].line == 2
def test_filter_document_rebuilds_groups() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
filtered = OCRTaskQueue.filter_document(document, 0.9)
assert [item.text for item in filtered.polygon.values()] == ["Hello", "下一行"]
assert filtered.text == "Hello\n下一行"
def test_queue_completes_task() -> None:
queue = OCRTaskQueue(lambda: FakeOCR(), worker_count=1)
file_id = uuid4()
task = queue.submit(file_id, Path("sample"))
queue._queue.join()
assert task.status == "completed"
assert task.progress == 100
assert task.ocr_started_at is not None
assert task.ocr_finished_at is not None
assert task.ocr_elapsed_ms is not None
assert queue.snapshot(file_id)[3] is not None
def test_resolve_cpu_threads_supports_max_and_int() -> None:
import os
from ocr_server.config import CPU_THREADS_MAX, resolve_cpu_threads
assert resolve_cpu_threads(4) == 4
assert resolve_cpu_threads("max") == max(1, os.cpu_count() or 1)
assert resolve_cpu_threads("MAX") == max(1, os.cpu_count() or 1)
assert resolve_cpu_threads(CPU_THREADS_MAX) == max(1, os.cpu_count() or 1)
def test_settings_validate_cpu_threads_and_expose_mkldnn() -> None:
import os
import pytest
from ocr_server.config import Settings
assert Settings(cpu_threads=8).cpu_threads_resolved == 8
assert Settings(cpu_threads="max").cpu_threads_resolved == max(1, os.cpu_count() or 1)
assert Settings(enable_mkldnn=True).enable_mkldnn is True
assert Settings(enable_mkldnn=False).enable_mkldnn is False
with pytest.raises(Exception):
Settings(cpu_threads="lots")
with pytest.raises(Exception):
Settings(cpu_threads=0)
def test_ocr_service_resolves_threads_and_stores_mkldnn() -> None:
from ocr_server.ocr import OCRService
service = OCRService(cpu_threads="max", enable_mkldnn=True)
assert service._cpu_threads == max(1, __import__("os").cpu_count() or 1)
assert service._enable_mkldnn is True
plain = OCRService(cpu_threads=3, enable_mkldnn=False)
assert plain._cpu_threads == 3
assert plain._enable_mkldnn is False
def test_build_document_preserves_word_boxes() -> None:
recognized = [
{
"text": "姓名:万镭",
"confidence": 0.99,
"polygon": [[0, 0], [100, 0], [100, 20], [0, 20]],
"words": [
[[0, 0], [50, 0], [50, 20], [0, 20]],
[[50, 0], [100, 0], [100, 20], [50, 20]],
],
}
]
document = OCRTaskQueue.build_document(recognized)
assert document.polygon["text1"].words == recognized[0]["words"]
def test_filter_document_keeps_word_boxes() -> None:
"""i2t 每次都走 filter_document,words 不能被过滤流程丢掉。"""
recognized = [
{
"text": "姓名:万镭",
"confidence": 0.9,
"polygon": [[0, 0], [100, 0], [100, 20], [0, 20]],
"words": [
[[0, 0], [50, 0], [50, 20], [0, 20]],
[[50, 0], [100, 0], [100, 20], [50, 20]],
],
}
]
document = OCRTaskQueue.build_document(recognized)
filtered = OCRTaskQueue.filter_document(document, 0.0)
assert filtered.polygon["text1"].words == recognized[0]["words"]
def test_filter_document_drops_low_confidence_with_words() -> None:
recognized = [
{"text": "保留", "confidence": 0.9, "polygon": [[0, 0], [10, 0], [10, 10], [0, 10]],
"words": [[[0, 0], [10, 0], [10, 10], [0, 10]]]},
{"text": "丢弃", "confidence": 0.2, "polygon": [[0, 20], [10, 20], [10, 30], [0, 30]],
"words": [[[0, 20], [10, 20], [10, 30], [0, 30]]]},
]
document = OCRTaskQueue.build_document(recognized)
filtered = OCRTaskQueue.filter_document(document, 0.5)
assert [item.text for item in filtered.polygon.values()] == ["保留"]
assert filtered.polygon["text1"].words is not None
def test_document_rows_groups_by_coordinates() -> None:
"""行文本按坐标(bbox 纵向重叠)归并,供字段抽取的 row 选项使用。"""
recognized = [
{"text": "检查号", "confidence": 0.9, "polygon": [[0, 0], [40, 0], [40, 10], [0, 10]]},
{"text": "26100830064", "confidence": 0.9, "polygon": [[45, 0], [120, 0], [120, 10], [45, 10]]},
{"text": "姓名", "confidence": 0.9, "polygon": [[0, 20], [40, 20], [40, 30], [0, 30]]},
{"text": "万镭", "confidence": 0.9, "polygon": [[45, 20], [90, 20], [90, 30], [45, 30]]},
]
document = OCRTaskQueue.build_document(recognized)
rows = OCRTaskQueue.document_rows(document)
assert rows == ["检查号26100830064", "姓名万镭"]
def test_document_rows_empty_document() -> None:
document = OCRTaskQueue.build_document([])
assert OCRTaskQueue.document_rows(document) == []
def test_parse_recognition_output_handles_list_and_scalar() -> None:
from ocr_server.ocr import OCRService
listed = OCRService._parse_recognition_output(
[{"rec_text": ["MU2379", "03DEC"], "rec_score": [0.97, 0.95]}]
)
assert [item["text"] for item in listed] == ["MU2379", "03DEC"]
assert listed[0]["confidence"] == 0.97
scalar = OCRService._parse_recognition_output(
[{"rec_text": "MU2379", "rec_score": 0.97}]
)
assert scalar == [{"text": "MU2379", "confidence": 0.97, "polygon": []}]
def test_parse_recognition_output_applies_fallback_polygon() -> None:
"""无检测模式必须带上兜底坐标,否则 build_document 会把片段丢掉。"""
from ocr_server.ocr import OCRService
whole = [[0, 0], [640, 0], [640, 42], [0, 42]]
parsed = OCRService._parse_recognition_output(
[{"rec_text": "MU2379", "rec_score": 0.97}], polygon=whole
)
assert parsed[0]["polygon"] == whole
from ocr_server.task_queue import OCRTaskQueue
document = OCRTaskQueue.build_document(parsed)
assert document.text == "MU2379"
assert len(document.polygon) == 1
assert document.polygon["text1"].text == "MU2379"
def test_parse_recognition_output_with_word_box_tuple() -> None:
from ocr_server.ocr import OCRService
parsed = OCRService._parse_recognition_output(
[{"rec_text": [("MU2379", [[1, 2, 3]])], "rec_score": [0.97]}]
)
assert parsed == [{"text": "MU2379", "confidence": 0.97, "polygon": []}]
def test_parse_recognition_output_skips_empty() -> None:
from ocr_server.ocr import OCRService
assert OCRService._parse_recognition_output([{"rec_text": [""], "rec_score": [0.0]}]) == []
assert OCRService._parse_recognition_output([{"rec_text": [], "rec_score": []}]) == []
assert OCRService._parse_recognition_output([None, "junk"]) == []
def test_enable_detection_defaults_to_true() -> None:
from ocr_server.config import Settings
assert Settings().enable_detection is True
assert Settings(enable_detection=False).enable_detection is False
def test_progress_is_monotonic_and_includes_checkpoints() -> None:
from ocr_server.ocr import OCRService
service = OCRService()
seen: list[int] = []
service._progress_callback = lambda percent, message: seen.append(percent)
service._emit_progress(5, "任务开始")
service._emit_progress(10, "模型就绪")
service._emit_progress(20, "图片就绪")
service._emit_progress(10, "重复的低进度应被忽略")
service._emit_progress(50, "框识别完成")
service._emit_progress(80, "文本识别完成")
service._emit_progress(100, "完成")
assert seen == [5, 10, 20, 50, 80, 100]