Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
refactor: remove OpenCV from base dependencies
myhlolie6d89a6af4d0
diff --git a/.github/workflows/docvortex-boundary.yml b/.github/workflows/docvortex-boundary.ymlindex 3c25c54b..75bbf3b2 100644--- a/.github/workflows/docvortex-boundary.yml+++ b/.github/workflows/docvortex-boundary.yml@@ -259,6 +259,7 @@ jobs:tests/unittest/test_pdf_window_snapshots.py \tests/unittest/test_native_span_assignment.py \tests/unittest/test_flash_pdf_render_scheduling.py \+ tests/unittest/test_opencv_boundaries.py \tests/unittest/test_process_heap_memory.py- name: Retain exact wheel and installation evidenceif: ${{ always() }}diff --git a/docs/next/opencv-loading.md b/docs/next/opencv-loading.mdnew file mode 100644index 00000000..4441771c--- /dev/null+++ b/docs/next/opencv-loading.md@@ -0,0 +1,137 @@+# OpenCV 按需加载与使用验收++2026-10-08。第二轮已从 MinerU 基础直接依赖中移除 OpenCV;下方第一轮章节保留此前按需加载阶段的历史记录。++## 第二轮:基础依赖移除++`project.dependencies` 不再包含任何 OpenCV 包。基础 ONNX 和 llama.cpp 推理、Torch/full extras、+以及 macOS Apple Silicon 自动选择 Torch extra 的声明保持原样;这些 extra 或其他依赖自行引入+OpenCV 的安装行为不在本轮清理范围。++MinerU 的常规 Torch/ONNX 预处理、OCR、公式、表格和印章 Homography 已通过+`docvortex.image` 公共接口使用共享数值内核。通用算法属于 DocVortex,模型阈值、排序和规则+继续属于 MinerU。解码、缩放、灰度、透视/仿射、轮廓、最小矩形、连通域、形态学、+多边形和推理抗锯齿线均不根据 cv2 是否安装更换算法。诊断图像使用 Pillow。++剩余四处直接调用仅限 `CurveTextRectifier.spatial_transform` 与 `calibrate` 两个旧相机标定方法,+使用函数内按需导入;它们不在产品印章 Homography 的实际调用链中。静态测试白名单限定到方法,+不放宽整个模块。公共 Parser、档位、参数、schema 2.0、旧持久缓存边界及九种渲染契约保持原样。++本轮需要新增公共图像接口,MinerU 的 DocVortex 最低版本提高为 `>=0.5.12,<1`。配套源码位于+`/Users/myhloli/.codex-workspaces/worktrees/docvortex-opencv-free-20261008/docvortex`;这是从已发布+0.5.11 建立的独立工作树,实现和验收期间原 main 未修改。验收后的双仓库改动现已分别+提交并合并到本地 MinerU dev、DocVortex main;0.5.12 和私有原生协议 32 是本地候选,尚未发布。+直接从索引安装此 checkout 前,应先发布或本地安装配套 DocVortex;当前指定环境已安装配套轮子。++| 验收 | 结果 |+| --- | --- |+| MinerU 完整测试 | 3010 passed、4 skipped;62 条既有第三方警告 |+| DocVortex 完整 Python 测试 | 9642 passed、14 skipped;6 条既有警告 |+| Rust workspace | 16 项通过;Clippy 检查通过 |+| 新公共图像接口 | 65 组独立 OpenCV 冻结数值样本,两后端验证;包含宽图分块舍入和边界粗线 |+| 真实 Torch、ONNX | 模型输入张量摘要、中间协议和九种输出相同;候选阻断 cv2 |+| 真实表格、Flash OCR、GGUF standard/advanced | 相同的实际产物和已采集输入摘要;候选阻断 cv2 |+| Python 参考后端 + 实际 ONNX | 输入张量、中间协议和九种输出相同;未加载 cv2 |+| Wheel 元数据 | MinerU 无 OpenCV 直接声明,ONNX/llama.cpp 仍在基础依赖 |+| 视觉复核 | 源 PDF 及前后导出页 5–6 已查看,无新增视觉差异;既有竖排表格导出版式局限未改动 |++数值校准专门覆盖 float32 灰度的向量/尾部舍入、三次采样计算精度、宽图通道块步长,以及+小型矩阵主元消元的融合乘加。这些差分在最终模型输入验证前完成修正。普通测试不要求 OpenCV:+新数值参考冻结为 fixture,历史运行时 OpenCV 对照通过 `importorskip` 运行。++原始证据为 `/tmp/mineru-opencv-free-20261008`:`identity.json`、`mineru-baseline/` 和+`baseline-site/` 冻结第一轮完成状态及 DocVortex 0.5.11;`acceptance.json` 保存七条验收比较;+`real-*/` 保存协议、九种输出、实际输入和后端信息;`production-opencv-audit.json` 保存白名单审计;+`wheel-metadata.json` 保存构建轮子依赖;`performance-summary.json` 与 `performance/` 保存成对计时。+`mineru-complete.patch`、`docvortex-complete.patch` 包含新增文件,配套轮子位于 `wheels/`。++每条路径使用五对交替运行的独立进程,首份后重新解析三次作为稳态样本。+计时包含实际解析,九种渲染与输入摘要在计时外;不复用解析结果,模型缓存按产品正常方式复用。+默认 Rust 后端的实际扩展路径与摘要写入记录,候选进程阻断 cv2。++| 路径(稳态中位数) | 第一轮完成状态 + DocVortex 0.5.11 | 本轮候选 | 变化 |+| --- | ---: | ---: | ---: |+| Flash txt | 0.2210 s | 0.2203 s | -0.31% |+| 基础 ONNX OCR | 3.8631 s | 4.0019 s | +3.59% |+| 基础 Torch OCR | 3.2700 s | 3.3559 s | +2.62% |+| ONNX 表格页 | 5.3238 s | 5.4964 s | +3.24% |++四条路径满足 <=5% 的稳态回归门槛,所有配对协议和九种产物相同。第一次表格轮次为 +5.13%,+因此继续优化大型连通区域:float32 坐标以连续字节传入 Rust,避免逐点创建 Python float/list;+凸包排序仍按完整坐标和原始索引裁决。241 项相关数值及私有接口测试、Clippy 通过后,+重测五对表格得到 +3.24%。失败轮次与修正后原始数据均保留,不混合两轮样本。++首次解析中位数变化分别为 Flash -0.50%、ONNX +0.36%、Torch +0.61%、表格 +1.31%。+这些结果仅针对本机样本和环境,不修改 README 的性能承诺;远端跨平台 CI 尚未执行。++原始证据归档到 [output/opencv-free-20261008/evidence.tar.gz](../../output/opencv-free-20261008/evidence.tar.gz),+完整双仓库补丁和本地配套轮子一并保存,SHA-256 位于同目录 evidence.sha256。+归档保留分支整合前的验收快照。当前源码已提交并合并到本地 dev/main,未推送或发布。+++## 第一轮记录++## 实现边界++Flash txt / auto→txt 在分类后直接进入 DocVortex 原生解析与按需补图,PDF 编排不再提前导入 Hybrid、OCR、表格和公式阶段。模型类型只在 TYPE_CHECKING 中导入,模型工厂仅导入当前需要的实现。混合用途模块中的 OpenCV 内核通过函数内普通导入加载;示例读图与调试绘图同样只在执行时导入。++后端文本回填、OCR、公式和表格,以及模型输入适配中的 RGB/BGR 交换改为 NumPy。三/四通道转换忽略 alpha,灰度输入复制为三通道,支持 uint8、uint16、float32,输出保持独立连续数组。模型侧仅新增 `model.ocr.image.rgb_to_bgr` 辅助函数;公共 Parser、分析接口、产品参数和文档协议保持原样。++方向评分的直角旋转、split/merge、既有 alpha 浮点合成、公式掩码裁边和 UniMERNet 零填充使用 NumPy。UNet 仍原位交换通道,保留随后 OpenCV 浮点减乘的原计算顺序。单通道 HWC 裁边和缩放后维度有专门回归断言。++保留的内核包括:图像解码、整数/浮点灰度转换、LINEAR/CUBIC 等缩放、透视/仿射变换、轮廓/连通域/形态学、印章矫正、表格 alpha 路径中的位运算与饱和加法,以及调试绘图。这些操作没有改动插值、边界、阈值或模型配置。high/xhigh 即使使用远程 VLM,仍可能因本地小模型加载 OpenCV。++静态 AST 审计的直接 `cv2.*()` 调用由 152 处降至 112 处,涉及文件由 26 个降至 19 个;顶层 `import cv2` 由 26 个降至 0。计数包含可选模型和调试代码,不代表单次解析调用次数。++## 验证++新增 `tests/unittest/test_opencv_boundaries.py`,现有 `docvortex-boundary` CI 矩阵纳入该文件。测试以独立进程阻断 cv2,避免测试顺序或已加载模块掩盖泄漏。++- 实际 Flash txt / auto→txt,同步与异步入口、非连续选页、含图补图、九种渲染和结果包保存均未加载 cv2,也未加载 Hybrid 模型管理器。+- 109 项现有非 PDF 原生回归在阻断 cv2 的进程中通过,包括 Office、EPUB、HTML、OFD、CSV 和 RTF 等现有格式路径。+- 31 项新增边界和像素测试通过:通道/位深/非连续数组、alpha 截断、旋转与所有权、透视内核、公式灰度与裁边、表格分类张量、UNet 输入和 UniMERNet 单通道填充。Torch 专属处理器测试在无 Torch 的 CI 环境跳过。+- 最终普通宿主回归 **3007 passed、4 skipped**,修改前基线独立复跑为 2976 passed、4 skipped;执行范围为 `tests/unittest -m 'not remote and not full_stack'`。真实本地模型另行对照,不替换推理结果。+- 最后完整回归含两条 Gradio 页范围测试期间的 BaseEventLoop 析构告警;该文件以 PytestUnraisableExceptionWarning 作为错误复跑,59 passed、3 skipped,未复现。记录保留,不修改或过滤该 Gradio 告警。+- 新增测试和验收脚本通过完整 Ruff lint/format;已修改旧文件相对基线没有新增 Ruff finding,旧文件已有 488 项 lint finding 保持原样。`git diff --check` 通过。++真实模型对照固定同一环境、模型文件和输入,对照两侧的完整 ModelJson、MiddleJson、九种输出与采集到的模型调用输入摘要:++| 路径 | 实际输入与后端 | 结果 |+| --- | --- | --- |+| basic / txt | demo2 第 1–2 页;ONNX 小模型 | 四类比较全部一致 |+| basic / txt | demo2 第 1–2 页;Torch CPU 小模型 | 四类比较全部一致 |+| standard / txt | demo2 第 1–2 页;ONNX + 本地 GGUF VLM | 四类比较全部一致 |+| advanced / txt | demo2 第 1–2 页;ONNX + 本地 GGUF 两阶段 VLM | 四类比较全部一致 |+| basic / txt 表格 | demo1 第 5–6 页;实际分类、SLANet、UNet | 四类比较全部一致 |+| Flash / ocr | demo1 第 5–6 页;方向 det/rec、OCR det/rec、表格投影 | 四类比较全部一致 |++ModelJson/MiddleJson 按完整 JSON 比较,包含内嵌素材;文本和结构输出按内容摘要比较。DOCX/EPUB 比较每个 ZIP 成员的解压内容,只归一化核心元数据中明确的创建时间。PDF 比较每页实际渲染像素,避免 PDF 时间字段影响结论。代表性正文/公式/彩色图和旋转表格源页与导出页已视觉检查;候选与基线相同,不据此扩大已有 OCR 精度承诺。++## 性能++macOS / arm64,Python 3.14.4,DocVortex 0.5.11,OpenCV 5.0.0.93;两侧使用同一安装环境,仅隔离 MinerU 源码。五对独立进程,轮换先后顺序,每进程首先转换一份三页含图 PDF,然后再真正解析十次。每轮通过公开 PdfModel.predict 记录 11 次实际原生入口调用、33 页请求,全部协议、渲染和素材比较一致。基线加载 cv2,候选全程未加载。++| 指标,中位数 | 基线 | 候选 | 变化 |+| --- | ---: | ---: | ---: |+| 准备模块和公开 PDF 接口 | 0.1933 秒 | 0.1926 秒 | 约持平 |+| 首份三页含图 parse,含延迟导入与补图 | 0.4081 秒 | 0.3066 秒 | -24.87% |+| 十次完整解析,共 30 页 | 0.1825 秒 | 0.1884 秒 | +3.26% |++稳态比例 1.0326,满足 ≤1.05 门槛。计时不含九种 renderer 和文件摘要;首份 parser 返回的协议与素材在计时内。准备模块包括解释器启动后脚本初始化和公开接口加载,不等于解释器启动耗时。两者相加的同进程中位数为 0.6014 → 0.4992 秒(-17.00%)。先前使用引擎诊断计数的五对实验每轮实测新增 33 次原生文本快照,记录另存 performance-summary-native-counter.json;正式交付脚本只依赖公开接口。未清空 OS 缓存或使用新安装位置,因此本表不是冷盘/首次安装结果,也不沿用 DocVortex 旧实验的 78% 收益。此处只报告该 Flash 样本的性能,模型对照的墙钟不用于吞吐结论。++## 复跑与证据++使用指定环境 `/Users/myhloli/projects/20240809magic_pdf/Magic-PDF/.venv4`。本轮对齐 DocVortex 0.5.11、mineru-vl-utils 2.0.5,并补装 pytest-cov;未删除 OpenCV。验证脚本 `tests/benchmarks/opencv_paths.py` 支持隔离源码、txt/ocr、档位、Torch/ONNX、选页及重复次数,并记录源文件摘要、加载状态、原生调用/页请求数、环境和产物。++```sh+.venv4/bin/python -m pytest tests/unittest -o addopts='' -q -m 'not remote and not full_stack'+.venv4/bin/python -m pytest tests/unittest/test_opencv_boundaries.py -o addopts='' -q+.venv4/bin/python tests/benchmarks/opencv_paths.py \+ --root /path/to/checkout --out /tmp/opencv-check \+ --tier basic --small-backend onnx --mode txt \+ --source demo/pdfs/demo1.pdf --pages 5-6+```++原始证据位于本机 `/tmp/mineru-opencv-20261008`:`identity.json` / `baseline.tar` 冻结修改前源码;`acceptance.json` 汇总比较;`real-*/` 保存真实模型产物和输入摘要;`performance-summary.json` / `performance-pairs.log` / `performance/` 保存五对时间和输出;`audit.json` 保存直接调用审计;`pixel-tests-final2.log` / `nonpdf-blocked.log` / `full-delivery.log` / `baseline-full.log` / `gradio-warning-replay.log` 保存测试;`lint-difference.json` 保存 lint 基线差分。原始记录已归档到 [output/opencv-20261008/evidence.tar.gz](../../output/opencv-20261008/evidence.tar.gz),SHA-256 位于同目录 evidence.sha256;归档含修改前源码 tar 和所有原始比较/计时记录。++远端跨平台 CI 尚未执行;此次没有提交、推送或发布。diff --git a/mineru/backend/analysis/pdf/formulas.py b/mineru/backend/analysis/pdf/formulas.pyindex 4f939751..9d70b5d9 100644--- a/mineru/backend/analysis/pdf/formulas.py+++ b/mineru/backend/analysis/pdf/formulas.py@@ -4,9 +4,8 @@from __future__ import annotationsimport math-from typing import Any+from typing import TYPE_CHECKING, Any-import cv2import numpy as npfrom docvortex.assets import image_size as _normalize_page_sizefrom docvortex.content.text import build_tagged_formula_content@@ -14,11 +13,13 @@ from docvortex.geometry import bbox_to_quad as _medium_bbox_to_quadfrom docvortex.geometry import normalize_to_int_bboxfrom PIL import Image-from ....model.ocr.image import get_rotate_crop_image_for_text_rec-from ....model.runtime.hybrid import HybridLocalModelContext+from ....model.ocr.image import get_rotate_crop_image_for_text_rec, rgb_to_bgrfrom ....types import RAW_FORMULA_NUMBER, BlockTypefrom .model_inputs import _bbox_to_pixel_bbox, _normalize_layout_bbox_to_unit, _normalize_medium_content+if TYPE_CHECKING:+ from ....model.runtime.hybrid import HybridLocalModelContext+def _is_hybrid_equation_block(block: dict[str, Any]) -> bool:"""判断 raw Hybrid/VLM block 是否表示可合并编号的行间公式。"""@@ -189,7 +190,7 @@ def _apply_medium_formula_number_ocr(formula_number_crops: list[np.ndarray] = []for block_list, np_img in zip(model_list, np_images):image_h, image_w = np_img.shape[:2]- bgr_image = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)+ bgr_image = rgb_to_bgr(np_img)for block_item in block_list:if block_item.get("type") != RAW_FORMULA_NUMBER:continuediff --git a/mineru/backend/analysis/pdf/ocr.py b/mineru/backend/analysis/pdf/ocr.pyindex f2aa6791..f3257cc1 100644--- a/mineru/backend/analysis/pdf/ocr.py+++ b/mineru/backend/analysis/pdf/ocr.py@@ -3,18 +3,18 @@from __future__ import annotations++from dataclasses import dataclass-from typing import Any, Literal+from typing import TYPE_CHECKING, Any, Literal-import cv2import numpy as npfrom docvortex.geometry import normalize_to_int_bboxfrom tqdm import tqdmfrom ....model.ocr.geometry import merge_det_boxes, sorted_boxes, update_det_boxes-from ....model.ocr.image import mask_formula_regions_for_ocr_det+from ....model.ocr.image import mask_formula_regions_for_ocr_det, rgb_to_bgrfrom ....model.ocr.results import OcrConfidence, get_adjusted_mfdetrec_res, get_ocr_result_list-from ....model.runtime.hybrid import HybridLocalModelContextfrom ....types import BlockTypefrom .constants import (BATCH_RATIO,@@ -26,6 +26,10 @@ from .constants import (from .images import crop_imgfrom .model_inputs import _bbox_to_pixel_bbox, _normalize_medium_content+if TYPE_CHECKING:+ from ....model.runtime.hybrid import HybridLocalModelContext++@dataclassclass _OcrDetCrop:@@ -96,7 +100,7 @@ def _collect_ocr_det_crops(finally:_restore_normalized_bbox(res)adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(page_mfd_res, useful_list)- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore+ bgr_image = rgb_to_bgr(new_image) # type: ignorebgr_image = mask_formula_regions_for_ocr_det(bgr_image, adjusted_mfdetrec_res)crops.append(_OcrDetCrop(@@ -291,7 +295,7 @@ def _apply_seal_ocr(if seal_crop_rgb.size == 0:continue- seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)+ seal_crop_bgr = rgb_to_bgr(seal_crop_rgb)seal_tasks.append((block_item, seal_crop_bgr))if not seal_tasks:diff --git a/mineru/backend/analysis/pdf/pipeline.py b/mineru/backend/analysis/pdf/pipeline.pyindex 00eca184..efeca1be 100644--- a/mineru/backend/analysis/pdf/pipeline.py+++ b/mineru/backend/analysis/pdf/pipeline.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport timefrom dataclasses import dataclass-from typing import cast+from typing import TYPE_CHECKING, castfrom docvortex.document.pdf import PDFDocumentfrom loguru import logger@@ -16,13 +16,16 @@ from ....config import VlmConfigfrom ....model.runtime.execution import acquire_document, release_documentfrom ....utils.async_utils import run_syncfrom ....model.vlm.contracts import VlmPredictor-from ....model.runtime.hybrid import HybridLocalModelContext, HybridLocalModelContextSingletonfrom ....model.runtime.memory import clean_memory, trim_process_heapfrom ....model.vlm.client import get_vlm_predictorfrom ..contracts import AnalysisResult, AnalyzeEffort, ParseMode, ResolvedParseModefrom .normalization import _normalize_pdf_model_listfrom .window import aio_process_pdf_windows, process_pdf_windows+if TYPE_CHECKING:+ from ....model.runtime.hybrid import HybridLocalModelContext++_SUPPORTED_PDF_EFFORTS = {"flash", "medium", "high", "xhigh"}@@ -58,6 +61,8 @@ def _prepare_analysis(state.parse_mode = cast(ResolvedParseMode, parse_mode)state.flash_txt_mode = effort == "flash" and state.parse_mode == "txt"if not state.flash_txt_mode:+ from ....model.runtime.hybrid import HybridLocalModelContextSingleton+state.hybrid_model = HybridLocalModelContextSingleton().get_model()acquire_document(state.hybrid_model.device)if effort in {"high", "xhigh"}:diff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.pyindex c3cc64fb..5dce8b9b 100644--- a/mineru/backend/analysis/pdf/tables.py+++ b/mineru/backend/analysis/pdf/tables.py@@ -7,9 +7,8 @@ import htmlimport mathfrom collections import Counterfrom dataclasses import dataclass-from typing import Any, Literal+from typing import TYPE_CHECKING, Any, Literal-import cv2import numpy as npfrom docvortex.analyzers.pdf import PDFTableRecoveryError, prepare_table_page, recover_table_regionfrom docvortex.analyzers.pdf import project_table_text as project_ocr_table_text@@ -24,9 +23,8 @@ from docvortex.geometry import normalize_quarter_turn_angle as _normalize_visualfrom docvortex.geometry import rotate_bbox as _rotate_medium_table_bboxfrom loguru import logger-from ....model.ocr.image import mask_formula_regions_for_ocr_det+from ....model.ocr.image import mask_formula_regions_for_ocr_det, rgb_to_bgrfrom ....model.runtime.contracts import AtomicModelName-from ....model.runtime.hybrid import HybridLocalModelContext, run_ocr_inferencefrom ....types import RAW_ALGORITHM, RAW_FORMULA_NUMBER, RAW_PHONETIC, BBox, BlockTypefrom .snapshots import PageSnapshotCache, get_page_snapshot_entryfrom .constants import (@@ -45,6 +43,10 @@ from .model_inputs import ()from .text.native import _is_supported_rotation+if TYPE_CHECKING:+ from ....model.runtime.hybrid import HybridLocalModelContext++_NATIVE_TABLE_ALWAYS_COMPLEX_BLOCK_TYPES = {BlockType.IMAGE,BlockType.CHART,@@ -814,6 +816,8 @@ def _prepare_medium_table_ocr_results(table_tasks: list[dict[str, Any]],) -> None:"""遮盖表内图片和公式后逐表执行 OCR,并合并内联对象 token。"""+ from ....model.runtime.hybrid import run_ocr_inference+table_ocr_model = Nonetry:table_ocr_model = local_model_context.get_ocr_model(@@ -826,7 +830,7 @@ def _prepare_medium_table_ocr_results(for table_task in table_tasks:ocr_result: list[list[Any]] = []- bgr_image = cv2.cvtColor(table_task["table_img"], cv2.COLOR_RGB2BGR)+ bgr_image = rgb_to_bgr(table_task["table_img"])mask_boxes = [{"bbox": item["mask_bbox"]} for item in table_task["inline_objects"]]masked_image = mask_formula_regions_for_ocr_det(bgr_image, mask_boxes)@@ -972,6 +976,8 @@ def _fill_flash_ocr_table_contents(local_model_context: HybridLocalModelContext,) -> None:"""为 Flash OCR 表格回填 OCR 空间投影文本。"""+ from ....model.runtime.hybrid import run_ocr_inference+table_entries: list[dict[str, Any]] = []for page_idx, page_model_list in enumerate(model_list):table_idx = 0@@ -1038,7 +1044,7 @@ def _fill_flash_ocr_table_contents(angle = _normalize_visual_block_angle(table_block.get("angle", 0))rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)- bgr_crop = cv2.cvtColor(rotated_crop, cv2.COLOR_RGB2BGR)+ bgr_crop = rgb_to_bgr(rotated_crop)page_ocr_results = run_ocr_inference(table_ocr_model.ocr, bgr_crop)raw_ocr_result = page_ocr_results[0] if page_ocr_results else Nonerotated_height, rotated_width = rotated_crop.shape[:2]diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.pyindex 570c6172..f26d312a 100644--- a/mineru/backend/analysis/pdf/text/content.py+++ b/mineru/backend/analysis/pdf/text/content.py@@ -3,7 +3,9 @@from __future__ import annotations-from typing import Any, Literal+++from typing import TYPE_CHECKING, Any, Literalimport numpy as npfrom docvortex.analyzers.pdf import PDF_NATIVE_SCRIPT_MARKUP_KEY, PDFTextEvidence, apply_text_evidence, prepare_text_evidence@@ -15,7 +17,6 @@ from ..snapshots import PageSnapshotCache, get_page_snapshot_entryfrom .....model.ocr.image import rotate_vertical_crop_if_neededfrom .....model.ocr.results import OcrConfidence-from .....model.runtime.hybrid import HybridLocalModelContext, run_ocr_inferencefrom .....types import BBox, BlockType, ContentTypefrom ..constants import (CODE_CONTENT_BLOCK_TYPES,@@ -36,6 +37,9 @@ from .native import (txt_spans_extract,)+if TYPE_CHECKING:+ from .....model.runtime.hybrid import HybridLocalModelContext+def _validate_text_formula_window_inputs(images_list: list[dict[str, Any]],@@ -254,6 +258,8 @@ def _apply_window_post_ocr(page_block_lines_list: list[dict[int, list[_AnalyzeLine]]],) -> None:"""在当前窗口内识别原生字符不足的 span,保持 finalize 后置 OCR 的回退语义。"""+ from .....model.runtime.hybrid import run_ocr_inference+need_ocr_spans: list[_AnalyzeSpan] = []img_crop_list: list[np.ndarray] = []for block_lines in page_block_lines_list:diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.pyindex ed763ed9..d1338b8f 100644--- a/mineru/backend/analysis/pdf/text/native.py+++ b/mineru/backend/analysis/pdf/text/native.py@@ -10,7 +10,6 @@ import statisticsimport unicodedatafrom typing import Any, Callable, cast-import cv2import numpy as npfrom docvortex.analyzers.pdf import PDF_NATIVE_SCRIPT_MARKUP_KEY, ScriptRole, classify_char_script_rolesfrom docvortex.analyzers.pdf import join_tight_text, needs_tight_space@@ -19,6 +18,7 @@ from docvortex.document.pdf import Char, PDFPage, get_lines_from_charsfrom docvortex.geometry import calculate_overlap_area_in_bbox1_area_ratiofrom loguru import logger+from .....model.ocr.image import rgb_to_bgrfrom .....types import BBox, BlockType, ContentTypefrom ..images import get_crop_imgfrom .models import _AnalyzeSpan@@ -294,7 +294,7 @@ def _prepare_post_ocr_spans(for span in need_ocr_spans:# 对span的bbox截图再ocrspan_pil_img = get_crop_img(span.bbox, pil_img, scale)- span_img = cv2.cvtColor(np.array(span_pil_img), cv2.COLOR_RGB2BGR)+ span_img = rgb_to_bgr(np.array(span_pil_img))# 计算span的对比度,低于0.17的span不进行ocr,等于0.17的临界框保留给后置OCR。if calculate_contrast(span_img, img_mode="bgr") < 0.17:if _restore_post_ocr_fallback(span):diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.pyindex af5aae58..21c8e845 100644--- a/mineru/backend/analysis/pdf/window.py+++ b/mineru/backend/analysis/pdf/window.py@@ -24,7 +24,6 @@ from ....utils.timing import stage_timerfrom ....model.runtime.execution import local_model_stagefrom ....utils.async_utils import drain_future, run_sync-from ....model.runtime.hybrid import HybridLocalModelContextfrom ....model.runtime.memory import trim_process_heapfrom ..contracts import AnalyzeEffortfrom .constants import (@@ -34,13 +33,6 @@ from .constants import (NOT_EXTRACT_TYPES,PIPELINE_DET_TYPE,)-from .formulas import (- _apply_medium_display_formula_results,- _apply_medium_formula_number_ocr,- _build_formula_inputs,- _split_formula_results,- optimize_hybrid_formula_number_blocks,-)from .images import (get_document_render_session,get_load_images_threads,@@ -54,28 +46,12 @@ from .layout import (_normalize_xhigh_vlm_blocks,)from .normalization import _apply_layout_title_split-from .ocr import (- _apply_ocr_rec_results,- _apply_seal_ocr,- _build_ocr_det_type_and_mfr_enable,- _ocr_det,-)from .snapshots import PageSnapshotCache, clear_page_snapshot_cache, create_page_snapshot_cache-from .tables import (- _apply_medium_table_recognition,- _apply_native_txt_table_priority,- _apply_table_orientations,- _build_table_external_mfr_inputs,- _fill_flash_ocr_table_contents,- _restore_native_high_table_blocks,- _split_native_high_table_blocks,-)-from .text.content import (- _fill_window_block_content_and_lines,- _validate_text_formula_window_inputs,-)from .visual_containers import supplement_missing_image_block_containers as _supplement_missing_image_block_containers+if TYPE_CHECKING:+ from ....model.runtime.hybrid import HybridLocalModelContext+def _configured_window_size(default: int = 64) -> int:"""读取 PDF 分析窗口大小,非法配置回退到正整数默认值。"""@@ -162,6 +138,10 @@ def _process_flash_ocr(np_images: list[np.ndarray] | None = None,) -> list[list[dict[str, Any]]]:"""使用本地 OCR 为 Flash layout block 填充正文和表格内容。"""+ from .ocr import _apply_ocr_rec_results, _ocr_det+ from .tables import _fill_flash_ocr_table_contents+ from .text.content import _fill_window_block_content_and_lines, _validate_text_formula_window_inputs+_validate_text_formula_window_inputs(images_list,pdf_pages,@@ -218,6 +198,17 @@ def _process_text_and_formulas(np_images: list[np.ndarray] | None = None,) -> list[list[dict[str, Any]]]:"""在当前窗口内完成 OCR、公式、原生文本及 block 行信息回填。"""+ from .formulas import (+ _apply_medium_display_formula_results,+ _apply_medium_formula_number_ocr,+ _build_formula_inputs,+ _split_formula_results,+ optimize_hybrid_formula_number_blocks,+ )+ from .ocr import _apply_ocr_rec_results, _build_ocr_det_type_and_mfr_enable, _ocr_det+ from .tables import _apply_medium_table_recognition, _build_table_external_mfr_inputs+ from .text.content import _fill_window_block_content_and_lines, _validate_text_formula_window_inputs+_validate_text_formula_window_inputs(images_list,@@ -366,6 +357,8 @@ def _prepare_pdf_window(hybrid_model: HybridLocalModelContext,) -> _WindowInputs:"""渲染并准备布局、原生表格和 VLM 输入;失败时由本阶段关闭图片。"""+ from .tables import _apply_native_txt_table_priority, _apply_table_orientations, _split_native_high_table_blocks+images_list: list[dict[str, Any]] = []images_pil_list = []np_images = []@@ -499,6 +492,10 @@ def _finish_pdf_window(hybrid_model: HybridLocalModelContext,) -> list[list[dict[str, Any]]]:"""按原有顺序回填推理结果、文本公式与视觉素材。"""+ from .formulas import optimize_hybrid_formula_number_blocks+ from .ocr import _apply_seal_ocr+ from .tables import _restore_native_high_table_blocks+images_list = state.images_listwindow_pages = state.window_pagesimages_pil_list = state.images_pil_listdiff --git a/mineru/model/_internal/pytorchocr/data/imaug/operators.py b/mineru/model/_internal/pytorchocr/data/imaug/operators.pyindex 69221a75..36f4fb25 100644--- a/mineru/model/_internal/pytorchocr/data/imaug/operators.py+++ b/mineru/model/_internal/pytorchocr/data/imaug/operators.py@@ -15,12 +15,13 @@"""from __future__ import absolute_import+from __future__ import divisionfrom __future__ import print_functionfrom __future__ import unicode_literals+from docvortex.image import decode_image, gray_image, resize_imageimport sys-import cv2import numpy as npfrom PIL import Image@@ -33,15 +34,16 @@ class DecodeImage(object):self.channel_first = channel_firstdef __call__(self, data):+img = data['image']assert type(img) is bytes and len(img) > 0, "invalid input 'img' in DecodeImage"img = np.frombuffer(img, dtype='uint8')- img = cv2.imdecode(img, 1)+ img = decode_image(img.tobytes(), color=True, apply_orientation=True)if img is None:return Noneif self.img_mode == 'GRAY':- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ img = np.repeat(img[:, :, None], 3, axis=2)elif self.img_mode == 'RGB':assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)img = img[:, :, ::-1]@@ -61,21 +63,22 @@ class NRTRDecodeImage(object):self.channel_first = channel_firstdef __call__(self, data):+img = data['image']assert type(img) is bytes and len(img) > 0, "invalid input 'img' in DecodeImage"img = np.frombuffer(img, dtype='uint8')- img = cv2.imdecode(img, 1)+ img = decode_image(img.tobytes(), color=True, apply_orientation=True)if img is None:return Noneif self.img_mode == 'GRAY':- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ img = np.repeat(img[:, :, None], 3, axis=2)elif self.img_mode == 'RGB':assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)img = img[:, :, ::-1]- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ img = gray_image(img, color_order='bgr')if self.channel_first:img = img.transpose((2, 0, 1))data['image'] = img@@ -152,11 +155,12 @@ class Resize(object):self.size = sizedef resize_image(self, img):+resize_h, resize_w = self.sizeori_h, ori_w = img.shape[:2] # (h, w, c)ratio_h = float(resize_h) / ori_hratio_w = float(resize_w) / ori_w- img = cv2.resize(img, (int(resize_w), int(resize_h)))+ img = resize_image(img, (int(resize_w), int(resize_h)))return img, [ratio_h, ratio_w]def __call__(self, data):@@ -210,11 +214,12 @@ class DetResizeForTest(object):return datadef resize_image_type1(self, img):+resize_h, resize_w = self.image_shapeori_h, ori_w = img.shape[:2] # (h, w, c)ratio_h = float(resize_h) / ori_hratio_w = float(resize_w) / ori_w- img = cv2.resize(img, (int(resize_w), int(resize_h)))+ img = resize_image(img, (int(resize_w), int(resize_h)))# return img, np.array([ori_h, ori_w])return img, [ratio_h, ratio_w]@@ -226,6 +231,7 @@ class DetResizeForTest(object):return(tuple):img, (ratio_h, ratio_w)"""+limit_side_len = self.limit_side_lenh, w, c = img.shape@@ -264,7 +270,7 @@ class DetResizeForTest(object):try:if int(resize_w) <= 0 or int(resize_h) <= 0:return None, (None, None)- img = cv2.resize(img, (int(resize_w), int(resize_h)))+ img = resize_image(img, (int(resize_w), int(resize_h)))except:print(img.shape, resize_w, resize_h)sys.exit(0)@@ -273,6 +279,7 @@ class DetResizeForTest(object):return img, [ratio_h, ratio_w]def resize_image_type2(self, img):+h, w, _ = img.shaperesize_w = w@@ -289,7 +296,7 @@ class DetResizeForTest(object):max_stride = 128resize_h = (resize_h + max_stride - 1) // max_stride * max_strideresize_w = (resize_w + max_stride - 1) // max_stride * max_stride- img = cv2.resize(img, (int(resize_w), int(resize_h)))+ img = resize_image(img, (int(resize_w), int(resize_h)))ratio_h = resize_h / float(h)ratio_w = resize_w / float(w)@@ -317,6 +324,7 @@ class E2EResizeForTest(object):def resize_image_for_totaltext(self, im, max_side_len=512):+h, w, _ = im.shaperesize_w = wresize_h = h@@ -329,7 +337,7 @@ class E2EResizeForTest(object):max_stride = 128resize_h = (resize_h + max_stride - 1) // max_stride * max_strideresize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(im, (int(resize_w), int(resize_h)))+ im = resize_image(im, (int(resize_w), int(resize_h)))ratio_h = resize_h / float(h)ratio_w = resize_w / float(w)return im, (ratio_h, ratio_w)@@ -341,6 +349,7 @@ class E2EResizeForTest(object)::param max_side_len: limit of max image size to avoid out of memory in gpu:return: the resized image and the resize ratio"""+h, w, _ = im.shaperesize_w = w@@ -358,7 +367,7 @@ class E2EResizeForTest(object):max_stride = 128resize_h = (resize_h + max_stride - 1) // max_stride * max_strideresize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(im, (int(resize_w), int(resize_h)))+ im = resize_image(im, (int(resize_w), int(resize_h)))ratio_h = resize_h / float(h)ratio_w = resize_w / float(w)@@ -386,6 +395,7 @@ class KieResize(object):return datadef resize_image(self, img):+norm_img = np.zeros([1024, 1024, 3], dtype='float32')scale = [512, 1024]h, w = img.shape[:2]@@ -398,7 +408,7 @@ class KieResize(object):max_stride = 32resize_h = (resize_h + max_stride - 1) // max_stride * max_strideresize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(img, (resize_w, resize_h))+ im = resize_image(img, (resize_w, resize_h))new_h, new_w = im.shape[:2]w_scale = new_w / wh_scale = new_h / hdiff --git a/mineru/model/_internal/pytorchocr/infer/predict_cls.py b/mineru/model/_internal/pytorchocr/infer/predict_cls.pyindex 6dc8a6a1..74c58a11 100644--- a/mineru/model/_internal/pytorchocr/infer/predict_cls.py+++ b/mineru/model/_internal/pytorchocr/infer/predict_cls.py@@ -1,5 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.-import cv2++from docvortex.image import resize_imageimport copyimport numpy as npimport math@@ -37,6 +38,7 @@ class TextClassifier(BaseOCRV20):self._apply_inference_precision(self.device)def resize_norm_img(self, img):+imgC, imgH, imgW = self.cls_image_shapeh = img.shape[0]w = img.shape[1]@@ -48,7 +50,7 @@ class TextClassifier(BaseOCRV20):resized_w = imgWelse:resized_w = int(math.ceil(imgH * ratio))- resized_image = cv2.resize(img, (resized_w, imgH))+ resized_image = resize_image(img, (resized_w, imgH))resized_image = resized_image.astype('float32')if self.cls_image_shape[0] == 1:resized_image = resized_image / 255@@ -102,6 +104,5 @@ class TextClassifier(BaseOCRV20):label, score = cls_result[rno]cls_res[indices[beg_img_no + rno]] = [label, score]if '180' in label and score > self.cls_thresh:- img_list[indices[beg_img_no + rno]] = cv2.rotate(- img_list[indices[beg_img_no + rno]], 1)+ img_list[indices[beg_img_no + rno]] = np.rot90(img_list[indices[beg_img_no + rno]], k=2).copy(order="C")return img_list, cls_res, elapsediff --git a/mineru/model/_internal/pytorchocr/infer/predict_rec.py b/mineru/model/_internal/pytorchocr/infer/predict_rec.pyindex fbcb9177..0277ab13 100644--- a/mineru/model/_internal/pytorchocr/infer/predict_rec.py+++ b/mineru/model/_internal/pytorchocr/infer/predict_rec.py@@ -1,6 +1,7 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import gray_image, resize_imagefrom PIL import Image-import cv2from ....ocr.image import resize_text_recognition_imageimport numpy as npimport math@@ -105,9 +106,10 @@ class TextRecognizer(BaseOCRV20):def resize_norm_img(self, img: np.ndarray, max_wh_ratio: float) -> np.ndarray:"""特殊识别器保持各自变换,标准 CTC 路径复用跨后端处理。"""+imgC, imgH, imgW = self.rec_image_shapeif self.rec_algorithm == 'NRTR' or self.rec_algorithm == 'ViTSTR':- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ img = gray_image(img, color_order='bgr')# return padding_imimage_pil = Image.fromarray(np.uint8(img))if self.rec_algorithm == 'ViTSTR':@@ -123,9 +125,8 @@ class TextRecognizer(BaseOCRV20):norm_img = norm_img.astype(np.float32) / 128. - 1.return norm_imgelif self.rec_algorithm == 'RFL':- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)- resized_image = cv2.resize(- img, (imgW, imgH), interpolation=cv2.INTER_CUBIC)+ img = gray_image(img, color_order='bgr')+ resized_image = resize_image(img, (imgW, imgH), interpolation='cubic')resized_image = resized_image.astype('float32')resized_image = resized_image / 255resized_image = resized_image[np.newaxis, :]@@ -139,9 +140,9 @@ class TextRecognizer(BaseOCRV20):def resize_norm_img_svtr(self, img, image_shape):+imgC, imgH, imgW = image_shape- resized_image = cv2.resize(- img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)+ resized_image = resize_image(img, (imgW, imgH), interpolation='linear')resized_image = resized_image.astype('float32')resized_image = resized_image.transpose((2, 0, 1)) / 255resized_image -= 0.5@@ -150,6 +151,7 @@ class TextRecognizer(BaseOCRV20):def resize_norm_img_srn(self, img, image_shape):+imgC, imgH, imgW = image_shapeimg_black = np.zeros((imgH, imgW))@@ -157,16 +159,16 @@ class TextRecognizer(BaseOCRV20):im_wid = img.shape[1]if im_wid <= im_hei * 1:- img_new = cv2.resize(img, (imgH * 1, imgH))+ img_new = resize_image(img, (imgH * 1, imgH))elif im_wid <= im_hei * 2:- img_new = cv2.resize(img, (imgH * 2, imgH))+ img_new = resize_image(img, (imgH * 2, imgH))elif im_wid <= im_hei * 3:- img_new = cv2.resize(img, (imgH * 3, imgH))+ img_new = resize_image(img, (imgH * 3, imgH))else:- img_new = cv2.resize(img, (imgW, imgH))+ img_new = resize_image(img, (imgW, imgH))img_np = np.asarray(img_new)- img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)+ img_np = gray_image(img_np, color_order='bgr')img_black[:, 0:img_np.shape[1]] = img_npimg_black = img_black[:, :, np.newaxis]@@ -223,6 +225,7 @@ class TextRecognizer(BaseOCRV20):def resize_norm_img_sar(self, img, image_shape,width_downsample_ratio=0.25):+imgC, imgH, imgW_min, imgW_max = image_shapeh = img.shape[0]w = img.shape[1]@@ -239,7 +242,7 @@ class TextRecognizer(BaseOCRV20):if imgW_max is not None:valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)resize_w = min(imgW_max, resize_w)- resized_image = cv2.resize(img, (resize_w, imgH))+ resized_image = resize_image(img, (resize_w, imgH))resized_image = resized_image.astype('float32')# normif image_shape[0] == 1:@@ -259,8 +262,8 @@ class TextRecognizer(BaseOCRV20):def norm_img_can(self, img, image_shape):- img = cv2.cvtColor(- img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image++ img = gray_image(img, color_order='bgr') # CAN only predict gray scale imageif self.inverse:img = 255 - imgdiff --git a/mineru/model/_internal/pytorchocr/infer/predict_system.py b/mineru/model/_internal/pytorchocr/infer/predict_system.pyindex 6285aece..bdf0d77c 100644--- a/mineru/model/_internal/pytorchocr/infer/predict_system.py+++ b/mineru/model/_internal/pytorchocr/infer/predict_system.py@@ -1,5 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.-import cv2++from docvortex.image import perspective_matrix, warp_imageimport copyimport numpy as np@@ -28,6 +29,7 @@ class TextSystem(object):points[:, 0] = points[:, 0] - leftpoints[:, 1] = points[:, 1] - top'''+img_crop_width = int(max(np.linalg.norm(points[0] - points[1]),@@ -39,12 +41,8 @@ class TextSystem(object):pts_std = np.float32([[0, 0], [img_crop_width, 0],[img_crop_width, img_crop_height],[0, img_crop_height]])- M = cv2.getPerspectiveTransform(points, pts_std)- dst_img = cv2.warpPerspective(- img,- M, (img_crop_width, img_crop_height),- borderMode=cv2.BORDER_REPLICATE,- flags=cv2.INTER_CUBIC)+ M = perspective_matrix(points, pts_std)+ dst_img = warp_image(img, M, (img_crop_width, img_crop_height), border='replicate', interpolation='cubic')dst_img_height, dst_img_width = dst_img.shape[0:2]if dst_img_height * 1.0 / dst_img_width >= 1.5:dst_img = np.rot90(dst_img)diff --git a/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py b/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.pyindex 6ee48190..21e9dad3 100644--- a/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py+++ b/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py@@ -1,9 +1,10 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import decode_image, resize_imageimport osimport mathfrom pathlib import Pathimport numpy as np-import cv2import argparsefrom ....ocr.resources import PPOCRV6_DICT_PATH@@ -178,11 +179,12 @@ def resize_img(img, input_size=600):"""resize img and limit the longest side of the image to input_size"""+img = np.array(img)im_shape = img.shapeim_size_max = np.max(im_shape[0:2])im_scale = float(input_size) / float(im_size_max)- img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale)+ img = resize_image(img, None, scale=(im_scale, im_scale))return img@@ -211,10 +213,11 @@ def str_count(s):def base64_to_cv2(b64str):+import base64data = base64.b64decode(b64str.encode('utf8'))data = np.fromstring(data, np.uint8)- data = cv2.imdecode(data, cv2.IMREAD_COLOR)+ data = decode_image(data.tobytes(), color=True, apply_orientation=True)return datadiff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.pyindex f98f0e47..2aae71f6 100644--- a/mineru/model/layout/pp_doclayout_v2_onnx.py+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py@@ -9,17 +9,19 @@"""from __future__ import annotations+from docvortex.image import resize_image+from pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Tuple, Union-import cv2import numpy as npimport yamlfrom loguru import loggerfrom PIL import Imagefrom tqdm import tqdm+from ..ocr.image import rgb_to_bgrfrom ..runtime.onnx import ort_sessionfrom .pp_doclayout_v2_base import PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor@@ -58,7 +60,7 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):self.use_paddlex_filter_boxes = use_paddlex_filter_boxesself.model_path = str(weight)self.imgsz = imgsz- self.interpolation = cv2.INTER_CUBIC+ self.interpolation = 2 # OpenCV INTER_CUBIC,与官方预处理配置的整数编码一致。configuration_path = Path(config_path) if config_path else Path(weight).with_suffix(".yml")if config_path or configuration_path.is_file():with configuration_path.open(encoding="utf-8") as handle:@@ -79,6 +81,7 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):def _preprocess_single_image(self, image: Union[np.ndarray, Image.Image]) -> Tuple[np.ndarray, Tuple[int, int]]:"""Resize 到 800x800 (BICUBIC) + /255,返回 CHW float32 ndarray。"""+if isinstance(image, Image.Image):pil_image = image.convert("RGB")target_size = pil_image.size[1], pil_image.size[0]@@ -86,12 +89,12 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):elif isinstance(image, np.ndarray):arr = imageif arr.ndim == 3 and arr.shape[2] == 3:- arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)+ arr = rgb_to_bgr(arr)target_size = arr.shape[0], arr.shape[1]else:raise TypeError(f"Unsupported image type for PP-DocLayoutV2 ONNX: {type(image)}")- resized = cv2.resize(arr, (self.imgsz[1], self.imgsz[0]), interpolation=self.interpolation)+ resized = resize_image(arr, (self.imgsz[1], self.imgsz[0]), interpolation={0: 'nearest', 1: 'linear', 2: 'cubic', 3: 'area', 4: 'lanczos4'}[self.interpolation])norm = resized.astype(np.float32) * self.rescale_factorchw = norm.transpose(2, 0, 1)return chw, target_sizediff --git a/mineru/model/mfr/pp_formulanet/processors.py b/mineru/model/mfr/pp_formulanet/processors.pyindex c31dad6b..d226398d 100644--- a/mineru/model/mfr/pp_formulanet/processors.py+++ b/mineru/model/mfr/pp_formulanet/processors.py@@ -1,10 +1,11 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import gray_imageimport jsonimport mathimport refrom typing import Any, Dict, List, Optional, Tuple, Union-import cv2import numpy as npfrom PIL import Image, ImageOpsfrom tokenizers import AddedToken@@ -42,9 +43,10 @@ class UniMERNetImgDecode(object):return imgdata = (data - min_val) / (max_val - min_val) * 255gray = 255 * (data < 200).astype(np.uint8)- coords = cv2.findNonZero(gray) # Find all non-zero points (text)- a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box- return img.crop((a, b, w + a, h + b))+ ys, xs = np.nonzero(gray)+ if xs.size == 0:+ return img.crop((0, 0, 0, 0))+ return img.crop((int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1))def get_dimensions(self, img: Union[Image.Image, np.ndarray]) -> List[int]:"""Gets the dimensions of the image.@@ -180,6 +182,7 @@ class UniMERNetTestTransform:Returns:numpy.ndarray: The transformed image."""+mean = [0.7931, 0.7931, 0.7931]std = [0.1738, 0.1738, 0.1738]scale = float(1 / 255.0)@@ -188,13 +191,13 @@ class UniMERNetTestTransform:std = np.array(std).reshape(shape).astype("float32")if self.paddle_compatible:# plus-S 对齐 Paddle:先对 RGB uint8 图像灰度化,再归一化;保留 plus-M 原行为。- gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)- img = cv2.merge([gray] * self.num_output_channels).astype("float32")+ gray = gray_image(img, color_order='rgb')+ img = np.stack([gray] * self.num_output_channels, axis=2).astype("float32")return (img - mean * 255.0) * (1.0 / (std * 255.0))img = (img.astype("float32") * scale - mean) / std- grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ grayscale_image = gray_image(img, color_order='bgr')squeezed = np.squeeze(grayscale_image)- img = cv2.merge([squeezed] * self.num_output_channels)+ img = np.stack([squeezed] * self.num_output_channels, axis=2)return imgdef __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.pyindex e737d6b3..31cdb4d9 100644--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py+++ b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py@@ -1,13 +1,13 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import gray_image, resize_imagefrom PIL import Image, ImageOpsfrom transformers.image_processing_utils import BaseImageProcessorimport numpy as np-import cv2import torchfrom torchvision.transforms.functional import resize-# TODO: dereference cv2 if possibleclass UnimerSwinImageProcessor(BaseImageProcessor):def __init__(self,@@ -28,7 +28,8 @@ class UnimerSwinImageProcessor(BaseImageProcessor):elif image.ndim == 3 and image.shape[2] == 1:gray = image[:, :, 0]elif image.ndim == 3 and image.shape[2] == 3:- gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)++ gray = gray_image(image, color_order='rgb')else:raise ValueError(f"Unsupported image shape for UnimerSwinImageProcessor: {image.shape}")@@ -46,16 +47,18 @@ class UnimerSwinImageProcessor(BaseImageProcessor):data = (data - min_val) / (max_val - min_val) * 255gray = 255 * (data < 200).astype(np.uint8)- coords = cv2.findNonZero(gray) # Find all non-zero points (text)- a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box- return img.crop((a, b, w + a, h + b))+ ys, xs = np.nonzero(gray)+ if xs.size == 0:+ return img.crop((0, 0, 0, 0))+ return img.crop((int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1))@staticmethoddef crop_margin_numpy(img: np.ndarray) -> np.ndarray:"""Crop margins of image using NumPy operations"""# Convert to grayscale if it's a color imageif len(img.shape) == 3 and img.shape[2] == 3:- gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)++ gray = gray_image(img, color_order='rgb')else:gray = img.copy()@@ -67,11 +70,11 @@ class UnimerSwinImageProcessor(BaseImageProcessor):binary = 255 * (normalized < 200).astype(np.uint8)# Find bounding box- coords = cv2.findNonZero(binary) # Find all non-zero points (text)- x, y, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box-- # Return cropped image- return img[y:y + h, x:x + w]+ mask = binary[:, :, 0] if binary.ndim == 3 and binary.shape[2] == 1 else binary+ ys, xs = np.nonzero(mask)+ if xs.size == 0:+ return img[0:0, 0:0]+ return img[int(ys.min()):int(ys.max()) + 1, int(xs.min()):int(xs.max()) + 1]def prepare_input(self, img, random_padding: bool = False):"""@@ -105,7 +108,8 @@ class UnimerSwinImageProcessor(BaseImageProcessor):new_h, new_w = int(h * scale), int(w * scale)# Resize the image while preserving aspect ratio- resized_img = cv2.resize(img, (new_w, new_h))++ resized_img = resize_image(img, (new_w, new_h))# Calculate padding values using the existing methoddelta_width = target_w - new_w@@ -113,18 +117,11 @@ class UnimerSwinImageProcessor(BaseImageProcessor):pad_width, pad_height = self._get_padding_values(new_w, new_h, random_padding)- # Apply padding (convert PIL padding format to OpenCV format)- padding_color = [0, 0, 0] if len(img.shape) == 3 else [0]-- padded_img = cv2.copyMakeBorder(- resized_img,- pad_height, # top- delta_height - pad_height, # bottom- pad_width, # left- delta_width - pad_width, # right- cv2.BORDER_CONSTANT,- value=padding_color- )+ # 常量零填充无需 OpenCV,保持缩放结果的维度和位深。+ padding = [(pad_height, delta_height - pad_height), (pad_width, delta_width - pad_width)]+ if resized_img.ndim == 3:+ padding.append((0, 0))+ padded_img = np.pad(resized_img, padding, mode="constant")return padded_imgdiff --git a/mineru/model/ocr/db_postprocess.py b/mineru/model/ocr/db_postprocess.pyindex 51cbeb35..7c32e70b 100644--- a/mineru/model/ocr/db_postprocess.py+++ b/mineru/model/ocr/db_postprocess.py@@ -5,11 +5,20 @@ https://github.com/WenmuZhou/DBNet.pytorch/blob/master/post_processing/seg_detec"""from __future__ import annotations+from docvortex.image import (+ morphology,+ rasterize_polygons,+ trace_contours,+ contour_length,+ minimum_rectangle,+ rectangle_corners,+ simplify_contour,+)+from typing import Any, Literalimport numpy as np-import cv2from shapely.geometry import Polygonimport pyclipper@@ -52,11 +61,11 @@ class DBPostProcess(object):boxes = []scores = []- contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)+ contours = trace_contours((bitmap * 255).astype(np.uint8))for contour in contours[: self.max_candidates]:- epsilon = 0.002 * cv2.arcLength(contour, True)- approx = cv2.approxPolyDP(contour, epsilon, True)+ epsilon = 0.002 * contour_length(contour, closed=True)+ approx = simplify_contour(contour, epsilon, closed=True)points = approx.reshape((-1, 2))if points.shape[0] < 4:continue@@ -95,11 +104,7 @@ class DBPostProcess(object):bitmap = _bitmapheight, width = bitmap.shape- outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)- if len(outs) == 3:- contours = outs[1]- elif len(outs) == 2:- contours, _ = outs[0], outs[1]+ contours = trace_contours((bitmap * 255).astype(np.uint8))num_contours = min(len(contours), self.max_candidates)@@ -144,8 +149,9 @@ class DBPostProcess(object):def get_mini_boxes(self, contour: np.ndarray) -> tuple[list[np.ndarray], float]:"""返回轮廓的有序最小外接矩形与短边长度。"""- bounding_box = cv2.minAreaRect(contour)- points = sorted(cv2.boxPoints(bounding_box), key=lambda x: x[0])++ bounding_box = minimum_rectangle(contour)+ points = sorted(rectangle_corners(bounding_box), key=lambda x: x[0])index_1, index_2, index_3, index_4 = 0, 1, 2, 3if points[1][1] > points[0][1]:@@ -166,6 +172,7 @@ class DBPostProcess(object):def box_score_fast(self, bitmap: np.ndarray, _box: np.ndarray) -> float:"""计算外接框覆盖区域的平均检测分数。"""+h, w = bitmap.shape[:2]box = _box.copy()xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int32), 0, w - 1)@@ -176,11 +183,12 @@ class DBPostProcess(object):mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)box[:, 0] = box[:, 0] - xminbox[:, 1] = box[:, 1] - ymin- cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)- return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]+ mask = rasterize_polygons(mask.shape, [box.astype(np.int32)])+ return self._masked_mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)def box_score_slow(self, bitmap: np.ndarray, contour: np.ndarray) -> float:"""计算原始轮廓覆盖区域的平均检测分数。"""+h, w = bitmap.shape[:2]contour = contour.copy()contour = np.reshape(contour, (-1, 2))@@ -195,11 +203,18 @@ class DBPostProcess(object):contour[:, 0] = contour[:, 0] - xmincontour[:, 1] = contour[:, 1] - ymin- cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1)- return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]+ mask = rasterize_polygons(mask.shape, [contour.astype(np.int32)])+ return self._masked_mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)++ @staticmethod+ def _masked_mean(bitmap: np.ndarray, mask: np.ndarray) -> float:+ """按非零掩码取平均,double 累计保持检测阈值原有数值语义。"""+ pixels = bitmap[mask != 0]+ return float(pixels.sum(dtype=np.float64) / pixels.size) if pixels.size else 0.0def __call__(self, outs_dict: dict[str, np.ndarray], shape_list: np.ndarray) -> list[dict[str, Any]]:"""逐项恢复原图坐标,保留普通文字与印章各自的点序和轮廓。"""+pred = outs_dict["maps"]pred = pred[:, 0, :, :]segmentation = pred > self.thresh@@ -208,7 +223,7 @@ class DBPostProcess(object):for batch_index in range(pred.shape[0]):src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]if self.dilation_kernel is not None:- mask = cv2.dilate(np.array(segmentation[batch_index]).astype(np.uint8), self.dilation_kernel)+ mask = morphology(np.array(segmentation[batch_index]).astype(np.uint8), self.dilation_kernel.shape[::-1])else:mask = segmentation[batch_index]if self.box_type == "poly":diff --git a/mineru/model/ocr/image.py b/mineru/model/ocr/image.pyindex 371c9a95..7b5cf03d 100644--- a/mineru/model/ocr/image.py+++ b/mineru/model/ocr/image.py@@ -2,10 +2,11 @@"""OCR 输入图像解码、遮罩与旋转裁剪。"""from __future__ import annotations+from docvortex.image import decode_image, perspective_matrix, resize_image, warp_image+from typing import Any-import cv2import numpy as npfrom docvortex.geometry import normalize_to_int_bbox@@ -14,10 +15,23 @@ from .geometry import is_bbox_aligned_rectTEXT_REC_ROTATE_RATIO = 1.5+def rgb_to_bgr(img: np.ndarray) -> np.ndarray:+ """为模型输入交换 RGB/BGR 通道,忽略 alpha 并返回独立连续数组。"""+ if img.dtype not in (np.uint8, np.uint16, np.float32) or img.size == 0:+ raise ValueError("Model input expects a non-empty uint8, uint16 or float32 image")+ if img.ndim == 2:+ return np.repeat(img[:, :, None], 3, axis=2)+ if img.ndim == 3 and img.shape[2] == 1:+ return np.repeat(img, 3, axis=2)+ if img.ndim == 3 and img.shape[2] in (3, 4):+ return img[:, :, 2::-1].copy(order="C")+ raise ValueError(f"Unsupported model input image shape: {img.shape}")++def img_decode(content: bytes) -> Any:- """把编码图片字节解码为 OpenCV 数组。"""- np_arr = np.frombuffer(content, dtype=np.uint8)- return cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED)+ """通过共享图像接口解码字节,保留 BGR、alpha 和原始位深。"""++ return decode_image(content)def check_img(img: bytes | np.ndarray) -> Any:@@ -25,19 +39,19 @@ def check_img(img: bytes | np.ndarray) -> Any:if isinstance(img, bytes):img = img_decode(img)if isinstance(img, np.ndarray) and len(img.shape) == 2:- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ img = np.repeat(img[:, :, None], 3, axis=2)return imgdef alpha_to_color(img: np.ndarray, alpha_color: tuple[int, int, int] = (255, 255, 255)) -> np.ndarray:"""把带透明通道的图像合成到指定纯色背景。"""if len(img.shape) == 3 and img.shape[2] == 4:- blue, green, red, alpha_channel = cv2.split(img)+ blue, green, red, alpha_channel = (img[:, :, index] for index in range(4))alpha = alpha_channel / 255red = (alpha_color[0] * (1 - alpha) + red * alpha).astype(np.uint8)green = (alpha_color[1] * (1 - alpha) + green * alpha).astype(np.uint8)blue = (alpha_color[2] * (1 - alpha) + blue * alpha).astype(np.uint8)- img = cv2.merge((blue, green, red))+ img = np.stack((blue, green, red), axis=2)return img@@ -83,14 +97,10 @@ def get_rotate_crop_image(img: np.ndarray, points: np.ndarray) -> np.ndarray:img_crop_width = int(max(np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3])))img_crop_height = int(max(np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2])))pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]])- matrix = cv2.getPerspectiveTransform(points, pts_std)- dst_img = cv2.warpPerspective(- img,- matrix,- (img_crop_width, img_crop_height),- borderMode=cv2.BORDER_REPLICATE,- flags=cv2.INTER_CUBIC,- )+ # 四边形裁图调用共享数值内核,轴对齐区域继续直接复制。++ matrix = perspective_matrix(points, pts_std)+ dst_img = warp_image(img, matrix, (img_crop_width, img_crop_height), border="replicate", interpolation="cubic")dst_img_height, dst_img_width = dst_img.shape[:2]if dst_img_height / dst_img_width >= TEXT_REC_ROTATE_RATIO:dst_img = np.rot90(dst_img)@@ -126,7 +136,8 @@ def resize_text_recognition_image(ratio = max(max_wh_ratio, width / height)width = max(min(int(height * ratio), max_width), min_width)resized_width = min(width, max(int(np.ceil(height * img.shape[1] / img.shape[0])), min_width))- resized = cv2.resize(img, (resized_width, height)) / 127.5 - 1++ resized = resize_image(img, (resized_width, height)) / 127.5 - 1padded = np.zeros((channels, height, width), dtype=np.float32)padded[:, :, :resized_width] = resized.transpose(2, 0, 1)return padded@@ -147,5 +158,6 @@ __all__ = ["mask_formula_regions_for_ocr_det","preprocess_image","resize_text_recognition_image",+ "rgb_to_bgr","rotate_vertical_crop_if_needed",]diff --git a/mineru/model/ocr/pp_ocr_v6_onnx.py b/mineru/model/ocr/pp_ocr_v6_onnx.pyindex 6b525718..c4418621 100644--- a/mineru/model/ocr/pp_ocr_v6_onnx.py+++ b/mineru/model/ocr/pp_ocr_v6_onnx.py@@ -20,7 +20,6 @@ import warningsfrom pathlib import Pathfrom typing import Any, List, Literal, Optional, Tuple, Union-import cv2import numpy as npfrom loguru import loggerfrom tqdm import tqdm@@ -543,6 +542,7 @@ class PPOCRv6ONNX:if __name__ == "__main__":+import argparseimport json@@ -568,7 +568,9 @@ if __name__ == "__main__":device=args.device,)- img = cv2.imread(args.image)+ from docvortex.image import decode_image++ img = decode_image(Path(args.image).read_bytes(), color=True, apply_orientation=True)results = model.ocr(img)print(f"\ndetected {len(results[0] or [])} text lines")for item in results[0] or []:diff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.pyindex 937764be..1beba38c 100644--- a/mineru/model/ocr/pytorch_paddle.py+++ b/mineru/model/ocr/pytorch_paddle.py@@ -5,9 +5,9 @@ import osimport warningsfrom pathlib import Path-import cv2import numpy as npimport yaml+from PIL import Image, ImageDrawfrom loguru import loggerfrom ..registry import MINERU_4_MODELS_TORCH@@ -110,7 +110,15 @@ class PytorchPaddleOCR(TextSystem):return None+ @staticmethod+ def _save_debug_image(path: Path, image: np.ndarray) -> None:+ """独立物化 BGR 诊断图后用 Pillow 保存,调试过程不加载视觉运行时。"""+ pixels = image[:, :, ::-1] if image.ndim == 3 else image+ with Image.fromarray(pixels) as canvas:+ canvas.save(path)+def _dump_seal_debug_artifacts(self, input_image, dt_boxes, img_crop_list, rec_res=None):+if not self._seal_debug_dir:return@@ -121,29 +129,19 @@ class PytorchPaddleOCR(TextSystem):self._seal_debug_counter += 1os.makedirs(sample_dir, exist_ok=True)- cv2.imwrite(os.path.join(sample_dir, "input.png"), input_image)-- det_vis = input_image.copy()- for index, box in enumerate(dt_boxes or []):- points = np.asarray(box, dtype=np.int32).reshape((-1, 1, 2))- cv2.polylines(det_vis, [points], isClosed=True, color=(0, 0, 255), thickness=2)- anchor = tuple(np.asarray(box[0], dtype=np.int32).tolist())- cv2.putText(- det_vis,- str(index),- anchor,- cv2.FONT_HERSHEY_SIMPLEX,- 0.6,- (255, 0, 0),- 2,- cv2.LINE_AA,- )- cv2.imwrite(os.path.join(sample_dir, "det_vis.png"), det_vis)+ self._save_debug_image(Path(sample_dir) / "input.png", input_image)+ with Image.fromarray(input_image[:, :, ::-1]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for index, box in enumerate(dt_boxes or []):+ points = [tuple(map(int, xy)) for xy in np.asarray(box).reshape(-1, 2)]+ draw.line(points + points[:1], fill=(255, 0, 0), width=2)+ draw.text(points[0], str(index), fill=(0, 0, 255))+ canvas.save(Path(sample_dir) / "det_vis.png")records = []for index, crop_img in enumerate(img_crop_list or []):crop_name = f"crop_{index:02d}.png"- cv2.imwrite(os.path.join(sample_dir, crop_name), crop_img)+ self._save_debug_image(Path(sample_dir) / crop_name, crop_img)record = {"index": index,"crop_path": crop_name,@@ -276,8 +274,9 @@ class PytorchPaddleOCR(TextSystem):return filter_boxes, filter_rec_resif __name__ == '__main__':+pytorch_paddle_ocr = PytorchPaddleOCR()- img = cv2.imread("/Users/myhloli/Downloads/screenshot-20250326-194348.png")+ img = np.asarray(Image.open("/Users/myhloli/Downloads/screenshot-20250326-194348.png").convert("RGB"))[:, :, ::-1].copy()dt_boxes, rec_res = pytorch_paddle_ocr(img)ocr_res = []if not dt_boxes and not rec_res:diff --git a/mineru/model/ocr/seal_crop.py b/mineru/model/ocr/seal_crop.pyindex 75f90e72..cc178fe3 100644--- a/mineru/model/ocr/seal_crop.py+++ b/mineru/model/ocr/seal_crop.py@@ -12,10 +12,11 @@# See the License for the specific language governing permissions and# limitations under the License.+from docvortex.image import minimum_rectangle, perspective_matrix, rectangle_corners, warp_image+import copyfrom typing import List, Tuple-import cv2import numpy as npfrom numpy.linalg import normfrom shapely.geometry import Polygon@@ -64,8 +65,8 @@ class CropByPolys:return output_listdef get_minarea_rect_crop(self, img: np.ndarray, points: np.ndarray) -> np.ndarray:- bounding_box = cv2.minAreaRect(np.array(points).astype(np.int32))- points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])+ bounding_box = minimum_rectangle(np.array(points).astype(np.int32))+ points = sorted(list(rectangle_corners(bounding_box)), key=lambda x: x[0])index_a, index_b, index_c, index_d = 0, 1, 2, 3if points[1][1] > points[0][1]:@@ -107,22 +108,14 @@ class CropByPolys:[0, img_crop_height],])- M = cv2.getPerspectiveTransform(points, pts_std)- dst_img = cv2.warpPerspective(- img,- M,- (img_crop_width, img_crop_height),- borderMode=cv2.BORDER_REPLICATE,- flags=cv2.INTER_CUBIC,- )+ M = perspective_matrix(points, pts_std)+ dst_img = warp_image(img, M, (img_crop_width, img_crop_height), border="replicate", interpolation="cubic")dst_img_height, dst_img_width = dst_img.shape[0:2]if dst_img_height * 1.0 / dst_img_width >= 1.5:dst_img = np.rot90(dst_img)return dst_img- def reorder_poly_edge(- self, points: np.ndarray- ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ def reorder_poly_edge(self, points: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:assert points.ndim == 2assert points.shape[0] >= 4assert points.shape[1] == 2@@ -143,9 +136,7 @@ class CropByPolys:assert len(vec) == 2return abs(vec[1] / (vec[0] + 1e-8))- def find_head_tail(- self, points: np.ndarray, orientation_thr: float- ) -> Tuple[list, list]:+ def find_head_tail(self, points: np.ndarray, orientation_thr: float) -> Tuple[list, list]:assert points.ndim == 2assert points.shape[0] >= 4assert points.shape[1] == 2@@ -161,9 +152,7 @@ class CropByPolys:adjacent_ind = [x % len(edge_vec) for x in [i - 1, i + 1]]adjacent_edge_vec = edge_vec[adjacent_ind]temp_theta_sum = np.sum(self.vector_angle(edge_vec1, adjacent_edge_vec))- temp_adjacent_theta = self.vector_angle(- adjacent_edge_vec[0], adjacent_edge_vec[1]- )+ temp_adjacent_theta = self.vector_angle(adjacent_edge_vec[0], adjacent_edge_vec[1])theta_sum.append(temp_theta_sum)adjacent_vec_theta.append(temp_adjacent_theta)theta_sum_score = np.array(theta_sum) / np.pi@@ -184,21 +173,12 @@ class CropByPolys:pad_score = np.concatenate([score, score])score_matrix = np.zeros((len(score), len(score) - 3))x = np.arange(len(score) - 3) / float(len(score) - 4)- gaussian = (- 1.0- / (np.sqrt(2.0 * np.pi) * 0.5)- * np.exp(-np.power((x - 0.5) / 0.5, 2.0) / 2)- )+ gaussian = 1.0 / (np.sqrt(2.0 * np.pi) * 0.5) * np.exp(-np.power((x - 0.5) / 0.5, 2.0) / 2)gaussian = gaussian / np.max(gaussian)for i in range(len(score)):- score_matrix[i, :] = (- score[i]- + pad_score[(i + 2) : (i + len(score) - 1)] * gaussian * 0.3- )+ score_matrix[i, :] = score[i] + pad_score[(i + 2) : (i + len(score) - 1)] * gaussian * 0.3- head_start, tail_increment = np.unravel_index(- score_matrix.argmax(), score_matrix.shape- )+ head_start, tail_increment = np.unravel_index(score_matrix.argmax(), score_matrix.shape)tail_start = (head_start + tail_increment + 2) % len(points)head_end = (head_start + 1) % len(points)tail_end = (tail_start + 1) % len(points)@@ -209,25 +189,19 @@ class CropByPolys:head_inds = [head_start, head_end]tail_inds = [tail_start, tail_end]else:- if self.vector_slope(points[1] - points[0]) + self.vector_slope(- points[3] - points[2]- ) < self.vector_slope(points[2] - points[1]) + self.vector_slope(- points[0] - points[3]- ):+ if self.vector_slope(points[1] - points[0]) + self.vector_slope(points[3] - points[2]) < self.vector_slope(+ points[2] - points[1]+ ) + self.vector_slope(points[0] - points[3]):horizontal_edge_inds = [[0, 1], [2, 3]]vertical_edge_inds = [[3, 0], [1, 2]]else:horizontal_edge_inds = [[3, 0], [1, 2]]vertical_edge_inds = [[0, 1], [2, 3]]- vertical_len_sum = norm(- points[vertical_edge_inds[0][0]] - points[vertical_edge_inds[0][1]]- ) + norm(+ vertical_len_sum = norm(points[vertical_edge_inds[0][0]] - points[vertical_edge_inds[0][1]]) + norm(points[vertical_edge_inds[1][0]] - points[vertical_edge_inds[1][1]])- horizontal_len_sum = norm(- points[horizontal_edge_inds[0][0]] - points[horizontal_edge_inds[0][1]]- ) + norm(+ horizontal_len_sum = norm(points[horizontal_edge_inds[0][0]] - points[horizontal_edge_inds[0][1]]) + norm(points[horizontal_edge_inds[1][0]] - points[horizontal_edge_inds[1][1]])@@ -251,11 +225,9 @@ class CropByPolys:unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8)return np.arccos(np.clip(np.sum(unit_vec1 * unit_vec2, axis=-1), -1.0, 1.0))- def get_minarea_rect(- self, img: np.ndarray, points: np.ndarray- ) -> Tuple[np.ndarray, list]:- bounding_box = cv2.minAreaRect(points)- points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])+ def get_minarea_rect(self, img: np.ndarray, points: np.ndarray) -> Tuple[np.ndarray, list]:+ bounding_box = minimum_rectangle(points)+ points = sorted(list(rectangle_corners(bounding_box)), key=lambda x: x[0])index_a, index_b, index_c, index_d = 0, 1, 2, 3if points[1][1] > points[0][1]:@@ -291,20 +263,13 @@ class CropByPolys:for i in range(1, n):current_line_len = i * delta_length- while (- current_edge_ind + 1 < len(length_cumsum)- and current_line_len >= length_cumsum[current_edge_ind + 1]- ):+ while current_edge_ind + 1 < len(length_cumsum) and current_line_len >= length_cumsum[current_edge_ind + 1]:current_edge_ind += 1current_edge_end_shift = current_line_len - length_cumsum[current_edge_ind]if current_edge_ind >= len(length_list):breakend_shift_ratio = current_edge_end_shift / length_list[current_edge_ind]- current_point = (- line[current_edge_ind]- + (line[current_edge_ind + 1] - line[current_edge_ind])- * end_shift_ratio- )+ current_point = line[current_edge_ind] + (line[current_edge_ind + 1] - line[current_edge_ind]) * end_shift_ratioresampled_line.append(current_point)resampled_line.append(line[-1])resampled_line = np.array(resampled_line)@@ -387,9 +352,7 @@ class CropByPolys:resample_top_line = self.sample_points_on_bbox_bp(top_line, 15)resample_bot_line = self.sample_points_on_bbox_bp(bot_line, 15)- sideline_mean_shift = np.mean(resample_top_line, axis=0) - np.mean(- resample_bot_line, axis=0- )+ sideline_mean_shift = np.mean(resample_top_line, axis=0) - np.mean(resample_bot_line, axis=0)if sideline_mean_shift[1] > 0:resample_bot_line, resample_top_line = resample_top_line, resample_bot_linerectifier = AutoRectifier()diff --git a/mineru/model/ocr/seal_det_warp.py b/mineru/model/ocr/seal_det_warp.pyindex aa6318a7..c15b9684 100644--- a/mineru/model/ocr/seal_det_warp.py+++ b/mineru/model/ocr/seal_det_warp.py@@ -12,11 +12,13 @@# See the License for the specific language governing permissions and# limitations under the License.+from docvortex.image import perspective_matrix, warp_image+import copy-import cv2import numpy as npfrom loguru import logger+from PIL import Image, ImageDrawfrom numpy import arctan, cos, sin, sqrt@@ -30,8 +32,10 @@ def Homography(ratio_height=1.0,):if interpolation is None:- interpolation = cv2.INTER_CUBIC+ interpolation = "cubic"+ if isinstance(interpolation, int):+ interpolation = {0: "nearest", 1: "linear", 2: "cubic", 3: "area", 4: "lanczos4"}[interpolation]_points = np.array(img_points).reshape(-1, 2).astype(np.float32)expand_x = int(0.5 * world_width * (ratio_width - 1))@@ -47,15 +51,9 @@ def Homography(img_crop_width = int(world_width * ratio_width)img_crop_height = int(world_height * ratio_height)- M = cv2.getPerspectiveTransform(_points, pts_std)+ M = perspective_matrix(_points, pts_std)- dst_img = cv2.warpPerspective(- image,- M,- (img_crop_width, img_crop_height),- borderMode=cv2.BORDER_CONSTANT,- flags=interpolation,- )+ dst_img = warp_image(image, M, (img_crop_width, img_crop_height), border="constant", interpolation=interpolation)return dst_img@@ -73,7 +71,7 @@ class PlanB:square=False,):if interpolation is None:- interpolation = cv2.INTER_LINEAR+ interpolation = "linear"h, w = image.shape[:2]_points = np.array(points).reshape(-1, 2).astype(np.float32)x_min = int(np.min(_points[:, 0]))@@ -145,9 +143,7 @@ class CurveTextRectifier:fv = 100matT = np.zeros((4, 4))- matT[0, 0] = cos(angle_z) * cos(angle_y) - sin(angle_z) * sin(angle_x1) * sin(- angle_y- )+ matT[0, 0] = cos(angle_z) * cos(angle_y) - sin(angle_z) * sin(angle_x1) * sin(angle_y)matT[0, 1] = cos(angle_z) * sin(angle_y) * sin(angle_x2) - sin(angle_z) * (cos(angle_x1) * cos(angle_x2) - sin(angle_x1) * cos(angle_y) * sin(angle_x2))@@ -155,9 +151,7 @@ class CurveTextRectifier:cos(angle_x1) * sin(angle_x2) + sin(angle_x1) * cos(angle_y) * cos(angle_x2))matT[0, 3] = optic_x- matT[1, 0] = sin(angle_z) * cos(angle_y) + cos(angle_z) * sin(angle_x1) * sin(- angle_y- )+ matT[1, 0] = sin(angle_z) * cos(angle_y) + cos(angle_z) * sin(angle_x1) * sin(angle_y)matT[1, 1] = sin(angle_z) * sin(angle_y) * sin(angle_x2) + cos(angle_z) * (cos(angle_x1) * cos(angle_x2) - sin(angle_x1) * cos(angle_y) * sin(angle_x2))@@ -166,12 +160,8 @@ class CurveTextRectifier:)matT[1, 3] = optic_ymatT[2, 0] = -cos(angle_x1) * sin(angle_y)- matT[2, 1] = cos(angle_x1) * cos(angle_y) * sin(angle_x2) + sin(angle_x1) * cos(- angle_x2- )- matT[2, 2] = cos(angle_x1) * cos(angle_y) * cos(angle_x2) - sin(angle_x1) * sin(- angle_x2- )+ matT[2, 1] = cos(angle_x1) * cos(angle_y) * sin(angle_x2) + sin(angle_x1) * cos(angle_x2)+ matT[2, 2] = cos(angle_x1) * cos(angle_y) * cos(angle_x2) - sin(angle_x1) * sin(angle_x2)matT[2, 3] = optic_zmatT[3, 0] = 0matT[3, 1] = 0@@ -199,9 +189,7 @@ class CurveTextRectifier:adjusted_points[:, 0] = _points[:, 1]adjusted_points[:, 1] = org_h - _points[:, 0] - 1- _image_coord, _world_coord, _new_image_size = self.horizontal_text_process(- adjusted_points- )+ _image_coord, _world_coord, _new_image_size = self.horizontal_text_process(adjusted_points)image_coord = _points.reshape(1, -1, 2)world_coord = np.zeros(_world_coord.shape, dtype=np.float32)@@ -229,10 +217,7 @@ class CurveTextRectifier:d = sqrt(ydx**2 + ydy**2)dy_list.append(d)- dx_list = [- (dx_list[i] + dx_list[len(dx_list) - 1 - i]) / 2- for i in range(len(dx_list) // 2)- ]+ dx_list = [(dx_list[i] + dx_list[len(dx_list) - 1 - i]) / 2 for i in range(len(dx_list) // 2)]height = np.around(np.mean(dy_list))@@ -319,30 +304,18 @@ class CurveTextRectifier:+ (K[0, 2] + K[2, 0]) * D0 * D2+ (K[1, 2] + K[2, 1]) * D1 * D2)- ratio_b = (- (K[0, 3] + K[3, 0]) * D0- + (K[1, 3] + K[3, 1]) * D1- + (K[2, 3] + K[3, 2]) * D2- )+ ratio_b = (K[0, 3] + K[3, 0]) * D0 + (K[1, 3] + K[3, 1]) * D1 + (K[2, 3] + K[3, 2]) * D2ratio_c = K[3, 3] * np.ones(ratio_b.shape)delta = ratio_b * ratio_b - 4 * ratio_a * ratio_ct = np.zeros(delta.shape)t[ratio_a == 0] = -ratio_c[ratio_a == 0] / ratio_b[ratio_a == 0]- t[ratio_a != 0] = (-ratio_b[ratio_a != 0] + sqrt(delta[ratio_a != 0])) / (- 2 * ratio_a[ratio_a != 0]- )+ t[ratio_a != 0] = (-ratio_b[ratio_a != 0] + sqrt(delta[ratio_a != 0])) / (2 * ratio_a[ratio_a != 0])t[delta < 0] = 0- P[:, :, 0] = matT[0, 3] + t * (- matT[0, 0] * D0 + matT[0, 1] * D1 + matT[0, 2] * D2- )- P[:, :, 1] = matT[1, 3] + t * (- matT[1, 0] * D0 + matT[1, 1] * D1 + matT[1, 2] * D2- )- P[:, :, 2] = matT[2, 3] + t * (- matT[2, 0] * D0 + matT[2, 1] * D1 + matT[2, 2] * D2- )+ P[:, :, 0] = matT[0, 3] + t * (matT[0, 0] * D0 + matT[0, 1] * D1 + matT[0, 2] * D2)+ P[:, :, 1] = matT[1, 3] + t * (matT[1, 0] * D0 + matT[1, 1] * D1 + matT[1, 2] * D2)+ P[:, :, 2] = matT[2, 3] + t * (matT[2, 0] * D0 + matT[2, 1] * D1 + matT[2, 2] * D2)return P@@ -416,15 +389,9 @@ class CurveTextRectifier:r4 = r2 * r2r6 = r2 * r4- radial_distortion = (1 + k1 * r2 + k2 * r4 + k3 * r6) / (- 1 + k4 * r2 + k5 * r4 + k6 * r6- )- x2 = (- x1 * radial_distortion + p1 * x1y1 + p2 * (r2 + 2 * x12) + s1 * r2 + s2 * r4- )- y2 = (- y1 * radial_distortion + p2 * x1y1 + p1 * (r2 + 2 * y12) + s3 * r2 + s4 * r4- )+ radial_distortion = (1 + k1 * r2 + k2 * r4 + k3 * r6) / (1 + k4 * r2 + k5 * r4 + k6 * r6)+ x2 = x1 * radial_distortion + p1 * x1y1 + p2 * (r2 + 2 * x12) + s1 * r2 + s2 * r4+ y2 = y1 * radial_distortion + p2 * x1y1 + p1 * (r2 + 2 * y12) + s3 * r2 + s4 * r4x3 = tao11 * x2 + tao12 * y2 + tao13y3 = tao21 * x2 + tao22 * y2 + tao23@@ -435,34 +402,27 @@ class CurveTextRectifier:return P- def spatial_transform(- self, image_data, new_image_size, mtx, dist, rvecs, tvecs, interpolation- ):+ def spatial_transform(self, image_data, new_image_size, mtx, dist, rvecs, tvecs, interpolation):+ import cv2+rotation, _ = cv2.Rodrigues(rvecs)world_map = self.virtual_camera_to_world(new_image_size)- image_map = self.world_to_image(- new_image_size, world_map, mtx, dist, rotation, tvecs- )+ image_map = self.world_to_image(new_image_size, world_map, mtx, dist, rotation, tvecs)image_map = image_map.astype(np.float32)- dst = cv2.remap(- image_data, image_map[:, :, 0], image_map[:, :, 1], interpolation- )+ if isinstance(interpolation, str):+ interpolation = {"nearest": 0, "linear": 1, "cubic": 2, "area": 3, "lanczos4": 4}[interpolation]+ dst = cv2.remap(image_data, image_map[:, :, 0], image_map[:, :, 1], interpolation)return dstdef calibrate(self, org_size, image_coord, world_coord):+ """只在明确选择旧相机标定时按需使用 OpenCV,保留历史标定参数。"""+ import cv2+flag = cv2.CALIB_RATIONAL_MODELflag2 = cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_TILTED_MODELflag3 = cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_THIN_PRISM_MODEL- flag4 = (- cv2.CALIB_RATIONAL_MODEL- | cv2.CALIB_ZERO_TANGENT_DIST- | cv2.CALIB_FIX_ASPECT_RATIO- )- flag5 = (- cv2.CALIB_RATIONAL_MODEL- | cv2.CALIB_TILTED_MODEL- | cv2.CALIB_ZERO_TANGENT_DIST- )+ flag4 = cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_ZERO_TANGENT_DIST | cv2.CALIB_FIX_ASPECT_RATIO+ flag5 = cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_TILTED_MODEL | cv2.CALIB_ZERO_TANGENT_DISTflag6 = cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_FIX_ASPECT_RATIOflag_list = [flag2, flag3, flag4, flag5, flag6]@@ -502,7 +462,7 @@ class CurveTextRectifier:ratio_height=1.0,):if interpolation is None:- interpolation = cv2.INTER_LINEAR+ interpolation = "linear"_img_points = img_points.reshape(-1, 2)_obj_points = obj_points.reshape(-1, 3)@@ -542,9 +502,7 @@ class CurveTextRectifier:width_list.append(_w)height_list.append(_h)- rectified_image = np.zeros((np.max(height_list), sum(width_list), 3)).astype(- np.uint8- )+ rectified_image = np.zeros((np.max(height_list), sum(width_list), 3)).astype(np.uint8)st = 0for homo_img, w, h in zip(homo_img_list, width_list, height_list):@@ -566,7 +524,7 @@ class CurveTextRectifier:mode="calibration",):if interpolation is None:- interpolation = cv2.INTER_LINEAR+ interpolation = "linear"org_h, org_w = image_data.shape[:2]org_size = (org_w, org_h)@@ -574,26 +532,18 @@ class CurveTextRectifier:is_horizontal_text = self.horizontal_text_estimate(points)if is_horizontal_text:- image_coord, world_coord, new_image_size = self.horizontal_text_process(- points- )+ image_coord, world_coord, new_image_size = self.horizontal_text_process(points)else:- image_coord, world_coord, new_image_size = self.vertical_text_process(- points, org_size- )+ image_coord, world_coord, new_image_size = self.vertical_text_process(points, org_size)if mode.lower() == "calibration":- ret, mtx, dist, rvecs, tvecs = self.calibrate(- org_size, image_coord, world_coord- )+ ret, mtx, dist, rvecs, tvecs = self.calibrate(org_size, image_coord, world_coord)st_size = (int(new_image_size[0] * ratio_width),int(new_image_size[1] * ratio_height),)- dst = self.spatial_transform(- image_data, st_size, mtx, dist[0], rvecs[0], tvecs[0], interpolation- )+ dst = self.spatial_transform(image_data, st_size, mtx, dist[0], rvecs[0], tvecs[0], interpolation)elif mode.lower() == "homography":ret = 0.01dst = self.dc_homo(@@ -606,9 +556,7 @@ class CurveTextRectifier:ratio_height=1.0,)else:- raise ValueError(- 'mode must be ["calibration", "homography"], but got {}'.format(mode)- )+ raise ValueError('mode must be ["calibration", "homography"], but got {}'.format(mode))return dst, ret@@ -619,11 +567,9 @@ class AutoRectifier:self.curveTextRectifier = CurveTextRectifier()@staticmethod- def get_rotate_crop_image(- img, points, interpolation=None, ratio_width=1.0, ratio_height=1.0- ):+ def get_rotate_crop_image(img, points, interpolation=None, ratio_width=1.0, ratio_height=1.0):if interpolation is None:- interpolation = cv2.INTER_CUBIC+ interpolation = "cubic"h, w = img.shape[:2]_points = np.array(points).reshape(-1, 2).astype(np.float32)@@ -669,31 +615,15 @@ class AutoRectifier:return dst_imgdef visualize(self, image_data, points_list):- visualization = image_data.copy()-- for box in points_list:- box = np.array(box).reshape(-1, 2).astype(np.int32)- cv2.drawContours(- visualization, [np.array(box).reshape((-1, 1, 2))], -1, (0, 0, 255), 2- )- for i, p in enumerate(box):- if i != 0:- cv2.circle(- visualization,- tuple(p),- radius=1,- color=(255, 0, 0),- thickness=2,- )- else:- cv2.circle(- visualization,- tuple(p),- radius=1,- color=(255, 255, 0),- thickness=2,- )- return visualization+ """使用 Pillow 标注印章矫正点,返回与输入同通道顺序的诊断图。"""+ with Image.fromarray(image_data[:, :, ::-1]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for box in points_list:+ points = [tuple(map(int, xy)) for xy in np.asarray(box).reshape(-1, 2)]+ draw.line(points + points[:1], fill=(255, 0, 0), width=2)+ for index, (x, y) in enumerate(points):+ draw.ellipse((x - 1, y - 1, x + 1, y + 1), outline=(0, 255, 255) if index == 0 else (0, 0, 255), width=2)+ return np.asarray(canvas)[:, :, ::-1].copy()def __call__(self,@@ -706,15 +636,13 @@ class AutoRectifier:mode="calibration",):if interpolation is None:- interpolation = cv2.INTER_LINEAR+ interpolation = "linear"_points = np.array(points).reshape(-1, 2)if len(_points) >= self.npoints and len(_points) % 2 == 0:try:curveTextRectifier = CurveTextRectifier()- dst_img, loss = curveTextRectifier(- image_data, points, interpolation, ratio_width, ratio_height, mode- )+ dst_img, loss = curveTextRectifier(image_data, points, interpolation, ratio_width, ratio_height, mode)if loss >= 2:img_list, loss_list = [dst_img], [loss]_dst_img, _loss = PlanB()(@@ -752,18 +680,12 @@ class AutoRectifier:loss))- dst_img = self.get_rotate_crop_image(- image_data, points, interpolation, ratio_width, ratio_height- )+ dst_img = self.get_rotate_crop_image(image_data, points, interpolation, ratio_width, ratio_height)except Exception as e:logger.warning(f"Exception caught: {e}")- dst_img = self.get_rotate_crop_image(- image_data, points, interpolation, ratio_width, ratio_height- )+ dst_img = self.get_rotate_crop_image(image_data, points, interpolation, ratio_width, ratio_height)else:- dst_img = self.get_rotate_crop_image(- image_data, _points, interpolation, ratio_width, ratio_height- )+ dst_img = self.get_rotate_crop_image(image_data, _points, interpolation, ratio_width, ratio_height)return dst_img@@ -785,7 +707,7 @@ class AutoRectifier:if not isinstance(points, list):raise ValueErrorif interpolation is None:- interpolation = cv2.INTER_LINEAR+ interpolation = "linear"if ratio_width < 1.0 or ratio_height < 1.0:raise ValueError(@@ -794,9 +716,7 @@ class AutoRectifier:)if mode.lower() != "calibration" and mode.lower() != "homography":- raise ValueError(- 'mode must be ["calibration", "homography"], but got {}'.format(mode)- )+ raise ValueError('mode must be ["calibration", "homography"], but got {}'.format(mode))if mode.lower() == "homography" and ratio_width != 1.0 and ratio_height != 1.0:raise ValueError(diff --git a/mineru/model/runtime/hybrid.py b/mineru/model/runtime/hybrid.pyindex c7f7bdae..46bb57f8 100644--- a/mineru/model/runtime/hybrid.py+++ b/mineru/model/runtime/hybrid.py@@ -16,13 +16,13 @@ from ...utils.timing import stage_timerfrom ..ocr.language import normalize_ocr_model_langfrom ..ocr.resources import PPOCRV6_DICT_PATHfrom ..registry import MINERU_4_MODELS_ONNX, small_model_repo-from ..table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel-from ..table.cls.paddle_table_cls import PaddleTableClsModel-from ..table.rec.slanet_plus.main import PaddleTableModel-from ..table.rec.unet_table.main import UnetTableModelfrom .contracts import AtomicModelNameif TYPE_CHECKING:+ from ..table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel+ from ..table.cls.paddle_table_cls import PaddleTableClsModel+ from ..table.rec.slanet_plus.main import PaddleTableModel+ from ..table.rec.unet_table.main import UnetTableModelfrom ..layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModelfrom ..mfr.pp_formulanet.predict_formula import FormulaRecognizerfrom ..ocr.pytorch_paddle import PytorchPaddleOCR@@ -84,6 +84,8 @@ def table_orientation_cls_model_init(small_backend: str | None = None, device: str | None = None) -> MineruTableOrientationClsModel:"""初始化表格方向分类包装器,并注入适配方向检测的 OCR 引擎。"""+ from ..table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel+atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(atom_model_name=AtomicModelName.OCR,@@ -100,6 +102,8 @@ def table_orientation_cls_model_init(def table_cls_model_init(small_backend: str | None = None) -> PaddleTableClsModel:"""初始化有线与无线表格类型分类模型。"""+ from ..table.cls.paddle_table_cls import PaddleTableClsModel+return PaddleTableClsModel(model_path=str(small_model_repo(small_backend).paddle_table_cls.ensure()))@@ -107,6 +111,8 @@ def wired_table_model_init(lang: str | None = None, *, small_backend: str | None = None, device: str | None = None) -> UnetTableModel:"""初始化有线表格识别模型,并注入指定语言的 OCR 引擎。"""+ from ..table.rec.unet_table.main import UnetTableModel+atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(atom_model_name=AtomicModelName.OCR,@@ -125,6 +131,8 @@ def wireless_table_model_init(lang: str | None = None, *, small_backend: str | None = None, device: str | None = None) -> PaddleTableModel:"""初始化无线表格识别模型,并注入指定语言的 OCR 引擎。"""+ from ..table.rec.slanet_plus.main import PaddleTableModel+atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(atom_model_name=AtomicModelName.OCR,diff --git a/mineru/model/table/cls/mineru_table_ori_cls.py b/mineru/model/table/cls/mineru_table_ori_cls.pyindex 17d1b828..b7fb12c0 100644--- a/mineru/model/table/cls/mineru_table_ori_cls.py+++ b/mineru/model/table/cls/mineru_table_ori_cls.py@@ -4,11 +4,12 @@ from collections import defaultdictimport inspectfrom typing import List, Dict-import cv2import numpy as npfrom loguru import loggerfrom PIL import Image+from ...ocr.image import rgb_to_bgr+# 旋转候选门控回到旧规则,先尽量召回疑似旋转表,再由 OCR rec 评分决定最终角度。ROTATED_TEXT_ASPECT_RATIO_THRESHOLD = 0.8@@ -45,7 +46,7 @@ class MineruTableOrientationClsModel:def _to_bgr_table_image(cls, table_info: Dict) -> np.ndarray:"""从表格信息中读取 table_img,并转换为 OCR detector 使用的 BGR 图像。"""table_img = cls._to_numpy_image(table_info["table_img"])- return cv2.cvtColor(table_img, cv2.COLOR_RGB2BGR)+ return rgb_to_bgr(table_img)@staticmethoddef _ceil_to_stride(value: int, stride: int) -> int:@@ -93,9 +94,9 @@ class MineruTableOrientationClsModel:def _rotate_image_by_label(img: np.ndarray, label: str) -> np.ndarray:"""按候选角度旋转图像,0 度返回副本以避免后续误改原图。"""if label == "270":- return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)+ return np.rot90(img, k=-1).copy(order="C")if label == "90":- return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)+ return np.rot90(img, k=1).copy(order="C")return img.copy()@staticmethoddiff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.pyindex 07e412cf..d9e680c7 100644--- a/mineru/model/table/cls/paddle_table_cls.py+++ b/mineru/model/table/cls/paddle_table_cls.py@@ -1,5 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.-import cv2++from docvortex.image import resize_imageimport numpy as npfrom PIL import Imagefrom tqdm import tqdm@@ -23,11 +24,12 @@ class PaddleTableClsModel:def preprocess(self, input_img):# 放大图片,使其最短边长为256+h, w = input_img.shape[:2]scale = 256 / min(h, w)h_resize = round(h * scale)w_resize = round(w * scale)- img = cv2.resize(input_img, (w_resize, h_resize), interpolation=1)+ img = resize_image(input_img, (w_resize, h_resize), interpolation='linear')# 调整为224*224的正方形h, w = img.shape[:2]cw, ch = 224, 224@@ -39,7 +41,7 @@ class PaddleTableClsModel:raise ValueError(f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch}).")img = img[y1:y2, x1:x2, ...]# 正则化- split_im = list(cv2.split(img))+ split_im = [img[:, :, channel].copy() for channel in range(img.shape[2])]std = [0.229, 0.224, 0.225]scale = 0.00392156862745098mean = [0.485, 0.456, 0.406]@@ -49,7 +51,7 @@ class PaddleTableClsModel:split_im[c] = split_im[c].astype(np.float32)split_im[c] *= alpha[c]split_im[c] += beta[c]- img = cv2.merge(split_im)+ img = np.stack(split_im, axis=2)# 5. 转换为 CHW 格式img = img.transpose((2, 0, 1))imgs = [img]@@ -87,6 +89,7 @@ class PaddleTableClsModel:return batchesdef batch_preprocess(self, imgs):+res_imgs = []for img in imgs:img = np.asarray(img)@@ -95,7 +98,7 @@ class PaddleTableClsModel:scale = 256 / min(h, w)h_resize = round(h * scale)w_resize = round(w * scale)- img = cv2.resize(img, (w_resize, h_resize), interpolation=1)+ img = resize_image(img, (w_resize, h_resize), interpolation='linear')# 调整为224*224的正方形h, w = img.shape[:2]cw, ch = 224, 224@@ -107,7 +110,7 @@ class PaddleTableClsModel:raise ValueError(f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch}).")img = img[y1:y2, x1:x2, ...]# 正则化- split_im = list(cv2.split(img))+ split_im = [img[:, :, channel].copy() for channel in range(img.shape[2])]std = [0.229, 0.224, 0.225]scale = 0.00392156862745098mean = [0.485, 0.456, 0.406]@@ -117,7 +120,7 @@ class PaddleTableClsModel:split_im[c] = split_im[c].astype(np.float32)split_im[c] *= alpha[c]split_im[c] += beta[c]- img = cv2.merge(split_im)+ img = np.stack(split_im, axis=2)# 5. 转换为 CHW 格式img = img.transpose((2, 0, 1))res_imgs.append(img)diff --git a/mineru/model/table/rec/slanet_plus/main.py b/mineru/model/table/rec/slanet_plus/main.pyindex abf465db..25b22c25 100644--- a/mineru/model/table/rec/slanet_plus/main.py+++ b/mineru/model/table/rec/slanet_plus/main.py@@ -7,11 +7,11 @@ from dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple, Union-import cv2import numpy as npfrom loguru import loggerfrom tqdm import tqdm+from ....ocr.image import rgb_to_bgrfrom ....registry import small_model_repofrom .matcher import TableMatchfrom .table_structure import TableStructurer@@ -158,7 +158,7 @@ class PaddleTableModel(object):self.ocr_engine = ocr_enginedef predict(self, image, ocr_result=None):- bgr_image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)+ bgr_image = rgb_to_bgr(np.asarray(image))# Continue with OCR on potentially rotated imageif ocr_result is None:@@ -187,7 +187,7 @@ class PaddleTableModel(object):with tqdm(total=len(table_res_list), desc="Table-wireless Predict") as pbar:for index in range(0, len(table_res_list), batch_size):batch_imgs = [- cv2.cvtColor(np.asarray(table_res_list[i]["table_img"]), cv2.COLOR_RGB2BGR)+ rgb_to_bgr(np.asarray(table_res_list[i]["table_img"]))for i in range(index, min(index + batch_size, len(table_res_list)))]batch_ocrs = [diff --git a/mineru/model/table/rec/slanet_plus/table_structure_utils.py b/mineru/model/table/rec/slanet_plus/table_structure_utils.pyindex 883cff3d..0ddb4fea 100644--- a/mineru/model/table/rec/slanet_plus/table_structure_utils.py+++ b/mineru/model/table/rec/slanet_plus/table_structure_utils.py@@ -11,11 +11,12 @@# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.++from docvortex.image import resize_imageimport tracebackfrom pathlib import Pathfrom typing import Any, Dict, List, Tuple, Union-import cv2import numpy as npfrom loguru import loggerfrom onnxruntime import GraphOptimizationLevel, SessionOptions@@ -322,12 +323,13 @@ class ResizeTableImage:self.infer_mode = infer_modedef __call__(self, data):+img = data["image"]height, width = img.shape[0:2]ratio = self.max_len / (max(height, width) * 1.0)resize_h = int(height * ratio)resize_w = int(width * ratio)- resize_img = cv2.resize(img, (resize_w, resize_h))+ resize_img = resize_image(img, (resize_w, resize_h))if self.resize_bboxes and not self.infer_mode:data["bboxes"] = data["bboxes"] * ratiodata["image"] = resize_imgdiff --git a/mineru/model/table/rec/unet_table/main.py b/mineru/model/table/rec/unet_table/main.pyindex 36e75fd8..f9bc3dee 100644--- a/mineru/model/table/rec/unet_table/main.py+++ b/mineru/model/table/rec/unet_table/main.py@@ -6,13 +6,13 @@ import tracebackfrom dataclasses import asdict, dataclassfrom typing import Any, Dict, List, Optional, Union-import cv2import numpy as npfrom bs4 import BeautifulSoupfrom docvortex.assets import calculate_contrastfrom loguru import loggerfrom PIL import Image+from ....ocr.image import rgb_to_bgrfrom ....registry import small_model_repofrom .table_recover import TableRecoverfrom .table_structure_unet import TSRUnet@@ -173,7 +173,7 @@ class WiredTableRecognition:cell_box_map: Dict[int, List[str]],) -> Dict[int, List[Any]]:"""找到poly对应为空的框,尝试将直接将poly框直接送到识别中"""- bgr_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)+ bgr_img = rgb_to_bgr(img)img_crop_info_list = []img_crop_list = []for i in range(sorted_polygons.shape[0]):@@ -275,7 +275,7 @@ class UnetTableModel:np_img = input_imgelse:raise ValueError("Input must be a pillow object or a numpy array.")- bgr_img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)+ bgr_img = rgb_to_bgr(np_img)if ocr_result is None:ocr_result = self.ocr_engine.ocr(bgr_img)[0]diff --git a/mineru/model/table/rec/unet_table/table_structure_unet.py b/mineru/model/table/rec/unet_table/table_structure_unet.pyindex 14f0f6fb..af7b8c77 100644--- a/mineru/model/table/rec/unet_table/table_structure_unet.py+++ b/mineru/model/table/rec/unet_table/table_structure_unet.py@@ -1,9 +1,10 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import contour_area, morphology, trace_contours, minimum_rectangle, resize_image, rotation_matrix, transform_points, warp_imageimport copyimport mathfrom typing import Optional, Dict, Any, Tuple-import cv2import numpy as npfrom .utils import OrtInferSession, resize_img@@ -59,15 +60,16 @@ class TSRUnet:return polygons, rotated_polygonsdef preprocess(self, img) -> Dict[str, Any]:+scale = (self.inp_height, self.inp_width)img, _, _ = resize_img(img, scale, True)img = img.copy().astype(np.float32)assert img.dtype != np.uint8mean = np.float64(self.mean.reshape(1, -1))stdinv = 1 / np.float64(self.std.reshape(1, -1))- cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace- cv2.subtract(img, mean, img) # inplace- cv2.multiply(img, stdinv, img) # inplace+ img[:] = img[:, :, ::-1] # 原位交换通道,保留输入数组所有权。+ np.subtract(img, mean, out=img, casting="unsafe") # 保留 double 中间计算再量化为 float32。+ np.multiply(img, stdinv, out=img, casting="unsafe")img = img.transpose(2, 0, 1)images = img[None, :]return {"img": images}@@ -78,6 +80,7 @@ class TSRUnet:return resultdef postprocess(self, img, pred, **kwargs):+row = kwargs.get("row", 50) if kwargs else 50col = kwargs.get("col", 30) if kwargs else 30h_lines_threshold = kwargs.get("h_lines_threshold", 100) if kwargs else 100@@ -107,19 +110,17 @@ class TSRUnet:hpred[wherev] = 0vpred[whereh] = 0- hpred = cv2.resize(hpred, (ori_shape[1], ori_shape[0]))- vpred = cv2.resize(vpred, (ori_shape[1], ori_shape[0]))+ hpred = resize_image(hpred, (ori_shape[1], ori_shape[0]))+ vpred = resize_image(vpred, (ori_shape[1], ori_shape[0]))h, w = pred.shapehors_k = int(math.sqrt(w) * 1.2)vert_k = int(math.sqrt(h) * 1.2)- hkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (hors_k, 1))- vkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, vert_k))- vpred = cv2.morphologyEx(- vpred, cv2.MORPH_CLOSE, vkernel, iterations=1- ) # 先膨胀后腐蚀的过程+ hkernel = (hors_k, 1)+ vkernel = (1, vert_k)+ vpred = morphology(vpred, vkernel, operation="close") # 先膨胀后腐蚀的过程if morph_close:- hpred = cv2.morphologyEx(hpred, cv2.MORPH_CLOSE, hkernel, iterations=1)+ hpred = morphology(hpred, hkernel, operation="close")colboxes = get_table_line(vpred, axis=1, lineW=col) # 竖线rowboxes = get_table_line(hpred, axis=0, lineW=row) # 横线rboxes_row_, rboxes_col_ = [], []@@ -159,11 +160,12 @@ class TSRUnet:def cal_rotate_angle(self, tmp):# 计算最外侧的旋转框- contours, _ = cv2.findContours(tmp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)++ contours = trace_contours(tmp, external_only=True)if not contours:return 0- largest_contour = max(contours, key=cv2.contourArea)- rect = cv2.minAreaRect(largest_contour)+ largest_contour = max(contours, key=contour_area)+ rect = minimum_rectangle(largest_contour)# 计算旋转角度angle = rect[2]if angle < -45:@@ -174,16 +176,15 @@ class TSRUnet:def rotate_image(self, image, angle):# 获取图像的中心点+(h, w) = image.shape[:2]center = (w // 2, h // 2)# 计算旋转矩阵- M = cv2.getRotationMatrix2D(center, angle, 1.0)+ M = rotation_matrix(center, angle, 1.0)# 进行旋转- rotated_image = cv2.warpAffine(- image, M, (w, h), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_REPLICATE- )+ rotated_image = warp_image(image, M, (w, h), interpolation='nearest', border='replicate')return rotated_image@@ -191,15 +192,16 @@ class TSRUnet:self, polygons: np.ndarray, angle: float, img_shape: tuple) -> np.ndarray:# 将多边形旋转回原始位置+(h, w) = img_shapecenter = (w // 2, h // 2)- M_inv = cv2.getRotationMatrix2D(center, -angle, 1.0)+ M_inv = rotation_matrix(center, -angle, 1.0)# 将 (N, 8) 转换为 (N, 4, 2)polygons_reshaped = polygons.reshape(-1, 4, 2)# 批量逆旋转- unrotated_polygons = cv2.transform(polygons_reshaped, M_inv)+ unrotated_polygons = transform_points(polygons_reshaped, M_inv)# 将 (N, 4, 2) 转换回 (N, 8)unrotated_polygons = unrotated_polygons.reshape(-1, 8)diff --git a/mineru/model/table/rec/unet_table/utils.py b/mineru/model/table/rec/unet_table/utils.pyindex 6a01aa0e..c77e60c5 100644--- a/mineru/model/table/rec/unet_table/utils.py+++ b/mineru/model/table/rec/unet_table/utils.py@@ -1,15 +1,15 @@# Copyright (c) Opendatalab. All rights reserved.-import os++from docvortex.image import resize_imageimport tracebackfrom io import BytesIOfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Union-import cv2import loguruimport numpy as npfrom onnxruntime import GraphOptimizationLevel, SessionOptions-from PIL import Image, UnidentifiedImageError+from PIL import Image, ImageDraw, UnidentifiedImageErrorfrom ....runtime.onnx import configure_ort_threads, table_ort_session@@ -94,12 +94,12 @@ class LoadImage:def convert_img(self, img: np.ndarray):if img.ndim == 2:- return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ return np.repeat(img[:, :, None], 3, axis=2)if img.ndim == 3:channel = img.shape[2]if channel == 1:- return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ return np.repeat(img, 3, axis=2)if channel == 2:return self.cvt_two_to_three(img)@@ -108,7 +108,7 @@ class LoadImage:return self.cvt_four_to_three(img)if channel == 3:- return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)+ return img[:, :, ::-1].copy(order="C")raise LoadImageError(f"The channel({channel}) of the img is not in [1, 2, 3, 4]")@@ -117,28 +117,30 @@ class LoadImage:@staticmethoddef cvt_four_to_three(img: np.ndarray) -> np.ndarray:"""RGBA → BGR"""- r, g, b, a = cv2.split(img)- new_img = cv2.merge((b, g, r))- not_a = cv2.bitwise_not(a)- not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)+ r, g, b, a = (img[:, :, index] for index in range(4))+ new_img = np.stack((b, g, r), axis=2)++ not_a = np.bitwise_not(a)+ not_a = np.repeat(not_a[:, :, None], 3, axis=2)- new_img = cv2.bitwise_and(new_img, new_img, mask=a)- new_img = cv2.add(new_img, not_a)+ new_img = np.where(a[:, :, None] != 0, new_img, 0)+ new_img = np.minimum(new_img.astype(np.uint16) + not_a, 255).astype(np.uint8)return new_img@staticmethoddef cvt_two_to_three(img: np.ndarray) -> np.ndarray:"""gray + alpha → BGR"""+img_gray = img[..., 0]- img_bgr = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)+ img_bgr = np.repeat(img_gray[:, :, None], 3, axis=2)img_alpha = img[..., 1]- not_a = cv2.bitwise_not(img_alpha)- not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)+ not_a = np.bitwise_not(img_alpha)+ not_a = np.repeat(not_a[:, :, None], 3, axis=2)- new_img = cv2.bitwise_and(img_bgr, img_bgr, mask=img_alpha)- new_img = cv2.add(new_img, not_a)+ new_img = np.where(img_alpha[:, :, None] != 0, img_bgr, 0)+ new_img = np.minimum(new_img.astype(np.uint16) + not_a, 255).astype(np.uint8)return new_img@staticmethod@@ -173,14 +175,6 @@ if Image is not None:"hamming": Image.HAMMING,}-cv2_interp_codes = {- "nearest": cv2.INTER_NEAREST,- "bilinear": cv2.INTER_LINEAR,- "bicubic": cv2.INTER_CUBIC,- "area": cv2.INTER_AREA,- "lanczos": cv2.INTER_LANCZOS4,-}-def resize_img(img, scale, keep_ratio=True):if keep_ratio:@@ -248,9 +242,9 @@ def imresize(img, size, return_scale=False, interpolation="bilinear", out=None,"""h, w = img.shape[:2]if backend is None:- backend = "cv2"- if backend not in ["cv2", "pillow"]:- raise ValueError(f"backend: {backend} is not supported for resize.Supported backends are 'cv2', 'pillow'")+ backend = "numeric"+ if backend not in ["numeric", "cv2", "pillow"]:+ raise ValueError(f"backend: {backend} is not supported for resize.Supported backends are 'numeric', 'pillow'")if backend == "pillow":assert img.dtype == np.uint8, "Pillow backend only support uint8 type"@@ -258,7 +252,18 @@ def imresize(img, size, return_scale=False, interpolation="bilinear", out=None,pil_image = pil_image.resize(size, pillow_interp_codes[interpolation])resized_img = np.array(pil_image)else:- resized_img = cv2.resize(img, size, dst=out, interpolation=cv2_interp_codes[interpolation])++ interpolation_names = {+ "nearest": 'nearest',+ "bilinear": 'linear',+ "bicubic": 'cubic',+ "area": 'area',+ "lanczos": 'lanczos4',+ }+ resized_img = resize_image(img, size, interpolation=interpolation_names[interpolation])+ if out is not None and out.shape == resized_img.shape and out.dtype == resized_img.dtype:+ np.copyto(out, resized_img)+ resized_img = outif not return_scale:return resized_imgelse:@@ -378,68 +383,42 @@ class VisTable:return html_with_borderdef plot_rec_box_with_logic_info(self, img, output_path, logic_points, sorted_polygons):- """- :param img_path- :param output_path- :param logic_points: [row_start,row_end,col_start,col_end]- :param sorted_polygons: [xmin,ymin,xmax,ymax]- :return:- """- # 读取原图- img = cv2.copyMakeBorder(img, 0, 0, 0, 100, cv2.BORDER_CONSTANT, value=[255, 255, 255])- # 绘制 polygons 矩形- for idx, polygon in enumerate(sorted_polygons):- x0, y0, x1, y1 = polygon[0], polygon[1], polygon[2], polygon[3]- x0 = round(x0)- y0 = round(y0)- x1 = round(x1)- y1 = round(y1)- cv2.rectangle(img, (x0, y0), (x1, y1), (0, 0, 255), 1)- # 增大字体大小和线宽- font_scale = 0.9 # 原先是0.5- thickness = 1 # 原先是1- logic_point = logic_points[idx]- cv2.putText(- img,- f"row: {logic_point[0]}-{logic_point[1]}",- (x0 + 3, y0 + 8),- cv2.FONT_HERSHEY_PLAIN,- font_scale,- (0, 0, 255),- thickness,- )- cv2.putText(- img,- f"col: {logic_point[2]}-{logic_point[3]}",- (x0 + 3, y0 + 18),- cv2.FONT_HERSHEY_PLAIN,- font_scale,- (0, 0, 255),- thickness,- )- os.makedirs(os.path.dirname(output_path), exist_ok=True)- # 保存绘制后的图像- self.save_img(output_path, img)+ """在表格诊断图中标注逻辑行列,Pillow 画布只用于调试输出。"""+ padded = np.pad(img, ((0, 0), (0, 100), (0, 0)), constant_values=255)+ with Image.fromarray(padded[:, :, ::-1]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for polygon, logic in zip(sorted_polygons, logic_points):+ x0, y0, x1, y1 = map(round, polygon[:4])+ draw.rectangle((x0, y0, x1, y1), outline=(255, 0, 0), width=1)+ draw.text((x0 + 3, y0 + 8), f"row: {logic[0]}-{logic[1]}", fill=(255, 0, 0))+ draw.text((x0 + 3, y0 + 18), f"col: {logic[2]}-{logic[3]}", fill=(255, 0, 0))+ Path(output_path).parent.mkdir(parents=True, exist_ok=True)+ canvas.save(output_path)@staticmethoddef draw_rectangle(img: np.ndarray, boxes: np.ndarray) -> np.ndarray:- img_copy = img.copy()- for box in boxes.astype(int):- x1, y1, x2, y2 = box- cv2.rectangle(img_copy, (x1, y1), (x2, y2), (255, 0, 0), 2)- return img_copy+ """在独立 BGR 诊断图上绘制矩形,保持原数组所有权。"""+ with Image.fromarray(img[:, :, ::-1]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for box in boxes.astype(int):+ draw.rectangle(tuple(map(int, box)), outline=(0, 0, 255), width=2)+ return np.asarray(canvas)[:, :, ::-1].copy()@staticmethoddef draw_polylines(img: np.ndarray, points) -> np.ndarray:- img_copy = img.copy()- for point in points.astype(int):- point = point.reshape(4, 2)- cv2.polylines(img_copy, [point.astype(int)], True, (255, 0, 0), 2)- return img_copy+ """用 Pillow 标注表格多边形,点序及蓝色诊断语义保持不变。"""+ with Image.fromarray(img[:, :, ::-1]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for point in points.astype(int):+ vertices = [tuple(map(int, xy)) for xy in point.reshape(4, 2)]+ draw.line(vertices + vertices[:1], fill=(0, 0, 255), width=2)+ return np.asarray(canvas)[:, :, ::-1].copy()@staticmethod- def save_img(save_path: Union[str, Path], img: np.ndarray):- cv2.imwrite(str(save_path), img)+ def save_img(save_path: Union[str, Path], img: np.ndarray) -> None:+ """物化 BGR 诊断图后交由 Pillow 编码保存。"""+ with Image.fromarray(img[:, :, ::-1] if img.ndim == 3 else img) as canvas:+ canvas.save(save_path)@staticmethoddef save_html(save_path: Union[str, Path], html: str):diff --git a/mineru/model/table/rec/unet_table/utils_table_line_rec.py b/mineru/model/table/rec/unet_table/utils_table_line_rec.pyindex 126a4677..4f5f00ff 100644--- a/mineru/model/table/rec/unet_table/utils_table_line_rec.py+++ b/mineru/model/table/rec/unet_table/utils_table_line_rec.py@@ -1,8 +1,9 @@# Copyright (c) Opendatalab. All rights reserved.++from docvortex.image import draw_lines as rasterize_lines, label_components, affine_matrix, minimum_rectangle, rectangle_cornersimport mathfrom typing import Iterator-import cv2import numpy as np@@ -35,7 +36,8 @@ class ConnectedComponent:def _iter_connected_component_coords(binary_mask: np.ndarray) -> Iterator[ConnectedComponent]:- """用 OpenCV 提取 8 连通域,避免构造旧版 region 对象带来的额外开销。"""+ """用共享数值内核提取 8 连通域,避免构造旧版 region 对象带来的额外开销。"""+mask = np.asarray(binary_mask)if mask.size == 0:return@@ -44,18 +46,15 @@ def _iter_connected_component_coords(binary_mask: np.ndarray) -> Iterator[Connecif not np.any(mask):return- label_count, labels, stats, _ = cv2.connectedComponentsWithStats(- mask,- connectivity=8,- )+ label_count, labels, stats = label_components(mask)if label_count <= 1:returnfor label_id in range(1, label_count):- left = int(stats[label_id, cv2.CC_STAT_LEFT])- top = int(stats[label_id, cv2.CC_STAT_TOP])- width = int(stats[label_id, cv2.CC_STAT_WIDTH])- height = int(stats[label_id, cv2.CC_STAT_HEIGHT])+ left = int(stats[label_id, 0])+ top = int(stats[label_id, 1])+ width = int(stats[label_id, 2])+ height = int(stats[label_id, 3])yield ConnectedComponent(labels=labels,label_id=label_id,@@ -72,9 +71,7 @@ def transform_preds(coords, center, scale, output_size, rot=0):return target_coords-def get_affine_transform(- center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=0-):+def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=0):if not isinstance(scale, np.ndarray) and not isinstance(scale, list):scale = np.array([scale, scale], dtype=np.float32)@@ -98,9 +95,9 @@ def get_affine_transform(dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])if inv:- trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))+ trans = affine_matrix(np.float32(dst), np.float32(src))else:- trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))+ trans = affine_matrix(np.float32(src), np.float32(dst))return trans@@ -133,15 +130,11 @@ def get_table_line(binimg, axis=0, lineW=10):components = _iter_connected_component_coords(binimg > 0)if axis == 1:lineboxes = [- min_area_rect(component.coords)- for component in components- if component.bbox[2] - component.bbox[0] > lineW+ min_area_rect(component.coords) for component in components if component.bbox[2] - component.bbox[0] > lineW]else:lineboxes = [- min_area_rect(component.coords)- for component in components- if component.bbox[3] - component.bbox[1] > lineW+ min_area_rect(component.coords) for component in components if component.bbox[3] - component.bbox[1] > lineW]return lineboxes@@ -150,8 +143,9 @@ def min_area_rect(coords):"""多边形外接矩形"""- rect = cv2.minAreaRect(coords[:, ::-1])- box = cv2.boxPoints(rect)++ rect = minimum_rectangle(coords[:, ::-1])+ box = rectangle_corners(rect)box = box.reshape((8,)).tolist()box = image_location_sort_box(box)@@ -199,14 +193,8 @@ def calculate_center_rotate_angle(box):x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]cx = (x1 + x3 + x2 + x4) / 4.0cy = (y1 + y3 + y4 + y2) / 4.0- w = (- np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)- + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)- ) / 2- h = (- np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2)- + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)- ) / 2+ w = (np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)) / 2+ h = (np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)) / 2# x = cx-w/2# y = cy-h/2sinA = (h * (x1 - cx) - w * (y1 - cy)) * 1.0 / (h * h + w * w + 1e-10) * 2@@ -251,9 +239,7 @@ def adjust_lines(lines, alph=50, angle=50):if i != j:x3, y3, x4, y4 = lines[j]cx2, cy2 = (x3 + x4) / 2, (y3 + y4) / 2- if (x3 < cx1 < x4 or y3 < cy1 < y4) or (- x1 < cx2 < x2 or y1 < cy2 < y2- ): # 判断两个横线在y方向的投影重不重合+ if (x3 < cx1 < x4 or y3 < cy1 < y4) or (x1 < cx2 < x2 or y1 < cy2 < y2): # 判断两个横线在y方向的投影重不重合continueelse:r = sqrt((x1, y1), (x3, y3))@@ -295,17 +281,21 @@ def draw_lines(im, bboxes, color=(0, 0, 0), lineW=3):"""boxes: bounding boxes"""- tmp = np.copy(im)- c = color- h, w = im.shape[:2]-- for box in bboxes:- x1, y1, x2, y2 = box[:4]- cv2.line(- tmp, (int(x1), int(y1)), (int(x2), int(y2)), c, lineW, lineType=cv2.LINE_AA- )-- return tmp+ # 只在入口复制一次掩码,批量栅格化避免逐条线反复物化整幅图。+ lines = np.asarray(bboxes, dtype=np.float64).reshape(-1, 4).astype(np.int32)+ if im.ndim == 3:+ # 彩色画线仅用于诊断;Pillow 保留 BGR/RGB 转换及原图所有权。+ from PIL import Image, ImageDraw++ order = [2, 1, 0, 3] if im.shape[2] == 4 else [2, 1, 0]+ values = tuple(color) if isinstance(color, (tuple, list)) else (int(color), 0, 0)+ with Image.fromarray(im[:, :, order]) as canvas:+ draw = ImageDraw.Draw(canvas)+ for x1, y1, x2, y2 in lines:+ draw.line((int(x1), int(y1), int(x2), int(y2)), fill=values[:3][::-1], width=lineW)+ return np.asarray(canvas)[:, :, order].copy()+ value = int(color[0]) if isinstance(color, (tuple, list)) else int(color)+ return rasterize_lines(im, lines, value=value, width=lineW, antialias=True)def line_to_line(points1, points2, alpha=10, angle=30):@@ -344,12 +334,11 @@ def line_to_line(points1, points2, alpha=10, angle=30):return points1-def min_area_rect_box(- regions, flag=True, W=0, H=0, filtersmall=False, adjust_box=False-):+def min_area_rect_box(regions, flag=True, W=0, H=0, filtersmall=False, adjust_box=False):"""多边形外接矩形"""+boxes = []for region in regions:region_bbox_area = getattr(region, "bbox_area", None)@@ -357,9 +346,9 @@ def min_area_rect_box(region_bbox_area = region.area_bboxif region_bbox_area > H * W * 3 / 4: # 过滤大的单元格continue- rect = cv2.minAreaRect(region.coords[:, ::-1])+ rect = minimum_rectangle(region.coords[:, ::-1])- box = cv2.boxPoints(rect)+ box = rectangle_corners(rect)box = box.reshape((8,)).tolist()box = image_location_sort_box(box)x1, y1, x2, y2, x3, y3, x4, y4 = box@@ -376,33 +365,28 @@ def min_area_rect_box(# boxes.append([x1, y1, x2, y2, x3, y3, x4, y4])# else:if w * h < 0.5 * W * H:- if filtersmall and (- w < 15 or h < 15- ): # or w / h > 30 or h / w > 30): # 过滤小的单元格+ if filtersmall and (w < 15 or h < 15): # or w / h > 30 or h / w > 30): # 过滤小的单元格continueboxes.append([x1, y1, x2, y2, x3, y3, x4, y4])return boxes-def min_area_rect_box_from_components(- components, flag=True, W=0, H=0, filtersmall=False, adjust_box=False-):+def min_area_rect_box_from_components(components, flag=True, W=0, H=0, filtersmall=False, adjust_box=False):"""对 OpenCV 连通域组件执行与 min_area_rect_box 相同的过滤和外接框计算。"""+boxes = []for component in components:if component.bbox_area > H * W * 3 / 4: # 过滤大的单元格continue- rect = cv2.minAreaRect(component.coords[:, ::-1])+ rect = minimum_rectangle(component.coords[:, ::-1])- box = cv2.boxPoints(rect)+ box = rectangle_corners(rect)box = box.reshape((8,)).tolist()box = image_location_sort_box(box)x1, y1, x2, y2, x3, y3, x4, y4 = boxangle, w, h, cx, cy = calculate_center_rotate_angle(box)if w * h < 0.5 * W * H:- if filtersmall and (- w < 15 or h < 15- ): # or w / h > 30 or h / w > 30): # 过滤小的单元格+ if filtersmall and (w < 15 or h < 15): # or w / h > 30 or h / w > 30): # 过滤小的单元格continueboxes.append([x1, y1, x2, y2, x3, y3, x4, y4])return boxesdiff --git a/pyproject.toml b/pyproject.tomlindex f17679ef..8a19cc50 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,7 +39,7 @@ classifiers = ["Programming Language :: Python :: 3.14",]dependencies = [- "docvortex>=0.5.4,<1",+ "docvortex>=0.5.12,<1","gradio>=6.8,<7","mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'","mineru-vl-utils>=2.0.5,<3",@@ -58,7 +58,6 @@ dependencies = ["huggingface-hub[hf_xet]>=0.32.4","filelock>=3.0.0","json-repair>=0.46.2",- "opencv-python>=4.11.0.86","openai>=1.70.0,<3","beautifulsoup4>=4.13.5,<5","tinycss2>=1.5.1,<2",diff --git a/tests/benchmarks/opencv_paths.py b/tests/benchmarks/opencv_paths.pynew file mode 100644index 00000000..13127fb3--- /dev/null+++ b/tests/benchmarks/opencv_paths.py@@ -0,0 +1,256 @@+"""隔离加载指定源码,记录真实档位输出、图像边界及性能。"""++import argparse+import hashlib+import json+import os+import re+import sys+import time+from io import BytesIO+from pathlib import Path+from typing import Any, Callable+from zipfile import ZipFile+++def main() -> None:+ """保护 spawn 子进程入口,仅主进程执行解析与模型初始化。"""+ startup_started = time.perf_counter()+ arg = argparse.ArgumentParser(description=__doc__)+ arg.add_argument("--root", type=Path, required=True)+ arg.add_argument("--out", type=Path, required=True)+ arg.add_argument("--tier", default="flash")+ arg.add_argument("--small-backend", default="onnx")+ arg.add_argument("--mode", default="txt")+ arg.add_argument("--source", type=Path)+ arg.add_argument("--pages")+ arg.add_argument("--repeat", type=int, default=1)+ arg.add_argument("--block-opencv", action="store_true")+ arg.add_argument("--no-input-trace", action="store_true")+ args = arg.parse_args()+ if args.repeat < 1:+ arg.error("--repeat must be positive")+ if not (args.root / "mineru").is_dir():+ arg.error("--root must contain the MinerU source package")+ sys.path.insert(0, str(args.root))+ if args.block_opencv:+ import importlib.abc++ class BlockOpenCV(importlib.abc.MetaPathFinder):+ """独立验收进程在真实模型加载前阻断直接及间接的 cv2 导入。"""++ def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> None:+ if fullname == "cv2" or fullname.startswith("cv2."):+ raise ModuleNotFoundError("OpenCV is blocked for acceptance", name=fullname)+ return None++ sys.meta_path.insert(0, BlockOpenCV())+ os.environ["MINERU_MODEL_SMALL_BACKEND"] = args.small_backend+ os.environ["MINERU_DEVICE_MODE"] = "cpu"+ os.environ["MINERU_TABLE_DEVICE"] = "cpu"+ os.environ["HF_HUB_OFFLINE"] = "1"+ os.environ["MINERU_LANG"] = "en"+ args.out.mkdir(parents=True, exist_ok=True)+ from mineru.config import VlmConfig, config+ import mineru++ assert Path(mineru.__file__).resolve().parent == (args.root / "mineru").resolve()++ config.llm_aided.features.title_leveling = False+ config.llm_aided.features.cross_page_table_cell_merge = False++ def fingerprint(value: Any) -> Any:+ """完整记录模型输入数组及相关参数,不使用有损数值归一化。"""+ import numpy as np+ from PIL import Image++ if isinstance(value, np.ndarray):+ return {+ "shape": list(value.shape),+ "dtype": str(value.dtype),+ "sha256": hashlib.sha256(value.tobytes()).hexdigest(),+ }+ if isinstance(value, Image.Image):+ return {"size": list(value.size), "mode": value.mode, "sha256": hashlib.sha256(value.tobytes()).hexdigest()}+ if isinstance(value, (list, tuple)):+ return [fingerprint(v) for v in value]+ if isinstance(value, dict):+ return {str(k): fingerprint(v) for k, v in value.items()}+ if isinstance(value, np.generic):+ return value.item()+ if isinstance(value, (str, int, float, bool)) or value is None:+ return value+ if "torch" in sys.modules and isinstance(value, sys.modules["torch"].Tensor):+ return fingerprint(value.detach().cpu().numpy())+ raise TypeError(f"Unsupported model input fingerprint type: {type(value).__name__}")++ traces = {}+ if not args.no_input_trace and (args.tier != "flash" or args.mode == "ocr"):+ from mineru.model.runtime.hybrid import HybridLocalModelContextSingleton++ context = HybridLocalModelContextSingleton().get_model()+ for prop, methods in {+ "layout_model": ["batch_predict"],+ "ocr_model": ["ocr"],+ "table_cls_model": ["predict", "batch_predict"],+ "table_orientation_cls_model": ["batch_predict"],+ "mfr_model": ["batch_predict"],+ }.items():+ try:+ model = getattr(context, prop)+ except AttributeError:+ continue+ for method in methods:+ original = getattr(model, method, None)+ if not callable(original):+ continue+ key = prop + "." + method++ def wrapped(*values: Any, _original: Callable[..., Any] = original, _key: str = key, **options: Any) -> Any:+ """仅在验收脚本采集真实模型调用,不替换算法或结果。"""+ traces.setdefault(_key, []).append({"input": fingerprint(values), "options": fingerprint(options)})+ result = _original(*values, **options)+ # OCR 返回值可能含运行耗时;最终协议另行完整比较。+ return result++ setattr(model, method, wrapped)++ if not args.no_input_trace and args.tier != "flash":+ import onnxruntime++ original_ort_run = onnxruntime.InferenceSession.run++ def record_ort_input(session: Any, output_names: Any, input_feed: dict[str, Any], *values: Any, **options: Any) -> Any:+ """记录送入 ONNX Runtime 的真实张量,原样透传模型推理。"""+ key = "onnx." + Path(str(getattr(session, "_model_path", "unknown"))).name+ traces.setdefault(key, []).append(fingerprint(input_feed))+ return original_ort_run(session, output_names, input_feed, *values, **options)++ onnxruntime.InferenceSession.run = record_ort_input+ if args.small_backend == "torch":+ for name, model in (+ ("torch.layout", context.layout_model.model),+ ("torch.ocr_det", context.ocr_model.text_detector.net),+ ("torch.ocr_rec", context.ocr_model.text_recognizer.net),+ ("torch.mfr", context.mfr_model.net),+ ):+ original_forward = model.forward++ def record_forward(+ *values: Any, _original: Callable[..., Any] = original_forward, _key: str = name, **options: Any+ ) -> Any:+ """只在完整模型 forward 边界记录张量,避免遍历每一层。"""+ traces.setdefault(_key, []).append({"args": fingerprint(values), "kwargs": fingerprint(options)})+ return _original(*values, **options)++ model.forward = record_forward++ from importlib.metadata import PackageNotFoundError, version++ def installed_version(name: str) -> str | None:+ """无 OpenCV 的验收环境允许可选依赖元数据缺失。"""+ try:+ return version(name)+ except PackageNotFoundError:+ return None++ from mineru.parser import parse+ from mineru.render import RenderFormat, render++ source = args.root / "demo/pdfs/demo2.pdf"+ source = args.source or source+ options = {"tier": args.tier, "ocr_mode": args.mode, "page_range": args.pages or ("all" if args.tier == "flash" else "1-2")}+ if args.tier in ("standard", "advanced"):+ options["vlm_config"] = VlmConfig(engine="llama-cpp", max_concurrency=1)+ from docvortex.analyzers.native import PdfModel+ from docvortex.document.pdf import PDFDocument++ native_parse_calls = 0+ native_pages_requested = 0+ original_predict = PdfModel.predict++ def counted_predict(model: PdfModel, document: PDFDocument) -> list[list[dict[str, Any]]]:+ """通过公开原生模型接口计数整本文档调用和页请求,不依赖私有诊断模块。"""+ nonlocal native_parse_calls, native_pages_requested+ native_parse_calls += 1+ native_pages_requested += document.page_count+ return original_predict(model, document)++ PdfModel.predict = counted_predict+ startup_seconds = time.perf_counter() - startup_started+ times = []+ for index in range(args.repeat):+ start = time.perf_counter()+ result = parse(source, **options)+ times.append(time.perf_counter() - start)+ if index:+ continue+ middle = result.middle_json.model_dump_json()+ (args.out / "middle.json").write_text(middle)+ (args.out / "model.json").write_text(result._model_output.model_dump_json())+ digests = {}+ for output_format in RenderFormat:+ value = render(result.middle_json, output_format)+ if isinstance(value, bytes):+ (args.out / (output_format.value + ".bin")).write_bytes(value)+ if output_format in (RenderFormat.DOCX, RenderFormat.EPUB):+ with ZipFile(BytesIO(value)) as archive:+ entries = {}+ for name in sorted(archive.namelist()):+ payload = archive.read(name)+ if name in ("docProps/core.xml", "OEBPS/content.opf", "EPUB/package.opf"):+ payload = re.sub(rb"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", b"NORMALIZED_CREATION_TIME", payload)+ entries[name] = hashlib.sha256(payload).hexdigest()+ digests[output_format.value] = entries+ elif output_format == RenderFormat.PDF:+ from docvortex.document.pdf import PDFDocument++ with PDFDocument(value) as pdf:+ pages = []+ for page in range(len(pdf)):+ image = pdf.render_page(page, scale=1).pil_image+ pages.append(fingerprint(image))+ image.close()+ digests["pdf"] = pages+ else:+ digests[output_format.value] = hashlib.sha256(value).hexdigest()+ elif isinstance(value, str):+ (args.out / (output_format.value + ".txt")).write_text(value)+ digests[output_format.value] = hashlib.sha256(value.encode()).hexdigest()+ else:+ text = json.dumps(value, ensure_ascii=False, sort_keys=True)+ (args.out / (output_format.value + ".json")).write_text(text)+ digests[output_format.value] = hashlib.sha256(text.encode()).hexdigest()+ (args.out / "digests.json").write_text(json.dumps(digests, indent=2))+ assert middle == result.middle_json.model_dump_json()+ (args.out / "traces.json").write_text(json.dumps(traces, ensure_ascii=False, indent=2))+ # 验收诊断记录实际扩展及其摘要,不以环境变量代替已选择的后端。+ from docvortex._compute_backend import backend_info++ (args.out / "performance.json").write_text(+ json.dumps(+ {+ "times": times,+ "startup_seconds": startup_seconds,+ "native_parse_calls": native_parse_calls,+ "native_pages_requested": native_pages_requested,+ "cv2_loaded": "cv2" in sys.modules,+ "source": str(source),+ "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ "options": str(options),+ "docvortex": version("docvortex"),+ "opencv_blocked": args.block_opencv,+ "compute_backend": backend_info(),+ "opencv": installed_version("opencv-python"),+ "python": sys.version,+ "numpy": version("numpy"),+ "pillow": version("pillow"),+ },+ indent=2,+ )+ )+ print(args.out, times, flush=True)+++if __name__ == "__main__":+ main()diff --git a/tests/benchmarks/pdf_cpu_gaps.py b/tests/benchmarks/pdf_cpu_gaps.pyindex 43f2e823..5c305ee7 100644--- a/tests/benchmarks/pdf_cpu_gaps.py+++ b/tests/benchmarks/pdf_cpu_gaps.py@@ -22,6 +22,8 @@ from collections import defaultdictfrom pathlib import Pathfrom types import SimpleNamespace+from mineru.model.runtime import hybrid as hybrid_runtime+def _input_digest(value: object) -> str:"""按值指纹化模型输入,覆盖数组像素、PIL 页图、顺序和标量参数。"""@@ -152,7 +154,7 @@ def main() -> None:setup_started = time.perf_counter()if live:- model = p.HybridLocalModelContextSingleton().get_model()+ model = hybrid_runtime.HybridLocalModelContextSingleton().get_model()predictor, backend = p.get_vlm_predictor(None)else:model = SimpleNamespace(@@ -165,7 +167,7 @@ def main() -> None:)predictor = SimpleNamespace()backend = "replay"- p.HybridLocalModelContextSingleton = lambda: SimpleNamespace(get_model=lambda: model)+ hybrid_runtime.HybridLocalModelContextSingleton = lambda: SimpleNamespace(get_model=lambda: model)p.get_vlm_predictor = lambda config: (predictor, backend)model_setup_seconds = time.perf_counter() - setup_startedfor owner, method, name in [diff --git a/tests/unittest/test_docvortex_import_boundary.py b/tests/unittest/test_docvortex_import_boundary.pyindex ad962051..4bc777e6 100644--- a/tests/unittest/test_docvortex_import_boundary.py+++ b/tests/unittest/test_docvortex_import_boundary.py@@ -26,7 +26,7 @@ def _check_source(source: str, *, model_layer: bool = False) -> list[str]:tree = ast.parse(source)aliases: dict[str, str] = {}errors: list[str] = []- model_modules = {"docvortex.schema", "docvortex.options", "docvortex.geometry", "docvortex.assets"}+ model_modules = {"docvortex.schema", "docvortex.options", "docvortex.geometry", "docvortex.assets", "docvortex.image"}def check_module(module: str, line: int) -> None:"""按公开清单和宿主层级校验模块依赖。"""diff --git a/tests/unittest/test_docvortex_routing.py b/tests/unittest/test_docvortex_routing.pyindex 3f051c30..75ed5408 100644--- a/tests/unittest/test_docvortex_routing.py+++ b/tests/unittest/test_docvortex_routing.py@@ -8,6 +8,8 @@ import pytestfrom mineru.backend.analysis.pdf import pipeline+from mineru.model.runtime import hybrid as hybrid_runtime+@pytest.mark.parametrize(("parse_mode", "classification", "native", "classification_calls"),@@ -62,7 +64,7 @@ def test_flash_routes_classification_and_native_analysis_explicitly(]monkeypatch.setattr(pipeline, "PDFDocument", Document)- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=get_model))+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=get_model))monkeypatch.setattr(pipeline, "process_pdf_windows", process)monkeypatch.setattr(pipeline, "clean_memory", lambda *_args: None)result = pipeline.analyze_pdf(b"pdf", effort="flash", parse_mode=parse_mode)@@ -91,7 +93,9 @@ def test_hybrid_and_vlm_pdf_outputs_share_docvortex_text_cleanup(lambda _data: SimpleNamespace(close=lambda: None, page_count=1, page_size=lambda _index: (612.0, 792.0)),)monkeypatch.setattr(- pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu"))+ hybrid_runtime,+ "HybridLocalModelContextSingleton",+ lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu")),)monkeypatch.setattr(pipeline, "get_vlm_predictor", lambda _config: (object(), "test"))monkeypatch.setattr(pipeline, "clean_memory", lambda _device: None)diff --git a/tests/unittest/test_native_pdf_table_pipeline.py b/tests/unittest/test_native_pdf_table_pipeline.pyindex 06155b7e..24a111f6 100644--- a/tests/unittest/test_native_pdf_table_pipeline.py+++ b/tests/unittest/test_native_pdf_table_pipeline.py@@ -19,6 +19,10 @@ from mineru.backend.analysis.pdf import tables as pdf_tablesfrom mineru.backend.analysis.pdf import window as pdf_windowfrom mineru.types import RAW_FORMULA_NUMBER, BlockType+from mineru.backend.analysis.pdf import ocr as stage_ocr+from mineru.backend.analysis.pdf.text import content as stage_text_content+from mineru.model.runtime import hybrid as hybrid_runtime+_PROJECT_ROOT = Path(__file__).parents[2]@@ -44,7 +48,7 @@ def test_flash_ocr_projects_table_text() -> None:"""验证 Flash OCR 保持现有 OCR 空间投影路径。"""- monkeypatch.setattr(pdf_tables, "run_ocr_inference", MagicMock(return_value=[[]]))+ monkeypatch.setattr(hybrid_runtime, "run_ocr_inference", MagicMock(return_value=[[]]))monkeypatch.setattr(pdf_tables, "project_ocr_table_text", MagicMock(return_value="OCR TABLE"))context = MagicMock()context.get_ocr_model.return_value = SimpleNamespace(ocr=object())@@ -384,12 +388,12 @@ def test_medium_formula_processing_skips_mfr_after_native_cleanup(local_model_context = MagicMock()local_model_context.mfr_model = MagicMock()medium_table_recognition = MagicMock()- monkeypatch.setattr(pdf_window, "_apply_medium_table_recognition", medium_table_recognition)- monkeypatch.setattr(pdf_window, "_apply_medium_display_formula_results", MagicMock())- monkeypatch.setattr(pdf_window, "_apply_medium_formula_number_ocr", MagicMock())- monkeypatch.setattr(pdf_window, "_ocr_det", MagicMock(return_value=[[]]))+ monkeypatch.setattr(pdf_tables, "_apply_medium_table_recognition", medium_table_recognition)+ monkeypatch.setattr(pdf_formulas, "_apply_medium_display_formula_results", MagicMock())+ monkeypatch.setattr(pdf_formulas, "_apply_medium_formula_number_ocr", MagicMock())+ monkeypatch.setattr(stage_ocr, "_ocr_det", MagicMock(return_value=[[]]))monkeypatch.setattr(- pdf_window,+ stage_text_content,"_fill_window_block_content_and_lines",MagicMock(return_value=model_list),)@@ -521,10 +525,10 @@ def test_high_txt_window_excludes_native_table_from_vlm("load_images_from_pdf_bytes_range",MagicMock(return_value=[{"img_pil": page_image, "scale": 1.0}]),)- monkeypatch.setattr(pdf_window, "_apply_table_orientations", MagicMock())- monkeypatch.setattr(pdf_window, "_apply_native_txt_table_priority", fake_native_priority)+ monkeypatch.setattr(pdf_tables, "_apply_table_orientations", MagicMock())+ monkeypatch.setattr(pdf_tables, "_apply_native_txt_table_priority", fake_native_priority)monkeypatch.setattr(pdf_window, "_process_text_and_formulas", keep_window_model_list)- monkeypatch.setattr(pdf_window, "_apply_seal_ocr", MagicMock())+ monkeypatch.setattr(stage_ocr, "_apply_seal_ocr", MagicMock())monkeypatch.setattr(pdf_window, "_attach_visual_block_images", MagicMock())result = pdf_window.process_pdf_windows(diff --git a/tests/unittest/test_onnx_model_stack.py b/tests/unittest/test_onnx_model_stack.pyindex d2fc149c..b3e1810d 100644--- a/tests/unittest/test_onnx_model_stack.py+++ b/tests/unittest/test_onnx_model_stack.py@@ -253,6 +253,9 @@ def test_light_standard_does_not_probe_platform_engines(monkeypatch: pytest.Monkdef test_light_table_models_use_only_the_onnx_bundle(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:"""三种表格模型从 Light 仓库取文件,并把相同 small_backend 传给共享 OCR。"""from mineru.model.runtime import hybrid+ from mineru.model.table.cls import paddle_table_cls+ from mineru.model.table.rec.slanet_plus import main as slanet+ from mineru.model.table.rec.unet_table import main as unetresources = []@@ -265,9 +268,9 @@ def test_light_table_models_use_only_the_onnx_bundle(monkeypatch: pytest.MonkeyPmonkeypatch.setattr(download.ModelPath, "ensure", ensure)ocr_factory = Mock(return_value=object())monkeypatch.setattr(hybrid.AtomModelSingleton, "get_atom_model", ocr_factory)- monkeypatch.setattr(hybrid, "PaddleTableModel", Mock())- monkeypatch.setattr(hybrid, "UnetTableModel", Mock())- monkeypatch.setattr(hybrid, "PaddleTableClsModel", Mock())+ monkeypatch.setattr(slanet, "PaddleTableModel", Mock())+ monkeypatch.setattr(unet, "UnetTableModel", Mock())+ monkeypatch.setattr(paddle_table_cls, "PaddleTableClsModel", Mock())hybrid.wireless_table_model_init(small_backend="onnx", device="cpu")hybrid.wired_table_model_init(small_backend="onnx", device="cpu")hybrid.table_cls_model_init(small_backend="onnx")diff --git a/tests/unittest/test_opencv_boundaries.py b/tests/unittest/test_opencv_boundaries.pynew file mode 100644index 00000000..5592cc72--- /dev/null+++ b/tests/unittest/test_opencv_boundaries.py@@ -0,0 +1,393 @@+"""守卫无需 OpenCV 的实际路径及模型输入替代操作的数值行为。"""++from __future__ import annotations++import subprocess+import sys+from pathlib import Path++import numpy as np+import pytest+from PIL import Image+from reportlab.lib.utils import ImageReader+from reportlab.pdfgen.canvas import Canvas++from mineru.model.ocr.image import alpha_to_color, check_img, get_rotate_crop_image, rgb_to_bgr+from mineru.model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel++_ROOT = Path(__file__).resolve().parents[2]+_BLOCK_CV2 = '''+import importlib.abc+import sys++class BlockCv2(importlib.abc.MetaPathFinder):+ """在实际入口执行前拒绝直接或间接的 OpenCV 导入。"""+ def find_spec(self, fullname, path=None, target=None):+ if fullname == "cv2" or fullname.startswith("cv2."):+ raise ImportError("OpenCV must not load on this path")++sys.meta_path.insert(0, BlockCv2())+'''+++def _run_blocked(script: str, *args: str) -> None:+ """在独立进程验证真实加载边界,避免其他测试已加载 cv2 掩盖泄漏。"""+ result = subprocess.run(+ [sys.executable, "-c", _BLOCK_CV2 + script, *args],+ cwd=_ROOT,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def test_pdf_and_model_helpers_import_without_opencv() -> None:+ """混合编排和模型模块的导入不提前加载 OpenCV 或实际表格模型。"""+ _run_blocked("""+import importlib+for module in (+ "mineru.parser", "mineru.render", "mineru.model.vlm.client",+ "mineru.backend.analysis.pdf.pipeline", "mineru.backend.analysis.pdf.window",+ "mineru.backend.analysis.pdf.formulas", "mineru.backend.analysis.pdf.ocr",+ "mineru.backend.analysis.pdf.tables", "mineru.backend.analysis.pdf.text.content",+ "mineru.model.runtime.hybrid", "mineru.model.ocr.image",+ "mineru.model.ocr.db_postprocess", "mineru.model.ocr.seal_crop",+ "mineru.model.table.cls.paddle_table_cls", "mineru.model.table.rec.unet_table.utils",+ "mineru.model.table.rec.unet_table.utils_table_line_rec",+):+ importlib.import_module(module)+assert "cv2" not in sys.modules+assert "mineru.model.table.rec.unet_table.main" not in sys.modules+assert "mineru.model.table.rec.slanet_plus.main" not in sys.modules+""")++[email protected]("asynchronous", [False, True])[email protected]("ocr_mode", ["txt", "auto"])+def test_real_flash_pdf_parse_and_all_renderers_without_opencv(tmp_path: Path, asynchronous: bool, ocr_mode: str) -> None:+ """真实选页、自动分类、原生补图和九种渲染均不加载 OpenCV。"""+ source = tmp_path / "source.pdf"+ canvas = Canvas(str(source))+ for page in range(3):+ for line in range(12):+ canvas.drawString(50, 760 - line * 18, f"Page {page + 1}: Native text evidence line {line}.")+ with Image.new("RGB", (180, 90), (30, 80, 180)) as picture:+ canvas.drawImage(ImageReader(picture), 50, 350, width=180, height=90)+ canvas.showPage()+ canvas.save()+ _run_blocked(+ """+import asyncio+from pathlib import Path+from mineru.config import config+from mineru.parser import parse, parse_async+from mineru.parser.writer import FileBasedDataWriter+from mineru.render import RenderFormat, render++config.llm_aided.features.title_leveling = False+config.llm_aided.features.cross_page_table_cell_merge = False+options = dict(tier="flash", ocr_mode=sys.argv[2], page_range="1,3")+result = asyncio.run(parse_async(sys.argv[1], **options)) if sys.argv[3] == "True" else parse(sys.argv[1], **options)+assert len(result.pages) == 2+assert result.middle_json.extensions["mineru"]["parse_mode"] == "txt"+assert "Page 1" in result.markdown() and "Page 3" in result.markdown()+assert "Page 2" not in result.markdown()+assert "image" in result.middle_json.model_dump_json()+assert "mineru.model.runtime.hybrid" not in sys.modules+before = result.middle_json.model_dump_json()+for output_format in RenderFormat:+ assert render(result.middle_json, output_format)+result.save(FileBasedDataWriter(str(Path(sys.argv[1]).parent / "export")))+assert before == result.middle_json.model_dump_json()+assert "cv2" not in sys.modules+""",+ str(source),+ ocr_mode,+ str(asynchronous),+ )+++def test_simple_image_operations_without_opencv() -> None:+ """颜色转换、alpha 合成、直角旋转和轴对齐裁剪不进入 OpenCV。"""+ _run_blocked("""+import numpy as np+from mineru.model.ocr.image import alpha_to_color, check_img, get_rotate_crop_image, rgb_to_bgr+from mineru.model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel+image = np.zeros((8, 10, 4), dtype=np.uint8)+assert rgb_to_bgr(image).shape == (8, 10, 3)+assert alpha_to_color(image).shape == (8, 10, 3)+assert check_img(image[:, :, 0]).shape == (8, 10, 3)+points = np.array([[1, 1], [7, 1], [7, 6], [1, 6]], dtype=np.float32)+assert get_rotate_crop_image(image, points).shape == (5, 6, 4)+assert MineruTableOrientationClsModel._rotate_image_by_label(image, "90").shape == (10, 8, 4)+assert "cv2" not in sys.modules+""")++[email protected]("dtype", [np.uint8, np.uint16, np.float32])[email protected]("channels", [1, 3, 4])+def test_model_channel_conversion_matches_opencv(dtype: type, channels: int) -> None:+ """各种实际位深和非连续数组逐像素一致,且转换结果拥有独立连续存储。"""+ cv2 = pytest.importorskip("cv2")++ image = np.arange(8 * 10 * channels).reshape(8, 10, channels).astype(dtype)[::2, ::2]+ actual = rgb_to_bgr(image)+ np.testing.assert_array_equal(actual, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))+ assert actual.flags.c_contiguous and not np.shares_memory(actual, image)+++def test_grayscale_and_alpha_conversion_keep_rounding() -> None:+ """灰度复制和非白色背景的 alpha 合成保持原来的逐通道截断顺序。"""+ cv2 = pytest.importorskip("cv2")++ image = np.random.default_rng(7).integers(0, 256, (17, 13, 4), dtype=np.uint8)+ np.testing.assert_array_equal(check_img(image[:, :, 0]), cv2.cvtColor(image[:, :, 0], cv2.COLOR_GRAY2BGR))+ blue, green, red, alpha_channel = cv2.split(image)+ alpha = alpha_channel / 255+ expected = cv2.merge(+ tuple(+ (background * (1 - alpha) + channel * alpha).astype(np.uint8)+ for channel, background in ((blue, 30), (green, 20), (red, 10))+ )+ )+ np.testing.assert_array_equal(alpha_to_color(image, (10, 20, 30)), expected)++[email protected]("label,rotation", [("90", 2), ("270", 0), ("0", None)])+def test_orientation_rotation_keeps_pixels_and_ownership(label: str, rotation: int | None) -> None:+ """方向评分使用的旋转保持像素、连续性和零角度副本行为。"""+ cv2 = pytest.importorskip("cv2")++ image = np.arange(8 * 10 * 3, dtype=np.uint8).reshape(8, 10, 3)[::2, ::2]+ actual = MineruTableOrientationClsModel._rotate_image_by_label(image, label)+ expected = image.copy() if rotation is None else cv2.rotate(image, rotation)+ np.testing.assert_array_equal(actual, expected)+ assert actual.flags.c_contiguous and not np.shares_memory(actual, image)+++def test_perspective_crop_keeps_numeric_contract() -> None:+ """共享内核的倾斜裁图保留透视矩阵、三次插值和边界复制。"""+ cv2 = pytest.importorskip("cv2")++ image = np.arange(20 * 30 * 3, dtype=np.uint16).reshape(20, 30, 3)+ points = np.array([[2, 2], [21, 4], [22, 15], [1, 14]], dtype=np.float32)+ width = int(max(np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3])))+ height = int(max(np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2])))+ target = np.float32([[0, 0], [width, 0], [width, height], [0, height]])+ expected = cv2.warpPerspective(+ image,+ cv2.getPerspectiveTransform(points, target),+ (width, height),+ flags=cv2.INTER_CUBIC,+ borderMode=cv2.BORDER_REPLICATE,+ )+ np.testing.assert_array_equal(get_rotate_crop_image(image, points), expected)++[email protected]("paddle_compatible", [False, True])+def test_formula_tensor_keeps_original_gray_and_channel_values(paddle_compatible: bool) -> None:+ """公式预处理仅替换 merge,灰度舍入和归一化计算顺序保持逐元素一致。"""+ cv2 = pytest.importorskip("cv2")++ from mineru.model.mfr.pp_formulanet.processors import UniMERNetTestTransform++ image = np.random.default_rng(11).integers(0, 256, (17, 19, 3), dtype=np.uint8)+ mean = np.array([0.7931] * 3).reshape(1, 1, 3).astype("float32")+ std = np.array([0.1738] * 3).reshape(1, 1, 3).astype("float32")+ if paddle_compatible:+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)+ expected = (cv2.merge([gray] * 3).astype("float32") - mean * 255.0) * (1.0 / (std * 255.0))+ else:+ normalized = (image.astype("float32") * float(1 / 255.0) - mean) / std+ expected = cv2.merge([np.squeeze(cv2.cvtColor(normalized, cv2.COLOR_BGR2GRAY))] * 3)+ np.testing.assert_array_equal(UniMERNetTestTransform(paddle_compatible=paddle_compatible).transform(image), expected)++[email protected]("shape", [(1, 1), (1, 17), (19, 1), (23, 27)])+def test_formula_margin_crop_keeps_threshold_and_bounds(shape: tuple[int, int]) -> None:+ """公式裁边覆盖空白、单行单列和边界像素,保持非零框的闭区间语义。"""+ cv2 = pytest.importorskip("cv2")++ from mineru.model.mfr.pp_formulanet.processors import UniMERNetImgDecode++ processor = UniMERNetImgDecode((192, 672))+ for blank in (True, False):+ array = np.full(shape, 255, dtype=np.uint8)+ if not blank:+ array[0, 0] = 0+ array[-1, -1] = 30+ with Image.fromarray(array) as image:+ actual = processor.crop_margin(image)+ if array.max() == array.min():+ assert actual is image+ continue+ normalized = (array - array.min()) / (array.max() - array.min()) * 255+ x, y, width, height = cv2.boundingRect(cv2.findNonZero(255 * (normalized < 200).astype(np.uint8)))+ with image.crop((x, y, x + width, y + height)) as expected:+ assert actual.size == expected.size+ np.testing.assert_array_equal(np.array(actual), np.array(expected))+ actual.close()+++def test_table_classifier_tensor_keeps_channel_calculation_order() -> None:+ """表格分类单张及批量预处理保持 OpenCV split/merge 的浮点计算顺序。"""+ cv2 = pytest.importorskip("cv2")++ from mineru.model.table.cls.paddle_table_cls import PaddleTableClsModel++ classifier = object.__new__(PaddleTableClsModel)+ image = np.random.default_rng(13).integers(0, 256, (79, 137, 3), dtype=np.uint8)+ scale = 256 / min(image.shape[:2])+ resized = cv2.resize(image, (round(image.shape[1] * scale), round(image.shape[0] * scale)), interpolation=1)+ y, x = (resized.shape[0] - 224) // 2, (resized.shape[1] - 224) // 2+ split = list(cv2.split(resized[y : y + 224, x : x + 224]))+ for channel in range(3):+ split[channel] = split[channel].astype(np.float32)+ split[channel] *= 0.00392156862745098 / [0.229, 0.224, 0.225][channel]+ split[channel] += -[0.485, 0.456, 0.406][channel] / [0.229, 0.224, 0.225][channel]+ expected = np.stack([cv2.merge(split).transpose(2, 0, 1)]).astype(np.float32)+ np.testing.assert_array_equal(classifier.preprocess(image), expected)+ np.testing.assert_array_equal(classifier.batch_preprocess([image]), expected)++[email protected]("channels", [None, 1, 3])+def test_unimer_crop_and_zero_padding_keep_shape(channels: int | None) -> None:+ """单通道和 RGB 公式图的裁边、零填充保持原形状及全部像素。"""+ cv2 = pytest.importorskip("cv2")++ pytest.importorskip("torch")+ pytest.importorskip("torchvision")+ pytest.importorskip("transformers")+ from mineru.model.mfr.unimernet.unimernet_hf.unimer_swin.image_processing_unimer_swin import UnimerSwinImageProcessor++ shape = (17, 29) if channels is None else (17, 29, channels)+ image = np.full(shape, 255, dtype=np.uint8)+ image[3:15, 5:24] = 0+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) if channels == 3 else image.copy()+ normalized = (((gray - gray.min()) / (gray.max() - gray.min())) * 255).astype(np.uint8)+ binary = 255 * (normalized < 200).astype(np.uint8)+ x, y, width, height = cv2.boundingRect(cv2.findNonZero(binary))+ cropped = image[y : y + height, x : x + width]+ np.testing.assert_array_equal(UnimerSwinImageProcessor.crop_margin_numpy(image), cropped)+ processor = UnimerSwinImageProcessor(image_size=(32, 64))+ scale = min(32 / height, 64 / width)+ resized = cv2.resize(cropped, (int(width * scale), int(height * scale)))+ pad_x, pad_y = (64 - resized.shape[1]) // 2, (32 - resized.shape[0]) // 2+ expected = cv2.copyMakeBorder(+ resized,+ pad_y,+ 32 - resized.shape[0] - pad_y,+ pad_x,+ 64 - resized.shape[1] - pad_x,+ cv2.BORDER_CONSTANT,+ value=[0, 0, 0],+ )+ np.testing.assert_array_equal(processor.prepare_input(image), expected)+++def test_unet_input_tensor_keeps_inplace_channel_exchange() -> None:+ """UNet 预处理保留原位 RGB 交换及 OpenCV 浮点减乘顺序。"""+ cv2 = pytest.importorskip("cv2")++ from mineru.model.table.rec.unet_table.table_structure_unet import TSRUnet+ from mineru.model.table.rec.unet_table.utils import resize_img++ model = object.__new__(TSRUnet)+ model.mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)+ model.std = np.array([58.395, 57.12, 57.375], dtype=np.float32)+ model.inp_height, model.inp_width = 32, 64+ image = np.random.default_rng(17).integers(0, 256, (29, 47, 3), dtype=np.uint8)+ resized, _, _ = resize_img(image, (32, 64), True)+ expected = resized.copy().astype(np.float32)+ cv2.cvtColor(expected, cv2.COLOR_BGR2RGB, expected)+ cv2.subtract(expected, np.float64(model.mean.reshape(1, -1)), expected)+ cv2.multiply(expected, 1 / np.float64(model.std.reshape(1, -1)), expected)+ actual = model.preprocess(image)+ np.testing.assert_array_equal(actual["img"], expected.transpose(2, 0, 1)[None, ...])+++def test_base_dependencies_exclude_opencv_and_keep_product_extras() -> None:+ """基础声明移除 OpenCV,ONNX、llama.cpp、Torch/full 和苹果自动 extra 保持原样。"""+ try:+ import tomllib+ except ModuleNotFoundError:+ import tomli as tomllib+ from packaging.requirements import Requirement++ project = tomllib.loads((_ROOT / "pyproject.toml").read_text())["project"]+ requirements = [Requirement(value) for value in project["dependencies"]]+ assert not any(requirement.name.lower().replace("_", "-").startswith("opencv") for requirement in requirements)+ names = {requirement.name for requirement in requirements}+ assert {"onnxruntime", "mineru-llama-cpp", "docvortex"} <= names+ assert "mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'" in project["dependencies"]+ extras = project["optional-dependencies"]+ assert {Requirement(value).name for value in extras["torch"]} == {+ "torch",+ "torchvision",+ "transformers",+ "accelerate",+ "safetensors",+ }+ assert {Requirement(value).name for value in extras["full"]} == {"mineru", "vllm", "lmdeploy", "qwen-vl-utils"}+ full_mineru = next(Requirement(value) for value in extras["full"] if Requirement(value).name == "mineru")+ assert full_mineru.extras == {"torch"}+++def test_production_opencv_is_limited_to_explicit_camera_calibration() -> None:+ """静态守卫只允许旧相机标定的两个按需入口使用 cv2,不放宽整个模块。"""+ import ast++ allowed = {+ ("model/ocr/seal_det_warp.py", "CurveTextRectifier.spatial_transform"),+ ("model/ocr/seal_det_warp.py", "CurveTextRectifier.calibrate"),+ }+ found: set[tuple[str, str]] = set()+ root = _ROOT / "mineru"+ for path in root.rglob("*.py"):+ tree = ast.parse(path.read_text())+ parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}+ for node in ast.walk(tree):+ is_import = isinstance(node, ast.Import) and any(alias.name == "cv2" for alias in node.names)+ is_attribute = isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "cv2"+ if not (is_import or is_attribute):+ continue+ names = []+ parent = node+ while parent in parents:+ parent = parents[parent]+ if isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ names.append(parent.name)+ location = (path.relative_to(root).as_posix(), ".".join(reversed(names)))+ assert location in allowed, (location, node.lineno)+ found.add(location)+ assert found == allowed+++def test_model_preprocessors_and_geometry_run_without_opencv() -> None:+ """独立阻断进程执行检测后处理、识别缩放、表格线和公式图像处理。"""+ _run_blocked("""+import numpy as np+from mineru.model.ocr.db_postprocess import DBPostProcess+from mineru.model.ocr.image import get_rotate_crop_image, resize_text_recognition_image+from mineru.model.table.rec.unet_table.utils import LoadImage+from mineru.model.table.rec.unet_table.utils_table_line_rec import draw_lines, _iter_connected_component_coords+from mineru.model.mfr.pp_formulanet.processors import UniMERNetTestTransform++pred = np.zeros((1, 1, 32, 48), np.float32)+pred[0, 0, 5:12, 8:30] = .85+pred[0, 0, 19:27, 23:42] = .95+result = DBPostProcess()({"maps": pred}, np.float32([[96, 144, 1, 1]]))+assert result[0]["points"].tolist() == [[[54, 42], [138, 42], [138, 93], [54, 93]], [[9, 0], [102, 0], [102, 48], [9, 48]]]+image = np.arange(40 * 80 * 3, dtype=np.uint8).reshape(40, 80, 3)+points = np.float32([[3, 5], [74, 7], [70, 30], [1, 28]])+crop = get_rotate_crop_image(image, points)+assert crop.size and crop.dtype == np.uint8 and crop.flags.c_contiguous+assert resize_text_recognition_image(crop, 8., (3, 48, 320)).dtype == np.float32+mask = draw_lines(np.zeros((60, 90), np.uint8), [[2, 30, 87, 30]], color=255, lineW=2)+assert len(list(_iter_connected_component_coords(mask))) == 1+rgba = np.zeros((10, 20, 4), np.uint8)+assert np.all(LoadImage.cvt_four_to_three(rgba) == 255)+assert "cv2" not in sys.modules+""")diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex d111c43f..3396089b 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -24,6 +24,11 @@ from mineru.backend.postprocess import document as postprocess_documentfrom mineru.integrations.docvortex import build_metadatafrom mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, BlockType, ContentType, MiddleJson, ModelJson+from mineru.backend.analysis.pdf import ocr as stage_ocr+from mineru.backend.analysis.pdf import tables as stage_tables+from mineru.backend.analysis.pdf.text import content as stage_text_content+from mineru.model.runtime import hybrid as hybrid_runtime+def _build_text_lines(*contents: str) -> list[_AnalyzeLine]:"""按输入文本构造稳定的多行文本结构,供 block content 拼接测试复用。"""@@ -196,7 +201,7 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(xhigh_normalizer = MagicMock(wraps=layout._normalize_xhigh_vlm_blocks)native_table_priority = MagicMock(return_value=MagicMock(total=0))monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))monkeypatch.setattr(pipeline,"get_vlm_predictor",@@ -208,9 +213,9 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(MagicMock(return_value=[{"img_pil": page_image, "scale": 1.0}]),)monkeypatch.setattr(window, "_process_text_and_formulas", fake_process_text_and_formulas)- monkeypatch.setattr(window, "_apply_native_txt_table_priority", native_table_priority)+ monkeypatch.setattr(stage_tables, "_apply_native_txt_table_priority", native_table_priority)monkeypatch.setattr(window, "_normalize_xhigh_vlm_blocks", xhigh_normalizer)- monkeypatch.setattr(window, "_apply_seal_ocr", MagicMock())+ monkeypatch.setattr(stage_ocr, "_apply_seal_ocr", MagicMock())monkeypatch.setattr(window, "_supplement_missing_image_block_containers", MagicMock())monkeypatch.setattr(window, "_attach_visual_block_images", MagicMock())expected_middle_json = MiddleJson(@@ -619,11 +624,11 @@ def test_process_flash_ocr_runs_detection_recognition_content_and_tables(apply_ocr_rec = MagicMock(side_effect=lambda *_args: events.append("rec"))fill_content = MagicMock(side_effect=lambda *_args: events.append("content") or model_list)fill_tables = MagicMock(side_effect=lambda *_args: events.append("tables"))- monkeypatch.setattr(window, "_validate_text_formula_window_inputs", validate_inputs)- monkeypatch.setattr(window, "_ocr_det", ocr_det)- monkeypatch.setattr(window, "_apply_ocr_rec_results", apply_ocr_rec)- monkeypatch.setattr(window, "_fill_window_block_content_and_lines", fill_content)- monkeypatch.setattr(window, "_fill_flash_ocr_table_contents", fill_tables)+ monkeypatch.setattr(stage_text_content, "_validate_text_formula_window_inputs", validate_inputs)+ monkeypatch.setattr(stage_ocr, "_ocr_det", ocr_det)+ monkeypatch.setattr(stage_ocr, "_apply_ocr_rec_results", apply_ocr_rec)+ monkeypatch.setattr(stage_text_content, "_fill_window_block_content_and_lines", fill_content)+ monkeypatch.setattr(stage_tables, "_fill_flash_ocr_table_contents", fill_tables)try:result = window._process_flash_ocr(diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 4e5a09e1..f981455e 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -34,6 +34,9 @@ from mineru.types import ()from mineru.version import __version__ as mineru_version+from mineru.backend.analysis.pdf import formulas as stage_formulas+from mineru.model.runtime import hybrid as hybrid_runtime+JPEG_DATA_URI_PREFIX = "data:image/jpeg;base64,"RED = (255, 0, 0)GREEN = (0, 255, 0)@@ -906,7 +909,7 @@ def test_flash_ocr_formula_number_merge_runs_before_visual_crop(MagicMock(return_value=[{"img_pil": page_image}]),)monkeypatch.setattr(window, "_process_flash_ocr", fake_process_flash_ocr)- monkeypatch.setattr(window, "optimize_hybrid_formula_number_blocks", tracked_optimizer)+ monkeypatch.setattr(stage_formulas, "optimize_hybrid_formula_number_blocks", tracked_optimizer)monkeypatch.setattr(window, "_attach_visual_block_images", fake_attach_visual_blocks)model_list = window.process_pdf_windows(@@ -1206,7 +1209,7 @@ def test_doc_analyze_office_returns_model_json_without_pdf_processing(model_list_normalizer = MagicMock()monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", hybrid_model_factory)monkeypatch.setattr(window, "_configured_window_size", window_size_reader)monkeypatch.setattr(window, "_build_processing_windows", window_builder)monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", image_loader)@@ -1328,7 +1331,7 @@ def test_doc_analyze_rejects_invalid_pdf_modes_before_model_initialization(pdf_document = MagicMock(return_value=fake_document)hybrid_model_factory = MagicMock()monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", hybrid_model_factory)with pytest.raises(ValueError, match=expected_message):analyze.doc_analyze(@@ -1363,7 +1366,7 @@ def test_pdf_flash_ocr_uses_local_ocr_without_vlm(monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))monkeypatch.setattr(- pipeline,+ hybrid_runtime,"HybridLocalModelContextSingleton",MagicMock(return_value=hybrid_singleton),)@@ -1402,7 +1405,7 @@ def test_pdf_flash_txt_skips_all_neural_model_loading(clean_memory = MagicMock()process_pdf_windows = MagicMock(return_value=[])monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", hybrid_model_factory)monkeypatch.setattr(pipeline, "get_vlm_predictor", get_vlm_predictor)monkeypatch.setattr(pipeline, "clean_memory", clean_memory)monkeypatch.setattr(pipeline, "process_pdf_windows", process_pdf_windows)@@ -1474,7 +1477,7 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(events.append("clean_memory")monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))monkeypatch.setattr(pipeline, "get_vlm_predictor", fake_vlm_get_model)monkeypatch.setattr(pipeline.time, "perf_counter", fake_perf_counter)monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", fake_normalize_model_list)@@ -1517,7 +1520,7 @@ def test_pdf_analyze_releases_document_and_model_when_window_processing_fails(monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))monkeypatch.setattr(- pipeline,+ hybrid_runtime,"HybridLocalModelContextSingleton",MagicMock(return_value=hybrid_singleton),)diff --git a/tests/unittest/test_pdf_memory_lifecycle.py b/tests/unittest/test_pdf_memory_lifecycle.pyindex 05e448f0..21321032 100644--- a/tests/unittest/test_pdf_memory_lifecycle.py+++ b/tests/unittest/test_pdf_memory_lifecycle.py@@ -18,6 +18,10 @@ from mineru.backend import analyzefrom mineru.backend.analysis.pdf import pipeline, windowfrom mineru.model.runtime import memory+from mineru.backend.analysis.pdf import ocr as stage_ocr+from mineru.backend.analysis.pdf import tables as stage_tables+from mineru.model.runtime import hybrid as hybrid_runtime+def _window_probe(monkeypatch: pytest.MonkeyPatch, failure: str = "") -> SimpleNamespace:"""隔离推理模型,保留真实数组、表格裁图和素材编码以检查窗口边界。"""@@ -90,11 +94,11 @@ def _window_probe(monkeypatch: pytest.MonkeyPatch, failure: str = "") -> SimpleNmonkeypatch.setattr(window, "get_document_render_session", lambda _document: None)monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", render)monkeypatch.setattr(window, "_collect_table_items", collect)- monkeypatch.setattr(window, "_apply_table_orientations", orient)+ monkeypatch.setattr(stage_tables, "_apply_table_orientations", orient)monkeypatch.setattr(window, "_build_vl_style_layout_blocks", blocks)monkeypatch.setattr(window, "_process_text_and_formulas", text)monkeypatch.setattr(window, "_process_flash_ocr", text)- monkeypatch.setattr(window, "_apply_seal_ocr", lambda *_args: None)+ monkeypatch.setattr(stage_ocr, "_apply_seal_ocr", lambda *_args: None)monkeypatch.setattr(window, "_convert_vlm_results_to_model_list", lambda value: value)monkeypatch.setattr(window, "_attach_visual_block_images", attach)monkeypatch.setattr(window, "trim_process_heap", trimmed)@@ -185,7 +189,7 @@ def test_document_cleanup_order_and_global_switch(monkeypatch.setattr(pipeline, "process_pdf_windows", process)monkeypatch.setattr(pipeline, "clean_memory", lambda _device: stage("device"))monkeypatch.setattr(- pipeline,+ hybrid_runtime,"HybridLocalModelContextSingleton",lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu")),)@@ -212,7 +216,11 @@ def test_real_window_and_document_hooks_share_switch(document = Mock(page_count=2, close=Mock())monkeypatch.setattr(window, "_get_window_pdf_pages", lambda *_args: [object()])monkeypatch.setattr(pipeline, "PDFDocument", lambda _data: document)- monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=lambda: probe.model))+ monkeypatch.setattr(+ hybrid_runtime,+ "HybridLocalModelContextSingleton",+ lambda: SimpleNamespace(get_model=lambda: probe.model),+ )monkeypatch.setattr(pipeline, "clean_memory", lambda _device: None)if asynchronous:middle, model = asyncio.run(analyze.aio_doc_analyze(b"pdf", effort="medium", parse_mode="ocr"))diff --git a/tests/unittest/test_pdf_mfr_table_routing.py b/tests/unittest/test_pdf_mfr_table_routing.pyindex 88d89f7e..de2b10a2 100644--- a/tests/unittest/test_pdf_mfr_table_routing.py+++ b/tests/unittest/test_pdf_mfr_table_routing.py@@ -16,6 +16,11 @@ from mineru.backend.analysis.pdf import windowfrom mineru.backend.analysis.pdf.formulas import _build_formula_inputsfrom mineru.backend.analysis.pdf.tables import _build_table_external_mfr_inputs+from mineru.backend.analysis.pdf import ocr as stage_ocr+from mineru.backend.analysis.pdf import formulas as stage_formulas+from mineru.backend.analysis.pdf import tables as stage_tables+from mineru.backend.analysis.pdf.text import content as stage_text_content+def _formula(bbox: list[float], label: str = "inline_formula") -> dict[str, Any]:"""构造与 MFD 输出一致的测试公式。"""@@ -84,15 +89,15 @@ def test_window_mfr_routing_and_original_ocr_masks(context = SimpleNamespace(mfr_model=SimpleNamespace(batch_predict=mfr)) if enabled else SimpleNamespace()det = MagicMock(return_value=[[]])fill = MagicMock(return_value=blocks)- monkeypatch.setattr(window, "_ocr_det", det)- monkeypatch.setattr(window, "_fill_window_block_content_and_lines", fill)- for name in (- "_apply_medium_table_recognition",- "_apply_medium_display_formula_results",- "_apply_medium_formula_number_ocr",- "_apply_ocr_rec_results",+ monkeypatch.setattr(stage_ocr, "_ocr_det", det)+ monkeypatch.setattr(stage_text_content, "_fill_window_block_content_and_lines", fill)+ for module, name in (+ (stage_tables, "_apply_medium_table_recognition"),+ (stage_formulas, "_apply_medium_display_formula_results"),+ (stage_formulas, "_apply_medium_formula_number_ocr"),+ (stage_ocr, "_apply_ocr_rec_results"),):- monkeypatch.setattr(window, name, MagicMock())+ monkeypatch.setattr(module, name, MagicMock())with Image.new("RGB", (100, 100)) as image:window._process_text_and_formulas([{"img_pil": image, "scale": 1.0}],@@ -132,8 +137,8 @@ def test_final_layout_controls_filter_and_empty_results_skip_model_loading(context = SimpleNamespace() if final_table else SimpleNamespace(mfr_model=SimpleNamespace(batch_predict=mfr))fill = MagicMock(return_value=blocks)det = MagicMock(return_value=[[], []])- monkeypatch.setattr(window, "_ocr_det", det)- monkeypatch.setattr(window, "_fill_window_block_content_and_lines", fill)+ monkeypatch.setattr(stage_ocr, "_ocr_det", det)+ monkeypatch.setattr(stage_text_content, "_fill_window_block_content_and_lines", fill)with Image.new("RGB", (100, 100)) as image:window._process_text_and_formulas([{"img_pil": image, "scale": 1.0}] * 2,diff --git a/tests/unittest/test_vlm_remote.py b/tests/unittest/test_vlm_remote.pyindex ed5403f4..0e5d7c39 100644--- a/tests/unittest/test_vlm_remote.py+++ b/tests/unittest/test_vlm_remote.py@@ -23,6 +23,9 @@ from mineru.config import VlmConfig, configfrom mineru.model.vlm.client import get_vlm_predictorfrom mineru.parser import api_server, parse, parse_async+from mineru.backend.analysis.pdf import ocr as stage_ocr+from mineru.model.runtime import hybrid as hybrid_runtime+@dataclassclass _OpenAIServer:@@ -240,7 +243,7 @@ def hybrid_stub(monkeypatch: pytest.MonkeyPatch) -> None:context.device = "cpu"context.layout_model.batch_predict.return_value = [[{"bbox": [20, 20, 250, 80], "label": "text"}]]monkeypatch.setattr(- pipeline,+ hybrid_runtime,"HybridLocalModelContextSingleton",MagicMock(return_value=MagicMock(get_model=MagicMock(return_value=context))),)@@ -263,7 +266,7 @@ def hybrid_stub(monkeypatch: pytest.MonkeyPatch) -> None:return blocksmonkeypatch.setattr(window, "_process_text_and_formulas", retain_vlm_text)- monkeypatch.setattr(window, "_apply_seal_ocr", lambda *args: None)+ monkeypatch.setattr(stage_ocr, "_apply_seal_ocr", lambda *args: None)monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", lambda tier, **kwargs: None)@@ -469,7 +472,7 @@ def test_standard_progress_label_survives_pdf_mode_routing(monkeypatch.setattr(config.model, "vlm", _settings(openai_server))monkeypatch.setattr(pipeline.PDFDocument, "classify", lambda self: resolved_mode)- context = pipeline.HybridLocalModelContextSingleton().get_model()+ context = hybrid_runtime.HybridLocalModelContextSingleton().get_model()# 公式块在 TXT 下仍需 VLM 抽取,避免测试被原生正文跳过逻辑短路。context.layout_model.batch_predict.return_value = [[{"bbox": [20, 20, 250, 80], "label": "display_formula"}]]source = _pdf_input(tmp_path)