"""Benchmark the configured OCR pipeline without modifying model files. 用法: uv run --no-sync python scripts/benchmark_ocr.py # 默认样例图 uv run --no-sync python scripts/benchmark_ocr.py 你的图.png # 指定图片 uv run --no-sync python scripts/benchmark_ocr.py 你的图.png 3 # 跑 3 次,报最快那次 ⚠️ `--no-sync` 不能省:uv run 默认会按 pyproject.toml 同步环境,那里声明的是 CPU 版 paddlepaddle,会把装好的 paddlepaddle-gpu 静默冲掉、退回 CPU——测速结果会失真。 改完 config.yaml 重新执行即可对比。调模型或参数时**重点看 chars**: 速度变快但字符数掉得多,就是丢字了。 """ import sys from pathlib import Path from time import perf_counter from ocr_server.config import Settings from ocr_server.ocr import OCRService def run_once(service: OCRService, image_path: Path) -> tuple[float, int, int, float, float]: marks: list[tuple[int, float]] = [] started = perf_counter() def on_progress(percent: int, message: str) -> None: marks.append((percent, perf_counter() - started)) lines = service.recognize(image_path, on_progress=on_progress) elapsed = perf_counter() - started texts = [item["text"] for item in lines if item.get("text")] detection = next((t for p, t in marks if p == 50), 0.0) recognition = next((t for p, t in marks if p == 80), 0.0) return elapsed, len(texts), sum(len(text) for text in texts), detection, recognition if __name__ == "__main__": image_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path( "http/fixtures/general_ocr_002.png" ) repeats = int(sys.argv[2]) if len(sys.argv) > 2 else 1 settings = Settings() service = OCRService.from_settings(settings) service.prepare() print(f"image={image_path}") print(f"det={settings.det_model_name} rec={settings.rec_model_name}") print(f"device={service._effective_device} (config={settings.device})") print(f"enable_mkldnn={settings.enable_mkldnn} cpu_threads={settings.cpu_threads_resolved}") print(f"text_det_limit_side_len={settings.text_det_limit_side_len} " f"text_recognition_batch_size={settings.text_recognition_batch_size}") results = [run_once(service, image_path) for _ in range(repeats)] # 至少跑一次预热,避免把首次推理的算子编译时间算进去。 if repeats == 1: print("(只跑一次,数值可能含首次推理的预热开销;建议传次数参数多跑几次)") elapsed, segments, chars, detection, recognition = min(results) print(f"elapsed_ms={elapsed * 1000:.2f}") print(f" detect_ms={detection * 1000:.2f}") print(f" recognize_ms={(recognition - detection) * 1000:.2f}") print(f"segments={segments}") print(f"chars={chars}")