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 test utilities and remove unused code across multiple files
myhlolidc0944984c0a
diff --git a/tests/README.md b/tests/README.mdnew file mode 100644index 00000000..f82875cf--- /dev/null+++ b/tests/README.md@@ -0,0 +1,32 @@+# MinerU 测试职责++原生解析、共享 Schema、确定性后处理、渲染与导出的完整算法回归已迁入 DocVortex。配套迁移清单和验证结果位于 DocVortex 仓库的 `docs/validation/test-migration.md`、`docs/validation/test-migration.json`。++本仓库保留 OCR/Hybrid/VLM 编排、Flash 模式路由、CLI/API/Doclib、产品元数据与协议适配、渲染参数传递、旧宿主路径移除、LLM 增强及 Content List V1/V2 测试。需要小型 Office 输入的集成测试继续使用本地构造器,不从 DocVortex 的测试目录导入代码。++## 本地运行++```sh+.venv1/bin/python -m pytest tests/unittest -o addopts= -q -m 'not remote and not full_stack'+```++迁移前后均存在的三个失败为两项 Doclib extras 元数据断言及一项 MFR LaTeX 修复断言;本次没有新增排除项或改变对应断言。++## Hybrid 输入与原始语料++`tests/unittest/pdfs` 已移除,MinerU 的真实 PDF 集成输入继续使用 `demo/pdfs/demo1.pdf`、`demo2.pdf`。完整 PDF/Office/EMF+ 语料、表格评测器和合成 PDF 生成器由 DocVortex 维护。++- `fixtures/hybrid_native_script_inputs.json`:原有 33 组字符与几何快照,内容及历史来源信息保持不变。+- `fixtures/hybrid_pdf_script_inputs.json`:新增四个 CJK 探针和一个旋转页场景,包含原始字符、字体、索引、tight/origin 几何及所需页面属性。+- `fixtures/pdf_mixed_font_script_line.json`:继续覆盖 Hybrid 的真实混合字体回填行为。+- `fixtures/rtf/semantic.rtf`:保留产品接入测试仍使用的小型输入。++普通测试只读取本仓库快照。显式再生新增快照时,由调用者提供 DocVortex 源码目录:++```sh+.venv1/bin/python tests/fixtures/capture_hybrid_native_script_inputs.py \+ --fixture tests/fixtures/hybrid_pdf_script_inputs.json \+ --source-root /path/to/DocVortex --check+```++不带 `--check` 时会写回指定快照。旧夹具仍使用原默认 `--fixture` 和 DocVortex 的 `demo/pdfs` 作为 source root。再生前先核对源文件哈希;不要为消除回归差异覆盖已有真值。diff --git a/tests/benchmarks/README.md b/tests/benchmarks/README.mddeleted file mode 100644index a249ad4c..00000000--- a/tests/benchmarks/README.md+++ /dev/null@@ -1,16 +0,0 @@-# Flash PDF 等价性基准--在仓库根目录执行,默认覆盖版本化的 19 份布局语料和 12 份原生表格文档:--```bash-.venv1/bin/python tests/benchmarks/flash_pdf.py --output output/flash_pdf_refactor/baseline-.venv1/bin/python tests/benchmarks/flash_pdf.py --output output/flash_pdf_refactor/candidate --baseline output/flash_pdf_refactor/baseline-```--每份文档在独立子进程中预热一次、计时五次,报告中位耗时与进程峰值 RSS。耗时包含 PDFDocument 打开、原生分析和关闭,不包含后处理、输出序列化、OCR 或渲染。RSS 在输出后处理和额外剖析之前采集;它包含解释器和已导入模块,不是文档的增量内存。--每份文档保存完整 `model_list` 和通过统一后处理入口生成的 `middle_json`。LLM 增强显式使用默认关闭配置,版本字符串固定,比较不移除任何输出字段。`report.json` 包含源码版本、依赖版本、文件指纹与历史清单差异;历史清单不会被改写。`comparison.json` 分别报告完整输出是否相等、耗时比例和 RSS 比例,输出不等价时命令失败。--使用 `--runs 0` 跳过预热和重复计时,只进行功能比较。`--path` 可重复指定固定子集;基线和候选必须使用同一份语料集合。`--profile` 额外生成逐函数调用次数、自身耗时与累计耗时,可定位提取、几何校准、页面准备、页面组装和样式物化阶段;剖析耗时不参与性能比较。性能测量期间避免同时执行测试、构建或其它 CPU 密集任务。--已有报告目录不能覆盖。先在原始版本建立基线,然后在候选版本使用新的输出目录;不可通过更新基线掩盖输出变化。超过 5% 的持续耗时或 RSS 回退应独立复测并定位。diff --git a/tests/fixtures/capture_hybrid_native_script_inputs.py b/tests/fixtures/capture_hybrid_native_script_inputs.pyindex 7679db51..60798cc2 100644--- a/tests/fixtures/capture_hybrid_native_script_inputs.py+++ b/tests/fixtures/capture_hybrid_native_script_inputs.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport argparseimport hashlib-from importlib.metadata import versionimport json+from importlib.metadata import versionfrom pathlib import Pathfrom typing import Any@@ -19,6 +19,8 @@ def extract_case(source_root: Path, case: dict[str, Any]) -> dict[str, Any]:"""只提取原断言实际使用的字符,保留原始索引、字体和对应几何。"""with PDFDocument(str(source_root / case["source"])) as document:geometry = document.get_page_chars_with_geometry(case["page_index"])+ page_rotation = document[case["page_index"]].rotation+ page_size = document.page_size(case["page_index"])probe = case["probe"]if case["selection"] == "contiguous":visible = [char for char in geometry.chars if str(char.get("char", "")) not in _CONTROL_CHARS]@@ -27,16 +29,16 @@ def extract_case(source_root: Path, case: dict[str, Any]) -> dict[str, Any]:if start < 0 or text.find(probe, start + 1) >= 0:raise ValueError(f"Probe is missing or ambiguous: {case['source']}, {probe}")groups = [visible[start : start + len(probe)]]- elif case["selection"] == "line":+ elif case["selection"] in {"line", "lines", "page"}:groups = []for line in get_lines_from_chars(geometry.chars):text = "".join(span["text"] for span in line["spans"])text = "".join(char for char in text if char not in _CONTROL_CHARS)- if probe in text:+ if case["selection"] == "page" or probe in text:groups.append([char for span in line["spans"] for char in span.get("chars", [])])else:raise ValueError(f"Unknown selection: {case['selection']}")- if len(groups) != 1:+ if not groups or (case["selection"] not in {"lines", "page"} and len(groups) != 1):raise ValueError(f"Expected one fragment: {case['source']}, {probe}")fragments = []for chars in groups:@@ -48,13 +50,19 @@ def extract_case(source_root: Path, case: dict[str, Any]) -> dict[str, Any]:"origins": {key: value for key, value in geometry.origins.items() if key in indices},})- return {**case, "fragments": fragments}+ result = {**case, "fragments": fragments}+ if case["selection"] == "page":+ result["page_rotation"] = page_rotation+ result["page_size"] = list(page_size)+ return resultdef main() -> None:"""校验源文件身份后检查或显式更新 fixture;日常 pytest 无需源文件。"""parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--source-root", required=True, type=Path, help="DocVortex demo/pdfs 目录")+ parser.add_argument(+ "--source-root", required=True, type=Path, help="夹具 source 相对路径的根目录;原夹具使用 DocVortex demo/pdfs"+ )parser.add_argument("--fixture", type=Path, default=Path(__file__).with_name("hybrid_native_script_inputs.json"))parser.add_argument("--check", action="store_true", help="只比较,不写出")args = parser.parse_args()diff --git a/tests/fixtures/evaluate_native_pdf_table_manifest.py b/tests/fixtures/evaluate_native_pdf_table_manifest.pydeleted file mode 100644index 73aea2a8..00000000--- a/tests/fixtures/evaluate_native_pdf_table_manifest.py+++ /dev/null@@ -1,347 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""运行外部跨页 PDF 真值 manifest 的 Native Table 发布门。"""--from __future__ import annotations--import argparse-import hashlib-import json-import statistics-import time-from collections import defaultdict-from pathlib import Path, PureWindowsPath-from typing import Any--from docvortex.analyzers.native.pdf.table_recovery import NativeTableInput-from docvortex.analyzers.native.pdf.table_recovery import coerce_native_table_rectangles-from docvortex.analyzers.native.pdf.table_recovery import coerce_native_table_rules-from docvortex.analyzers.native.pdf.table_recovery import recover_native_pdf_table-from docvortex.analyzers.native.pdf.table_recovery.engine import diagnose_native_pdf_table-from docvortex.document.pdf.document import PDFDocument--_DEFAULT_SOURCE_ROOT = Path(__file__).resolve().parents[1] / "unittest" / "pdfs" / "native_pdf_tables"---def _validate_portable_manifest(manifest: dict[str, Any]) -> None:- """拒绝把语料根目录或主机绝对路径固化进版本化 manifest。"""-- forbidden_root_keys = {"source_root", "source_root_hint"}- persisted_root_keys = forbidden_root_keys.intersection(manifest)- if persisted_root_keys:- keys = ", ".join(sorted(persisted_root_keys))- raise ValueError(f"manifest 不得保存语料根目录字段: {keys}")-- for collection_name in ("entries", "flash_targets"):- for entry_index, entry in enumerate(- manifest.get(collection_name, []),- ):- filename = str(entry["file"])- path = Path(filename)- if path.is_absolute() or PureWindowsPath(filename).is_absolute() or ".." in path.parts:- raise ValueError(- f"manifest {collection_name}[{entry_index}].file 必须是 source root 下的安全相对路径: {filename}"- )---def _result_signature(result: Any) -> dict[str, Any] | None:- """把原生结构结果转换为 manifest 可比较的稳定签名。"""-- if result is None:- return None- return {- "rows": result.rows,- "cols": result.cols,- "span_signature": [- [cell.row, cell.col, cell.rowspan, cell.colspan] for cell in result.cells if cell.rowspan > 1 or cell.colspan > 1- ],- "text_sha256": hashlib.sha256("\n".join(cell.content for cell in result.cells).encode("utf-8")).hexdigest(),- }---def _recover_table_input(- table_input: NativeTableInput,- *,- measure_performance: bool,-) -> tuple[dict[str, Any] | None, float]:- """按性能门开关执行一次功能恢复,或执行预热后的正式计时恢复。"""-- if not measure_performance:- return _result_signature(recover_native_pdf_table(table_input)), 0.0- # 性能模式保留一次不计时预热,避免 Python 首次路径和页面缓存抖动污染 p95。- recover_native_pdf_table(table_input)- started = time.perf_counter()- result = recover_native_pdf_table(table_input)- return _result_signature(result), time.perf_counter() - started---def _maybe_diagnose_table_input(- table_input: NativeTableInput,- *,- collect_diagnostics: bool,- mismatch: bool,-) -> dict[str, Any] | None:- """仅在显式请求诊断或结果不匹配时执行昂贵的候选诊断。"""-- if not collect_diagnostics and not mismatch:- return None- return diagnose_native_pdf_table(table_input)---def _evaluate_entry(- document: PDFDocument,- entry: dict[str, Any],- page_cache: dict[int, tuple[Any, ...]],- *,- measure_performance: bool,-) -> tuple[dict[str, Any] | None, float, NativeTableInput]:- """构造一个 manifest 表格输入,并返回结构签名、耗时和诊断输入。"""-- page_index = int(entry["page_index"])- if page_index not in page_cache:- page = document[page_index]- page_cache[page_index] = (- page.size,- tuple(page.get_chars()),- coerce_native_table_rules(page.get_drawing_lines()),- coerce_native_table_rectangles(page.get_path_infos()),- )- page_size, chars, rules, rectangles = page_cache[page_index]- if "bbox_points" in entry:- point_bbox = tuple(float(value) for value in entry["bbox_points"])- else:- bbox = entry["bbox"]- # layout bbox 使用整数化 PDFPage 尺寸还原;评测必须复现同一生产坐标边界,- # 避免亚点级外缘生成幽灵轨道。- production_page_size = (int(page_size[0]), int(page_size[1]))- point_bbox = tuple(- bbox[index] * (production_page_size[0] if index % 2 == 0 else production_page_size[1]) for index in range(4)- )- table_input = NativeTableInput(- table_bbox=point_bbox,- page_size=page_size,- angle=0,- chars=chars,- drawing_lines=rules,- rectangles=rectangles,- )- actual, duration = _recover_table_input(- table_input,- measure_performance=measure_performance,- )- return actual, duration, table_input---def _entry_mismatch(- entry: dict[str, Any],- actual: dict[str, Any] | None,-) -> tuple[str, bool]:- """比较一个真值条目的输出模式、拓扑和单元格文本哈希。"""-- actual_output = "html" if actual is not None else "projection"- expected_output = entry["expected_output"]- mismatch = actual_output != expected_output- if actual is not None and expected_output == "html":- mismatch = mismatch or any(- actual[field] != entry[field]- for field in (- "rows",- "cols",- "span_signature",- "text_sha256",- )- )- return actual_output, mismatch---def main() -> None:- """校验 HTML 覆盖率、结构真值、文本哈希和解析性能。"""-- parser = argparse.ArgumentParser()- parser.add_argument(- "--source-root",- type=Path,- default=_DEFAULT_SOURCE_ROOT,- help="PDF 语料目录;默认使用仓库内 Native Table fixtures。",- )- parser.add_argument(- "--manifest",- type=Path,- default=Path("tests/fixtures/native_pdf_table_cross_page_manifest.json"),- )- parser.add_argument(- "--diagnostics-output",- type=Path,- help="可选写出逐表候选和首个拒绝门诊断。",- )- parser.add_argument(- "--skip-performance-gate",- action="store_true",- help="跳过易受共享 CI 负载影响的 p95 门,仅用于 pytest 功能回归。",- )- args = parser.parse_args()- manifest = json.loads(args.manifest.read_text(encoding="utf-8"))- _validate_portable_manifest(manifest)- entries_by_file: dict[str, list[dict[str, Any]]] = defaultdict(list)- for entry in manifest["entries"]:- entries_by_file[entry["file"]].append(entry)-- target_mismatches: list[dict[str, Any]] = []- regression_mismatches: list[dict[str, Any]] = []- diagnostics: list[dict[str, Any]] = []- html_count = 0- target_html_count = 0- durations: list[float] = []- measure_performance = not args.skip_performance_gate- collect_diagnostics = args.diagnostics_output is not None- for filename, entries in entries_by_file.items():- with PDFDocument(str(args.source_root / filename)) as document:- page_cache: dict[int, tuple[Any, ...]] = {}- for entry in entries:- actual, duration, table_input = _evaluate_entry(- document,- entry,- page_cache,- measure_performance=measure_performance,- )- durations.append(duration)- actual_output, mismatch = _entry_mismatch(entry, actual)- diagnostic = _maybe_diagnose_table_input(- table_input,- collect_diagnostics=collect_diagnostics,- mismatch=mismatch,- )- if diagnostic is not None:- diagnostics.append(- {- "scope": "corpus",- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "bbox": entry["bbox"],- "expected_output": entry["expected_output"],- **diagnostic,- }- )- if actual_output == "html":- html_count += 1- is_target = entry["review_status"] == "target_verified"- if is_target and actual_output == "html":- target_html_count += 1- if mismatch:- mismatch_record = {- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "review_status": entry["review_status"],- "expected_output": entry["expected_output"],- "actual": actual,- }- if diagnostic is not None:- mismatch_record["diagnostic"] = diagnostic- if is_target:- target_mismatches.append(mismatch_record)- else:- regression_mismatches.append(mismatch_record)-- flash_targets_by_file: dict[str, list[dict[str, Any]]] = defaultdict(list)- for entry in manifest.get("flash_targets", []):- flash_targets_by_file[entry["file"]].append(entry)- flash_target_html_count = 0- flash_target_mismatches: list[dict[str, Any]] = []- for filename, entries in flash_targets_by_file.items():- with PDFDocument(str(args.source_root / filename)) as document:- page_cache = {}- for entry in entries:- actual, duration, table_input = _evaluate_entry(- document,- entry,- page_cache,- measure_performance=measure_performance,- )- durations.append(duration)- actual_output, mismatch = _entry_mismatch(entry, actual)- diagnostic = _maybe_diagnose_table_input(- table_input,- collect_diagnostics=collect_diagnostics,- mismatch=mismatch,- )- if diagnostic is not None:- diagnostics.append(- {- "scope": "flash_target",- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "bbox_points": entry["bbox_points"],- "expected_output": entry["expected_output"],- **diagnostic,- }- )- if actual_output == "html":- flash_target_html_count += 1- if mismatch:- mismatch_record = {- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "expected_output": entry["expected_output"],- "actual": actual,- }- if diagnostic is not None:- mismatch_record["diagnostic"] = diagnostic- flash_target_mismatches.append(mismatch_record)-- total = len(manifest["entries"])- target_total = sum(entry["review_status"] == "target_verified" for entry in manifest["entries"])- flash_target_total = len(manifest.get("flash_targets", []))- p95_milliseconds = 1000.0 * statistics.quantiles(durations, n=20)[18] if len(durations) >= 20 else 0.0- summary = {- "accuracy_scope": manifest["accuracy_scope"],- "tables": total,- "html": html_count,- "coverage": html_count / total if total else 0.0,- "target_tables": target_total,- "target_html": target_html_count,- "target_mismatches": len(target_mismatches),- "target_precision": ((target_html_count - len(target_mismatches)) / target_html_count if target_html_count else 0.0),- "regression_mismatches": len(regression_mismatches),- "flash_targets": flash_target_total,- "flash_target_html": flash_target_html_count,- "flash_target_mismatches": len(flash_target_mismatches),- "p95_milliseconds": p95_milliseconds,- }- result_payload = {- "summary": summary,- "target_mismatches": target_mismatches,- "regression_mismatches": regression_mismatches,- "flash_target_mismatches": flash_target_mismatches,- }- print(json.dumps(result_payload, ensure_ascii=False, indent=2))- if args.diagnostics_output is not None:- args.diagnostics_output.parent.mkdir(parents=True, exist_ok=True)- args.diagnostics_output.write_text(- json.dumps(- {- "summary": summary,- "tables": diagnostics,- },- ensure_ascii=False,- indent=2,- ),- encoding="utf-8",- )- if (- html_count != manifest["expected_html"]- or target_total != manifest["target_verified_tables"]- or target_html_count != target_total- or target_mismatches- or regression_mismatches- or flash_target_html_count != flash_target_total- or flash_target_mismatches- or (not args.skip_performance_gate and p95_milliseconds > manifest["performance_p95_limit_ms"])- ):- raise SystemExit(1)---if __name__ == "__main__":- main()diff --git a/tests/fixtures/generate_synthetic_pdf_fixtures.py b/tests/fixtures/generate_synthetic_pdf_fixtures.pydeleted file mode 100644index 88d7a126..00000000--- a/tests/fixtures/generate_synthetic_pdf_fixtures.py+++ /dev/null@@ -1,465 +0,0 @@-#!/usr/bin/env python3-"""生成不含真实文档内容的 Flash PDF 单元测试夹具。"""--from __future__ import annotations--import argparse-from io import BytesIO-from pathlib import Path-from tempfile import TemporaryDirectory--from PIL import Image-from reportlab.lib.colors import HexColor, black-from reportlab.lib.pagesizes import A4-from reportlab.lib.utils import ImageReader-from reportlab.pdfbase import cidfonts, pdfmetrics-from reportlab.pdfgen.canvas import Canvas---PROJECT_ROOT = Path(__file__).resolve().parents[2]-OUTPUT_DIR = PROJECT_ROOT / "tests" / "unittest" / "pdfs"-FLASH_FIXTURE_NAME = "flash_table_annotations_synthetic.pdf"-CJK_FIXTURE_NAME = "native_cjk_layout_synthetic.pdf"-SAFE_WATERMARK_TEXT = "MINERU TEST WATERMARK"-NEUTRAL_METADATA_VALUE = "MinerU Test Suite"-CJK_FONT_NAME = "STSong-Light"-PAGE_WIDTH, PAGE_HEIGHT = A4---def _register_fonts() -> None:- """注册无需读取原文或本机私有字体文件的标准 CJK 字体。"""-- if CJK_FONT_NAME not in pdfmetrics.getRegisteredFontNames():- pdfmetrics.registerFont(cidfonts.UnicodeCIDFont(CJK_FONT_NAME))---def _new_canvas(output_path: Path) -> Canvas:- """创建具有固定元数据和确定性对象编号的 A4 PDF 画布。"""-- canvas = Canvas(- str(output_path),- pagesize=A4,- pageCompression=1,- invariant=1,- )- canvas.setAuthor(NEUTRAL_METADATA_VALUE)- canvas.setCreator(NEUTRAL_METADATA_VALUE)- canvas.setTitle(NEUTRAL_METADATA_VALUE)- canvas.setSubject("Synthetic PDF regression fixture")- canvas.setKeywords("MinerU synthetic test fixture")- canvas._doc.info.producer = NEUTRAL_METADATA_VALUE # noqa: SLF001- return canvas---def _draw_page_heading(canvas: Canvas, title: str, subtitle: str = "") -> None:- """绘制统一的合成页面标题和可选副标题。"""-- canvas.setFillColor(black)- canvas.setFont("Helvetica-Bold", 15)- canvas.drawString(54, PAGE_HEIGHT - 54, title)- if subtitle:- canvas.setFont("Helvetica", 9)- canvas.drawString(54, PAGE_HEIGHT - 70, subtitle)---def _draw_page_number(canvas: Canvas, page_number: int) -> None:- """在页面底部中央绘制独立页码。"""-- canvas.setFillColor(black)- canvas.setFont("Helvetica", 9)- canvas.drawCentredString(PAGE_WIDTH / 2, 30, str(page_number))---def _draw_table(- canvas: Canvas,- *,- left: float,- top: float,- width: float,- row_height: float,- rows: list[list[str]],-) -> tuple[float, float, float, float]:- """用矢量线和中性单元格文本绘制稳定的规则表格。"""-- column_count = len(rows[0])- height = row_height * len(rows)- bottom = top - height- column_width = width / column_count- canvas.saveState()- canvas.setStrokeColor(black)- canvas.setLineWidth(0.8)- for row_index in range(len(rows) + 1):- y = top - row_index * row_height- canvas.line(left, y, left + width, y)- for column_index in range(column_count + 1):- x = left + column_index * column_width- canvas.line(x, bottom, x, top)- canvas.setFont("Helvetica", 8)- for row_index, row in enumerate(rows):- baseline = top - row_index * row_height - 0.68 * row_height- for column_index, value in enumerate(row):- canvas.drawString(left + column_index * column_width + 5, baseline, value)- canvas.restoreState()- return left, bottom, left + width, top---def _solid_image_reader(color: tuple[int, int, int]) -> ImageReader:- """创建仅用于图像和 footer 几何回归的内存 PNG。"""-- image = Image.new("RGB", (80, 50), color=color)- buffer = BytesIO()- image.save(buffer, format="PNG", optimize=False)- buffer.seek(0)- return ImageReader(buffer)---def _draw_flash_fixture(output_path: Path) -> None:- """生成八页表格、注释、跨页和 footer 行为合成夹具。"""-- canvas = _new_canvas(output_path)-- _draw_page_heading(canvas, "Synthetic Flash Table Fixture", "Neutral content for parser regression tests")- canvas.setFont("Helvetica", 11)- canvas.drawString(72, 690, "This document contains only generated test content.")- canvas.drawString(72, 668, "Each page isolates one layout behavior used by the test suite.")- _draw_page_number(canvas, 1)- canvas.showPage()-- _draw_page_heading(canvas, "Two Independent Vector Tables")- canvas.setFont("Helvetica-Bold", 10)- canvas.drawString(72, 715, "Table 1 Synthetic Inventory")- _draw_table(- canvas,- left=72,- top=700,- width=450,- row_height=28,- rows=[- ["ITEM", "VALUE", "STATE"],- ["ALPHA", "10", "READY"],- ["BETA", "20", "READY"],- ["GAMMA", "30", "DONE"],- ],- )- canvas.drawString(72, 545, "Table 2 Synthetic Metrics")- _draw_table(- canvas,- left=72,- top=530,- width=450,- row_height=28,- rows=[- ["METRIC", "LOW", "HIGH"],- ["WIDTH", "12", "48"],- ["HEIGHT", "8", "32"],- ["COUNT", "3", "9"],- ],- )- canvas.setFont("Helvetica", 10)- canvas.drawString(72, 370, "Ordinary text below both tables must remain outside table bodies.")- _draw_page_number(canvas, 2)- canvas.showPage()-- _draw_page_heading(canvas, "Same-page Table Footnote Continuation")- canvas.setFont("Helvetica-Bold", 10)- canvas.drawString(72, 715, "Table 3 Synthetic Footnote Merge")- _draw_table(- canvas,- left=72,- top=700,- width=450,- row_height=30,- rows=[- ["FIELD", "DETAIL", "STATUS"],- ["A", "Generated value", "OK"],- ["B", "Generated value", "OK"],- ["C", "Generated value", "OK"],- ],- )- canvas.setFont("Helvetica", 8)- canvas.drawString(76, 535, "Note: This generated note belongs to Table 3.")- canvas.drawString(92, 523, "Its first indented continuation remains on the same page.")- canvas.drawString(92, 511, "Its second indented continuation completes the annotation.")- _draw_page_number(canvas, 3)- canvas.showPage()-- _draw_page_heading(canvas, "In-border Note Remains Table Content")- canvas.setFont("Helvetica-Bold", 10)- canvas.drawString(72, 715, "Table 4 Bordered Note")- _draw_table(- canvas,- left=72,- top=700,- width=450,- row_height=34,- rows=[- ["KEY", "DESCRIPTION", "FLAG"],- ["A1", "Neutral row", "YES"],- ["A2", "Neutral row", "NO"],- ["NOTE", "Note: This sentence is inside the border.", "TABLE"],- ],- )- _draw_page_number(canvas, 4)- canvas.showPage()-- _draw_page_heading(canvas, "Body Text Negative Samples")- canvas.setFont("Helvetica", 10)- canvas.drawString(72, 700, "This ordinary paragraph is unrelated to any table or figure.")- canvas.drawString(72, 680, "ITEM_001 and VALUE_002 are prose tokens, not a code block.")- canvas.drawString(72, 660, "A distant Note: marker remains body text without a visual parent.")- canvas.drawString(72, 620, "The parser should preserve these lines as readable text.")- _draw_page_number(canvas, 5)- canvas.showPage()-- _draw_page_heading(canvas, "Code-like Cells Stay in a Table")- canvas.setFont("Helvetica-Bold", 10)- canvas.drawString(72, 715, "Table 5 Generated Token Grid")- _draw_table(- canvas,- left=72,- top=700,- width=450,- row_height=30,- rows=[- ["TOKEN", "EXPRESSION", "RESULT"],- ["ROW_001", "A=B+1", "PASS"],- ["ROW_002", "C=D+2", "PASS"],- ["ROW_003", "E=F+3", "PASS"],- ],- )- canvas.setFont("Helvetica", 8)- canvas.drawString(76, 566, "Note: Token-shaped cell text must not become a code block.")- _draw_page_number(canvas, 6)- canvas.showPage()-- _draw_page_heading(canvas, "Cross-page Footnote Boundary")- canvas.setFont("Helvetica-Bold", 10)- canvas.drawString(72, 250, "Table 6 Page-local Annotation")- _draw_table(- canvas,- left=72,- top=235,- width=450,- row_height=30,- rows=[- ["GROUP", "VALUE", "STATE"],- ["LOCAL", "77", "OPEN"],- ["LOCAL", "88", "CLOSED"],- ],- )- canvas.setFont("Helvetica", 8)- canvas.drawString(76, 132, "Note: This annotation ends on page seven.")- _draw_page_number(canvas, 7)- canvas.showPage()-- _draw_page_heading(canvas, "Cross-page Text and Empty Footer Image")- canvas.setFont("Helvetica", 9)- canvas.drawString(92, 744, "This top paragraph must not merge into the previous page footnote.")- canvas.drawString(72, 700, "The final page also contains an image below its page number.")- _draw_page_number(canvas, 8)- canvas.drawImage(- _solid_image_reader((220, 230, 240)),- PAGE_WIDTH / 2 - 60,- 1,- width=120,- height=26,- mask="auto",- )- canvas.showPage()- canvas.save()---def _draw_safe_watermark_grid(canvas: Canvas) -> None:- """在当前页底层绘制四乘四个安全旋转文本水印。"""-- canvas.saveState()- canvas.setFillColor(HexColor("#D9DEE7"))- canvas.setFont("Helvetica", 7)- for row_index in range(4):- for column_index in range(4):- canvas.saveState()- canvas.translate(48 + column_index * 145, 120 + row_index * 185)- canvas.rotate(5.5)- canvas.drawString(0, 0, SAFE_WATERMARK_TEXT)- canvas.restoreState()- canvas.restoreState()---def _draw_cjk_page_heading(canvas: Canvas, title: str) -> None:- """用标准 CJK 字体绘制合成中文页面标题。"""-- canvas.setFillColor(black)- canvas.setFont(CJK_FONT_NAME, 15)- canvas.drawString(54, PAGE_HEIGHT - 54, title)---def _draw_mixed_line(- canvas: Canvas,- *,- y: float,- cjk_prefix: str,- latin_suffix: str,-) -> None:- """在同一基线绘制 CJK 与西文字体混排的物理行。"""-- line_x = 72.0- if cjk_prefix.startswith("• "):- canvas.setFont("Helvetica", 10)- canvas.drawString(line_x, y, "• ")- line_x += pdfmetrics.stringWidth("• ", "Helvetica", 10)- cjk_prefix = cjk_prefix[2:]- canvas.setFont(CJK_FONT_NAME, 10)- canvas.drawString(line_x, y, cjk_prefix)- prefix_width = pdfmetrics.stringWidth(cjk_prefix, CJK_FONT_NAME, 10)- canvas.setFont("Helvetica", 10)- canvas.drawString(line_x + prefix_width, y, latin_suffix)---def _draw_link_text(- canvas: Canvas,- *,- x: float,- y: float,- visible_text: str,- target: str,-) -> float:- """绘制带精确 URI 注解的西文文本并返回其右边界。"""-- font_name = "Helvetica"- font_size = 9- width = pdfmetrics.stringWidth(visible_text, font_name, font_size)- canvas.setFont(font_name, font_size)- canvas.drawString(x, y, visible_text)- canvas.linkURL(- target,- (x, y - 2, x + width, y + font_size + 1),- relative=0,- thickness=0,- )- return x + width---def _draw_cjk_fixture(output_path: Path) -> None:- """生成四页目录、字体、URL 和安全水印合成夹具。"""-- _register_fonts()- canvas = _new_canvas(output_path)-- _draw_safe_watermark_grid(canvas)- _draw_cjk_page_heading(canvas, "MinerU 合成原生文本测试")- canvas.setFont(CJK_FONT_NAME, 11)- canvas.drawString(72, 690, "本文档完全由测试生成器创建,不包含真实人员或组织信息。")- canvas.drawString(72, 665, "页面用于验证目录、图注、链接、字体基线和水印过滤。")- _draw_page_number(canvas, 1)- canvas.showPage()-- _draw_safe_watermark_grid(canvas)- _draw_cjk_page_heading(canvas, "目录")- canvas.setFont(CJK_FONT_NAME, 9)- for row_index in range(24):- baseline = 742 - row_index * 26- canvas.drawString(65, baseline, f"{row_index + 1} 合成章节 {row_index + 1}")- canvas.drawRightString(520, baseline, str(row_index + 1))- _draw_page_number(canvas, 2)- canvas.showPage()-- _draw_safe_watermark_grid(canvas)- _draw_cjk_page_heading(canvas, "混合字体和基线")- _draw_mixed_line(canvas, y=700, cjk_prefix="• 合成支持工程师 ", latin_suffix="Support Engineer")- _draw_mixed_line(canvas, y=660, cjk_prefix="• 混合字体工具 ", latin_suffix="Acuity Toolkit")- _draw_mixed_line(canvas, y=620, cjk_prefix="• 测试系统 ", latin_suffix="Ubuntu 24.04")- canvas.setFont("Helvetica", 10)- canvas.drawString(72, 580, "mineru_toolkit_binary_1.0.0_linux_x86_64.tgz")- canvas.setFont(CJK_FONT_NAME, 10)- canvas.drawString(72, 535, "以上普通文本均应保持在基线,不应生成上下标标签。")- _draw_page_number(canvas, 3)- canvas.showPage()-- _draw_safe_watermark_grid(canvas)- _draw_cjk_page_heading(canvas, "图注和链接")- canvas.drawImage(_solid_image_reader((210, 225, 240)), 72, 565, width=190, height=105, mask="auto")- canvas.drawImage(_solid_image_reader((235, 220, 210)), 332, 565, width=190, height=105, mask="auto")- canvas.setFont(CJK_FONT_NAME, 9)- canvas.drawString(72, 548, "图 1 合成示意图 A")- canvas.drawString(332, 548, "图 2 合成示意图 B")- wrapped_url = "https://example.com/downloads/mineru/fixture/"- _draw_link_text(- canvas,- x=72,- y=485,- visible_text="https://example.com/downloads/",- target=wrapped_url,- )- _draw_link_text(- canvas,- x=72,- y=473,- visible_text="mineru/fixture/",- target=wrapped_url,- )- link_x = 72.0- for link_index, target in enumerate(- (- "https://example.com/ref/a",- "https://example.com/ref/b",- "https://example.com/ref/c",- )- ):- if link_index:- link_x += pdfmetrics.stringWidth(" ", "Helvetica", 9)- link_x = _draw_link_text(- canvas,- x=link_x,- y=425,- visible_text=target,- target=target,- )- canvas.setFont(CJK_FONT_NAME, 9)- canvas.drawString(72, 390, "链接均使用保留域名,不指向真实账号或资源。")- _draw_page_number(canvas, 4)- canvas.showPage()- canvas.save()---def generate_fixtures(output_dir: Path) -> tuple[Path, Path]:- """生成两份合成 PDF 并返回稳定输出路径。"""-- output_dir.mkdir(parents=True, exist_ok=True)- flash_path = output_dir / FLASH_FIXTURE_NAME- cjk_path = output_dir / CJK_FIXTURE_NAME- _draw_flash_fixture(flash_path)- _draw_cjk_fixture(cjk_path)- return flash_path, cjk_path---def _check_committed_fixtures() -> None:- """重新生成夹具并逐字节校验仓库产物未发生漂移。"""-- with TemporaryDirectory(prefix="mineru-synthetic-pdf-") as temporary_directory:- generated_paths = generate_fixtures(Path(temporary_directory))- for generated_path in generated_paths:- committed_path = OUTPUT_DIR / generated_path.name- if not committed_path.is_file():- raise SystemExit(f"missing committed fixture: {committed_path}")- if generated_path.read_bytes() != committed_path.read_bytes():- raise SystemExit(f"fixture is stale: {committed_path}")---def main() -> None:- """解析命令行参数并执行生成或一致性检查。"""-- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument(- "--check",- action="store_true",- help="regenerate in a temporary directory and compare committed PDFs",- )- arguments = parser.parse_args()- if arguments.check:- _check_committed_fixtures()- return- generate_fixtures(OUTPUT_DIR)---if __name__ == "__main__":- main()diff --git a/tests/fixtures/hybrid_pdf_script_inputs.json b/tests/fixtures/hybrid_pdf_script_inputs.jsonnew file mode 100644index 00000000..30fa6021--- /dev/null+++ b/tests/fixtures/hybrid_pdf_script_inputs.json@@ -0,0 +1,22781 @@+{+ "schema_version": 1,+ "producer": {+ "docvortex": "0.1.0",+ "pypdfium2": "5.10.1"+ },+ "sources": {+ "tests/unittest/pdfs/native_cjk_layout_synthetic.pdf": {+ "sha256": "78ae9e8f670a99c17058ec53e5abdf7631671830e84461803ed2f00c1778ee59"+ },+ "tests/unittest/pdfs/metabolic_pathway_page_3.pdf": {+ "sha256": "f383399e3459b20e35a13290a1e813dcd964850c3bf945fe64fb1cd3bfe54b12"+ }+ },+ "cases": [+ {+ "source": "tests/unittest/pdfs/native_cjk_layout_synthetic.pdf",+ "page_index": 2,+ "probe": "• 合成支持工程师 Support Engineer",+ "selection": "lines",+ "fragments": [+ {+ "chars": [+ {+ "bbox": [+ 72.0,+ 132.95001220703125,+ 75.5,+ 144.1099853515625+ ],+ "char": "•",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 365,+ "source_indices": [+ 365+ ],+ "raw_code": 8226,+ "loose_bbox": [+ 72.0,+ 132.83978271484375,+ 75.5,+ 143.999755859375+ ],+ "tight_bbox": [+ 72.52999877929688,+ 137.1497802734375,+ 75.01000213623047,+ 139.6197509765625+ ],+ "origin": [+ 72.0,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 75.5,+ 132.95001220703125,+ 78.27999877929688,+ 144.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 366,+ "source_indices": [+ 366+ ],+ "raw_code": 32,+ "loose_bbox": [+ 75.5,+ 132.83978271484375,+ 78.27999877929688,+ 143.999755859375+ ],+ "tight_bbox": [+ 75.5,+ 141.8797607421875,+ 78.27999877929688,+ 141.8897705078125+ ],+ "origin": [+ 75.5,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 78.27999877929688,+ 133.67999267578125,+ 88.27999877929688,+ 144.53997802734375+ ],+ "char": "合",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 367,+ "source_indices": [+ 367+ ],+ "raw_code": 21512,+ "loose_bbox": [+ 78.27999877929688,+ 133.56976318359375,+ 88.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 78.66999816894531,+ 133.56976318359375,+ 87.8499984741211,+ 142.77978515625+ ],+ "origin": [+ 78.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 88.27999877929688,+ 133.78997802734375,+ 98.27999877929688,+ 144.53997802734375+ ],+ "char": "成",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 368,+ "source_indices": [+ 368+ ],+ "raw_code": 25104,+ "loose_bbox": [+ 88.27999877929688,+ 133.67974853515625,+ 98.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 88.66999816894531,+ 133.67974853515625,+ 97.7699966430664,+ 142.77978515625+ ],+ "origin": [+ 88.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 98.27999877929688,+ 133.78997802734375,+ 108.27999877929688,+ 144.53997802734375+ ],+ "char": "支",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 369,+ "source_indices": [+ 369+ ],+ "raw_code": 25903,+ "loose_bbox": [+ 98.27999877929688,+ 133.67974853515625,+ 108.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 98.94000244140625,+ 133.67974853515625,+ 107.69000244140625,+ 142.81976318359375+ ],+ "origin": [+ 98.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 108.27999877929688,+ 133.75,+ 118.27999877929688,+ 144.53997802734375+ ],+ "char": "持",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 370,+ "source_indices": [+ 370+ ],+ "raw_code": 25345,+ "loose_bbox": [+ 108.27999877929688,+ 133.6397705078125,+ 118.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 108.66999816894531,+ 133.6397705078125,+ 117.7699966430664,+ 142.77978515625+ ],+ "origin": [+ 108.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 118.27999877929688,+ 134.3499755859375,+ 128.27999877929688,+ 144.53997802734375+ ],+ "char": "工",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 371,+ "source_indices": [+ 371+ ],+ "raw_code": 24037,+ "loose_bbox": [+ 118.27999877929688,+ 134.23974609375,+ 128.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 118.8699951171875,+ 134.23974609375,+ 127.69000244140625,+ 142.46978759765625+ ],+ "origin": [+ 118.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 128.27999877929688,+ 133.8699951171875,+ 138.27999877929688,+ 144.53997802734375+ ],+ "char": "程",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 372,+ "source_indices": [+ 372+ ],+ "raw_code": 31243,+ "loose_bbox": [+ 128.27999877929688,+ 133.759765625,+ 138.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 128.70999145507812,+ 133.759765625,+ 137.72999572753906,+ 142.77978515625+ ],+ "origin": [+ 128.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 138.27999877929688,+ 133.78997802734375,+ 148.27999877929688,+ 144.53997802734375+ ],+ "char": "师",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 373,+ "source_indices": [+ 373+ ],+ "raw_code": 24072,+ "loose_bbox": [+ 138.27999877929688,+ 133.67974853515625,+ 148.27999877929688,+ 144.42974853515625+ ],+ "tight_bbox": [+ 139.3300018310547,+ 133.67974853515625,+ 147.66000366210938,+ 142.77978515625+ ],+ "origin": [+ 138.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 148.27999877929688,+ 134.47998046875,+ 150.35000610351562,+ 144.53997802734375+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 374,+ "source_indices": [+ 374+ ],+ "raw_code": 32,+ "loose_bbox": [+ 148.27999877929688,+ 134.3697509765625,+ 150.35000610351562,+ 144.42974853515625+ ],+ "tight_bbox": [+ 148.27999877929688,+ 141.8797607421875,+ 150.35000610351562,+ 141.8897705078125+ ],+ "origin": [+ 148.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 150.35000610351562,+ 132.95001220703125,+ 157.02000427246094,+ 144.1099853515625+ ],+ "char": "S",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 375,+ "source_indices": [+ 375+ ],+ "raw_code": 83,+ "loose_bbox": [+ 150.35000610351562,+ 132.83978271484375,+ 157.02000427246094,+ 143.999755859375+ ],+ "tight_bbox": [+ 150.8000030517578,+ 134.6097412109375,+ 156.5,+ 141.999755859375+ ],+ "origin": [+ 150.35000610351562,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 157.02000427246094,+ 132.95001220703125,+ 162.5800018310547,+ 144.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 376,+ "source_indices": [+ 376+ ],+ "raw_code": 117,+ "loose_bbox": [+ 157.02000427246094,+ 132.83978271484375,+ 162.5800018310547,+ 143.999755859375+ ],+ "tight_bbox": [+ 157.66000366210938,+ 136.69976806640625,+ 161.86000061035156,+ 141.999755859375+ ],+ "origin": [+ 157.02000427246094,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 162.5800018310547,+ 132.95001220703125,+ 168.13999938964844,+ 144.1099853515625+ ],+ "char": "p",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 377,+ "source_indices": [+ 377+ ],+ "raw_code": 112,+ "loose_bbox": [+ 162.5800018310547,+ 132.83978271484375,+ 168.13999938964844,+ 143.999755859375+ ],+ "tight_bbox": [+ 163.24000549316406,+ 136.58978271484375,+ 167.74000549316406,+ 143.8697509765625+ ],+ "origin": [+ 162.5800018310547,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 168.13999938964844,+ 132.95001220703125,+ 173.6999969482422,+ 144.1099853515625+ ],+ "char": "p",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 378,+ "source_indices": [+ 378+ ],+ "raw_code": 112,+ "loose_bbox": [+ 168.13999938964844,+ 132.83978271484375,+ 173.6999969482422,+ 143.999755859375+ ],+ "tight_bbox": [+ 168.8000030517578,+ 136.58978271484375,+ 173.3000030517578,+ 143.8697509765625+ ],+ "origin": [+ 168.13999938964844,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 173.70001220703125,+ 132.95001220703125,+ 179.260009765625,+ 144.1099853515625+ ],+ "char": "o",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 379,+ "source_indices": [+ 379+ ],+ "raw_code": 111,+ "loose_bbox": [+ 173.70001220703125,+ 132.83978271484375,+ 179.260009765625,+ 143.999755859375+ ],+ "tight_bbox": [+ 174.02999877929688,+ 136.58978271484375,+ 178.88999938964844,+ 141.999755859375+ ],+ "origin": [+ 173.70001220703125,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 179.260009765625,+ 132.95001220703125,+ 182.73001098632812,+ 144.1099853515625+ ],+ "char": "r",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 380,+ "source_indices": [+ 380+ ],+ "raw_code": 114,+ "loose_bbox": [+ 179.260009765625,+ 132.83978271484375,+ 182.73001098632812,+ 143.999755859375+ ],+ "tight_bbox": [+ 179.91000366210938,+ 136.58978271484375,+ 182.73001098632812,+ 141.8897705078125+ ],+ "origin": [+ 179.260009765625,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 182.58999633789062,+ 132.95001220703125,+ 185.3699951171875,+ 144.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 381,+ "source_indices": [+ 381+ ],+ "raw_code": 116,+ "loose_bbox": [+ 182.58999633789062,+ 132.83978271484375,+ 185.3699951171875,+ 143.999755859375+ ],+ "tight_bbox": [+ 182.77000427246094,+ 134.8897705078125,+ 185.3000030517578,+ 141.94976806640625+ ],+ "origin": [+ 182.58999633789062,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 185.3699951171875,+ 132.95001220703125,+ 188.14999389648438,+ 144.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 382,+ "source_indices": [+ 382+ ],+ "raw_code": 32,+ "loose_bbox": [+ 185.3699951171875,+ 132.83978271484375,+ 188.14999389648438,+ 143.999755859375+ ],+ "tight_bbox": [+ 185.3699951171875,+ 141.8797607421875,+ 188.14999389648438,+ 141.8897705078125+ ],+ "origin": [+ 185.3699951171875,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 188.14999389648438,+ 132.95001220703125,+ 194.8199920654297,+ 144.1099853515625+ ],+ "char": "E",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 383,+ "source_indices": [+ 383+ ],+ "raw_code": 69,+ "loose_bbox": [+ 188.14999389648438,+ 132.83978271484375,+ 194.8199920654297,+ 143.999755859375+ ],+ "tight_bbox": [+ 188.94000244140625,+ 134.72979736328125,+ 194.27999877929688,+ 141.8897705078125+ ],+ "origin": [+ 188.14999389648438,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 194.82000732421875,+ 132.95001220703125,+ 200.3800048828125,+ 144.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 384,+ "source_indices": [+ 384+ ],+ "raw_code": 110,+ "loose_bbox": [+ 194.82000732421875,+ 132.83978271484375,+ 200.3800048828125,+ 143.999755859375+ ],+ "tight_bbox": [+ 195.47999572753906,+ 136.58978271484375,+ 199.69000244140625,+ 141.8897705078125+ ],+ "origin": [+ 194.82000732421875,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 200.3800048828125,+ 132.95001220703125,+ 205.94000244140625,+ 144.1099853515625+ ],+ "char": "g",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 385,+ "source_indices": [+ 385+ ],+ "raw_code": 103,+ "loose_bbox": [+ 200.3800048828125,+ 132.83978271484375,+ 205.94000244140625,+ 143.999755859375+ ],+ "tight_bbox": [+ 200.6999969482422,+ 136.58978271484375,+ 205.27000427246094,+ 143.97979736328125+ ],+ "origin": [+ 200.3800048828125,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 205.94000244140625,+ 132.95001220703125,+ 208.16000366210938,+ 144.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 386,+ "source_indices": [+ 386+ ],+ "raw_code": 105,+ "loose_bbox": [+ 205.94000244140625,+ 132.83978271484375,+ 208.16000366210938,+ 143.999755859375+ ],+ "tight_bbox": [+ 206.60000610351562,+ 134.72979736328125,+ 207.48001098632812,+ 141.8897705078125+ ],+ "origin": [+ 205.94000244140625,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 208.16000366210938,+ 132.95001220703125,+ 213.72000122070312,+ 144.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 387,+ "source_indices": [+ 387+ ],+ "raw_code": 110,+ "loose_bbox": [+ 208.16000366210938,+ 132.83978271484375,+ 213.72000122070312,+ 143.999755859375+ ],+ "tight_bbox": [+ 208.82000732421875,+ 136.58978271484375,+ 213.02999877929688,+ 141.8897705078125+ ],+ "origin": [+ 208.16000366210938,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 213.72000122070312,+ 132.95001220703125,+ 219.27999877929688,+ 144.1099853515625+ ],+ "char": "e",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 388,+ "source_indices": [+ 388+ ],+ "raw_code": 101,+ "loose_bbox": [+ 213.72000122070312,+ 132.83978271484375,+ 219.27999877929688,+ 143.999755859375+ ],+ "tight_bbox": [+ 214.08999633789062,+ 136.58978271484375,+ 218.8699951171875,+ 141.999755859375+ ],+ "origin": [+ 213.72000122070312,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 219.27999877929688,+ 132.95001220703125,+ 224.83999633789062,+ 144.1099853515625+ ],+ "char": "e",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 389,+ "source_indices": [+ 389+ ],+ "raw_code": 101,+ "loose_bbox": [+ 219.27999877929688,+ 132.83978271484375,+ 224.83999633789062,+ 143.999755859375+ ],+ "tight_bbox": [+ 219.65000915527344,+ 136.58978271484375,+ 224.4300079345703,+ 141.999755859375+ ],+ "origin": [+ 219.27999877929688,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 224.83999633789062,+ 132.95001220703125,+ 228.30999755859375,+ 144.1099853515625+ ],+ "char": "r",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 390,+ "source_indices": [+ 390+ ],+ "raw_code": 114,+ "loose_bbox": [+ 224.83999633789062,+ 132.83978271484375,+ 228.30999755859375,+ 143.999755859375+ ],+ "tight_bbox": [+ 225.49000549316406,+ 136.58978271484375,+ 228.30999755859375,+ 141.8897705078125+ ],+ "origin": [+ 224.83999633789062,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 228.1699981689453,+ 142.0,+ 228.1699981689453,+ 142.0+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 391,+ "source_indices": [+ 391+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 228.1699981689453,+ 141.8897705078125+ ]+ },+ {+ "bbox": [+ 228.1699981689453,+ 142.0,+ 228.1699981689453,+ 142.0+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 392,+ "source_indices": [+ 392+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 228.1699981689453,+ 141.8897705078125+ ]+ }+ ],+ "tight_bboxes": {+ "365": [+ 72.52999877929688,+ 137.1497802734375,+ 75.01000213623047,+ 139.6197509765625+ ],+ "366": [+ 75.5,+ 141.8797607421875,+ 78.27999877929688,+ 141.8897705078125+ ],+ "367": [+ 78.66999816894531,+ 133.56976318359375,+ 87.8499984741211,+ 142.77978515625+ ],+ "368": [+ 88.66999816894531,+ 133.67974853515625,+ 97.7699966430664,+ 142.77978515625+ ],+ "369": [+ 98.94000244140625,+ 133.67974853515625,+ 107.69000244140625,+ 142.81976318359375+ ],+ "370": [+ 108.66999816894531,+ 133.6397705078125,+ 117.7699966430664,+ 142.77978515625+ ],+ "371": [+ 118.8699951171875,+ 134.23974609375,+ 127.69000244140625,+ 142.46978759765625+ ],+ "372": [+ 128.70999145507812,+ 133.759765625,+ 137.72999572753906,+ 142.77978515625+ ],+ "373": [+ 139.3300018310547,+ 133.67974853515625,+ 147.66000366210938,+ 142.77978515625+ ],+ "374": [+ 148.27999877929688,+ 141.8797607421875,+ 150.35000610351562,+ 141.8897705078125+ ],+ "375": [+ 150.8000030517578,+ 134.6097412109375,+ 156.5,+ 141.999755859375+ ],+ "376": [+ 157.66000366210938,+ 136.69976806640625,+ 161.86000061035156,+ 141.999755859375+ ],+ "377": [+ 163.24000549316406,+ 136.58978271484375,+ 167.74000549316406,+ 143.8697509765625+ ],+ "378": [+ 168.8000030517578,+ 136.58978271484375,+ 173.3000030517578,+ 143.8697509765625+ ],+ "379": [+ 174.02999877929688,+ 136.58978271484375,+ 178.88999938964844,+ 141.999755859375+ ],+ "380": [+ 179.91000366210938,+ 136.58978271484375,+ 182.73001098632812,+ 141.8897705078125+ ],+ "381": [+ 182.77000427246094,+ 134.8897705078125,+ 185.3000030517578,+ 141.94976806640625+ ],+ "382": [+ 185.3699951171875,+ 141.8797607421875,+ 188.14999389648438,+ 141.8897705078125+ ],+ "383": [+ 188.94000244140625,+ 134.72979736328125,+ 194.27999877929688,+ 141.8897705078125+ ],+ "384": [+ 195.47999572753906,+ 136.58978271484375,+ 199.69000244140625,+ 141.8897705078125+ ],+ "385": [+ 200.6999969482422,+ 136.58978271484375,+ 205.27000427246094,+ 143.97979736328125+ ],+ "386": [+ 206.60000610351562,+ 134.72979736328125,+ 207.48001098632812,+ 141.8897705078125+ ],+ "387": [+ 208.82000732421875,+ 136.58978271484375,+ 213.02999877929688,+ 141.8897705078125+ ],+ "388": [+ 214.08999633789062,+ 136.58978271484375,+ 218.8699951171875,+ 141.999755859375+ ],+ "389": [+ 219.65000915527344,+ 136.58978271484375,+ 224.4300079345703,+ 141.999755859375+ ],+ "390": [+ 225.49000549316406,+ 136.58978271484375,+ 228.30999755859375,+ 141.8897705078125+ ]+ },+ "origins": {+ "365": [+ 72.0,+ 141.8897705078125+ ],+ "366": [+ 75.5,+ 141.8897705078125+ ],+ "367": [+ 78.27999877929688,+ 141.8897705078125+ ],+ "368": [+ 88.27999877929688,+ 141.8897705078125+ ],+ "369": [+ 98.27999877929688,+ 141.8897705078125+ ],+ "370": [+ 108.27999877929688,+ 141.8897705078125+ ],+ "371": [+ 118.27999877929688,+ 141.8897705078125+ ],+ "372": [+ 128.27999877929688,+ 141.8897705078125+ ],+ "373": [+ 138.27999877929688,+ 141.8897705078125+ ],+ "374": [+ 148.27999877929688,+ 141.8897705078125+ ],+ "375": [+ 150.35000610351562,+ 141.8897705078125+ ],+ "376": [+ 157.02000427246094,+ 141.8897705078125+ ],+ "377": [+ 162.5800018310547,+ 141.8897705078125+ ],+ "378": [+ 168.13999938964844,+ 141.8897705078125+ ],+ "379": [+ 173.70001220703125,+ 141.8897705078125+ ],+ "380": [+ 179.260009765625,+ 141.8897705078125+ ],+ "381": [+ 182.58999633789062,+ 141.8897705078125+ ],+ "382": [+ 185.3699951171875,+ 141.8897705078125+ ],+ "383": [+ 188.14999389648438,+ 141.8897705078125+ ],+ "384": [+ 194.82000732421875,+ 141.8897705078125+ ],+ "385": [+ 200.3800048828125,+ 141.8897705078125+ ],+ "386": [+ 205.94000244140625,+ 141.8897705078125+ ],+ "387": [+ 208.16000366210938,+ 141.8897705078125+ ],+ "388": [+ 213.72000122070312,+ 141.8897705078125+ ],+ "389": [+ 219.27999877929688,+ 141.8897705078125+ ],+ "390": [+ 224.83999633789062,+ 141.8897705078125+ ],+ "391": [+ 228.1699981689453,+ 141.8897705078125+ ],+ "392": [+ 228.1699981689453,+ 141.8897705078125+ ]+ }+ }+ ]+ },+ {+ "source": "tests/unittest/pdfs/native_cjk_layout_synthetic.pdf",+ "page_index": 2,+ "probe": "• 混合字体工具 Acuity Toolkit",+ "selection": "lines",+ "fragments": [+ {+ "chars": [+ {+ "bbox": [+ 72.0,+ 172.95001220703125,+ 75.5,+ 184.1099853515625+ ],+ "char": "•",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 393,+ "source_indices": [+ 393+ ],+ "raw_code": 8226,+ "loose_bbox": [+ 72.0,+ 172.83978271484375,+ 75.5,+ 183.999755859375+ ],+ "tight_bbox": [+ 72.52999877929688,+ 177.1497802734375,+ 75.01000213623047,+ 179.6197509765625+ ],+ "origin": [+ 72.0,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 75.5,+ 172.95001220703125,+ 78.27999877929688,+ 184.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 394,+ "source_indices": [+ 394+ ],+ "raw_code": 32,+ "loose_bbox": [+ 75.5,+ 172.83978271484375,+ 78.27999877929688,+ 183.999755859375+ ],+ "tight_bbox": [+ 75.5,+ 181.8797607421875,+ 78.27999877929688,+ 181.8897705078125+ ],+ "origin": [+ 75.5,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 78.27999877929688,+ 173.8699951171875,+ 88.27999877929688,+ 184.53997802734375+ ],+ "char": "混",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 395,+ "source_indices": [+ 395+ ],+ "raw_code": 28151,+ "loose_bbox": [+ 78.27999877929688,+ 173.759765625,+ 88.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 78.75,+ 173.759765625,+ 87.8499984741211,+ 182.73974609375+ ],+ "origin": [+ 78.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 88.27999877929688,+ 173.67999267578125,+ 98.27999877929688,+ 184.53997802734375+ ],+ "char": "合",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 396,+ "source_indices": [+ 396+ ],+ "raw_code": 21512,+ "loose_bbox": [+ 88.27999877929688,+ 173.56976318359375,+ 98.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 88.66999816894531,+ 173.56976318359375,+ 97.8499984741211,+ 182.77978515625+ ],+ "origin": [+ 88.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 98.27999877929688,+ 173.719970703125,+ 108.27999877929688,+ 184.53997802734375+ ],+ "char": "字",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 397,+ "source_indices": [+ 397+ ],+ "raw_code": 23383,+ "loose_bbox": [+ 98.27999877929688,+ 173.6097412109375,+ 108.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 98.94000244140625,+ 173.6097412109375,+ 107.6199951171875,+ 182.81976318359375+ ],+ "origin": [+ 98.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 108.27999877929688,+ 173.78997802734375,+ 118.27999877929688,+ 184.53997802734375+ ],+ "char": "体",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 398,+ "source_indices": [+ 398+ ],+ "raw_code": 20307,+ "loose_bbox": [+ 108.27999877929688,+ 173.67974853515625,+ 118.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 108.66999816894531,+ 173.67974853515625,+ 117.8499984741211,+ 182.81976318359375+ ],+ "origin": [+ 108.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 118.27999877929688,+ 174.3499755859375,+ 128.27999877929688,+ 184.53997802734375+ ],+ "char": "工",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 399,+ "source_indices": [+ 399+ ],+ "raw_code": 24037,+ "loose_bbox": [+ 118.27999877929688,+ 174.23974609375,+ 128.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 118.8699951171875,+ 174.23974609375,+ 127.69000244140625,+ 182.46978759765625+ ],+ "origin": [+ 118.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 128.27999877929688,+ 174.07000732421875,+ 138.27999877929688,+ 184.53997802734375+ ],+ "char": "具",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 400,+ "source_indices": [+ 400+ ],+ "raw_code": 20855,+ "loose_bbox": [+ 128.27999877929688,+ 173.95977783203125,+ 138.27999877929688,+ 184.42974853515625+ ],+ "tight_bbox": [+ 128.75,+ 173.95977783203125,+ 137.76998901367188,+ 182.8597412109375+ ],+ "origin": [+ 128.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 138.27999877929688,+ 174.47998046875,+ 140.35000610351562,+ 184.53997802734375+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 401,+ "source_indices": [+ 401+ ],+ "raw_code": 32,+ "loose_bbox": [+ 138.27999877929688,+ 174.3697509765625,+ 140.35000610351562,+ 184.42974853515625+ ],+ "tight_bbox": [+ 138.27999877929688,+ 181.8797607421875,+ 140.35000610351562,+ 181.8897705078125+ ],+ "origin": [+ 138.27999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 140.35000610351562,+ 172.95001220703125,+ 147.02999877929688,+ 184.1099853515625+ ],+ "char": "A",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 402,+ "source_indices": [+ 402+ ],+ "raw_code": 65,+ "loose_bbox": [+ 140.35000610351562,+ 172.83978271484375,+ 147.02999877929688,+ 183.999755859375+ ],+ "tight_bbox": [+ 140.35000610351562,+ 174.72979736328125,+ 147.02999877929688,+ 181.8897705078125+ ],+ "origin": [+ 140.35000610351562,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 147.02000427246094,+ 172.95001220703125,+ 152.02000427246094,+ 184.1099853515625+ ],+ "char": "c",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 403,+ "source_indices": [+ 403+ ],+ "raw_code": 99,+ "loose_bbox": [+ 147.02000427246094,+ 172.83978271484375,+ 152.02000427246094,+ 183.999755859375+ ],+ "tight_bbox": [+ 147.41000366210938,+ 176.58978271484375,+ 151.9300079345703,+ 181.999755859375+ ],+ "origin": [+ 147.02000427246094,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 152.02000427246094,+ 172.95001220703125,+ 157.5800018310547,+ 184.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 404,+ "source_indices": [+ 404+ ],+ "raw_code": 117,+ "loose_bbox": [+ 152.02000427246094,+ 172.83978271484375,+ 157.5800018310547,+ 183.999755859375+ ],+ "tight_bbox": [+ 152.66000366210938,+ 176.69976806640625,+ 156.86000061035156,+ 181.999755859375+ ],+ "origin": [+ 152.02000427246094,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 157.5800018310547,+ 172.95001220703125,+ 159.8000030517578,+ 184.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 405,+ "source_indices": [+ 405+ ],+ "raw_code": 105,+ "loose_bbox": [+ 157.5800018310547,+ 172.83978271484375,+ 159.8000030517578,+ 183.999755859375+ ],+ "tight_bbox": [+ 158.24000549316406,+ 174.72979736328125,+ 159.12001037597656,+ 181.8897705078125+ ],+ "origin": [+ 157.5800018310547,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 159.8000030517578,+ 172.95001220703125,+ 162.5800018310547,+ 184.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 406,+ "source_indices": [+ 406+ ],+ "raw_code": 116,+ "loose_bbox": [+ 159.8000030517578,+ 172.83978271484375,+ 162.5800018310547,+ 183.999755859375+ ],+ "tight_bbox": [+ 159.98001098632812,+ 174.8897705078125,+ 162.510009765625,+ 181.94976806640625+ ],+ "origin": [+ 159.8000030517578,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 162.5800018310547,+ 172.95001220703125,+ 167.5800018310547,+ 184.1099853515625+ ],+ "char": "y",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 407,+ "source_indices": [+ 407+ ],+ "raw_code": 121,+ "loose_bbox": [+ 162.5800018310547,+ 172.83978271484375,+ 167.5800018310547,+ 183.999755859375+ ],+ "tight_bbox": [+ 162.74000549316406,+ 176.69976806640625,+ 167.49000549316406,+ 183.97979736328125+ ],+ "origin": [+ 162.5800018310547,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 167.5800018310547,+ 172.95001220703125,+ 170.36000061035156,+ 184.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 408,+ "source_indices": [+ 408+ ],+ "raw_code": 32,+ "loose_bbox": [+ 167.5800018310547,+ 172.83978271484375,+ 170.36000061035156,+ 183.999755859375+ ],+ "tight_bbox": [+ 167.5800018310547,+ 181.8797607421875,+ 170.36000061035156,+ 181.8897705078125+ ],+ "origin": [+ 167.5800018310547,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 170.36000061035156,+ 172.95001220703125,+ 176.47000122070312,+ 184.1099853515625+ ],+ "char": "T",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 409,+ "source_indices": [+ 409+ ],+ "raw_code": 84,+ "loose_bbox": [+ 170.36000061035156,+ 172.83978271484375,+ 176.47000122070312,+ 183.999755859375+ ],+ "tight_bbox": [+ 170.5900115966797,+ 174.72979736328125,+ 176.27000427246094,+ 181.8897705078125+ ],+ "origin": [+ 170.36000061035156,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 176.47000122070312,+ 172.95001220703125,+ 182.02999877929688,+ 184.1099853515625+ ],+ "char": "o",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 410,+ "source_indices": [+ 410+ ],+ "raw_code": 111,+ "loose_bbox": [+ 176.47000122070312,+ 172.83978271484375,+ 182.02999877929688,+ 183.999755859375+ ],+ "tight_bbox": [+ 176.8000030517578,+ 176.58978271484375,+ 181.66000366210938,+ 181.999755859375+ ],+ "origin": [+ 176.47000122070312,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 182.02999877929688,+ 172.95001220703125,+ 187.58999633789062,+ 184.1099853515625+ ],+ "char": "o",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 411,+ "source_indices": [+ 411+ ],+ "raw_code": 111,+ "loose_bbox": [+ 182.02999877929688,+ 172.83978271484375,+ 187.58999633789062,+ 183.999755859375+ ],+ "tight_bbox": [+ 182.36001586914062,+ 176.58978271484375,+ 187.22000122070312,+ 181.999755859375+ ],+ "origin": [+ 182.02999877929688,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 187.5900115966797,+ 172.95001220703125,+ 189.8100128173828,+ 184.1099853515625+ ],+ "char": "l",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 412,+ "source_indices": [+ 412+ ],+ "raw_code": 108,+ "loose_bbox": [+ 187.5900115966797,+ 172.83978271484375,+ 189.8100128173828,+ 183.999755859375+ ],+ "tight_bbox": [+ 188.23001098632812,+ 174.72979736328125,+ 189.11001586914062,+ 181.8897705078125+ ],+ "origin": [+ 187.5900115966797,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 189.8100128173828,+ 172.95001220703125,+ 194.8100128173828,+ 184.1099853515625+ ],+ "char": "k",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 413,+ "source_indices": [+ 413+ ],+ "raw_code": 107,+ "loose_bbox": [+ 189.8100128173828,+ 172.83978271484375,+ 194.8100128173828,+ 183.999755859375+ ],+ "tight_bbox": [+ 190.47000122070312,+ 174.72979736328125,+ 194.77000427246094,+ 181.8897705078125+ ],+ "origin": [+ 189.8100128173828,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 194.8100128173828,+ 172.95001220703125,+ 197.03001403808594,+ 184.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 414,+ "source_indices": [+ 414+ ],+ "raw_code": 105,+ "loose_bbox": [+ 194.8100128173828,+ 172.83978271484375,+ 197.03001403808594,+ 183.999755859375+ ],+ "tight_bbox": [+ 195.47000122070312,+ 174.72979736328125,+ 196.35000610351562,+ 181.8897705078125+ ],+ "origin": [+ 194.8100128173828,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 197.03001403808594,+ 172.95001220703125,+ 199.8100128173828,+ 184.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 415,+ "source_indices": [+ 415+ ],+ "raw_code": 116,+ "loose_bbox": [+ 197.03001403808594,+ 172.83978271484375,+ 199.8100128173828,+ 183.999755859375+ ],+ "tight_bbox": [+ 197.2100067138672,+ 174.8897705078125,+ 199.74000549316406,+ 181.94976806640625+ ],+ "origin": [+ 197.03001403808594,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 199.8100128173828,+ 182.0,+ 199.8100128173828,+ 182.0+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 416,+ "source_indices": [+ 416+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 199.8100128173828,+ 181.8897705078125+ ]+ },+ {+ "bbox": [+ 199.8100128173828,+ 182.0,+ 199.8100128173828,+ 182.0+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 417,+ "source_indices": [+ 417+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 199.8100128173828,+ 181.8897705078125+ ]+ }+ ],+ "tight_bboxes": {+ "393": [+ 72.52999877929688,+ 177.1497802734375,+ 75.01000213623047,+ 179.6197509765625+ ],+ "394": [+ 75.5,+ 181.8797607421875,+ 78.27999877929688,+ 181.8897705078125+ ],+ "395": [+ 78.75,+ 173.759765625,+ 87.8499984741211,+ 182.73974609375+ ],+ "396": [+ 88.66999816894531,+ 173.56976318359375,+ 97.8499984741211,+ 182.77978515625+ ],+ "397": [+ 98.94000244140625,+ 173.6097412109375,+ 107.6199951171875,+ 182.81976318359375+ ],+ "398": [+ 108.66999816894531,+ 173.67974853515625,+ 117.8499984741211,+ 182.81976318359375+ ],+ "399": [+ 118.8699951171875,+ 174.23974609375,+ 127.69000244140625,+ 182.46978759765625+ ],+ "400": [+ 128.75,+ 173.95977783203125,+ 137.76998901367188,+ 182.8597412109375+ ],+ "401": [+ 138.27999877929688,+ 181.8797607421875,+ 140.35000610351562,+ 181.8897705078125+ ],+ "402": [+ 140.35000610351562,+ 174.72979736328125,+ 147.02999877929688,+ 181.8897705078125+ ],+ "403": [+ 147.41000366210938,+ 176.58978271484375,+ 151.9300079345703,+ 181.999755859375+ ],+ "404": [+ 152.66000366210938,+ 176.69976806640625,+ 156.86000061035156,+ 181.999755859375+ ],+ "405": [+ 158.24000549316406,+ 174.72979736328125,+ 159.12001037597656,+ 181.8897705078125+ ],+ "406": [+ 159.98001098632812,+ 174.8897705078125,+ 162.510009765625,+ 181.94976806640625+ ],+ "407": [+ 162.74000549316406,+ 176.69976806640625,+ 167.49000549316406,+ 183.97979736328125+ ],+ "408": [+ 167.5800018310547,+ 181.8797607421875,+ 170.36000061035156,+ 181.8897705078125+ ],+ "409": [+ 170.5900115966797,+ 174.72979736328125,+ 176.27000427246094,+ 181.8897705078125+ ],+ "410": [+ 176.8000030517578,+ 176.58978271484375,+ 181.66000366210938,+ 181.999755859375+ ],+ "411": [+ 182.36001586914062,+ 176.58978271484375,+ 187.22000122070312,+ 181.999755859375+ ],+ "412": [+ 188.23001098632812,+ 174.72979736328125,+ 189.11001586914062,+ 181.8897705078125+ ],+ "413": [+ 190.47000122070312,+ 174.72979736328125,+ 194.77000427246094,+ 181.8897705078125+ ],+ "414": [+ 195.47000122070312,+ 174.72979736328125,+ 196.35000610351562,+ 181.8897705078125+ ],+ "415": [+ 197.2100067138672,+ 174.8897705078125,+ 199.74000549316406,+ 181.94976806640625+ ]+ },+ "origins": {+ "393": [+ 72.0,+ 181.8897705078125+ ],+ "394": [+ 75.5,+ 181.8897705078125+ ],+ "395": [+ 78.27999877929688,+ 181.8897705078125+ ],+ "396": [+ 88.27999877929688,+ 181.8897705078125+ ],+ "397": [+ 98.27999877929688,+ 181.8897705078125+ ],+ "398": [+ 108.27999877929688,+ 181.8897705078125+ ],+ "399": [+ 118.27999877929688,+ 181.8897705078125+ ],+ "400": [+ 128.27999877929688,+ 181.8897705078125+ ],+ "401": [+ 138.27999877929688,+ 181.8897705078125+ ],+ "402": [+ 140.35000610351562,+ 181.8897705078125+ ],+ "403": [+ 147.02000427246094,+ 181.8897705078125+ ],+ "404": [+ 152.02000427246094,+ 181.8897705078125+ ],+ "405": [+ 157.5800018310547,+ 181.8897705078125+ ],+ "406": [+ 159.8000030517578,+ 181.8897705078125+ ],+ "407": [+ 162.5800018310547,+ 181.8897705078125+ ],+ "408": [+ 167.5800018310547,+ 181.8897705078125+ ],+ "409": [+ 170.36000061035156,+ 181.8897705078125+ ],+ "410": [+ 176.47000122070312,+ 181.8897705078125+ ],+ "411": [+ 182.02999877929688,+ 181.8897705078125+ ],+ "412": [+ 187.5900115966797,+ 181.8897705078125+ ],+ "413": [+ 189.8100128173828,+ 181.8897705078125+ ],+ "414": [+ 194.8100128173828,+ 181.8897705078125+ ],+ "415": [+ 197.03001403808594,+ 181.8897705078125+ ],+ "416": [+ 199.8100128173828,+ 181.8897705078125+ ],+ "417": [+ 199.8100128173828,+ 181.8897705078125+ ]+ }+ }+ ]+ },+ {+ "source": "tests/unittest/pdfs/native_cjk_layout_synthetic.pdf",+ "page_index": 2,+ "probe": "• 测试系统 Ubuntu 24.04",+ "selection": "lines",+ "fragments": [+ {+ "chars": [+ {+ "bbox": [+ 72.0,+ 212.95001220703125,+ 75.5,+ 224.1099853515625+ ],+ "char": "•",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 418,+ "source_indices": [+ 418+ ],+ "raw_code": 8226,+ "loose_bbox": [+ 72.0,+ 212.83978271484375,+ 75.5,+ 223.999755859375+ ],+ "tight_bbox": [+ 72.52999877929688,+ 217.1497802734375,+ 75.01000213623047,+ 219.6197509765625+ ],+ "origin": [+ 72.0,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 75.5,+ 212.95001220703125,+ 78.27999877929688,+ 224.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 419,+ "source_indices": [+ 419+ ],+ "raw_code": 32,+ "loose_bbox": [+ 75.5,+ 212.83978271484375,+ 78.27999877929688,+ 223.999755859375+ ],+ "tight_bbox": [+ 75.5,+ 221.8797607421875,+ 78.27999877929688,+ 221.8897705078125+ ],+ "origin": [+ 75.5,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 78.27999877929688,+ 213.78997802734375,+ 88.27999877929688,+ 224.53997802734375+ ],+ "char": "测",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 420,+ "source_indices": [+ 420+ ],+ "raw_code": 27979,+ "loose_bbox": [+ 78.27999877929688,+ 213.67974853515625,+ 88.27999877929688,+ 224.42974853515625+ ],+ "tight_bbox": [+ 78.70999908447266,+ 213.67974853515625,+ 87.5,+ 222.81976318359375+ ],+ "origin": [+ 78.27999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 88.27999877929688,+ 213.78997802734375,+ 98.27999877929688,+ 224.53997802734375+ ],+ "char": "试",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 421,+ "source_indices": [+ 421+ ],+ "raw_code": 35797,+ "loose_bbox": [+ 88.27999877929688,+ 213.67974853515625,+ 98.27999877929688,+ 224.42974853515625+ ],+ "tight_bbox": [+ 88.79000091552734,+ 213.67974853515625,+ 97.8499984741211,+ 222.77978515625+ ],+ "origin": [+ 88.27999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 98.27999877929688,+ 213.8699951171875,+ 108.27999877929688,+ 224.53997802734375+ ],+ "char": "系",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 422,+ "source_indices": [+ 422+ ],+ "raw_code": 31995,+ "loose_bbox": [+ 98.27999877929688,+ 213.759765625,+ 108.27999877929688,+ 224.42974853515625+ ],+ "tight_bbox": [+ 98.79000091552734,+ 213.759765625,+ 107.37999725341797,+ 222.77978515625+ ],+ "origin": [+ 98.27999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 108.27999877929688,+ 213.78997802734375,+ 118.27999877929688,+ 224.53997802734375+ ],+ "char": "统",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 423,+ "source_indices": [+ 423+ ],+ "raw_code": 32479,+ "loose_bbox": [+ 108.27999877929688,+ 213.67974853515625,+ 118.27999877929688,+ 224.42974853515625+ ],+ "tight_bbox": [+ 108.79000091552734,+ 213.67974853515625,+ 117.7699966430664,+ 222.77978515625+ ],+ "origin": [+ 108.27999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 118.27999877929688,+ 214.47998046875,+ 120.3499984741211,+ 224.53997802734375+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "STSong-Light",+ "flags": 524294,+ "size": 10.0,+ "weight": 290+ },+ "char_idx": 424,+ "source_indices": [+ 424+ ],+ "raw_code": 32,+ "loose_bbox": [+ 118.27999877929688,+ 214.3697509765625,+ 120.3499984741211,+ 224.42974853515625+ ],+ "tight_bbox": [+ 118.27999877929688,+ 221.8797607421875,+ 120.3499984741211,+ 221.8897705078125+ ],+ "origin": [+ 118.27999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 120.3499984741211,+ 212.95001220703125,+ 127.56999969482422,+ 224.1099853515625+ ],+ "char": "U",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 425,+ "source_indices": [+ 425+ ],+ "raw_code": 85,+ "loose_bbox": [+ 120.3499984741211,+ 212.83978271484375,+ 127.56999969482422,+ 223.999755859375+ ],+ "tight_bbox": [+ 121.13999938964844,+ 214.72979736328125,+ 126.7699966430664,+ 221.999755859375+ ],+ "origin": [+ 120.3499984741211,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 127.56999969482422,+ 212.95001220703125,+ 133.1300048828125,+ 224.1099853515625+ ],+ "char": "b",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 426,+ "source_indices": [+ 426+ ],+ "raw_code": 98,+ "loose_bbox": [+ 127.56999969482422,+ 212.83978271484375,+ 133.1300048828125,+ 223.999755859375+ ],+ "tight_bbox": [+ 128.22000122070312,+ 214.72979736328125,+ 132.72000122070312,+ 221.999755859375+ ],+ "origin": [+ 127.56999969482422,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 133.1300048828125,+ 212.95001220703125,+ 138.69000244140625,+ 224.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 427,+ "source_indices": [+ 427+ ],+ "raw_code": 117,+ "loose_bbox": [+ 133.1300048828125,+ 212.83978271484375,+ 138.69000244140625,+ 223.999755859375+ ],+ "tight_bbox": [+ 133.77000427246094,+ 216.69976806640625,+ 137.97000122070312,+ 221.999755859375+ ],+ "origin": [+ 133.1300048828125,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 138.69000244140625,+ 212.95001220703125,+ 144.25,+ 224.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 428,+ "source_indices": [+ 428+ ],+ "raw_code": 110,+ "loose_bbox": [+ 138.69000244140625,+ 212.83978271484375,+ 144.25,+ 223.999755859375+ ],+ "tight_bbox": [+ 139.35000610351562,+ 216.58978271484375,+ 143.55999755859375,+ 221.8897705078125+ ],+ "origin": [+ 138.69000244140625,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 144.25,+ 212.95001220703125,+ 147.02999877929688,+ 224.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 429,+ "source_indices": [+ 429+ ],+ "raw_code": 116,+ "loose_bbox": [+ 144.25,+ 212.83978271484375,+ 147.02999877929688,+ 223.999755859375+ ],+ "tight_bbox": [+ 144.42999267578125,+ 214.8897705078125,+ 146.95999145507812,+ 221.94976806640625+ ],+ "origin": [+ 144.25,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 147.02999877929688,+ 212.95001220703125,+ 152.58999633789062,+ 224.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 430,+ "source_indices": [+ 430+ ],+ "raw_code": 117,+ "loose_bbox": [+ 147.02999877929688,+ 212.83978271484375,+ 152.58999633789062,+ 223.999755859375+ ],+ "tight_bbox": [+ 147.6699981689453,+ 216.69976806640625,+ 151.8699951171875,+ 221.999755859375+ ],+ "origin": [+ 147.02999877929688,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 152.58999633789062,+ 212.95001220703125,+ 155.3699951171875,+ 224.1099853515625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 431,+ "source_indices": [+ 431+ ],+ "raw_code": 32,+ "loose_bbox": [+ 152.58999633789062,+ 212.83978271484375,+ 155.3699951171875,+ 223.999755859375+ ],+ "tight_bbox": [+ 152.58999633789062,+ 221.8797607421875,+ 155.3699951171875,+ 221.8897705078125+ ],+ "origin": [+ 152.58999633789062,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 155.3699951171875,+ 212.95001220703125,+ 160.92999267578125,+ 224.1099853515625+ ],+ "char": "2",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 432,+ "source_indices": [+ 432+ ],+ "raw_code": 50,+ "loose_bbox": [+ 155.3699951171875,+ 212.83978271484375,+ 160.92999267578125,+ 223.999755859375+ ],+ "tight_bbox": [+ 155.66000366210938,+ 214.69976806640625,+ 160.39999389648438,+ 221.8897705078125+ ],+ "origin": [+ 155.3699951171875,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 160.92999267578125,+ 212.95001220703125,+ 166.489990234375,+ 224.1099853515625+ ],+ "char": "4",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 433,+ "source_indices": [+ 433+ ],+ "raw_code": 52,+ "loose_bbox": [+ 160.92999267578125,+ 212.83978271484375,+ 166.489990234375,+ 223.999755859375+ ],+ "tight_bbox": [+ 161.05999755859375,+ 214.72979736328125,+ 166.010009765625,+ 221.8897705078125+ ],+ "origin": [+ 160.92999267578125,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 166.49000549316406,+ 212.95001220703125,+ 169.27000427246094,+ 224.1099853515625+ ],+ "char": ".",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 434,+ "source_indices": [+ 434+ ],+ "raw_code": 46,+ "loose_bbox": [+ 166.49000549316406,+ 212.83978271484375,+ 169.27000427246094,+ 223.999755859375+ ],+ "tight_bbox": [+ 167.39999389648438,+ 220.8897705078125,+ 168.39999389648438,+ 221.8897705078125+ ],+ "origin": [+ 166.49000549316406,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 169.27000427246094,+ 212.95001220703125,+ 174.8300018310547,+ 224.1099853515625+ ],+ "char": "0",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 435,+ "source_indices": [+ 435+ ],+ "raw_code": 48,+ "loose_bbox": [+ 169.27000427246094,+ 212.83978271484375,+ 174.8300018310547,+ 223.999755859375+ ],+ "tight_bbox": [+ 169.69000244140625,+ 214.69976806640625,+ 174.35000610351562,+ 221.999755859375+ ],+ "origin": [+ 169.27000427246094,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 174.8300018310547,+ 212.95001220703125,+ 180.38999938964844,+ 224.1099853515625+ ],+ "char": "4",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 436,+ "source_indices": [+ 436+ ],+ "raw_code": 52,+ "loose_bbox": [+ 174.8300018310547,+ 212.83978271484375,+ 180.38999938964844,+ 223.999755859375+ ],+ "tight_bbox": [+ 174.9600067138672,+ 214.72979736328125,+ 179.91000366210938,+ 221.8897705078125+ ],+ "origin": [+ 174.8300018310547,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 180.38999938964844,+ 222.0,+ 180.38999938964844,+ 222.0+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 437,+ "source_indices": [+ 437+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 180.38999938964844,+ 221.8897705078125+ ]+ },+ {+ "bbox": [+ 180.38999938964844,+ 222.0,+ 180.38999938964844,+ 222.0+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 438,+ "source_indices": [+ 438+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 180.38999938964844,+ 221.8897705078125+ ]+ }+ ],+ "tight_bboxes": {+ "418": [+ 72.52999877929688,+ 217.1497802734375,+ 75.01000213623047,+ 219.6197509765625+ ],+ "419": [+ 75.5,+ 221.8797607421875,+ 78.27999877929688,+ 221.8897705078125+ ],+ "420": [+ 78.70999908447266,+ 213.67974853515625,+ 87.5,+ 222.81976318359375+ ],+ "421": [+ 88.79000091552734,+ 213.67974853515625,+ 97.8499984741211,+ 222.77978515625+ ],+ "422": [+ 98.79000091552734,+ 213.759765625,+ 107.37999725341797,+ 222.77978515625+ ],+ "423": [+ 108.79000091552734,+ 213.67974853515625,+ 117.7699966430664,+ 222.77978515625+ ],+ "424": [+ 118.27999877929688,+ 221.8797607421875,+ 120.3499984741211,+ 221.8897705078125+ ],+ "425": [+ 121.13999938964844,+ 214.72979736328125,+ 126.7699966430664,+ 221.999755859375+ ],+ "426": [+ 128.22000122070312,+ 214.72979736328125,+ 132.72000122070312,+ 221.999755859375+ ],+ "427": [+ 133.77000427246094,+ 216.69976806640625,+ 137.97000122070312,+ 221.999755859375+ ],+ "428": [+ 139.35000610351562,+ 216.58978271484375,+ 143.55999755859375,+ 221.8897705078125+ ],+ "429": [+ 144.42999267578125,+ 214.8897705078125,+ 146.95999145507812,+ 221.94976806640625+ ],+ "430": [+ 147.6699981689453,+ 216.69976806640625,+ 151.8699951171875,+ 221.999755859375+ ],+ "431": [+ 152.58999633789062,+ 221.8797607421875,+ 155.3699951171875,+ 221.8897705078125+ ],+ "432": [+ 155.66000366210938,+ 214.69976806640625,+ 160.39999389648438,+ 221.8897705078125+ ],+ "433": [+ 161.05999755859375,+ 214.72979736328125,+ 166.010009765625,+ 221.8897705078125+ ],+ "434": [+ 167.39999389648438,+ 220.8897705078125,+ 168.39999389648438,+ 221.8897705078125+ ],+ "435": [+ 169.69000244140625,+ 214.69976806640625,+ 174.35000610351562,+ 221.999755859375+ ],+ "436": [+ 174.9600067138672,+ 214.72979736328125,+ 179.91000366210938,+ 221.8897705078125+ ]+ },+ "origins": {+ "418": [+ 72.0,+ 221.8897705078125+ ],+ "419": [+ 75.5,+ 221.8897705078125+ ],+ "420": [+ 78.27999877929688,+ 221.8897705078125+ ],+ "421": [+ 88.27999877929688,+ 221.8897705078125+ ],+ "422": [+ 98.27999877929688,+ 221.8897705078125+ ],+ "423": [+ 108.27999877929688,+ 221.8897705078125+ ],+ "424": [+ 118.27999877929688,+ 221.8897705078125+ ],+ "425": [+ 120.3499984741211,+ 221.8897705078125+ ],+ "426": [+ 127.56999969482422,+ 221.8897705078125+ ],+ "427": [+ 133.1300048828125,+ 221.8897705078125+ ],+ "428": [+ 138.69000244140625,+ 221.8897705078125+ ],+ "429": [+ 144.25,+ 221.8897705078125+ ],+ "430": [+ 147.02999877929688,+ 221.8897705078125+ ],+ "431": [+ 152.58999633789062,+ 221.8897705078125+ ],+ "432": [+ 155.3699951171875,+ 221.8897705078125+ ],+ "433": [+ 160.92999267578125,+ 221.8897705078125+ ],+ "434": [+ 166.49000549316406,+ 221.8897705078125+ ],+ "435": [+ 169.27000427246094,+ 221.8897705078125+ ],+ "436": [+ 174.8300018310547,+ 221.8897705078125+ ],+ "437": [+ 180.38999938964844,+ 221.8897705078125+ ],+ "438": [+ 180.38999938964844,+ 221.8897705078125+ ]+ }+ }+ ]+ },+ {+ "source": "tests/unittest/pdfs/native_cjk_layout_synthetic.pdf",+ "page_index": 2,+ "probe": "mineru_toolkit_binary_1.0.0_linux_x86_64.tgz",+ "selection": "lines",+ "fragments": [+ {+ "chars": [+ {+ "bbox": [+ 72.0,+ 252.95001220703125,+ 80.33000183105469,+ 264.1099853515625+ ],+ "char": "m",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 439,+ "source_indices": [+ 439+ ],+ "raw_code": 109,+ "loose_bbox": [+ 72.0,+ 252.83978271484375,+ 80.33000183105469,+ 263.999755859375+ ],+ "tight_bbox": [+ 72.66000366210938,+ 256.58978271484375,+ 79.69000244140625,+ 261.8897705078125+ ],+ "origin": [+ 72.0,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 80.33000183105469,+ 252.95001220703125,+ 82.55000305175781,+ 264.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 440,+ "source_indices": [+ 440+ ],+ "raw_code": 105,+ "loose_bbox": [+ 80.33000183105469,+ 252.83978271484375,+ 82.55000305175781,+ 263.999755859375+ ],+ "tight_bbox": [+ 80.98999786376953,+ 254.72979736328125,+ 81.87000274658203,+ 261.8897705078125+ ],+ "origin": [+ 80.33000183105469,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 82.55000305175781,+ 252.95001220703125,+ 88.11000061035156,+ 264.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 441,+ "source_indices": [+ 441+ ],+ "raw_code": 110,+ "loose_bbox": [+ 82.55000305175781,+ 252.83978271484375,+ 88.11000061035156,+ 263.999755859375+ ],+ "tight_bbox": [+ 83.20999908447266,+ 256.58978271484375,+ 87.41999816894531,+ 261.8897705078125+ ],+ "origin": [+ 82.55000305175781,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 88.11000061035156,+ 252.95001220703125,+ 93.66999816894531,+ 264.1099853515625+ ],+ "char": "e",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 442,+ "source_indices": [+ 442+ ],+ "raw_code": 101,+ "loose_bbox": [+ 88.11000061035156,+ 252.83978271484375,+ 93.66999816894531,+ 263.999755859375+ ],+ "tight_bbox": [+ 88.4800033569336,+ 256.58978271484375,+ 93.26000213623047,+ 261.999755859375+ ],+ "origin": [+ 88.11000061035156,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 93.66999816894531,+ 252.95001220703125,+ 97.13999938964844,+ 264.1099853515625+ ],+ "char": "r",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 443,+ "source_indices": [+ 443+ ],+ "raw_code": 114,+ "loose_bbox": [+ 93.66999816894531,+ 252.83978271484375,+ 97.13999938964844,+ 263.999755859375+ ],+ "tight_bbox": [+ 94.31999969482422,+ 256.58978271484375,+ 97.13999938964844,+ 261.8897705078125+ ],+ "origin": [+ 93.66999816894531,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 97.0,+ 252.95001220703125,+ 102.55999755859375,+ 264.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 444,+ "source_indices": [+ 444+ ],+ "raw_code": 117,+ "loose_bbox": [+ 97.0,+ 252.83978271484375,+ 102.55999755859375,+ 263.999755859375+ ],+ "tight_bbox": [+ 97.63999938964844,+ 256.69976806640625,+ 101.83999633789062,+ 261.999755859375+ ],+ "origin": [+ 97.0,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 102.41999816894531,+ 252.95001220703125,+ 108.22999572753906,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 445,+ "source_indices": [+ 445+ ],+ "raw_code": 95,+ "loose_bbox": [+ 102.41999816894531,+ 252.83978271484375,+ 108.22999572753906,+ 263.999755859375+ ],+ "tight_bbox": [+ 102.41999816894531,+ 263.22979736328125,+ 108.22999572753906,+ 263.8697509765625+ ],+ "origin": [+ 102.55999755859375,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 108.1199951171875,+ 252.95001220703125,+ 110.89999389648438,+ 264.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 446,+ "source_indices": [+ 446+ ],+ "raw_code": 116,+ "loose_bbox": [+ 108.1199951171875,+ 252.83978271484375,+ 110.89999389648438,+ 263.999755859375+ ],+ "tight_bbox": [+ 108.30000305175781,+ 254.8897705078125,+ 110.83000183105469,+ 261.94976806640625+ ],+ "origin": [+ 108.1199951171875,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 110.89999389648438,+ 252.95001220703125,+ 116.45999145507812,+ 264.1099853515625+ ],+ "char": "o",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 447,+ "source_indices": [+ 447+ ],+ "raw_code": 111,+ "loose_bbox": [+ 110.89999389648438,+ 252.83978271484375,+ 116.45999145507812,+ 263.999755859375+ ],+ "tight_bbox": [+ 111.22999572753906,+ 256.58978271484375,+ 116.08999633789062,+ 261.999755859375+ ],+ "origin": [+ 110.89999389648438,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 116.45999908447266,+ 252.95001220703125,+ 122.02000427246094,+ 264.1099853515625+ ],+ "char": "o",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 448,+ "source_indices": [+ 448+ ],+ "raw_code": 111,+ "loose_bbox": [+ 116.45999908447266,+ 252.83978271484375,+ 122.02000427246094,+ 263.999755859375+ ],+ "tight_bbox": [+ 116.79000091552734,+ 256.58978271484375,+ 121.64999389648438,+ 261.999755859375+ ],+ "origin": [+ 116.45999908447266,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 122.02000427246094,+ 252.95001220703125,+ 124.24000549316406,+ 264.1099853515625+ ],+ "char": "l",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 449,+ "source_indices": [+ 449+ ],+ "raw_code": 108,+ "loose_bbox": [+ 122.02000427246094,+ 252.83978271484375,+ 124.24000549316406,+ 263.999755859375+ ],+ "tight_bbox": [+ 122.66000366210938,+ 254.72979736328125,+ 123.54000091552734,+ 261.8897705078125+ ],+ "origin": [+ 122.02000427246094,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 124.24000549316406,+ 252.95001220703125,+ 129.24000549316406,+ 264.1099853515625+ ],+ "char": "k",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 450,+ "source_indices": [+ 450+ ],+ "raw_code": 107,+ "loose_bbox": [+ 124.24000549316406,+ 252.83978271484375,+ 129.24000549316406,+ 263.999755859375+ ],+ "tight_bbox": [+ 124.9000015258789,+ 254.72979736328125,+ 129.1999969482422,+ 261.8897705078125+ ],+ "origin": [+ 124.24000549316406,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 129.24000549316406,+ 252.95001220703125,+ 131.4600067138672,+ 264.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 451,+ "source_indices": [+ 451+ ],+ "raw_code": 105,+ "loose_bbox": [+ 129.24000549316406,+ 252.83978271484375,+ 131.4600067138672,+ 263.999755859375+ ],+ "tight_bbox": [+ 129.89999389648438,+ 254.72979736328125,+ 130.77999877929688,+ 261.8897705078125+ ],+ "origin": [+ 129.24000549316406,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 131.4600067138672,+ 252.95001220703125,+ 134.24000549316406,+ 264.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 452,+ "source_indices": [+ 452+ ],+ "raw_code": 116,+ "loose_bbox": [+ 131.4600067138672,+ 252.83978271484375,+ 134.24000549316406,+ 263.999755859375+ ],+ "tight_bbox": [+ 131.63999938964844,+ 254.8897705078125,+ 134.1699981689453,+ 261.94976806640625+ ],+ "origin": [+ 131.4600067138672,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 134.10000610351562,+ 252.95001220703125,+ 139.91000366210938,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 453,+ "source_indices": [+ 453+ ],+ "raw_code": 95,+ "loose_bbox": [+ 134.10000610351562,+ 252.83978271484375,+ 139.91000366210938,+ 263.999755859375+ ],+ "tight_bbox": [+ 134.10000610351562,+ 263.22979736328125,+ 139.91000366210938,+ 263.8697509765625+ ],+ "origin": [+ 134.24000549316406,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 139.8000030517578,+ 252.95001220703125,+ 145.36000061035156,+ 264.1099853515625+ ],+ "char": "b",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 454,+ "source_indices": [+ 454+ ],+ "raw_code": 98,+ "loose_bbox": [+ 139.8000030517578,+ 252.83978271484375,+ 145.36000061035156,+ 263.999755859375+ ],+ "tight_bbox": [+ 140.45001220703125,+ 254.72979736328125,+ 144.95001220703125,+ 261.999755859375+ ],+ "origin": [+ 139.8000030517578,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 145.36000061035156,+ 252.95001220703125,+ 147.5800018310547,+ 264.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 455,+ "source_indices": [+ 455+ ],+ "raw_code": 105,+ "loose_bbox": [+ 145.36000061035156,+ 252.83978271484375,+ 147.5800018310547,+ 263.999755859375+ ],+ "tight_bbox": [+ 146.02000427246094,+ 254.72979736328125,+ 146.89999389648438,+ 261.8897705078125+ ],+ "origin": [+ 145.36000061035156,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 147.5800018310547,+ 252.95001220703125,+ 153.13999938964844,+ 264.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 456,+ "source_indices": [+ 456+ ],+ "raw_code": 110,+ "loose_bbox": [+ 147.5800018310547,+ 252.83978271484375,+ 153.13999938964844,+ 263.999755859375+ ],+ "tight_bbox": [+ 148.24000549316406,+ 256.58978271484375,+ 152.45001220703125,+ 261.8897705078125+ ],+ "origin": [+ 147.5800018310547,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 153.13999938964844,+ 252.95001220703125,+ 158.6999969482422,+ 264.1099853515625+ ],+ "char": "a",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 457,+ "source_indices": [+ 457+ ],+ "raw_code": 97,+ "loose_bbox": [+ 153.13999938964844,+ 252.83978271484375,+ 158.6999969482422,+ 263.999755859375+ ],+ "tight_bbox": [+ 153.5,+ 256.58978271484375,+ 158.27999877929688,+ 261.999755859375+ ],+ "origin": [+ 153.13999938964844,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 158.6999969482422,+ 252.95001220703125,+ 162.1699981689453,+ 264.1099853515625+ ],+ "char": "r",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 458,+ "source_indices": [+ 458+ ],+ "raw_code": 114,+ "loose_bbox": [+ 158.6999969482422,+ 252.83978271484375,+ 162.1699981689453,+ 263.999755859375+ ],+ "tight_bbox": [+ 159.35000610351562,+ 256.58978271484375,+ 162.1699981689453,+ 261.8897705078125+ ],+ "origin": [+ 158.6999969482422,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 162.02999877929688,+ 252.95001220703125,+ 167.02999877929688,+ 264.1099853515625+ ],+ "char": "y",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 459,+ "source_indices": [+ 459+ ],+ "raw_code": 121,+ "loose_bbox": [+ 162.02999877929688,+ 252.83978271484375,+ 167.02999877929688,+ 263.999755859375+ ],+ "tight_bbox": [+ 162.19000244140625,+ 256.69976806640625,+ 166.94000244140625,+ 263.97979736328125+ ],+ "origin": [+ 162.02999877929688,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 166.88999938964844,+ 252.95001220703125,+ 172.6999969482422,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 460,+ "source_indices": [+ 460+ ],+ "raw_code": 95,+ "loose_bbox": [+ 166.88999938964844,+ 252.83978271484375,+ 172.6999969482422,+ 263.999755859375+ ],+ "tight_bbox": [+ 166.88999938964844,+ 263.22979736328125,+ 172.6999969482422,+ 263.8697509765625+ ],+ "origin": [+ 167.02999877929688,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 172.58999633789062,+ 252.95001220703125,+ 178.14999389648438,+ 264.1099853515625+ ],+ "char": "1",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 461,+ "source_indices": [+ 461+ ],+ "raw_code": 49,+ "loose_bbox": [+ 172.58999633789062,+ 252.83978271484375,+ 178.14999389648438,+ 263.999755859375+ ],+ "tight_bbox": [+ 173.67999267578125,+ 254.69976806640625,+ 176.32000732421875,+ 261.8897705078125+ ],+ "origin": [+ 172.58999633789062,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 178.14999389648438,+ 252.95001220703125,+ 180.92999267578125,+ 264.1099853515625+ ],+ "char": ".",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 462,+ "source_indices": [+ 462+ ],+ "raw_code": 46,+ "loose_bbox": [+ 178.14999389648438,+ 252.83978271484375,+ 180.92999267578125,+ 263.999755859375+ ],+ "tight_bbox": [+ 179.05999755859375,+ 260.8897705078125,+ 180.05999755859375,+ 261.8897705078125+ ],+ "origin": [+ 178.14999389648438,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 180.92999267578125,+ 252.95001220703125,+ 186.489990234375,+ 264.1099853515625+ ],+ "char": "0",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 463,+ "source_indices": [+ 463+ ],+ "raw_code": 48,+ "loose_bbox": [+ 180.92999267578125,+ 252.83978271484375,+ 186.489990234375,+ 263.999755859375+ ],+ "tight_bbox": [+ 181.34999084472656,+ 254.69976806640625,+ 186.00999450683594,+ 261.999755859375+ ],+ "origin": [+ 180.92999267578125,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 186.489990234375,+ 252.95001220703125,+ 189.26998901367188,+ 264.1099853515625+ ],+ "char": ".",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 464,+ "source_indices": [+ 464+ ],+ "raw_code": 46,+ "loose_bbox": [+ 186.489990234375,+ 252.83978271484375,+ 189.26998901367188,+ 263.999755859375+ ],+ "tight_bbox": [+ 187.39999389648438,+ 260.8897705078125,+ 188.39999389648438,+ 261.8897705078125+ ],+ "origin": [+ 186.489990234375,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 189.26998901367188,+ 252.95001220703125,+ 194.82998657226562,+ 264.1099853515625+ ],+ "char": "0",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 465,+ "source_indices": [+ 465+ ],+ "raw_code": 48,+ "loose_bbox": [+ 189.26998901367188,+ 252.83978271484375,+ 194.82998657226562,+ 263.999755859375+ ],+ "tight_bbox": [+ 189.6899871826172,+ 254.69976806640625,+ 194.34999084472656,+ 261.999755859375+ ],+ "origin": [+ 189.26998901367188,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 194.6899871826172,+ 252.95001220703125,+ 200.49998474121094,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 466,+ "source_indices": [+ 466+ ],+ "raw_code": 95,+ "loose_bbox": [+ 194.6899871826172,+ 252.83978271484375,+ 200.49998474121094,+ 263.999755859375+ ],+ "tight_bbox": [+ 194.6899871826172,+ 263.22979736328125,+ 200.49998474121094,+ 263.8697509765625+ ],+ "origin": [+ 194.82998657226562,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 200.38998413085938,+ 252.95001220703125,+ 202.6099853515625,+ 264.1099853515625+ ],+ "char": "l",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 467,+ "source_indices": [+ 467+ ],+ "raw_code": 108,+ "loose_bbox": [+ 200.38998413085938,+ 252.83978271484375,+ 202.6099853515625,+ 263.999755859375+ ],+ "tight_bbox": [+ 201.0299835205078,+ 254.72979736328125,+ 201.9099884033203,+ 261.8897705078125+ ],+ "origin": [+ 200.38998413085938,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 202.6099853515625,+ 252.95001220703125,+ 204.82998657226562,+ 264.1099853515625+ ],+ "char": "i",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 468,+ "source_indices": [+ 468+ ],+ "raw_code": 105,+ "loose_bbox": [+ 202.6099853515625,+ 252.83978271484375,+ 204.82998657226562,+ 263.999755859375+ ],+ "tight_bbox": [+ 203.26998901367188,+ 254.72979736328125,+ 204.1499786376953,+ 261.8897705078125+ ],+ "origin": [+ 202.6099853515625,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 204.82998657226562,+ 252.95001220703125,+ 210.38998413085938,+ 264.1099853515625+ ],+ "char": "n",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 469,+ "source_indices": [+ 469+ ],+ "raw_code": 110,+ "loose_bbox": [+ 204.82998657226562,+ 252.83978271484375,+ 210.38998413085938,+ 263.999755859375+ ],+ "tight_bbox": [+ 205.489990234375,+ 256.58978271484375,+ 209.69998168945312,+ 261.8897705078125+ ],+ "origin": [+ 204.82998657226562,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 210.38998413085938,+ 252.95001220703125,+ 215.94998168945312,+ 264.1099853515625+ ],+ "char": "u",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 470,+ "source_indices": [+ 470+ ],+ "raw_code": 117,+ "loose_bbox": [+ 210.38998413085938,+ 252.83978271484375,+ 215.94998168945312,+ 263.999755859375+ ],+ "tight_bbox": [+ 211.0299835205078,+ 256.69976806640625,+ 215.22998046875,+ 261.999755859375+ ],+ "origin": [+ 210.38998413085938,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 215.94998168945312,+ 252.95001220703125,+ 220.94998168945312,+ 264.1099853515625+ ],+ "char": "x",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 471,+ "source_indices": [+ 471+ ],+ "raw_code": 120,+ "loose_bbox": [+ 215.94998168945312,+ 252.83978271484375,+ 220.94998168945312,+ 263.999755859375+ ],+ "tight_bbox": [+ 216.01998901367188,+ 256.69976806640625,+ 220.87997436523438,+ 261.8897705078125+ ],+ "origin": [+ 215.94998168945312,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 220.8099822998047,+ 252.95001220703125,+ 226.61997985839844,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 472,+ "source_indices": [+ 472+ ],+ "raw_code": 95,+ "loose_bbox": [+ 220.8099822998047,+ 252.83978271484375,+ 226.61997985839844,+ 263.999755859375+ ],+ "tight_bbox": [+ 220.8099822998047,+ 263.22979736328125,+ 226.61997985839844,+ 263.8697509765625+ ],+ "origin": [+ 220.94998168945312,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 226.50997924804688,+ 252.95001220703125,+ 231.50997924804688,+ 264.1099853515625+ ],+ "char": "x",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 473,+ "source_indices": [+ 473+ ],+ "raw_code": 120,+ "loose_bbox": [+ 226.50997924804688,+ 252.83978271484375,+ 231.50997924804688,+ 263.999755859375+ ],+ "tight_bbox": [+ 226.57998657226562,+ 256.69976806640625,+ 231.43997192382812,+ 261.8897705078125+ ],+ "origin": [+ 226.50997924804688,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 231.50997924804688,+ 252.95001220703125,+ 237.06997680664062,+ 264.1099853515625+ ],+ "char": "8",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 474,+ "source_indices": [+ 474+ ],+ "raw_code": 56,+ "loose_bbox": [+ 231.50997924804688,+ 252.83978271484375,+ 237.06997680664062,+ 263.999755859375+ ],+ "tight_bbox": [+ 231.91998291015625,+ 254.69976806640625,+ 236.62997436523438,+ 261.999755859375+ ],+ "origin": [+ 231.50997924804688,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 237.06997680664062,+ 252.95001220703125,+ 242.62997436523438,+ 264.1099853515625+ ],+ "char": "6",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 475,+ "source_indices": [+ 475+ ],+ "raw_code": 54,+ "loose_bbox": [+ 237.06997680664062,+ 252.83978271484375,+ 242.62997436523438,+ 263.999755859375+ ],+ "tight_bbox": [+ 237.44998168945312,+ 254.69976806640625,+ 242.16998291015625,+ 261.999755859375+ ],+ "origin": [+ 237.06997680664062,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 242.48997497558594,+ 252.95001220703125,+ 248.2999725341797,+ 264.1099853515625+ ],+ "char": "_",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 476,+ "source_indices": [+ 476+ ],+ "raw_code": 95,+ "loose_bbox": [+ 242.48997497558594,+ 252.83978271484375,+ 248.2999725341797,+ 263.999755859375+ ],+ "tight_bbox": [+ 242.48997497558594,+ 263.22979736328125,+ 248.2999725341797,+ 263.8697509765625+ ],+ "origin": [+ 242.62997436523438,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 248.18997192382812,+ 252.95001220703125,+ 253.74996948242188,+ 264.1099853515625+ ],+ "char": "6",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 477,+ "source_indices": [+ 477+ ],+ "raw_code": 54,+ "loose_bbox": [+ 248.18997192382812,+ 252.83978271484375,+ 253.74996948242188,+ 263.999755859375+ ],+ "tight_bbox": [+ 248.56997680664062,+ 254.69976806640625,+ 253.28997802734375,+ 261.999755859375+ ],+ "origin": [+ 248.18997192382812,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 253.74996948242188,+ 252.95001220703125,+ 259.3099670410156,+ 264.1099853515625+ ],+ "char": "4",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 478,+ "source_indices": [+ 478+ ],+ "raw_code": 52,+ "loose_bbox": [+ 253.74996948242188,+ 252.83978271484375,+ 259.3099670410156,+ 263.999755859375+ ],+ "tight_bbox": [+ 253.87997436523438,+ 254.72979736328125,+ 258.8299560546875,+ 261.8897705078125+ ],+ "origin": [+ 253.74996948242188,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 259.3099670410156,+ 252.95001220703125,+ 262.0899658203125,+ 264.1099853515625+ ],+ "char": ".",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 479,+ "source_indices": [+ 479+ ],+ "raw_code": 46,+ "loose_bbox": [+ 259.3099670410156,+ 252.83978271484375,+ 262.0899658203125,+ 263.999755859375+ ],+ "tight_bbox": [+ 260.219970703125,+ 260.8897705078125,+ 261.219970703125,+ 261.8897705078125+ ],+ "origin": [+ 259.3099670410156,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 262.0899658203125,+ 252.95001220703125,+ 264.8699645996094,+ 264.1099853515625+ ],+ "char": "t",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 480,+ "source_indices": [+ 480+ ],+ "raw_code": 116,+ "loose_bbox": [+ 262.0899658203125,+ 252.83978271484375,+ 264.8699645996094,+ 263.999755859375+ ],+ "tight_bbox": [+ 262.26995849609375,+ 254.8897705078125,+ 264.79998779296875,+ 261.94976806640625+ ],+ "origin": [+ 262.0899658203125,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 264.8699645996094,+ 252.95001220703125,+ 270.4299621582031,+ 264.1099853515625+ ],+ "char": "g",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 481,+ "source_indices": [+ 481+ ],+ "raw_code": 103,+ "loose_bbox": [+ 264.8699645996094,+ 252.83978271484375,+ 270.4299621582031,+ 263.999755859375+ ],+ "tight_bbox": [+ 265.1899719238281,+ 256.58978271484375,+ 269.75994873046875,+ 263.97979736328125+ ],+ "origin": [+ 264.8699645996094,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 270.4299621582031,+ 252.95001220703125,+ 275.4299621582031,+ 264.1099853515625+ ],+ "char": "z",+ "rotation": 0.0,+ "font": {+ "name": "Helvetica",+ "flags": 32,+ "size": 10.0,+ "weight": 0+ },+ "char_idx": 482,+ "source_indices": [+ 482+ ],+ "raw_code": 122,+ "loose_bbox": [+ 270.4299621582031,+ 252.83978271484375,+ 275.4299621582031,+ 263.999755859375+ ],+ "tight_bbox": [+ 270.62994384765625,+ 256.69976806640625,+ 275.219970703125,+ 261.8897705078125+ ],+ "origin": [+ 270.4299621582031,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 275.4299621582031,+ 262.0,+ 275.4299621582031,+ 262.0+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 483,+ "source_indices": [+ 483+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 275.4299621582031,+ 261.8897705078125+ ]+ },+ {+ "bbox": [+ 275.4299621582031,+ 262.0,+ 275.4299621582031,+ 262.0+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 484,+ "source_indices": [+ 484+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 275.4299621582031,+ 261.8897705078125+ ]+ }+ ],+ "tight_bboxes": {+ "439": [+ 72.66000366210938,+ 256.58978271484375,+ 79.69000244140625,+ 261.8897705078125+ ],+ "440": [+ 80.98999786376953,+ 254.72979736328125,+ 81.87000274658203,+ 261.8897705078125+ ],+ "441": [+ 83.20999908447266,+ 256.58978271484375,+ 87.41999816894531,+ 261.8897705078125+ ],+ "442": [+ 88.4800033569336,+ 256.58978271484375,+ 93.26000213623047,+ 261.999755859375+ ],+ "443": [+ 94.31999969482422,+ 256.58978271484375,+ 97.13999938964844,+ 261.8897705078125+ ],+ "444": [+ 97.63999938964844,+ 256.69976806640625,+ 101.83999633789062,+ 261.999755859375+ ],+ "445": [+ 102.41999816894531,+ 263.22979736328125,+ 108.22999572753906,+ 263.8697509765625+ ],+ "446": [+ 108.30000305175781,+ 254.8897705078125,+ 110.83000183105469,+ 261.94976806640625+ ],+ "447": [+ 111.22999572753906,+ 256.58978271484375,+ 116.08999633789062,+ 261.999755859375+ ],+ "448": [+ 116.79000091552734,+ 256.58978271484375,+ 121.64999389648438,+ 261.999755859375+ ],+ "449": [+ 122.66000366210938,+ 254.72979736328125,+ 123.54000091552734,+ 261.8897705078125+ ],+ "450": [+ 124.9000015258789,+ 254.72979736328125,+ 129.1999969482422,+ 261.8897705078125+ ],+ "451": [+ 129.89999389648438,+ 254.72979736328125,+ 130.77999877929688,+ 261.8897705078125+ ],+ "452": [+ 131.63999938964844,+ 254.8897705078125,+ 134.1699981689453,+ 261.94976806640625+ ],+ "453": [+ 134.10000610351562,+ 263.22979736328125,+ 139.91000366210938,+ 263.8697509765625+ ],+ "454": [+ 140.45001220703125,+ 254.72979736328125,+ 144.95001220703125,+ 261.999755859375+ ],+ "455": [+ 146.02000427246094,+ 254.72979736328125,+ 146.89999389648438,+ 261.8897705078125+ ],+ "456": [+ 148.24000549316406,+ 256.58978271484375,+ 152.45001220703125,+ 261.8897705078125+ ],+ "457": [+ 153.5,+ 256.58978271484375,+ 158.27999877929688,+ 261.999755859375+ ],+ "458": [+ 159.35000610351562,+ 256.58978271484375,+ 162.1699981689453,+ 261.8897705078125+ ],+ "459": [+ 162.19000244140625,+ 256.69976806640625,+ 166.94000244140625,+ 263.97979736328125+ ],+ "460": [+ 166.88999938964844,+ 263.22979736328125,+ 172.6999969482422,+ 263.8697509765625+ ],+ "461": [+ 173.67999267578125,+ 254.69976806640625,+ 176.32000732421875,+ 261.8897705078125+ ],+ "462": [+ 179.05999755859375,+ 260.8897705078125,+ 180.05999755859375,+ 261.8897705078125+ ],+ "463": [+ 181.34999084472656,+ 254.69976806640625,+ 186.00999450683594,+ 261.999755859375+ ],+ "464": [+ 187.39999389648438,+ 260.8897705078125,+ 188.39999389648438,+ 261.8897705078125+ ],+ "465": [+ 189.6899871826172,+ 254.69976806640625,+ 194.34999084472656,+ 261.999755859375+ ],+ "466": [+ 194.6899871826172,+ 263.22979736328125,+ 200.49998474121094,+ 263.8697509765625+ ],+ "467": [+ 201.0299835205078,+ 254.72979736328125,+ 201.9099884033203,+ 261.8897705078125+ ],+ "468": [+ 203.26998901367188,+ 254.72979736328125,+ 204.1499786376953,+ 261.8897705078125+ ],+ "469": [+ 205.489990234375,+ 256.58978271484375,+ 209.69998168945312,+ 261.8897705078125+ ],+ "470": [+ 211.0299835205078,+ 256.69976806640625,+ 215.22998046875,+ 261.999755859375+ ],+ "471": [+ 216.01998901367188,+ 256.69976806640625,+ 220.87997436523438,+ 261.8897705078125+ ],+ "472": [+ 220.8099822998047,+ 263.22979736328125,+ 226.61997985839844,+ 263.8697509765625+ ],+ "473": [+ 226.57998657226562,+ 256.69976806640625,+ 231.43997192382812,+ 261.8897705078125+ ],+ "474": [+ 231.91998291015625,+ 254.69976806640625,+ 236.62997436523438,+ 261.999755859375+ ],+ "475": [+ 237.44998168945312,+ 254.69976806640625,+ 242.16998291015625,+ 261.999755859375+ ],+ "476": [+ 242.48997497558594,+ 263.22979736328125,+ 248.2999725341797,+ 263.8697509765625+ ],+ "477": [+ 248.56997680664062,+ 254.69976806640625,+ 253.28997802734375,+ 261.999755859375+ ],+ "478": [+ 253.87997436523438,+ 254.72979736328125,+ 258.8299560546875,+ 261.8897705078125+ ],+ "479": [+ 260.219970703125,+ 260.8897705078125,+ 261.219970703125,+ 261.8897705078125+ ],+ "480": [+ 262.26995849609375,+ 254.8897705078125,+ 264.79998779296875,+ 261.94976806640625+ ],+ "481": [+ 265.1899719238281,+ 256.58978271484375,+ 269.75994873046875,+ 263.97979736328125+ ],+ "482": [+ 270.62994384765625,+ 256.69976806640625,+ 275.219970703125,+ 261.8897705078125+ ]+ },+ "origins": {+ "439": [+ 72.0,+ 261.8897705078125+ ],+ "440": [+ 80.33000183105469,+ 261.8897705078125+ ],+ "441": [+ 82.55000305175781,+ 261.8897705078125+ ],+ "442": [+ 88.11000061035156,+ 261.8897705078125+ ],+ "443": [+ 93.66999816894531,+ 261.8897705078125+ ],+ "444": [+ 97.0,+ 261.8897705078125+ ],+ "445": [+ 102.55999755859375,+ 261.8897705078125+ ],+ "446": [+ 108.1199951171875,+ 261.8897705078125+ ],+ "447": [+ 110.89999389648438,+ 261.8897705078125+ ],+ "448": [+ 116.45999908447266,+ 261.8897705078125+ ],+ "449": [+ 122.02000427246094,+ 261.8897705078125+ ],+ "450": [+ 124.24000549316406,+ 261.8897705078125+ ],+ "451": [+ 129.24000549316406,+ 261.8897705078125+ ],+ "452": [+ 131.4600067138672,+ 261.8897705078125+ ],+ "453": [+ 134.24000549316406,+ 261.8897705078125+ ],+ "454": [+ 139.8000030517578,+ 261.8897705078125+ ],+ "455": [+ 145.36000061035156,+ 261.8897705078125+ ],+ "456": [+ 147.5800018310547,+ 261.8897705078125+ ],+ "457": [+ 153.13999938964844,+ 261.8897705078125+ ],+ "458": [+ 158.6999969482422,+ 261.8897705078125+ ],+ "459": [+ 162.02999877929688,+ 261.8897705078125+ ],+ "460": [+ 167.02999877929688,+ 261.8897705078125+ ],+ "461": [+ 172.58999633789062,+ 261.8897705078125+ ],+ "462": [+ 178.14999389648438,+ 261.8897705078125+ ],+ "463": [+ 180.92999267578125,+ 261.8897705078125+ ],+ "464": [+ 186.489990234375,+ 261.8897705078125+ ],+ "465": [+ 189.26998901367188,+ 261.8897705078125+ ],+ "466": [+ 194.82998657226562,+ 261.8897705078125+ ],+ "467": [+ 200.38998413085938,+ 261.8897705078125+ ],+ "468": [+ 202.6099853515625,+ 261.8897705078125+ ],+ "469": [+ 204.82998657226562,+ 261.8897705078125+ ],+ "470": [+ 210.38998413085938,+ 261.8897705078125+ ],+ "471": [+ 215.94998168945312,+ 261.8897705078125+ ],+ "472": [+ 220.94998168945312,+ 261.8897705078125+ ],+ "473": [+ 226.50997924804688,+ 261.8897705078125+ ],+ "474": [+ 231.50997924804688,+ 261.8897705078125+ ],+ "475": [+ 237.06997680664062,+ 261.8897705078125+ ],+ "476": [+ 242.62997436523438,+ 261.8897705078125+ ],+ "477": [+ 248.18997192382812,+ 261.8897705078125+ ],+ "478": [+ 253.74996948242188,+ 261.8897705078125+ ],+ "479": [+ 259.3099670410156,+ 261.8897705078125+ ],+ "480": [+ 262.0899658203125,+ 261.8897705078125+ ],+ "481": [+ 264.8699645996094,+ 261.8897705078125+ ],+ "482": [+ 270.4299621582031,+ 261.8897705078125+ ],+ "483": [+ 275.4299621582031,+ 261.8897705078125+ ],+ "484": [+ 275.4299621582031,+ 261.8897705078125+ ]+ }+ }+ ]+ },+ {+ "source": "tests/unittest/pdfs/metabolic_pathway_page_3.pdf",+ "page_index": 0,+ "probe": "",+ "selection": "page",+ "fragments": [+ {+ "chars": [+ {+ "bbox": [+ 51.852779388427734,+ 54.838680267333984,+ 66.19902038574219,+ 73.5+ ],+ "char": "E",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 0,+ "source_indices": [+ 0+ ],+ "raw_code": 69,+ "loose_bbox": [+ 50.7599983215332,+ 48.84239959716797,+ 66.81546020507812,+ 80.64510345458984+ ],+ "tight_bbox": [+ 51.852779388427734,+ 54.838680267333984,+ 66.19902038574219,+ 73.5+ ],+ "origin": [+ 50.7599983215332,+ 73.5+ ]+ },+ {+ "bbox": [+ 67.30860900878906,+ 60.69485855102539,+ 81.5147476196289,+ 73.5+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 1,+ "source_indices": [+ 1+ ],+ "raw_code": 110,+ "loose_bbox": [+ 66.80425262451172,+ 48.84239959716797,+ 81.7389144897461,+ 80.64510345458984+ ],+ "tight_bbox": [+ 67.30860900878906,+ 60.69485855102539,+ 81.5147476196289,+ 73.5+ ],+ "origin": [+ 66.80425262451172,+ 73.5+ ]+ },+ {+ "bbox": [+ 82.62434387207031,+ 60.862979888916016,+ 93.29996490478516,+ 73.69613647460938+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 2,+ "source_indices": [+ 2+ ],+ "raw_code": 101,+ "loose_bbox": [+ 81.72770690917969,+ 48.84239959716797,+ 93.72026062011719,+ 80.64510345458984+ ],+ "tight_bbox": [+ 82.62434387207031,+ 60.862979888916016,+ 93.29996490478516,+ 73.69613647460938+ ],+ "origin": [+ 81.72770690917969,+ 73.5+ ]+ },+ {+ "bbox": [+ 94.10133361816406,+ 60.610801696777344,+ 103.71219635009766,+ 73.5+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 3,+ "source_indices": [+ 3+ ],+ "raw_code": 114,+ "loose_bbox": [+ 93.70906066894531,+ 48.84239959716797,+ 103.90834045410156,+ 80.64510345458984+ ],+ "tight_bbox": [+ 94.10133361816406,+ 60.610801696777344,+ 103.71219635009766,+ 73.5+ ],+ "origin": [+ 93.70906066894531,+ 73.5+ ]+ },+ {+ "bbox": [+ 104.23336791992188,+ 60.722877502441406,+ 116.92643737792969,+ 80.61708068847656+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 4,+ "source_indices": [+ 4+ ],+ "raw_code": 103,+ "loose_bbox": [+ 103.89712524414062,+ 48.84239959716797,+ 117.17860412597656,+ 80.64510345458984+ ],+ "tight_bbox": [+ 104.23336791992188,+ 60.722877502441406,+ 116.92643737792969,+ 80.61708068847656+ ],+ "origin": [+ 103.89712524414062,+ 73.5+ ]+ },+ {+ "bbox": [+ 117.30751037597656,+ 61.00307846069336,+ 130.1406707763672,+ 80.58905792236328+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 5,+ "source_indices": [+ 5+ ],+ "raw_code": 121,+ "loose_bbox": [+ 117.16738891601562,+ 48.84239959716797,+ 130.28076171875,+ 80.64510345458984+ ],+ "tight_bbox": [+ 117.30751037597656,+ 61.00307846069336,+ 130.1406707763672,+ 80.58905792236328+ ],+ "origin": [+ 117.16740417480469,+ 73.5+ ]+ },+ {+ "bbox": [+ 130.26954650878906,+ 73.47197723388672,+ 136.26583862304688,+ 73.5+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 6,+ "source_indices": [+ 6+ ],+ "raw_code": 32,+ "loose_bbox": [+ 130.26954650878906,+ 48.84239959716797,+ 136.26583862304688,+ 80.64510345458984+ ],+ "tight_bbox": [+ 130.26954650878906,+ 73.47197723388672,+ 136.26583862304688,+ 73.5+ ],+ "origin": [+ 130.26954650878906,+ 73.5+ ]+ },+ {+ "bbox": [+ 137.47909545898438,+ 54.894718170166016,+ 160.70767211914062,+ 73.8642578125+ ],+ "char": "M",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 7,+ "source_indices": [+ 7+ ],+ "raw_code": 77,+ "loose_bbox": [+ 136.2742156982422,+ 48.84239959716797,+ 161.68836975097656,+ 80.64510345458984+ ],+ "tight_bbox": [+ 137.47909545898438,+ 54.894718170166016,+ 160.70767211914062,+ 73.8642578125+ ],+ "origin": [+ 136.27423095703125,+ 73.5+ ]+ },+ {+ "bbox": [+ 162.5738067626953,+ 60.862979888916016,+ 173.2494354248047,+ 73.69613647460938+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 8,+ "source_indices": [+ 8+ ],+ "raw_code": 101,+ "loose_bbox": [+ 161.6771697998047,+ 48.84239959716797,+ 173.6697235107422,+ 80.64510345458984+ ],+ "tight_bbox": [+ 162.5738067626953,+ 60.862979888916016,+ 173.2494354248047,+ 73.69613647460938+ ],+ "origin": [+ 161.6771697998047,+ 73.5+ ]+ },+ {+ "bbox": [+ 174.3310089111328,+ 58.42523956298828,+ 183.10125732421875,+ 73.72415924072266+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 9,+ "source_indices": [+ 9+ ],+ "raw_code": 116,+ "loose_bbox": [+ 173.6585235595703,+ 48.84239959716797,+ 183.5775909423828,+ 80.64510345458984+ ],+ "tight_bbox": [+ 174.3310089111328,+ 58.42523956298828,+ 183.10125732421875,+ 73.72415924072266+ ],+ "origin": [+ 173.6585235595703,+ 73.5+ ]+ },+ {+ "bbox": [+ 184.7992706298828,+ 61.031097412109375,+ 195.5309295654297,+ 73.83624267578125+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 10,+ "source_indices": [+ 10+ ],+ "raw_code": 97,+ "loose_bbox": [+ 183.56639099121094,+ 48.84239959716797,+ 195.92320251464844,+ 80.64510345458984+ ],+ "tight_bbox": [+ 184.7992706298828,+ 61.031097412109375,+ 195.5309295654297,+ 73.83624267578125+ ],+ "origin": [+ 183.56639099121094,+ 73.5+ ]+ },+ {+ "bbox": [+ 196.02407836914062,+ 52.79322052001953,+ 209.89398193359375,+ 74.36862182617188+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 11,+ "source_indices": [+ 11+ ],+ "raw_code": 98,+ "loose_bbox": [+ 195.91200256347656,+ 48.84239959716797,+ 210.79061889648438,+ 80.64510345458984+ ],+ "tight_bbox": [+ 196.02407836914062,+ 52.79322052001953,+ 209.89398193359375,+ 74.36862182617188+ ],+ "origin": [+ 195.91200256347656,+ 73.5+ ]+ },+ {+ "bbox": [+ 211.67605590820312,+ 60.75090026855469,+ 223.64059448242188,+ 73.64009857177734+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 12,+ "source_indices": [+ 12+ ],+ "raw_code": 111,+ "loose_bbox": [+ 210.77940368652344,+ 48.84239959716797,+ 224.53721618652344,+ 80.64510345458984+ ],+ "tight_bbox": [+ 211.67605590820312,+ 60.75090026855469,+ 223.64059448242188,+ 73.64009857177734+ ],+ "origin": [+ 210.77940368652344,+ 73.5+ ]+ },+ {+ "bbox": [+ 224.72216796875,+ 52.82123947143555,+ 231.83924865722656,+ 73.5+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 13,+ "source_indices": [+ 13+ ],+ "raw_code": 108,+ "loose_bbox": [+ 224.52601623535156,+ 48.84239959716797,+ 232.0634002685547,+ 80.64510345458984+ ],+ "tight_bbox": [+ 224.72216796875,+ 52.82123947143555,+ 231.83924865722656,+ 73.5+ ],+ "origin": [+ 224.52603149414062,+ 73.5+ ]+ },+ {+ "bbox": [+ 232.50051879882812,+ 55.17491912841797,+ 239.3093719482422,+ 73.5+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 14,+ "source_indices": [+ 14+ ],+ "raw_code": 105,+ "loose_bbox": [+ 232.0522003173828,+ 48.84239959716797,+ 239.64561462402344,+ 80.64510345458984+ ],+ "tight_bbox": [+ 232.50051879882812,+ 55.17491912841797,+ 239.3093719482422,+ 73.5+ ],+ "origin": [+ 232.0522003173828,+ 73.5+ ]+ },+ {+ "bbox": [+ 240.78321838378906,+ 60.94704055786133,+ 249.7496337890625,+ 73.66812133789062+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 15,+ "source_indices": [+ 15+ ],+ "raw_code": 115,+ "loose_bbox": [+ 239.63438415527344,+ 48.84239959716797,+ 250.73031616210938,+ 80.64510345458984+ ],+ "tight_bbox": [+ 240.78321838378906,+ 60.94704055786133,+ 249.7496337890625,+ 73.66812133789062+ ],+ "origin": [+ 239.6343994140625,+ 73.5+ ]+ },+ {+ "bbox": [+ 251.11138916015625,+ 60.666839599609375,+ 272.2665100097656,+ 73.5+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 16,+ "source_indices": [+ 16+ ],+ "raw_code": 109,+ "loose_bbox": [+ 250.7191162109375,+ 48.84239959716797,+ 272.462646484375,+ 80.64510345458984+ ],+ "tight_bbox": [+ 251.11138916015625,+ 60.666839599609375,+ 272.2665100097656,+ 73.5+ ],+ "origin": [+ 250.7191162109375,+ 73.5+ ]+ }+ ],+ "tight_bboxes": {+ "0": [+ 51.852779388427734,+ 54.838680267333984,+ 66.19902038574219,+ 73.5+ ],+ "1": [+ 67.30860900878906,+ 60.69485855102539,+ 81.5147476196289,+ 73.5+ ],+ "2": [+ 82.62434387207031,+ 60.862979888916016,+ 93.29996490478516,+ 73.69613647460938+ ],+ "3": [+ 94.10133361816406,+ 60.610801696777344,+ 103.71219635009766,+ 73.5+ ],+ "4": [+ 104.23336791992188,+ 60.722877502441406,+ 116.92643737792969,+ 80.61708068847656+ ],+ "5": [+ 117.30751037597656,+ 61.00307846069336,+ 130.1406707763672,+ 80.58905792236328+ ],+ "6": [+ 130.26954650878906,+ 73.47197723388672,+ 136.26583862304688,+ 73.5+ ],+ "7": [+ 137.47909545898438,+ 54.894718170166016,+ 160.70767211914062,+ 73.8642578125+ ],+ "8": [+ 162.5738067626953,+ 60.862979888916016,+ 173.2494354248047,+ 73.69613647460938+ ],+ "9": [+ 174.3310089111328,+ 58.42523956298828,+ 183.10125732421875,+ 73.72415924072266+ ],+ "10": [+ 184.7992706298828,+ 61.031097412109375,+ 195.5309295654297,+ 73.83624267578125+ ],+ "11": [+ 196.02407836914062,+ 52.79322052001953,+ 209.89398193359375,+ 74.36862182617188+ ],+ "12": [+ 211.67605590820312,+ 60.75090026855469,+ 223.64059448242188,+ 73.64009857177734+ ],+ "13": [+ 224.72216796875,+ 52.82123947143555,+ 231.83924865722656,+ 73.5+ ],+ "14": [+ 232.50051879882812,+ 55.17491912841797,+ 239.3093719482422,+ 73.5+ ],+ "15": [+ 240.78321838378906,+ 60.94704055786133,+ 249.7496337890625,+ 73.66812133789062+ ],+ "16": [+ 251.11138916015625,+ 60.666839599609375,+ 272.2665100097656,+ 73.5+ ]+ },+ "origins": {+ "0": [+ 50.7599983215332,+ 73.5+ ],+ "1": [+ 66.80425262451172,+ 73.5+ ],+ "2": [+ 81.72770690917969,+ 73.5+ ],+ "3": [+ 93.70906066894531,+ 73.5+ ],+ "4": [+ 103.89712524414062,+ 73.5+ ],+ "5": [+ 117.16740417480469,+ 73.5+ ],+ "6": [+ 130.26954650878906,+ 73.5+ ],+ "7": [+ 136.27423095703125,+ 73.5+ ],+ "8": [+ 161.6771697998047,+ 73.5+ ],+ "9": [+ 173.6585235595703,+ 73.5+ ],+ "10": [+ 183.56639099121094,+ 73.5+ ],+ "11": [+ 195.91200256347656,+ 73.5+ ],+ "12": [+ 210.77940368652344,+ 73.5+ ],+ "13": [+ 224.52603149414062,+ 73.5+ ],+ "14": [+ 232.0522003173828,+ 73.5+ ],+ "15": [+ 239.6343994140625,+ 73.5+ ],+ "16": [+ 250.7191162109375,+ 73.5+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 250.7191162109375,+ 74.2760009765625,+ 250.7191162109375,+ 74.2760009765625+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 17,+ "source_indices": [+ 17+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 250.7191162109375,+ 74.2760009765625+ ]+ },+ {+ "bbox": [+ 250.7191162109375,+ 74.2760009765625,+ 250.7191162109375,+ 74.2760009765625+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 18,+ "source_indices": [+ 18+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 250.7191162109375,+ 74.2760009765625+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "17": [+ 250.7191162109375,+ 74.2760009765625+ ],+ "18": [+ 250.7191162109375,+ 74.2760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 60.91200256347656,+ 114.69599914550781,+ 67.03199768066406,+ 117.79199981689453+ ],+ "char": "-",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 19,+ "source_indices": [+ 19+ ],+ "raw_code": 45,+ "loose_bbox": [+ 59.8800048828125,+ 101.39999389648438,+ 68.06401062011719,+ 128.63999938964844+ ],+ "tight_bbox": [+ 60.91200256347656,+ 114.69599914550781,+ 67.03199768066406,+ 117.79199981689453+ ],+ "origin": [+ 59.880001068115234,+ 122.5199966430664+ ]+ }+ ],+ "tight_bboxes": {+ "19": [+ 60.91200256347656,+ 114.69599914550781,+ 67.03199768066406,+ 117.79199981689453+ ]+ },+ "origins": {+ "19": [+ 59.880001068115234,+ 122.5199966430664+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 73.14240264892578,+ 122.5199966430664,+ 73.14240264892578,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 20,+ "source_indices": [+ 20+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 73.14240264892578,+ 122.5199966430664+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "20": [+ 73.14240264892578,+ 122.5199966430664+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 73.38240051269531,+ 106.39199829101562,+ 87.44639587402344,+ 122.5199966430664+ ],+ "char": "T",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 21,+ "source_indices": [+ 21+ ],+ "raw_code": 84,+ "loose_bbox": [+ 73.14241027832031,+ 101.39999389648438,+ 87.83041381835938,+ 128.63999938964844+ ],+ "tight_bbox": [+ 73.38240051269531,+ 106.39199829101562,+ 87.44639587402344,+ 122.5199966430664+ ],+ "origin": [+ 73.14240264892578,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 88.13279724121094,+ 104.68799591064453,+ 100.42080688476562,+ 122.5199966430664+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 22,+ "source_indices": [+ 22+ ],+ "raw_code": 104,+ "loose_bbox": [+ 87.84480285644531,+ 101.39999389648438,+ 100.54080200195312,+ 128.63999938964844+ ],+ "tight_bbox": [+ 88.13279724121094,+ 104.68799591064453,+ 100.42080688476562,+ 122.5199966430664+ ],+ "origin": [+ 87.84480285644531,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 101.29920196533203,+ 111.69599914550781,+ 110.44320678710938,+ 122.68799591064453+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 23,+ "source_indices": [+ 23+ ],+ "raw_code": 101,+ "loose_bbox": [+ 100.53121185302734,+ 101.39999389648438,+ 110.80320739746094,+ 128.63999938964844+ ],+ "tight_bbox": [+ 101.29920196533203,+ 111.69599914550781,+ 110.44320678710938,+ 122.68799591064453+ ],+ "origin": [+ 100.53120422363281,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 110.79360961914062,+ 122.4959945678711,+ 115.92960357666016,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 24,+ "source_indices": [+ 24+ ],+ "raw_code": 32,+ "loose_bbox": [+ 110.79360961914062,+ 101.39999389648438,+ 115.92962646484375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 110.79360961914062,+ 122.4959945678711,+ 115.92960357666016,+ 122.5199966430664+ ],+ "origin": [+ 110.79360961914062,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 116.15760803222656,+ 104.66399383544922,+ 123.693603515625,+ 122.5199966430664+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 25,+ "source_indices": [+ 25+ ],+ "raw_code": 102,+ "loose_bbox": [+ 115.94160461425781,+ 101.39999389648438,+ 123.693603515625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 116.15760803222656,+ 104.66399383544922,+ 123.693603515625,+ 122.5199966430664+ ],+ "origin": [+ 115.94160461425781,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 123.25199890136719,+ 106.8239974975586,+ 129.08399963378906,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 26,+ "source_indices": [+ 26+ ],+ "raw_code": 105,+ "loose_bbox": [+ 122.86801147460938,+ 101.39999389648438,+ 129.37200927734375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 123.25199890136719,+ 106.8239974975586,+ 129.08399963378906,+ 122.5199966430664+ ],+ "origin": [+ 122.86799621582031,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 129.69839477539062,+ 111.47999572753906,+ 137.93040466308594,+ 122.5199966430664+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 27,+ "source_indices": [+ 27+ ],+ "raw_code": 114,+ "loose_bbox": [+ 129.36241149902344,+ 101.39999389648438,+ 138.09840393066406,+ 128.63999938964844+ ],+ "tight_bbox": [+ 129.69839477539062,+ 111.47999572753906,+ 137.93040466308594,+ 122.5199966430664+ ],+ "origin": [+ 129.36239624023438,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 139.0727996826172,+ 111.76799774169922,+ 146.7528076171875,+ 122.66399383544922+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 28,+ "source_indices": [+ 28+ ],+ "raw_code": 115,+ "loose_bbox": [+ 138.08880615234375,+ 101.39999389648438,+ 147.59280395507812,+ 128.63999938964844+ ],+ "tight_bbox": [+ 139.0727996826172,+ 111.76799774169922,+ 146.7528076171875,+ 122.66399383544922+ ],+ "origin": [+ 138.08880615234375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 148.15919494628906,+ 109.60799407958984,+ 155.6711883544922,+ 122.71199798583984+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 29,+ "source_indices": [+ 29+ ],+ "raw_code": 116,+ "loose_bbox": [+ 147.58319091796875,+ 101.39999389648438,+ 156.07919311523438,+ 128.63999938964844+ ],+ "tight_bbox": [+ 148.15919494628906,+ 109.60799407958984,+ 155.6711883544922,+ 122.71199798583984+ ],+ "origin": [+ 147.58319091796875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 156.06959533691406,+ 122.4959945678711,+ 161.20559692382812,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 30,+ "source_indices": [+ 30+ ],+ "raw_code": 32,+ "loose_bbox": [+ 156.06959533691406,+ 101.39999389648438,+ 161.2056121826172,+ 128.63999938964844+ ],+ "tight_bbox": [+ 156.06959533691406,+ 122.4959945678711,+ 161.20559692382812,+ 122.5199966430664+ ],+ "origin": [+ 156.06959533691406,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 161.79359436035156,+ 109.60799407958984,+ 169.3055877685547,+ 122.71199798583984+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 31,+ "source_indices": [+ 31+ ],+ "raw_code": 116,+ "loose_bbox": [+ 161.21759033203125,+ 101.39999389648438,+ 169.71359252929688,+ 128.63999938964844+ ],+ "tight_bbox": [+ 161.79359436035156,+ 109.60799407958984,+ 169.3055877685547,+ 122.71199798583984+ ],+ "origin": [+ 161.21759033203125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 169.99200439453125,+ 104.68799591064453,+ 182.27999877929688,+ 122.5199966430664+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 32,+ "source_indices": [+ 32+ ],+ "raw_code": 104,+ "loose_bbox": [+ 169.70401000976562,+ 101.39999389648438,+ 182.40000915527344,+ 128.63999938964844+ ],+ "tight_bbox": [+ 169.99200439453125,+ 104.68799591064453,+ 182.27999877929688,+ 122.5199966430664+ ],+ "origin": [+ 169.70399475097656,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 182.77438354492188,+ 106.8239974975586,+ 188.60638427734375,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 33,+ "source_indices": [+ 33+ ],+ "raw_code": 105,+ "loose_bbox": [+ 182.39039611816406,+ 101.39999389648438,+ 188.8944091796875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 182.77438354492188,+ 106.8239974975586,+ 188.60638427734375,+ 122.5199966430664+ ],+ "origin": [+ 182.39039611816406,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 189.31678771972656,+ 111.55199432373047,+ 201.4847869873047,+ 122.5199966430664+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 34,+ "source_indices": [+ 34+ ],+ "raw_code": 110,+ "loose_bbox": [+ 188.8848114013672,+ 101.39999389648438,+ 201.67681884765625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 189.31678771972656,+ 111.55199432373047,+ 201.4847869873047,+ 122.5199966430664+ ],+ "origin": [+ 188.88479614257812,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 201.95518493652344,+ 111.57599639892578,+ 212.8271942138672,+ 128.61599731445312+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 35,+ "source_indices": [+ 35+ ],+ "raw_code": 103,+ "loose_bbox": [+ 201.66720581054688,+ 101.39999389648438,+ 213.04319763183594,+ 128.63999938964844+ ],+ "tight_bbox": [+ 201.95518493652344,+ 111.57599639892578,+ 212.8271942138672,+ 128.61599731445312+ ],+ "origin": [+ 201.6671905517578,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 213.03358459472656,+ 122.4959945678711,+ 218.16958618164062,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 36,+ "source_indices": [+ 36+ ],+ "raw_code": 32,+ "loose_bbox": [+ 213.03358459472656,+ 101.39999389648438,+ 218.16961669921875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 213.03358459472656,+ 122.4959945678711,+ 218.16958618164062,+ 122.5199966430664+ ],+ "origin": [+ 213.03358459472656,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 219.23757934570312,+ 111.83999633789062,+ 228.42958068847656,+ 122.80799865722656+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 37,+ "source_indices": [+ 37+ ],+ "raw_code": 97,+ "loose_bbox": [+ 218.1815948486328,+ 101.39999389648438,+ 228.76559448242188,+ 128.63999938964844+ ],+ "tight_bbox": [+ 219.23757934570312,+ 111.83999633789062,+ 228.42958068847656,+ 122.80799865722656+ ],+ "origin": [+ 218.18157958984375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 228.7559814453125,+ 122.4959945678711,+ 233.89198303222656,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 38,+ "source_indices": [+ 38+ ],+ "raw_code": 32,+ "loose_bbox": [+ 228.7559814453125,+ 101.39999389648438,+ 233.8920135498047,+ 128.63999938964844+ ],+ "tight_bbox": [+ 228.7559814453125,+ 122.4959945678711,+ 233.89198303222656,+ 122.5199966430664+ ],+ "origin": [+ 228.7559814453125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 234.0719757080078,+ 104.80799865722656,+ 240.16798400878906,+ 122.5199966430664+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 39,+ "source_indices": [+ 39+ ],+ "raw_code": 108,+ "loose_bbox": [+ 233.90399169921875,+ 101.39999389648438,+ 240.3599853515625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 234.0719757080078,+ 104.80799865722656,+ 240.16798400878906,+ 122.5199966430664+ ],+ "origin": [+ 233.9039764404297,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 240.734375,+ 106.8239974975586,+ 246.56637573242188,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 40,+ "source_indices": [+ 40+ ],+ "raw_code": 105,+ "loose_bbox": [+ 240.35037231445312,+ 101.39999389648438,+ 246.8543701171875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 240.734375,+ 106.8239974975586,+ 246.56637573242188,+ 122.5199966430664+ ],+ "origin": [+ 240.35037231445312,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 246.96478271484375,+ 111.81599426269531,+ 257.8367614746094,+ 122.59199523925781+ ],+ "char": "v",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 41,+ "source_indices": [+ 41+ ],+ "raw_code": 118,+ "loose_bbox": [+ 246.84478759765625,+ 101.39999389648438,+ 257.86077880859375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 246.96478271484375,+ 111.81599426269531,+ 257.8367614746094,+ 122.59199523925781+ ],+ "origin": [+ 246.8447723388672,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 258.23516845703125,+ 106.8239974975586,+ 264.0671691894531,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 42,+ "source_indices": [+ 42+ ],+ "raw_code": 105,+ "loose_bbox": [+ 257.8511962890625,+ 101.39999389648438,+ 264.3551940917969,+ 128.63999938964844+ ],+ "tight_bbox": [+ 258.23516845703125,+ 106.8239974975586,+ 264.0671691894531,+ 122.5199966430664+ ],+ "origin": [+ 257.8511962890625,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 264.777587890625,+ 111.55199432373047,+ 276.9455871582031,+ 122.5199966430664+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 43,+ "source_indices": [+ 43+ ],+ "raw_code": 110,+ "loose_bbox": [+ 264.3455810546875,+ 101.39999389648438,+ 277.1376037597656,+ 128.63999938964844+ ],+ "tight_bbox": [+ 264.777587890625,+ 111.55199432373047,+ 276.9455871582031,+ 122.5199966430664+ ],+ "origin": [+ 264.3455810546875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 277.416015625,+ 111.57599639892578,+ 288.2879943847656,+ 128.61599731445312+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 44,+ "source_indices": [+ 44+ ],+ "raw_code": 103,+ "loose_bbox": [+ 277.12799072265625,+ 101.39999389648438,+ 288.5039978027344,+ 128.63999938964844+ ],+ "tight_bbox": [+ 277.416015625,+ 111.57599639892578,+ 288.2879943847656,+ 128.61599731445312+ ],+ "origin": [+ 277.12799072265625,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 288.4944152832031,+ 122.4959945678711,+ 293.6304016113281,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 45,+ "source_indices": [+ 45+ ],+ "raw_code": 32,+ "loose_bbox": [+ 288.4944152832031,+ 101.39999389648438,+ 293.63043212890625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 288.4944152832031,+ 122.4959945678711,+ 293.6304016113281,+ 122.5199966430664+ ],+ "origin": [+ 288.4944152832031,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 294.410400390625,+ 111.5999984741211,+ 304.6584167480469,+ 122.63999938964844+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 46,+ "source_indices": [+ 46+ ],+ "raw_code": 111,+ "loose_bbox": [+ 293.6424560546875,+ 101.39999389648438,+ 305.42645263671875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 294.410400390625,+ 111.5999984741211,+ 304.6584167480469,+ 122.63999938964844+ ],+ "origin": [+ 293.6424255371094,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 305.7528381347656,+ 111.47999572753906,+ 313.9848327636719,+ 122.5199966430664+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 47,+ "source_indices": [+ 47+ ],+ "raw_code": 114,+ "loose_bbox": [+ 305.4168701171875,+ 101.39999389648438,+ 314.1528625488281,+ 128.63999938964844+ ],+ "tight_bbox": [+ 305.7528381347656,+ 111.47999572753906,+ 313.9848327636719,+ 122.5199966430664+ ],+ "origin": [+ 305.4168395996094,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 314.4312438964844,+ 111.57599639892578,+ 325.3032531738281,+ 128.61599731445312+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 48,+ "source_indices": [+ 48+ ],+ "raw_code": 103,+ "loose_bbox": [+ 314.14324951171875,+ 101.39999389648438,+ 325.5192565917969,+ 128.63999938964844+ ],+ "tight_bbox": [+ 314.4312438964844,+ 111.57599639892578,+ 325.3032531738281,+ 128.61599731445312+ ],+ "origin": [+ 314.14324951171875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 326.565673828125,+ 111.83999633789062,+ 335.7576599121094,+ 122.80799865722656+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 49,+ "source_indices": [+ 49+ ],+ "raw_code": 97,+ "loose_bbox": [+ 325.50970458984375,+ 101.39999389648438,+ 336.09368896484375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 326.565673828125,+ 111.83999633789062,+ 335.7576599121094,+ 122.80799865722656+ ],+ "origin": [+ 325.5096740722656,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 336.51605224609375,+ 111.55199432373047,+ 348.68408203125,+ 122.5199966430664+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 50,+ "source_indices": [+ 50+ ],+ "raw_code": 110,+ "loose_bbox": [+ 336.0841064453125,+ 101.39999389648438,+ 348.8760986328125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 336.51605224609375,+ 111.55199432373047,+ 348.68408203125,+ 122.5199966430664+ ],+ "origin": [+ 336.0840759277344,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 349.25048828125,+ 106.8239974975586,+ 355.0824890136719,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 51,+ "source_indices": [+ 51+ ],+ "raw_code": 105,+ "loose_bbox": [+ 348.86651611328125,+ 101.39999389648438,+ 355.3705139160156,+ 128.63999938964844+ ],+ "tight_bbox": [+ 349.25048828125,+ 106.8239974975586,+ 355.0824890136719,+ 122.5199966430664+ ],+ "origin": [+ 348.8664855957031,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 356.34490966796875,+ 111.76799774169922,+ 364.02490234375,+ 122.66399383544922+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 52,+ "source_indices": [+ 52+ ],+ "raw_code": 115,+ "loose_bbox": [+ 355.36090087890625,+ 101.39999389648438,+ 364.86492919921875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 356.34490966796875,+ 111.76799774169922,+ 364.02490234375,+ 122.66399383544922+ ],+ "origin": [+ 355.36090087890625,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 365.1912841796875,+ 111.52799987792969,+ 383.3113098144531,+ 122.5199966430664+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 53,+ "source_indices": [+ 53+ ],+ "raw_code": 109,+ "loose_bbox": [+ 364.85528564453125,+ 101.39999389648438,+ 383.47930908203125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 365.1912841796875,+ 111.52799987792969,+ 383.3113098144531,+ 122.5199966430664+ ],+ "origin": [+ 364.85528564453125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 383.5199890136719,+ 122.4959945678711,+ 388.6559753417969,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 54,+ "source_indices": [+ 54+ ],+ "raw_code": 32,+ "loose_bbox": [+ 383.5199890136719,+ 101.39999389648438,+ 388.6559753417969,+ 128.63999938964844+ ],+ "tight_bbox": [+ 383.5199890136719,+ 122.4959945678711,+ 388.6559753417969,+ 122.5199966430664+ ],+ "origin": [+ 383.5199890136719,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 388.9607849121094,+ 104.68799591064453,+ 401.248779296875,+ 122.5199966430664+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 55,+ "source_indices": [+ 55+ ],+ "raw_code": 104,+ "loose_bbox": [+ 388.67279052734375,+ 101.39999389648438,+ 401.3688049316406,+ 128.63999938964844+ ],+ "tight_bbox": [+ 388.9607849121094,+ 104.68799591064453,+ 401.248779296875,+ 122.5199966430664+ ],+ "origin": [+ 388.67279052734375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 402.41998291015625,+ 111.83999633789062,+ 411.61199951171875,+ 122.80799865722656+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 56,+ "source_indices": [+ 56+ ],+ "raw_code": 97,+ "loose_bbox": [+ 401.3639831542969,+ 101.39999389648438,+ 411.947998046875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 402.41998291015625,+ 111.83999633789062,+ 411.61199951171875,+ 122.80799865722656+ ],+ "origin": [+ 401.3639831542969,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 412.92718505859375,+ 111.76799774169922,+ 420.607177734375,+ 122.66399383544922+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 57,+ "source_indices": [+ 57+ ],+ "raw_code": 115,+ "loose_bbox": [+ 411.94317626953125,+ 101.39999389648438,+ 421.4471740722656,+ 128.63999938964844+ ],+ "tight_bbox": [+ 412.92718505859375,+ 111.76799774169922,+ 420.607177734375,+ 122.66399383544922+ ],+ "origin": [+ 411.94317626953125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 421.4423828125,+ 122.4959945678711,+ 426.5783996582031,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 58,+ "source_indices": [+ 58+ ],+ "raw_code": 32,+ "loose_bbox": [+ 421.4423828125,+ 101.39999389648438,+ 426.57843017578125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 421.4423828125,+ 122.4959945678711,+ 426.5783996582031,+ 122.5199966430664+ ],+ "origin": [+ 421.4423828125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 426.8831787109375,+ 111.57599639892578,+ 437.75518798828125,+ 128.61599731445312+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 59,+ "source_indices": [+ 59+ ],+ "raw_code": 103,+ "loose_bbox": [+ 426.5951843261719,+ 101.39999389648438,+ 437.97119140625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 426.8831787109375,+ 111.57599639892578,+ 437.75518798828125,+ 128.61599731445312+ ],+ "origin": [+ 426.5951843261719,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 438.734375,+ 111.5999984741211,+ 448.9823913574219,+ 122.63999938964844+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 60,+ "source_indices": [+ 60+ ],+ "raw_code": 111,+ "loose_bbox": [+ 437.9664001464844,+ 101.39999389648438,+ 449.7503967285156,+ 128.63999938964844+ ],+ "tight_bbox": [+ 438.734375,+ 111.5999984741211,+ 448.9823913574219,+ 122.63999938964844+ ],+ "origin": [+ 437.9664001464844,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 450.32159423828125,+ 109.60799407958984,+ 457.8335876464844,+ 122.71199798583984+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 61,+ "source_indices": [+ 61+ ],+ "raw_code": 116,+ "loose_bbox": [+ 449.74560546875,+ 101.39999389648438,+ 458.24163818359375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 450.32159423828125,+ 109.60799407958984,+ 457.8335876464844,+ 122.71199798583984+ ],+ "origin": [+ 449.74560546875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 458.2367858886719,+ 122.4959945678711,+ 463.372802734375,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 62,+ "source_indices": [+ 62+ ],+ "raw_code": 32,+ "loose_bbox": [+ 458.2367858886719,+ 101.39999389648438,+ 463.372802734375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 458.2367858886719,+ 122.4959945678711,+ 463.372802734375,+ 122.5199966430664+ ],+ "origin": [+ 458.2367858886719,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 463.965576171875,+ 109.60799407958984,+ 471.47760009765625,+ 122.71199798583984+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 63,+ "source_indices": [+ 63+ ],+ "raw_code": 116,+ "loose_bbox": [+ 463.38958740234375,+ 101.39999389648438,+ 471.8855895996094,+ 128.63999938964844+ ],+ "tight_bbox": [+ 463.965576171875,+ 109.60799407958984,+ 471.47760009765625,+ 122.71199798583984+ ],+ "origin": [+ 463.38958740234375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 472.6488037109375,+ 111.5999984741211,+ 482.89678955078125,+ 122.63999938964844+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 64,+ "source_indices": [+ 64+ ],+ "raw_code": 111,+ "loose_bbox": [+ 471.8808288574219,+ 101.39999389648438,+ 483.6648254394531,+ 128.63999938964844+ ],+ "tight_bbox": [+ 472.6488037109375,+ 111.5999984741211,+ 482.89678955078125,+ 122.63999938964844+ ],+ "origin": [+ 471.88079833984375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 483.65997314453125,+ 122.4959945678711,+ 488.7959899902344,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 65,+ "source_indices": [+ 65+ ],+ "raw_code": 32,+ "loose_bbox": [+ 483.65997314453125,+ 101.39999389648438,+ 488.7960205078125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 483.65997314453125,+ 122.4959945678711,+ 488.7959899902344,+ 122.5199966430664+ ],+ "origin": [+ 483.65997314453125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 488.9088134765625,+ 104.78399658203125,+ 500.788818359375,+ 123.26399993896484+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 66,+ "source_indices": [+ 66+ ],+ "raw_code": 98,+ "loose_bbox": [+ 488.81280517578125,+ 101.39999389648438,+ 501.55682373046875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 488.9088134765625,+ 104.78399658203125,+ 500.788818359375,+ 123.26399993896484+ ],+ "origin": [+ 488.81280517578125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 502.32000732421875,+ 111.69599914550781,+ 511.4639892578125,+ 122.68799591064453+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 67,+ "source_indices": [+ 67+ ],+ "raw_code": 101,+ "loose_bbox": [+ 501.552001953125,+ 101.39999389648438,+ 511.82403564453125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 502.32000732421875,+ 111.69599914550781,+ 511.4639892578125,+ 122.68799591064453+ ],+ "origin": [+ 501.552001953125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 511.8192138671875,+ 122.4959945678711,+ 516.9552001953125,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 68,+ "source_indices": [+ 68+ ],+ "raw_code": 32,+ "loose_bbox": [+ 511.8192138671875,+ 101.39999389648438,+ 516.9552612304688,+ 128.63999938964844+ ],+ "tight_bbox": [+ 511.8192138671875,+ 122.4959945678711,+ 516.9552001953125,+ 122.5199966430664+ ],+ "origin": [+ 511.8192138671875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 518.0280151367188,+ 111.83999633789062,+ 527.2200317382812,+ 122.80799865722656+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 69,+ "source_indices": [+ 69+ ],+ "raw_code": 97,+ "loose_bbox": [+ 516.9720458984375,+ 101.39999389648438,+ 527.5560302734375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 518.0280151367188,+ 111.83999633789062,+ 527.2200317382812,+ 122.80799865722656+ ],+ "origin": [+ 516.9720458984375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 527.647216796875,+ 104.78399658203125,+ 539.5272216796875,+ 123.26399993896484+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 70,+ "source_indices": [+ 70+ ],+ "raw_code": 98,+ "loose_bbox": [+ 527.5512084960938,+ 101.39999389648438,+ 540.2952270507812,+ 128.63999938964844+ ],+ "tight_bbox": [+ 527.647216796875,+ 104.78399658203125,+ 539.5272216796875,+ 123.26399993896484+ ],+ "origin": [+ 527.5512084960938,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 540.4584350585938,+ 104.80799865722656,+ 546.554443359375,+ 122.5199966430664+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 71,+ "source_indices": [+ 71+ ],+ "raw_code": 108,+ "loose_bbox": [+ 540.2904052734375,+ 101.39999389648438,+ 546.7463989257812,+ 128.63999938964844+ ],+ "tight_bbox": [+ 540.4584350585938,+ 104.80799865722656,+ 546.554443359375,+ 122.5199966430664+ ],+ "origin": [+ 540.2904052734375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 547.5096435546875,+ 111.69599914550781,+ 556.6536254882812,+ 122.68799591064453+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 72,+ "source_indices": [+ 72+ ],+ "raw_code": 101,+ "loose_bbox": [+ 546.74169921875,+ 101.39999389648438,+ 557.013671875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 547.5096435546875,+ 111.69599914550781,+ 556.6536254882812,+ 122.68799591064453+ ],+ "origin": [+ 546.7416381835938,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 557.0088500976562,+ 122.4959945678711,+ 562.1448364257812,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 73,+ "source_indices": [+ 73+ ],+ "raw_code": 32,+ "loose_bbox": [+ 557.0088500976562,+ 101.39999389648438,+ 562.1448364257812,+ 128.63999938964844+ ],+ "tight_bbox": [+ 557.0088500976562,+ 122.4959945678711,+ 562.1448364257812,+ 122.5199966430664+ ],+ "origin": [+ 557.0088500976562,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 562.7376708984375,+ 109.60799407958984,+ 570.2496337890625,+ 122.71199798583984+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 74,+ "source_indices": [+ 74+ ],+ "raw_code": 116,+ "loose_bbox": [+ 562.16162109375,+ 101.39999389648438,+ 570.6575927734375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 562.7376708984375,+ 109.60799407958984,+ 570.2496337890625,+ 122.71199798583984+ ],+ "origin": [+ 562.16162109375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 571.4208374023438,+ 111.5999984741211,+ 581.6688232421875,+ 122.63999938964844+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 75,+ "source_indices": [+ 75+ ],+ "raw_code": 111,+ "loose_bbox": [+ 570.65283203125,+ 101.39999389648438,+ 582.4368896484375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 571.4208374023438,+ 111.5999984741211,+ 581.6688232421875,+ 122.63999938964844+ ],+ "origin": [+ 570.65283203125,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 582.4320068359375,+ 122.4959945678711,+ 587.5679931640625,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 76,+ "source_indices": [+ 76+ ],+ "raw_code": 32,+ "loose_bbox": [+ 582.4320068359375,+ 101.39999389648438,+ 587.5679931640625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 582.4320068359375,+ 122.4959945678711,+ 587.5679931640625,+ 122.5199966430664+ ],+ "origin": [+ 582.4320068359375,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 588.352783203125,+ 104.68799591064453,+ 600.496826171875,+ 122.87999725341797+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 77,+ "source_indices": [+ 77+ ],+ "raw_code": 100,+ "loose_bbox": [+ 587.5848388671875,+ 101.39999389648438,+ 600.496826171875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 588.352783203125,+ 104.68799591064453,+ 600.496826171875,+ 122.87999725341797+ ],+ "origin": [+ 587.5848388671875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 601.1400146484375,+ 111.5999984741211,+ 611.3880004882812,+ 122.63999938964844+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 78,+ "source_indices": [+ 78+ ],+ "raw_code": 111,+ "loose_bbox": [+ 600.3720092773438,+ 101.39999389648438,+ 612.156005859375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 601.1400146484375,+ 111.5999984741211,+ 611.3880004882812,+ 122.63999938964844+ ],+ "origin": [+ 600.3720092773438,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 612.1512451171875,+ 122.4959945678711,+ 617.2872314453125,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 79,+ "source_indices": [+ 79+ ],+ "raw_code": 32,+ "loose_bbox": [+ 612.1512451171875,+ 101.39999389648438,+ 617.2872314453125,+ 128.63999938964844+ ],+ "tight_bbox": [+ 612.1512451171875,+ 122.4959945678711,+ 617.2872314453125,+ 122.5199966430664+ ],+ "origin": [+ 612.1512451171875,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 617.68798828125,+ 106.8239974975586,+ 623.52001953125,+ 122.5199966430664+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 80,+ "source_indices": [+ 80+ ],+ "raw_code": 105,+ "loose_bbox": [+ 617.3040161132812,+ 101.39999389648438,+ 623.8079833984375,+ 128.63999938964844+ ],+ "tight_bbox": [+ 617.68798828125,+ 106.8239974975586,+ 623.52001953125,+ 122.5199966430664+ ],+ "origin": [+ 617.3040161132812,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 624.7872314453125,+ 111.76799774169922,+ 632.4672241210938,+ 122.66399383544922+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 81,+ "source_indices": [+ 81+ ],+ "raw_code": 115,+ "loose_bbox": [+ 623.80322265625,+ 101.39999389648438,+ 633.3072509765625,+ 128.63999938964844+ ],+ "tight_bbox": [+ 624.7872314453125,+ 111.76799774169922,+ 632.4672241210938,+ 122.66399383544922+ ],+ "origin": [+ 623.80322265625,+ 122.5199966430664+ ]+ },+ {+ "bbox": [+ 633.3023681640625,+ 122.4959945678711,+ 638.4383544921875,+ 122.5199966430664+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 82,+ "source_indices": [+ 82+ ],+ "raw_code": 32,+ "loose_bbox": [+ 633.3023681640625,+ 101.39999389648438,+ 638.4383544921875,+ 128.63999938964844+ ],+ "tight_bbox": [+ 633.3023681640625,+ 122.4959945678711,+ 638.4383544921875,+ 122.5199966430664+ ],+ "origin": [+ 633.3023681640625,+ 122.5199966430664+ ]+ }+ ],+ "tight_bboxes": {+ "21": [+ 73.38240051269531,+ 106.39199829101562,+ 87.44639587402344,+ 122.5199966430664+ ],+ "22": [+ 88.13279724121094,+ 104.68799591064453,+ 100.42080688476562,+ 122.5199966430664+ ],+ "23": [+ 101.29920196533203,+ 111.69599914550781,+ 110.44320678710938,+ 122.68799591064453+ ],+ "24": [+ 110.79360961914062,+ 122.4959945678711,+ 115.92960357666016,+ 122.5199966430664+ ],+ "25": [+ 116.15760803222656,+ 104.66399383544922,+ 123.693603515625,+ 122.5199966430664+ ],+ "26": [+ 123.25199890136719,+ 106.8239974975586,+ 129.08399963378906,+ 122.5199966430664+ ],+ "27": [+ 129.69839477539062,+ 111.47999572753906,+ 137.93040466308594,+ 122.5199966430664+ ],+ "28": [+ 139.0727996826172,+ 111.76799774169922,+ 146.7528076171875,+ 122.66399383544922+ ],+ "29": [+ 148.15919494628906,+ 109.60799407958984,+ 155.6711883544922,+ 122.71199798583984+ ],+ "30": [+ 156.06959533691406,+ 122.4959945678711,+ 161.20559692382812,+ 122.5199966430664+ ],+ "31": [+ 161.79359436035156,+ 109.60799407958984,+ 169.3055877685547,+ 122.71199798583984+ ],+ "32": [+ 169.99200439453125,+ 104.68799591064453,+ 182.27999877929688,+ 122.5199966430664+ ],+ "33": [+ 182.77438354492188,+ 106.8239974975586,+ 188.60638427734375,+ 122.5199966430664+ ],+ "34": [+ 189.31678771972656,+ 111.55199432373047,+ 201.4847869873047,+ 122.5199966430664+ ],+ "35": [+ 201.95518493652344,+ 111.57599639892578,+ 212.8271942138672,+ 128.61599731445312+ ],+ "36": [+ 213.03358459472656,+ 122.4959945678711,+ 218.16958618164062,+ 122.5199966430664+ ],+ "37": [+ 219.23757934570312,+ 111.83999633789062,+ 228.42958068847656,+ 122.80799865722656+ ],+ "38": [+ 228.7559814453125,+ 122.4959945678711,+ 233.89198303222656,+ 122.5199966430664+ ],+ "39": [+ 234.0719757080078,+ 104.80799865722656,+ 240.16798400878906,+ 122.5199966430664+ ],+ "40": [+ 240.734375,+ 106.8239974975586,+ 246.56637573242188,+ 122.5199966430664+ ],+ "41": [+ 246.96478271484375,+ 111.81599426269531,+ 257.8367614746094,+ 122.59199523925781+ ],+ "42": [+ 258.23516845703125,+ 106.8239974975586,+ 264.0671691894531,+ 122.5199966430664+ ],+ "43": [+ 264.777587890625,+ 111.55199432373047,+ 276.9455871582031,+ 122.5199966430664+ ],+ "44": [+ 277.416015625,+ 111.57599639892578,+ 288.2879943847656,+ 128.61599731445312+ ],+ "45": [+ 288.4944152832031,+ 122.4959945678711,+ 293.6304016113281,+ 122.5199966430664+ ],+ "46": [+ 294.410400390625,+ 111.5999984741211,+ 304.6584167480469,+ 122.63999938964844+ ],+ "47": [+ 305.7528381347656,+ 111.47999572753906,+ 313.9848327636719,+ 122.5199966430664+ ],+ "48": [+ 314.4312438964844,+ 111.57599639892578,+ 325.3032531738281,+ 128.61599731445312+ ],+ "49": [+ 326.565673828125,+ 111.83999633789062,+ 335.7576599121094,+ 122.80799865722656+ ],+ "50": [+ 336.51605224609375,+ 111.55199432373047,+ 348.68408203125,+ 122.5199966430664+ ],+ "51": [+ 349.25048828125,+ 106.8239974975586,+ 355.0824890136719,+ 122.5199966430664+ ],+ "52": [+ 356.34490966796875,+ 111.76799774169922,+ 364.02490234375,+ 122.66399383544922+ ],+ "53": [+ 365.1912841796875,+ 111.52799987792969,+ 383.3113098144531,+ 122.5199966430664+ ],+ "54": [+ 383.5199890136719,+ 122.4959945678711,+ 388.6559753417969,+ 122.5199966430664+ ],+ "55": [+ 388.9607849121094,+ 104.68799591064453,+ 401.248779296875,+ 122.5199966430664+ ],+ "56": [+ 402.41998291015625,+ 111.83999633789062,+ 411.61199951171875,+ 122.80799865722656+ ],+ "57": [+ 412.92718505859375,+ 111.76799774169922,+ 420.607177734375,+ 122.66399383544922+ ],+ "58": [+ 421.4423828125,+ 122.4959945678711,+ 426.5783996582031,+ 122.5199966430664+ ],+ "59": [+ 426.8831787109375,+ 111.57599639892578,+ 437.75518798828125,+ 128.61599731445312+ ],+ "60": [+ 438.734375,+ 111.5999984741211,+ 448.9823913574219,+ 122.63999938964844+ ],+ "61": [+ 450.32159423828125,+ 109.60799407958984,+ 457.8335876464844,+ 122.71199798583984+ ],+ "62": [+ 458.2367858886719,+ 122.4959945678711,+ 463.372802734375,+ 122.5199966430664+ ],+ "63": [+ 463.965576171875,+ 109.60799407958984,+ 471.47760009765625,+ 122.71199798583984+ ],+ "64": [+ 472.6488037109375,+ 111.5999984741211,+ 482.89678955078125,+ 122.63999938964844+ ],+ "65": [+ 483.65997314453125,+ 122.4959945678711,+ 488.7959899902344,+ 122.5199966430664+ ],+ "66": [+ 488.9088134765625,+ 104.78399658203125,+ 500.788818359375,+ 123.26399993896484+ ],+ "67": [+ 502.32000732421875,+ 111.69599914550781,+ 511.4639892578125,+ 122.68799591064453+ ],+ "68": [+ 511.8192138671875,+ 122.4959945678711,+ 516.9552001953125,+ 122.5199966430664+ ],+ "69": [+ 518.0280151367188,+ 111.83999633789062,+ 527.2200317382812,+ 122.80799865722656+ ],+ "70": [+ 527.647216796875,+ 104.78399658203125,+ 539.5272216796875,+ 123.26399993896484+ ],+ "71": [+ 540.4584350585938,+ 104.80799865722656,+ 546.554443359375,+ 122.5199966430664+ ],+ "72": [+ 547.5096435546875,+ 111.69599914550781,+ 556.6536254882812,+ 122.68799591064453+ ],+ "73": [+ 557.0088500976562,+ 122.4959945678711,+ 562.1448364257812,+ 122.5199966430664+ ],+ "74": [+ 562.7376708984375,+ 109.60799407958984,+ 570.2496337890625,+ 122.71199798583984+ ],+ "75": [+ 571.4208374023438,+ 111.5999984741211,+ 581.6688232421875,+ 122.63999938964844+ ],+ "76": [+ 582.4320068359375,+ 122.4959945678711,+ 587.5679931640625,+ 122.5199966430664+ ],+ "77": [+ 588.352783203125,+ 104.68799591064453,+ 600.496826171875,+ 122.87999725341797+ ],+ "78": [+ 601.1400146484375,+ 111.5999984741211,+ 611.3880004882812,+ 122.63999938964844+ ],+ "79": [+ 612.1512451171875,+ 122.4959945678711,+ 617.2872314453125,+ 122.5199966430664+ ],+ "80": [+ 617.68798828125,+ 106.8239974975586,+ 623.52001953125,+ 122.5199966430664+ ],+ "81": [+ 624.7872314453125,+ 111.76799774169922,+ 632.4672241210938,+ 122.66399383544922+ ],+ "82": [+ 633.3023681640625,+ 122.4959945678711,+ 638.4383544921875,+ 122.5199966430664+ ]+ },+ "origins": {+ "21": [+ 73.14240264892578,+ 122.5199966430664+ ],+ "22": [+ 87.84480285644531,+ 122.5199966430664+ ],+ "23": [+ 100.53120422363281,+ 122.5199966430664+ ],+ "24": [+ 110.79360961914062,+ 122.5199966430664+ ],+ "25": [+ 115.94160461425781,+ 122.5199966430664+ ],+ "26": [+ 122.86799621582031,+ 122.5199966430664+ ],+ "27": [+ 129.36239624023438,+ 122.5199966430664+ ],+ "28": [+ 138.08880615234375,+ 122.5199966430664+ ],+ "29": [+ 147.58319091796875,+ 122.5199966430664+ ],+ "30": [+ 156.06959533691406,+ 122.5199966430664+ ],+ "31": [+ 161.21759033203125,+ 122.5199966430664+ ],+ "32": [+ 169.70399475097656,+ 122.5199966430664+ ],+ "33": [+ 182.39039611816406,+ 122.5199966430664+ ],+ "34": [+ 188.88479614257812,+ 122.5199966430664+ ],+ "35": [+ 201.6671905517578,+ 122.5199966430664+ ],+ "36": [+ 213.03358459472656,+ 122.5199966430664+ ],+ "37": [+ 218.18157958984375,+ 122.5199966430664+ ],+ "38": [+ 228.7559814453125,+ 122.5199966430664+ ],+ "39": [+ 233.9039764404297,+ 122.5199966430664+ ],+ "40": [+ 240.35037231445312,+ 122.5199966430664+ ],+ "41": [+ 246.8447723388672,+ 122.5199966430664+ ],+ "42": [+ 257.8511962890625,+ 122.5199966430664+ ],+ "43": [+ 264.3455810546875,+ 122.5199966430664+ ],+ "44": [+ 277.12799072265625,+ 122.5199966430664+ ],+ "45": [+ 288.4944152832031,+ 122.5199966430664+ ],+ "46": [+ 293.6424255371094,+ 122.5199966430664+ ],+ "47": [+ 305.4168395996094,+ 122.5199966430664+ ],+ "48": [+ 314.14324951171875,+ 122.5199966430664+ ],+ "49": [+ 325.5096740722656,+ 122.5199966430664+ ],+ "50": [+ 336.0840759277344,+ 122.5199966430664+ ],+ "51": [+ 348.8664855957031,+ 122.5199966430664+ ],+ "52": [+ 355.36090087890625,+ 122.5199966430664+ ],+ "53": [+ 364.85528564453125,+ 122.5199966430664+ ],+ "54": [+ 383.5199890136719,+ 122.5199966430664+ ],+ "55": [+ 388.67279052734375,+ 122.5199966430664+ ],+ "56": [+ 401.3639831542969,+ 122.5199966430664+ ],+ "57": [+ 411.94317626953125,+ 122.5199966430664+ ],+ "58": [+ 421.4423828125,+ 122.5199966430664+ ],+ "59": [+ 426.5951843261719,+ 122.5199966430664+ ],+ "60": [+ 437.9664001464844,+ 122.5199966430664+ ],+ "61": [+ 449.74560546875,+ 122.5199966430664+ ],+ "62": [+ 458.2367858886719,+ 122.5199966430664+ ],+ "63": [+ 463.38958740234375,+ 122.5199966430664+ ],+ "64": [+ 471.88079833984375,+ 122.5199966430664+ ],+ "65": [+ 483.65997314453125,+ 122.5199966430664+ ],+ "66": [+ 488.81280517578125,+ 122.5199966430664+ ],+ "67": [+ 501.552001953125,+ 122.5199966430664+ ],+ "68": [+ 511.8192138671875,+ 122.5199966430664+ ],+ "69": [+ 516.9720458984375,+ 122.5199966430664+ ],+ "70": [+ 527.5512084960938,+ 122.5199966430664+ ],+ "71": [+ 540.2904052734375,+ 122.5199966430664+ ],+ "72": [+ 546.7416381835938,+ 122.5199966430664+ ],+ "73": [+ 557.0088500976562,+ 122.5199966430664+ ],+ "74": [+ 562.16162109375,+ 122.5199966430664+ ],+ "75": [+ 570.65283203125,+ 122.5199966430664+ ],+ "76": [+ 582.4320068359375,+ 122.5199966430664+ ],+ "77": [+ 587.5848388671875,+ 122.5199966430664+ ],+ "78": [+ 600.3720092773438,+ 122.5199966430664+ ],+ "79": [+ 612.1512451171875,+ 122.5199966430664+ ],+ "80": [+ 617.3040161132812,+ 122.5199966430664+ ],+ "81": [+ 623.80322265625,+ 122.5199966430664+ ],+ "82": [+ 633.3023681640625,+ 122.5199966430664+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 633.3023681640625,+ 122.73399353027344,+ 633.3023681640625,+ 122.73399353027344+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 83,+ "source_indices": [+ 83+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 633.3023681640625,+ 122.73399353027344+ ]+ },+ {+ "bbox": [+ 633.3023681640625,+ 122.73399353027344,+ 633.3023681640625,+ 122.73399353027344+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 84,+ "source_indices": [+ 84+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 633.3023681640625,+ 122.73399353027344+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "83": [+ 633.3023681640625,+ 122.73399353027344+ ],+ "84": [+ 633.3023681640625,+ 122.73399353027344+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 60.167999267578125,+ 133.42799377441406,+ 72.45600128173828,+ 151.25999450683594+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 85,+ "source_indices": [+ 85+ ],+ "raw_code": 104,+ "loose_bbox": [+ 59.8800048828125,+ 130.13999938964844,+ 72.57600402832031,+ 157.37998962402344+ ],+ "tight_bbox": [+ 60.167999267578125,+ 133.42799377441406,+ 72.45600128173828,+ 151.25999450683594+ ],+ "origin": [+ 59.880001068115234,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 73.62480163574219,+ 140.57998657226562,+ 82.81680297851562,+ 151.54798889160156+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 86,+ "source_indices": [+ 86+ ],+ "raw_code": 97,+ "loose_bbox": [+ 72.56880950927734,+ 130.13999938964844,+ 83.1528091430664,+ 157.37998962402344+ ],+ "tight_bbox": [+ 73.62480163574219,+ 140.57998657226562,+ 82.81680297851562,+ 151.54798889160156+ ],+ "origin": [+ 72.56880187988281,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 83.48159790039062,+ 140.22000122070312,+ 91.7136001586914,+ 151.25999450683594+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 87,+ "source_indices": [+ 87+ ],+ "raw_code": 114,+ "loose_bbox": [+ 83.1456069946289,+ 130.13999938964844,+ 91.88160705566406,+ 157.37998962402344+ ],+ "tight_bbox": [+ 83.48159790039062,+ 140.22000122070312,+ 91.7136001586914,+ 151.25999450683594+ ],+ "origin": [+ 83.14559936523438,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 92.306396484375,+ 140.2919921875,+ 104.47439575195312,+ 151.25999450683594+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 88,+ "source_indices": [+ 88+ ],+ "raw_code": 110,+ "loose_bbox": [+ 91.87440490722656,+ 130.13999938964844,+ 104.66641235351562,+ 157.37998962402344+ ],+ "tight_bbox": [+ 92.306396484375,+ 140.2919921875,+ 104.47439575195312,+ 151.25999450683594+ ],+ "origin": [+ 91.87440490722656,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 105.42720031738281,+ 140.4359893798828,+ 114.57119750976562,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 89,+ "source_indices": [+ 89+ ],+ "raw_code": 101,+ "loose_bbox": [+ 104.65919494628906,+ 130.13999938964844,+ 114.93119812011719,+ 157.37998962402344+ ],+ "tight_bbox": [+ 105.42720031738281,+ 140.4359893798828,+ 114.57119750976562,+ 151.42799377441406+ ],+ "origin": [+ 104.65919494628906,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 115.90799713134766,+ 140.50799560546875,+ 123.58799743652344,+ 151.40399169921875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 90,+ "source_indices": [+ 90+ ],+ "raw_code": 115,+ "loose_bbox": [+ 114.92399597167969,+ 130.13999938964844,+ 124.42799377441406,+ 157.37998962402344+ ],+ "tight_bbox": [+ 115.90799713134766,+ 140.50799560546875,+ 123.58799743652344,+ 151.40399169921875+ ],+ "origin": [+ 114.92399597167969,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 125.40480041503906,+ 140.50799560546875,+ 133.08480834960938,+ 151.40399169921875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 91,+ "source_indices": [+ 91+ ],+ "raw_code": 115,+ "loose_bbox": [+ 124.42080688476562,+ 130.13999938964844,+ 133.9248046875,+ 157.37998962402344+ ],+ "tight_bbox": [+ 125.40480041503906,+ 140.50799560546875,+ 133.08480834960938,+ 151.40399169921875+ ],+ "origin": [+ 124.42080688476562,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 133.9176025390625,+ 151.23599243164062,+ 139.05360412597656,+ 151.25999450683594+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 92,+ "source_indices": [+ 92+ ],+ "raw_code": 32,+ "loose_bbox": [+ 133.9176025390625,+ 130.13999938964844,+ 139.05360412597656,+ 157.37998962402344+ ],+ "tight_bbox": [+ 133.9176025390625,+ 151.23599243164062,+ 139.05360412597656,+ 151.25999450683594+ ],+ "origin": [+ 133.9176025390625,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 139.84800720214844,+ 140.4359893798828,+ 148.99200439453125,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 93,+ "source_indices": [+ 93+ ],+ "raw_code": 101,+ "loose_bbox": [+ 139.0800018310547,+ 130.13999938964844,+ 149.3520050048828,+ 157.37998962402344+ ],+ "tight_bbox": [+ 139.84800720214844,+ 140.4359893798828,+ 148.99200439453125,+ 151.42799377441406+ ],+ "origin": [+ 139.0800018310547,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 149.77679443359375,+ 140.2919921875,+ 161.94479370117188,+ 151.25999450683594+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 94,+ "source_indices": [+ 94+ ],+ "raw_code": 110,+ "loose_bbox": [+ 149.3448028564453,+ 130.13999938964844,+ 162.13681030273438,+ 157.37998962402344+ ],+ "tight_bbox": [+ 149.77679443359375,+ 140.2919921875,+ 161.94479370117188,+ 151.25999450683594+ ],+ "origin": [+ 149.3448028564453,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 162.89761352539062,+ 140.4359893798828,+ 172.04161071777344,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 95,+ "source_indices": [+ 95+ ],+ "raw_code": 101,+ "loose_bbox": [+ 162.12962341308594,+ 130.13999938964844,+ 172.40162658691406,+ 157.37998962402344+ ],+ "tight_bbox": [+ 162.89761352539062,+ 140.4359893798828,+ 172.04161071777344,+ 151.42799377441406+ ],+ "origin": [+ 162.12960815429688,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 172.73040771484375,+ 140.22000122070312,+ 180.96240234375,+ 151.25999450683594+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 96,+ "source_indices": [+ 96+ ],+ "raw_code": 114,+ "loose_bbox": [+ 172.39442443847656,+ 130.13999938964844,+ 181.1304168701172,+ 157.37998962402344+ ],+ "tight_bbox": [+ 172.73040771484375,+ 140.22000122070312,+ 180.96240234375,+ 151.25999450683594+ ],+ "origin": [+ 172.3944091796875,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 181.4112091064453,+ 140.3159942626953,+ 192.28321838378906,+ 157.35598754882812+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 97,+ "source_indices": [+ 97+ ],+ "raw_code": 103,+ "loose_bbox": [+ 181.1232147216797,+ 130.13999938964844,+ 192.4992218017578,+ 157.37998962402344+ ],+ "tight_bbox": [+ 181.4112091064453,+ 140.3159942626953,+ 192.28321838378906,+ 157.35598754882812+ ],+ "origin": [+ 181.1232147216797,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 192.6120147705078,+ 140.55599975585938,+ 203.60400390625,+ 157.33200073242188+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 98,+ "source_indices": [+ 98+ ],+ "raw_code": 121,+ "loose_bbox": [+ 192.49200439453125,+ 130.13999938964844,+ 203.72401428222656,+ 157.37998962402344+ ],+ "tight_bbox": [+ 192.6120147705078,+ 140.55599975585938,+ 203.60400390625,+ 157.33200073242188+ ],+ "origin": [+ 192.49200439453125,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 203.71681213378906,+ 151.23599243164062,+ 208.85281372070312,+ 151.25999450683594+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 99,+ "source_indices": [+ 99+ ],+ "raw_code": 32,+ "loose_bbox": [+ 203.71681213378906,+ 130.13999938964844,+ 208.85284423828125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 203.71681213378906,+ 151.23599243164062,+ 208.85281372070312,+ 151.25999450683594+ ],+ "origin": [+ 203.71681213378906,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 209.09521484375,+ 133.40399169921875,+ 216.6312255859375,+ 151.25999450683594+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 100,+ "source_indices": [+ 100+ ],+ "raw_code": 102,+ "loose_bbox": [+ 208.87921142578125,+ 130.13999938964844,+ 216.6312255859375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 209.09521484375,+ 133.40399169921875,+ 216.6312255859375,+ 151.25999450683594+ ],+ "origin": [+ 208.87921142578125,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 216.14401245117188,+ 140.22000122070312,+ 224.3760223388672,+ 151.25999450683594+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 101,+ "source_indices": [+ 101+ ],+ "raw_code": 114,+ "loose_bbox": [+ 215.80801391601562,+ 130.13999938964844,+ 224.5440216064453,+ 157.37998962402344+ ],+ "tight_bbox": [+ 216.14401245117188,+ 140.22000122070312,+ 224.3760223388672,+ 151.25999450683594+ ],+ "origin": [+ 215.80801391601562,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 225.30482482910156,+ 140.33999633789062,+ 235.55282592773438,+ 151.37998962402344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 102,+ "source_indices": [+ 102+ ],+ "raw_code": 111,+ "loose_bbox": [+ 224.53683471679688,+ 130.13999938964844,+ 236.3208465576172,+ 157.37998962402344+ ],+ "tight_bbox": [+ 225.30482482910156,+ 140.33999633789062,+ 235.55282592773438,+ 151.37998962402344+ ],+ "origin": [+ 224.5368194580078,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 236.64962768554688,+ 140.2679901123047,+ 254.76963806152344,+ 151.25999450683594+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 103,+ "source_indices": [+ 103+ ],+ "raw_code": 109,+ "loose_bbox": [+ 236.31362915039062,+ 130.13999938964844,+ 254.93763732910156,+ 157.37998962402344+ ],+ "tight_bbox": [+ 236.64962768554688,+ 140.2679901123047,+ 254.76963806152344,+ 151.25999450683594+ ],+ "origin": [+ 236.31362915039062,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 254.930419921875,+ 151.23599243164062,+ 260.06640625,+ 151.25999450683594+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 104,+ "source_indices": [+ 104+ ],+ "raw_code": 32,+ "loose_bbox": [+ 254.930419921875,+ 130.13999938964844,+ 260.06640625,+ 157.37998962402344+ ],+ "tight_bbox": [+ 254.930419921875,+ 151.23599243164062,+ 260.06640625,+ 151.25999450683594+ ],+ "origin": [+ 254.930419921875,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 260.6688232421875,+ 138.34799194335938,+ 268.1808166503906,+ 151.45199584960938+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 105,+ "source_indices": [+ 105+ ],+ "raw_code": 116,+ "loose_bbox": [+ 260.0928039550781,+ 130.13999938964844,+ 268.58880615234375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 260.6688232421875,+ 138.34799194335938,+ 268.1808166503906,+ 151.45199584960938+ ],+ "origin": [+ 260.0928039550781,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 268.8695983886719,+ 133.42799377441406,+ 281.1575927734375,+ 151.25999450683594+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 106,+ "source_indices": [+ 106+ ],+ "raw_code": 104,+ "loose_bbox": [+ 268.5816345214844,+ 130.13999938964844,+ 281.2776184082031,+ 157.37998962402344+ ],+ "tight_bbox": [+ 268.8695983886719,+ 133.42799377441406,+ 281.1575927734375,+ 151.25999450683594+ ],+ "origin": [+ 268.58160400390625,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 282.03839111328125,+ 140.4359893798828,+ 291.1824035644531,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 107,+ "source_indices": [+ 107+ ],+ "raw_code": 101,+ "loose_bbox": [+ 281.2703857421875,+ 130.13999938964844,+ 291.54241943359375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 282.03839111328125,+ 140.4359893798828,+ 291.1824035644531,+ 151.42799377441406+ ],+ "origin": [+ 281.2703857421875,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 291.5351867675781,+ 151.23599243164062,+ 296.67120361328125,+ 151.25999450683594+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 108,+ "source_indices": [+ 108+ ],+ "raw_code": 32,+ "loose_bbox": [+ 291.5351867675781,+ 130.13999938964844,+ 296.67120361328125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 291.5351867675781,+ 151.23599243164062,+ 296.67120361328125,+ 151.25999450683594+ ],+ "origin": [+ 291.5351867675781,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 297.465576171875,+ 140.4359893798828,+ 306.6095886230469,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 109,+ "source_indices": [+ 109+ ],+ "raw_code": 101,+ "loose_bbox": [+ 296.69757080078125,+ 130.13999938964844,+ 306.9696044921875,+ 157.37998962402344+ ],+ "tight_bbox": [+ 297.465576171875,+ 140.4359893798828,+ 306.6095886230469,+ 151.42799377441406+ ],+ "origin": [+ 296.69757080078125,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 307.3943786621094,+ 140.2919921875,+ 319.5623779296875,+ 151.25999450683594+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 110,+ "source_indices": [+ 110+ ],+ "raw_code": 110,+ "loose_bbox": [+ 306.9623718261719,+ 130.13999938964844,+ 319.75439453125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 307.3943786621094,+ 140.2919921875,+ 319.5623779296875,+ 151.25999450683594+ ],+ "origin": [+ 306.9623718261719,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 319.8671875,+ 140.55599975585938,+ 330.73919677734375,+ 151.33200073242188+ ],+ "char": "v",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 111,+ "source_indices": [+ 111+ ],+ "raw_code": 118,+ "loose_bbox": [+ 319.7471923828125,+ 130.13999938964844,+ 330.76318359375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 319.8671875,+ 140.55599975585938,+ 330.73919677734375,+ 151.33200073242188+ ],+ "origin": [+ 319.7471923828125,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 331.13995361328125,+ 135.56399536132812,+ 336.9719543457031,+ 151.25999450683594+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 112,+ "source_indices": [+ 112+ ],+ "raw_code": 105,+ "loose_bbox": [+ 330.7559509277344,+ 130.13999938964844,+ 337.25994873046875,+ 157.37998962402344+ ],+ "tight_bbox": [+ 331.13995361328125,+ 135.56399536132812,+ 336.9719543457031,+ 151.25999450683594+ ],+ "origin": [+ 330.7559509277344,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 337.5887451171875,+ 140.22000122070312,+ 345.82073974609375,+ 151.25999450683594+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 113,+ "source_indices": [+ 113+ ],+ "raw_code": 114,+ "loose_bbox": [+ 337.2527770996094,+ 130.13999938964844,+ 345.98876953125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 337.5887451171875,+ 140.22000122070312,+ 345.82073974609375,+ 151.25999450683594+ ],+ "origin": [+ 337.25274658203125,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 346.7495422363281,+ 140.33999633789062,+ 356.9975280761719,+ 151.37998962402344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 114,+ "source_indices": [+ 114+ ],+ "raw_code": 111,+ "loose_bbox": [+ 345.9815368652344,+ 130.13999938964844,+ 357.76556396484375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 346.7495422363281,+ 140.33999633789062,+ 356.9975280761719,+ 151.37998962402344+ ],+ "origin": [+ 345.9815368652344,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 358.1903381347656,+ 140.2919921875,+ 370.35833740234375,+ 151.25999450683594+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 115,+ "source_indices": [+ 115+ ],+ "raw_code": 110,+ "loose_bbox": [+ 357.7583312988281,+ 130.13999938964844,+ 370.55035400390625,+ 157.37998962402344+ ],+ "tight_bbox": [+ 358.1903381347656,+ 140.2919921875,+ 370.35833740234375,+ 151.25999450683594+ ],+ "origin": [+ 357.7583312988281,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 370.8791198730469,+ 140.2679901123047,+ 388.9991455078125,+ 151.25999450683594+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 116,+ "source_indices": [+ 116+ ],+ "raw_code": 109,+ "loose_bbox": [+ 370.5431213378906,+ 130.13999938964844,+ 389.1671142578125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 370.8791198730469,+ 140.2679901123047,+ 388.9991455078125,+ 151.25999450683594+ ],+ "origin": [+ 370.5431213378906,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 389.92791748046875,+ 140.4359893798828,+ 399.0719299316406,+ 151.42799377441406+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 117,+ "source_indices": [+ 117+ ],+ "raw_code": 101,+ "loose_bbox": [+ 389.159912109375,+ 130.13999938964844,+ 399.43194580078125,+ 157.37998962402344+ ],+ "tight_bbox": [+ 389.92791748046875,+ 140.4359893798828,+ 399.0719299316406,+ 151.42799377441406+ ],+ "origin": [+ 389.159912109375,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 399.8567199707031,+ 140.2919921875,+ 412.02471923828125,+ 151.25999450683594+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 118,+ "source_indices": [+ 118+ ],+ "raw_code": 110,+ "loose_bbox": [+ 399.4247131347656,+ 130.13999938964844,+ 412.21673583984375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 399.8567199707031,+ 140.2919921875,+ 412.02471923828125,+ 151.25999450683594+ ],+ "origin": [+ 399.4247131347656,+ 151.25999450683594+ ]+ },+ {+ "bbox": [+ 412.7855224609375,+ 138.34799194335938,+ 420.2975158691406,+ 151.45199584960938+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 119,+ "source_indices": [+ 119+ ],+ "raw_code": 116,+ "loose_bbox": [+ 412.2095031738281,+ 130.13999938964844,+ 420.70550537109375,+ 157.37998962402344+ ],+ "tight_bbox": [+ 412.7855224609375,+ 138.34799194335938,+ 420.2975158691406,+ 151.45199584960938+ ],+ "origin": [+ 412.2095031738281,+ 151.25999450683594+ ]+ }+ ],+ "tight_bboxes": {+ "85": [+ 60.167999267578125,+ 133.42799377441406,+ 72.45600128173828,+ 151.25999450683594+ ],+ "86": [+ 73.62480163574219,+ 140.57998657226562,+ 82.81680297851562,+ 151.54798889160156+ ],+ "87": [+ 83.48159790039062,+ 140.22000122070312,+ 91.7136001586914,+ 151.25999450683594+ ],+ "88": [+ 92.306396484375,+ 140.2919921875,+ 104.47439575195312,+ 151.25999450683594+ ],+ "89": [+ 105.42720031738281,+ 140.4359893798828,+ 114.57119750976562,+ 151.42799377441406+ ],+ "90": [+ 115.90799713134766,+ 140.50799560546875,+ 123.58799743652344,+ 151.40399169921875+ ],+ "91": [+ 125.40480041503906,+ 140.50799560546875,+ 133.08480834960938,+ 151.40399169921875+ ],+ "92": [+ 133.9176025390625,+ 151.23599243164062,+ 139.05360412597656,+ 151.25999450683594+ ],+ "93": [+ 139.84800720214844,+ 140.4359893798828,+ 148.99200439453125,+ 151.42799377441406+ ],+ "94": [+ 149.77679443359375,+ 140.2919921875,+ 161.94479370117188,+ 151.25999450683594+ ],+ "95": [+ 162.89761352539062,+ 140.4359893798828,+ 172.04161071777344,+ 151.42799377441406+ ],+ "96": [+ 172.73040771484375,+ 140.22000122070312,+ 180.96240234375,+ 151.25999450683594+ ],+ "97": [+ 181.4112091064453,+ 140.3159942626953,+ 192.28321838378906,+ 157.35598754882812+ ],+ "98": [+ 192.6120147705078,+ 140.55599975585938,+ 203.60400390625,+ 157.33200073242188+ ],+ "99": [+ 203.71681213378906,+ 151.23599243164062,+ 208.85281372070312,+ 151.25999450683594+ ],+ "100": [+ 209.09521484375,+ 133.40399169921875,+ 216.6312255859375,+ 151.25999450683594+ ],+ "101": [+ 216.14401245117188,+ 140.22000122070312,+ 224.3760223388672,+ 151.25999450683594+ ],+ "102": [+ 225.30482482910156,+ 140.33999633789062,+ 235.55282592773438,+ 151.37998962402344+ ],+ "103": [+ 236.64962768554688,+ 140.2679901123047,+ 254.76963806152344,+ 151.25999450683594+ ],+ "104": [+ 254.930419921875,+ 151.23599243164062,+ 260.06640625,+ 151.25999450683594+ ],+ "105": [+ 260.6688232421875,+ 138.34799194335938,+ 268.1808166503906,+ 151.45199584960938+ ],+ "106": [+ 268.8695983886719,+ 133.42799377441406,+ 281.1575927734375,+ 151.25999450683594+ ],+ "107": [+ 282.03839111328125,+ 140.4359893798828,+ 291.1824035644531,+ 151.42799377441406+ ],+ "108": [+ 291.5351867675781,+ 151.23599243164062,+ 296.67120361328125,+ 151.25999450683594+ ],+ "109": [+ 297.465576171875,+ 140.4359893798828,+ 306.6095886230469,+ 151.42799377441406+ ],+ "110": [+ 307.3943786621094,+ 140.2919921875,+ 319.5623779296875,+ 151.25999450683594+ ],+ "111": [+ 319.8671875,+ 140.55599975585938,+ 330.73919677734375,+ 151.33200073242188+ ],+ "112": [+ 331.13995361328125,+ 135.56399536132812,+ 336.9719543457031,+ 151.25999450683594+ ],+ "113": [+ 337.5887451171875,+ 140.22000122070312,+ 345.82073974609375,+ 151.25999450683594+ ],+ "114": [+ 346.7495422363281,+ 140.33999633789062,+ 356.9975280761719,+ 151.37998962402344+ ],+ "115": [+ 358.1903381347656,+ 140.2919921875,+ 370.35833740234375,+ 151.25999450683594+ ],+ "116": [+ 370.8791198730469,+ 140.2679901123047,+ 388.9991455078125,+ 151.25999450683594+ ],+ "117": [+ 389.92791748046875,+ 140.4359893798828,+ 399.0719299316406,+ 151.42799377441406+ ],+ "118": [+ 399.8567199707031,+ 140.2919921875,+ 412.02471923828125,+ 151.25999450683594+ ],+ "119": [+ 412.7855224609375,+ 138.34799194335938,+ 420.2975158691406,+ 151.45199584960938+ ]+ },+ "origins": {+ "85": [+ 59.880001068115234,+ 151.25999450683594+ ],+ "86": [+ 72.56880187988281,+ 151.25999450683594+ ],+ "87": [+ 83.14559936523438,+ 151.25999450683594+ ],+ "88": [+ 91.87440490722656,+ 151.25999450683594+ ],+ "89": [+ 104.65919494628906,+ 151.25999450683594+ ],+ "90": [+ 114.92399597167969,+ 151.25999450683594+ ],+ "91": [+ 124.42080688476562,+ 151.25999450683594+ ],+ "92": [+ 133.9176025390625,+ 151.25999450683594+ ],+ "93": [+ 139.0800018310547,+ 151.25999450683594+ ],+ "94": [+ 149.3448028564453,+ 151.25999450683594+ ],+ "95": [+ 162.12960815429688,+ 151.25999450683594+ ],+ "96": [+ 172.3944091796875,+ 151.25999450683594+ ],+ "97": [+ 181.1232147216797,+ 151.25999450683594+ ],+ "98": [+ 192.49200439453125,+ 151.25999450683594+ ],+ "99": [+ 203.71681213378906,+ 151.25999450683594+ ],+ "100": [+ 208.87921142578125,+ 151.25999450683594+ ],+ "101": [+ 215.80801391601562,+ 151.25999450683594+ ],+ "102": [+ 224.5368194580078,+ 151.25999450683594+ ],+ "103": [+ 236.31362915039062,+ 151.25999450683594+ ],+ "104": [+ 254.930419921875,+ 151.25999450683594+ ],+ "105": [+ 260.0928039550781,+ 151.25999450683594+ ],+ "106": [+ 268.58160400390625,+ 151.25999450683594+ ],+ "107": [+ 281.2703857421875,+ 151.25999450683594+ ],+ "108": [+ 291.5351867675781,+ 151.25999450683594+ ],+ "109": [+ 296.69757080078125,+ 151.25999450683594+ ],+ "110": [+ 306.9623718261719,+ 151.25999450683594+ ],+ "111": [+ 319.7471923828125,+ 151.25999450683594+ ],+ "112": [+ 330.7559509277344,+ 151.25999450683594+ ],+ "113": [+ 337.25274658203125,+ 151.25999450683594+ ],+ "114": [+ 345.9815368652344,+ 151.25999450683594+ ],+ "115": [+ 357.7583312988281,+ 151.25999450683594+ ],+ "116": [+ 370.5431213378906,+ 151.25999450683594+ ],+ "117": [+ 389.159912109375,+ 151.25999450683594+ ],+ "118": [+ 399.4247131347656,+ 151.25999450683594+ ],+ "119": [+ 412.2095031738281,+ 151.25999450683594+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 412.2095031738281,+ 151.61399841308594,+ 412.2095031738281,+ 151.61399841308594+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 120,+ "source_indices": [+ 120+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 412.2095031738281,+ 151.61399841308594+ ]+ },+ {+ "bbox": [+ 412.2095031738281,+ 151.61399841308594,+ 412.2095031738281,+ 151.61399841308594+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 121,+ "source_indices": [+ 121+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 412.2095031738281,+ 151.61399841308594+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "120": [+ 412.2095031738281,+ 151.61399841308594+ ],+ "121": [+ 412.2095031738281,+ 151.61399841308594+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 61.39200210571289,+ 195.09597778320312,+ 67.51200103759766,+ 198.19198608398438+ ],+ "char": "-",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 122,+ "source_indices": [+ 122+ ],+ "raw_code": 45,+ "loose_bbox": [+ 60.36000061035156,+ 181.8000030517578,+ 68.54399871826172,+ 209.04000854492188+ ],+ "tight_bbox": [+ 61.39200210571289,+ 195.09597778320312,+ 67.51200103759766,+ 198.19198608398438+ ],+ "origin": [+ 60.36000061035156,+ 202.91998291015625+ ]+ }+ ],+ "tight_bboxes": {+ "122": [+ 61.39200210571289,+ 195.09597778320312,+ 67.51200103759766,+ 198.19198608398438+ ]+ },+ "origins": {+ "122": [+ 60.36000061035156,+ 202.91998291015625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 73.68479919433594,+ 202.91998291015625,+ 73.68479919433594,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 123,+ "source_indices": [+ 123+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 73.68479919433594,+ 202.91998291015625+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "123": [+ 73.68479919433594,+ 202.91998291015625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 74.62080383300781,+ 187.07998657226562,+ 86.30879974365234,+ 202.91998291015625+ ],+ "char": "P",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 124,+ "source_indices": [+ 124+ ],+ "raw_code": 80,+ "loose_bbox": [+ 73.68479919433594,+ 181.8000030517578,+ 86.93280029296875,+ 209.04000854492188+ ],+ "tight_bbox": [+ 74.62080383300781,+ 187.07998657226562,+ 86.30879974365234,+ 202.91998291015625+ ],+ "origin": [+ 73.68479919433594,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 87.11759948730469,+ 185.20797729492188,+ 93.2136001586914,+ 202.91998291015625+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 125,+ "source_indices": [+ 125+ ],+ "raw_code": 108,+ "loose_bbox": [+ 86.94960021972656,+ 181.8000030517578,+ 93.40560150146484,+ 209.04000854492188+ ],+ "tight_bbox": [+ 87.11759948730469,+ 185.20797729492188,+ 93.2136001586914,+ 202.91998291015625+ ],+ "origin": [+ 86.94960021972656,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 94.46160125732422,+ 192.239990234375,+ 103.65360260009766,+ 203.20797729492188+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 126,+ "source_indices": [+ 126+ ],+ "raw_code": 97,+ "loose_bbox": [+ 93.40560150146484,+ 181.8000030517578,+ 103.9896011352539,+ 209.04000854492188+ ],+ "tight_bbox": [+ 94.46160125732422,+ 192.239990234375,+ 103.65360260009766,+ 203.20797729492188+ ],+ "origin": [+ 93.40560150146484,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 104.42160034179688,+ 191.9519805908203,+ 116.589599609375,+ 202.91998291015625+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 127,+ "source_indices": [+ 127+ ],+ "raw_code": 110,+ "loose_bbox": [+ 103.9896011352539,+ 181.8000030517578,+ 116.78160095214844,+ 209.04000854492188+ ],+ "tight_bbox": [+ 104.42160034179688,+ 191.9519805908203,+ 116.589599609375,+ 202.91998291015625+ ],+ "origin": [+ 103.9896011352539,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 117.35759735107422,+ 190.0079803466797,+ 124.86959838867188,+ 203.1119842529297+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 128,+ "source_indices": [+ 128+ ],+ "raw_code": 116,+ "loose_bbox": [+ 116.78160095214844,+ 181.8000030517578,+ 125.27760314941406,+ 209.04000854492188+ ],+ "tight_bbox": [+ 117.35759735107422,+ 190.0079803466797,+ 124.86959838867188,+ 203.1119842529297+ ],+ "origin": [+ 116.78160095214844,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 126.2615966796875,+ 192.16798400878906,+ 133.9416046142578,+ 203.06398010253906+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 129,+ "source_indices": [+ 129+ ],+ "raw_code": 115,+ "loose_bbox": [+ 125.27760314941406,+ 181.8000030517578,+ 134.78160095214844,+ 209.04000854492188+ ],+ "tight_bbox": [+ 126.2615966796875,+ 192.16798400878906,+ 133.9416046142578,+ 203.06398010253906+ ],+ "origin": [+ 125.27760314941406,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 134.78160095214844,+ 202.89598083496094,+ 139.9176025390625,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 130,+ "source_indices": [+ 130+ ],+ "raw_code": 32,+ "loose_bbox": [+ 134.78160095214844,+ 181.8000030517578,+ 139.9176025390625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 134.78160095214844,+ 202.89598083496094,+ 139.9176025390625,+ 202.91998291015625+ ],+ "origin": [+ 134.78160095214844,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 140.71200561523438,+ 185.08798217773438,+ 152.8560028076172,+ 203.2799835205078+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 131,+ "source_indices": [+ 131+ ],+ "raw_code": 100,+ "loose_bbox": [+ 139.94400024414062,+ 181.8000030517578,+ 152.8560028076172,+ 209.04000854492188+ ],+ "tight_bbox": [+ 140.71200561523438,+ 185.08798217773438,+ 152.8560028076172,+ 203.2799835205078+ ],+ "origin": [+ 139.94400024414062,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 153.50399780273438,+ 191.99998474121094,+ 163.7519989013672,+ 203.03997802734375+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 132,+ "source_indices": [+ 132+ ],+ "raw_code": 111,+ "loose_bbox": [+ 152.73599243164062,+ 181.8000030517578,+ 164.51998901367188,+ 209.04000854492188+ ],+ "tight_bbox": [+ 153.50399780273438,+ 191.99998474121094,+ 163.7519989013672,+ 203.03997802734375+ ],+ "origin": [+ 152.73599243164062,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 164.52000427246094,+ 202.89598083496094,+ 169.656005859375,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 133,+ "source_indices": [+ 133+ ],+ "raw_code": 32,+ "loose_bbox": [+ 164.52000427246094,+ 181.8000030517578,+ 169.656005859375,+ 209.04000854492188+ ],+ "tight_bbox": [+ 164.52000427246094,+ 202.89598083496094,+ 169.656005859375,+ 202.91998291015625+ ],+ "origin": [+ 164.52000427246094,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 170.06640625,+ 187.22398376464844,+ 175.89840698242188,+ 202.91998291015625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 134,+ "source_indices": [+ 134+ ],+ "raw_code": 105,+ "loose_bbox": [+ 169.68240356445312,+ 181.8000030517578,+ 176.1864013671875,+ 209.04000854492188+ ],+ "tight_bbox": [+ 170.06640625,+ 187.22398376464844,+ 175.89840698242188,+ 202.91998291015625+ ],+ "origin": [+ 169.68240356445312,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 176.76242065429688,+ 190.0079803466797,+ 184.2744140625,+ 203.1119842529297+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 135,+ "source_indices": [+ 135+ ],+ "raw_code": 116,+ "loose_bbox": [+ 176.1864013671875,+ 181.8000030517578,+ 184.68240356445312,+ 209.04000854492188+ ],+ "tight_bbox": [+ 176.76242065429688,+ 190.0079803466797,+ 184.2744140625,+ 203.1119842529297+ ],+ "origin": [+ 176.1864013671875,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 184.68240356445312,+ 202.89598083496094,+ 189.81842041015625,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 136,+ "source_indices": [+ 136+ ],+ "raw_code": 32,+ "loose_bbox": [+ 184.68240356445312,+ 181.8000030517578,+ 189.81842041015625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 184.68240356445312,+ 202.89598083496094,+ 189.81842041015625,+ 202.91998291015625+ ],+ "origin": [+ 184.68240356445312,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 189.94082641601562,+ 185.18399047851562,+ 201.82081604003906,+ 203.6639862060547+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 137,+ "source_indices": [+ 137+ ],+ "raw_code": 98,+ "loose_bbox": [+ 189.84481811523438,+ 181.8000030517578,+ 202.5888214111328,+ 209.04000854492188+ ],+ "tight_bbox": [+ 189.94082641601562,+ 185.18399047851562,+ 201.82081604003906,+ 203.6639862060547+ ],+ "origin": [+ 189.84481811523438,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 202.7088165283203,+ 192.2159881591797,+ 213.70082092285156,+ 208.9919891357422+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 138,+ "source_indices": [+ 138+ ],+ "raw_code": 121,+ "loose_bbox": [+ 202.5888214111328,+ 181.8000030517578,+ 213.82081604003906,+ 209.04000854492188+ ],+ "tight_bbox": [+ 202.7088165283203,+ 192.2159881591797,+ 213.70082092285156,+ 208.9919891357422+ ],+ "origin": [+ 202.5888214111328,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 213.82081604003906,+ 202.89598083496094,+ 218.9568328857422,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 139,+ "source_indices": [+ 139+ ],+ "raw_code": 32,+ "loose_bbox": [+ 213.82081604003906,+ 181.8000030517578,+ 218.9568328857422,+ 209.04000854492188+ ],+ "tight_bbox": [+ 213.82081604003906,+ 202.89598083496094,+ 218.9568328857422,+ 202.91998291015625+ ],+ "origin": [+ 213.82081604003906,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 220.0392303466797,+ 192.239990234375,+ 229.23123168945312,+ 203.20797729492188+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 140,+ "source_indices": [+ 140+ ],+ "raw_code": 97,+ "loose_bbox": [+ 218.9832305908203,+ 181.8000030517578,+ 229.56724548339844,+ 209.04000854492188+ ],+ "tight_bbox": [+ 220.0392303466797,+ 192.239990234375,+ 229.23123168945312,+ 203.20797729492188+ ],+ "origin": [+ 218.9832305908203,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 229.66322326660156,+ 185.18399047851562,+ 241.54322814941406,+ 203.6639862060547+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 141,+ "source_indices": [+ 141+ ],+ "raw_code": 98,+ "loose_bbox": [+ 229.56724548339844,+ 181.8000030517578,+ 242.3112335205078,+ 209.04000854492188+ ],+ "tight_bbox": [+ 229.66322326660156,+ 185.18399047851562,+ 241.54322814941406,+ 203.6639862060547+ ],+ "origin": [+ 229.56723022460938,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 243.29522705078125,+ 192.16798400878906,+ 250.97523498535156,+ 203.06398010253906+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 142,+ "source_indices": [+ 142+ ],+ "raw_code": 115,+ "loose_bbox": [+ 242.3112335205078,+ 181.8000030517578,+ 251.8152313232422,+ 209.04000854492188+ ],+ "tight_bbox": [+ 243.29522705078125,+ 192.16798400878906,+ 250.97523498535156,+ 203.06398010253906+ ],+ "origin": [+ 242.3112335205078,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 252.58323669433594,+ 191.99998474121094,+ 262.83123779296875,+ 203.03997802734375+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 143,+ "source_indices": [+ 143+ ],+ "raw_code": 111,+ "loose_bbox": [+ 251.8152313232422,+ 181.8000030517578,+ 263.5992431640625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 252.58323669433594,+ 191.99998474121094,+ 262.83123779296875,+ 203.03997802734375+ ],+ "origin": [+ 251.8152313232422,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 263.93524169921875,+ 191.87998962402344,+ 272.167236328125,+ 202.91998291015625+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 144,+ "source_indices": [+ 144+ ],+ "raw_code": 114,+ "loose_bbox": [+ 263.5992431640625,+ 181.8000030517578,+ 272.33526611328125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 263.93524169921875,+ 191.87998962402344,+ 272.167236328125,+ 202.91998291015625+ ],+ "origin": [+ 263.5992431640625,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 272.43121337890625,+ 185.18399047851562,+ 284.31121826171875,+ 203.6639862060547+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 145,+ "source_indices": [+ 145+ ],+ "raw_code": 98,+ "loose_bbox": [+ 272.335205078125,+ 181.8000030517578,+ 285.0792236328125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 272.43121337890625,+ 185.18399047851562,+ 284.31121826171875,+ 203.6639862060547+ ],+ "origin": [+ 272.335205078125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 285.4632263183594,+ 187.22398376464844,+ 291.29522705078125,+ 202.91998291015625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 146,+ "source_indices": [+ 146+ ],+ "raw_code": 105,+ "loose_bbox": [+ 285.0792236328125,+ 181.8000030517578,+ 291.583251953125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 285.4632263183594,+ 187.22398376464844,+ 291.29522705078125,+ 202.91998291015625+ ],+ "origin": [+ 285.0792236328125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 292.01519775390625,+ 191.9519805908203,+ 304.1832275390625,+ 202.91998291015625+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 147,+ "source_indices": [+ 147+ ],+ "raw_code": 110,+ "loose_bbox": [+ 291.583251953125,+ 181.8000030517578,+ 304.375244140625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 292.01519775390625,+ 191.9519805908203,+ 304.1832275390625,+ 202.91998291015625+ ],+ "origin": [+ 291.583251953125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 304.6632080078125,+ 191.97598266601562,+ 315.53521728515625,+ 209.01597595214844+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 148,+ "source_indices": [+ 148+ ],+ "raw_code": 103,+ "loose_bbox": [+ 304.375244140625,+ 181.8000030517578,+ 315.7512512207031,+ 209.04000854492188+ ],+ "tight_bbox": [+ 304.6632080078125,+ 191.97598266601562,+ 315.53521728515625,+ 209.01597595214844+ ],+ "origin": [+ 304.375244140625,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 315.751220703125,+ 202.89598083496094,+ 320.88720703125,+ 202.91998291015625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 149,+ "source_indices": [+ 149+ ],+ "raw_code": 32,+ "loose_bbox": [+ 315.751220703125,+ 181.8000030517578,+ 320.88720703125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 315.751220703125,+ 202.89598083496094,+ 320.88720703125,+ 202.91998291015625+ ],+ "origin": [+ 315.751220703125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 321.89764404296875,+ 192.16798400878906,+ 329.57763671875,+ 203.06398010253906+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 150,+ "source_indices": [+ 150+ ],+ "raw_code": 115,+ "loose_bbox": [+ 320.91363525390625,+ 181.8000030517578,+ 330.4176025390625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 321.89764404296875,+ 192.16798400878906,+ 329.57763671875,+ 203.06398010253906+ ],+ "origin": [+ 320.91363525390625,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 330.4896240234375,+ 192.02398681640625,+ 342.20159912109375,+ 203.20797729492188+ ],+ "char": "u",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 151,+ "source_indices": [+ 151+ ],+ "raw_code": 117,+ "loose_bbox": [+ 330.4176025390625,+ 181.8000030517578,+ 343.11358642578125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 330.4896240234375,+ 192.02398681640625,+ 342.20159912109375,+ 203.20797729492188+ ],+ "origin": [+ 330.4176025390625,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 343.54559326171875,+ 191.9519805908203,+ 355.713623046875,+ 202.91998291015625+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 152,+ "source_indices": [+ 152+ ],+ "raw_code": 110,+ "loose_bbox": [+ 343.11358642578125,+ 181.8000030517578,+ 355.90557861328125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 343.54559326171875,+ 191.9519805908203,+ 355.713623046875,+ 202.91998291015625+ ],+ "origin": [+ 343.11358642578125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 356.0736083984375,+ 185.20797729492188,+ 362.16961669921875,+ 202.91998291015625+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 153,+ "source_indices": [+ 153+ ],+ "raw_code": 108,+ "loose_bbox": [+ 355.9056396484375,+ 181.8000030517578,+ 362.36163330078125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 356.0736083984375,+ 185.20797729492188,+ 362.16961669921875,+ 202.91998291015625+ ],+ "origin": [+ 355.9056396484375,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 362.74560546875,+ 187.22398376464844,+ 368.57763671875,+ 202.91998291015625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 154,+ "source_indices": [+ 154+ ],+ "raw_code": 105,+ "loose_bbox": [+ 362.36163330078125,+ 181.8000030517578,+ 368.86566162109375,+ 209.04000854492188+ ],+ "tight_bbox": [+ 362.74560546875,+ 187.22398376464844,+ 368.57763671875,+ 202.91998291015625+ ],+ "origin": [+ 362.36163330078125,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 369.15362548828125,+ 191.97598266601562,+ 380.025634765625,+ 209.01597595214844+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 155,+ "source_indices": [+ 155+ ],+ "raw_code": 103,+ "loose_bbox": [+ 368.8656005859375,+ 181.8000030517578,+ 380.2415771484375,+ 209.04000854492188+ ],+ "tight_bbox": [+ 369.15362548828125,+ 191.97598266601562,+ 380.025634765625,+ 209.01597595214844+ ],+ "origin": [+ 368.8656005859375,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 380.52960205078125,+ 185.08798217773438,+ 392.817626953125,+ 202.91998291015625+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 156,+ "source_indices": [+ 156+ ],+ "raw_code": 104,+ "loose_bbox": [+ 380.24163818359375,+ 181.8000030517578,+ 392.9376220703125,+ 209.04000854492188+ ],+ "tight_bbox": [+ 380.52960205078125,+ 185.08798217773438,+ 392.817626953125,+ 202.91998291015625+ ],+ "origin": [+ 380.24163818359375,+ 202.91998291015625+ ]+ },+ {+ "bbox": [+ 393.51361083984375,+ 190.0079803466797,+ 401.025634765625,+ 203.1119842529297+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 157,+ "source_indices": [+ 157+ ],+ "raw_code": 116,+ "loose_bbox": [+ 392.9376220703125,+ 181.8000030517578,+ 401.43365478515625,+ 209.04000854492188+ ],+ "tight_bbox": [+ 393.51361083984375,+ 190.0079803466797,+ 401.025634765625,+ 203.1119842529297+ ],+ "origin": [+ 392.9376220703125,+ 202.91998291015625+ ]+ }+ ],+ "tight_bboxes": {+ "124": [+ 74.62080383300781,+ 187.07998657226562,+ 86.30879974365234,+ 202.91998291015625+ ],+ "125": [+ 87.11759948730469,+ 185.20797729492188,+ 93.2136001586914,+ 202.91998291015625+ ],+ "126": [+ 94.46160125732422,+ 192.239990234375,+ 103.65360260009766,+ 203.20797729492188+ ],+ "127": [+ 104.42160034179688,+ 191.9519805908203,+ 116.589599609375,+ 202.91998291015625+ ],+ "128": [+ 117.35759735107422,+ 190.0079803466797,+ 124.86959838867188,+ 203.1119842529297+ ],+ "129": [+ 126.2615966796875,+ 192.16798400878906,+ 133.9416046142578,+ 203.06398010253906+ ],+ "130": [+ 134.78160095214844,+ 202.89598083496094,+ 139.9176025390625,+ 202.91998291015625+ ],+ "131": [+ 140.71200561523438,+ 185.08798217773438,+ 152.8560028076172,+ 203.2799835205078+ ],+ "132": [+ 153.50399780273438,+ 191.99998474121094,+ 163.7519989013672,+ 203.03997802734375+ ],+ "133": [+ 164.52000427246094,+ 202.89598083496094,+ 169.656005859375,+ 202.91998291015625+ ],+ "134": [+ 170.06640625,+ 187.22398376464844,+ 175.89840698242188,+ 202.91998291015625+ ],+ "135": [+ 176.76242065429688,+ 190.0079803466797,+ 184.2744140625,+ 203.1119842529297+ ],+ "136": [+ 184.68240356445312,+ 202.89598083496094,+ 189.81842041015625,+ 202.91998291015625+ ],+ "137": [+ 189.94082641601562,+ 185.18399047851562,+ 201.82081604003906,+ 203.6639862060547+ ],+ "138": [+ 202.7088165283203,+ 192.2159881591797,+ 213.70082092285156,+ 208.9919891357422+ ],+ "139": [+ 213.82081604003906,+ 202.89598083496094,+ 218.9568328857422,+ 202.91998291015625+ ],+ "140": [+ 220.0392303466797,+ 192.239990234375,+ 229.23123168945312,+ 203.20797729492188+ ],+ "141": [+ 229.66322326660156,+ 185.18399047851562,+ 241.54322814941406,+ 203.6639862060547+ ],+ "142": [+ 243.29522705078125,+ 192.16798400878906,+ 250.97523498535156,+ 203.06398010253906+ ],+ "143": [+ 252.58323669433594,+ 191.99998474121094,+ 262.83123779296875,+ 203.03997802734375+ ],+ "144": [+ 263.93524169921875,+ 191.87998962402344,+ 272.167236328125,+ 202.91998291015625+ ],+ "145": [+ 272.43121337890625,+ 185.18399047851562,+ 284.31121826171875,+ 203.6639862060547+ ],+ "146": [+ 285.4632263183594,+ 187.22398376464844,+ 291.29522705078125,+ 202.91998291015625+ ],+ "147": [+ 292.01519775390625,+ 191.9519805908203,+ 304.1832275390625,+ 202.91998291015625+ ],+ "148": [+ 304.6632080078125,+ 191.97598266601562,+ 315.53521728515625,+ 209.01597595214844+ ],+ "149": [+ 315.751220703125,+ 202.89598083496094,+ 320.88720703125,+ 202.91998291015625+ ],+ "150": [+ 321.89764404296875,+ 192.16798400878906,+ 329.57763671875,+ 203.06398010253906+ ],+ "151": [+ 330.4896240234375,+ 192.02398681640625,+ 342.20159912109375,+ 203.20797729492188+ ],+ "152": [+ 343.54559326171875,+ 191.9519805908203,+ 355.713623046875,+ 202.91998291015625+ ],+ "153": [+ 356.0736083984375,+ 185.20797729492188,+ 362.16961669921875,+ 202.91998291015625+ ],+ "154": [+ 362.74560546875,+ 187.22398376464844,+ 368.57763671875,+ 202.91998291015625+ ],+ "155": [+ 369.15362548828125,+ 191.97598266601562,+ 380.025634765625,+ 209.01597595214844+ ],+ "156": [+ 380.52960205078125,+ 185.08798217773438,+ 392.817626953125,+ 202.91998291015625+ ],+ "157": [+ 393.51361083984375,+ 190.0079803466797,+ 401.025634765625,+ 203.1119842529297+ ]+ },+ "origins": {+ "124": [+ 73.68479919433594,+ 202.91998291015625+ ],+ "125": [+ 86.94960021972656,+ 202.91998291015625+ ],+ "126": [+ 93.40560150146484,+ 202.91998291015625+ ],+ "127": [+ 103.9896011352539,+ 202.91998291015625+ ],+ "128": [+ 116.78160095214844,+ 202.91998291015625+ ],+ "129": [+ 125.27760314941406,+ 202.91998291015625+ ],+ "130": [+ 134.78160095214844,+ 202.91998291015625+ ],+ "131": [+ 139.94400024414062,+ 202.91998291015625+ ],+ "132": [+ 152.73599243164062,+ 202.91998291015625+ ],+ "133": [+ 164.52000427246094,+ 202.91998291015625+ ],+ "134": [+ 169.68240356445312,+ 202.91998291015625+ ],+ "135": [+ 176.1864013671875,+ 202.91998291015625+ ],+ "136": [+ 184.68240356445312,+ 202.91998291015625+ ],+ "137": [+ 189.84481811523438,+ 202.91998291015625+ ],+ "138": [+ 202.5888214111328,+ 202.91998291015625+ ],+ "139": [+ 213.82081604003906,+ 202.91998291015625+ ],+ "140": [+ 218.9832305908203,+ 202.91998291015625+ ],+ "141": [+ 229.56723022460938,+ 202.91998291015625+ ],+ "142": [+ 242.3112335205078,+ 202.91998291015625+ ],+ "143": [+ 251.8152313232422,+ 202.91998291015625+ ],+ "144": [+ 263.5992431640625,+ 202.91998291015625+ ],+ "145": [+ 272.335205078125,+ 202.91998291015625+ ],+ "146": [+ 285.0792236328125,+ 202.91998291015625+ ],+ "147": [+ 291.583251953125,+ 202.91998291015625+ ],+ "148": [+ 304.375244140625,+ 202.91998291015625+ ],+ "149": [+ 315.751220703125,+ 202.91998291015625+ ],+ "150": [+ 320.91363525390625,+ 202.91998291015625+ ],+ "151": [+ 330.4176025390625,+ 202.91998291015625+ ],+ "152": [+ 343.11358642578125,+ 202.91998291015625+ ],+ "153": [+ 355.9056396484375,+ 202.91998291015625+ ],+ "154": [+ 362.36163330078125,+ 202.91998291015625+ ],+ "155": [+ 368.8656005859375,+ 202.91998291015625+ ],+ "156": [+ 380.24163818359375,+ 202.91998291015625+ ],+ "157": [+ 392.9376220703125,+ 202.91998291015625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 392.9376220703125,+ 203.27398681640625,+ 392.9376220703125,+ 203.27398681640625+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 158,+ "source_indices": [+ 158+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 392.9376220703125,+ 203.27398681640625+ ]+ },+ {+ "bbox": [+ 392.9376220703125,+ 203.27398681640625,+ 392.9376220703125,+ 203.27398681640625+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 159,+ "source_indices": [+ 159+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 392.9376220703125,+ 203.27398681640625+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "158": [+ 392.9376220703125,+ 203.27398681640625+ ],+ "159": [+ 392.9376220703125,+ 203.27398681640625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 63.31200408935547,+ 246.69598388671875,+ 69.4320068359375,+ 249.7919921875+ ],+ "char": "-",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 160,+ "source_indices": [+ 160+ ],+ "raw_code": 45,+ "loose_bbox": [+ 62.28000259399414,+ 233.39999389648438,+ 70.46400451660156,+ 260.6399841308594+ ],+ "tight_bbox": [+ 63.31200408935547,+ 246.69598388671875,+ 69.4320068359375,+ 249.7919921875+ ],+ "origin": [+ 62.28000259399414,+ 254.51998901367188+ ]+ }+ ],+ "tight_bboxes": {+ "160": [+ 63.31200408935547,+ 246.69598388671875,+ 69.4320068359375,+ 249.7919921875+ ]+ },+ "origins": {+ "160": [+ 62.28000259399414,+ 254.51998901367188+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 75.60480499267578,+ 254.51998901367188,+ 75.60480499267578,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 161,+ "source_indices": [+ 161+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 75.60480499267578,+ 254.51998901367188+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "161": [+ 75.60480499267578,+ 254.51998901367188+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 75.72480010986328,+ 238.583984375,+ 101.50080108642578,+ 254.75999450683594+ ],+ "char": "W",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 162,+ "source_indices": [+ 162+ ],+ "raw_code": 87,+ "loose_bbox": [+ 75.60480499267578,+ 233.39999389648438,+ 101.54881286621094,+ 260.6399841308594+ ],+ "tight_bbox": [+ 75.72480010986328,+ 238.583984375,+ 101.50080108642578,+ 254.75999450683594+ ],+ "origin": [+ 75.60480499267578,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 102.2904052734375,+ 243.69598388671875,+ 111.43440246582031,+ 254.68798828125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 163,+ "source_indices": [+ 163+ ],+ "raw_code": 101,+ "loose_bbox": [+ 101.52239990234375,+ 233.39999389648438,+ 111.79440307617188,+ 260.6399841308594+ ],+ "tight_bbox": [+ 102.2904052734375,+ 243.69598388671875,+ 111.43440246582031,+ 254.68798828125+ ],+ "origin": [+ 101.52239990234375,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 111.78480529785156,+ 254.49598693847656,+ 116.92080688476562,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 164,+ "source_indices": [+ 164+ ],+ "raw_code": 32,+ "loose_bbox": [+ 111.78480529785156,+ 233.39999389648438,+ 116.92080688476562,+ 260.6399841308594+ ],+ "tight_bbox": [+ 111.78480529785156,+ 254.49598693847656,+ 116.92080688476562,+ 254.51998901367188+ ],+ "origin": [+ 111.78480529785156,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 117.69120788574219,+ 236.68798828125,+ 129.835205078125,+ 254.87998962402344+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 165,+ "source_indices": [+ 165+ ],+ "raw_code": 100,+ "loose_bbox": [+ 116.92320251464844,+ 233.39999389648438,+ 129.835205078125,+ 260.6399841308594+ ],+ "tight_bbox": [+ 117.69120788574219,+ 236.68798828125,+ 129.835205078125,+ 254.87998962402344+ ],+ "origin": [+ 116.92320251464844,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 130.47360229492188,+ 243.59999084472656,+ 140.7216033935547,+ 254.63998413085938+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 166,+ "source_indices": [+ 166+ ],+ "raw_code": 111,+ "loose_bbox": [+ 129.70559692382812,+ 233.39999389648438,+ 141.48959350585938,+ 260.6399841308594+ ],+ "tight_bbox": [+ 130.47360229492188,+ 243.59999084472656,+ 140.7216033935547,+ 254.63998413085938+ ],+ "origin": [+ 129.70559692382812,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 141.47999572753906,+ 254.49598693847656,+ 146.61599731445312,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 167,+ "source_indices": [+ 167+ ],+ "raw_code": 32,+ "loose_bbox": [+ 141.47999572753906,+ 233.39999389648438,+ 146.61599731445312,+ 260.6399841308594+ ],+ "tight_bbox": [+ 141.47999572753906,+ 254.49598693847656,+ 146.61599731445312,+ 254.51998901367188+ ],+ "origin": [+ 141.47999572753906,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 147.0023956298828,+ 238.82398986816406,+ 152.8343963623047,+ 254.51998901367188+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 168,+ "source_indices": [+ 168+ ],+ "raw_code": 105,+ "loose_bbox": [+ 146.61839294433594,+ 233.39999389648438,+ 153.1223907470703,+ 260.6399841308594+ ],+ "tight_bbox": [+ 147.0023956298828,+ 238.82398986816406,+ 152.8343963623047,+ 254.51998901367188+ ],+ "origin": [+ 146.61839294433594,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 153.68878173828125,+ 241.6079864501953,+ 161.20079040527344,+ 254.7119903564453+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 169,+ "source_indices": [+ 169+ ],+ "raw_code": 116,+ "loose_bbox": [+ 153.11279296875,+ 233.39999389648438,+ 161.60879516601562,+ 260.6399841308594+ ],+ "tight_bbox": [+ 153.68878173828125,+ 241.6079864501953,+ 161.20079040527344,+ 254.7119903564453+ ],+ "origin": [+ 153.11279296875,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 161.59918212890625,+ 254.49598693847656,+ 166.73519897460938,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 170,+ "source_indices": [+ 170+ ],+ "raw_code": 32,+ "loose_bbox": [+ 161.59918212890625,+ 233.39999389648438,+ 166.73519897460938,+ 260.6399841308594+ ],+ "tight_bbox": [+ 161.59918212890625,+ 254.49598693847656,+ 166.73519897460938,+ 254.51998901367188+ ],+ "origin": [+ 161.59918212890625,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 166.83360290527344,+ 236.78399658203125,+ 178.71359252929688,+ 255.2639923095703+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 171,+ "source_indices": [+ 171+ ],+ "raw_code": 98,+ "loose_bbox": [+ 166.7375946044922,+ 233.39999389648438,+ 179.48159790039062,+ 260.6399841308594+ ],+ "tight_bbox": [+ 166.83360290527344,+ 236.78399658203125,+ 178.71359252929688,+ 255.2639923095703+ ],+ "origin": [+ 166.7375946044922,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 179.5919952392578,+ 243.8159942626953,+ 190.583984375,+ 260.59197998046875+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 172,+ "source_indices": [+ 172+ ],+ "raw_code": 121,+ "loose_bbox": [+ 179.4720001220703,+ 233.39999389648438,+ 190.70399475097656,+ 260.6399841308594+ ],+ "tight_bbox": [+ 179.5919952392578,+ 243.8159942626953,+ 190.583984375,+ 260.59197998046875+ ],+ "origin": [+ 179.4720001220703,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 190.69439697265625,+ 254.49598693847656,+ 195.8303985595703,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 173,+ "source_indices": [+ 173+ ],+ "raw_code": 32,+ "loose_bbox": [+ 190.69439697265625,+ 233.39999389648438,+ 195.8303985595703,+ 260.6399841308594+ ],+ "tight_bbox": [+ 190.69439697265625,+ 254.49598693847656,+ 195.8303985595703,+ 254.51998901367188+ ],+ "origin": [+ 190.69439697265625,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 196.60079956054688,+ 243.69598388671875,+ 205.74481201171875,+ 254.68798828125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 174,+ "source_indices": [+ 174+ ],+ "raw_code": 101,+ "loose_bbox": [+ 195.83279418945312,+ 233.39999389648438,+ 206.10479736328125,+ 260.6399841308594+ ],+ "tight_bbox": [+ 196.60079956054688,+ 243.69598388671875,+ 205.74481201171875,+ 254.68798828125+ ],+ "origin": [+ 195.83279418945312,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 207.1511993408203,+ 243.83999633789062,+ 216.34320068359375,+ 254.8079833984375+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 175,+ "source_indices": [+ 175+ ],+ "raw_code": 97,+ "loose_bbox": [+ 206.09519958496094,+ 233.39999389648438,+ 216.67919921875,+ 260.6399841308594+ ],+ "tight_bbox": [+ 207.1511993408203,+ 243.83999633789062,+ 216.34320068359375,+ 254.8079833984375+ ],+ "origin": [+ 206.09519958496094,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 217.24560546875,+ 241.6079864501953,+ 224.75759887695312,+ 254.7119903564453+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 176,+ "source_indices": [+ 176+ ],+ "raw_code": 116,+ "loose_bbox": [+ 216.66961669921875,+ 233.39999389648438,+ 225.16561889648438,+ 260.6399841308594+ ],+ "tight_bbox": [+ 217.24560546875,+ 241.6079864501953,+ 224.75759887695312,+ 254.7119903564453+ ],+ "origin": [+ 216.6696014404297,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 225.5399932861328,+ 238.82398986816406,+ 231.3719940185547,+ 254.51998901367188+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 177,+ "source_indices": [+ 177+ ],+ "raw_code": 105,+ "loose_bbox": [+ 225.156005859375,+ 233.39999389648438,+ 231.66000366210938,+ 260.6399841308594+ ],+ "tight_bbox": [+ 225.5399932861328,+ 238.82398986816406,+ 231.3719940185547,+ 254.51998901367188+ ],+ "origin": [+ 225.156005859375,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 232.0823974609375,+ 243.55198669433594,+ 244.25039672851562,+ 254.51998901367188+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 178,+ "source_indices": [+ 178+ ],+ "raw_code": 110,+ "loose_bbox": [+ 231.650390625,+ 233.39999389648438,+ 244.4423828125,+ 260.6399841308594+ ],+ "tight_bbox": [+ 232.0823974609375,+ 243.55198669433594,+ 244.25039672851562,+ 254.51998901367188+ ],+ "origin": [+ 231.650390625,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 244.72079467773438,+ 243.57598876953125,+ 255.59280395507812,+ 260.6159973144531+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 179,+ "source_indices": [+ 179+ ],+ "raw_code": 103,+ "loose_bbox": [+ 244.43280029296875,+ 233.39999389648438,+ 255.8087921142578,+ 260.6399841308594+ ],+ "tight_bbox": [+ 244.72079467773438,+ 243.57598876953125,+ 255.59280395507812,+ 260.6159973144531+ ],+ "origin": [+ 244.43280029296875,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 255.7991943359375,+ 254.49598693847656,+ 260.9352111816406,+ 254.51998901367188+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 180,+ "source_indices": [+ 180+ ],+ "raw_code": 32,+ "loose_bbox": [+ 255.7991943359375,+ 233.39999389648438,+ 260.9352111816406,+ 260.6399841308594+ ],+ "tight_bbox": [+ 255.7991943359375,+ 254.49598693847656,+ 260.9352111816406,+ 254.51998901367188+ ],+ "origin": [+ 255.7991943359375,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 261.1535949707031,+ 236.6639862060547,+ 268.6896057128906,+ 254.51998901367188+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 181,+ "source_indices": [+ 181+ ],+ "raw_code": 102,+ "loose_bbox": [+ 260.9375915527344,+ 233.39999389648438,+ 268.6896057128906,+ 260.6399841308594+ ],+ "tight_bbox": [+ 261.1535949707031,+ 236.6639862060547,+ 268.6896057128906,+ 254.51998901367188+ ],+ "origin": [+ 260.9375915527344,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 268.6319885253906,+ 243.59999084472656,+ 278.8800048828125,+ 254.63998413085938+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 182,+ "source_indices": [+ 182+ ],+ "raw_code": 111,+ "loose_bbox": [+ 267.864013671875,+ 233.39999389648438,+ 279.6480407714844,+ 260.6399841308594+ ],+ "tight_bbox": [+ 268.6319885253906,+ 243.59999084472656,+ 278.8800048828125,+ 254.63998413085938+ ],+ "origin": [+ 267.864013671875,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 280.4064025878906,+ 243.59999084472656,+ 290.6544189453125,+ 254.63998413085938+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 183,+ "source_indices": [+ 183+ ],+ "raw_code": 111,+ "loose_bbox": [+ 279.638427734375,+ 233.39999389648438,+ 291.4224548339844,+ 260.6399841308594+ ],+ "tight_bbox": [+ 280.4064025878906,+ 243.59999084472656,+ 290.6544189453125,+ 254.63998413085938+ ],+ "origin": [+ 279.638427734375,+ 254.51998901367188+ ]+ },+ {+ "bbox": [+ 292.1808166503906,+ 236.68798828125,+ 304.3248291015625,+ 254.87998962402344+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 184,+ "source_indices": [+ 184+ ],+ "raw_code": 100,+ "loose_bbox": [+ 291.412841796875,+ 233.39999389648438,+ 304.3248291015625,+ 260.6399841308594+ ],+ "tight_bbox": [+ 292.1808166503906,+ 236.68798828125,+ 304.3248291015625,+ 254.87998962402344+ ],+ "origin": [+ 291.412841796875,+ 254.51998901367188+ ]+ }+ ],+ "tight_bboxes": {+ "162": [+ 75.72480010986328,+ 238.583984375,+ 101.50080108642578,+ 254.75999450683594+ ],+ "163": [+ 102.2904052734375,+ 243.69598388671875,+ 111.43440246582031,+ 254.68798828125+ ],+ "164": [+ 111.78480529785156,+ 254.49598693847656,+ 116.92080688476562,+ 254.51998901367188+ ],+ "165": [+ 117.69120788574219,+ 236.68798828125,+ 129.835205078125,+ 254.87998962402344+ ],+ "166": [+ 130.47360229492188,+ 243.59999084472656,+ 140.7216033935547,+ 254.63998413085938+ ],+ "167": [+ 141.47999572753906,+ 254.49598693847656,+ 146.61599731445312,+ 254.51998901367188+ ],+ "168": [+ 147.0023956298828,+ 238.82398986816406,+ 152.8343963623047,+ 254.51998901367188+ ],+ "169": [+ 153.68878173828125,+ 241.6079864501953,+ 161.20079040527344,+ 254.7119903564453+ ],+ "170": [+ 161.59918212890625,+ 254.49598693847656,+ 166.73519897460938,+ 254.51998901367188+ ],+ "171": [+ 166.83360290527344,+ 236.78399658203125,+ 178.71359252929688,+ 255.2639923095703+ ],+ "172": [+ 179.5919952392578,+ 243.8159942626953,+ 190.583984375,+ 260.59197998046875+ ],+ "173": [+ 190.69439697265625,+ 254.49598693847656,+ 195.8303985595703,+ 254.51998901367188+ ],+ "174": [+ 196.60079956054688,+ 243.69598388671875,+ 205.74481201171875,+ 254.68798828125+ ],+ "175": [+ 207.1511993408203,+ 243.83999633789062,+ 216.34320068359375,+ 254.8079833984375+ ],+ "176": [+ 217.24560546875,+ 241.6079864501953,+ 224.75759887695312,+ 254.7119903564453+ ],+ "177": [+ 225.5399932861328,+ 238.82398986816406,+ 231.3719940185547,+ 254.51998901367188+ ],+ "178": [+ 232.0823974609375,+ 243.55198669433594,+ 244.25039672851562,+ 254.51998901367188+ ],+ "179": [+ 244.72079467773438,+ 243.57598876953125,+ 255.59280395507812,+ 260.6159973144531+ ],+ "180": [+ 255.7991943359375,+ 254.49598693847656,+ 260.9352111816406,+ 254.51998901367188+ ],+ "181": [+ 261.1535949707031,+ 236.6639862060547,+ 268.6896057128906,+ 254.51998901367188+ ],+ "182": [+ 268.6319885253906,+ 243.59999084472656,+ 278.8800048828125,+ 254.63998413085938+ ],+ "183": [+ 280.4064025878906,+ 243.59999084472656,+ 290.6544189453125,+ 254.63998413085938+ ],+ "184": [+ 292.1808166503906,+ 236.68798828125,+ 304.3248291015625,+ 254.87998962402344+ ]+ },+ "origins": {+ "162": [+ 75.60480499267578,+ 254.51998901367188+ ],+ "163": [+ 101.52239990234375,+ 254.51998901367188+ ],+ "164": [+ 111.78480529785156,+ 254.51998901367188+ ],+ "165": [+ 116.92320251464844,+ 254.51998901367188+ ],+ "166": [+ 129.70559692382812,+ 254.51998901367188+ ],+ "167": [+ 141.47999572753906,+ 254.51998901367188+ ],+ "168": [+ 146.61839294433594,+ 254.51998901367188+ ],+ "169": [+ 153.11279296875,+ 254.51998901367188+ ],+ "170": [+ 161.59918212890625,+ 254.51998901367188+ ],+ "171": [+ 166.7375946044922,+ 254.51998901367188+ ],+ "172": [+ 179.4720001220703,+ 254.51998901367188+ ],+ "173": [+ 190.69439697265625,+ 254.51998901367188+ ],+ "174": [+ 195.83279418945312,+ 254.51998901367188+ ],+ "175": [+ 206.09519958496094,+ 254.51998901367188+ ],+ "176": [+ 216.6696014404297,+ 254.51998901367188+ ],+ "177": [+ 225.156005859375,+ 254.51998901367188+ ],+ "178": [+ 231.650390625,+ 254.51998901367188+ ],+ "179": [+ 244.43280029296875,+ 254.51998901367188+ ],+ "180": [+ 255.7991943359375,+ 254.51998901367188+ ],+ "181": [+ 260.9375915527344,+ 254.51998901367188+ ],+ "182": [+ 267.864013671875,+ 254.51998901367188+ ],+ "183": [+ 279.638427734375,+ 254.51998901367188+ ],+ "184": [+ 291.412841796875,+ 254.51998901367188+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 291.412841796875,+ 255.05299377441406,+ 291.412841796875,+ 255.05299377441406+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 185,+ "source_indices": [+ 185+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 291.412841796875,+ 255.05299377441406+ ]+ },+ {+ "bbox": [+ 291.412841796875,+ 255.05299377441406,+ 291.412841796875,+ 255.05299377441406+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 186,+ "source_indices": [+ 186+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 291.412841796875,+ 255.05299377441406+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "185": [+ 291.412841796875,+ 255.05299377441406+ ],+ "186": [+ 291.412841796875,+ 255.05299377441406+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 65.89199829101562,+ 306.9360046386719,+ 72.01200103759766,+ 310.0320129394531+ ],+ "char": "-",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 187,+ "source_indices": [+ 187+ ],+ "raw_code": 45,+ "loose_bbox": [+ 64.86000061035156,+ 293.6400146484375,+ 73.04399871826172,+ 320.8800048828125+ ],+ "tight_bbox": [+ 65.89199829101562,+ 306.9360046386719,+ 72.01200103759766,+ 310.0320129394531+ ],+ "origin": [+ 64.86000061035156,+ 314.760009765625+ ]+ }+ ],+ "tight_bboxes": {+ "187": [+ 65.89199829101562,+ 306.9360046386719,+ 72.01200103759766,+ 310.0320129394531+ ]+ },+ "origins": {+ "187": [+ 64.86000061035156,+ 314.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 78.18479919433594,+ 314.760009765625,+ 78.18479919433594,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 188,+ "source_indices": [+ 188+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 78.18479919433594,+ 314.760009765625+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "188": [+ 78.18479919433594,+ 314.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 79.0968017578125,+ 298.8480224609375,+ 85.216796875,+ 314.760009765625+ ],+ "char": "I",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 189,+ "source_indices": [+ 189+ ],+ "raw_code": 73,+ "loose_bbox": [+ 78.18479919433594,+ 293.6400146484375,+ 86.03279876708984,+ 320.8800048828125+ ],+ "tight_bbox": [+ 79.0968017578125,+ 298.8480224609375,+ 85.216796875,+ 314.760009765625+ ],+ "origin": [+ 78.18479919433594,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 86.04240417480469,+ 314.73602294921875,+ 91.17840576171875,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 190,+ "source_indices": [+ 190+ ],+ "raw_code": 32,+ "loose_bbox": [+ 86.04240417480469,+ 293.6400146484375,+ 91.17840576171875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 86.04240417480469,+ 314.73602294921875,+ 91.17840576171875,+ 314.760009765625+ ],+ "origin": [+ 86.04240417480469,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 92.18880462646484,+ 304.00799560546875,+ 99.86880493164062,+ 314.9040222167969+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 191,+ "source_indices": [+ 191+ ],+ "raw_code": 115,+ "loose_bbox": [+ 91.20480346679688,+ 293.6400146484375,+ 100.70880126953125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 92.18880462646484,+ 304.00799560546875,+ 99.86880493164062,+ 314.9040222167969+ ],+ "origin": [+ 91.20480346679688,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 100.783203125,+ 303.864013671875,+ 112.49520874023438,+ 315.0480041503906+ ],+ "char": "u",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 192,+ "source_indices": [+ 192+ ],+ "raw_code": 117,+ "loose_bbox": [+ 100.71121215820312,+ 293.6400146484375,+ 113.40721130371094,+ 320.8800048828125+ ],+ "tight_bbox": [+ 100.783203125,+ 303.864013671875,+ 112.49520874023438,+ 315.0480041503906+ ],+ "origin": [+ 100.7112045288086,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 113.55360412597656,+ 303.7920227050781,+ 125.62560272216797,+ 320.8320007324219+ ],+ "char": "p",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 193,+ "source_indices": [+ 193+ ],+ "raw_code": 112,+ "loose_bbox": [+ 113.40960693359375,+ 293.6400146484375,+ 126.39361572265625,+ 320.8800048828125+ ],+ "tight_bbox": [+ 113.55360412597656,+ 303.7920227050781,+ 125.62560272216797,+ 320.8320007324219+ ],+ "origin": [+ 113.40960693359375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 126.54000091552734,+ 303.7920227050781,+ 138.61199951171875,+ 320.8320007324219+ ],+ "char": "p",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 194,+ "source_indices": [+ 194+ ],+ "raw_code": 112,+ "loose_bbox": [+ 126.39599609375,+ 293.6400146484375,+ 139.3800048828125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 126.54000091552734,+ 303.7920227050781,+ 138.61199951171875,+ 320.8320007324219+ ],+ "origin": [+ 126.39599609375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 140.150390625,+ 303.8399963378906,+ 150.39840698242188,+ 314.8800048828125+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 195,+ "source_indices": [+ 195+ ],+ "raw_code": 111,+ "loose_bbox": [+ 139.3824005126953,+ 293.6400146484375,+ 151.16639709472656,+ 320.8800048828125+ ],+ "tight_bbox": [+ 140.150390625,+ 303.8399963378906,+ 150.39840698242188,+ 314.8800048828125+ ],+ "origin": [+ 139.3824005126953,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 152.15280151367188,+ 304.00799560546875,+ 159.83279418945312,+ 314.9040222167969+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 196,+ "source_indices": [+ 196+ ],+ "raw_code": 115,+ "loose_bbox": [+ 151.16879272460938,+ 293.6400146484375,+ 160.67279052734375,+ 320.8800048828125+ ],+ "tight_bbox": [+ 152.15280151367188,+ 304.00799560546875,+ 159.83279418945312,+ 314.9040222167969+ ],+ "origin": [+ 151.16879272460938,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 161.4431915283203,+ 303.9360046386719,+ 170.58718872070312,+ 314.9280090332031+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 197,+ "source_indices": [+ 197+ ],+ "raw_code": 101,+ "loose_bbox": [+ 160.67518615722656,+ 293.6400146484375,+ 170.9471893310547,+ 320.8800048828125+ ],+ "tight_bbox": [+ 161.4431915283203,+ 303.9360046386719,+ 170.58718872070312,+ 314.9280090332031+ ],+ "origin": [+ 160.67518615722656,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 170.9495849609375,+ 314.73602294921875,+ 176.08560180664062,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 198,+ "source_indices": [+ 198+ ],+ "raw_code": 32,+ "loose_bbox": [+ 170.9495849609375,+ 293.6400146484375,+ 176.08560180664062,+ 320.8800048828125+ ],+ "tight_bbox": [+ 170.9495849609375,+ 314.73602294921875,+ 176.08560180664062,+ 314.760009765625+ ],+ "origin": [+ 170.9495849609375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 176.68800354003906,+ 301.8480224609375,+ 184.1999969482422,+ 314.9519958496094+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 199,+ "source_indices": [+ 199+ ],+ "raw_code": 116,+ "loose_bbox": [+ 176.11199951171875,+ 293.6400146484375,+ 184.60800170898438,+ 320.8800048828125+ ],+ "tight_bbox": [+ 176.68800354003906,+ 301.8480224609375,+ 184.1999969482422,+ 314.9519958496094+ ],+ "origin": [+ 176.11199951171875,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 184.89840698242188,+ 296.9280090332031,+ 197.18641662597656,+ 314.760009765625+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 200,+ "source_indices": [+ 200+ ],+ "raw_code": 104,+ "loose_bbox": [+ 184.61041259765625,+ 293.6400146484375,+ 197.30641174316406,+ 320.8800048828125+ ],+ "tight_bbox": [+ 184.89840698242188,+ 296.9280090332031,+ 197.18641662597656,+ 314.760009765625+ ],+ "origin": [+ 184.61041259765625,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 197.6927947998047,+ 299.0639953613281,+ 203.52479553222656,+ 314.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 201,+ "source_indices": [+ 201+ ],+ "raw_code": 105,+ "loose_bbox": [+ 197.30882263183594,+ 293.6400146484375,+ 203.8128204345703,+ 320.8800048828125+ ],+ "tight_bbox": [+ 197.6927947998047,+ 299.0639953613281,+ 203.52479553222656,+ 314.760009765625+ ],+ "origin": [+ 197.30880737304688,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 204.79920959472656,+ 304.00799560546875,+ 212.4792022705078,+ 314.9040222167969+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 202,+ "source_indices": [+ 202+ ],+ "raw_code": 115,+ "loose_bbox": [+ 203.81520080566406,+ 293.6400146484375,+ 213.31919860839844,+ 320.8800048828125+ ],+ "tight_bbox": [+ 204.79920959472656,+ 304.00799560546875,+ 212.4792022705078,+ 314.9040222167969+ ],+ "origin": [+ 203.81520080566406,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 213.3216094970703,+ 314.73602294921875,+ 218.45761108398438,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 203,+ "source_indices": [+ 203+ ],+ "raw_code": 32,+ "loose_bbox": [+ 213.3216094970703,+ 293.6400146484375,+ 218.45762634277344,+ 320.8800048828125+ ],+ "tight_bbox": [+ 213.3216094970703,+ 314.73602294921875,+ 218.45761108398438,+ 314.760009765625+ ],+ "origin": [+ 213.3216094970703,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 219.25201416015625,+ 303.9360046386719,+ 228.39601135253906,+ 314.9280090332031+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 204,+ "source_indices": [+ 204+ ],+ "raw_code": 101,+ "loose_bbox": [+ 218.48399353027344,+ 293.6400146484375,+ 228.75599670410156,+ 320.8800048828125+ ],+ "tight_bbox": [+ 219.25201416015625,+ 303.9360046386719,+ 228.39601135253906,+ 314.9280090332031+ ],+ "origin": [+ 218.4840087890625,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 228.9024200439453,+ 304.0559997558594,+ 241.3344268798828,+ 314.760009765625+ ],+ "char": "x",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 205,+ "source_indices": [+ 205+ ],+ "raw_code": 120,+ "loose_bbox": [+ 228.75840759277344,+ 293.6400146484375,+ 241.4544219970703,+ 320.8800048828125+ ],+ "tight_bbox": [+ 228.9024200439453,+ 304.0559997558594,+ 241.3344268798828,+ 314.760009765625+ ],+ "origin": [+ 228.75840759277344,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 241.60081481933594,+ 303.7920227050781,+ 253.6728057861328,+ 320.8320007324219+ ],+ "char": "p",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 206,+ "source_indices": [+ 206+ ],+ "raw_code": 112,+ "loose_bbox": [+ 241.4568328857422,+ 293.6400146484375,+ 254.44082641601562,+ 320.8800048828125+ ],+ "tight_bbox": [+ 241.60081481933594,+ 303.7920227050781,+ 253.6728057861328,+ 320.8320007324219+ ],+ "origin": [+ 241.45681762695312,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 254.61122131347656,+ 297.0480041503906,+ 260.70721435546875,+ 314.760009765625+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 207,+ "source_indices": [+ 207+ ],+ "raw_code": 108,+ "loose_bbox": [+ 254.44322204589844,+ 293.6400146484375,+ 260.89923095703125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 254.61122131347656,+ 297.0480041503906,+ 260.70721435546875,+ 314.760009765625+ ],+ "origin": [+ 254.44322204589844,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 261.9576110839844,+ 304.08001708984375,+ 271.14959716796875,+ 315.0480041503906+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 208,+ "source_indices": [+ 208+ ],+ "raw_code": 97,+ "loose_bbox": [+ 260.901611328125,+ 293.6400146484375,+ 271.485595703125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 261.9576110839844,+ 304.08001708984375,+ 271.14959716796875,+ 315.0480041503906+ ],+ "origin": [+ 260.901611328125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 271.87200927734375,+ 299.0639953613281,+ 277.70404052734375,+ 314.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 209,+ "source_indices": [+ 209+ ],+ "raw_code": 105,+ "loose_bbox": [+ 271.488037109375,+ 293.6400146484375,+ 277.9920654296875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 271.87200927734375,+ 299.0639953613281,+ 277.70404052734375,+ 314.760009765625+ ],+ "origin": [+ 271.488037109375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 278.4263916015625,+ 303.7920227050781,+ 290.59442138671875,+ 314.760009765625+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 210,+ "source_indices": [+ 210+ ],+ "raw_code": 110,+ "loose_bbox": [+ 277.99444580078125,+ 293.6400146484375,+ 290.78643798828125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 278.4263916015625,+ 303.7920227050781,+ 290.59442138671875,+ 314.760009765625+ ],+ "origin": [+ 277.99444580078125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 291.7728271484375,+ 304.00799560546875,+ 299.45281982421875,+ 314.9040222167969+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 211,+ "source_indices": [+ 211+ ],+ "raw_code": 115,+ "loose_bbox": [+ 290.788818359375,+ 293.6400146484375,+ 300.2928466796875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 291.7728271484375,+ 304.00799560546875,+ 299.45281982421875,+ 314.9040222167969+ ],+ "origin": [+ 290.788818359375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 300.29522705078125,+ 314.73602294921875,+ 305.43121337890625,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 212,+ "source_indices": [+ 212+ ],+ "raw_code": 32,+ "loose_bbox": [+ 300.29522705078125,+ 293.6400146484375,+ 305.43121337890625,+ 320.8800048828125+ ],+ "tight_bbox": [+ 300.29522705078125,+ 314.73602294921875,+ 305.43121337890625,+ 314.760009765625+ ],+ "origin": [+ 300.29522705078125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 306.03363037109375,+ 301.8480224609375,+ 313.545654296875,+ 314.9519958496094+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 213,+ "source_indices": [+ 213+ ],+ "raw_code": 116,+ "loose_bbox": [+ 305.4576416015625,+ 293.6400146484375,+ 313.95361328125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 306.03363037109375,+ 301.8480224609375,+ 313.545654296875,+ 314.9519958496094+ ],+ "origin": [+ 305.4576416015625,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 314.2440185546875,+ 296.9280090332031,+ 326.53204345703125,+ 314.760009765625+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 214,+ "source_indices": [+ 214+ ],+ "raw_code": 104,+ "loose_bbox": [+ 313.9560546875,+ 293.6400146484375,+ 326.65203857421875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 314.2440185546875,+ 296.9280090332031,+ 326.53204345703125,+ 314.760009765625+ ],+ "origin": [+ 313.9560546875,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 327.42242431640625,+ 303.9360046386719,+ 336.56646728515625,+ 314.9280090332031+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 215,+ "source_indices": [+ 215+ ],+ "raw_code": 101,+ "loose_bbox": [+ 326.6544189453125,+ 293.6400146484375,+ 336.92645263671875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 327.42242431640625,+ 303.9360046386719,+ 336.56646728515625,+ 314.9280090332031+ ],+ "origin": [+ 326.6544189453125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 336.9288330078125,+ 314.73602294921875,+ 342.06488037109375,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 216,+ "source_indices": [+ 216+ ],+ "raw_code": 32,+ "loose_bbox": [+ 336.9288330078125,+ 293.6400146484375,+ 342.06488037109375,+ 320.8800048828125+ ],+ "tight_bbox": [+ 336.9288330078125,+ 314.73602294921875,+ 342.06488037109375,+ 314.760009765625+ ],+ "origin": [+ 336.9288330078125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 342.3072509765625,+ 296.9040222167969,+ 349.84326171875,+ 314.760009765625+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 217,+ "source_indices": [+ 217+ ],+ "raw_code": 102,+ "loose_bbox": [+ 342.09124755859375,+ 293.6400146484375,+ 349.84326171875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 342.3072509765625,+ 296.9040222167969,+ 349.84326171875,+ 314.760009765625+ ],+ "origin": [+ 342.09124755859375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 349.79766845703125,+ 303.8399963378906,+ 360.045654296875,+ 314.8800048828125+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 218,+ "source_indices": [+ 218+ ],+ "raw_code": 111,+ "loose_bbox": [+ 349.0296630859375,+ 293.6400146484375,+ 360.81365966796875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 349.79766845703125,+ 303.8399963378906,+ 360.045654296875,+ 314.8800048828125+ ],+ "origin": [+ 349.0296630859375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 361.58404541015625,+ 303.864013671875,+ 370.8720703125,+ 314.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 219,+ "source_indices": [+ 219+ ],+ "raw_code": 99,+ "loose_bbox": [+ 360.8160400390625,+ 293.6400146484375,+ 371.4000244140625,+ 320.8800048828125+ ],+ "tight_bbox": [+ 361.58404541015625,+ 303.864013671875,+ 370.8720703125,+ 314.9040222167969+ ],+ "origin": [+ 360.8160400390625,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 371.4744873046875,+ 303.864013671875,+ 383.18646240234375,+ 315.0480041503906+ ],+ "char": "u",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 220,+ "source_indices": [+ 220+ ],+ "raw_code": 117,+ "loose_bbox": [+ 371.4024658203125,+ 293.6400146484375,+ 384.09844970703125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 371.4744873046875,+ 303.864013671875,+ 383.18646240234375,+ 315.0480041503906+ ],+ "origin": [+ 371.4024658203125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 385.08489990234375,+ 304.00799560546875,+ 392.764892578125,+ 314.9040222167969+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 221,+ "source_indices": [+ 221+ ],+ "raw_code": 115,+ "loose_bbox": [+ 384.10089111328125,+ 293.6400146484375,+ 393.6048583984375,+ 320.8800048828125+ ],+ "tight_bbox": [+ 385.08489990234375,+ 304.00799560546875,+ 392.764892578125,+ 314.9040222167969+ ],+ "origin": [+ 384.10089111328125,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 393.6072998046875,+ 314.73602294921875,+ 398.7432861328125,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 222,+ "source_indices": [+ 222+ ],+ "raw_code": 32,+ "loose_bbox": [+ 393.6072998046875,+ 293.6400146484375,+ 398.7432861328125,+ 320.8800048828125+ ],+ "tight_bbox": [+ 393.6072998046875,+ 314.73602294921875,+ 398.7432861328125,+ 314.760009765625+ ],+ "origin": [+ 393.6072998046875,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 399.53765869140625,+ 303.8399963378906,+ 409.78570556640625,+ 314.8800048828125+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 223,+ "source_indices": [+ 223+ ],+ "raw_code": 111,+ "loose_bbox": [+ 398.76971435546875,+ 293.6400146484375,+ 410.5537109375,+ 320.8800048828125+ ],+ "tight_bbox": [+ 399.53765869140625,+ 303.8399963378906,+ 409.78570556640625,+ 314.8800048828125+ ],+ "origin": [+ 398.76971435546875,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 410.7720947265625,+ 296.9040222167969,+ 418.30810546875,+ 314.760009765625+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 224,+ "source_indices": [+ 224+ ],+ "raw_code": 102,+ "loose_bbox": [+ 410.55609130859375,+ 293.6400146484375,+ 418.30810546875,+ 320.8800048828125+ ],+ "tight_bbox": [+ 410.7720947265625,+ 296.9040222167969,+ 418.30810546875,+ 314.760009765625+ ],+ "origin": [+ 410.55609130859375,+ 314.760009765625+ ]+ },+ {+ "bbox": [+ 417.4945068359375,+ 314.73602294921875,+ 422.6304931640625,+ 314.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 225,+ "source_indices": [+ 225+ ],+ "raw_code": 32,+ "loose_bbox": [+ 417.4945068359375,+ 293.6400146484375,+ 422.6304931640625,+ 320.8800048828125+ ],+ "tight_bbox": [+ 417.4945068359375,+ 314.73602294921875,+ 422.6304931640625,+ 314.760009765625+ ],+ "origin": [+ 417.4945068359375,+ 314.760009765625+ ]+ }+ ],+ "tight_bboxes": {+ "189": [+ 79.0968017578125,+ 298.8480224609375,+ 85.216796875,+ 314.760009765625+ ],+ "190": [+ 86.04240417480469,+ 314.73602294921875,+ 91.17840576171875,+ 314.760009765625+ ],+ "191": [+ 92.18880462646484,+ 304.00799560546875,+ 99.86880493164062,+ 314.9040222167969+ ],+ "192": [+ 100.783203125,+ 303.864013671875,+ 112.49520874023438,+ 315.0480041503906+ ],+ "193": [+ 113.55360412597656,+ 303.7920227050781,+ 125.62560272216797,+ 320.8320007324219+ ],+ "194": [+ 126.54000091552734,+ 303.7920227050781,+ 138.61199951171875,+ 320.8320007324219+ ],+ "195": [+ 140.150390625,+ 303.8399963378906,+ 150.39840698242188,+ 314.8800048828125+ ],+ "196": [+ 152.15280151367188,+ 304.00799560546875,+ 159.83279418945312,+ 314.9040222167969+ ],+ "197": [+ 161.4431915283203,+ 303.9360046386719,+ 170.58718872070312,+ 314.9280090332031+ ],+ "198": [+ 170.9495849609375,+ 314.73602294921875,+ 176.08560180664062,+ 314.760009765625+ ],+ "199": [+ 176.68800354003906,+ 301.8480224609375,+ 184.1999969482422,+ 314.9519958496094+ ],+ "200": [+ 184.89840698242188,+ 296.9280090332031,+ 197.18641662597656,+ 314.760009765625+ ],+ "201": [+ 197.6927947998047,+ 299.0639953613281,+ 203.52479553222656,+ 314.760009765625+ ],+ "202": [+ 204.79920959472656,+ 304.00799560546875,+ 212.4792022705078,+ 314.9040222167969+ ],+ "203": [+ 213.3216094970703,+ 314.73602294921875,+ 218.45761108398438,+ 314.760009765625+ ],+ "204": [+ 219.25201416015625,+ 303.9360046386719,+ 228.39601135253906,+ 314.9280090332031+ ],+ "205": [+ 228.9024200439453,+ 304.0559997558594,+ 241.3344268798828,+ 314.760009765625+ ],+ "206": [+ 241.60081481933594,+ 303.7920227050781,+ 253.6728057861328,+ 320.8320007324219+ ],+ "207": [+ 254.61122131347656,+ 297.0480041503906,+ 260.70721435546875,+ 314.760009765625+ ],+ "208": [+ 261.9576110839844,+ 304.08001708984375,+ 271.14959716796875,+ 315.0480041503906+ ],+ "209": [+ 271.87200927734375,+ 299.0639953613281,+ 277.70404052734375,+ 314.760009765625+ ],+ "210": [+ 278.4263916015625,+ 303.7920227050781,+ 290.59442138671875,+ 314.760009765625+ ],+ "211": [+ 291.7728271484375,+ 304.00799560546875,+ 299.45281982421875,+ 314.9040222167969+ ],+ "212": [+ 300.29522705078125,+ 314.73602294921875,+ 305.43121337890625,+ 314.760009765625+ ],+ "213": [+ 306.03363037109375,+ 301.8480224609375,+ 313.545654296875,+ 314.9519958496094+ ],+ "214": [+ 314.2440185546875,+ 296.9280090332031,+ 326.53204345703125,+ 314.760009765625+ ],+ "215": [+ 327.42242431640625,+ 303.9360046386719,+ 336.56646728515625,+ 314.9280090332031+ ],+ "216": [+ 336.9288330078125,+ 314.73602294921875,+ 342.06488037109375,+ 314.760009765625+ ],+ "217": [+ 342.3072509765625,+ 296.9040222167969,+ 349.84326171875,+ 314.760009765625+ ],+ "218": [+ 349.79766845703125,+ 303.8399963378906,+ 360.045654296875,+ 314.8800048828125+ ],+ "219": [+ 361.58404541015625,+ 303.864013671875,+ 370.8720703125,+ 314.9040222167969+ ],+ "220": [+ 371.4744873046875,+ 303.864013671875,+ 383.18646240234375,+ 315.0480041503906+ ],+ "221": [+ 385.08489990234375,+ 304.00799560546875,+ 392.764892578125,+ 314.9040222167969+ ],+ "222": [+ 393.6072998046875,+ 314.73602294921875,+ 398.7432861328125,+ 314.760009765625+ ],+ "223": [+ 399.53765869140625,+ 303.8399963378906,+ 409.78570556640625,+ 314.8800048828125+ ],+ "224": [+ 410.7720947265625,+ 296.9040222167969,+ 418.30810546875,+ 314.760009765625+ ],+ "225": [+ 417.4945068359375,+ 314.73602294921875,+ 422.6304931640625,+ 314.760009765625+ ]+ },+ "origins": {+ "189": [+ 78.18479919433594,+ 314.760009765625+ ],+ "190": [+ 86.04240417480469,+ 314.760009765625+ ],+ "191": [+ 91.20480346679688,+ 314.760009765625+ ],+ "192": [+ 100.7112045288086,+ 314.760009765625+ ],+ "193": [+ 113.40960693359375,+ 314.760009765625+ ],+ "194": [+ 126.39599609375,+ 314.760009765625+ ],+ "195": [+ 139.3824005126953,+ 314.760009765625+ ],+ "196": [+ 151.16879272460938,+ 314.760009765625+ ],+ "197": [+ 160.67518615722656,+ 314.760009765625+ ],+ "198": [+ 170.9495849609375,+ 314.760009765625+ ],+ "199": [+ 176.11199951171875,+ 314.760009765625+ ],+ "200": [+ 184.61041259765625,+ 314.760009765625+ ],+ "201": [+ 197.30880737304688,+ 314.760009765625+ ],+ "202": [+ 203.81520080566406,+ 314.760009765625+ ],+ "203": [+ 213.3216094970703,+ 314.760009765625+ ],+ "204": [+ 218.4840087890625,+ 314.760009765625+ ],+ "205": [+ 228.75840759277344,+ 314.760009765625+ ],+ "206": [+ 241.45681762695312,+ 314.760009765625+ ],+ "207": [+ 254.44322204589844,+ 314.760009765625+ ],+ "208": [+ 260.901611328125,+ 314.760009765625+ ],+ "209": [+ 271.488037109375,+ 314.760009765625+ ],+ "210": [+ 277.99444580078125,+ 314.760009765625+ ],+ "211": [+ 290.788818359375,+ 314.760009765625+ ],+ "212": [+ 300.29522705078125,+ 314.760009765625+ ],+ "213": [+ 305.4576416015625,+ 314.760009765625+ ],+ "214": [+ 313.9560546875,+ 314.760009765625+ ],+ "215": [+ 326.6544189453125,+ 314.760009765625+ ],+ "216": [+ 336.9288330078125,+ 314.760009765625+ ],+ "217": [+ 342.09124755859375,+ 314.760009765625+ ],+ "218": [+ 349.0296630859375,+ 314.760009765625+ ],+ "219": [+ 360.8160400390625,+ 314.760009765625+ ],+ "220": [+ 371.4024658203125,+ 314.760009765625+ ],+ "221": [+ 384.10089111328125,+ 314.760009765625+ ],+ "222": [+ 393.6072998046875,+ 314.760009765625+ ],+ "223": [+ 398.76971435546875,+ 314.760009765625+ ],+ "224": [+ 410.55609130859375,+ 314.760009765625+ ],+ "225": [+ 417.4945068359375,+ 314.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 417.4945068359375,+ 314.9739990234375,+ 417.4945068359375,+ 314.9739990234375+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 226,+ "source_indices": [+ 226+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 417.4945068359375,+ 314.9739990234375+ ]+ },+ {+ "bbox": [+ 417.4945068359375,+ 314.9739990234375,+ 417.4945068359375,+ 314.9739990234375+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 227,+ "source_indices": [+ 227+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 417.4945068359375,+ 314.9739990234375+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "226": [+ 417.4945068359375,+ 314.9739990234375+ ],+ "227": [+ 417.4945068359375,+ 314.9739990234375+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 65.62799835205078,+ 332.6759948730469,+ 74.77200317382812,+ 343.6679992675781+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 228,+ "source_indices": [+ 228+ ],+ "raw_code": 101,+ "loose_bbox": [+ 64.86000061035156,+ 322.3800048828125,+ 75.13200378417969,+ 349.6199951171875+ ],+ "tight_bbox": [+ 65.62799835205078,+ 332.6759948730469,+ 74.77200317382812,+ 343.6679992675781+ ],+ "origin": [+ 64.86000061035156,+ 343.5+ ]+ },+ {+ "bbox": [+ 75.25440216064453,+ 332.7959899902344,+ 86.12640380859375,+ 343.5719909667969+ ],+ "char": "v",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 229,+ "source_indices": [+ 229+ ],+ "raw_code": 118,+ "loose_bbox": [+ 75.1343994140625,+ 322.3800048828125,+ 86.15039825439453,+ 349.6199951171875+ ],+ "tight_bbox": [+ 75.25440216064453,+ 332.7959899902344,+ 86.12640380859375,+ 343.5719909667969+ ],+ "origin": [+ 75.1343994140625,+ 343.5+ ]+ },+ {+ "bbox": [+ 86.9207992553711,+ 332.6759948730469,+ 96.06480407714844,+ 343.6679992675781+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 230,+ "source_indices": [+ 230+ ],+ "raw_code": 101,+ "loose_bbox": [+ 86.15280151367188,+ 322.3800048828125,+ 96.4248046875,+ 349.6199951171875+ ],+ "tight_bbox": [+ 86.9207992553711,+ 332.6759948730469,+ 96.06480407714844,+ 343.6679992675781+ ],+ "origin": [+ 86.15280151367188,+ 343.5+ ]+ },+ {+ "bbox": [+ 96.76319885253906,+ 332.4599914550781,+ 104.99520111083984,+ 343.5+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 231,+ "source_indices": [+ 231+ ],+ "raw_code": 114,+ "loose_bbox": [+ 96.42720794677734,+ 322.3800048828125,+ 105.1632080078125,+ 349.6199951171875+ ],+ "tight_bbox": [+ 96.76319885253906,+ 332.4599914550781,+ 104.99520111083984,+ 343.5+ ],+ "origin": [+ 96.42720031738281,+ 343.5+ ]+ },+ {+ "bbox": [+ 105.28559875488281,+ 332.7959899902344,+ 116.27760314941406,+ 349.5719909667969+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 232,+ "source_indices": [+ 232+ ],+ "raw_code": 121,+ "loose_bbox": [+ 105.16560363769531,+ 322.3800048828125,+ 116.3976058959961,+ 349.6199951171875+ ],+ "tight_bbox": [+ 105.28559875488281,+ 332.7959899902344,+ 116.27760314941406,+ 349.5719909667969+ ],+ "origin": [+ 105.16560363769531,+ 343.5+ ]+ },+ {+ "bbox": [+ 116.39999389648438,+ 343.47601318359375,+ 121.53599548339844,+ 343.5+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 233,+ "source_indices": [+ 233+ ],+ "raw_code": 32,+ "loose_bbox": [+ 116.39999389648438,+ 322.3800048828125,+ 121.53599548339844,+ 349.6199951171875+ ],+ "tight_bbox": [+ 116.39999389648438,+ 343.47601318359375,+ 121.53599548339844,+ 343.5+ ],+ "origin": [+ 116.39999389648438,+ 343.5+ ]+ },+ {+ "bbox": [+ 121.62959289550781,+ 325.7640075683594,+ 133.5095977783203,+ 344.2439880371094+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 234,+ "source_indices": [+ 234+ ],+ "raw_code": 98,+ "loose_bbox": [+ 121.53359985351562,+ 322.3800048828125,+ 134.277587890625,+ 349.6199951171875+ ],+ "tight_bbox": [+ 121.62959289550781,+ 325.7640075683594,+ 133.5095977783203,+ 344.2439880371094+ ],+ "origin": [+ 121.5335922241211,+ 343.5+ ]+ },+ {+ "bbox": [+ 134.66400146484375,+ 327.8039855957031,+ 140.49600219726562,+ 343.5+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 235,+ "source_indices": [+ 235+ ],+ "raw_code": 105,+ "loose_bbox": [+ 134.27999877929688,+ 322.3800048828125,+ 140.7840118408203,+ 349.6199951171875+ ],+ "tight_bbox": [+ 134.66400146484375,+ 327.8039855957031,+ 140.49600219726562,+ 343.5+ ],+ "origin": [+ 134.27999877929688,+ 343.5+ ]+ },+ {+ "bbox": [+ 141.55438232421875,+ 332.5799865722656,+ 151.80239868164062,+ 343.6199951171875+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 236,+ "source_indices": [+ 236+ ],+ "raw_code": 111,+ "loose_bbox": [+ 140.78639221191406,+ 322.3800048828125,+ 152.5703887939453,+ 349.6199951171875+ ],+ "tight_bbox": [+ 141.55438232421875,+ 332.5799865722656,+ 151.80239868164062,+ 343.6199951171875+ ],+ "origin": [+ 140.78639221191406,+ 343.5+ ]+ },+ {+ "bbox": [+ 153.34078979492188,+ 332.60400390625,+ 162.6287841796875,+ 343.6440124511719+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 237,+ "source_indices": [+ 237+ ],+ "raw_code": 99,+ "loose_bbox": [+ 152.57278442382812,+ 322.3800048828125,+ 163.15679931640625,+ 349.6199951171875+ ],+ "tight_bbox": [+ 153.34078979492188,+ 332.60400390625,+ 162.6287841796875,+ 343.6440124511719+ ],+ "origin": [+ 152.57278442382812,+ 343.5+ ]+ },+ {+ "bbox": [+ 163.4471893310547,+ 325.6679992675781,+ 175.73519897460938,+ 343.5+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 238,+ "source_indices": [+ 238+ ],+ "raw_code": 104,+ "loose_bbox": [+ 163.1591796875,+ 322.3800048828125,+ 175.85519409179688,+ 349.6199951171875+ ],+ "tight_bbox": [+ 163.4471893310547,+ 325.6679992675781,+ 175.73519897460938,+ 343.5+ ],+ "origin": [+ 163.1591796875,+ 343.5+ ]+ },+ {+ "bbox": [+ 176.62557983398438,+ 332.6759948730469,+ 185.76959228515625,+ 343.6679992675781+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 239,+ "source_indices": [+ 239+ ],+ "raw_code": 101,+ "loose_bbox": [+ 175.85760498046875,+ 322.3800048828125,+ 186.1295928955078,+ 349.6199951171875+ ],+ "tight_bbox": [+ 176.62557983398438,+ 332.6759948730469,+ 185.76959228515625,+ 343.6679992675781+ ],+ "origin": [+ 175.8575897216797,+ 343.5+ ]+ },+ {+ "bbox": [+ 186.46798706054688,+ 332.50799560546875,+ 204.58799743652344,+ 343.5+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 240,+ "source_indices": [+ 240+ ],+ "raw_code": 109,+ "loose_bbox": [+ 186.13198852539062,+ 322.3800048828125,+ 204.75599670410156,+ 349.6199951171875+ ],+ "tight_bbox": [+ 186.46798706054688,+ 332.50799560546875,+ 204.58799743652344,+ 343.5+ ],+ "origin": [+ 186.13198852539062,+ 343.5+ ]+ },+ {+ "bbox": [+ 205.1423797607422,+ 327.8039855957031,+ 210.97438049316406,+ 343.5+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 241,+ "source_indices": [+ 241+ ],+ "raw_code": 105,+ "loose_bbox": [+ 204.75839233398438,+ 322.3800048828125,+ 211.26239013671875,+ 349.6199951171875+ ],+ "tight_bbox": [+ 205.1423797607422,+ 327.8039855957031,+ 210.97438049316406,+ 343.5+ ],+ "origin": [+ 204.75839233398438,+ 343.5+ ]+ },+ {+ "bbox": [+ 212.24879455566406,+ 332.74798583984375,+ 219.9287872314453,+ 343.6440124511719+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 242,+ "source_indices": [+ 242+ ],+ "raw_code": 115,+ "loose_bbox": [+ 211.26478576660156,+ 322.3800048828125,+ 220.76878356933594,+ 349.6199951171875+ ],+ "tight_bbox": [+ 212.24879455566406,+ 332.74798583984375,+ 219.9287872314453,+ 343.6440124511719+ ],+ "origin": [+ 211.26478576660156,+ 343.5+ ]+ },+ {+ "bbox": [+ 221.34719848632812,+ 330.5880126953125,+ 228.85919189453125,+ 343.6919860839844+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 243,+ "source_indices": [+ 243+ ],+ "raw_code": 116,+ "loose_bbox": [+ 220.7711944580078,+ 322.3800048828125,+ 229.26719665527344,+ 349.6199951171875+ ],+ "tight_bbox": [+ 221.34719848632812,+ 330.5880126953125,+ 228.85919189453125,+ 343.6919860839844+ ],+ "origin": [+ 220.7711944580078,+ 343.5+ ]+ },+ {+ "bbox": [+ 229.60560607910156,+ 332.4599914550781,+ 237.8376007080078,+ 343.5+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 244,+ "source_indices": [+ 244+ ],+ "raw_code": 114,+ "loose_bbox": [+ 229.2696075439453,+ 322.3800048828125,+ 238.00559997558594,+ 349.6199951171875+ ],+ "tight_bbox": [+ 229.60560607910156,+ 332.4599914550781,+ 237.8376007080078,+ 343.5+ ],+ "origin": [+ 229.2696075439453,+ 343.5+ ]+ },+ {+ "bbox": [+ 238.1280059814453,+ 332.7959899902344,+ 249.1199951171875,+ 349.5719909667969+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 245,+ "source_indices": [+ 245+ ],+ "raw_code": 121,+ "loose_bbox": [+ 238.0079803466797,+ 322.3800048828125,+ 249.239990234375,+ 349.6199951171875+ ],+ "tight_bbox": [+ 238.1280059814453,+ 332.7959899902344,+ 249.1199951171875,+ 349.5719909667969+ ],+ "origin": [+ 238.00799560546875,+ 343.5+ ]+ },+ {+ "bbox": [+ 249.24240112304688,+ 343.47601318359375,+ 254.37840270996094,+ 343.5+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 246,+ "source_indices": [+ 246+ ],+ "raw_code": 32,+ "loose_bbox": [+ 249.24240112304688,+ 322.3800048828125,+ 254.37840270996094,+ 349.6199951171875+ ],+ "tight_bbox": [+ 249.24240112304688,+ 343.47601318359375,+ 254.37840270996094,+ 343.5+ ],+ "origin": [+ 249.24240112304688,+ 343.5+ ]+ },+ {+ "bbox": [+ 254.95201110839844,+ 330.5880126953125,+ 262.4639892578125,+ 343.6919860839844+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 247,+ "source_indices": [+ 247+ ],+ "raw_code": 116,+ "loose_bbox": [+ 254.3760223388672,+ 322.3800048828125,+ 262.87200927734375,+ 349.6199951171875+ ],+ "tight_bbox": [+ 254.95201110839844,+ 330.5880126953125,+ 262.4639892578125,+ 343.6919860839844+ ],+ "origin": [+ 254.3760223388672,+ 343.5+ ]+ },+ {+ "bbox": [+ 263.64239501953125,+ 332.6759948730469,+ 272.78643798828125,+ 343.6679992675781+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 248,+ "source_indices": [+ 248+ ],+ "raw_code": 101,+ "loose_bbox": [+ 262.8744201660156,+ 322.3800048828125,+ 273.14642333984375,+ 349.6199951171875+ ],+ "tight_bbox": [+ 263.64239501953125,+ 332.6759948730469,+ 272.78643798828125,+ 343.6679992675781+ ],+ "origin": [+ 262.8744201660156,+ 343.5+ ]+ },+ {+ "bbox": [+ 273.2928466796875,+ 332.7959899902344,+ 285.724853515625,+ 343.5+ ],+ "char": "x",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 249,+ "source_indices": [+ 249+ ],+ "raw_code": 120,+ "loose_bbox": [+ 273.1488342285156,+ 322.3800048828125,+ 285.8448486328125,+ 349.6199951171875+ ],+ "tight_bbox": [+ 273.2928466796875,+ 332.7959899902344,+ 285.724853515625,+ 343.5+ ],+ "origin": [+ 273.1488342285156,+ 343.5+ ]+ },+ {+ "bbox": [+ 286.4232482910156,+ 330.5880126953125,+ 293.93524169921875,+ 343.6919860839844+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 250,+ "source_indices": [+ 250+ ],+ "raw_code": 116,+ "loose_bbox": [+ 285.84722900390625,+ 322.3800048828125,+ 294.34320068359375,+ 349.6199951171875+ ],+ "tight_bbox": [+ 286.4232482910156,+ 330.5880126953125,+ 293.93524169921875,+ 343.6919860839844+ ],+ "origin": [+ 285.84722900390625,+ 343.5+ ]+ },+ {+ "bbox": [+ 294.441650390625,+ 325.7640075683594,+ 306.3216552734375,+ 344.2439880371094+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 251,+ "source_indices": [+ 251+ ],+ "raw_code": 98,+ "loose_bbox": [+ 294.34564208984375,+ 322.3800048828125,+ 307.08966064453125,+ 349.6199951171875+ ],+ "tight_bbox": [+ 294.441650390625,+ 325.7640075683594,+ 306.3216552734375,+ 344.2439880371094+ ],+ "origin": [+ 294.34564208984375,+ 343.5+ ]+ },+ {+ "bbox": [+ 307.86004638671875,+ 332.5799865722656,+ 318.1080322265625,+ 343.6199951171875+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 252,+ "source_indices": [+ 252+ ],+ "raw_code": 111,+ "loose_bbox": [+ 307.092041015625,+ 322.3800048828125,+ 318.87603759765625,+ 349.6199951171875+ ],+ "tight_bbox": [+ 307.86004638671875,+ 332.5799865722656,+ 318.1080322265625,+ 343.6199951171875+ ],+ "origin": [+ 307.092041015625,+ 343.5+ ]+ },+ {+ "bbox": [+ 319.6464538574219,+ 332.5799865722656,+ 329.89447021484375,+ 343.6199951171875+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 253,+ "source_indices": [+ 253+ ],+ "raw_code": 111,+ "loose_bbox": [+ 318.87847900390625,+ 322.3800048828125,+ 330.6624755859375,+ 349.6199951171875+ ],+ "tight_bbox": [+ 319.6464538574219,+ 332.5799865722656,+ 329.89447021484375,+ 343.6199951171875+ ],+ "origin": [+ 318.87847900390625,+ 343.5+ ]+ },+ {+ "bbox": [+ 330.9288330078125,+ 325.81201171875,+ 343.5048828125,+ 343.5+ ],+ "char": "k",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 254,+ "source_indices": [+ 254+ ],+ "raw_code": 107,+ "loose_bbox": [+ 330.66485595703125,+ 322.3800048828125,+ 343.62481689453125,+ 349.6199951171875+ ],+ "tight_bbox": [+ 330.9288330078125,+ 325.81201171875,+ 343.5048828125,+ 343.5+ ],+ "origin": [+ 330.66485595703125,+ 343.5+ ]+ }+ ],+ "tight_bboxes": {+ "228": [+ 65.62799835205078,+ 332.6759948730469,+ 74.77200317382812,+ 343.6679992675781+ ],+ "229": [+ 75.25440216064453,+ 332.7959899902344,+ 86.12640380859375,+ 343.5719909667969+ ],+ "230": [+ 86.9207992553711,+ 332.6759948730469,+ 96.06480407714844,+ 343.6679992675781+ ],+ "231": [+ 96.76319885253906,+ 332.4599914550781,+ 104.99520111083984,+ 343.5+ ],+ "232": [+ 105.28559875488281,+ 332.7959899902344,+ 116.27760314941406,+ 349.5719909667969+ ],+ "233": [+ 116.39999389648438,+ 343.47601318359375,+ 121.53599548339844,+ 343.5+ ],+ "234": [+ 121.62959289550781,+ 325.7640075683594,+ 133.5095977783203,+ 344.2439880371094+ ],+ "235": [+ 134.66400146484375,+ 327.8039855957031,+ 140.49600219726562,+ 343.5+ ],+ "236": [+ 141.55438232421875,+ 332.5799865722656,+ 151.80239868164062,+ 343.6199951171875+ ],+ "237": [+ 153.34078979492188,+ 332.60400390625,+ 162.6287841796875,+ 343.6440124511719+ ],+ "238": [+ 163.4471893310547,+ 325.6679992675781,+ 175.73519897460938,+ 343.5+ ],+ "239": [+ 176.62557983398438,+ 332.6759948730469,+ 185.76959228515625,+ 343.6679992675781+ ],+ "240": [+ 186.46798706054688,+ 332.50799560546875,+ 204.58799743652344,+ 343.5+ ],+ "241": [+ 205.1423797607422,+ 327.8039855957031,+ 210.97438049316406,+ 343.5+ ],+ "242": [+ 212.24879455566406,+ 332.74798583984375,+ 219.9287872314453,+ 343.6440124511719+ ],+ "243": [+ 221.34719848632812,+ 330.5880126953125,+ 228.85919189453125,+ 343.6919860839844+ ],+ "244": [+ 229.60560607910156,+ 332.4599914550781,+ 237.8376007080078,+ 343.5+ ],+ "245": [+ 238.1280059814453,+ 332.7959899902344,+ 249.1199951171875,+ 349.5719909667969+ ],+ "246": [+ 249.24240112304688,+ 343.47601318359375,+ 254.37840270996094,+ 343.5+ ],+ "247": [+ 254.95201110839844,+ 330.5880126953125,+ 262.4639892578125,+ 343.6919860839844+ ],+ "248": [+ 263.64239501953125,+ 332.6759948730469,+ 272.78643798828125,+ 343.6679992675781+ ],+ "249": [+ 273.2928466796875,+ 332.7959899902344,+ 285.724853515625,+ 343.5+ ],+ "250": [+ 286.4232482910156,+ 330.5880126953125,+ 293.93524169921875,+ 343.6919860839844+ ],+ "251": [+ 294.441650390625,+ 325.7640075683594,+ 306.3216552734375,+ 344.2439880371094+ ],+ "252": [+ 307.86004638671875,+ 332.5799865722656,+ 318.1080322265625,+ 343.6199951171875+ ],+ "253": [+ 319.6464538574219,+ 332.5799865722656,+ 329.89447021484375,+ 343.6199951171875+ ],+ "254": [+ 330.9288330078125,+ 325.81201171875,+ 343.5048828125,+ 343.5+ ]+ },+ "origins": {+ "228": [+ 64.86000061035156,+ 343.5+ ],+ "229": [+ 75.1343994140625,+ 343.5+ ],+ "230": [+ 86.15280151367188,+ 343.5+ ],+ "231": [+ 96.42720031738281,+ 343.5+ ],+ "232": [+ 105.16560363769531,+ 343.5+ ],+ "233": [+ 116.39999389648438,+ 343.5+ ],+ "234": [+ 121.5335922241211,+ 343.5+ ],+ "235": [+ 134.27999877929688,+ 343.5+ ],+ "236": [+ 140.78639221191406,+ 343.5+ ],+ "237": [+ 152.57278442382812,+ 343.5+ ],+ "238": [+ 163.1591796875,+ 343.5+ ],+ "239": [+ 175.8575897216797,+ 343.5+ ],+ "240": [+ 186.13198852539062,+ 343.5+ ],+ "241": [+ 204.75839233398438,+ 343.5+ ],+ "242": [+ 211.26478576660156,+ 343.5+ ],+ "243": [+ 220.7711944580078,+ 343.5+ ],+ "244": [+ 229.2696075439453,+ 343.5+ ],+ "245": [+ 238.00799560546875,+ 343.5+ ],+ "246": [+ 249.24240112304688,+ 343.5+ ],+ "247": [+ 254.3760223388672,+ 343.5+ ],+ "248": [+ 262.8744201660156,+ 343.5+ ],+ "249": [+ 273.1488342285156,+ 343.5+ ],+ "250": [+ 285.84722900390625,+ 343.5+ ],+ "251": [+ 294.34564208984375,+ 343.5+ ],+ "252": [+ 307.092041015625,+ 343.5+ ],+ "253": [+ 318.87847900390625,+ 343.5+ ],+ "254": [+ 330.66485595703125,+ 343.5+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 330.66485595703125,+ 344.0400085449219,+ 330.66485595703125,+ 344.0400085449219+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 255,+ "source_indices": [+ 255+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 330.66485595703125,+ 344.0400085449219+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "255": [+ 330.66485595703125,+ 344.0400085449219+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 349.6080322265625,+ 332.5799865722656,+ 359.85601806640625,+ 343.6199951171875+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 256,+ "source_indices": [+ 256+ ],+ "raw_code": 111,+ "loose_bbox": [+ 348.840087890625,+ 322.3800048828125,+ 360.62408447265625,+ 349.6199951171875+ ],+ "tight_bbox": [+ 349.6080322265625,+ 332.5799865722656,+ 359.85601806640625,+ 343.6199951171875+ ],+ "origin": [+ 348.84002685546875,+ 343.5+ ]+ },+ {+ "bbox": [+ 361.0392150878906,+ 332.5320129394531,+ 373.20721435546875,+ 343.5+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 257,+ "source_indices": [+ 257+ ],+ "raw_code": 110,+ "loose_bbox": [+ 360.6072692871094,+ 322.3800048828125,+ 373.3992919921875,+ 349.6199951171875+ ],+ "tight_bbox": [+ 361.0392150878906,+ 332.5320129394531,+ 373.20721435546875,+ 343.5+ ],+ "origin": [+ 360.60723876953125,+ 343.5+ ]+ },+ {+ "bbox": [+ 373.3824157714844,+ 343.47601318359375,+ 378.5184326171875,+ 343.5+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 258,+ "source_indices": [+ 258+ ],+ "raw_code": 32,+ "loose_bbox": [+ 373.3824157714844,+ 322.3800048828125,+ 378.5184631347656,+ 349.6199951171875+ ],+ "tight_bbox": [+ 373.3824157714844,+ 343.47601318359375,+ 378.5184326171875,+ 343.5+ ],+ "origin": [+ 373.3824157714844,+ 343.5+ ]+ },+ {+ "bbox": [+ 379.1208190917969,+ 330.5880126953125,+ 386.6328125,+ 343.6919860839844+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 259,+ "source_indices": [+ 259+ ],+ "raw_code": 116,+ "loose_bbox": [+ 378.54486083984375,+ 322.3800048828125,+ 387.0408630371094,+ 349.6199951171875+ ],+ "tight_bbox": [+ 379.1208190917969,+ 330.5880126953125,+ 386.6328125,+ 343.6919860839844+ ],+ "origin": [+ 378.5448303222656,+ 343.5+ ]+ },+ {+ "bbox": [+ 387.31201171875,+ 325.6679992675781,+ 399.60003662109375,+ 343.5+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 260,+ "source_indices": [+ 260+ ],+ "raw_code": 104,+ "loose_bbox": [+ 387.0240478515625,+ 322.3800048828125,+ 399.7200622558594,+ 349.6199951171875+ ],+ "tight_bbox": [+ 387.31201171875,+ 325.6679992675781,+ 399.60003662109375,+ 343.5+ ],+ "origin": [+ 387.0240173339844,+ 343.5+ ]+ },+ {+ "bbox": [+ 400.4712219238281,+ 332.6759948730469,+ 409.615234375,+ 343.6679992675781+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 261,+ "source_indices": [+ 261+ ],+ "raw_code": 101,+ "loose_bbox": [+ 399.7032470703125,+ 322.3800048828125,+ 409.9752502441406,+ 349.6199951171875+ ],+ "tight_bbox": [+ 400.4712219238281,+ 332.6759948730469,+ 409.615234375,+ 343.6679992675781+ ],+ "origin": [+ 399.7032165527344,+ 343.5+ ]+ },+ {+ "bbox": [+ 409.95843505859375,+ 343.47601318359375,+ 415.09442138671875,+ 343.5+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 262,+ "source_indices": [+ 262+ ],+ "raw_code": 32,+ "loose_bbox": [+ 409.95843505859375,+ 322.3800048828125,+ 415.094482421875,+ 349.6199951171875+ ],+ "tight_bbox": [+ 409.95843505859375,+ 343.47601318359375,+ 415.09442138671875,+ 343.5+ ],+ "origin": [+ 409.95843505859375,+ 343.5+ ]+ }+ ],+ "tight_bboxes": {+ "256": [+ 349.6080322265625,+ 332.5799865722656,+ 359.85601806640625,+ 343.6199951171875+ ],+ "257": [+ 361.0392150878906,+ 332.5320129394531,+ 373.20721435546875,+ 343.5+ ],+ "258": [+ 373.3824157714844,+ 343.47601318359375,+ 378.5184326171875,+ 343.5+ ],+ "259": [+ 379.1208190917969,+ 330.5880126953125,+ 386.6328125,+ 343.6919860839844+ ],+ "260": [+ 387.31201171875,+ 325.6679992675781,+ 399.60003662109375,+ 343.5+ ],+ "261": [+ 400.4712219238281,+ 332.6759948730469,+ 409.615234375,+ 343.6679992675781+ ],+ "262": [+ 409.95843505859375,+ 343.47601318359375,+ 415.09442138671875,+ 343.5+ ]+ },+ "origins": {+ "256": [+ 348.84002685546875,+ 343.5+ ],+ "257": [+ 360.60723876953125,+ 343.5+ ],+ "258": [+ 373.3824157714844,+ 343.5+ ],+ "259": [+ 378.5448303222656,+ 343.5+ ],+ "260": [+ 387.0240173339844,+ 343.5+ ],+ "261": [+ 399.7032165527344,+ 343.5+ ],+ "262": [+ 409.95843505859375,+ 343.5+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 409.95843505859375,+ 343.7139892578125,+ 409.95843505859375,+ 343.7139892578125+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 263,+ "source_indices": [+ 263+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 409.95843505859375,+ 343.7139892578125+ ]+ },+ {+ "bbox": [+ 409.95843505859375,+ 343.7139892578125,+ 409.95843505859375,+ 343.7139892578125+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 264,+ "source_indices": [+ 264+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 409.95843505859375,+ 343.7139892578125+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "263": [+ 409.95843505859375,+ 343.7139892578125+ ],+ "264": [+ 409.95843505859375,+ 343.7139892578125+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 65.00399780273438,+ 361.33203125,+ 77.07600402832031,+ 378.37200927734375+ ],+ "char": "p",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 265,+ "source_indices": [+ 265+ ],+ "raw_code": 112,+ "loose_bbox": [+ 64.86000061035156,+ 351.1800231933594,+ 77.84400177001953,+ 378.4200134277344+ ],+ "tight_bbox": [+ 65.00399780273438,+ 361.33203125,+ 77.07600402832031,+ 378.37200927734375+ ],+ "origin": [+ 64.86000061035156,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 78.17759704589844,+ 361.260009765625,+ 86.40959930419922,+ 372.3000183105469+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 266,+ "source_indices": [+ 266+ ],+ "raw_code": 114,+ "loose_bbox": [+ 77.84159851074219,+ 351.1800231933594,+ 86.57759857177734,+ 378.4200134277344+ ],+ "tight_bbox": [+ 78.17759704589844,+ 361.260009765625,+ 86.40959930419922,+ 372.3000183105469+ ],+ "origin": [+ 77.84159851074219,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 87.34320068359375,+ 361.3800048828125,+ 97.59120178222656,+ 372.4200134277344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 267,+ "source_indices": [+ 267+ ],+ "raw_code": 111,+ "loose_bbox": [+ 86.5751953125,+ 351.1800231933594,+ 98.35919189453125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 87.34320068359375,+ 361.3800048828125,+ 97.59120178222656,+ 372.4200134277344+ ],+ "origin": [+ 86.5751953125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 99.12479400634766,+ 361.4040222167969,+ 108.41279602050781,+ 372.44403076171875+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 268,+ "source_indices": [+ 268+ ],+ "raw_code": 99,+ "loose_bbox": [+ 98.35679626464844,+ 351.1800231933594,+ 108.9407958984375,+ 378.4200134277344+ ],+ "tight_bbox": [+ 99.12479400634766,+ 361.4040222167969,+ 108.41279602050781,+ 372.44403076171875+ ],+ "origin": [+ 98.35679626464844,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 109.70639038085938,+ 361.47601318359375,+ 118.85040283203125,+ 372.468017578125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 269,+ "source_indices": [+ 269+ ],+ "raw_code": 101,+ "loose_bbox": [+ 108.93840026855469,+ 351.1800231933594,+ 119.21040344238281,+ 378.4200134277344+ ],+ "tight_bbox": [+ 109.70639038085938,+ 361.47601318359375,+ 118.85040283203125,+ 372.468017578125+ ],+ "origin": [+ 108.93840026855469,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 120.1919937133789,+ 361.5480041503906,+ 127.87200164794922,+ 372.44403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 270,+ "source_indices": [+ 270+ ],+ "raw_code": 115,+ "loose_bbox": [+ 119.20800018310547,+ 351.1800231933594,+ 128.71200561523438,+ 378.4200134277344+ ],+ "tight_bbox": [+ 120.1919937133789,+ 361.5480041503906,+ 127.87200164794922,+ 372.44403076171875+ ],+ "origin": [+ 119.20800018310547,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 129.693603515625,+ 361.5480041503906,+ 137.37359619140625,+ 372.44403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 271,+ "source_indices": [+ 271+ ],+ "raw_code": 115,+ "loose_bbox": [+ 128.7095947265625,+ 351.1800231933594,+ 138.21359252929688,+ 378.4200134277344+ ],+ "tight_bbox": [+ 129.693603515625,+ 361.5480041503906,+ 137.37359619140625,+ 372.44403076171875+ ],+ "origin": [+ 128.7095947265625,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 138.9792022705078,+ 361.47601318359375,+ 148.12319946289062,+ 372.468017578125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 272,+ "source_indices": [+ 272+ ],+ "raw_code": 101,+ "loose_bbox": [+ 138.21119689941406,+ 351.1800231933594,+ 148.4832000732422,+ 378.4200134277344+ ],+ "tight_bbox": [+ 138.9792022705078,+ 361.47601318359375,+ 148.12319946289062,+ 372.468017578125+ ],+ "origin": [+ 138.21119689941406,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 149.4647979736328,+ 361.5480041503906,+ 157.14480590820312,+ 372.44403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 273,+ "source_indices": [+ 273+ ],+ "raw_code": 115,+ "loose_bbox": [+ 148.48080444335938,+ 351.1800231933594,+ 157.98480224609375,+ 378.4200134277344+ ],+ "tight_bbox": [+ 149.4647979736328,+ 361.5480041503906,+ 157.14480590820312,+ 372.44403076171875+ ],+ "origin": [+ 148.48080444335938,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 157.98239135742188,+ 372.2760314941406,+ 163.118408203125,+ 372.3000183105469+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 274,+ "source_indices": [+ 274+ ],+ "raw_code": 32,+ "loose_bbox": [+ 157.98239135742188,+ 351.1800231933594,+ 163.118408203125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 157.98239135742188,+ 372.2760314941406,+ 163.118408203125,+ 372.3000183105469+ ],+ "origin": [+ 157.98239135742188,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 163.91281127929688,+ 361.3800048828125,+ 174.16079711914062,+ 372.4200134277344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 275,+ "source_indices": [+ 275+ ],+ "raw_code": 111,+ "loose_bbox": [+ 163.14480590820312,+ 351.1800231933594,+ 174.92881774902344,+ 378.4200134277344+ ],+ "tight_bbox": [+ 163.91281127929688,+ 361.3800048828125,+ 174.16079711914062,+ 372.4200134277344+ ],+ "origin": [+ 163.14480590820312,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 175.14239501953125,+ 354.44403076171875,+ 182.67840576171875,+ 372.3000183105469+ ],+ "char": "f",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 276,+ "source_indices": [+ 276+ ],+ "raw_code": 102,+ "loose_bbox": [+ 174.92642211914062,+ 351.1800231933594,+ 182.67840576171875,+ 378.4200134277344+ ],+ "tight_bbox": [+ 175.14239501953125,+ 354.44403076171875,+ 182.67840576171875,+ 372.3000183105469+ ],+ "origin": [+ 174.92640686035156,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 181.86000061035156,+ 372.2760314941406,+ 186.99600219726562,+ 372.3000183105469+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 277,+ "source_indices": [+ 277+ ],+ "raw_code": 32,+ "loose_bbox": [+ 181.86000061035156,+ 351.1800231933594,+ 186.99600219726562,+ 378.4200134277344+ ],+ "tight_bbox": [+ 181.86000061035156,+ 372.2760314941406,+ 186.99600219726562,+ 372.3000183105469+ ],+ "origin": [+ 181.86000061035156,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 187.7904052734375,+ 361.47601318359375,+ 196.9344024658203,+ 372.468017578125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 278,+ "source_indices": [+ 278+ ],+ "raw_code": 101,+ "loose_bbox": [+ 187.02239990234375,+ 351.1800231933594,+ 197.29440307617188,+ 378.4200134277344+ ],+ "tight_bbox": [+ 187.7904052734375,+ 361.47601318359375,+ 196.9344024658203,+ 372.468017578125+ ],+ "origin": [+ 187.02239990234375,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 197.72401428222656,+ 361.33203125,+ 209.8920135498047,+ 372.3000183105469+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 279,+ "source_indices": [+ 279+ ],+ "raw_code": 110,+ "loose_bbox": [+ 197.29200744628906,+ 351.1800231933594,+ 210.08401489257812,+ 378.4200134277344+ ],+ "tight_bbox": [+ 197.72401428222656,+ 361.33203125,+ 209.8920135498047,+ 372.3000183105469+ ],+ "origin": [+ 197.29200744628906,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 210.84959411621094,+ 361.47601318359375,+ 219.9936065673828,+ 372.468017578125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 280,+ "source_indices": [+ 280+ ],+ "raw_code": 101,+ "loose_bbox": [+ 210.0816192626953,+ 351.1800231933594,+ 220.35360717773438,+ 378.4200134277344+ ],+ "tight_bbox": [+ 210.84959411621094,+ 361.47601318359375,+ 219.9936065673828,+ 372.468017578125+ ],+ "origin": [+ 210.08160400390625,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 220.68719482421875,+ 361.260009765625,+ 228.919189453125,+ 372.3000183105469+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 281,+ "source_indices": [+ 281+ ],+ "raw_code": 114,+ "loose_bbox": [+ 220.3511962890625,+ 351.1800231933594,+ 229.08718872070312,+ 378.4200134277344+ ],+ "tight_bbox": [+ 220.68719482421875,+ 361.260009765625,+ 228.919189453125,+ 372.3000183105469+ ],+ "origin": [+ 220.3511962890625,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 229.37278747558594,+ 361.35601806640625,+ 240.2447967529297,+ 378.3960266113281+ ],+ "char": "g",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 282,+ "source_indices": [+ 282+ ],+ "raw_code": 103,+ "loose_bbox": [+ 229.0847930908203,+ 351.1800231933594,+ 240.46080017089844,+ 378.4200134277344+ ],+ "tight_bbox": [+ 229.37278747558594,+ 361.35601806640625,+ 240.2447967529297,+ 378.3960266113281+ ],+ "origin": [+ 229.0847930908203,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 240.57838439941406,+ 361.59600830078125,+ 251.5703887939453,+ 378.37200927734375+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 283,+ "source_indices": [+ 283+ ],+ "raw_code": 121,+ "loose_bbox": [+ 240.45838928222656,+ 351.1800231933594,+ 251.69039916992188,+ 378.4200134277344+ ],+ "tight_bbox": [+ 240.57838439941406,+ 361.59600830078125,+ 251.5703887939453,+ 378.37200927734375+ ],+ "origin": [+ 240.45838928222656,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 251.68797302246094,+ 372.2760314941406,+ 256.823974609375,+ 372.3000183105469+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 284,+ "source_indices": [+ 284+ ],+ "raw_code": 32,+ "loose_bbox": [+ 251.68797302246094,+ 351.1800231933594,+ 256.823974609375,+ 378.4200134277344+ ],+ "tight_bbox": [+ 251.68797302246094,+ 372.2760314941406,+ 256.823974609375,+ 372.3000183105469+ ],+ "origin": [+ 251.68797302246094,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 257.1864013671875,+ 361.3080139160156,+ 275.306396484375,+ 372.3000183105469+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 285,+ "source_indices": [+ 285+ ],+ "raw_code": 109,+ "loose_bbox": [+ 256.85040283203125,+ 351.1800231933594,+ 275.47442626953125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 257.1864013671875,+ 361.3080139160156,+ 275.306396484375,+ 372.3000183105469+ ],+ "origin": [+ 256.85040283203125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 276.239990234375,+ 361.47601318359375,+ 285.38397216796875,+ 372.468017578125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 286,+ "source_indices": [+ 286+ ],+ "raw_code": 101,+ "loose_bbox": [+ 275.47198486328125,+ 351.1800231933594,+ 285.7440185546875,+ 378.4200134277344+ ],+ "tight_bbox": [+ 276.239990234375,+ 361.47601318359375,+ 285.38397216796875,+ 372.468017578125+ ],+ "origin": [+ 275.47198486328125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 286.3175964355469,+ 359.3880310058594,+ 293.82958984375,+ 372.49200439453125+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 287,+ "source_indices": [+ 287+ ],+ "raw_code": 116,+ "loose_bbox": [+ 285.7415771484375,+ 351.1800231933594,+ 294.237548828125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 286.3175964355469,+ 359.3880310058594,+ 293.82958984375,+ 372.49200439453125+ ],+ "origin": [+ 285.7415771484375,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 295.29119873046875,+ 361.6200256347656,+ 304.48321533203125,+ 372.5880126953125+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 288,+ "source_indices": [+ 288+ ],+ "raw_code": 97,+ "loose_bbox": [+ 294.23516845703125,+ 351.1800231933594,+ 304.81915283203125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 295.29119873046875,+ 361.6200256347656,+ 304.48321533203125,+ 372.5880126953125+ ],+ "origin": [+ 294.23516845703125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 304.91278076171875,+ 354.56402587890625,+ 316.79278564453125,+ 373.04400634765625+ ],+ "char": "b",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 289,+ "source_indices": [+ 289+ ],+ "raw_code": 98,+ "loose_bbox": [+ 304.8167724609375,+ 351.1800231933594,+ 317.560791015625,+ 378.4200134277344+ ],+ "tight_bbox": [+ 304.91278076171875,+ 354.56402587890625,+ 316.79278564453125,+ 373.04400634765625+ ],+ "origin": [+ 304.8167724609375,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 318.32635498046875,+ 361.3800048828125,+ 328.57440185546875,+ 372.4200134277344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 290,+ "source_indices": [+ 290+ ],+ "raw_code": 111,+ "loose_bbox": [+ 317.55841064453125,+ 351.1800231933594,+ 329.3424072265625,+ 378.4200134277344+ ],+ "tight_bbox": [+ 318.32635498046875,+ 361.3800048828125,+ 328.57440185546875,+ 372.4200134277344+ ],+ "origin": [+ 317.55841064453125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 329.50799560546875,+ 354.5880126953125,+ 335.60400390625,+ 372.3000183105469+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 291,+ "source_indices": [+ 291+ ],+ "raw_code": 108,+ "loose_bbox": [+ 329.3399658203125,+ 351.1800231933594,+ 335.79595947265625,+ 378.4200134277344+ ],+ "tight_bbox": [+ 329.50799560546875,+ 354.5880126953125,+ 335.60400390625,+ 372.3000183105469+ ],+ "origin": [+ 329.3399658203125,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 336.17755126953125,+ 356.60400390625,+ 342.00958251953125,+ 372.3000183105469+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 292,+ "source_indices": [+ 292+ ],+ "raw_code": 105,+ "loose_bbox": [+ 335.7935791015625,+ 351.1800231933594,+ 342.297607421875,+ 378.4200134277344+ ],+ "tight_bbox": [+ 336.17755126953125,+ 356.60400390625,+ 342.00958251953125,+ 372.3000183105469+ ],+ "origin": [+ 335.7935791015625,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 343.2791748046875,+ 361.5480041503906,+ 350.95916748046875,+ 372.44403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 293,+ "source_indices": [+ 293+ ],+ "raw_code": 115,+ "loose_bbox": [+ 342.295166015625,+ 351.1800231933594,+ 351.79913330078125,+ 378.4200134277344+ ],+ "tight_bbox": [+ 343.2791748046875,+ 361.5480041503906,+ 350.95916748046875,+ 372.44403076171875+ ],+ "origin": [+ 342.295166015625,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 352.13275146484375,+ 361.3080139160156,+ 370.25274658203125,+ 372.3000183105469+ ],+ "char": "m",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 294,+ "source_indices": [+ 294+ ],+ "raw_code": 109,+ "loose_bbox": [+ 351.7967529296875,+ 351.1800231933594,+ 370.4207763671875,+ 378.4200134277344+ ],+ "tight_bbox": [+ 352.13275146484375,+ 361.3080139160156,+ 370.25274658203125,+ 372.3000183105469+ ],+ "origin": [+ 351.7967529296875,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 371.8583984375,+ 361.572021484375,+ 374.01837158203125,+ 372.3000183105469+ ],+ "char": ":",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 295,+ "source_indices": [+ 295+ ],+ "raw_code": 58,+ "loose_bbox": [+ 370.41839599609375,+ 351.1800231933594,+ 375.55438232421875,+ 378.4200134277344+ ],+ "tight_bbox": [+ 371.8583984375,+ 361.572021484375,+ 374.01837158203125,+ 372.3000183105469+ ],+ "origin": [+ 370.41839599609375,+ 372.3000183105469+ ]+ },+ {+ "bbox": [+ 375.55194091796875,+ 372.2760314941406,+ 380.68792724609375,+ 372.3000183105469+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 296,+ "source_indices": [+ 296+ ],+ "raw_code": 32,+ "loose_bbox": [+ 375.55194091796875,+ 351.1800231933594,+ 380.68792724609375,+ 378.4200134277344+ ],+ "tight_bbox": [+ 375.55194091796875,+ 372.2760314941406,+ 380.68792724609375,+ 372.3000183105469+ ],+ "origin": [+ 375.55194091796875,+ 372.3000183105469+ ]+ }+ ],+ "tight_bboxes": {+ "265": [+ 65.00399780273438,+ 361.33203125,+ 77.07600402832031,+ 378.37200927734375+ ],+ "266": [+ 78.17759704589844,+ 361.260009765625,+ 86.40959930419922,+ 372.3000183105469+ ],+ "267": [+ 87.34320068359375,+ 361.3800048828125,+ 97.59120178222656,+ 372.4200134277344+ ],+ "268": [+ 99.12479400634766,+ 361.4040222167969,+ 108.41279602050781,+ 372.44403076171875+ ],+ "269": [+ 109.70639038085938,+ 361.47601318359375,+ 118.85040283203125,+ 372.468017578125+ ],+ "270": [+ 120.1919937133789,+ 361.5480041503906,+ 127.87200164794922,+ 372.44403076171875+ ],+ "271": [+ 129.693603515625,+ 361.5480041503906,+ 137.37359619140625,+ 372.44403076171875+ ],+ "272": [+ 138.9792022705078,+ 361.47601318359375,+ 148.12319946289062,+ 372.468017578125+ ],+ "273": [+ 149.4647979736328,+ 361.5480041503906,+ 157.14480590820312,+ 372.44403076171875+ ],+ "274": [+ 157.98239135742188,+ 372.2760314941406,+ 163.118408203125,+ 372.3000183105469+ ],+ "275": [+ 163.91281127929688,+ 361.3800048828125,+ 174.16079711914062,+ 372.4200134277344+ ],+ "276": [+ 175.14239501953125,+ 354.44403076171875,+ 182.67840576171875,+ 372.3000183105469+ ],+ "277": [+ 181.86000061035156,+ 372.2760314941406,+ 186.99600219726562,+ 372.3000183105469+ ],+ "278": [+ 187.7904052734375,+ 361.47601318359375,+ 196.9344024658203,+ 372.468017578125+ ],+ "279": [+ 197.72401428222656,+ 361.33203125,+ 209.8920135498047,+ 372.3000183105469+ ],+ "280": [+ 210.84959411621094,+ 361.47601318359375,+ 219.9936065673828,+ 372.468017578125+ ],+ "281": [+ 220.68719482421875,+ 361.260009765625,+ 228.919189453125,+ 372.3000183105469+ ],+ "282": [+ 229.37278747558594,+ 361.35601806640625,+ 240.2447967529297,+ 378.3960266113281+ ],+ "283": [+ 240.57838439941406,+ 361.59600830078125,+ 251.5703887939453,+ 378.37200927734375+ ],+ "284": [+ 251.68797302246094,+ 372.2760314941406,+ 256.823974609375,+ 372.3000183105469+ ],+ "285": [+ 257.1864013671875,+ 361.3080139160156,+ 275.306396484375,+ 372.3000183105469+ ],+ "286": [+ 276.239990234375,+ 361.47601318359375,+ 285.38397216796875,+ 372.468017578125+ ],+ "287": [+ 286.3175964355469,+ 359.3880310058594,+ 293.82958984375,+ 372.49200439453125+ ],+ "288": [+ 295.29119873046875,+ 361.6200256347656,+ 304.48321533203125,+ 372.5880126953125+ ],+ "289": [+ 304.91278076171875,+ 354.56402587890625,+ 316.79278564453125,+ 373.04400634765625+ ],+ "290": [+ 318.32635498046875,+ 361.3800048828125,+ 328.57440185546875,+ 372.4200134277344+ ],+ "291": [+ 329.50799560546875,+ 354.5880126953125,+ 335.60400390625,+ 372.3000183105469+ ],+ "292": [+ 336.17755126953125,+ 356.60400390625,+ 342.00958251953125,+ 372.3000183105469+ ],+ "293": [+ 343.2791748046875,+ 361.5480041503906,+ 350.95916748046875,+ 372.44403076171875+ ],+ "294": [+ 352.13275146484375,+ 361.3080139160156,+ 370.25274658203125,+ 372.3000183105469+ ],+ "295": [+ 371.8583984375,+ 361.572021484375,+ 374.01837158203125,+ 372.3000183105469+ ],+ "296": [+ 375.55194091796875,+ 372.2760314941406,+ 380.68792724609375,+ 372.3000183105469+ ]+ },+ "origins": {+ "265": [+ 64.86000061035156,+ 372.3000183105469+ ],+ "266": [+ 77.84159851074219,+ 372.3000183105469+ ],+ "267": [+ 86.5751953125,+ 372.3000183105469+ ],+ "268": [+ 98.35679626464844,+ 372.3000183105469+ ],+ "269": [+ 108.93840026855469,+ 372.3000183105469+ ],+ "270": [+ 119.20800018310547,+ 372.3000183105469+ ],+ "271": [+ 128.7095947265625,+ 372.3000183105469+ ],+ "272": [+ 138.21119689941406,+ 372.3000183105469+ ],+ "273": [+ 148.48080444335938,+ 372.3000183105469+ ],+ "274": [+ 157.98239135742188,+ 372.3000183105469+ ],+ "275": [+ 163.14480590820312,+ 372.3000183105469+ ],+ "276": [+ 174.92640686035156,+ 372.3000183105469+ ],+ "277": [+ 181.86000061035156,+ 372.3000183105469+ ],+ "278": [+ 187.02239990234375,+ 372.3000183105469+ ],+ "279": [+ 197.29200744628906,+ 372.3000183105469+ ],+ "280": [+ 210.08160400390625,+ 372.3000183105469+ ],+ "281": [+ 220.3511962890625,+ 372.3000183105469+ ],+ "282": [+ 229.0847930908203,+ 372.3000183105469+ ],+ "283": [+ 240.45838928222656,+ 372.3000183105469+ ],+ "284": [+ 251.68797302246094,+ 372.3000183105469+ ],+ "285": [+ 256.85040283203125,+ 372.3000183105469+ ],+ "286": [+ 275.47198486328125,+ 372.3000183105469+ ],+ "287": [+ 285.7415771484375,+ 372.3000183105469+ ],+ "288": [+ 294.23516845703125,+ 372.3000183105469+ ],+ "289": [+ 304.8167724609375,+ 372.3000183105469+ ],+ "290": [+ 317.55841064453125,+ 372.3000183105469+ ],+ "291": [+ 329.3399658203125,+ 372.3000183105469+ ],+ "292": [+ 335.7935791015625,+ 372.3000183105469+ ],+ "293": [+ 342.295166015625,+ 372.3000183105469+ ],+ "294": [+ 351.7967529296875,+ 372.3000183105469+ ],+ "295": [+ 370.41839599609375,+ 372.3000183105469+ ],+ "296": [+ 375.55194091796875,+ 372.3000183105469+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 375.55194091796875,+ 372.5140075683594,+ 375.55194091796875,+ 372.5140075683594+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 297,+ "source_indices": [+ 297+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 375.55194091796875,+ 372.5140075683594+ ]+ },+ {+ "bbox": [+ 375.55194091796875,+ 372.5140075683594,+ 375.55194091796875,+ 372.5140075683594+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 298,+ "source_indices": [+ 298+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 375.55194091796875,+ 372.5140075683594+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "297": [+ 375.55194091796875,+ 372.5140075683594+ ],+ "298": [+ 375.55194091796875,+ 372.5140075683594+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 133.90798950195312,+ 406.0080261230469,+ 140.531982421875,+ 421.8000183105469+ ],+ "char": "1",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 299,+ "source_indices": [+ 299+ ],+ "raw_code": 49,+ "loose_bbox": [+ 133.01998901367188,+ 400.6800231933594,+ 141.17999267578125,+ 427.9200134277344+ ],+ "tight_bbox": [+ 133.90798950195312,+ 406.0080261230469,+ 140.531982421875,+ 421.8000183105469+ ],+ "origin": [+ 133.01998901367188,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 141.9359893798828,+ 404.2320251464844,+ 149.0399932861328,+ 427.6080322265625+ ],+ "char": ")",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 300,+ "source_indices": [+ 300+ ],+ "raw_code": 41,+ "loose_bbox": [+ 141.19198608398438,+ 400.6800231933594,+ 150.43199157714844,+ 427.9200134277344+ ],+ "tight_bbox": [+ 141.9359893798828,+ 404.2320251464844,+ 149.0399932861328,+ 427.6080322265625+ ],+ "origin": [+ 141.19198608398438,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 150.44398498535156,+ 421.7760314941406,+ 155.57998657226562,+ 421.8000183105469+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 301,+ "source_indices": [+ 301+ ],+ "raw_code": 32,+ "loose_bbox": [+ 150.44398498535156,+ 400.6800231933594,+ 155.57998657226562,+ 427.9200134277344+ ],+ "tight_bbox": [+ 150.44398498535156,+ 421.7760314941406,+ 155.57998657226562,+ 421.8000183105469+ ],+ "origin": [+ 150.44398498535156,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 156.494384765625,+ 405.864013671875,+ 172.33438110351562,+ 421.94403076171875+ ],+ "char": "G",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 302,+ "source_indices": [+ 302+ ],+ "raw_code": 71,+ "loose_bbox": [+ 155.60638427734375,+ 400.6800231933594,+ 173.07839965820312,+ 427.9200134277344+ ],+ "tight_bbox": [+ 156.494384765625,+ 405.864013671875,+ 172.33438110351562,+ 421.94403076171875+ ],+ "origin": [+ 155.60638427734375,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 173.25839233398438,+ 404.0880126953125,+ 179.35438537597656,+ 421.8000183105469+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 303,+ "source_indices": [+ 303+ ],+ "raw_code": 108,+ "loose_bbox": [+ 173.09039306640625,+ 400.6800231933594,+ 179.54640197753906,+ 427.9200134277344+ ],+ "tight_bbox": [+ 173.25839233398438,+ 404.0880126953125,+ 179.35438537597656,+ 421.8000183105469+ ],+ "origin": [+ 173.09039306640625,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 179.6783905029297,+ 411.09600830078125,+ 190.67039489746094,+ 427.87200927734375+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 304,+ "source_indices": [+ 304+ ],+ "raw_code": 121,+ "loose_bbox": [+ 179.55838012695312,+ 400.6800231933594,+ 190.79037475585938,+ 427.9200134277344+ ],+ "tight_bbox": [+ 179.6783905029297,+ 411.09600830078125,+ 190.67039489746094,+ 427.87200927734375+ ],+ "origin": [+ 179.55838012695312,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 191.5703887939453,+ 410.9040222167969,+ 200.8583984375,+ 421.94403076171875+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 305,+ "source_indices": [+ 305+ ],+ "raw_code": 99,+ "loose_bbox": [+ 190.80238342285156,+ 400.6800231933594,+ 201.38638305664062,+ 427.9200134277344+ ],+ "tight_bbox": [+ 191.5703887939453,+ 410.9040222167969,+ 200.8583984375,+ 421.94403076171875+ ],+ "origin": [+ 190.80238342285156,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 202.1663818359375,+ 410.8800048828125,+ 212.41439819335938,+ 421.9200134277344+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 306,+ "source_indices": [+ 306+ ],+ "raw_code": 111,+ "loose_bbox": [+ 201.3983917236328,+ 400.6800231933594,+ 213.18238830566406,+ 427.9200134277344+ ],+ "tight_bbox": [+ 202.1663818359375,+ 410.8800048828125,+ 212.41439819335938,+ 421.9200134277344+ ],+ "origin": [+ 201.39837646484375,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 213.3623809814453,+ 404.0880126953125,+ 219.4583740234375,+ 421.8000183105469+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 307,+ "source_indices": [+ 307+ ],+ "raw_code": 108,+ "loose_bbox": [+ 213.19439697265625,+ 400.6800231933594,+ 219.650390625,+ 427.9200134277344+ ],+ "tight_bbox": [+ 213.3623809814453,+ 404.0880126953125,+ 219.4583740234375,+ 421.8000183105469+ ],+ "origin": [+ 213.1943817138672,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 219.78237915039062,+ 411.09600830078125,+ 230.77438354492188,+ 427.87200927734375+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 308,+ "source_indices": [+ 308+ ],+ "raw_code": 121,+ "loose_bbox": [+ 219.66238403320312,+ 400.6800231933594,+ 230.89437866210938,+ 427.9200134277344+ ],+ "tight_bbox": [+ 219.78237915039062,+ 411.09600830078125,+ 230.77438354492188,+ 427.87200927734375+ ],+ "origin": [+ 219.66238403320312,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 231.890380859375,+ 411.0480041503906,+ 239.5703887939453,+ 421.94403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 309,+ "source_indices": [+ 309+ ],+ "raw_code": 115,+ "loose_bbox": [+ 230.90638732910156,+ 400.6800231933594,+ 240.41038513183594,+ 427.9200134277344+ ],+ "tight_bbox": [+ 231.890380859375,+ 411.0480041503906,+ 239.5703887939453,+ 421.94403076171875+ ],+ "origin": [+ 230.90638732910156,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 240.80638122558594,+ 406.10400390625,+ 246.6383819580078,+ 421.8000183105469+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 310,+ "source_indices": [+ 310+ ],+ "raw_code": 105,+ "loose_bbox": [+ 240.42239379882812,+ 400.6800231933594,+ 246.9263916015625,+ 427.9200134277344+ ],+ "tight_bbox": [+ 240.80638122558594,+ 406.10400390625,+ 246.6383819580078,+ 421.8000183105469+ ],+ "origin": [+ 240.42239379882812,+ 421.8000183105469+ ]+ },+ {+ "bbox": [+ 247.92239379882812,+ 411.0480041503906,+ 255.60238647460938,+ 421.94403076171875+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 311,+ "source_indices": [+ 311+ ],+ "raw_code": 115,+ "loose_bbox": [+ 246.93838500976562,+ 400.6800231933594,+ 256.4423828125,+ 427.9200134277344+ ],+ "tight_bbox": [+ 247.92239379882812,+ 411.0480041503906,+ 255.60238647460938,+ 421.94403076171875+ ],+ "origin": [+ 246.93838500976562,+ 421.8000183105469+ ]+ }+ ],+ "tight_bboxes": {+ "299": [+ 133.90798950195312,+ 406.0080261230469,+ 140.531982421875,+ 421.8000183105469+ ],+ "300": [+ 141.9359893798828,+ 404.2320251464844,+ 149.0399932861328,+ 427.6080322265625+ ],+ "301": [+ 150.44398498535156,+ 421.7760314941406,+ 155.57998657226562,+ 421.8000183105469+ ],+ "302": [+ 156.494384765625,+ 405.864013671875,+ 172.33438110351562,+ 421.94403076171875+ ],+ "303": [+ 173.25839233398438,+ 404.0880126953125,+ 179.35438537597656,+ 421.8000183105469+ ],+ "304": [+ 179.6783905029297,+ 411.09600830078125,+ 190.67039489746094,+ 427.87200927734375+ ],+ "305": [+ 191.5703887939453,+ 410.9040222167969,+ 200.8583984375,+ 421.94403076171875+ ],+ "306": [+ 202.1663818359375,+ 410.8800048828125,+ 212.41439819335938,+ 421.9200134277344+ ],+ "307": [+ 213.3623809814453,+ 404.0880126953125,+ 219.4583740234375,+ 421.8000183105469+ ],+ "308": [+ 219.78237915039062,+ 411.09600830078125,+ 230.77438354492188,+ 427.87200927734375+ ],+ "309": [+ 231.890380859375,+ 411.0480041503906,+ 239.5703887939453,+ 421.94403076171875+ ],+ "310": [+ 240.80638122558594,+ 406.10400390625,+ 246.6383819580078,+ 421.8000183105469+ ],+ "311": [+ 247.92239379882812,+ 411.0480041503906,+ 255.60238647460938,+ 421.94403076171875+ ]+ },+ "origins": {+ "299": [+ 133.01998901367188,+ 421.8000183105469+ ],+ "300": [+ 141.19198608398438,+ 421.8000183105469+ ],+ "301": [+ 150.44398498535156,+ 421.8000183105469+ ],+ "302": [+ 155.60638427734375,+ 421.8000183105469+ ],+ "303": [+ 173.09039306640625,+ 421.8000183105469+ ],+ "304": [+ 179.55838012695312,+ 421.8000183105469+ ],+ "305": [+ 190.80238342285156,+ 421.8000183105469+ ],+ "306": [+ 201.39837646484375,+ 421.8000183105469+ ],+ "307": [+ 213.1943817138672,+ 421.8000183105469+ ],+ "308": [+ 219.66238403320312,+ 421.8000183105469+ ],+ "309": [+ 230.90638732910156,+ 421.8000183105469+ ],+ "310": [+ 240.42239379882812,+ 421.8000183105469+ ],+ "311": [+ 246.93838500976562,+ 421.8000183105469+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 246.93838500976562,+ 422.1960144042969,+ 246.93838500976562,+ 422.1960144042969+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 312,+ "source_indices": [+ 312+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 246.93838500976562,+ 422.1960144042969+ ]+ },+ {+ "bbox": [+ 246.93838500976562,+ 422.1960144042969,+ 246.93838500976562,+ 422.1960144042969+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 313,+ "source_indices": [+ 313+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 246.93838500976562,+ 422.1960144042969+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "312": [+ 246.93838500976562,+ 422.1960144042969+ ],+ "313": [+ 246.93838500976562,+ 422.1960144042969+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 132.36000061035156,+ 449.0160217285156,+ 142.2239990234375,+ 464.760009765625+ ],+ "char": "2",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 314,+ "source_indices": [+ 314+ ],+ "raw_code": 50,+ "loose_bbox": [+ 131.28001403808594,+ 443.6400451660156,+ 143.2320098876953,+ 470.88006591796875+ ],+ "tight_bbox": [+ 132.36000061035156,+ 449.0160217285156,+ 142.2239990234375,+ 464.760009765625+ ],+ "origin": [+ 131.27999877929688,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 143.98080444335938,+ 447.1920166015625,+ 151.0847930908203,+ 470.5680236816406+ ],+ "char": ")",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 315,+ "source_indices": [+ 315+ ],+ "raw_code": 41,+ "loose_bbox": [+ 143.23681640625,+ 443.6400451660156,+ 152.476806640625,+ 470.88006591796875+ ],+ "tight_bbox": [+ 143.98080444335938,+ 447.1920166015625,+ 151.0847930908203,+ 470.5680236816406+ ],+ "origin": [+ 143.23680114746094,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 152.48159790039062,+ 464.73602294921875,+ 157.6175994873047,+ 464.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 316,+ "source_indices": [+ 316+ ],+ "raw_code": 32,+ "loose_bbox": [+ 152.48159790039062,+ 443.6400451660156,+ 157.61761474609375,+ 470.88006591796875+ ],+ "tight_bbox": [+ 152.48159790039062,+ 464.73602294921875,+ 157.6175994873047,+ 464.760009765625+ ],+ "origin": [+ 152.48159790039062,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 157.88400268554688,+ 448.63201904296875,+ 171.947998046875,+ 464.760009765625+ ],+ "char": "T",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 317,+ "source_indices": [+ 317+ ],+ "raw_code": 84,+ "loose_bbox": [+ 157.64401245117188,+ 443.6400451660156,+ 172.33200073242188,+ 470.88006591796875+ ],+ "tight_bbox": [+ 157.88400268554688,+ 448.63201904296875,+ 171.947998046875,+ 464.760009765625+ ],+ "origin": [+ 157.6439971923828,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 172.6248016357422,+ 446.9280090332031,+ 184.91281127929688,+ 464.760009765625+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 318,+ "source_indices": [+ 318+ ],+ "raw_code": 104,+ "loose_bbox": [+ 172.3367919921875,+ 443.6400451660156,+ 185.03280639648438,+ 470.88006591796875+ ],+ "tight_bbox": [+ 172.6248016357422,+ 446.9280090332031,+ 184.91281127929688,+ 464.760009765625+ ],+ "origin": [+ 172.3367919921875,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 185.80560302734375,+ 453.9360046386719,+ 194.94960021972656,+ 464.9280090332031+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 319,+ "source_indices": [+ 319+ ],+ "raw_code": 101,+ "loose_bbox": [+ 185.03759765625,+ 443.6400451660156,+ 195.30960083007812,+ 470.88006591796875+ ],+ "tight_bbox": [+ 185.80560302734375,+ 453.9360046386719,+ 194.94960021972656,+ 464.9280090332031+ ],+ "origin": [+ 185.03759765625,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 195.31439208984375,+ 464.73602294921875,+ 200.45040893554688,+ 464.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 320,+ "source_indices": [+ 320+ ],+ "raw_code": 32,+ "loose_bbox": [+ 195.31439208984375,+ 443.6400451660156,+ 200.45040893554688,+ 470.88006591796875+ ],+ "tight_bbox": [+ 195.31439208984375,+ 464.73602294921875,+ 200.45040893554688,+ 464.760009765625+ ],+ "origin": [+ 195.31439208984375,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 201.24481201171875,+ 453.864013671875,+ 210.53280639648438,+ 464.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 321,+ "source_indices": [+ 321+ ],+ "raw_code": 99,+ "loose_bbox": [+ 200.47682189941406,+ 443.6400451660156,+ 211.06082153320312,+ 470.88006591796875+ ],+ "tight_bbox": [+ 201.24481201171875,+ 453.864013671875,+ 210.53280639648438,+ 464.9040222167969+ ],+ "origin": [+ 200.476806640625,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 211.44960021972656,+ 449.0639953613281,+ 217.28160095214844,+ 464.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 322,+ "source_indices": [+ 322+ ],+ "raw_code": 105,+ "loose_bbox": [+ 211.0656280517578,+ 443.6400451660156,+ 217.5696258544922,+ 470.88006591796875+ ],+ "tight_bbox": [+ 211.44960021972656,+ 449.0639953613281,+ 217.28160095214844,+ 464.760009765625+ ],+ "origin": [+ 211.06561279296875,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 218.150390625,+ 451.8480224609375,+ 225.6623992919922,+ 464.9519958496094+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 323,+ "source_indices": [+ 323+ ],+ "raw_code": 116,+ "loose_bbox": [+ 217.5744171142578,+ 443.6400451660156,+ 226.07041931152344,+ 470.88006591796875+ ],+ "tight_bbox": [+ 218.150390625,+ 451.8480224609375,+ 225.6623992919922,+ 464.9519958496094+ ],+ "origin": [+ 217.57440185546875,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 226.45919799804688,+ 449.0639953613281,+ 232.29119873046875,+ 464.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 324,+ "source_indices": [+ 324+ ],+ "raw_code": 105,+ "loose_bbox": [+ 226.0751953125,+ 443.6400451660156,+ 232.57919311523438,+ 470.88006591796875+ ],+ "tight_bbox": [+ 226.45919799804688,+ 449.0639953613281,+ 232.29119873046875,+ 464.760009765625+ ],+ "origin": [+ 226.0751953125,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 232.9199981689453,+ 453.7200012207031,+ 241.15200805664062,+ 464.760009765625+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 325,+ "source_indices": [+ 325+ ],+ "raw_code": 114,+ "loose_bbox": [+ 232.58399963378906,+ 443.6400451660156,+ 241.32000732421875,+ 470.88006591796875+ ],+ "tight_bbox": [+ 232.9199981689453,+ 453.7200012207031,+ 241.15200805664062,+ 464.760009765625+ ],+ "origin": [+ 232.58399963378906,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 241.7087860107422,+ 449.0639953613281,+ 247.54078674316406,+ 464.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 326,+ "source_indices": [+ 326+ ],+ "raw_code": 105,+ "loose_bbox": [+ 241.32481384277344,+ 443.6400451660156,+ 247.8288116455078,+ 470.88006591796875+ ],+ "tight_bbox": [+ 241.7087860107422,+ 449.0639953613281,+ 247.54078674316406,+ 464.760009765625+ ],+ "origin": [+ 241.32479858398438,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 248.60159301757812,+ 453.864013671875,+ 257.88958740234375,+ 464.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 327,+ "source_indices": [+ 327+ ],+ "raw_code": 99,+ "loose_bbox": [+ 247.83360290527344,+ 443.6400451660156,+ 258.4176025390625,+ 470.88006591796875+ ],+ "tight_bbox": [+ 248.60159301757812,+ 453.864013671875,+ 257.88958740234375,+ 464.9040222167969+ ],+ "origin": [+ 247.83358764648438,+ 464.760009765625+ ]+ }+ ],+ "tight_bboxes": {+ "314": [+ 132.36000061035156,+ 449.0160217285156,+ 142.2239990234375,+ 464.760009765625+ ],+ "315": [+ 143.98080444335938,+ 447.1920166015625,+ 151.0847930908203,+ 470.5680236816406+ ],+ "316": [+ 152.48159790039062,+ 464.73602294921875,+ 157.6175994873047,+ 464.760009765625+ ],+ "317": [+ 157.88400268554688,+ 448.63201904296875,+ 171.947998046875,+ 464.760009765625+ ],+ "318": [+ 172.6248016357422,+ 446.9280090332031,+ 184.91281127929688,+ 464.760009765625+ ],+ "319": [+ 185.80560302734375,+ 453.9360046386719,+ 194.94960021972656,+ 464.9280090332031+ ],+ "320": [+ 195.31439208984375,+ 464.73602294921875,+ 200.45040893554688,+ 464.760009765625+ ],+ "321": [+ 201.24481201171875,+ 453.864013671875,+ 210.53280639648438,+ 464.9040222167969+ ],+ "322": [+ 211.44960021972656,+ 449.0639953613281,+ 217.28160095214844,+ 464.760009765625+ ],+ "323": [+ 218.150390625,+ 451.8480224609375,+ 225.6623992919922,+ 464.9519958496094+ ],+ "324": [+ 226.45919799804688,+ 449.0639953613281,+ 232.29119873046875,+ 464.760009765625+ ],+ "325": [+ 232.9199981689453,+ 453.7200012207031,+ 241.15200805664062,+ 464.760009765625+ ],+ "326": [+ 241.7087860107422,+ 449.0639953613281,+ 247.54078674316406,+ 464.760009765625+ ],+ "327": [+ 248.60159301757812,+ 453.864013671875,+ 257.88958740234375,+ 464.9040222167969+ ]+ },+ "origins": {+ "314": [+ 131.27999877929688,+ 464.760009765625+ ],+ "315": [+ 143.23680114746094,+ 464.760009765625+ ],+ "316": [+ 152.48159790039062,+ 464.760009765625+ ],+ "317": [+ 157.6439971923828,+ 464.760009765625+ ],+ "318": [+ 172.3367919921875,+ 464.760009765625+ ],+ "319": [+ 185.03759765625,+ 464.760009765625+ ],+ "320": [+ 195.31439208984375,+ 464.760009765625+ ],+ "321": [+ 200.476806640625,+ 464.760009765625+ ],+ "322": [+ 211.06561279296875,+ 464.760009765625+ ],+ "323": [+ 217.57440185546875,+ 464.760009765625+ ],+ "324": [+ 226.0751953125,+ 464.760009765625+ ],+ "325": [+ 232.58399963378906,+ 464.760009765625+ ],+ "326": [+ 241.32479858398438,+ 464.760009765625+ ],+ "327": [+ 247.83358764648438,+ 464.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 263.615966796875,+ 464.760009765625,+ 263.615966796875,+ 464.760009765625+ ],+ "char": " ",+ "rotation": 0.0,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 328,+ "source_indices": [+ 328+ ],+ "raw_code": 32,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 263.615966796875,+ 464.760009765625+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "328": [+ 263.615966796875,+ 464.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 264.6719970703125,+ 454.08001708984375,+ 273.8639831542969,+ 465.0480041503906+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 329,+ "source_indices": [+ 329+ ],+ "raw_code": 97,+ "loose_bbox": [+ 263.615966796875,+ 443.6400451660156,+ 274.1999816894531,+ 470.88006591796875+ ],+ "tight_bbox": [+ 264.6719970703125,+ 454.08001708984375,+ 273.8639831542969,+ 465.0480041503906+ ],+ "origin": [+ 263.615966796875,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 275.0063781738281,+ 453.864013671875,+ 284.29437255859375,+ 464.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 330,+ "source_indices": [+ 330+ ],+ "raw_code": 99,+ "loose_bbox": [+ 274.2384033203125,+ 443.6400451660156,+ 284.8223876953125,+ 470.88006591796875+ ],+ "tight_bbox": [+ 275.0063781738281,+ 453.864013671875,+ 284.29437255859375,+ 464.9040222167969+ ],+ "origin": [+ 274.2383728027344,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 285.211181640625,+ 449.0639953613281,+ 291.04315185546875,+ 464.760009765625+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 331,+ "source_indices": [+ 331+ ],+ "raw_code": 105,+ "loose_bbox": [+ 284.82720947265625,+ 443.6400451660156,+ 291.3311767578125,+ 470.88006591796875+ ],+ "tight_bbox": [+ 285.211181640625,+ 449.0639953613281,+ 291.04315185546875,+ 464.760009765625+ ],+ "origin": [+ 284.8271789550781,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 292.1039733886719,+ 446.9280090332031,+ 304.24798583984375,+ 465.1199951171875+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 332,+ "source_indices": [+ 332+ ],+ "raw_code": 100,+ "loose_bbox": [+ 291.33599853515625,+ 443.6400451660156,+ 304.24798583984375,+ 470.88006591796875+ ],+ "tight_bbox": [+ 292.1039733886719,+ 446.9280090332031,+ 304.24798583984375,+ 465.1199951171875+ ],+ "origin": [+ 291.3359680175781,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 304.13275146484375,+ 464.73602294921875,+ 309.2687683105469,+ 464.760009765625+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 333,+ "source_indices": [+ 333+ ],+ "raw_code": 32,+ "loose_bbox": [+ 304.13275146484375,+ 443.6400451660156,+ 309.2687683105469,+ 470.88006591796875+ ],+ "tight_bbox": [+ 304.13275146484375,+ 464.73602294921875,+ 309.2687683105469,+ 464.760009765625+ ],+ "origin": [+ 304.13275146484375,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 310.06317138671875,+ 453.864013671875,+ 319.3511657714844,+ 464.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 334,+ "source_indices": [+ 334+ ],+ "raw_code": 99,+ "loose_bbox": [+ 309.295166015625,+ 443.6400451660156,+ 319.879150390625,+ 470.88006591796875+ ],+ "tight_bbox": [+ 310.06317138671875,+ 453.864013671875,+ 319.3511657714844,+ 464.9040222167969+ ],+ "origin": [+ 309.295166015625,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 320.00396728515625,+ 454.0559997558594,+ 330.9959411621094,+ 470.8320007324219+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 335,+ "source_indices": [+ 335+ ],+ "raw_code": 121,+ "loose_bbox": [+ 319.88397216796875,+ 443.6400451660156,+ 331.115966796875,+ 470.88006591796875+ ],+ "tight_bbox": [+ 320.00396728515625,+ 454.0559997558594,+ 330.9959411621094,+ 470.8320007324219+ ],+ "origin": [+ 319.88397216796875,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 331.88873291015625,+ 453.864013671875,+ 341.1767578125,+ 464.9040222167969+ ],+ "char": "c",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 336,+ "source_indices": [+ 336+ ],+ "raw_code": 99,+ "loose_bbox": [+ 331.1207580566406,+ 443.6400451660156,+ 341.70477294921875,+ 470.88006591796875+ ],+ "tight_bbox": [+ 331.88873291015625,+ 453.864013671875,+ 341.1767578125,+ 464.9040222167969+ ],+ "origin": [+ 331.1207580566406,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 341.8775634765625,+ 447.0480041503906,+ 347.97357177734375,+ 464.760009765625+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 337,+ "source_indices": [+ 337+ ],+ "raw_code": 108,+ "loose_bbox": [+ 341.7095642089844,+ 443.6400451660156,+ 348.1655578613281,+ 470.88006591796875+ ],+ "tight_bbox": [+ 341.8775634765625,+ 447.0480041503906,+ 347.97357177734375,+ 464.760009765625+ ],+ "origin": [+ 341.7095642089844,+ 464.760009765625+ ]+ },+ {+ "bbox": [+ 348.9383544921875,+ 453.9360046386719,+ 358.0823669433594,+ 464.9280090332031+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 338,+ "source_indices": [+ 338+ ],+ "raw_code": 101,+ "loose_bbox": [+ 348.17041015625,+ 443.6400451660156,+ 358.4424133300781,+ 470.88006591796875+ ],+ "tight_bbox": [+ 348.9383544921875,+ 453.9360046386719,+ 358.0823669433594,+ 464.9280090332031+ ],+ "origin": [+ 348.1703796386719,+ 464.760009765625+ ]+ }+ ],+ "tight_bboxes": {+ "329": [+ 264.6719970703125,+ 454.08001708984375,+ 273.8639831542969,+ 465.0480041503906+ ],+ "330": [+ 275.0063781738281,+ 453.864013671875,+ 284.29437255859375,+ 464.9040222167969+ ],+ "331": [+ 285.211181640625,+ 449.0639953613281,+ 291.04315185546875,+ 464.760009765625+ ],+ "332": [+ 292.1039733886719,+ 446.9280090332031,+ 304.24798583984375,+ 465.1199951171875+ ],+ "333": [+ 304.13275146484375,+ 464.73602294921875,+ 309.2687683105469,+ 464.760009765625+ ],+ "334": [+ 310.06317138671875,+ 453.864013671875,+ 319.3511657714844,+ 464.9040222167969+ ],+ "335": [+ 320.00396728515625,+ 454.0559997558594,+ 330.9959411621094,+ 470.8320007324219+ ],+ "336": [+ 331.88873291015625,+ 453.864013671875,+ 341.1767578125,+ 464.9040222167969+ ],+ "337": [+ 341.8775634765625,+ 447.0480041503906,+ 347.97357177734375,+ 464.760009765625+ ],+ "338": [+ 348.9383544921875,+ 453.9360046386719,+ 358.0823669433594,+ 464.9280090332031+ ]+ },+ "origins": {+ "329": [+ 263.615966796875,+ 464.760009765625+ ],+ "330": [+ 274.2383728027344,+ 464.760009765625+ ],+ "331": [+ 284.8271789550781,+ 464.760009765625+ ],+ "332": [+ 291.3359680175781,+ 464.760009765625+ ],+ "333": [+ 304.13275146484375,+ 464.760009765625+ ],+ "334": [+ 309.295166015625,+ 464.760009765625+ ],+ "335": [+ 319.88397216796875,+ 464.760009765625+ ],+ "336": [+ 331.1207580566406,+ 464.760009765625+ ],+ "337": [+ 341.7095642089844,+ 464.760009765625+ ],+ "338": [+ 348.1703796386719,+ 464.760009765625+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 348.1703796386719,+ 465.1880187988281,+ 348.1703796386719,+ 465.1880187988281+ ],+ "char": "\r",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 339,+ "source_indices": [+ 339+ ],+ "raw_code": 13,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 348.1703796386719,+ 465.1880187988281+ ]+ },+ {+ "bbox": [+ 348.1703796386719,+ 465.1880187988281,+ 348.1703796386719,+ 465.1880187988281+ ],+ "char": "\n",+ "rotation": 0.0,+ "font": {+ "name": "",+ "flags": 0,+ "size": 1.0,+ "weight": -1+ },+ "char_idx": 340,+ "source_indices": [+ 340+ ],+ "raw_code": 10,+ "loose_bbox": null,+ "tight_bbox": null,+ "origin": [+ 348.1703796386719,+ 465.1880187988281+ ]+ }+ ],+ "tight_bboxes": {},+ "origins": {+ "339": [+ 348.1703796386719,+ 465.1880187988281+ ],+ "340": [+ 348.1703796386719,+ 465.1880187988281+ ]+ }+ },+ {+ "chars": [+ {+ "bbox": [+ 133.41600036621094,+ 493.1280212402344,+ 142.27200317382812,+ 509.0880126953125+ ],+ "char": "3",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 341,+ "source_indices": [+ 341+ ],+ "raw_code": 51,+ "loose_bbox": [+ 132.47999572753906,+ 487.800048828125,+ 143.4720001220703,+ 515.0400390625+ ],+ "tight_bbox": [+ 133.41600036621094,+ 493.1280212402344,+ 142.27200317382812,+ 509.0880126953125+ ],+ "origin": [+ 132.47999572753906,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 144.22079467773438,+ 491.3520202636719,+ 151.32479858398438,+ 514.72802734375+ ],+ "char": ")",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 342,+ "source_indices": [+ 342+ ],+ "raw_code": 41,+ "loose_bbox": [+ 143.47679138183594,+ 487.800048828125,+ 152.716796875,+ 515.0400390625+ ],+ "tight_bbox": [+ 144.22079467773438,+ 491.3520202636719,+ 151.32479858398438,+ 514.72802734375+ ],+ "origin": [+ 143.47679138183594,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 152.72158813476562,+ 508.8960266113281,+ 157.8575897216797,+ 508.9200134277344+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 343,+ "source_indices": [+ 343+ ],+ "raw_code": 32,+ "loose_bbox": [+ 152.72158813476562,+ 487.800048828125,+ 157.8575897216797,+ 515.0400390625+ ],+ "tight_bbox": [+ 152.72158813476562,+ 508.8960266113281,+ 157.8575897216797,+ 508.9200134277344+ ],+ "origin": [+ 152.72158813476562,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 158.77200317382812,+ 492.864013671875,+ 174.32400512695312,+ 509.0400085449219+ ],+ "char": "O",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 344,+ "source_indices": [+ 344+ ],+ "raw_code": 79,+ "loose_bbox": [+ 157.88400268554688,+ 487.800048828125,+ 175.21200561523438,+ 515.0400390625+ ],+ "tight_bbox": [+ 158.77200317382812,+ 492.864013671875,+ 174.32400512695312,+ 509.0400085449219+ ],+ "origin": [+ 157.88400268554688,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 175.3607940673828,+ 498.21600341796875,+ 187.7928009033203,+ 508.9200134277344+ ],+ "char": "x",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 345,+ "source_indices": [+ 345+ ],+ "raw_code": 120,+ "loose_bbox": [+ 175.216796875,+ 487.800048828125,+ 187.91281127929688,+ 515.0400390625+ ],+ "tight_bbox": [+ 175.3607940673828,+ 498.21600341796875,+ 187.7928009033203,+ 508.9200134277344+ ],+ "origin": [+ 175.216796875,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 188.30160522460938,+ 493.2239990234375,+ 194.13360595703125,+ 508.9200134277344+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 346,+ "source_indices": [+ 346+ ],+ "raw_code": 105,+ "loose_bbox": [+ 187.9176025390625,+ 487.800048828125,+ 194.42160034179688,+ 515.0400390625+ ],+ "tight_bbox": [+ 188.30160522460938,+ 493.2239990234375,+ 194.13360595703125,+ 508.9200134277344+ ],+ "origin": [+ 187.9176025390625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 195.19439697265625,+ 491.0880126953125,+ 207.33839416503906,+ 509.2799987792969+ ],+ "char": "d",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 347,+ "source_indices": [+ 347+ ],+ "raw_code": 100,+ "loose_bbox": [+ 194.4263916015625,+ 487.800048828125,+ 207.33839416503906,+ 515.0400390625+ ],+ "tight_bbox": [+ 195.19439697265625,+ 491.0880126953125,+ 207.33839416503906,+ 509.2799987792969+ ],+ "origin": [+ 194.4263916015625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 208.27919006347656,+ 498.2400207519531,+ 217.47119140625,+ 509.2080078125+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 348,+ "source_indices": [+ 348+ ],+ "raw_code": 97,+ "loose_bbox": [+ 207.22320556640625,+ 487.800048828125,+ 217.8072052001953,+ 515.0400390625+ ],+ "tight_bbox": [+ 208.27919006347656,+ 498.2400207519531,+ 217.47119140625,+ 509.2080078125+ ],+ "origin": [+ 207.22320556640625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 218.38800048828125,+ 496.0080261230469,+ 225.89999389648438,+ 509.11199951171875+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 349,+ "source_indices": [+ 349+ ],+ "raw_code": 116,+ "loose_bbox": [+ 217.81201171875,+ 487.800048828125,+ 226.30801391601562,+ 515.0400390625+ ],+ "tight_bbox": [+ 218.38800048828125,+ 496.0080261230469,+ 225.89999389648438,+ 509.11199951171875+ ],+ "origin": [+ 217.81199645996094,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 226.69680786132812,+ 493.2239990234375,+ 232.52880859375,+ 508.9200134277344+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 350,+ "source_indices": [+ 350+ ],+ "raw_code": 105,+ "loose_bbox": [+ 226.3128204345703,+ 487.800048828125,+ 232.8168182373047,+ 515.0400390625+ ],+ "tight_bbox": [+ 226.69680786132812,+ 493.2239990234375,+ 232.52880859375,+ 508.9200134277344+ ],+ "origin": [+ 226.31280517578125,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 232.9416046142578,+ 498.21600341796875,+ 243.8135986328125,+ 508.99200439453125+ ],+ "char": "v",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 351,+ "source_indices": [+ 351+ ],+ "raw_code": 118,+ "loose_bbox": [+ 232.82159423828125,+ 487.800048828125,+ 243.8376007080078,+ 515.0400390625+ ],+ "tight_bbox": [+ 232.9416046142578,+ 498.21600341796875,+ 243.8135986328125,+ 508.99200439453125+ ],+ "origin": [+ 232.82159423828125,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 244.6103973388672,+ 498.09600830078125,+ 253.75439453125,+ 509.0880126953125+ ],+ "char": "e",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 352,+ "source_indices": [+ 352+ ],+ "raw_code": 101,+ "loose_bbox": [+ 243.84239196777344,+ 487.800048828125,+ 254.11439514160156,+ 515.0400390625+ ],+ "tight_bbox": [+ 244.6103973388672,+ 498.09600830078125,+ 253.75439453125,+ 509.0880126953125+ ],+ "origin": [+ 243.84239196777344,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 254.1191864013672,+ 508.8960266113281,+ 259.25518798828125,+ 508.9200134277344+ ],+ "char": " ",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 353,+ "source_indices": [+ 353+ ],+ "raw_code": 32,+ "loose_bbox": [+ 254.1191864013672,+ 487.800048828125,+ 259.25518798828125,+ 515.0400390625+ ],+ "tight_bbox": [+ 254.1191864013672,+ 508.8960266113281,+ 259.25518798828125,+ 508.9200134277344+ ],+ "origin": [+ 254.1191864013672,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 260.21759033203125,+ 493.08001708984375,+ 271.90557861328125,+ 508.9200134277344+ ],+ "char": "P",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 354,+ "source_indices": [+ 354+ ],+ "raw_code": 80,+ "loose_bbox": [+ 259.2816162109375,+ 487.800048828125,+ 272.52960205078125,+ 515.0400390625+ ],+ "tight_bbox": [+ 260.21759033203125,+ 493.08001708984375,+ 271.90557861328125,+ 508.9200134277344+ ],+ "origin": [+ 259.2815856933594,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 272.8223876953125,+ 491.0880126953125,+ 285.1103820800781,+ 508.9200134277344+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 355,+ "source_indices": [+ 355+ ],+ "raw_code": 104,+ "loose_bbox": [+ 272.53436279296875,+ 487.800048828125,+ 285.2303466796875,+ 515.0400390625+ ],+ "tight_bbox": [+ 272.8223876953125,+ 491.0880126953125,+ 285.1103820800781,+ 508.9200134277344+ ],+ "origin": [+ 272.53436279296875,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 286.003173828125,+ 498.0,+ 296.25115966796875,+ 509.0400085449219+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 356,+ "source_indices": [+ 356+ ],+ "raw_code": 111,+ "loose_bbox": [+ 285.23516845703125,+ 487.800048828125,+ 297.0191650390625,+ 515.0400390625+ ],+ "tight_bbox": [+ 286.003173828125,+ 498.0,+ 296.25115966796875,+ 509.0400085449219+ ],+ "origin": [+ 285.23516845703125,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 298.0079650878906,+ 498.1679992675781,+ 305.68798828125,+ 509.06402587890625+ ],+ "char": "s",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 357,+ "source_indices": [+ 357+ ],+ "raw_code": 115,+ "loose_bbox": [+ 297.02398681640625,+ 487.800048828125,+ 306.5279846191406,+ 515.0400390625+ ],+ "tight_bbox": [+ 298.0079650878906,+ 498.1679992675781,+ 305.68798828125,+ 509.06402587890625+ ],+ "origin": [+ 297.02398681640625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 306.6767578125,+ 497.9520263671875,+ 318.748779296875,+ 514.9920043945312+ ],+ "char": "p",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 358,+ "source_indices": [+ 358+ ],+ "raw_code": 112,+ "loose_bbox": [+ 306.53277587890625,+ 487.800048828125,+ 319.51678466796875,+ 515.0400390625+ ],+ "tight_bbox": [+ 306.6767578125,+ 497.9520263671875,+ 318.748779296875,+ 514.9920043945312+ ],+ "origin": [+ 306.53277587890625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 319.8095703125,+ 491.0880126953125,+ 332.0975341796875,+ 508.9200134277344+ ],+ "char": "h",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 359,+ "source_indices": [+ 359+ ],+ "raw_code": 104,+ "loose_bbox": [+ 319.52154541015625,+ 487.800048828125,+ 332.217529296875,+ 515.0400390625+ ],+ "tight_bbox": [+ 319.8095703125,+ 491.0880126953125,+ 332.0975341796875,+ 508.9200134277344+ ],+ "origin": [+ 319.52154541015625,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 332.9903564453125,+ 498.0,+ 343.23834228515625,+ 509.0400085449219+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 360,+ "source_indices": [+ 360+ ],+ "raw_code": 111,+ "loose_bbox": [+ 332.22235107421875,+ 487.800048828125,+ 344.00634765625,+ 515.0400390625+ ],+ "tight_bbox": [+ 332.9903564453125,+ 498.0,+ 343.23834228515625,+ 509.0400085449219+ ],+ "origin": [+ 332.22235107421875,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 344.34716796875,+ 497.8800048828125,+ 352.57916259765625,+ 508.9200134277344+ ],+ "char": "r",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 361,+ "source_indices": [+ 361+ ],+ "raw_code": 114,+ "loose_bbox": [+ 344.01116943359375,+ 487.800048828125,+ 352.7471923828125,+ 515.0400390625+ ],+ "tight_bbox": [+ 344.34716796875,+ 497.8800048828125,+ 352.57916259765625,+ 508.9200134277344+ ],+ "origin": [+ 344.01116943359375,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 352.87200927734375,+ 498.21600341796875,+ 363.864013671875,+ 514.9920043945312+ ],+ "char": "y",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 362,+ "source_indices": [+ 362+ ],+ "raw_code": 121,+ "loose_bbox": [+ 352.7519836425781,+ 487.800048828125,+ 363.9840087890625,+ 515.0400390625+ ],+ "tight_bbox": [+ 352.87200927734375,+ 498.21600341796875,+ 363.864013671875,+ 514.9920043945312+ ],+ "origin": [+ 352.7519836425781,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 364.15679931640625,+ 491.2080078125,+ 370.2528076171875,+ 508.9200134277344+ ],+ "char": "l",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 363,+ "source_indices": [+ 363+ ],+ "raw_code": 108,+ "loose_bbox": [+ 363.9888000488281,+ 487.800048828125,+ 370.44482421875,+ 515.0400390625+ ],+ "tight_bbox": [+ 364.15679931640625,+ 491.2080078125,+ 370.2528076171875,+ 508.9200134277344+ ],+ "origin": [+ 363.9888000488281,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 371.505615234375,+ 498.2400207519531,+ 380.6976318359375,+ 509.2080078125+ ],+ "char": "a",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 364,+ "source_indices": [+ 364+ ],+ "raw_code": 97,+ "loose_bbox": [+ 370.4495849609375,+ 487.800048828125,+ 381.0335693359375,+ 515.0400390625+ ],+ "tight_bbox": [+ 371.505615234375,+ 498.2400207519531,+ 380.6976318359375,+ 509.2080078125+ ],+ "origin": [+ 370.4495849609375,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 381.61444091796875,+ 496.0080261230469,+ 389.12640380859375,+ 509.11199951171875+ ],+ "char": "t",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 365,+ "source_indices": [+ 365+ ],+ "raw_code": 116,+ "loose_bbox": [+ 381.03839111328125,+ 487.800048828125,+ 389.53436279296875,+ 515.0400390625+ ],+ "tight_bbox": [+ 381.61444091796875,+ 496.0080261230469,+ 389.12640380859375,+ 509.11199951171875+ ],+ "origin": [+ 381.03839111328125,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 389.9232177734375,+ 493.2239990234375,+ 395.75518798828125,+ 508.9200134277344+ ],+ "char": "i",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 366,+ "source_indices": [+ 366+ ],+ "raw_code": 105,+ "loose_bbox": [+ 389.53924560546875,+ 487.800048828125,+ 396.043212890625,+ 515.0400390625+ ],+ "tight_bbox": [+ 389.9232177734375,+ 493.2239990234375,+ 395.75518798828125,+ 508.9200134277344+ ],+ "origin": [+ 389.53924560546875,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 396.8160400390625,+ 498.0,+ 407.06402587890625,+ 509.0400085449219+ ],+ "char": "o",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 367,+ "source_indices": [+ 367+ ],+ "raw_code": 111,+ "loose_bbox": [+ 396.04803466796875,+ 487.800048828125,+ 407.83203125,+ 515.0400390625+ ],+ "tight_bbox": [+ 396.8160400390625,+ 498.0,+ 407.06402587890625,+ 509.0400085449219+ ],+ "origin": [+ 396.04803466796875,+ 508.9200134277344+ ]+ },+ {+ "bbox": [+ 408.268798828125,+ 497.9520263671875,+ 420.43682861328125,+ 508.9200134277344+ ],+ "char": "n",+ "rotation": 4.71238899230957,+ "font": {+ "name": "CalifornianFB-Reg",+ "flags": 524322,+ "size": 1.0,+ "weight": 335+ },+ "char_idx": 368,+ "source_indices": [+ 368+ ],+ "raw_code": 110,+ "loose_bbox": [+ 407.83685302734375,+ 487.800048828125,+ 420.62884521484375,+ 515.0400390625+ ],+ "tight_bbox": [+ 408.268798828125,+ 497.9520263671875,+ 420.43682861328125,+ 508.9200134277344+ ],+ "origin": [+ 407.83685302734375,+ 508.9200134277344+ ]+ }+ ],+ "tight_bboxes": {+ "341": [+ 133.41600036621094,+ 493.1280212402344,+ 142.27200317382812,+ 509.0880126953125+ ],+ "342": [+ 144.22079467773438,+ 491.3520202636719,+ 151.32479858398438,+ 514.72802734375+ ],+ "343": [+ 152.72158813476562,+ 508.8960266113281,+ 157.8575897216797,+ 508.9200134277344+ ],+ "344": [+ 158.77200317382812,+ 492.864013671875,+ 174.32400512695312,+ 509.0400085449219+ ],+ "345": [+ 175.3607940673828,+ 498.21600341796875,+ 187.7928009033203,+ 508.9200134277344+ ],+ "346": [+ 188.30160522460938,+ 493.2239990234375,+ 194.13360595703125,+ 508.9200134277344+ ],+ "347": [+ 195.19439697265625,+ 491.0880126953125,+ 207.33839416503906,+ 509.2799987792969+ ],+ "348": [+ 208.27919006347656,+ 498.2400207519531,+ 217.47119140625,+ 509.2080078125+ ],+ "349": [+ 218.38800048828125,+ 496.0080261230469,+ 225.89999389648438,+ 509.11199951171875+ ],+ "350": [+ 226.69680786132812,+ 493.2239990234375,+ 232.52880859375,+ 508.9200134277344+ ],+ "351": [+ 232.9416046142578,+ 498.21600341796875,+ 243.8135986328125,+ 508.99200439453125+ ],+ "352": [+ 244.6103973388672,+ 498.09600830078125,+ 253.75439453125,+ 509.0880126953125+ ],+ "353": [+ 254.1191864013672,+ 508.8960266113281,+ 259.25518798828125,+ 508.9200134277344+ ],+ "354": [+ 260.21759033203125,+ 493.08001708984375,+ 271.90557861328125,+ 508.9200134277344+ ],+ "355": [+ 272.8223876953125,+ 491.0880126953125,+ 285.1103820800781,+ 508.9200134277344+ ],+ "356": [+ 286.003173828125,+ 498.0,+ 296.25115966796875,+ 509.0400085449219+ ],+ "357": [+ 298.0079650878906,+ 498.1679992675781,+ 305.68798828125,+ 509.06402587890625+ ],+ "358": [+ 306.6767578125,+ 497.9520263671875,+ 318.748779296875,+ 514.9920043945312+ ],+ "359": [+ 319.8095703125,+ 491.0880126953125,+ 332.0975341796875,+ 508.9200134277344+ ],+ "360": [+ 332.9903564453125,+ 498.0,+ 343.23834228515625,+ 509.0400085449219+ ],+ "361": [+ 344.34716796875,+ 497.8800048828125,+ 352.57916259765625,+ 508.9200134277344+ ],+ "362": [+ 352.87200927734375,+ 498.21600341796875,+ 363.864013671875,+ 514.9920043945312+ ],+ "363": [+ 364.15679931640625,+ 491.2080078125,+ 370.2528076171875,+ 508.9200134277344+ ],+ "364": [+ 371.505615234375,+ 498.2400207519531,+ 380.6976318359375,+ 509.2080078125+ ],+ "365": [+ 381.61444091796875,+ 496.0080261230469,+ 389.12640380859375,+ 509.11199951171875+ ],+ "366": [+ 389.9232177734375,+ 493.2239990234375,+ 395.75518798828125,+ 508.9200134277344+ ],+ "367": [+ 396.8160400390625,+ 498.0,+ 407.06402587890625,+ 509.0400085449219+ ],+ "368": [+ 408.268798828125,+ 497.9520263671875,+ 420.43682861328125,+ 508.9200134277344+ ]+ },+ "origins": {+ "341": [+ 132.47999572753906,+ 508.9200134277344+ ],+ "342": [+ 143.47679138183594,+ 508.9200134277344+ ],+ "343": [+ 152.72158813476562,+ 508.9200134277344+ ],+ "344": [+ 157.88400268554688,+ 508.9200134277344+ ],+ "345": [+ 175.216796875,+ 508.9200134277344+ ],+ "346": [+ 187.9176025390625,+ 508.9200134277344+ ],+ "347": [+ 194.4263916015625,+ 508.9200134277344+ ],+ "348": [+ 207.22320556640625,+ 508.9200134277344+ ],+ "349": [+ 217.81199645996094,+ 508.9200134277344+ ],+ "350": [+ 226.31280517578125,+ 508.9200134277344+ ],+ "351": [+ 232.82159423828125,+ 508.9200134277344+ ],+ "352": [+ 243.84239196777344,+ 508.9200134277344+ ],+ "353": [+ 254.1191864013672,+ 508.9200134277344+ ],+ "354": [+ 259.2815856933594,+ 508.9200134277344+ ],+ "355": [+ 272.53436279296875,+ 508.9200134277344+ ],+ "356": [+ 285.23516845703125,+ 508.9200134277344+ ],+ "357": [+ 297.02398681640625,+ 508.9200134277344+ ],+ "358": [+ 306.53277587890625,+ 508.9200134277344+ ],+ "359": [+ 319.52154541015625,+ 508.9200134277344+ ],+ "360": [+ 332.22235107421875,+ 508.9200134277344+ ],+ "361": [+ 344.01116943359375,+ 508.9200134277344+ ],+ "362": [+ 352.7519836425781,+ 508.9200134277344+ ],+ "363": [+ 363.9888000488281,+ 508.9200134277344+ ],+ "364": [+ 370.4495849609375,+ 508.9200134277344+ ],+ "365": [+ 381.03839111328125,+ 508.9200134277344+ ],+ "366": [+ 389.53924560546875,+ 508.9200134277344+ ],+ "367": [+ 396.04803466796875,+ 508.9200134277344+ ],+ "368": [+ 407.83685302734375,+ 508.9200134277344+ ]+ }+ }+ ],+ "page_rotation": 90,+ "page_size": [+ 792.0,+ 612.0+ ]+ }+ ]+}diff --git a/tests/fixtures/native_pdf_table_cross_page_manifest.json b/tests/fixtures/native_pdf_table_cross_page_manifest.jsondeleted file mode 100644index 0aac0335..00000000--- a/tests/fixtures/native_pdf_table_cross_page_manifest.json+++ /dev/null@@ -1,8389 +0,0 @@-{- "schema_version": 5,- "manifest_version": "2026-08-25-v5-repository-fixtures",- "total_tables": 133,- "expected_html": 133,- "expected_projection": 0,- "performance_p95_limit_ms": 27.0,- "entries": [- {- "file": "conference_schedule_tables.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.092,- 0.209,- 0.928,- 0.911- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 4,- "span_signature": [- [- 1,- 0,- 1,- 4- ],- [- 3,- 2,- 2,- 1- ],- [- 3,- 3,- 4,- 1- ],- [- 5,- 1,- 1,- 2- ],- [- 7,- 1,- 1,- 2- ],- [- 8,- 0,- 2,- 1- ]- ],- "text_sha256": "810d555fabe290304673013dc4356a7f2e3992250ac81ef4a65a745564769a8d"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.093,- 0.089,- 0.928,- 0.895- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 4,- "span_signature": [- [- 0,- 0,- 5,- 1- ]- ],- "text_sha256": "764463f5dfcec4ab72f5db2dfa6baf5074612bb1c73cd997c683e0eaf2055b5f"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 2,- "table_index": 0,- "bbox": [- 0.092,- 0.09,- 0.929,- 0.923- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 4,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 2,- 1,- 1,- 3- ],- [- 3,- 0,- 3,- 1- ]- ],- "text_sha256": "2506fd5ea02ab1abcce4d86c6010c213e5ed0f64c5d0ab1f6821905c3ebcd536"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 3,- "table_index": 0,- "bbox": [- 0.202,- 0.09,- 0.929,- 0.909- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 3,- "span_signature": [],- "text_sha256": "a6e63e3f226220e813730c30a044aa34c9beb3d4bc16052470d5af2884154085"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 4,- "table_index": 0,- "bbox": [- 0.092,- 0.09,- 0.928,- 0.909- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 8,- "cols": 4,- "span_signature": [- [- 1,- 0,- 1,- 4- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 4,- 1,- 1,- 3- ],- [- 5,- 0,- 3,- 1- ]- ],- "text_sha256": "0d00c0749caa6c177a3a59406e99970c08f000c2306574455a85b339de26277f"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 5,- "table_index": 0,- "bbox": [- 0.158,- 0.09,- 0.931,- 0.913- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 4,- "span_signature": [- [- 0,- 0,- 6,- 1- ]- ],- "text_sha256": "47c55c2a4920d713875d7e88895a28844dc56b82be90e001a1cad9b0b076e744"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 6,- "table_index": 0,- "bbox": [- 0.092,- 0.09,- 0.928,- 0.9- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 4,- "span_signature": [- [- 1,- 1,- 1,- 2- ],- [- 2,- 0,- 4,- 1- ]- ],- "text_sha256": "fc13188f8e07725e1ff6acc094e22cfb266fe1ff8a88931d8a04eae2dfdbcc6e"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 7,- "table_index": 0,- "bbox": [- 0.092,- 0.09,- 0.929,- 0.919- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 4,- "span_signature": [- [- 0,- 0,- 5,- 1- ]- ],- "text_sha256": "704d7793284eaa624d29d545ae9fb17a519ae17ad13915bffc3f7556624ee8ee"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 8,- "table_index": 0,- "bbox": [- 0.092,- 0.089,- 0.928,- 0.918- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 4,- "span_signature": [- [- 0,- 0,- 6,- 1- ]- ],- "text_sha256": "8864dca4ca86743515fb3545106829b3c966849f88d8f0560795fa1b486d5c29"- },- {- "file": "conference_schedule_tables.pdf",- "page_index": 9,- "table_index": 0,- "bbox": [- 0.092,- 0.09,- 0.928,- 0.718- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 4,- "span_signature": [- [- 0,- 0,- 2,- 1- ]- ],- "text_sha256": "23d2a97190151ed201b5911536a56d57dde00128513efcf2f08e3986b6588718"- },- {- "file": "manufacturing_facilities_cross_page_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.046,- 0.149,- 0.952,- 0.69- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 13,- "cols": 15,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 4- ],- [- 0,- 9,- 2,- 1- ],- [- 0,- 10,- 2,- 1- ],- [- 0,- 11,- 2,- 1- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 2,- 0,- 9,- 1- ],- [- 2,- 1,- 9,- 1- ],- [- 2,- 2,- 9,- 1- ],- [- 2,- 10,- 9,- 1- ],- [- 2,- 11,- 9,- 1- ],- [- 2,- 12,- 9,- 1- ],- [- 2,- 13,- 9,- 1- ],- [- 2,- 14,- 9,- 1- ],- [- 11,- 0,- 2,- 1- ],- [- 11,- 1,- 2,- 1- ],- [- 11,- 2,- 2,- 1- ]- ],- "text_sha256": "d0e4429d94f793465108795e8b835dfaa5d9482a861ede79f09d8d76c2330e46"- },- {- "file": "manufacturing_facilities_cross_page_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.047,- 0.149,- 0.953,- 0.68- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 15,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 4- ],- [- 0,- 9,- 2,- 1- ],- [- 0,- 10,- 2,- 1- ],- [- 0,- 11,- 2,- 1- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 2,- 0,- 10,- 1- ],- [- 2,- 1,- 9,- 1- ],- [- 2,- 2,- 9,- 1- ]- ],- "text_sha256": "d45581f7a401d5bac5d5dc7d77b3a862d72252ad17bc86c1e6c21490e8bef9df"- },- {- "file": "procurement_document_blank_page_tables.pdf",- "page_index": 2,- "table_index": 0,- "bbox": [- 0.169,- 0.501,- 0.828,- 0.596- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 5,- "span_signature": [],- "text_sha256": "e03fb9e7ae02cfe3a8435dc2c97fda32b9070211d56f4749511081968c6ceef8"- },- {- "file": "procurement_document_blank_page_tables.pdf",- "page_index": 2,- "table_index": 1,- "bbox": [- 0.144,- 0.755,- 0.853,- 0.901- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 3,- "span_signature": [],- "text_sha256": "0167a7b5e8ab8907367eb22dee475ca1d46a9a4ffb6a71d739b340f2431eb7c7"- },- {- "file": "procurement_document_blank_page_tables.pdf",- "page_index": 3,- "table_index": 0,- "bbox": [- 0.143,- 0.091,- 0.852,- 0.219- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 1,- "cols": 3,- "span_signature": [],- "text_sha256": "a6ff60c437ff5a76b820349ae9c4439d78b883d4292a76c1915a5f2afb15dc63"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.047,- 0.346,- 0.951,- 0.482- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 8,- "span_signature": [- [- 1,- 0,- 2,- 1- ],- [- 1,- 1,- 2,- 1- ],- [- 1,- 2,- 2,- 1- ]- ],- "text_sha256": "9d44bbed1883eeec0c5c2d644fb57e46161f47b2e849fa3dd11d3862eca6f64a"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 1,- "table_index": 1,- "bbox": [- 0.05,- 0.658,- 0.952,- 0.689- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 1,- "cols": 10,- "span_signature": [],- "text_sha256": "85ebb40794f7aa7e77c782fd1ac20ef9c7a1819fb62a460c4a56d27c089bd455"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 2,- "table_index": 0,- "bbox": [- 0.047,- 0.15,- 0.952,- 0.678- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 13,- "span_signature": [- [- 1,- 0,- 11,- 1- ],- [- 1,- 1,- 11,- 1- ],- [- 1,- 2,- 11,- 1- ],- [- 1,- 3,- 3,- 1- ],- [- 1,- 4,- 3,- 1- ],- [- 1,- 12,- 3,- 1- ],- [- 4,- 3,- 6,- 1- ],- [- 4,- 4,- 6,- 1- ],- [- 4,- 12,- 6,- 1- ],- [- 10,- 3,- 2,- 1- ],- [- 10,- 4,- 2,- 1- ],- [- 10,- 12,- 2,- 1- ]- ],- "text_sha256": "ec07c9fadb35f5c3fdd63df1adaccd3346f3f6c27cc9067b0d41751645cc27fe"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 3,- "table_index": 0,- "bbox": [- 0.047,- 0.149,- 0.951,- 0.363- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 13,- "span_signature": [- [- 0,- 0,- 5,- 1- ],- [- 0,- 1,- 5,- 1- ],- [- 0,- 2,- 5,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 12,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 2,- 4,- 2,- 1- ],- [- 2,- 12,- 2,- 1- ]- ],- "text_sha256": "64f07274e5daf1e4326e2cfe4a924fde1f58b110919859267508e671a8021dc7"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 4,- "table_index": 0,- "bbox": [- 0.077,- 0.193,- 0.921,- 0.502- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "localized_alias_blank_row",- "rows": 8,- "cols": 20,- "span_signature": [- [- 0,- 1,- 1,- 2- ],- [- 0,- 3,- 1,- 2- ],- [- 0,- 5,- 1,- 2- ],- [- 0,- 7,- 1,- 3- ],- [- 0,- 10,- 1,- 2- ],- [- 0,- 12,- 1,- 2- ],- [- 0,- 14,- 1,- 2- ],- [- 0,- 16,- 1,- 2- ],- [- 0,- 18,- 1,- 2- ],- [- 1,- 0,- 1,- 20- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 2- ],- [- 2,- 3,- 3,- 2- ],- [- 2,- 5,- 1,- 2- ],- [- 2,- 7,- 1,- 3- ],- [- 2,- 10,- 1,- 2- ],- [- 2,- 12,- 1,- 2- ],- [- 2,- 14,- 1,- 2- ],- [- 2,- 16,- 1,- 2- ],- [- 2,- 18,- 1,- 2- ],- [- 3,- 5,- 1,- 2- ],- [- 3,- 7,- 1,- 3- ],- [- 3,- 10,- 1,- 2- ],- [- 3,- 12,- 1,- 2- ],- [- 3,- 14,- 1,- 2- ],- [- 3,- 16,- 1,- 2- ],- [- 3,- 18,- 1,- 2- ],- [- 4,- 5,- 1,- 2- ],- [- 4,- 7,- 1,- 3- ],- [- 4,- 10,- 1,- 2- ],- [- 4,- 12,- 1,- 2- ],- [- 4,- 14,- 1,- 2- ],- [- 4,- 16,- 1,- 2- ],- [- 4,- 18,- 1,- 2- ],- [- 5,- 0,- 1,- 20- ],- [- 6,- 2,- 1,- 2- ],- [- 6,- 4,- 1,- 2- ],- [- 6,- 6,- 1,- 2- ],- [- 6,- 9,- 1,- 2- ],- [- 6,- 11,- 1,- 2- ],- [- 6,- 13,- 1,- 2- ],- [- 6,- 15,- 1,- 2- ],- [- 6,- 17,- 1,- 2- ],- [- 7,- 0,- 1,- 20- ]- ],- "text_sha256": "4a8cd5fa0282d84710832ac77a3d17f0c7777a9bb68eeeb5ad5efcc920a2f217"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 5,- "table_index": 0,- "bbox": [- 0.032,- 0.278,- 0.967,- 0.679- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 5,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 2,- 3,- 1- ],- [- 2,- 3,- 3,- 1- ],- [- 2,- 4,- 3,- 1- ]- ],- "text_sha256": "ac047b16952c0b278223180c89f1c4af1f8eb5e7b630b244f5eb33843b133c6c",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 6,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.695- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 7,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ],- [- 2,- 1,- 2,- 1- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 2,- 4,- 2,- 1- ],- [- 4,- 0,- 3,- 1- ],- [- 4,- 1,- 3,- 1- ],- [- 4,- 2,- 3,- 1- ],- [- 4,- 3,- 3,- 1- ],- [- 4,- 4,- 3,- 1- ]- ],- "text_sha256": "1ea46ec814021e97bd7637df48a3f3428f572b265b3c5e395c3d30dad4264b28",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 7,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.968,- 0.682- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ],- [- 2,- 1,- 2,- 1- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 2,- 4,- 2,- 1- ],- [- 4,- 0,- 2,- 1- ],- [- 4,- 1,- 2,- 1- ],- [- 4,- 2,- 2,- 1- ],- [- 4,- 3,- 2,- 1- ],- [- 4,- 4,- 2,- 1- ]- ],- "text_sha256": "cb53f1139e709f837b053a68b5281a8a4dec3f76b959f0c55c47d628bf610afc",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 8,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.683- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ],- [- 2,- 1,- 2,- 1- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 2,- 4,- 2,- 1- ],- [- 4,- 0,- 2,- 1- ],- [- 4,- 1,- 2,- 1- ],- [- 4,- 2,- 2,- 1- ],- [- 4,- 3,- 2,- 1- ],- [- 4,- 4,- 2,- 1- ]- ],- "text_sha256": "b62ba6922e38f41e192b8bd63aa181ec4b41906ad3b47b1258096e62138b20a6",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 9,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.695- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 7,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 2,- 3,- 1- ],- [- 2,- 3,- 3,- 1- ],- [- 2,- 4,- 3,- 1- ],- [- 5,- 0,- 2,- 1- ],- [- 5,- 1,- 2,- 1- ],- [- 5,- 2,- 2,- 1- ],- [- 5,- 3,- 2,- 1- ],- [- 5,- 4,- 2,- 1- ]- ],- "text_sha256": "12e73efe0af627cf436fbfc4c303ecd43207dce0f3f7ce7172268f71aafd3c34",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 10,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.695- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 7,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 2,- 3,- 1- ],- [- 2,- 3,- 3,- 1- ],- [- 2,- 4,- 3,- 1- ],- [- 5,- 0,- 2,- 1- ],- [- 5,- 1,- 2,- 1- ],- [- 5,- 2,- 2,- 1- ],- [- 5,- 3,- 2,- 1- ],- [- 5,- 4,- 2,- 1- ]- ],- "text_sha256": "36fddefb6c3e69d327637f7011372ef3cf17cfd61316653acfd590cbf2bfa74e",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 11,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.968,- 0.683- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 2,- 3,- 1- ],- [- 2,- 3,- 3,- 1- ],- [- 2,- 4,- 3,- 1- ]- ],- "text_sha256": "06726eeb12cc2bb6fabc33b6da8efa57d66db4c103f817591cfb2a4b698d9a46",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 12,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.683- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 2,- 3,- 1- ],- [- 2,- 3,- 3,- 1- ],- [- 2,- 4,- 3,- 1- ]- ],- "text_sha256": "36bbaa1f5e01cbebd709b54b23a18aa1d1075f0c3037cd495927df1d5f555dfc",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 13,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.695- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 7,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 4,- 1- ],- [- 2,- 1,- 4,- 1- ],- [- 2,- 2,- 4,- 1- ],- [- 2,- 3,- 4,- 1- ],- [- 2,- 4,- 4,- 1- ]- ],- "text_sha256": "b816f259927cd8c8348a69fd8e344b014f1e672af195f269644122136145e5ce",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 14,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.695- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 7,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 4,- 1- ],- [- 2,- 1,- 4,- 1- ],- [- 2,- 2,- 4,- 1- ],- [- 2,- 3,- 4,- 1- ],- [- 2,- 4,- 4,- 1- ]- ],- "text_sha256": "11733f9afbd79cd992af510aa155bdf9d38727465463e9ee3d462a52b417f00a",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 15,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.694- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "446b54e6925f68c53bd6cdca0a9b65bf3c33e58ec52350b52df4b4d262b9d27e",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 16,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "0b53fb535c7056e1886d44842a0fa3f9f9b54d3c6b5cd32c65806b3bb8293896",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 17,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "8fd8a101e53cf232ac4a24f505617b18c2d3c75239661322c6c3a1dfbfdce044",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 18,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "46395d286fb411ab8f180c43aa6a4124b24527d175b756f5221e3899c765012b",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 19,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.694- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "0d5a51a80c1511330f104fb2ab52213ee68d93585ec1545630c4fe4e00864b39",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 20,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.694- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "be15439fd1171187cd50829133251a3ebeb00350d7669517906a383b879bb752",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 21,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "5467e9c755ae0b82d182c95556d3ff3bb389efb2d2b0c16e5ec00b2515f793cd",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 22,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "a58a6179db6b1c6bacae3fc5b338242259e9d1eee3a1e964e1b5d1f1dba360c3",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 23,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "a6f0c74060b981c6ac39beeb8ac1b5907ade247694b1fbd50b12e98401f1f490",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 24,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.694- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "fa214a9e9f51e19d35fd32c9957df8788f93b9f3f5271d1f33ffff2f8f64e11e",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 25,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "b5a6b192486bf9c4e9f2fdf6f9b5dc07039bd6a625cb984ba8a2fab84c79e09b",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 26,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.693- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "7c9e5a1f6273156a6dd6f136f8ec0ec113c262bbe016bc03dd4674033d4f616f",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 27,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.967,- 0.694- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 6,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ]- ],- "text_sha256": "85f8ec979792391a44d868e74d3de26749bbcdeea7b8e5aaf3aba8792356ad1a",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 28,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.967,- 0.471- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 4,- "cols": 19,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 6- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ],- [- 2,- 1,- 2,- 1- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ],- [- 2,- 4,- 2,- 1- ]- ],- "text_sha256": "3106f3317a87cba1a3683c6a91e3214658a7e7d2d3474317cf8fa73527515579",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 30,- "table_index": 0,- "bbox": [- 0.032,- 0.174,- 0.968,- 0.679- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 20,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 9- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 0,- 19,- 2,- 1- ]- ],- "text_sha256": "386799ed2a97572a7eba7f0e743c23e091acecc80c113bf9ee5dbb1856e2bcc4"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 31,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.968,- 0.693- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 20,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 9- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 0,- 19,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ]- ],- "text_sha256": "c3c89771d7cc6e352e98227bbe4a61d8ed38ed7b658a28952ad76ab1fc66e46d"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 32,- "table_index": 0,- "bbox": [- 0.032,- 0.149,- 0.968,- 0.693- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 20,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 9- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 0,- 19,- 2,- 1- ],- [- 2,- 0,- 2,- 1- ]- ],- "text_sha256": "69a6452bf68db05ef551aa99cc507380c94ddd8bc59c4ca7397fa9be8dc6abc0"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 33,- "table_index": 0,- "bbox": [- 0.031,- 0.149,- 0.968,- 0.523- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 20,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 9- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 0,- 14,- 2,- 1- ],- [- 0,- 15,- 2,- 1- ],- [- 0,- 16,- 2,- 1- ],- [- 0,- 17,- 2,- 1- ],- [- 0,- 18,- 2,- 1- ],- [- 0,- 19,- 2,- 1- ]- ],- "text_sha256": "d1fa7bda69e183d7576a8ee3783fd4a5fdc0e8fe1cc32b4c914f491c58917626"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 35,- "table_index": 0,- "bbox": [- 0.077,- 0.299,- 0.921,- 0.683- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 2- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "26f3baff18adda46c5e72f613be50eaae6595828e04ff1d3819e8caa7be2b9f5"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 36,- "table_index": 0,- "bbox": [- 0.076,- 0.149,- 0.921,- 0.561- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 7,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 2- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "69be1a0181d8a81f4da0a7395f369d1e6db51464846657eaa1548d737a4dd8e2"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 37,- "table_index": 0,- "bbox": [- 0.077,- 0.174,- 0.922,- 0.677- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 3- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "4b2b93d8ef76e633407428348b65bfe55ea7e587b7a1368c1896c2202a13465e"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 38,- "table_index": 0,- "bbox": [- 0.076,- 0.15,- 0.922,- 0.679- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 3- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "70264f91860ea5c8c1fa445083c2b24cefbc40772723d15483e224ec4738c893"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 39,- "table_index": 0,- "bbox": [- 0.076,- 0.15,- 0.922,- 0.679- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 3- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "c629bf2983199a84c906318d9a6692d74f292b4c2ab53503bf4f1051b44ca6d0"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 40,- "table_index": 0,- "bbox": [- 0.076,- 0.149,- 0.921,- 0.548- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 3- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ]- ],- "text_sha256": "3d4b1caf73d4065fa3a1c122694f0b3810e7f73b08fa09a54afa52e48f442417"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 42,- "table_index": 0,- "bbox": [- 0.068,- 0.236,- 0.93,- 0.689- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 8,- "cols": 13,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 1,- 5- ],- [- 0,- 11,- 2,- 1- ],- [- 0,- 12,- 2,- 1- ],- [- 2,- 0,- 1,- 13- ]- ],- "text_sha256": "66191f7b01a8bd61d6840cc07827c1ae66cc149397051c23d96297b751a15dcf",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 43,- "table_index": 0,- "bbox": [- 0.068,- 0.149,- 0.93,- 0.683- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 9,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 2- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 1,- 5- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 2,- 2,- 1,- 2- ],- [- 3,- 2,- 1,- 2- ],- [- 4,- 2,- 1,- 2- ],- [- 5,- 2,- 1,- 2- ],- [- 6,- 0,- 3,- 3- ],- [- 6,- 3,- 1,- 4- ],- [- 7,- 3,- 1,- 4- ],- [- 8,- 3,- 1,- 4- ]- ],- "text_sha256": "ebb899ba3f5eb926c83dda979f3c49460e19eacc5661698b7cd8a2882bb5d0cc"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 44,- "table_index": 0,- "bbox": [- 0.068,- 0.149,- 0.93,- 0.683- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 9,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 2- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 1,- 5- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 2,- 0,- 1,- 3- ],- [- 2,- 3,- 1,- 4- ],- [- 3,- 0,- 1,- 14- ],- [- 4,- 2,- 1,- 2- ],- [- 5,- 2,- 1,- 2- ],- [- 6,- 2,- 1,- 2- ],- [- 7,- 2,- 1,- 2- ],- [- 8,- 2,- 1,- 2- ]- ],- "text_sha256": "589ce1f526396a66b06f9ab39abf2f0077c220d6114fb569a33fe151155f1ab2",- "target_reason": "canonical_track_alias"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 45,- "table_index": 0,- "bbox": [- 0.069,- 0.149,- 0.93,- 0.552- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 2- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 1,- 5- ],- [- 0,- 12,- 2,- 1- ],- [- 0,- 13,- 2,- 1- ],- [- 2,- 2,- 1,- 2- ],- [- 3,- 0,- 4,- 3- ],- [- 3,- 3,- 1,- 4- ],- [- 4,- 3,- 1,- 4- ],- [- 5,- 3,- 1,- 4- ],- [- 6,- 3,- 1,- 4- ],- [- 7,- 0,- 1,- 14- ],- [- 8,- 0,- 4,- 3- ],- [- 8,- 3,- 1,- 4- ],- [- 9,- 3,- 1,- 4- ],- [- 10,- 3,- 1,- 4- ],- [- 11,- 3,- 1,- 4- ]- ],- "text_sha256": "814854eed2f4961152ef1b17e2422d3cc92250abe8ffdcc8f496cc18c6db2660"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 46,- "table_index": 0,- "bbox": [- 0.069,- 0.149,- 0.929,- 0.585- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "strong_single_column_line_grid",- "rows": 5,- "cols": 1,- "span_signature": [],- "text_sha256": "9a45006a8964a521e15842c4cf9b32e5ed7e22f2c9e03a3d50dc1f44572c624b"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 48,- "table_index": 0,- "bbox": [- 0.046,- 0.236,- 0.953,- 0.677- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 2- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 5- ],- [- 0,- 13,- 2,- 1- ]- ],- "text_sha256": "dc7fa47d9a797d698f0c22c9662e5115cdc7fc54b32c6cd4d62cfbc1d6b646f1"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 49,- "table_index": 0,- "bbox": [- 0.046,- 0.149,- 0.953,- 0.689- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 20,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 2- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 5- ],- [- 0,- 13,- 2,- 1- ]- ],- "text_sha256": "6ce730aa700d6d95ec6769e3155e79bad67166f2c2bbb598bba291555defb193"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 50,- "table_index": 0,- "bbox": [- 0.046,- 0.149,- 0.952,- 0.531- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 13,- "cols": 14,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 2- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 5- ],- [- 0,- 13,- 2,- 1- ],- [- 8,- 0,- 1,- 14- ],- [- 9,- 0,- 4,- 3- ],- [- 9,- 3,- 1,- 5- ],- [- 10,- 3,- 1,- 5- ],- [- 11,- 3,- 1,- 5- ],- [- 12,- 3,- 1,- 5- ]- ],- "text_sha256": "1f273bf0778dc26d6a5331b6f3ff1d876dde83c476d1c9424b552650fd1b3897"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 51,- "table_index": 0,- "bbox": [- 0.078,- 0.279,- 0.921,- 0.478- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 7,- "span_signature": [],- "text_sha256": "dede35df351b7b9948a93309f53cca60fd1a2063ff9973d4d2d9555a1acfba3a"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 53,- "table_index": 0,- "bbox": [- 0.09,- 0.299,- 0.909,- 0.468- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 3,- "cols": 13,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 2- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 2- ],- [- 0,- 10,- 1,- 2- ],- [- 0,- 12,- 2,- 1- ],- [- 2,- 0,- 1,- 13- ]- ],- "text_sha256": "abc97a9378840af6fb20fd2e9c5ed38e575f45ed017c253600be37cdbdbe9d84"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 53,- "table_index": 1,- "bbox": [- 0.08,- 0.545,- 0.918,- 0.633- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 3,- "cols": 7,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 3- ],- [- 0,- 6,- 2,- 1- ],- [- 2,- 0,- 1,- 7- ]- ],- "text_sha256": "529d475596688e733e86c99402a47610179c2f168c2ba2fc1f4fda4980123be5"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 54,- "table_index": 0,- "bbox": [- 0.09,- 0.223,- 0.909,- 0.392- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 3,- "cols": 13,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 2- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 2- ],- [- 0,- 10,- 1,- 2- ],- [- 0,- 12,- 2,- 1- ],- [- 2,- 0,- 1,- 13- ]- ],- "text_sha256": "abc97a9378840af6fb20fd2e9c5ed38e575f45ed017c253600be37cdbdbe9d84"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 55,- "table_index": 0,- "bbox": [- 0.089,- 0.264,- 0.909,- 0.427- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 3,- "cols": 12,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 1,- 2- ],- [- 0,- 5,- 2,- 1- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 1,- 4- ],- [- 2,- 0,- 1,- 12- ]- ],- "text_sha256": "92c6304b4ec5b6eea640d14aed5ab12bee2580517e5ce4710490aaa52db072be"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 56,- "table_index": 0,- "bbox": [- 0.091,- 0.216,- 0.907,- 0.326- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 3,- "cols": 10,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 1,- 2- ],- [- 0,- 6,- 2,- 1- ],- [- 0,- 7,- 2,- 1- ],- [- 0,- 8,- 2,- 1- ],- [- 0,- 9,- 2,- 1- ],- [- 2,- 0,- 1,- 10- ]- ],- "text_sha256": "d8d6e0d1394542f6537e013fe923897065c3d59b9e8ccafcd979fcdc0d737e53"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 57,- "table_index": 0,- "bbox": [- 0.077,- 0.236,- 0.922,- 0.578- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "physical_blank_row",- "rows": 13,- "cols": 11,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 2,- 1- ],- [- 0,- 3,- 2,- 1- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 1,- 5- ],- [- 0,- 10,- 2,- 1- ],- [- 2,- 0,- 1,- 11- ],- [- 3,- 0,- 1,- 11- ],- [- 4,- 0,- 2,- 3- ],- [- 4,- 3,- 1,- 2- ],- [- 5,- 3,- 1,- 2- ],- [- 6,- 0,- 1,- 11- ],- [- 7,- 0,- 1,- 11- ],- [- 8,- 0,- 2,- 3- ],- [- 8,- 3,- 1,- 2- ],- [- 9,- 3,- 1,- 2- ],- [- 10,- 0,- 1,- 11- ],- [- 11,- 0,- 2,- 3- ],- [- 11,- 3,- 1,- 2- ],- [- 12,- 3,- 1,- 2- ]- ],- "text_sha256": "d600150e6ce968d53bff9ec6692f831e0a977c65fb666d1bf6dbb60e813b65b7"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 60,- "table_index": 0,- "bbox": [- 0.081,- 0.279,- 0.917,- 0.687- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 10,- "span_signature": [- [- 0,- 0,- 1,- 10- ]- ],- "text_sha256": "bf969fef10bf457290c223e2a3692b5e2dd0e9c4811e122e2180e1c7ed649e02"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 61,- "table_index": 0,- "bbox": [- 0.081,- 0.149,- 0.917,- 0.338- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 10,- "span_signature": [],- "text_sha256": "db7d286c0a705906d7b51e11454b5f9a86624fd5d0fe00077cf3c79c59f14961"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 61,- "table_index": 1,- "bbox": [- 0.081,- 0.412,- 0.917,- 0.68- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 8,- "cols": 14,- "span_signature": [- [- 0,- 0,- 1,- 8- ],- [- 0,- 8,- 1,- 6- ],- [- 1,- 0,- 1,- 14- ],- [- 2,- 0,- 1,- 3- ],- [- 2,- 3,- 1,- 5- ],- [- 2,- 8,- 1,- 3- ],- [- 2,- 11,- 1,- 3- ],- [- 3,- 0,- 1,- 3- ],- [- 3,- 3,- 1,- 5- ],- [- 3,- 8,- 1,- 3- ],- [- 3,- 11,- 1,- 3- ],- [- 4,- 0,- 1,- 3- ],- [- 4,- 3,- 1,- 5- ],- [- 4,- 8,- 1,- 3- ],- [- 4,- 11,- 1,- 3- ],- [- 5,- 0,- 1,- 3- ],- [- 5,- 3,- 1,- 2- ],- [- 5,- 5,- 1,- 2- ],- [- 5,- 8,- 1,- 3- ],- [- 5,- 11,- 1,- 3- ],- [- 6,- 0,- 1,- 14- ],- [- 7,- 2,- 1,- 2- ],- [- 7,- 4,- 1,- 2- ],- [- 7,- 6,- 1,- 2- ],- [- 7,- 10,- 1,- 2- ]- ],- "text_sha256": "822dea9bb19cd89b08f3c9f8f03363debbe1247bff042639386bacc3c6e91b45"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 62,- "table_index": 0,- "bbox": [- 0.081,- 0.149,- 0.917,- 0.397- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "outer_edge_duplicate_track",- "rows": 4,- "cols": 10,- "span_signature": [- [- 1,- 0,- 1,- 10- ],- [- 2,- 0,- 1,- 10- ],- [- 3,- 0,- 1,- 10- ]- ],- "text_sha256": "2f7304ac1be915f56b615e8b28f27fb7cfecabe2da474dc7e3140e9340c649a6"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 62,- "table_index": 1,- "bbox": [- 0.082,- 0.435,- 0.917,- 0.672- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 7,- "cols": 6,- "span_signature": [- [- 0,- 0,- 1,- 4- ],- [- 0,- 4,- 1,- 2- ],- [- 1,- 0,- 1,- 6- ],- [- 2,- 1,- 1,- 3- ],- [- 3,- 1,- 1,- 3- ],- [- 4,- 1,- 1,- 3- ],- [- 6,- 0,- 1,- 6- ]- ],- "text_sha256": "d9b759e238855d66ac6e99a5ab296428c37eb307d86a209956f0fe809f3906be"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 63,- "table_index": 0,- "bbox": [- 0.081,- 0.149,- 0.917,- 0.401- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "outer_edge_duplicate_track",- "rows": 5,- "cols": 10,- "span_signature": [- [- 2,- 0,- 1,- 10- ],- [- 3,- 0,- 1,- 10- ],- [- 4,- 0,- 1,- 10- ]- ],- "text_sha256": "8cfdf6818cb161bbe5cfe7bddf7fdbf219e63a23c815d0bc488005c144760611"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 63,- "table_index": 1,- "bbox": [- 0.085,- 0.542,- 0.914,- 0.674- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 4,- "span_signature": [- [- 0,- 0,- 2,- 4- ]- ],- "text_sha256": "d03cbdbbbb77e5d8dc54829f1734fa03999fb37c156187bc307d8c0623d0a714"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 64,- "table_index": 0,- "bbox": [- 0.084,- 0.15,- 0.914,- 0.661- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 6,- "span_signature": [- [- 0,- 0,- 2,- 2- ],- [- 0,- 2,- 1,- 4- ],- [- 1,- 2,- 1,- 2- ],- [- 1,- 4,- 1,- 2- ],- [- 2,- 0,- 1,- 2- ],- [- 2,- 2,- 1,- 2- ],- [- 2,- 4,- 1,- 2- ],- [- 3,- 0,- 1,- 6- ],- [- 4,- 0,- 3,- 1- ],- [- 4,- 1,- 3,- 1- ],- [- 4,- 2,- 1,- 4- ],- [- 5,- 3,- 1,- 3- ],- [- 11,- 4,- 1,- 2- ]- ],- "text_sha256": "aeab2147c34d8cc05b75b1d09adbb8340a759eafc92a08033a2cd55a4873b7d2"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 65,- "table_index": 0,- "bbox": [- 0.083,- 0.15,- 0.914,- 0.58- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 5,- "span_signature": [- [- 4,- 0,- 1,- 5- ],- [- 5,- 0,- 1,- 5- ]- ],- "text_sha256": "b32a8464e7faf5248d7ca378266f12df74bd887f9796b15df76847b74f1b7101"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 66,- "table_index": 0,- "bbox": [- 0.056,- 0.243,- 0.942,- 0.686- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "8a4e9961aa5a5435140c4f2739062038693204c0bb455a3f73653a226688e4bf"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 67,- "table_index": 0,- "bbox": [- 0.056,- 0.15,- 0.943,- 0.682- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "dd09406289c01d6df0c8e98a59333df322ba49c87bcb2c5bbebcecfc11313d50"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 68,- "table_index": 0,- "bbox": [- 0.056,- 0.149,- 0.942,- 0.683- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 15,- "span_signature": [],- "text_sha256": "4c886dafbc47f31e94ad48268f5ac10a1ac583a2371c311cce45b0a08582ae05"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 69,- "table_index": 0,- "bbox": [- 0.056,- 0.149,- 0.943,- 0.682- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "947e33095354f178a4a617202c37eeec86622c45fe7c809cd0980277f6659c25"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 70,- "table_index": 0,- "bbox": [- 0.056,- 0.15,- 0.942,- 0.683- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "1b4335d34b5b8c6b6ffbd4abe9cee1671e6477436f6373d02a136cff0b586530"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 71,- "table_index": 0,- "bbox": [- 0.056,- 0.149,- 0.942,- 0.684- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 15,- "span_signature": [],- "text_sha256": "0f82f933f03e9c97e8d130f3535487b55a5151c3e2ceecb531f1fa36870ae28e"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 72,- "table_index": 0,- "bbox": [- 0.056,- 0.15,- 0.942,- 0.682- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "950a2375cc33ec0dc035e36e95f27323d10eafdb4d52170b536670ebc9a6c02a"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 73,- "table_index": 0,- "bbox": [- 0.056,- 0.15,- 0.942,- 0.683- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 15,- "span_signature": [],- "text_sha256": "90a5186230e7044fc036d767a490f434d0f111ce1e9b32f7b91a20da63d6cb07"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 74,- "table_index": 0,- "bbox": [- 0.055,- 0.149,- 0.942,- 0.569- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 15,- "span_signature": [],- "text_sha256": "5a1820e2bc2758c78f996acee7601d16f1df0b503fe43aac0d218eea5dadf6f5"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 77,- "table_index": 0,- "bbox": [- 0.14,- 0.146,- 0.857,- 0.785- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 6,- "span_signature": [],- "text_sha256": "d7a93bbf6282ec895aeb7187f1b7ddc89adfccb67fb2f0f37e5642a81524f320"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 78,- "table_index": 0,- "bbox": [- 0.141,- 0.086,- 0.857,- 0.783- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 6,- "span_signature": [],- "text_sha256": "e7db8dc5f8ac2c65c386a19cd1d416ee0d4b674b01309274d85345ea962c7897"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 79,- "table_index": 0,- "bbox": [- 0.141,- 0.085,- 0.857,- 0.607- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 6,- "span_signature": [],- "text_sha256": "7898488bc258d80a2cba4111bc398aadaf6a5bbb02c7f28e5eddff5c09b47342"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 80,- "table_index": 0,- "bbox": [- 0.047,- 0.313,- 0.951,- 0.418- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 7,- "span_signature": [],- "text_sha256": "09cae9d74ed2ba7375634ae3e4cd3ff33151b2a292b2351d38c747fee58b8261"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 80,- "table_index": 1,- "bbox": [- 0.048,- 0.492,- 0.951,- 0.584- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 6,- "span_signature": [- [- 1,- 0,- 1,- 6- ]- ],- "text_sha256": "41b45c1961218c75b05f99045e659dd9f6dfdc59f6e94a3d6c6a7684ce66a6ef"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 81,- "table_index": 0,- "bbox": [- 0.047,- 0.15,- 0.952,- 0.242- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 6,- "span_signature": [- [- 1,- 0,- 1,- 6- ]- ],- "text_sha256": "a1ac37c84bb7b8913fa19c461706828805cd434bb59c9f0aea8e503e30d521ff"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 81,- "table_index": 1,- "bbox": [- 0.047,- 0.316,- 0.951,- 0.513- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 6,- "span_signature": [],- "text_sha256": "cbe5984248be83176d2cbb8c287552bfa009fa02cc563a9bb0a29e9bc4c3417c"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 81,- "table_index": 2,- "bbox": [- 0.047,- 0.54,- 0.952,- 0.658- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 5,- "span_signature": [],- "text_sha256": "3f5f81a4031362e8d92dc9f5f6e78e1ef3842917e0563c9cfead89e038728d84"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 82,- "table_index": 0,- "bbox": [- 0.047,- 0.197,- 0.951,- 0.29- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 5,- "span_signature": [- [- 1,- 0,- 1,- 5- ]- ],- "text_sha256": "7d02fde92db7ffe3223491df45c34a88eb945d5118544f662d715a21e4de3bef"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 82,- "table_index": 1,- "bbox": [- 0.047,- 0.316,- 0.952,- 0.409- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 5,- "span_signature": [- [- 1,- 0,- 1,- 5- ]- ],- "text_sha256": "194763f985119aadf8aacba0a50a6c2a1e7fb8e5b899c5526ab3ba48aed4ae2c"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 82,- "table_index": 2,- "bbox": [- 0.048,- 0.482,- 0.951,- 0.574- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 5,- "span_signature": [- [- 1,- 0,- 1,- 5- ]- ],- "text_sha256": "7d60b1272dc37d43093a756350b38d3442bfe10d2336a6817f4c7bc2299bc59c"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 83,- "table_index": 0,- "bbox": [- 0.051,- 0.151,- 0.947,- 0.226- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 3,- "span_signature": [],- "text_sha256": "63877a6bc50f9424270d22e6397d432726c5ec0484f7e2d26e8cdb09dd55e943"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 84,- "table_index": 0,- "bbox": [- 0.083,- 0.15,- 0.915,- 0.232- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 6,- "span_signature": [- [- 1,- 0,- 1,- 6- ]- ],- "text_sha256": "d8e47a14def4de0ccd469f94f5a12a1669518bc77011639e2465631b8daa1a6d"- },- {- "file": "procurement_contract_tables.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.139,- 0.489,- 0.859,- 0.569- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 2,- "cols": 2,- "span_signature": [],- "text_sha256": "d43223bb1a67a3c0a843fe927e3d948eec05d03de577bd8b0e15fe6f99512fb9"- },- {- "file": "procurement_contract_tables.pdf",- "page_index": 0,- "table_index": 1,- "bbox": [- 0.14,- 0.828,- 0.859,- 0.898- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 3,- "span_signature": [- [- 1,- 0,- 2,- 1- ],- [- 1,- 1,- 2,- 1- ],- [- 1,- 2,- 2,- 1- ]- ],- "text_sha256": "832106596b6066321211c9862a508270740978bb39d994c0d33d2aaa5564e45b"- },- {- "file": "procurement_contract_tables.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.14,- 0.083,- 0.859,- 0.401- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 4,- "span_signature": [- [- 0,- 1,- 1,- 2- ],- [- 1,- 0,- 4,- 1- ],- [- 2,- 1,- 2,- 1- ],- [- 2,- 2,- 2,- 1- ],- [- 2,- 3,- 2,- 1- ]- ],- "text_sha256": "e3c47adee3fd3bf7db7d317b1bcfcca2793e5f4ca9c479e9a93e97f03d530230"- },- {- "file": "procurement_contract_tables.pdf",- "page_index": 1,- "table_index": 1,- "bbox": [- 0.137,- 0.669,- 0.857,- 0.806- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 2,- "span_signature": [],- "text_sha256": "6060a2f4d6a27746f206f1f432b931d8fee5f99eaa4af146bdd788e9f217c47d"- },- {- "file": "annual_report_research_projects_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.083,- 0.139,- 0.898,- 0.91- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 5,- "span_signature": [],- "text_sha256": "c9a0a360b9163e73a1233514f2ad4c29fd1d9971c6cf33364ff1601db16f060b"- },- {- "file": "annual_report_research_projects_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.084,- 0.083,- 0.897,- 0.281- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 1,- "cols": 5,- "span_signature": [],- "text_sha256": "2ef9fca3d29d3759a310c5a30916bb2995ac66b1b502e60238dd2e584a1830db"- },- {- "file": "annual_report_research_projects_table.pdf",- "page_index": 1,- "table_index": 1,- "bbox": [- 0.084,- 0.305,- 0.897,- 0.481- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 9,- "cols": 4,- "span_signature": [- [- 3,- 0,- 1,- 4- ],- [- 6,- 0,- 1,- 4- ]- ],- "text_sha256": "a2df13db67d4ae47aaf6b5e8035cd3d39a1c4f506ba3aa6ea2b6e9c0023549e8"- },- {- "file": "annual_report_research_projects_table.pdf",- "page_index": 1,- "table_index": 2,- "bbox": [- 0.084,- 0.505,- 0.897,- 0.631- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 5,- "cols": 4,- "span_signature": [],- "text_sha256": "547b1709643781f5b78e628ae41f9f482c92219b11badc57dccdd01291485e63"- },- {- "file": "annual_report_research_projects_table.pdf",- "page_index": 1,- "table_index": 3,- "bbox": [- 0.084,- 0.819,- 0.897,- 0.899- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 4,- "span_signature": [],- "text_sha256": "b0b7de04153947e0bcf15380d261f72de78a9ec68f0cbb2f775423f571573bf5"- },- {- "file": "annual_report_fundraising_projects_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.083,- 0.085,- 0.897,- 0.91- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 14,- "cols": 11,- "span_signature": [- [- 1,- 0,- 1,- 11- ],- [- 10,- 0,- 1,- 11- ],- [- 13,- 1,- 1,- 10- ]- ],- "text_sha256": "7092c61dcc649d55840b9bf272d6a6b3695404cf6abd4de6c5747b6012cd9821"- },- {- "file": "annual_report_fundraising_projects_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.083,- 0.083,- 0.897,- 0.898- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 12,- "cols": 2,- "span_signature": [- [- 3,- 0,- 3,- 1- ],- [- 6,- 0,- 3,- 1- ],- [- 9,- 0,- 2,- 1- ]- ],- "text_sha256": "79d3bee25a495158c12e63120a0f38c66d4f70f07168de58f3b3ffd5026bda16"- },- {- "file": "annual_report_management_roles_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.084,- 0.575,- 0.897,- 0.696- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 6,- "span_signature": [],- "text_sha256": "a2257a9f4b6c73d96d48b7d5f5ea153282c144425210519d4b05ab474ec36175"- },- {- "file": "annual_report_management_roles_table.pdf",- "page_index": 0,- "table_index": 1,- "bbox": [- 0.084,- 0.741,- 0.897,- 0.907- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 6,- "span_signature": [],- "text_sha256": "b9bf1096012d98434c43318fc080b8ab24c64232718a6d82afc67ebcc5481338"- },- {- "file": "annual_report_management_roles_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.083,- 0.084,- 0.898,- 0.881- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 24,- "cols": 6,- "span_signature": [- [- 23,- 1,- 1,- 5- ]- ],- "text_sha256": "1be9a3fe8f7d475326a69238903ade16209bca2ada1bd744f3645c37eddb8950"- },- {- "file": "quarterly_report_financial_tables.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.148,- 0.088,- 0.894,- 0.335- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 6,- "cols": 5,- "span_signature": [- [- 3,- 2,- 1,- 2- ],- [- 4,- 2,- 1,- 2- ],- [- 5,- 2,- 1,- 2- ]- ],- "text_sha256": "0cb3edbf1b1b5f1a3feb6521b4d9acbde71c1d9205e406b019e1a9b72b14228b"- },- {- "file": "quarterly_report_financial_tables.pdf",- "page_index": 0,- "table_index": 1,- "bbox": [- 0.148,- 0.427,- 0.894,- 0.879- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 4,- "span_signature": [],- "text_sha256": "6dce9f81f9858da39dce0d0bf4cc166dbf514347c383877b4dfe8831514fadac"- },- {- "file": "quarterly_report_financial_tables.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.148,- 0.089,- 0.894,- 0.676- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 17,- "cols": 4,- "span_signature": [],- "text_sha256": "2e5eb09dc9ca8c33568a23e95958773a4d2fab956e9be87b30691b81aa6c74be"- },- {- "file": "quarterly_report_financial_tables.pdf",- "page_index": 1,- "table_index": 1,- "bbox": [- 0.149,- 0.833,- 0.893,- 0.892- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 2,- "cols": 3,- "span_signature": [],- "text_sha256": "94867057db096b7d71f2b7f0d6d0ff8d1437de8ce151094ac623c1a753de6a92"- },- {- "file": "fund_manager_profile_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.127,- 0.862,- 0.872,- 0.923- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 6,- "span_signature": [- [- 0,- 0,- 2,- 1- ],- [- 0,- 1,- 2,- 1- ],- [- 0,- 2,- 1,- 2- ],- [- 0,- 4,- 2,- 1- ],- [- 0,- 5,- 2,- 1- ]- ],- "text_sha256": "7bf9d4a2d906bec5baf64375e737dc4eb4d7f5097b60f019fde39dbd2a41198e"- },- {- "file": "fund_manager_profile_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.127,- 0.084,- 0.873,- 0.457- ],- "expected_output": "html",- "review_status": "target_verified",- "rows": 1,- "cols": 6,- "span_signature": [],- "text_sha256": "babbe430014e5944e51e9f25da1d520ef0439c5b40bd1097edc270adbd16f3e3"- },- {- "file": "fund_asset_and_transaction_tables.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.127,- 0.344,- 0.873,- 0.502- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 8,- "cols": 3,- "span_signature": [],- "text_sha256": "51e058a89c37feffd56978170bc12e9d0187fba8034bc13c8ce7e6305c85f765"- },- {- "file": "fund_asset_and_transaction_tables.pdf",- "page_index": 0,- "table_index": 1,- "bbox": [- 0.126,- 0.629,- 0.871,- 0.912- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 5,- "span_signature": [],- "text_sha256": "d53eebe2b7d99c132553288faa2e8c640d7b42dd64f7871d768e4a207fb25a57"- },- {- "file": "fund_asset_and_transaction_tables.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.125,- 0.083,- 0.873,- 0.699- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 5,- "span_signature": [],- "text_sha256": "48a2c768df7a1c9ff7f2c434c6c1dfee2283e1a0c8c485d838e999df6b09dba2"- },- {- "file": "fund_asset_and_transaction_tables.pdf",- "page_index": 1,- "table_index": 1,- "bbox": [- 0.127,- 0.799,- 0.873,- 0.917- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 3,- "cols": 6,- "span_signature": [],- "text_sha256": "142abff4014383f56e8fb81443fe19554f4c3e4960756d504c4a0670a20030e6"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 0,- "table_index": 0,- "bbox": [- 0.052,- 0.131,- 0.946,- 0.919- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 7,- "span_signature": [- [- 1,- 0,- 1,- 6- ]- ],- "text_sha256": "ad5104dbf481f378d0293464db320e2effd71478abed326904ccc38ac3ee41d4"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 1,- "table_index": 0,- "bbox": [- 0.052,- 0.079,- 0.946,- 0.93- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 11,- "cols": 7,- "span_signature": [- [- 3,- 0,- 2,- 1- ],- [- 3,- 1,- 2,- 1- ],- [- 3,- 5,- 2,- 1- ],- [- 3,- 6,- 2,- 1- ],- [- 5,- 0,- 1,- 6- ]- ],- "text_sha256": "cf58d4b97f4f4f0aa18a51b2991e45044131e0b24de417f5af5c56195da8338c"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 2,- "table_index": 0,- "bbox": [- 0.052,- 0.079,- 0.946,- 0.921- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 7,- "span_signature": [- [- 8,- 0,- 1,- 6- ]- ],- "text_sha256": "1ce8fcd3d6ce5f37ed5fc0a4bb8ec55ce1b93e612c5b593dc5b259e5a5f78e3a"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 3,- "table_index": 0,- "bbox": [- 0.052,- 0.079,- 0.946,- 0.92- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 7,- "span_signature": [- [- 8,- 0,- 1,- 6- ]- ],- "text_sha256": "4d30eb5754ad23ffa49865ffc25388adea00e5357bedc743d3654cfb417f3038"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 4,- "table_index": 0,- "bbox": [- 0.052,- 0.08,- 0.947,- 0.909- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 4,- "cols": 7,- "span_signature": [- [- 1,- 0,- 1,- 6- ]- ],- "text_sha256": "3a9cb6a16b0feb1c82f5c93f4406fb1215708142c725aa89aa5692733b44b967"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 5,- "table_index": 0,- "bbox": [- 0.052,- 0.08,- 0.946,- 0.914- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 7,- "cols": 7,- "span_signature": [- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 1- ],- [- 2,- 5,- 3,- 1- ],- [- 2,- 6,- 3,- 1- ],- [- 5,- 0,- 2,- 1- ],- [- 5,- 1,- 2,- 1- ],- [- 5,- 3,- 2,- 1- ],- [- 5,- 4,- 2,- 1- ],- [- 5,- 5,- 2,- 1- ],- [- 5,- 6,- 2,- 1- ]- ],- "text_sha256": "fb1dd5694f1e98481dce883905c377d940d2d262a06a43123befeed68037a5e1"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 6,- "table_index": 0,- "bbox": [- 0.052,- 0.08,- 0.946,- 0.924- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 8,- "cols": 7,- "span_signature": [- [- 1,- 0,- 3,- 1- ],- [- 1,- 1,- 3,- 1- ],- [- 1,- 5,- 3,- 1- ],- [- 1,- 6,- 3,- 1- ]- ],- "text_sha256": "c79dc528a20e014af933f94a2ce051a54b3981d5c267c95cd1ed4bbf81ff5c9f"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 7,- "table_index": 0,- "bbox": [- 0.052,- 0.079,- 0.946,- 0.924- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 10,- "cols": 7,- "span_signature": [- [- 1,- 0,- 2,- 1- ],- [- 1,- 1,- 2,- 1- ],- [- 1,- 5,- 2,- 1- ],- [- 1,- 6,- 2,- 1- ],- [- 4,- 0,- 5,- 1- ],- [- 4,- 1,- 5,- 1- ],- [- 4,- 5,- 2,- 1- ],- [- 4,- 6,- 5,- 1- ],- [- 5,- 2,- 2,- 1- ],- [- 5,- 4,- 2,- 1- ],- [- 6,- 5,- 3,- 1- ]- ],- "text_sha256": "ef769af78876fd1c41c729515ac2c86f847e81517d433386839ccaffb3af9abd"- },- {- "file": "engineering_process_restrictions_table.pdf",- "page_index": 8,- "table_index": 0,- "bbox": [- 0.052,- 0.079,- 0.946,- 0.925- ],- "expected_output": "html",- "review_status": "legacy_unverified",- "rows": 8,- "cols": 7,- "span_signature": [],- "text_sha256": "347dd5bc006f7f7545a522f067dec7352d83d7c5a96face2692a47712cd12cd7"- }- ],- "flash_targets": [- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 4,- "table_index": 0,- "bbox_points": [- 65.8499984741211,- 116.11700439453125,- 776.0500106811523,- 299.91700744628906- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "localized_alias_blank_row",- "rows": 8,- "cols": 20,- "span_signature": [- [- 0,- 1,- 1,- 2- ],- [- 0,- 3,- 1,- 2- ],- [- 0,- 5,- 1,- 2- ],- [- 0,- 7,- 1,- 3- ],- [- 0,- 10,- 1,- 2- ],- [- 0,- 12,- 1,- 2- ],- [- 0,- 14,- 1,- 2- ],- [- 0,- 16,- 1,- 2- ],- [- 0,- 18,- 1,- 2- ],- [- 1,- 0,- 1,- 20- ],- [- 2,- 0,- 3,- 1- ],- [- 2,- 1,- 3,- 2- ],- [- 2,- 3,- 3,- 2- ],- [- 2,- 5,- 1,- 2- ],- [- 2,- 7,- 1,- 3- ],- [- 2,- 10,- 1,- 2- ],- [- 2,- 12,- 1,- 2- ],- [- 2,- 14,- 1,- 2- ],- [- 2,- 16,- 1,- 2- ],- [- 2,- 18,- 1,- 2- ],- [- 3,- 5,- 1,- 2- ],- [- 3,- 7,- 1,- 3- ],- [- 3,- 10,- 1,- 2- ],- [- 3,- 12,- 1,- 2- ],- [- 3,- 14,- 1,- 2- ],- [- 3,- 16,- 1,- 2- ],- [- 3,- 18,- 1,- 2- ],- [- 4,- 5,- 1,- 2- ],- [- 4,- 7,- 1,- 3- ],- [- 4,- 10,- 1,- 2- ],- [- 4,- 12,- 1,- 2- ],- [- 4,- 14,- 1,- 2- ],- [- 4,- 16,- 1,- 2- ],- [- 4,- 18,- 1,- 2- ],- [- 5,- 0,- 1,- 20- ],- [- 6,- 2,- 1,- 2- ],- [- 6,- 4,- 1,- 2- ],- [- 6,- 6,- 1,- 2- ],- [- 6,- 9,- 1,- 2- ],- [- 6,- 11,- 1,- 2- ],- [- 6,- 13,- 1,- 2- ],- [- 6,- 15,- 1,- 2- ],- [- 6,- 17,- 1,- 2- ],- [- 7,- 0,- 1,- 20- ]- ],- "text_sha256": "4a8cd5fa0282d84710832ac77a3d17f0c7777a9bb68eeeb5ad5efcc920a2f217"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 46,- "table_index": 0,- "bbox_points": [- 58.29999923706055,- 89.85000610351562,- 783.5999870300293,- 349.9499816894531- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "strong_single_column_line_grid",- "rows": 5,- "cols": 1,- "span_signature": [],- "text_sha256": "9a45006a8964a521e15842c4cf9b32e5ed7e22f2c9e03a3d50dc1f44572c624b"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 52,- "table_index": 0,- "bbox_points": [- 65.55000305175781,- 89.85002136230469,- 776.3499908447266,- 191.13401794433594- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "strong_single_column_line_grid",- "rows": 2,- "cols": 1,- "span_signature": [],- "text_sha256": "78f42aea1b91cdb6f9c10e211e0154cff1e0f13140731f47ebf6bfaa17099430"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 58,- "table_index": 0,- "bbox_points": [- 65.8499984741211,- 105.60000610351562,- 769.0500106811523,- 370.8340148925781- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "strong_single_column_line_grid",- "rows": 6,- "cols": 1,- "span_signature": [],- "text_sha256": "064700a9efac905c389491468a41b894b19b743efda3afca52482411bcac11f0"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 62,- "table_index": 0,- "bbox_points": [- 69.3499984741211,- 90.0,- 772.5500106811523,- 237.0500030517578- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "outer_edge_duplicate_track",- "rows": 4,- "cols": 10,- "span_signature": [- [- 1,- 0,- 1,- 10- ],- [- 2,- 0,- 1,- 10- ],- [- 3,- 0,- 1,- 10- ]- ],- "text_sha256": "2f7304ac1be915f56b615e8b28f27fb7cfecabe2da474dc7e3140e9340c649a6"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 63,- "table_index": 0,- "bbox_points": [- 69.3499984741211,- 90.0,- 772.5500106811523,- 239.5- ],- "expected_output": "html",- "review_status": "target_verified",- "target_reason": "outer_edge_duplicate_track",- "rows": 5,- "cols": 10,- "span_signature": [- [- 2,- 0,- 1,- 10- ],- [- 3,- 0,- 1,- 10- ],- [- 4,- 0,- 1,- 10- ]- ],- "text_sha256": "8cfdf6818cb161bbe5cfe7bddf7fdbf219e63a23c815d0bc488005c144760611"- }- ],- "accuracy_scope": "targeted_only",- "target_verified_tables": 41,- "legacy_unverified_tables": 92-}diff --git a/tests/fixtures/native_pdf_table_script_truth.json b/tests/fixtures/native_pdf_table_script_truth.jsondeleted file mode 100644index 3a03442e..00000000--- a/tests/fixtures/native_pdf_table_script_truth.json+++ /dev/null@@ -1,1065 +0,0 @@-{- "schema_version": 1,- "matching": [- "file",- "page_index",- "table_index",- "row",- "col",- "text",- "style"- ],- "precision_policy": "actual_runs_must_be_subset_of_truth; required_runs_must_be_emitted",- "runs": [- {- "file": "demo1.pdf",- "page_index": 8,- "table_index": 0,- "row": 0,- "col": 2,- "cell_text": "Rainfalla (mm)",- "text": "a",- "style": "superscript"- },- {- "file": "demo1.pdf",- "page_index": 8,- "table_index": 0,- "row": 1,- "col": 5,- "cell_text": "Total flowreduction (%)b",- "text": "b",- "style": "superscript"- },- {- "file": "demo1.pdf",- "page_index": 8,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "Low flowreduction (%)c",- "text": "c",- "style": "superscript"- },- {- "file": "demo1.pdf",- "page_index": 8,- "table_index": 0,- "row": 3,- "col": 5,- "cell_text": "62d",- "text": "d",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 3,- "col": 0,- "cell_text": "γc",- "text": "c",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 3,- "col": 1,- "cell_text": "Strength of grouping by color similarity 1",- "text": "1",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "γg",- "text": "g",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 4,- "col": 1,- "cell_text": "Strength of grouping by proximity 1",- "text": "1",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "γt",- "text": "t",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 2,- "cell_text": "MDE/s1",- "text": "1",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "FPS2",- "text": "2",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 4,- "cell_text": "Error3",- "text": "3",- "style": "superscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 1,- "col": 3,- "cell_text": "ALLd",- "text": "d",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 7,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 8,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 9,- "col": 0,- "cell_text": "TABLEFORMERLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 10,- "col": 0,- "cell_text": "TAPASBASE inter",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 11,- "col": 0,- "cell_text": "TABLEFORMERBASE inter",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 12,- "col": 0,- "cell_text": "TAPASLARGE inter",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 13,- "col": 0,- "cell_text": "TABLEFORMERLARGE inter",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 3,- "cell_text": "testsimple",- "text": "simple",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 4,- "cell_text": "testcomplex",- "text": "complex",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 5,- "cell_text": "testsmall",- "text": "small",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 7,- "cell_text": "testsimple",- "text": "simple",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 8,- "cell_text": "testcomplex",- "text": "complex",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 1,- "col": 9,- "cell_text": "testsmall",- "text": "small",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 5,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 7,- "col": 0,- "cell_text": "TABLEFORMERLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 8,- "col": 0,- "cell_text": "TAPASBASE inter",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 9,- "col": 0,- "cell_text": "TABLEFORMERBASE inter",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 10,- "col": 0,- "cell_text": "TAPASLARGE inter",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 11,- "col": 0,- "cell_text": "TABLEFORMERLARGE inter",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 3,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 4,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 5,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 6,- "col": 0,- "cell_text": "TABLEFORMERLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 7,- "col": 0,- "cell_text": "TAPASBASE inter-sqa",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 8,- "col": 0,- "cell_text": "TABLEFORMERBASE inter-sqa",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 9,- "col": 0,- "cell_text": "TAPASLARGE inter-sqa",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 10,- "col": 0,- "cell_text": "TABLEFORMERLARGE inter-sqa",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 1,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 2,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 3,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "TABLEFORMERLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 1,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 2,- "col": 0,- "cell_text": "TAPASBASE-SAT",- "text": "BASE-SAT",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 3,- "col": 0,- "cell_text": "TABLEFORMERBASE-SO",- "text": "BASE-SO",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 4,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 2,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 3,- "col": 0,- "cell_text": "TAPASBASE 1p",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "TAPASBASE 2p",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 5,- "col": 0,- "cell_text": "TAPASBASE 4p",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "TAPASBASE 8p",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 7,- "col": 0,- "cell_text": "TAPASBASE 16p",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 8,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 1,- "row": 1,- "col": 0,- "cell_text": "TABLEFORMERBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 1,- "cell_text": "T0, K",- "text": "0",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "N(EF), eV-1 cm-3",- "text": "-1",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "N(EF), eV-1 cm-3",- "text": "-3",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "N(EF), eV-1 cm-3",- "text": "F",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 1,- "col": 2,- "cell_text": "9.2 × 103",- "text": "3",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 1,- "col": 5,- "cell_text": "1.28 × 10-4",- "text": "-4",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 2,- "col": 2,- "cell_text": "7.2 × 104",- "text": "4",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 2,- "col": 5,- "cell_text": "2.72 × 10-5",- "text": "-5",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 2,- "col": 1,- "cell_text": "26.5 ± 4.3a",- "text": "a",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 3,- "col": 1,- "cell_text": "25.5 ± 3.9a",- "text": "a",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 4,- "col": 1,- "cell_text": "27.0 ± 3.0a",- "text": "a",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 4,- "col": 2,- "cell_text": "39.5 ± 4.2a",- "text": "a",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 5,- "col": 1,- "cell_text": "6.4 ± 3.0a,b,c",- "text": "a,b,c",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 6,- "col": 1,- "cell_text": "6.1 ± 2.8a,b,d",- "text": "a,b,d",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 6,- "col": 2,- "cell_text": "40.7 ± 4.1a",- "text": "a",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 48,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 49,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 50,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- }- ],- "required_runs": [- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 3,- "col": 0,- "cell_text": "γc",- "text": "c",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "γg",- "text": "g",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 3,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "γt",- "text": "t",- "style": "subscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 2,- "cell_text": "MDE/s1",- "text": "1",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "FPS2",- "text": "2",- "style": "superscript"- },- {- "file": "demo2.pdf",- "page_index": 4,- "table_index": 0,- "row": 0,- "col": 4,- "cell_text": "Error3",- "text": "3",- "style": "superscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 4,- "table_index": 0,- "row": 8,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 4,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 0,- "row": 6,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 3,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 5,- "table_index": 1,- "row": 5,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 1,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 0,- "row": 3,- "col": 0,- "cell_text": "TAPASLARGE",- "text": "LARGE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 1,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 2,- "col": 0,- "cell_text": "TAPASBASE-SAT",- "text": "BASE-SAT",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "row": 3,- "col": 0,- "cell_text": "TABLEFORMERBASE-SO",- "text": "BASE-SO",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 7,- "table_index": 0,- "row": 2,- "col": 0,- "cell_text": "TAPASBASE",- "text": "BASE",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 1,- "cell_text": "T0, K",- "text": "0",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "N(EF), eV-1 cm-3",- "text": "-1",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 0,- "col": 3,- "cell_text": "N(EF), eV-1 cm-3",- "text": "F",- "style": "subscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 1,- "col": 2,- "cell_text": "9.2 × 103",- "text": "3",- "style": "superscript"- },- {- "file": "mixed_elements_pages_03_06.pdf",- "page_index": 2,- "table_index": 0,- "row": 1,- "col": 5,- "cell_text": "1.28 × 10-4",- "text": "-4",- "style": "superscript"- },- {- "file": "mixed_elements_pages_11_15.pdf",- "page_index": 3,- "table_index": 0,- "row": 5,- "col": 1,- "cell_text": "6.4 ± 3.0a,b,c",- "text": "a,b,c",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 48,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 49,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- },- {- "file": "pollutant_discharge_tables.pdf",- "page_index": 50,- "table_index": 0,- "row": 1,- "col": 6,- "cell_text": "浓度限值(mg/Nm3)",- "text": "3",- "style": "superscript"- }- ],- "forbidden_runs": [],- "forbidden_plain_cells": [- "最小值",- "最大值",- "序号",- "7,059.94",- "2,845.04"- ]-}diff --git a/tests/fixtures/ofd/README.md b/tests/fixtures/ofd/README.mddeleted file mode 100644index 0cab32ad..00000000--- a/tests/fixtures/ofd/README.md+++ /dev/null@@ -1,23 +0,0 @@-# OFD fixtures--自动化单元测试通过 `tests/unittest/_ofd_test_utils.py` 在内存中构造最小 OFD 包,避免把来源或隐私不明确的 issue-附件提交到仓库。--本地真实语料测试会在以下目录存在时自动运行:--```text-tmp/ofd_samples/ofdrw_issues_20260828/ofd-```--其中以下文件已在 2026-08-28 对照 OFDRW `7459e35082170061efa6b399a6518dbc219f08ac` 的官方测试资源,-SHA-256 完全一致:--| 本地 SHA-256 前缀 | OFDRW 源路径 |-|---|---|-| `a7b6f9eceb` | `ofdrw-converter/src/test/resources/helloworld.ofd` |-| `a2b9080ae3` | `ofdrw-converter/src/test/resources/999.ofd` |-| `dfed483fa0` | `ofdrw-layout/src/test/resources/AddWatermarkAnnot.ofd` |-| `e7cac8d149` | `ofdrw-layout/src/test/resources/no_page_container.ofd` |-| `bff244b113` | `ofdrw-layout/src/test/resources/keyword2.ofd` |--OFDRW 使用 Apache License 2.0。其余 issue 附件仅作为本地兼容语料,不应在未确认授权和隐私边界前提交。diff --git a/tests/unittest/_docx_equationxml_test_utils.py b/tests/unittest/_docx_equationxml_test_utils.pyindex bddcbfb0..4632c142 100644--- a/tests/unittest/_docx_equationxml_test_utils.py+++ b/tests/unittest/_docx_equationxml_test_utils.py@@ -5,8 +5,6 @@ from __future__ import annotationsfrom io import BytesIOfrom zipfile import ZipFile-from lxml import etree # type: ignore[reportAttributeAccessIssue]-from _mtef_test_utils import _TINY_PNGfrom _ooxml_mtef_test_utils import (M_NS,@@ -16,6 +14,7 @@ from _ooxml_mtef_test_utils import (_rewrite_zip,build_equation_docx,)+from lxml import etree # type: ignore[reportAttributeAccessIssue]WORD_2003_NS = "http://schemas.microsoft.com/office/word/2003/wordml"@@ -96,11 +95,7 @@ def _patch_equationxml_part("""向一个 Word XML part 的公式 shape 写入属性并可移除 OLE 语义对象。"""root = etree.fromstring(payload)- shapes = [- shape- for shape in root.findall(f".//{{{V_NS}}}shape")- if shape.find(f"{{{V_NS}}}imagedata") is not None- ]+ shapes = [shape for shape in root.findall(f".//{{{V_NS}}}shape") if shape.find(f"{{{V_NS}}}imagedata") is not None]for shape, equation_xml in zip(shapes, equation_xml_values, strict=False):shape.set("equationxml", equation_xml)if paragraph_style:@@ -116,9 +111,7 @@ def _patch_equationxml_part(if share_preview and len(shapes) > 1:first_image = shapes[0].find(f"{{{V_NS}}}imagedata")first_rel_id = (- first_image.get(- "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"- )+ first_image.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")if first_image is not Noneelse None)@@ -178,11 +171,7 @@ def build_equationxml_docx(consumed = 0with ZipFile(BytesIO(package)) as source:part_names = [- name- for name in source.namelist()- if name.startswith("word/")- and name.endswith(".xml")- and "/_rels/" not in name+ name for name in source.namelist() if name.startswith("word/") and name.endswith(".xml") and "/_rels/" not in name]if header_footer:part_names.sort(diff --git a/tests/unittest/_epub_test_utils.py b/tests/unittest/_epub_test_utils.pyindex 78971c32..03cc926e 100644--- a/tests/unittest/_epub_test_utils.py+++ b/tests/unittest/_epub_test_utils.py@@ -5,7 +5,6 @@ import htmlfrom io import BytesIOfrom zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile-_PNG_BYTES = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")@@ -297,6 +296,3 @@ def build_epub_table_toc_fixture() -> bytes:package.writestr("EPUB/contents.xhtml", contents, compress_type=ZIP_DEFLATED)package.writestr("EPUB/chapter.xhtml", chapter, compress_type=ZIP_DEFLATED)return output.getvalue()---__all__ = ["build_epub2_fixture", "build_epub_fixture", "build_epub_notes_fixture", "build_epub_table_toc_fixture"]diff --git a/tests/unittest/_flash_pdf_test_utils.py b/tests/unittest/_flash_pdf_test_utils.pydeleted file mode 100644index 70e9d321..00000000--- a/tests/unittest/_flash_pdf_test_utils.py+++ /dev/null@@ -1,156 +0,0 @@-from __future__ import annotations--import hashlib-import json-from typing import Any--from docvortex.analyzers.native.pdf import models---_IGNORED_FINGERPRINT_KEYS = {- "bbox",- "lines",- "image_path",- "image_url",- "img_path",- "_layout_tree",-}---def _sha256_bytes(value: bytes) -> str:- """返回测试载荷的稳定 SHA256。"""-- return hashlib.sha256(value).hexdigest()---def _canonical_value(value: Any) -> Any:- """移除允许变化的几何与大载荷,保留语义标签、层级和可见内容。"""-- if isinstance(value, dict):- return {- str(key): _canonical_value(item)- for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))- if key not in _IGNORED_FINGERPRINT_KEYS- }- if isinstance(value, list):- return [_canonical_value(item) for item in value]- if isinstance(value, str) and len(value) > 2048:- return {"sha256": _sha256_bytes(value.encode("utf-8", errors="replace")), "length": len(value)}- return value---def _visible_text(value: Any) -> str:- """递归提取指纹计算使用的可见文本。"""-- if isinstance(value, str):- return value- if isinstance(value, list):- return "".join(_visible_text(item) for item in value)- if isinstance(value, dict):- return _visible_text(value.get("content", ""))- return ""---def _page_fingerprint(page: list[dict[str, Any]]) -> str:- """计算忽略输出 bbox 后的逐页语义指纹。"""-- payload = json.dumps(_canonical_value(page), ensure_ascii=False, sort_keys=True, separators=(",", ":"))- return _sha256_bytes(payload.encode("utf-8"))---def _page_bbox_fingerprint(page: list[dict[str, Any]]) -> str:- """计算类型、文本顺序和公开 bbox 共同组成的逐页指纹。"""-- payload = [- {- "type": block.get("type"),- "bbox": block.get("bbox"),- "text_sha256": _sha256_bytes(_visible_text(block.get("content")).encode("utf-8", errors="replace")),- }- for block in page- ]- return _sha256_bytes(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8"))---def _geometry_summary_mismatch(- file_name: str,- expected_document: dict[str, Any],- actual_document: dict[str, Any],-) -> dict[str, Any] | None:- """比较版本化几何摘要,并返回缺失或数值漂移的结构化诊断。"""-- expected_summary = expected_document.get("expected_geometry_summary")- actual_summary = actual_document.get("geometry_summary")- if not isinstance(expected_summary, dict):- return {- "file": file_name,- "reason": "geometry_summary_expectation_missing",- }- if actual_summary != expected_summary:- return {- "file": file_name,- "reason": "geometry_summary_mismatch",- "expected": expected_summary,- "actual": actual_summary,- }- return None---def _text_line(- text: str,- bbox: tuple[float, float, float, float],- source_index: int,- *,- angle: int = 0,- visual_row_id: int | None = None,- run_index: int = 0,- split_from_row: bool = False,- effective_height: float | None = None,- font_signature: tuple[str, int] | None = None,- font_coverage: float = 0.0,- dominant_font_weight: float | None = None,- median_glyph_width: float | None = None,- leading_emphasis_width: float | None = None,- leading_typography_width: float | None = None,- paragraph_formula_context: bool = False,- preserve_split_boundary: bool = False,- semantic_type: str | None = None,- ink_bbox: tuple[float, float, float, float] | None = None,-) -> models._LineItem:- """构造栏带、排版恢复与图形标签测试使用的原生文本行。"""-- return models._LineItem(- text=text,- bbox=bbox,- ink_bbox=ink_bbox,- angle=angle,- source_index=source_index,- visual_row_id=visual_row_id,- run_index=run_index,- effective_height=effective_height or (bbox[3] - bbox[1]),- font_signature=font_signature,- font_coverage=font_coverage,- dominant_font_weight=dominant_font_weight,- median_glyph_width=median_glyph_width,- leading_emphasis_width=leading_emphasis_width,- leading_typography_width=leading_typography_width,- paragraph_formula_context=paragraph_formula_context,- split_from_row=split_from_row,- preserve_split_boundary=preserve_split_boundary,- semantic_type=semantic_type,- )---def _prepared_text_page(- *lines: models._LineItem,- page_size: tuple[float, float] = (100.0, 100.0),-) -> models._PreparedPage:- """构造跨页边缘类型测试使用的无容器轻量页面。"""-- return models._PreparedPage(- page_size=page_size,- remaining_lines=list(lines),- table_bboxes=[],- drawing_lines=[],- fixed_blocks=[],- )diff --git a/tests/unittest/_image_mtef_test_utils.py b/tests/unittest/_image_mtef_test_utils.pyindex 4d8eef42..7875bd8e 100644--- a/tests/unittest/_image_mtef_test_utils.py+++ b/tests/unittest/_image_mtef_test_utils.py@@ -5,9 +5,7 @@ from __future__ import annotationsimport base64import struct-_TINY_GIF = base64.b64decode(- "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"-)+_TINY_GIF = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")def _wmf_record(function: int, payload: bytes = b"") -> bytes:@@ -63,14 +61,6 @@ def build_wmf(return placeable_header + metafile-def pre6_wmf_comment(mtef: bytes) -> bytes:- """构造 MathType 6.0b 前的单 comment MTEF 头。"""-- if len(mtef) > 0xFFFF:- raise ValueError("pre-6 WMF fixture MTEF is too large")- return b"MathType" + struct.pack("<HH", 0x5555, len(mtef)) + mtef--def baseline_wmf_comment(delta: int = 0) -> bytes:"""构造必须被忽略的 MathType baseline comment。"""@@ -85,13 +75,7 @@ def apps_mfcc_comment() -> bytes:"""构造一个 AppsMFCC v1 chunk。"""- return (- b"AppsMFCC"- + struct.pack("<HII", 1, total_length, len(chunk))- + signature.encode("ascii")- + b"\x00"- + chunk- )+ return b"AppsMFCC" + struct.pack("<HII", 1, total_length, len(chunk)) + signature.encode("ascii") + b"\x00" + chunkdef apps_mfcc_comments(@@ -125,8 +109,7 @@ def _gif_application_extension(if len(authentication) != 3 or not 0 < chunk_size <= 255:raise ValueError("GIF application fixture parameters are invalid")subblocks = b"".join(- bytes([len(payload[start : start + chunk_size])])- + payload[start : start + chunk_size]+ bytes([len(payload[start : start + chunk_size])]) + payload[start : start + chunk_size]for start in range(0, len(payload), chunk_size))return b"\x21\xff\x0bMathType" + authentication + subblocks + b"\x00"@@ -138,11 +121,7 @@ def build_gif_with_extensions(extensions: list[bytes]) -> bytes:image_separator = _TINY_GIF.find(b"\x2c")if image_separator < 0:raise ValueError("tiny GIF fixture has no image descriptor")- return (- _TINY_GIF[:image_separator]- + b"".join(extensions)- + _TINY_GIF[image_separator:]- )+ return _TINY_GIF[:image_separator] + b"".join(extensions) + _TINY_GIF[image_separator:]def gif_mtef_extension(@@ -167,9 +146,7 @@ def build_gif_with_mtef() -> bytes:"""构造带 MathType/001 MTEF 及可选 002 baseline 的有效 GIF。"""- extensions = [- gif_mtef_extension(mtef, chunk_size=chunk_size)- ]+ extensions = [gif_mtef_extension(mtef, chunk_size=chunk_size)]if include_baseline:extensions.insert(0,diff --git a/tests/unittest/_legacy_ppt_test_utils.py b/tests/unittest/_legacy_ppt_test_utils.pyindex ce66cd37..eda8319c 100644--- a/tests/unittest/_legacy_ppt_test_utils.py+++ b/tests/unittest/_legacy_ppt_test_utils.py@@ -108,16 +108,11 @@ def build_equation_ppt()slide_persist_ids = list(range(2, 2 + len(formulas)))- storage_persist_ids = list(- range(2 + len(formulas), 2 + len(formulas) * 2)- )+ storage_persist_ids = list(range(2 + len(formulas), 2 + len(formulas) * 2))slide_list = _ppt_container(0,0x0FF0,- b"".join(- persist_atom(persist_id, 256 + index)- for index, persist_id in enumerate(slide_persist_ids)- ),+ b"".join(persist_atom(persist_id, 256 + index) for index, persist_id in enumerate(slide_persist_ids)),)external_objects = []for index, storage_id in enumerate(storage_persist_ids, start=1):@@ -216,9 +211,7 @@ def build_equation_ppt(0x0FF6,struct.pack("<III", 20, 0xE391C05F, edit_offset),)- return _build_cfb(- [("Current User", current_user), ("PowerPoint Document", stream)]- )+ return _build_cfb([("Current User", current_user), ("PowerPoint Document", stream)])def _build_cfb(streams: list[tuple[str, bytes]]) -> bytes:@@ -418,9 +411,7 @@ def build_multimaster_ppt() -> bytes:for persist_id, record in records:offsets[persist_id] = len(stream)stream += record- directory = struct.pack("<I", 1 | (5 << 20)) + struct.pack(- "<5I", *(offsets[index] for index in range(1, 6))- )+ directory = struct.pack("<I", 1 | (5 << 20)) + struct.pack("<5I", *(offsets[index] for index in range(1, 6)))directory_offset = len(stream)stream += _ppt_record(0, 0x1772, directory)edit_offset = len(stream)diff --git a/tests/unittest/_legacy_xls_test_utils.py b/tests/unittest/_legacy_xls_test_utils.pyindex 772bd153..f1be9c2f 100644--- a/tests/unittest/_legacy_xls_test_utils.py+++ b/tests/unittest/_legacy_xls_test_utils.py@@ -2,13 +2,13 @@from __future__ import annotations-from dataclasses import dataclassimport structimport uuidimport zlib+from dataclasses import dataclass-from _mtef_test_utils import _TINY_PNG, _build_nested_cfb, equation_nativefrom _legacy_ppt_test_utils import _build_cfb+from _mtef_test_utils import _TINY_PNG, _build_nested_cfb, equation_native@dataclass(frozen=True, slots=True)@@ -35,12 +35,15 @@ def _officeart_record() -> bytes:"""构造一条 OfficeArt record。"""- return struct.pack(- "<HHI",- (instance << 4) | version,- record_type,- len(payload),- ) + payload+ return (+ struct.pack(+ "<HHI",+ (instance << 4) | version,+ record_type,+ len(payload),+ )+ + payload+ )def _equation_shape(row: int, col: int, object_id: int, *, preview: bool) -> bytes:@@ -92,11 +95,7 @@ def _equation_obj(location: int, object_id: int) -> bytes:parsed_formula = struct.pack("<H", 5) + b"\x00" * 4 + b"\x02" + b"\x00" * 4embed_info = b"\x03\x00\x00"obj_formula = parsed_formula + embed_info- pict_formula = (- struct.pack("<H", len(obj_formula))- + obj_formula- + struct.pack("<I", location)- )+ pict_formula = struct.pack("<H", len(obj_formula)) + obj_formula + struct.pack("<I", location)payload = b"".join((struct.pack("<HH", 0x0015, len(cmo)) + cmo,@@ -205,12 +204,6 @@ def label_cell(row: int, col: int, text: str, *, xf_index: int = 0) -> bytes:return biff_record(0x0204, struct.pack("<HHH", row, col, xf_index) + string)-def number_cell(row: int, col: int, value: float, *, xf_index: int = 0) -> bytes:- """构造 NUMBER 单元格。"""-- return biff_record(0x0203, struct.pack("<HHHd", row, col, xf_index, value))--def formula_number_cell(row: int, col: int, value: float, *, xf_index: int = 0) -> bytes:"""构造仅依赖缓存数值的 FORMULA 单元格。"""@@ -302,10 +295,7 @@ def continued_rich_sst(text: str, starts: list[tuple[int, int]]) -> bytes:base = struct.pack("<IIHBH", 1, 1, unit_count, 0x09, len(starts))base += first_charactercontinuation = bytes([0x01]) + remaining_characters- continuation += b"".join(- struct.pack("<HH", character_index, font_index)- for character_index, font_index in starts- )+ continuation += b"".join(struct.pack("<HH", character_index, font_index) for character_index, font_index in starts)return biff_record(0x00FC, base) + biff_record(0x003C, continuation)@@ -352,10 +342,7 @@ def build_xls(cursor += len(stream)if corrupt_first_offset and offsets:offsets[0] = 0x7FFF_FFF0- directory = b"".join(- boundsheet(offset, sheet)- for offset, sheet in zip(offsets, sheets, strict=True)- )+ directory = b"".join(boundsheet(offset, sheet) for offset, sheet in zip(offsets, sheets, strict=True))workbook = prefix + directory + biff_record(0x000A) + b"".join(sheet_streams)if equations:return _build_xls_with_embeddings(@@ -383,11 +370,7 @@ def build_equation_xls(_equation_shape(index - 1, 0, index, preview=preview),)drawing_records += _equation_obj(location, index)- globals_records = (- biff_record(0x00EB, _preview_bstore(preview_payload))- if preview- else b""- )+ globals_records = biff_record(0x00EB, _preview_bstore(preview_payload)) if preview else b""return build_xls([SheetFixture("Equations", cell_records + drawing_records)],globals_records=globals_records,diff --git a/tests/unittest/_metafile_test_utils.py b/tests/unittest/_metafile_test_utils.pydeleted file mode 100644index 835b1beb..00000000--- a/tests/unittest/_metafile_test_utils.py+++ /dev/null@@ -1,364 +0,0 @@-"""构造确定性 WMF/EMF 测试载荷。"""--from __future__ import annotations--import struct---def _pad4(data: bytes) -> bytes:- """把 EMF payload 填充到 4 字节边界。"""- return data + b"\x00" * (-len(data) % 4)---def emf_record(record_type: int, payload: bytes = b"") -> bytes:- """构造带通用头部和 4 字节对齐的 EMF record。"""- aligned = _pad4(payload)- return struct.pack("<II", record_type, 8 + len(aligned)) + aligned---def _emf_header(- total_bytes: int,- record_count: int,- *,- bounds: tuple[int, int, int, int],- frame: tuple[int, int, int, int],-) -> bytes:- """构造满足 EMR_HEADER 基础版本的 88 字节头部。"""- header = bytearray(88)- struct.pack_into("<II", header, 0, 1, 88)- struct.pack_into("<4i", header, 8, *bounds)- struct.pack_into("<4i", header, 24, *frame)- struct.pack_into("<I", header, 40, 0x464D4520)- struct.pack_into("<I", header, 44, 0x00010000)- struct.pack_into("<II", header, 48, total_bytes, record_count)- struct.pack_into("<HH", header, 56, 16, 0)- struct.pack_into("<III", header, 60, 0, 0, 0)- struct.pack_into("<2i", header, 72, 1000, 1000)- struct.pack_into("<2i", header, 80, 254, 254)- return bytes(header)---def build_emf(- records: list[bytes],- *,- bounds: tuple[int, int, int, int] = (0, 0, 100, 100),- frame: tuple[int, int, int, int] = (0, 0, 2540, 2540),-) -> bytes:- """为给定 records 补齐 EMR_HEADER 与 EMR_EOF。"""- eof = emf_record(14, struct.pack("<III", 0, 0, 20))- body = b"".join(records) + eof- total_bytes = 88 + len(body)- return _emf_header(total_bytes, len(records) + 2, bounds=bounds, frame=frame) + body---def emf_create_pen(handle: int, colorref: int, *, width: int = 1, style: int = 0) -> bytes:- """构造 EMR_CREATEPEN。"""- return emf_record(38, struct.pack("<IIiiI", handle, style, width, 0, colorref))---def emf_create_brush(handle: int, colorref: int, *, style: int = 0) -> bytes:- """构造 EMR_CREATEBRUSHINDIRECT。"""- return emf_record(39, struct.pack("<IIII", handle, style, colorref, 0))---def emf_select_object(handle: int) -> bytes:- """构造 EMR_SELECTOBJECT。"""- return emf_record(37, struct.pack("<I", handle))---def emf_rectangle(left: int, top: int, right: int, bottom: int) -> bytes:- """构造 EMR_RECTANGLE。"""- return emf_record(43, struct.pack("<4i", left, top, right, bottom))---def emf_savedc() -> bytes:- """构造 EMR_SAVEDC。"""- return emf_record(33)---def emf_restoredc(level: int = -1) -> bytes:- """构造 EMR_RESTOREDC。"""- return emf_record(34, struct.pack("<i", level))---def emf_set_world_transform(matrix: tuple[float, float, float, float, float, float]) -> bytes:- """构造 EMR_SETWORLDTRANSFORM。"""- return emf_record(35, struct.pack("<6f", *matrix))---def emf_move_to(x: int, y: int) -> bytes:- """构造 EMR_MOVETOEX。"""- return emf_record(27, struct.pack("<2i", x, y))---def emf_line_to(x: int, y: int) -> bytes:- """构造 EMR_LINETO。"""- return emf_record(54, struct.pack("<2i", x, y))---def emf_intersect_clip_rect(left: int, top: int, right: int, bottom: int) -> bytes:- """构造 EMR_INTERSECTCLIPRECT。"""- return emf_record(30, struct.pack("<4i", left, top, right, bottom))---def emf_angle_arc(center_x: int, center_y: int, radius: int, start_angle: float, sweep_angle: float) -> bytes:- """构造 EMR_ANGLEARC。"""- return emf_record(41, struct.pack("<iiIff", center_x, center_y, radius, start_angle, sweep_angle))---def emf_arc_to(- rect: tuple[int, int, int, int],- start: tuple[int, int],- end: tuple[int, int],-) -> bytes:- """构造 EMR_ARCTO,start/end 可位于椭圆边界之外。"""- return emf_record(55, struct.pack("<8i", *rect, *start, *end))---def emf_begin_path() -> bytes:- """构造 EMR_BEGINPATH。"""- return emf_record(59)---def emf_end_path() -> bytes:- """构造 EMR_ENDPATH。"""- return emf_record(60)---def emf_close_figure() -> bytes:- """构造 EMR_CLOSEFIGURE。"""- return emf_record(61)---def emf_fill_path() -> bytes:- """构造 EMR_FILLPATH。"""- return emf_record(62)---def emf_stroke_and_fill_path() -> bytes:- """构造 EMR_STROKEANDFILLPATH。"""- return emf_record(63)---def emf_stroke_path() -> bytes:- """构造 EMR_STROKEPATH。"""- return emf_record(64)---def _emf_compact_poly_record(record_type: int, points: list[tuple[int, int]]) -> bytes:- """构造使用 PointS 数组的紧凑 EMF poly record。"""- if points:- xs = [point[0] for point in points]- ys = [point[1] for point in points]- bounds = min(xs), min(ys), max(xs), max(ys)- else:- bounds = (0, 0, 0, 0)- payload = struct.pack("<4iI", *bounds, len(points))- payload += b"".join(struct.pack("<2h", *point) for point in points)- return emf_record(record_type, payload)---def emf_polyline_to(points: list[tuple[int, int]]) -> bytes:- """构造 EMR_POLYLINETO16。"""- return _emf_compact_poly_record(89, points)---def emf_polybezier(points: list[tuple[int, int]], *, to: bool) -> bytes:- """构造 EMR_POLYBEZIER16 或 EMR_POLYBEZIERTO16。"""- return _emf_compact_poly_record(88 if to else 85, points)---def emf_set_polyfill_mode(mode: int) -> bytes:- """构造 EMR_SETPOLYFILLMODE。"""- return emf_record(19, struct.pack("<I", mode))---def emf_set_miter_limit(value: float) -> bytes:- """构造 EMR_SETMITERLIMIT。"""- return emf_record(58, struct.pack("<f", value))---def emf_set_text_align(value: int) -> bytes:- """构造 EMR_SETTEXTALIGN。"""- return emf_record(22, struct.pack("<I", value))---def emf_font(handle: int, face_name: str = "DejaVu Sans", *, height: int = -14) -> bytes:- """构造只填充常用 LOGFONTW 字段的 EMR_EXTCREATEFONTINDIRECTW。"""- logfont = bytearray(92)- struct.pack_into("<iiiii", logfont, 0, height, 0, 0, 0, 400)- logfont[23] = 1- encoded = face_name.encode("utf-16le")[:62]- logfont[28 : 28 + len(encoded)] = encoded- return emf_record(82, struct.pack("<I", handle) + bytes(logfont))---def emf_text(text: str, x: int, y: int, *, dx: int | None = 12) -> bytes:- """构造可选显式 Dx 数组的 EMR_EXTTEXTOUTW。"""- encoded = text.encode("utf-16le")- record = bytearray(76)- nominal_dx = dx if dx is not None else 12- struct.pack_into("<II", record, 0, 84, 0)- struct.pack_into("<4i", record, 8, x, y - 20, x + max(1, len(text)) * nominal_dx, y + 5)- struct.pack_into("<Iff", record, 24, 1, 1.0, 1.0)- struct.pack_into("<2i", record, 36, x, y)- struct.pack_into("<I", record, 44, len(text))- struct.pack_into("<I", record, 48, 76)- struct.pack_into("<I", record, 52, 0)- struct.pack_into("<4i", record, 56, 0, 0, -1, -1)- string_and_padding = _pad4(encoded)- record.extend(string_and_padding)- if dx is not None:- dx_offset = 76 + len(string_and_padding)- struct.pack_into("<I", record, 72, dx_offset)- record.extend(struct.pack(f"<{len(text)}i", *([dx] * len(text))))- struct.pack_into("<I", record, 4, len(record))- return bytes(record)---def emf_stretch_dib() -> bytes:- """构造含红绿蓝白四像素的 EMR_STRETCHDIBITS。"""- header = bytearray(40)- struct.pack_into("<IiiHHIIiiII", header, 0, 40, 2, -2, 1, 32, 0, 16, 0, 0, 0, 0)- bits = bytes(- (- 0,- 0,- 255,- 255,- 0,- 255,- 0,- 255,- 255,- 0,- 0,- 255,- 255,- 255,- 255,- 255,- )- )- record = bytearray(80)- struct.pack_into("<II", record, 0, 81, 80 + len(header) + len(bits))- struct.pack_into("<4i", record, 8, 10, 10, 90, 90)- struct.pack_into("<6i", record, 24, 10, 10, 0, 0, 2, 2)- struct.pack_into("<4I", record, 48, 80, len(header), 80 + len(header), len(bits))- struct.pack_into("<IIii", record, 64, 0, 0x00CC0020, 80, 80)- record.extend(header)- record.extend(bits)- return bytes(record)---def emfplus_comment(*, dual: bool) -> bytes:- """构造只含 EMF+ Header 的 EMR_COMMENT。"""- plus = struct.pack("<IHHII", 0x2B464D45, 0x4001, 1 if dual else 0, 12, 0)- return emf_record(70, struct.pack("<I", len(plus)) + plus)---def wmf_record(function: int, payload: bytes = b"") -> bytes:- """构造按 WORD 计长的 WMF record。"""- if len(payload) % 2:- payload += b"\x00"- return struct.pack("<IH", (6 + len(payload)) // 2, function) + payload---def wmf_move_to(x: int, y: int) -> bytes:- """构造 META_MOVETO。"""- return wmf_record(0x0214, struct.pack("<hh", y, x))---def wmf_set_text_align(value: int) -> bytes:- """构造 META_SETTEXTALIGN。"""- return wmf_record(0x012E, struct.pack("<H", value))---def wmf_set_map_mode(value: int) -> bytes:- """构造 META_SETMAPMODE。"""- return wmf_record(0x0103, struct.pack("<h", value))---def wmf_rectangle(left: int, top: int, right: int, bottom: int) -> bytes:- """构造 META_RECTANGLE。"""- return wmf_record(0x041B, struct.pack("<hhhh", bottom, right, top, left))---def wmf_textout(text: str, x: int, y: int) -> bytes:- """构造没有显式字符 spacing 的 META_TEXTOUT。"""- encoded = text.encode("cp1252")- payload = struct.pack("<H", len(encoded)) + encoded- if len(encoded) & 1:- payload += b"\x00"- payload += struct.pack("<hh", y, x)- return wmf_record(0x0521, payload)---def build_placeable_wmf(records: list[bytes], *, bbox: tuple[int, int, int, int] = (0, 0, 1000, 1000)) -> bytes:- """构造带 Aldus placeable header 的标准 WMF。"""- eof = wmf_record(0)- body = b"".join(records) + eof- standard = struct.pack("<HHHIHIH", 1, 9, 0x0300, (18 + len(body)) // 2, 16, max(3, len(body) // 2), 0)- placeable = bytearray(struct.pack("<IHhhhhHI", 0x9AC6CDD7, 0, *bbox, 1000, 0))- checksum = 0- for offset in range(0, 20, 2):- checksum ^= struct.unpack_from("<H", placeable, offset)[0]- placeable.extend(struct.pack("<H", checksum))- return bytes(placeable) + standard + body---def basic_wmf() -> bytes:- """构造包含画笔、画刷、矩形与多边形的 placeable WMF。"""- records = [- wmf_record(0x02FA, struct.pack("<HhhI", 0, 8, 0, 0x000000FF)),- wmf_record(0x02FC, struct.pack("<HIH", 0, 0x0000FF00, 0)),- wmf_record(0x012D, struct.pack("<H", 0)),- wmf_record(0x012D, struct.pack("<H", 1)),- wmf_record(0x041B, struct.pack("<hhhh", 800, 800, 200, 200)),- wmf_record(- 0x0324,- struct.pack("<Hhhhhhh", 3, 100, 900, 500, 100, 900, 900),- ),- ]- return build_placeable_wmf(records)---__all__ = [- "basic_wmf",- "build_emf",- "build_placeable_wmf",- "emf_angle_arc",- "emf_arc_to",- "emf_create_brush",- "emf_create_pen",- "emf_begin_path",- "emf_close_figure",- "emf_end_path",- "emf_fill_path",- "emf_font",- "emf_intersect_clip_rect",- "emf_line_to",- "emf_move_to",- "emf_polybezier",- "emf_polyline_to",- "emf_record",- "emf_rectangle",- "emf_restoredc",- "emf_savedc",- "emf_select_object",- "emf_set_miter_limit",- "emf_set_polyfill_mode",- "emf_set_text_align",- "emf_set_world_transform",- "emf_stroke_and_fill_path",- "emf_stroke_path",- "emf_stretch_dib",- "emf_text",- "emfplus_comment",- "wmf_move_to",- "wmf_rectangle",- "wmf_record",- "wmf_set_map_mode",- "wmf_set_text_align",- "wmf_textout",-]diff --git a/tests/unittest/_mtef_test_utils.py b/tests/unittest/_mtef_test_utils.pyindex b4e12536..07c25af0 100644--- a/tests/unittest/_mtef_test_utils.py+++ b/tests/unittest/_mtef_test_utils.py@@ -4,12 +4,10 @@ from __future__ import annotationsimport base64import struct-from typing import castimport uuid+from typing import cast-_TINY_PNG = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"-)+_TINY_PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")def mtef_char(value: str, *, embellishments: tuple[int, ...] = ()) -> bytes:@@ -71,23 +69,26 @@ def mtef_equation(*records: bytes) -> bytes:"""构造完整 MTEF v3 头、FULL size 和根 LINE。"""header = bytes([3, 1, 1, 3, 0])- return header + b"\x0A" + mtef_line(*records) + b"\x00"+ return header + b"\x0a" + mtef_line(*records) + b"\x00"def equation_native(mtef: bytes) -> bytes:"""为 MTEF 添加 28 字节 EQNOLEFILEHDR。"""- return struct.pack(- "<HIHI4I",- 28,- 0x0002_0000,- 0xC1C2,- len(mtef),- 0,- 0,- 0,- 0,- ) + mtef+ return (+ struct.pack(+ "<HIHI4I",+ 28,+ 0x0002_0000,+ 0xC1C2,+ len(mtef),+ 0,+ 0,+ 0,+ 0,+ )+ + mtef+ )def formula_corpus() -> list[tuple[str, bytes, str]]:@@ -396,11 +397,7 @@ def build_equation_doc(if storage_id in previews:preview_offset = len(data_stream)preview_payload = custom_previews.get(storage_id)- data_stream.extend(- _raw_picf(preview_payload)- if preview_payload is not None- else _png_picf(_TINY_PNG)- )+ data_stream.extend(_raw_picf(preview_payload) if preview_payload is not None else _png_picf(_TINY_PNG))anchors.append((separator_cp + 1, preview_offset, False))text_parts.append(field)cp_cursor += len(field)diff --git a/tests/unittest/_mtef_v5_test_utils.py b/tests/unittest/_mtef_v5_test_utils.pyindex 462df91d..4f9ffd2b 100644--- a/tests/unittest/_mtef_v5_test_utils.py+++ b/tests/unittest/_mtef_v5_test_utils.py@@ -59,11 +59,7 @@ def v5_char(if not omit_mtcode:payload += struct.pack("<H", ord(value))if font_position is not None:- payload += (- bytes([font_position])- if font_position <= 0xFF- else struct.pack("<H", font_position)- )+ payload += bytes([font_position]) if font_position <= 0xFF else struct.pack("<H", font_position)if embellishments:payload += b"".join(bytes([6, 0, item]) for item in embellishments)payload += b"\x00"@@ -94,13 +90,7 @@ def v5_template() -> bytes:"""构造一个含完整 subobject list 的 MTEF v5 TMPL。"""- return (- bytes([3, 0, selector])- + v5_variation(variation)- + bytes([options])- + b"".join(slots)- + b"\x00"- )+ return bytes([3, 0, selector]) + v5_variation(variation) + bytes([options]) + b"".join(slots) + b"\x00"def v5_pile(*lines: bytes) -> bytes:@@ -119,47 +109,7 @@ def v5_matrix(rows: list[list[bytes]]) -> bytes:row_parts = b"\x00" * ((2 * (row_count + 1) + 7) // 8)col_parts = b"\x00" * ((2 * (col_count + 1) + 7) // 8)cells = b"".join(v5_line(cell) for row in rows for cell in row)- return (- bytes([5, 0, 0, 2, 0, row_count, col_count])- + row_parts- + col_parts- + cells- + b"\x00"- )---def v5_encoding_definition(name: str) -> bytes:- """构造一个 ENCODING_DEF。"""-- return b"\x13" + name.encode("ascii") + b"\x00"---def v5_font_definition(encoding_index: int, name: str) -> bytes:- """构造一个 FONT_DEF。"""-- return b"\x11" + v5_unsigned(encoding_index) + name.encode("ascii") + b"\x00"---def v5_font_style_definition(font_index: int, style_bits: int) -> bytes:- """构造一个 FONT_STYLE_DEF。"""-- return b"\x08" + v5_unsigned(font_index) + bytes([style_bits])---def v5_equation_preferences(- styles: list[tuple[int, int] | None],-) -> bytes:- """构造尺寸和间距为空、仅含 style definitions 的 EQN_PREFS。"""-- payload = bytearray([18, 0, 0, 0, len(styles)])- for style in styles:- if style is None:- payload.extend(v5_unsigned(0))- else:- font_index, style_bits = style- payload.extend(v5_unsigned(font_index))- payload.append(style_bits)- return bytes(payload)+ return bytes([5, 0, 0, 2, 0, row_count, col_count]) + row_parts + col_parts + cells + b"\x00"def v5_future_record(payload: bytes) -> bytes:@@ -270,66 +220,3 @@ def v5_formula_corpus() -> list[tuple[str, bytes, str]]:("box", v5_equation(v5_template(37, v5_line(v5_char("x")))), r"\boxed{x}"),("future", v5_equation(v5_future_record(b"future"), v5_char("x")), "x"),]---def v5_template_corpus() -> list[tuple[str, bytes, str]]:- """返回覆盖 v5 各类标准 template selector 的精确语料。"""-- line_x = v5_line(v5_char("x"))- line_a = v5_line(v5_char("a"))- line_b = v5_line(v5_char("b"))- line_i = v5_line(v5_char("i"))- line_n = v5_line(v5_char("n"))- null_line = v5_line(null=True)- cases = [- ("angle", v5_template(0, line_x, variation=3), r"\left\langle x\right\rangle"),- ("parenthesis", v5_template(1, line_x, variation=3), r"\left(x\right)"),- ("brace", v5_template(2, line_x, variation=3), r"\left\{x\right\}"),- ("bracket", v5_template(3, line_x, variation=3), r"\left[x\right]"),- ("bar", v5_template(4, line_x, variation=3), r"\left|x\right|"),- ("double_bar", v5_template(5, line_x, variation=3), r"\left\|x\right\|"),- ("floor", v5_template(6, line_x, variation=3), r"\left\lfloor x\right\rfloor"),- ("ceiling", v5_template(7, line_x, variation=3), r"\left\lceil x\right\rceil"),- ("white_bracket", v5_template(8, line_x, variation=3), r"\left\llbracket x\right\rrbracket"),- ("slash_fraction", v5_template(11, line_a, line_b, variation=2), r"{a}/{b}"),- ("double_underbar", v5_template(12, line_x, variation=1), r"\underline{\underline{x}}"),- ("overbar", v5_template(13, line_x), r"\overline{x}"),- ("arrow", v5_template(14, line_a, variation=0x20), r"\overset{a}{\rightarrow}"),- ("product", v5_template(17, line_x, line_n, line_i, v5_char("∏"), variation=3), r"\prod_{i}^{n}{x}"),- ("coproduct", v5_template(18, line_x, line_n, line_i, v5_char("∐"), variation=3), r"\coprod_{i}^{n}{x}"),- ("union", v5_template(19, line_x, line_n, line_i, v5_char("∪"), variation=3), r"\bigcup_{i}^{n}{x}"),- ("intersection", v5_template(20, line_x, line_n, line_i, v5_char("∩"), variation=3), r"\bigcap_{i}^{n}{x}"),- ("custom_bigop", v5_template(21, line_x, line_n, line_i, v5_char("∫"), variation=3), r"\int_{i}^{n}{x}"),- ("sum_style_bigop", v5_template(22, line_x, line_n, line_i, v5_char("∑"), variation=0x43), r"\sum_{i}^{n}{x}"),- (- "two_byte_variation",- v5_template(- 15,- line_x,- null_line,- null_line,- v5_char("∫"),- variation=0x100,- ),- r"\int{x}",- ),- ("limit", v5_template(23, line_x, v5_line(v5_char("0")), v5_line(v5_char("1"))), r"\lim_{0}^{1}{x}"),- ("overbrace", v5_template(24, line_x, line_n, variation=1), r"\overbrace{x}^{n}"),- ("underbracket", v5_template(25, line_x, line_n), r"\underbracket{x}_{n}"),- ("long_division", v5_template(26, line_x, v5_line(v5_char("q")), variation=1), r"\overline{q}\smash{\big) x}"),- ("subscript", v5_template(27, line_i, null_line), r"_{i}"),- ("superscript", v5_template(28, null_line, v5_line(v5_char("2"))), r"^{2}"),- ("prescripts", v5_template(29, line_i, v5_line(v5_char("2")), variation=1), r"{}_{i}^{2}"),- ("under_vector", v5_template(31, line_x, variation=0x05), r"\underleftarrow{x}"),- ("tilde", v5_template(32, line_x), r"\widetilde{x}"),- ("hat", v5_template(33, line_x), r"\widehat{x}"),- ("arc", v5_template(34, line_x), r"\overparen{x}"),- ("cancel", v5_template(36, line_x, variation=2), r"\cancel{x}"),- ("back_cancel", v5_template(36, line_x, variation=4), r"\bcancel{x}"),- ("cross_cancel", v5_template(36, line_x, variation=6), r"\xcancel{x}"),- ("box", v5_template(37, line_x, variation=0x1E), r"\boxed{x}"),- ]- return [- (name, v5_equation(template), expected)- for name, template, expected in cases- ]diff --git a/tests/unittest/_odf_test_utils.py b/tests/unittest/_odf_test_utils.pyindex 2fd578a2..309cf2a8 100644--- a/tests/unittest/_odf_test_utils.py+++ b/tests/unittest/_odf_test_utils.py@@ -1,17 +1,16 @@from __future__ import annotations-# ruff: noqa: E501 -- 测试夹具保留紧凑 XML,便于直接核对 ODF 结构。-import base64from io import BytesIOfrom zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile-_MIME_BY_SUFFIX = {"odt": "application/vnd.oasis.opendocument.text","ods": "application/vnd.oasis.opendocument.spreadsheet","odp": "application/vnd.oasis.opendocument.presentation",}++_PIXEL_PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP8zwACTGCSAQANHQEDgslx/wAAAABJRU5ErkJggg==")@@ -38,11 +37,9 @@ def build_odf_package("<manifest:encryption-data/>""</manifest:file-entry>")- for name in (extra_parts or {}):+ for name in extra_parts or {}:media_type = "image/png" if name.endswith(".png") else "text/xml"- manifest_entries.append(- f'<manifest:file-entry manifest:full-path="{name}" manifest:media-type="{media_type}"/>'- )+ manifest_entries.append(f'<manifest:file-entry manifest:full-path="{name}" manifest:media-type="{media_type}"/>')manifest = ('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">'+ "".join(manifest_entries)@@ -166,6 +163,3 @@ def build_ods_fixture() -> bytes:content,extra_parts={"Object 1/content.xml": _chart_object_xml(), "Pictures/pixel.png": _PIXEL_PNG},)---__all__ = ["build_odf_package", "build_odp_fixture", "build_ods_fixture", "build_odt_fixture"]diff --git a/tests/unittest/_ofd_test_utils.py b/tests/unittest/_ofd_test_utils.pyindex 6e93d801..6d097f8a 100644--- a/tests/unittest/_ofd_test_utils.py+++ b/tests/unittest/_ofd_test_utils.py@@ -130,6 +130,3 @@ def build_multi_document_ofd() -> bytes:page_xml(text_object(2, label, boundary="10 10 40 10")),)return output.getvalue()---__all__ = ["build_multi_document_ofd", "build_ofd_package", "page_xml", "path_object", "text_object"]diff --git a/tests/unittest/_office_image_mtef_test_utils.py b/tests/unittest/_office_image_mtef_test_utils.pyindex e332ac5e..205e5bf9 100644--- a/tests/unittest/_office_image_mtef_test_utils.py+++ b/tests/unittest/_office_image_mtef_test_utils.py@@ -6,23 +6,21 @@ import base64from io import BytesIOfrom zipfile import ZipFile-from docx import Document-from openpyxl import Workbook-from openpyxl.drawing.image import Image as XlsxImage-from pptx import Presentation-from pptx.util import Inches-from lxml import etree # type: ignore[reportAttributeAccessIssue]-from _ooxml_mtef_test_utils import (IMAGE_REL_TYPE,PACKAGE_RELS_NS,REL_NS,_rewrite_zip,)+from docx import Document+from lxml import etree # type: ignore[reportAttributeAccessIssue]+from openpyxl import Workbook+from openpyxl.drawing.image import Image as XlsxImage+from pptx import Presentation+from pptx.util import Inches_VALID_TINY_PNG = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/"- "x8AAusB9Wl2l9sAAAAASUVORK5CYII="+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII=")@@ -35,11 +33,7 @@ def _replace_media_parts("""把指定 OOXML media 目录下的图片成员替换为原始测试载荷。"""with ZipFile(BytesIO(package)) as source:- replacements = {- name: payload- for name in source.namelist()- if name.startswith(prefix)- }+ replacements = {name: payload for name in source.namelist() if name.startswith(prefix)}if not replacements:raise ValueError(f"OOXML image fixture has no media under {prefix}")return _rewrite_zip(package, replacements, {})@@ -84,9 +78,7 @@ def _move_pptx_picture_to_notes(package: bytes) -> bytes:replacements: dict[str, bytes] = {}with ZipFile(BytesIO(package)) as source:slide_root = etree.fromstring(source.read("ppt/slides/slide1.xml"))- notes_root = etree.fromstring(- source.read("ppt/notesSlides/notesSlide1.xml")- )+ notes_root = etree.fromstring(source.read("ppt/notesSlides/notesSlide1.xml"))pictures = slide_root.xpath(".//*[local-name()='pic']")note_trees = notes_root.xpath(".//*[local-name()='spTree']")if not pictures or not note_trees:@@ -100,15 +92,9 @@ def _move_pptx_picture_to_notes(package: bytes) -> bytes:if not blips:raise ValueError("PPTX notes image fixture has no blip")relationship_id = blips[0].get(f"{{{REL_NS}}}embed")- slide_rels = etree.fromstring(- source.read("ppt/slides/_rels/slide1.xml.rels")- )+ slide_rels = etree.fromstring(source.read("ppt/slides/_rels/slide1.xml.rels"))target = next(- (- rel.get("Target")- for rel in slide_rels- if rel.get("Id") == relationship_id- ),+ (rel.get("Target") for rel in slide_rels if rel.get("Id") == relationship_id),None,)if not target:diff --git a/tests/unittest/_ooxml_mtef_test_utils.py b/tests/unittest/_ooxml_mtef_test_utils.pyindex bf3f2837..4300ab1f 100644--- a/tests/unittest/_ooxml_mtef_test_utils.py+++ b/tests/unittest/_ooxml_mtef_test_utils.py@@ -5,27 +5,52 @@ from __future__ import annotationsfrom io import BytesIOfrom zipfile import ZIP_DEFLATED, ZipFile, ZipInfo+from _mtef_test_utils import _TINY_PNG, build_equation_objectfrom docx import Documentfrom lxml import etree # type: ignore[reportAttributeAccessIssue]from openpyxl import Workbookfrom pptx import Presentationfrom pptx.util import Inches-from _mtef_test_utils import _TINY_PNG, build_equation_object-CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"++PACKAGE_RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"++REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"++W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"++M_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"++MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"++V_NS = "urn:schemas-microsoft-com:vml"++O_NS = "urn:schemas-microsoft-com:office:office"++X_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"++XDR_NS = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"++A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"++XVML_NS = "urn:schemas-microsoft-com:office:excel"++OLE_REL_TYPE = f"{REL_NS}/oleObject"++IMAGE_REL_TYPE = f"{REL_NS}/image"@@ -60,20 +85,14 @@ def _content_types_with_ole(content_types: bytes) -> bytes:"""为 .bin 公式 OLE persistence part 添加默认内容类型。"""root = etree.fromstring(content_types)- if not any(- child.get("Extension", "").casefold() == "bin"- for child in root- ):+ if not any(child.get("Extension", "").casefold() == "bin" for child in root):etree.SubElement(root,f"{{{CONTENT_TYPES_NS}}}Default",Extension="bin",ContentType="application/vnd.openxmlformats-officedocument.oleObject",)- if not any(- child.get("Extension", "").casefold() == "png"- for child in root- ):+ if not any(child.get("Extension", "").casefold() == "png" for child in root):etree.SubElement(root,f"{{{CONTENT_TYPES_NS}}}Default",@@ -160,11 +179,7 @@ def _replace_word_placeholder("""用公式 run 或 AlternateContent 替换指定占位 run。"""text_node = next(- (- node- for node in root.findall(f".//{{{W_NS}}}t")- if node.text == placeholder- ),+ (node for node in root.findall(f".//{{{W_NS}}}t") if node.text == placeholder),None,)if text_node is None:@@ -206,9 +221,7 @@ def _patch_word_part(rels,image_rid,IMAGE_REL_TYPE,- f"../media/{image_part.rsplit('/', 1)[-1]}"- if directory != "word"- else f"media/{image_part.rsplit('/', 1)[-1]}",+ f"../media/{image_part.rsplit('/', 1)[-1]}" if directory != "word" else f"media/{image_part.rsplit('/', 1)[-1]}",)additions[object_part] = build_equation_object(mtef,@@ -334,14 +347,10 @@ def build_equation_docx(with ZipFile(BytesIO(package)) as source:if header_footer:header_parts = sorted(- name- for name in source.namelist()- if name.startswith("word/header") and name.endswith(".xml")+ name for name in source.namelist() if name.startswith("word/header") and name.endswith(".xml"))footer_parts = sorted(- name- for name in source.namelist()- if name.startswith("word/footer") and name.endswith(".xml")+ name for name in source.namelist() if name.startswith("word/footer") and name.endswith(".xml"))assignments: dict[str, list[tuple[str, bytes, bool]]] = {}for index, (placeholder, mtef) in enumerate(zip(placeholders, formulas, strict=True)):@@ -370,9 +379,7 @@ def build_equation_docx(mtef,alternate_omml and index == 0,)- for index, (placeholder, mtef) in enumerate(- zip(placeholders, formulas, strict=True)- )+ for index, (placeholder, mtef) in enumerate(zip(placeholders, formulas, strict=True))]xml, rels = _patch_word_part(source,@@ -388,9 +395,7 @@ def build_equation_docx(xml = _set_word_equations_as_icons(xml)replacements[target_part] = xmlreplacements["word/_rels/document.xml.rels"] = rels- replacements["[Content_Types].xml"] = _content_types_with_ole(- source.read("[Content_Types].xml")- )+ replacements["[Content_Types].xml"] = _content_types_with_ole(source.read("[Content_Types].xml"))return _rewrite_zip(package, replacements, additions)@@ -408,11 +413,7 @@ def build_equation_pptx(presentation = Presentation()presentation.slides.add_slide(presentation.slide_layouts[6])for index, mtef in enumerate(formulas):- slide = (- presentation.slides[0]- if index == 0- else presentation.slides.add_slide(presentation.slide_layouts[6])- )+ slide = presentation.slides[0] if index == 0 else presentation.slides.add_slide(presentation.slide_layouts[6])slide.shapes.add_ole_object(BytesIO(build_equation_object(mtef, prog_id=prog_id)),prog_id,@@ -430,11 +431,7 @@ def build_equation_pptx(if preview_image != _TINY_PNG:replacements = {}with ZipFile(BytesIO(package)) as source:- replacements = {- name: preview_image- for name in source.namelist()- if name.startswith("ppt/media/")- }+ replacements = {name: preview_image for name in source.namelist() if name.startswith("ppt/media/")}package = _rewrite_zip(package, replacements, {})if notes:return _move_pptx_equations_to_notes(@@ -479,9 +476,7 @@ def _move_pptx_equations_to_notes(replacements: dict[str, bytes] = {}with ZipFile(BytesIO(package)) as source:slide_parts = sorted(- name- for name in source.namelist()- if name.startswith("ppt/slides/slide") and name.endswith(".xml")+ name for name in source.namelist() if name.startswith("ppt/slides/slide") and name.endswith(".xml"))for index, slide_part in enumerate(slide_parts, start=1):notes_part = f"ppt/notesSlides/notesSlide{index}.xml"@@ -505,11 +500,7 @@ def _move_pptx_equations_to_notes(for attribute, value in node.attrib.items()if attribute in {f"{{{REL_NS}}}id", f"{{{REL_NS}}}embed"}}- copied_relationships = [- relationship- for relationship in slide_rels- if relationship.get("Id") in referenced_ids- ]+ copied_relationships = [relationship for relationship in slide_rels if relationship.get("Id") in referenced_ids]notes_rels_name = f"ppt/notesSlides/_rels/notesSlide{index}.xml.rels"notes_rels = _relationships_root(source.read(notes_rels_name))id_mapping: dict[str, str] = {}@@ -628,9 +619,7 @@ def _xlsx_vml_parts(shape = etree.SubElement(root, f"{{{V_NS}}}shape", id=f"_x0000_s{shape_id}")etree.SubElement(shape, f"{{{V_NS}}}imagedata", {f"{{{REL_NS}}}id": "rIdPreview"})client_data = etree.SubElement(shape, f"{{{XVML_NS}}}ClientData")- etree.SubElement(client_data, f"{{{XVML_NS}}}Anchor").text = (- f"{col}, 0, {row}, 0, {col + 2}, 0, {row + 3}, 0"- )+ etree.SubElement(client_data, f"{{{XVML_NS}}}Anchor").text = f"{col}, 0, {row}, 0, {col + 2}, 0, {row + 3}, 0"rels = _relationships_root(None)_append_relationship(rels, "rIdPreview", IMAGE_REL_TYPE, "../media/equationMtef.png")return (@@ -702,19 +691,13 @@ def build_equation_xlsx(rels,ole_rid,OLE_REL_TYPE,- (- "https://example.test/equation.bin"- if linked- else f"../embeddings/oleObjectMtef{index}.bin"- ),+ ("https://example.test/equation.bin" if linked else f"../embeddings/oleObjectMtef{index}.bin"),external=linked,)if linked:ole_object.set("link", "https://example.test/equation.bin")else:- additions[- f"xl/embeddings/oleObjectMtef{index}.bin"- ] = build_equation_object(+ additions[f"xl/embeddings/oleObjectMtef{index}.bin"] = build_equation_object(mtef,prog_id=prog_id,)@@ -766,7 +749,5 @@ def build_equation_xlsx(replacements[rels_name] = rels_payloadelse:additions[rels_name] = rels_payload- replacements["[Content_Types].xml"] = _content_types_with_ole(- source.read("[Content_Types].xml")- )+ replacements["[Content_Types].xml"] = _content_types_with_ole(source.read("[Content_Types].xml"))return _rewrite_zip(package, replacements, additions)diff --git a/tests/unittest/_span_test_utils.py b/tests/unittest/_span_test_utils.pyindex 3e41b49f..0483bf12 100644--- a/tests/unittest/_span_test_utils.py+++ b/tests/unittest/_span_test_utils.py@@ -16,11 +16,6 @@ def equation(latex: str) -> dict[str, str]:return {"type": "equation_inline", "content": latex}-def code(content: str) -> dict[str, str]:- """构造测试用行内代码 Span。"""- return {"type": "code_inline", "content": content}--def hyperlink(url: str, content: str) -> dict[str, Any]:"""构造测试用超链接 Span。"""return {"type": "hyperlink", "url": url, "content": inline(content)}@@ -73,15 +68,3 @@ def inline_urls(spans: Any) -> list[str]:def visible_content(content: Any) -> str:"""统一提取专用字符串内容或 InlineSpan 内容的可见文字。"""return content if isinstance(content, str) else inline_text(content)---__all__ = [- "code",- "equation",- "hyperlink",- "inline",- "inline_items",- "inline_text",- "inline_urls",- "visible_content",-]diff --git a/tests/unittest/fixtures/emfplus/fallback-only.emf b/tests/unittest/fixtures/emfplus/fallback-only.emfdeleted file mode 100644index f7259d73..00000000Binary files a/tests/unittest/fixtures/emfplus/fallback-only.emf and /dev/null differdiff --git a/tests/unittest/fixtures/emfplus/geometry-only.emf b/tests/unittest/fixtures/emfplus/geometry-only.emfdeleted file mode 100644index 80d66d68..00000000Binary files a/tests/unittest/fixtures/emfplus/geometry-only.emf and /dev/null differdiff --git a/tests/unittest/pdfs/flash_layout/mixed_text_layout_sample.pdf.xor b/tests/unittest/pdfs/flash_layout/mixed_text_layout_sample.pdf.xordeleted file mode 100644index a52058ee..00000000Binary files a/tests/unittest/pdfs/flash_layout/mixed_text_layout_sample.pdf.xor and /dev/null differdiff --git a/tests/unittest/pdfs/flash_table_annotations_synthetic.pdf b/tests/unittest/pdfs/flash_table_annotations_synthetic.pdfdeleted file mode 100644index 72ea1bf5..00000000--- a/tests/unittest/pdfs/flash_table_annotations_synthetic.pdf+++ /dev/null@@ -1,218 +0,0 @@-%PDF-1.4-%���� ReportLab Generated PDF document http://www.reportlab.com-1 0 obj-<<-/F1 2 0 R /F2 3 0 R->>-endobj-2 0 obj-<<-/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font->>-endobj-3 0 obj-<<-/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font->>-endobj-4 0 obj-<<-/Contents 16 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-5 0 obj-<<-/Contents 17 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-6 0 obj-<<-/Contents 18 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-7 0 obj-<<-/Contents 19 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-8 0 obj-<<-/Contents 20 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-9 0 obj-<<-/Contents 21 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-10 0 obj-<<-/Contents 22 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-11 0 obj-<<-/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 50 /Length 52 /Subtype /Image- /Type /XObject /Width 80->>-stream-Gb"0<0b"*_$j.XP*ddXaKZVjK+^J&I<E3%!<E3%!<V?4iCK2Ic~>endstream-endobj-12 0 obj-<<-/Contents 23 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 15 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<-/FormXob.95340d3e485331727775aa13da4b0f71 11 0 R->>->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-13 0 obj-<<-/PageMode /UseNone /Pages 15 0 R /Type /Catalog->>-endobj-14 0 obj-<<-/Author (MinerU Test Suite) /CreationDate (D:20000101000000+00'00') /Creator (MinerU Test Suite) /Keywords (MinerU synthetic test fixture) /ModDate (D:20000101000000+00'00') /Producer (MinerU Test Suite)- /Subject (Synthetic PDF regression fixture) /Title (MinerU Test Suite) /Trapped /False->>-endobj-15 0 obj-<<-/Count 8 /Kids [ 4 0 R 5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 12 0 R ] /Type /Pages->>-endobj-16 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 341->>-stream-Gas2EbAMqd&4Q?hMS!]:TU86"D5FJ:\uC1pO9mlJ]<Y.2rk?BKPpgBYaU?GYS3(58fH1msFp),2SneOrJ7$*t-j+t<M'(a(@Ceg>8AOfC:i9kEau3.hTdYht/1Y'InaJ^mf9;CMl9X&D>VlPVQ="MboE]mLJ(bHl\I.+OqL`%W?h,.1cA2M'<fWE^72pU[A')M_B?48U'c^@hmlcU5;&UbTU*@FYMM$QUdc.@_Bj;()8P!EdeM*aC77K6t#KKW!kgm.S*nT0pdIob;8!$a^*jG,>K:)>mcqlAZV&s9ST%qQZgKOi)P)f82gJ@WhG=e&i/Bph`lWe7]_;Q=cPDWE~>endstream-endobj-17 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 709->>-stream-GasbY?^$p4'ZJu.'_em""!n8)nAqb3S^Fjqm-aMn5I='RTgcE@Dnejd,ZmW"Nm+'3O)m(u]b:O_p`]=c*<GRfI/JWt@Gp#C"^V1V%OiLqMQ"7M'S$3]"gI^.:f6OH",L(?0c#\67sN)#--V6pp+mACU5#R^=-jZkc1[6ih?3cYr'P7nN.#8rs#,lk6o%ehb)_7`^(g65<p)Q,n6;9He\uS,eZO3U)0lY9UI&,Y4rf.5VE2N(O[JYWA6Bd1#dc-4,GS)YU?Z:3==_S[8ri7+N4"Uk.j5p.H9B0T]@P`S@WKLu0>+Q$&VSC&i_]$rN2MU5L2.:Z*r(uD+4Jsil!(<9_?WU<;QR]Frcsql_@;?L8$]s3BeoZKS;[OZhPK!BCd@=o2OHRn`h<Saa^X4"[RfCK[]o;m_;=K2=2R<+HT85e*/go$o%iP;UHs_X%9]+mp%<">Wfr'+O+s`p*9be3Q'%2H?<LRUOe%<5Q>pghUr,cbVq?1EqYuKY79pug;SJUU3tBH,oB!==Zj\ma9r<P['!SO$T4_Xt!6Si17!L]D_?)V89=m*RVIFu/O_`;E5LMJ9"07V"mX"YWq=rl?2'd1;)CiHB#^(L)mLU$,lH<bHc\kM?JNE[,__sT@B@rOC$e4HRK&c0rL+59&ncHtcqNUHTk*;V5H$8b[jSnP&+BJ<PGN4"f1%c*O$qR]5He2Zt##@C^)Z~>endstream-endobj-18 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 569->>-stream-Gat%`d;GF-(kqF(MK?=&)T+HCcL0+=WM3sn2S99fM+a8PFPq&jgWqiEbXS=#8B<hUI)e/EItGa*`4bm[E$Omj6U3'\,=ifoO?9OT&337E#L5S#\2/qig8^qrnJI*R66VY<ZGNY!X45ne/6@qd6`I;hCSP[?E*I*Vka0L-[=/S\*V)pcEWM:1T`53A'M0*Zfgd5RqHKF:AW$GCr_YP`nut@T/UY5B6@iKpG+9sI"\t,R''W8",_Om3:3&J>YqM;<-D&H#+EsTqjMXiiFHG`t-#BrpM4[_=53Vs;'A]oF_o9j1-$D@f`h(st]AD@<:OV_0l5T3CEja`J44sb)b*Dmjc9"*t4;_-9E_"Tld]1EJ3oFXO^8MDI(dIioiI!U&9K*d)ao@-[/&Jh69Xj3&:St21:S1=t^Kban(?"O]6D&)!]SCka>3'1tX.T\teiI_XlFq:A35:cU]oJ=;g=EWU/=P._cj-C/f%qou1oe\*h80Y=_4n?N!F9WR5UL"e\&uPtB@-OeH7kI[XWqK4m_MWmk\1j>I+Ml&E2JWB,nC=B!\ABfbekRu"1^-PCB~>endstream-endobj-19 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 479->>-stream-GasbW?Z1NM'ZJu*'^'I?1=d3JAT-k\Ql4_e00]61Rk=a[ZM=)o$4&UJ$OO@(rGbSZbG??XU#s%FJA/tNOFf7/%oCl$+X[Pl71><-=pAB-g]4'Reg`8B\-l[=[Le!rN,U_9+4j)q<@Oe:VD)*!C*+N@=6kLU+GhlhBD7KpO:S1OnL)>KrUon&r&e7h(EP4*`a<RW6Gr-$h"H,+f`ENO2BNTa#b2X[!K0;<4Kk"@Wg4Z+agsOV>T^,1o;\*>[utlV+oBMP`[[CaG2f$3Vo<`.FKb?-[RAuQ_"KgXjhp[QI2SnhYMleCkmCq%`P$q__0l/-a0TJ=n$ILuPMW5WbW2"i>`[`tYHb)'ajS]?Bl^cs?h;H[EBTkKF#ppq?=X".Dt(*6iS8Wm8qtsXS"Tb7T-8FU,E=5qNfAXnouQL/$JA1JQmV_,jr/-Cf:Om@h_,2%+u"(-m#FYL!Oo&G"WV!qgkHEB?W%:'Nr~>endstream-endobj-20 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 415->>-stream-Gas2E?VeNm'ZJu*'^&>QRHn69I"MP8'D09/X1>IXW,1kLFsu8)Y$_=YO=!^%SGPD8\H6I^,0m4nQq?'r$A]+2%5CIEO:0:o+H6_4%AFttaJ5Cf?ADI!,ip80MfDW/PAo45C1bUO,_(0RE(++#(pDGr27mYF:WT#8IC)]n2>^#eB,IO\"Nl^E0XarLllI`]W[tOsK[W\#Y/t_kDa8UZ:Wo2Z(i*,oQBQC5'DQuqJ3V0Oo1,7,:gN(/\p0^">m@Tnef)R0]OgJJToB:cAP0tJ2QQ3Ko_eeR7B)e)*J,u:+4-,*ZA%CpP]g1&3Vbk:0BG-ilg['u3i`'AZM#(SZJT3&f=F4iJP_]lboCmMEk_nge4R%L\R8$@N2ANr"eYNl?kOEA-N>n`S)fDCjopJEp\Y/H_%3D"UY5~>endstream-endobj-21 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 522->>-stream-GasbX?#Q2d(kqGS($BUA<9au&cD4^P)3(Ln9ikT%G7u.VQA(AO@G:SHCE0"W$W2V2XQ.@afIsn7+QfBkSJAr:_YFoMAPh8L"$_=I7]\^]M;<C%!Xr%15do-2V6,pe&BW"[EbZp/]U;i:I?nf[)KVJ4HR*b1LeW^?.UD04/_!RpGHH_0-J"XaD]LQ#9sAWFCE]q/V;A&V?:.^s?"1(nX9Y'+gPt)B4C@*O='?,$:dD8&-qA<>_l/cgdBahbE\N_l0@PJ'A1'=2(NM?+A?:u_ZP23Ugu/DU\p&Jt]jt'IW?31\=_*P&B:>hP5K,R!`B0*b+W*H!hSi(WEB-@,a4?pXfBP?KJ3a\u^O.>\T%H>i?Hb#L,9V1mD_I8a4IWk/lpPrVc=\4G,9V1m:IY`V7e?06B/H2c9h%D9GeT"5r/)R>KEr*HDlR!U5;^U;r^Zh.FAHLp'=Ig@U\M1!;-#PT3i`U)qD9uKN)a1q>CR4Kh?XfogU4saE[@rhn0o.dSCmaY?j#j(&;UC_~>endstream-endobj-22 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 449->>-stream-GasbW6#V?/*6%AoMKdjAaCq9Um"Q"`&91ltB?H_P_Bs0D^AVdM/5[0M!mU%lpW0+Z!_6Nahj7PT+E9Ui+;FA]`3VVJ#beUF:$gGs"t0c+J>foA8h)4NJI??'iN(3TDMGct/:/J\3lS$Gp3Eo=0dsd,<O2M8Km\ZgWuSLMUODC;0;kJed?ZP5a\qac<MmI2==+o;>T"pd9p$BdT@IT#`g/4GA*)F_A_;U^j!qsZP+>'c%%6Tg5-.Mbf>ug:bY;kFCRMUTh$/(-4JSd#X]N8+*6Rg=re5MTW;9eJh9U<]0;e,SCQ;:+Hk)l>GStU-NcQ)Z%T%.5e6E[uK;^m-"EN?>H_TM639a1Lf;:I!&HAOae1cdCiM/\&?."-D`23>'M)sT+ODgU$8TQADk,T-[W<]+j^XLsr'&)A7i9Mh2ljNDRI:a.Z$+S#a0T1VW#CW<"EW~>endstream-endobj-23 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 376->>-stream-Gas2D9hPRC(khAT/*<d^l/o%g?I]eo01$.TZYeE6Bf9aiqXO#K[k"g.'$)4Pml^2rU+V4]pW<RK#.#TZAM>'"5m5C>(8e*%8)..?JUttkTI7:_dO@`p.'8<V9bBO+*b.b*I^!#]j1[9b^W+,$q&@KgZAWu$7D"9,_q[shV[CZSW6$-;L-Z,#VOLkXOMcUb7_=Y'fYJY.7NXCuMZqi-3?[c1L?Lh4E(h+\C^RhB*4[Er,#gkXon4a]Y.'2XTKT*$<TpdVqGamhGNt7?*Ps284N7%bhn"%MIf4p!m`-5;.$kkMgd#5b]N:>gUY$QF.l-9[Q^O,BB$1ba>A-SQ\Z"-8#q\08MCGBt[?RksB^:YPGRDu:L$AonH%eZ~>endstream-endobj-xref-0 24-0000000000 65535 f-0000000073 00000 n-0000000114 00000 n-0000000221 00000 n-0000000333 00000 n-0000000538 00000 n-0000000743 00000 n-0000000948 00000 n-0000001153 00000 n-0000001358 00000 n-0000001563 00000 n-0000001769 00000 n-0000002009 00000 n-0000002279 00000 n-0000002349 00000 n-0000002665 00000 n-0000002769 00000 n-0000003201 00000 n-0000004001 00000 n-0000004661 00000 n-0000005231 00000 n-0000005737 00000 n-0000006350 00000 n-0000006890 00000 n-trailer-<<-/ID-[<b0ce4bb64c905e47caef5c06c690f477><b0ce4bb64c905e47caef5c06c690f477>]-% ReportLab generated PDF document -- digest (http://www.reportlab.com)--/Info 14 0 R-/Root 13 0 R-/Size 24->>-startxref-7357-%%EOFdiff --git a/tests/unittest/pdfs/metabolic_pathway_page_3.pdf b/tests/unittest/pdfs/metabolic_pathway_page_3.pdfdeleted file mode 100644index 8fef0ea3..00000000Binary files a/tests/unittest/pdfs/metabolic_pathway_page_3.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_cjk_layout_synthetic.pdf b/tests/unittest/pdfs/native_cjk_layout_synthetic.pdfdeleted file mode 100644index 439d65a8..00000000--- a/tests/unittest/pdfs/native_cjk_layout_synthetic.pdf+++ /dev/null@@ -1,206 +0,0 @@-%PDF-1.4-%���� ReportLab Generated PDF document http://www.reportlab.com-1 0 obj-<<-/F1 2 0 R /F2 3 0 R->>-endobj-2 0 obj-<<-/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font->>-endobj-3 0 obj-<<-/BaseFont /STSong-Light /DescendantFonts [ <<-/BaseFont /STSong-Light /CIDSystemInfo <<-/Ordering (GB1) /Registry (Adobe) /Supplement 0->> /DW 1000 /FontDescriptor <<-/Ascent 752 /CapHeight 737 /Descent -271 /Flags 6 /FontBBox [ -25 -254 1000 880 ] /FontName /STSongStd-Light- /ItalicAngle 0 /Leading 148 /MaxWidth 1000 /MissingWidth 500 /StemH 91 /StemV 58- /Type /FontDescriptor /XHeight 553->> /Subtype /CIDFontType0 /Type /Font- /W [ 1 [ 207 270 342 467 462 797 710 239 374 ] 10 [ 374 423 605 238 375 238 334 462 ] 18 26 462 27 28 238- 29 31 605 32 [ 344 748 684 560 695 739 563 511 729 793- 318 312 666 526 896 758 772 544 772 628- 465 607 753 711 972 647 620 607 374 333- 374 606 500 239 417 503 427 529 415 264- 444 518 241 230 495 228 793 527 524 ] 81 [ 524 504 338 336 277 517 450 652 466 452- 407 370 258 370 605 ] ]->> ] /Encoding /UniGB-UCS2-H /Name /F2 /Subtype /Type0 /Type /Font->>-endobj-4 0 obj-<<-/Contents 18 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 17 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-5 0 obj-<<-/Contents 19 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 17 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-6 0 obj-<<-/Contents 20 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 17 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]->> /Rotate 0 /Trans <<-->>- /Type /Page->>-endobj-7 0 obj-<<-/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 50 /Length 52 /Subtype /Image- /Type /XObject /Width 80->>-stream-Gb"0<5nO(s$j*+$ok\"<,:phuE28DlWiE)!WiE)!WiCM4mG0Wj~>endstream-endobj-8 0 obj-<<-/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 50 /Length 52 /Subtype /Image- /Type /XObject /Width 80->>-stream-Gb"0<0b"*_$j.XPp3P=V9h`PJ#]$<;WiE)!WiE)!WiFqe#e68t~>endstream-endobj-9 0 obj-<<-/A <<-/S /URI /Type /Action /URI (https://example.com/downloads/mineru/fixture/)->> /Border [ 0 0 0 ] /Rect [ 72 483 200.556 495 ] /Subtype /Link /Type /Annot->>-endobj-10 0 obj-<<-/A <<-/S /URI /Type /Action /URI (https://example.com/downloads/mineru/fixture/)->> /Border [ 0 0 0 ] /Rect [ 72 471 129.015 483 ] /Subtype /Link /Type /Annot->>-endobj-11 0 obj-<<-/A <<-/S /URI /Type /Action /URI (https://example.com/ref/a)->> /Border [ 0 0 0 ] /Rect [ 72 423 173.043 435 ] /Subtype /Link /Type /Annot->>-endobj-12 0 obj-<<-/A <<-/S /URI /Type /Action /URI (https://example.com/ref/b)->> /Border [ 0 0 0 ] /Rect [ 175.545 423 276.588 435 ] /Subtype /Link /Type /Annot->>-endobj-13 0 obj-<<-/A <<-/S /URI /Type /Action /URI (https://example.com/ref/c)->> /Border [ 0 0 0 ] /Rect [ 279.09 423 379.629 435 ] /Subtype /Link /Type /Annot->>-endobj-14 0 obj-<<-/Annots [ 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R ] /Contents 21 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 17 0 R /Resources <<-/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<-/FormXob.55532f1fc7ef8212e848f00ec587c85b 7 0 R /FormXob.abcafa7fe09633469641670e19e0fafe 8 0 R->>->> /Rotate 0- /Trans <<-->> /Type /Page->>-endobj-15 0 obj-<<-/PageMode /UseNone /Pages 17 0 R /Type /Catalog->>-endobj-16 0 obj-<<-/Author (MinerU Test Suite) /CreationDate (D:20000101000000+00'00') /Creator (MinerU Test Suite) /Keywords (MinerU synthetic test fixture) /ModDate (D:20000101000000+00'00') /Producer (MinerU Test Suite)- /Subject (Synthetic PDF regression fixture) /Title (MinerU Test Suite) /Trapped /False->>-endobj-17 0 obj-<<-/Count 4 /Kids [ 4 0 R 5 0 R 6 0 R 14 0 R ] /Type /Pages->>-endobj-18 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 591->>-stream-Gau1,;/[+&%*.8o;u!W53,BtQ,`b;B&fU/e?Fim8"DH>!60j%mKsuJRm'+?L!so9&V`K#^qu?[bc8>_Q(R;Ma!k_4riY;JKU^o`![?07\3&P'42E6Wrg>L?^)5@ZM\*N1j`bS-_<lF2qm%D>]K'hJVmdKjfC_.sO<Xft?Ub.NPYG^FV!n+SSYWP\@q;cdLnc[Ag85IcDp.lG<9m$tVlEA*[qWj5d(j+<_;;4Im;;4Im;;VIlXT*Fmp<\!4p<\!4pOLQ@s#OnABKKsUBKQ46A(G&0hB+?YjN<#fmLPY8WjCW9DaTW(8^nh/O"qnS1jmelUZ"h_XbMN68/V^e1G\ZlNSe;(r[K`#p!NIY1RW(3%06,r<,>7OO/Y6/(\&<g60;j/<7Ek-$PBkSc&R8-'_B1^[[G=PH(0e+q0@Ou;[KTCBU><=f1]$qh))J$FKSX">rH@RpsX%1^&O%Sc%kdUaNj_f;M9%VRJl5"O2QT1R:-9uM2LpW)qVc-Vu`Fq@<X::=<=<alHC`aF_0]EH.joo.<bjZPNlE-rel_A@;c;"5"%Qh"9bt0@f(pd^sTQ#SGr&F4[oMkBRTsMc25N~>endstream-endobj-19 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 791->>-stream-Gau1/9oBZN&;KZL'm3aba/\FnisHAd=4l/`QN9B<6.gf24S\65SkNZ=>L`o*KRCRWfCOZqa\.BhQNsXr?QK5S<I">.J/IQQ+?t.Mn).:Y57UU%=>EQ1@E?W=Bl=DE^E'aGWGTcS*Mim?,"u**p(:WhjjW=KcO6_'>7K;ce47$ZHh75]H@U>>:uUGO4eD(Z:N)jkr=8LG"5K@W<8;GIF5t#jcf;d\dLM%@GWSAN>!#20>!'_[^mFS8a(RqXa(RqXa*7g,2#cn[c"QJ]c"QM>+3+6[f@?4,@A'h/;Vo9%=#G4n3DDLeiNuSaGO`q]fnK4c@97q/=k6#$4]+!>8=hKrXqom<Le-n:lAUCgB4Up'4-)0BYKqB/?$4Ei.njBo96Hfpo\Loa;;T;>1%'js"Ap]cPd`Z:R+'#rJh.\N]ZlqaHq-jVaC6dFgO`!JFMq.1/4Rcq7[$s@LoCMS/7`<KP=[=i@QHdjMoo^FP?@7/W<?AJ.AL$>@\k<H&nE^r7W\NZ7GG$4\l;S'.;!L,M4Qp*K#!`XC*]<4%4p0g."b1dE$."]2U=Q[p2nFsP<CEe%?/Q<c]UFg)/HNJ#H@O(H1kC8Vb=_V[Nu6ZEH:b0Y[l),Rr)B6OI@ekB:gJsEc8C'3C@Q6Cn?'@m"rF/[`&`Ufs>tt=e[:AhJCqELt!h6HQ$"lVcRK"m<QX)4>O-O:KD(sm<QX)4>O-/:Fa&!MXdo[a<Ld[p.WVFZTXB%O@KM@m-0egApYT(+cd&5?%M=J3b\h7/n#q?gAc6[?NL&4^u5gDP2OX~>endstream-endobj-20 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 699->>-stream-Gau0Bd;IDe'RfFOgrG#^Z`icKGq;iYBWP-::OSU57'!I)eoXlJfEUWMA%N2ng+a1><[9&5I."Q.*oApcW4Q.KVb;Pa##=#2?jPm5QllIS-cf!E7u(bL;[l,F.^cmdre@YKGBOhb+hEM$;p!Jk#Yh-2$,!,-;uK1!a5i)*%+[tg/>7FaZ(DIY^gnYlj.=AIB>*9g.kokr]_2J\s.WmMO3YReHlYPofAZ)S<(=>A2M\ad2M\ad4pQm#IWr`mn92b4n92b5J4.BFNn>?.Nn>?.Nak$Q*?%u1LC40IiBYi'_kdrF$;an<XkhssU@0c'/hKk`Z'<YZnbL7.A7BAc_Mq!\)Q`VR7fsM;M%kQ9>6U<A"oDDL$*+Bt)SWtn)mYr8MKF"s[?RuCQ4*NHB).^Ajeh5Bh+O_&8I:`5diDGt\#XWX=YX7tZe;pdl6JA^oaZGDqPc28o&+/-W?Om8F6lW%7<oDU[CZ1J.,,*Jj+QDVKV#bLa"9gWgMK'eZ(.lg3cV3AQf>u[.`r)p&1Uk`P^49Xl1W!*b0+Y$o#[X$ZG+X&ES[/B/;i^F^XGcG#ZAqi=r"qP\4iNq7,OKhGF%93@1h>8juB\<ebm\e_j-]'kH6d"oYB+&+8aPN\<8T*Yqdl3**.cb$1[r/^H.kl_lo&<)Jl5JoRk"'%;A]1bSLF]8Jmfn-R'7^2o7iC%li!eb5~>endstream-endobj-21 0 obj-<<-/Filter [ /ASCII85Decode /FlateDecode ] /Length 715->>-stream-Gau1-hf$st&BE]"=54H=80mA*Z+[VAlO\Yb>%]5h^SI8"6Z'/PXZ$0*Cpujt(i(X4<Jm@>r;GFHmc"dCs!.&;:B?Ib'W2'>"k*J13=#-f"t$t*E[=O4aH]/er2@Lu@K&DoYE<7MlE8K;0O7#*=t!^o>MRF\s)@'k!?<pe`t^CahV%et_=/,*_3KRKh[G6PrS`O`@"*]Q'*+AG+c'aP)2tDQK<+WapiJ2(ajZB@&^lf1&^lf5!F2PkNms#LNms#LNq<`.Abtgcbm<Q)bm<S/+3%lHd<]lD:`pr'88<R_FArDKWFW/r5FfC_;rc_Ib@EW<9VAYTE(_Vj:MNP5kWnSlU/t1NgKIJdAb<_sD<KA$m5PnK0\VVcQEF)L:oCg<&7$lPXHaX?8K2lO/&U#s3n:aCRS#IJFibIRFid3(d1PcMW>`7o=bj+h+IGA,GAr]E$$j^5'sg=s#T"+d`Zi7(7>ej?.R09S7fCV=F=8kqr@i=8bjdS<HoJ\X,?H')c&]j'pAV!=gg`4TS[c=MVo<fU0UoH"omLhaWantLH8BX6A^T9q/s^R&\.&>FF*#qIeNndTMHk,*;g!JL.[A_sk>'G$WT^ME@iCuCMQI@-]t:L:b,+K2=N8;Mlc9Sl'T)<;dZ=;ggsj%t_IH1Z/2I%G;HEX;'sFbk.qPZWG^D4;lA4;aG5U0F=hMBd>3(?nn:;.[K6LiKq[HETJZf~>endstream-endobj-xref-0 22-0000000000 65535 f-0000000073 00000 n-0000000114 00000 n-0000000221 00000 n-0000001154 00000 n-0000001359 00000 n-0000001564 00000 n-0000001769 00000 n-0000002008 00000 n-0000002247 00000 n-0000002427 00000 n-0000002608 00000 n-0000002769 00000 n-0000002935 00000 n-0000003100 00000 n-0000003463 00000 n-0000003533 00000 n-0000003849 00000 n-0000003928 00000 n-0000004610 00000 n-0000005492 00000 n-0000006282 00000 n-trailer-<<-/ID-[<b0ce4bb64c905e47caef5c06c690f477><b0ce4bb64c905e47caef5c06c690f477>]-% ReportLab generated PDF document -- digest (http://www.reportlab.com)--/Info 16 0 R-/Root 15 0 R-/Size 22->>-startxref-7088-%%EOFdiff --git a/tests/unittest/pdfs/native_pdf_tables/README.md b/tests/unittest/pdfs/native_pdf_tables/README.mddeleted file mode 100644index 71e2e702..00000000--- a/tests/unittest/pdfs/native_pdf_tables/README.md+++ /dev/null@@ -1,24 +0,0 @@-# Native PDF Table 真实语料--本目录保存 Native PDF 表格结构恢复的仓库内回归输入。文件名采用稳定的英文语义名,评测真值位于 `tests/fixtures/native_pdf_table_cross_page_manifest.json`。--| 文件 | 页数 | 场景 |-|---|---:|---|-| `conference_schedule_tables.pdf` | 12 | 会议日程中的多页规则表格 |-| `manufacturing_facilities_cross_page_table.pdf` | 2 | 生产设施跨页表格 |-| `procurement_document_blank_page_tables.pdf` | 4 | 含空白页的采购文档表格 |-| `pollutant_discharge_tables.pdf` | 89 | 排污许可多样式表格 |-| `procurement_contract_tables.pdf` | 2 | 采购合同付款及账户表格 |-| `annual_report_research_projects_table.pdf` | 2 | 年报研发项目跨页表格 |-| `annual_report_fundraising_projects_table.pdf` | 2 | 年报募投项目跨页表格 |-| `annual_report_management_roles_table.pdf` | 2 | 年报任职情况跨页表格 |-| `quarterly_report_financial_tables.pdf` | 2 | 季报财务数据跨页表格 |-| `fund_manager_profile_table.pdf` | 2 | 基金经理简介跨页表格 |-| `fund_asset_and_transaction_tables.pdf` | 2 | 基金资产及交易表格 |-| `engineering_process_restrictions_table.pdf` | 9 | 工艺禁限用目录跨页表格 |--## 隐私处理--- 所有 PDF 均通过逐页重写移除了文档信息字典和 XMP 元数据,包括 Title、Author、Subject、Keywords、Creator、Producer 和日期字段。-- `pollutant_discharge_tables.pdf` 仅保留原文档第 3 页及之后的页面;含企业与个人信息的前两页未进入仓库。-- 除上述裁页外,页面可见内容、页面尺寸、旋转和绘图对象保持不变,并由结构真值与渲染回归共同校验。diff --git a/tests/unittest/pdfs/native_pdf_tables/annual_report_fundraising_projects_table.pdf b/tests/unittest/pdfs/native_pdf_tables/annual_report_fundraising_projects_table.pdfdeleted file mode 100644index 50239b7f..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/annual_report_fundraising_projects_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/annual_report_management_roles_table.pdf b/tests/unittest/pdfs/native_pdf_tables/annual_report_management_roles_table.pdfdeleted file mode 100644index 4b538f9a..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/annual_report_management_roles_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/annual_report_research_projects_table.pdf b/tests/unittest/pdfs/native_pdf_tables/annual_report_research_projects_table.pdfdeleted file mode 100644index 3d6d8a68..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/annual_report_research_projects_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/conference_schedule_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/conference_schedule_tables.pdfdeleted file mode 100644index 87a7f15d..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/conference_schedule_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/engineering_process_restrictions_table.pdf b/tests/unittest/pdfs/native_pdf_tables/engineering_process_restrictions_table.pdfdeleted file mode 100644index 0ea2a883..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/engineering_process_restrictions_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/fund_asset_and_transaction_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/fund_asset_and_transaction_tables.pdfdeleted file mode 100644index ce872129..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/fund_asset_and_transaction_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/fund_manager_profile_table.pdf b/tests/unittest/pdfs/native_pdf_tables/fund_manager_profile_table.pdfdeleted file mode 100644index f1b7c5e3..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/fund_manager_profile_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/manufacturing_facilities_cross_page_table.pdf b/tests/unittest/pdfs/native_pdf_tables/manufacturing_facilities_cross_page_table.pdfdeleted file mode 100644index 42550b30..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/manufacturing_facilities_cross_page_table.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/pollutant_discharge_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/pollutant_discharge_tables.pdfdeleted file mode 100644index 0229b3b7..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/pollutant_discharge_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/procurement_contract_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/procurement_contract_tables.pdfdeleted file mode 100644index bfe45232..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/procurement_contract_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/procurement_document_blank_page_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/procurement_document_blank_page_tables.pdfdeleted file mode 100644index b547f843..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/procurement_document_blank_page_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/native_pdf_tables/quarterly_report_financial_tables.pdf b/tests/unittest/pdfs/native_pdf_tables/quarterly_report_financial_tables.pdfdeleted file mode 100644index 70306083..00000000Binary files a/tests/unittest/pdfs/native_pdf_tables/quarterly_report_financial_tables.pdf and /dev/null differdiff --git a/tests/unittest/pdfs/test.pdf b/tests/unittest/pdfs/test.pdfdeleted file mode 100644index 009632f6..00000000Binary files a/tests/unittest/pdfs/test.pdf and /dev/null differdiff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.pyindex 695a81bb..7b778b7e 100644--- a/tests/unittest/test_backend_architecture.py+++ b/tests/unittest/test_backend_architecture.py@@ -2,15 +2,21 @@ from __future__ import annotationsimport astimport importlib.util-from pathlib import Pathimport subprocessimport sys+from pathlib import Pathfrom mineru.backend.postprocess import table_merge_PROJECT_ROOT = Path(__file__).resolve().parents[2]++_DOCVORTEX_ROOT = Path(importlib.util.find_spec("docvortex").origin).parent++_COPYRIGHT_HEADER = "# Copyright (c) Opendatalab. All rights reserved."++_SOURCE_ROOTS = (_PROJECT_ROOT / "mineru/backend",_PROJECT_ROOT / "mineru/model",@@ -18,6 +24,8 @@ _SOURCE_ROOTS = (_PROJECT_ROOT / "mineru/utils",_PROJECT_ROOT / "mineru/parser",)++_HEADER_PATHS = (_PROJECT_ROOT / "mineru/backend",_PROJECT_ROOT / "mineru/model/runtime",@@ -34,6 +42,8 @@ _HEADER_PATHS = (_PROJECT_ROOT / "mineru/parser/process_control.py",_PROJECT_ROOT / "mineru/parser/writer.py",)++_CHINESE_DOCSTRING_PATHS = (_PROJECT_ROOT / "mineru/backend",_PROJECT_ROOT / "mineru/model/runtime/device.py",@@ -48,30 +58,15 @@ _CHINESE_DOCSTRING_PATHS = (_PROJECT_ROOT / "mineru/render/epub.py",_PROJECT_ROOT / "mineru/render/pdf.py",_PROJECT_ROOT / "mineru/render/structured_content.py",- _DOCVORTEX_ROOT / "render/_internal/common/html_table.py",- _DOCVORTEX_ROOT / "render/_internal/latex",)++_REMOVED_INTERNAL_MODULES = (- "docvortex.compat","mineru.cli_old","mineru.backend.local_model_runtime","mineru.model.model_types",- "docvortex.analyzers.native.model",- "docvortex.analyzers.native.native_pdf",- "docvortex.analyzers.native.office.chart",- "docvortex.analyzers.native.office.docx.tools",- "docvortex.analyzers.native.office.docx.tools.math",- "docvortex.analyzers.native.office.image_equation",- "docvortex.analyzers.native.office.legacy.errors",- "docvortex.analyzers.native.office.legacy.limits",- "docvortex.analyzers.native.office.legacy.mtef",- "docvortex.analyzers.native.office.legacy.mtef_v5",- "docvortex.analyzers.native.office.legacy.stream",- "docvortex.analyzers.native.office.math",- "docvortex.analyzers.native.office.ooxml_equation","mineru.model.utils","mineru.render.writer",- "docvortex.render._internal.common.inline","mineru.utils.backend_options","mineru.utils.config_reader","mineru.utils.model_registry",@@ -83,9 +78,9 @@ _REMOVED_INTERNAL_MODULES = (def _module_name(path: Path) -> str:"""把项目内 Python 路径转换为完整模块名。"""- relative = path.relative_to(- _DOCVORTEX_ROOT.parent if path.is_relative_to(_DOCVORTEX_ROOT) else _PROJECT_ROOT- ).with_suffix("")+ relative = path.relative_to(_DOCVORTEX_ROOT.parent if path.is_relative_to(_DOCVORTEX_ROOT) else _PROJECT_ROOT).with_suffix(+ ""+ )parts = list(relative.parts)if parts[-1] == "__init__":parts.pop()@@ -117,12 +112,6 @@ def _resolved_imports(path: Path) -> set[str]:return imports-def _relative_imports(path: Path) -> set[str]:- """读取 Python 文件对同包模块的相对 import 名称。"""- tree = ast.parse(path.read_text(encoding="utf-8"))- return {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module}--def _contains_chinese(text: str) -> bool:"""判断职责说明中是否至少包含一个中文字符。"""return any("\u4e00" <= char <= "\u9fff" for char in text)@@ -221,78 +210,6 @@ def test_layer_dependencies_are_one_way() -> None:assert not offenders-def test_latex_and_render_common_keep_private_dependencies_one_way() -> None:- """守卫 LaTeX 不跨入其它格式私有实现,common 也不反向依赖格式包。"""- format_names = ("content_list", "docx", "epub", "html", "markdown", "pdf", "structured_content")- latex_offenders = {- str(path): sorted(- module- for module in _resolved_imports(path)- if module.startswith(tuple(f"docvortex.render._internal.{name}" for name in format_names))- )- for path in (_DOCVORTEX_ROOT / "render/_internal/latex").rglob("*.py")- }- common_offenders = {- str(path): sorted(- module- for module in _resolved_imports(path)- if module.startswith(tuple(f"docvortex.render._internal.{name}" for name in (*format_names, "latex")))- )- for path in (_DOCVORTEX_ROOT / "render/_internal/common").rglob("*.py")- }- assert not {path: imports for path, imports in latex_offenders.items() if imports}- assert not {path: imports for path, imports in common_offenders.items() if imports}---def test_flash_office_does_not_depend_on_pdf_implementation() -> None:- """守卫 Office 格式只复用中立能力,不反向依赖 Flash PDF 实现。"""- offenders = {- str(path): sorted(module for module in _resolved_imports(path) if module.startswith("docvortex.analyzers.native.pdf"))- for path in (_PROJECT_ROOT / "mineru/model/flash/office").rglob("*.py")- }- assert not {path: imports for path, imports in offenders.items() if imports}---def test_flash_spreadsheet_dependencies_are_one_way() -> None:- """守卫 XLS/XLSX 只依赖中立 spreadsheet 层且共享层不反向引用格式实现。"""- xls_offenders = {- str(path): sorted(- module for module in _resolved_imports(path) if module.startswith("docvortex.analyzers.native.office.xlsx")- )- for path in (_PROJECT_ROOT / "mineru/model/flash/office/xls").rglob("*.py")- }- spreadsheet_offenders = {- str(path): sorted(- module- for module in _resolved_imports(path)- if module.startswith(("docvortex.analyzers.native.office.xls", "docvortex.analyzers.native.office.xlsx"))- )- for path in (_PROJECT_ROOT / "mineru/model/flash/office/spreadsheet").rglob("*.py")- }- assert not {path: imports for path, imports in xls_offenders.items() if imports}- assert not {path: imports for path, imports in spreadsheet_offenders.items() if imports}---def test_flash_equation_and_legacy_dependencies_are_one_way() -> None:- """守卫公式层不反向引用格式实现,legacy 层也不重新承载公式解析。"""- format_prefixes = tuple(- f"docvortex.analyzers.native.office.{name}"- for name in ("doc", "docx", "odf", "ppt", "pptx", "rtf", "spreadsheet", "xls", "xlsx")- )- equation_offenders = {- str(path): sorted(module for module in _resolved_imports(path) if module.startswith(format_prefixes))- for path in (_PROJECT_ROOT / "mineru/model/flash/office/equation").rglob("*.py")- }- legacy_offenders = {- str(path): sorted(- module for module in _resolved_imports(path) if module.startswith("docvortex.analyzers.native.office.equation")- )- for path in (_PROJECT_ROOT / "mineru/model/flash/office/legacy").rglob("*.py")- }- assert not {path: imports for path, imports in equation_offenders.items() if imports}- assert not {path: imports for path, imports in legacy_offenders.items() if imports}--def test_package_initializers_define_explicit_all() -> None:"""守卫目标目录下每个包入口都显式声明 __all__。"""offenders = [@@ -373,22 +290,6 @@ assert before_env == dict(os.environ)assert result.returncode == 0, result.stderr-def test_table_merge_package_keeps_one_way_internal_dependencies() -> None:- """守卫 table_merge 低层模块不反向导入内容合并或文档编排模块。"""- package_path = _DOCVORTEX_ROOT / "content/table"- allowed_imports = {- "models.py": set(),- "html.py": {"models"},- "blocks.py": {"html", "models", "rules"},- "structure.py": {"blocks", "html", "models"},- "content.py": {"blocks", "html", "models", "structure"},- "document.py": {"blocks", "models", "structure"},- "rules.py": set(),- }- actual_imports = {filename: _relative_imports(package_path / filename) for filename in allowed_imports}- assert actual_imports == allowed_imports--def test_table_merge_public_contract_remains_callable() -> None:"""验证本地入口和 mineru-vl-utils 使用的七个公开函数保持可调用。"""function_names = [diff --git a/tests/unittest/test_backend_block_object_regressions.py b/tests/unittest/test_backend_block_object_regressions.pydeleted file mode 100644index bbc5fb80..00000000--- a/tests/unittest/test_backend_block_object_regressions.py+++ /dev/null@@ -1,68 +0,0 @@-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from typing import Any--from docvortex.postprocess.pages import model_json_to_pages-from mineru.types import BlockType, ImageBlock, ModelJson--from _span_test_utils import inline---def _model_json(pages: list[list[dict[str, Any]]]) -> ModelJson:- """为 raw block 对象化回归构造最小严格 ModelJson。"""- return ModelJson(- pages=pages,- page_index_map=[],- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def test_postprocess_groups_pdf_visual_blocks_without_dict_access() -> None:- """验证 PDF raw 视觉块会在严格对象化边界完成分组。"""- page = model_json_to_pages(- _model_json(- [- [- {- "type": BlockType.IMAGE_CAPTION,- "bbox": [0.05, 0.05, 0.6, 0.12],- "content": inline("Figure 1"),- },- {- "type": BlockType.IMAGE,- "bbox": [0.05, 0.15, 0.6, 0.45],- },- ]- ]- )- )[0]-- assert len(page.blocks) == 1- assert isinstance(page.blocks[0], ImageBlock)- assert {block.type for block in page.blocks[0].content} == {- BlockType.IMAGE_BODY,- BlockType.IMAGE_CAPTION,- }---def test_postprocess_groups_raw_vision_footnote_as_image_footnote() -> None:- """验证通用 raw footnote 会归入相邻图片而不是页脚注。"""- page = model_json_to_pages(- _model_json(- [- [- {"type": BlockType.IMAGE, "bbox": [0.1, 0.1, 0.6, 0.45]},- {"type": "footnote", "bbox": [0.12, 0.47, 0.6, 0.6], "content": inline("Figure note")},- ]- ]- )- )[0]-- assert len(page.blocks) == 1- assert isinstance(page.blocks[0], ImageBlock)- assert {block.type for block in page.blocks[0].content} == {- BlockType.IMAGE_BODY,- BlockType.IMAGE_FOOTNOTE,- }diff --git a/tests/unittest/test_docx_assets.py b/tests/unittest/test_docx_assets.pydeleted file mode 100644index 39227dc9..00000000--- a/tests/unittest/test_docx_assets.py+++ /dev/null@@ -1,242 +0,0 @@-from __future__ import annotations--import base64-from dataclasses import FrozenInstanceError-from io import BytesIO-from pathlib import Path--from PIL import Image, features-import pytest--from docvortex.render._internal.docx.assets import DocxAssetError-from docvortex.render._internal.docx.assets import PreparedImage-from docvortex.render._internal.docx.assets import prepare_block_image-from docvortex.render._internal.docx.assets import prepare_html_image-from docvortex.render._internal.docx.assets import prepare_image_bytes-from mineru.types import ImageBodyBlock---def _image_bytes(image_format: str, *, size: tuple[int, int] = (7, 5)) -> bytes:- """生成指定格式的有效测试图片字节。"""- output = BytesIO()- Image.new("RGBA" if image_format == "PNG" else "RGB", size, (20, 40, 60, 128)).save(- output,- format=image_format,- )- return output.getvalue()---def _data_uri(mime_subtype: str, payload: bytes) -> str:- """把测试图片包装成严格 base64 data URI。"""- encoded = base64.b64encode(payload).decode("ascii")- return f"data:image/{mime_subtype};base64,{encoded}"---def _generated_svg(*, logical_size: tuple[int, int] = (7, 5), fallback_size: tuple[int, int] = (56, 40)) -> bytes:- """构造带高密度 PNG fallback 的最小 MinerU SVG。"""- fallback = base64.b64encode(_image_bytes("PNG", size=fallback_size)).decode("ascii")- width, height = logical_size- return (- f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '- f'viewBox="0 0 {width} {height}" data-metafile-render="wmf-emf">'- f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{fallback}</metadata>'- f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'- "</svg>"- ).encode()---def test_generated_svg_rejects_dtd_beyond_prefix_window() -> None:- """验证 DOCX 不会嵌入在长前缀后隐藏 DTD 或实体声明的 SVG。"""- payload = (- b" " * 4097- + b'<!DOCTYPE svg [<!ENTITY injected "expanded">]>'- + _generated_svg().replace(b"</svg>", b'<text x="0" y="0" fill="#000">&injected;</text></svg>')- )-- with pytest.raises(DocxAssetError, match="safely generated by DocVortex"):- prepare_image_bytes(payload, declared_extension="svg")---def _image_block(**values: str | None) -> ImageBodyBlock:- """构造最小图片 body block。"""- return ImageBodyBlock(type="image_body", index=0, content="", **values)---def test_block_prefers_sidecar_over_base64() -> None:- """验证同时存在两种载荷时按公共契约优先解析 image_path。"""- embedded_data = _image_bytes("PNG", size=(11, 9))- sidecar_data = _image_bytes("PNG", size=(13, 7))-- def resolver(path: str) -> bytes:- """验证 helper 请求规范 sidecar 路径并返回不同尺寸图片。"""- assert path == "images/preferred.png"- return sidecar_data-- prepared = prepare_block_image(- _image_block(image_base64=_data_uri("png", embedded_data), image_path="images/preferred.png"),- resolver,- )-- assert prepared == PreparedImage(sidecar_data, "png", 13, 7)---def test_block_loads_safe_sidecar_through_resolver() -> None:- """验证 sidecar 仅通过 resolver 读取,并返回真实格式和尺寸。"""- jpeg_data = _image_bytes("JPEG", size=(13, 8))- requested_paths: list[str] = []-- def resolver(path: str) -> bytes:- """记录 renderer 交给调用方的规范化路径。"""- requested_paths.append(path)- return jpeg_data-- prepared = prepare_block_image(_image_block(image_path="images/photo.jpeg"), resolver)-- assert requested_paths == ["images/photo.jpeg"]- assert prepared == PreparedImage(jpeg_data, "jpg", 13, 8)---def test_existing_cwd_file_is_never_read_without_resolver(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """验证即使 cwd 存在同名文件,helper 也不会自行读取。"""- image_path = tmp_path / "images/local.png"- image_path.parent.mkdir()- image_path.write_bytes(_image_bytes("PNG"))- monkeypatch.chdir(tmp_path)-- with pytest.raises(DocxAssetError, match="asset_resolver is required"):- prepare_block_image(_image_block(image_path="images/local.png"))---def test_resolver_error_is_wrapped_with_safe_path() -> None:- """验证 resolver 的底层异常被统一包装,并保留原始异常链。"""-- def failing_resolver(_path: str) -> bytes:- """模拟调用方无法读取 sidecar。"""- raise OSError("disk unavailable")-- with pytest.raises(DocxAssetError, match="images/missing.png") as error:- prepare_html_image("images/missing.png", failing_resolver)-- assert isinstance(error.value.__cause__, OSError)--- "source",- [- "https://example.com/image.png",- "http://example.com/image.png",- "//example.com/image.png",- "file:///tmp/image.png",- "/tmp/image.png",- "../image.png",- r"C:\\image.png",- ],-)-def test_html_image_rejects_remote_absolute_and_unsafe_sources(source: str) -> None:- """验证 HTML 图片不会触发联网、绝对路径读取或目录逃逸。"""- resolver_called = False-- def resolver(_path: str) -> bytes:- """记录非法来源是否越过安全校验。"""- nonlocal resolver_called- resolver_called = True- return _image_bytes("PNG")-- with pytest.raises(DocxAssetError):- prepare_html_image(source, resolver)-- assert resolver_called is False---def test_html_data_uri_and_relative_sidecar_use_the_expected_source() -> None:- """验证 HTML src 支持内联 data URI 以及由 resolver 提供的相对 sidecar。"""- gif_data = _image_bytes("GIF", size=(6, 4))- inline = prepare_html_image(_data_uri("gif", gif_data))- sidecar = prepare_html_image("images/figure.gif", lambda path: gif_data if path == "images/figure.gif" else b"")-- assert inline == PreparedImage(gif_data, "gif", 6, 4)- assert sidecar == inline--[email protected](not features.check("webp"), reason="Pillow build does not support WebP")-def test_webp_is_converted_to_png_in_memory() -> None:- """验证 WebP 会转为可嵌入 Word 的 PNG,且尺寸和像素保持有效。"""- webp_data = _image_bytes("WEBP", size=(9, 7))- prepared = prepare_html_image(_data_uri("webp", webp_data))-- assert prepared.extension == "png"- assert prepared.data.startswith(b"\x89PNG\r\n\x1a\n")- assert (prepared.width_px, prepared.height_px) == (9, 7)- with Image.open(BytesIO(prepared.data)) as image:- assert image.format == "PNG"- assert image.size == (9, 7)--- ("image_format", "extension"),- [- ("PNG", "png"),- ("JPEG", "jpg"),- ("GIF", "gif"),- ("TIFF", "tiff"),- ("BMP", "bmp"),- ],-)-def test_supported_word_image_formats_keep_original_bytes(image_format: str, extension: str) -> None:- """验证 Word 可直接使用的五种格式不发生重编码。"""- data = _image_bytes(image_format)-- prepared = prepare_image_bytes(data)-- assert prepared.data is data- assert prepared.extension == extension- assert (prepared.width_px, prepared.height_px) == (7, 5)---def test_svg_is_rejected_explicitly_for_data_uri_and_sidecar() -> None:- """验证内联与 sidecar SVG 都返回明确的不支持错误。"""- svg = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'-- with pytest.raises(DocxAssetError, match="SVG images are not supported"):- prepare_html_image(_data_uri("svg+xml", svg))- with pytest.raises(DocxAssetError, match="SVG images are not supported"):- prepare_html_image("images/vector.svg", lambda _path: svg)---def test_mineru_generated_svg_keeps_native_data_and_high_density_png_fallback() -> None:- """验证 DOCX 图片准备同时保留 SVG、逻辑尺寸与高密度 PNG。"""- svg = _generated_svg()-- prepared = prepare_html_image(_data_uri("svg+xml", svg))-- assert prepared.svg_data == svg- assert prepared.extension == "png"- assert (prepared.width_px, prepared.height_px) == (7, 5)- with Image.open(BytesIO(prepared.data)) as fallback:- assert fallback.format == "PNG"- assert fallback.size == (56, 40)--- "action",- [- lambda: prepare_html_image(_data_uri("jpeg", _image_bytes("PNG"))),- lambda: prepare_html_image("data:image/png;base64,not-base64!"),- lambda: prepare_image_bytes(b""),- lambda: prepare_image_bytes(b"\x89PNG\r\n\x1a\ntruncated"),- lambda: prepare_html_image("images/empty.png", lambda _path: b""),- lambda: prepare_html_image("images/wrong.jpg", lambda _path: _image_bytes("PNG")),- ],-)-def test_invalid_mime_empty_and_corrupt_payloads_are_rejected(action: object) -> None:- """验证 MIME 不符、坏 base64、空字节、坏签名和扩展名不符都报错。"""- with pytest.raises(DocxAssetError):- action() # type: ignore[operator]---def test_prepared_image_is_immutable() -> None:- """验证 PreparedImage 是不可变的值对象。"""- prepared = PreparedImage(b"image", "png", 1, 1)-- with pytest.raises(FrozenInstanceError):- prepared.extension = "jpg" # type: ignore[misc]diff --git a/tests/unittest/test_docx_complex_fields.py b/tests/unittest/test_docx_complex_fields.pydeleted file mode 100644index 70de2a53..00000000--- a/tests/unittest/test_docx_complex_fields.py+++ /dev/null@@ -1,388 +0,0 @@-from __future__ import annotations--from io import BytesIO--from docx import Document-from docx.enum.style import WD_STYLE_TYPE-from docx.oxml import OxmlElement-from docx.oxml.ns import qn-from docx.opc.constants import RELATIONSHIP_TYPE-from docx.text.paragraph import Paragraph--from mineru.backend.analyze import doc_analyze-from docvortex.content.inline import inline_plain_text-from docvortex.analyzers.native import DocxModel-from docvortex.content.spans import inline_span_plain_text-from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter-from mineru.types import IndexBlock, ParagraphTitleBlock, TextBlock-from _span_test_utils import inline_urls---def _append_field_char(paragraph: Paragraph, field_type: str) -> None:- """向段落追加一个复杂字段边界 run。"""- run = OxmlElement("w:r")- field_char = OxmlElement("w:fldChar")- field_char.set(qn("w:fldCharType"), field_type)- run.append(field_char)- paragraph._p.append(run)---def _append_instruction(paragraph: Paragraph, instruction: str) -> None:- """向段落追加复杂字段指令 run。"""- run = OxmlElement("w:r")- instruction_element = OxmlElement("w:instrText")- instruction_element.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")- instruction_element.text = instruction- run.append(instruction_element)- paragraph._p.append(run)---def _append_result_text(- paragraph: Paragraph,- text: str,- *,- bold: bool = False,-) -> None:- """向字段结果追加一个可见文本 run。"""- run = OxmlElement("w:r")- if bold:- run_properties = OxmlElement("w:rPr")- run_properties.append(OxmlElement("w:b"))- run.append(run_properties)- text_element = OxmlElement("w:t")- if text != text.strip():- text_element.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")- text_element.text = text- run.append(text_element)- paragraph._p.append(run)---def _append_native_hyperlink(- paragraph: Paragraph,- target: str,- parts: list[tuple[str, bool]],-) -> None:- """向段落追加由多个格式 run 组成的真实外部超链接。"""-- relationship_id = paragraph.part.relate_to(- target,- RELATIONSHIP_TYPE.HYPERLINK,- is_external=True,- )- hyperlink = OxmlElement("w:hyperlink")- hyperlink.set(qn("r:id"), relationship_id)- for text, bold in parts:- run = OxmlElement("w:r")- if bold:- run_properties = OxmlElement("w:rPr")- run_properties.append(OxmlElement("w:b"))- run.append(run_properties)- text_element = OxmlElement("w:t")- if text != text.strip():- text_element.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")- text_element.text = text- run.append(text_element)- hyperlink.append(run)- paragraph._p.append(hyperlink)---def _append_result_tab(paragraph: Paragraph) -> None:- """向字段结果追加 Word 制表符 run。"""- run = OxmlElement("w:r")- run.append(OxmlElement("w:tab"))- paragraph._p.append(run)---def _append_toc_complex_field(- paragraph: Paragraph,- *,- title: str,- page_number: str,- anchor: str,- include_outer_toc: bool,- split_hyperlink_instruction: bool = False,-) -> None:- """构造 WPS 常见的 TOC、HYPERLINK 与 PAGEREF 嵌套复杂域。"""- if include_outer_toc:- _append_field_char(paragraph, "begin")- _append_instruction(paragraph, ' TOC \\o "1-1" \\h \\z \\u ')- _append_field_char(paragraph, "separate")-- _append_field_char(paragraph, "begin")- if split_hyperlink_instruction:- split_at = max(1, len(anchor) // 2)- _append_instruction(paragraph, " HYPER")- _append_instruction(paragraph, f'LINK \\l "{anchor[:split_at]}')- _append_instruction(paragraph, f'{anchor[split_at:]}" ')- else:- _append_instruction(paragraph, f' HYPERLINK \\l "{anchor}" ')- _append_field_char(paragraph, "separate")- _append_result_text(paragraph, title)- _append_result_tab(paragraph)- _append_field_char(paragraph, "begin")- _append_instruction(paragraph, f" PAGEREF {anchor} \\h ")- _append_field_char(paragraph, "separate")- _append_result_text(paragraph, page_number)- _append_field_char(paragraph, "end")- _append_field_char(paragraph, "end")-- if include_outer_toc:- _append_field_char(paragraph, "end")---def _attach_bookmark(paragraph: Paragraph, anchor: str, bookmark_id: int) -> None:- """把 bookmark 包围段落现有正文,模拟 TOC 的真实跳转目标。"""- start = OxmlElement("w:bookmarkStart")- start.set(qn("w:id"), str(bookmark_id))- start.set(qn("w:name"), anchor)- end = OxmlElement("w:bookmarkEnd")- end.set(qn("w:id"), str(bookmark_id))- insert_at = 1 if paragraph._p.pPr is not None else 0- paragraph._p.insert(insert_at, start)- paragraph._p.append(end)---def _build_complex_toc_docx() -> bytes:- """生成一个包含匹配目标和缺失目标的最小复杂域目录 DOCX。"""- document = Document()- toc_style = document.styles.add_style("TOC 1", WD_STYLE_TYPE.PARAGRAPH)-- first = document.add_paragraph(style=toc_style)- _append_toc_complex_field(- first,- title="一、建设项目基本情况",- page_number="1",- anchor="_TocTarget",- include_outer_toc=True,- split_hyperlink_instruction=True,- )- second = document.add_paragraph(style=toc_style)- _append_toc_complex_field(- second,- title="二、缺失章节",- page_number="9",- anchor="_TocMissing",- include_outer_toc=False,- )-- heading = document.add_heading("一、建设项目基本情况", level=1)- _attach_bookmark(heading, "_TocTarget", 7)-- output = BytesIO()- document.save(output)- return output.getvalue()---def _build_external_bookmark_field_docx() -> bytes:- """生成同时包含外部文档地址与 bookmark switch 的复杂字段。"""-- document = Document()- paragraph = document.add_paragraph()- _append_field_char(paragraph, "begin")- _append_instruction(- paragraph,- ' HYPERLINK "chapter.docx" \\l "Section1" ',- )- _append_field_char(paragraph, "separate")- _append_result_text(paragraph, "Open ")- _append_result_text(paragraph, "section", bold=True)- _append_field_char(paragraph, "end")- output = BytesIO()- document.save(output)- return output.getvalue()---def _build_multi_alias_toc_docx() -> bytes:- """生成两个被引用 TOC bookmark 指向同一正文段落的 DOCX。"""-- document = Document()- toc_style = document.styles.add_style("TOC 1", WD_STYLE_TYPE.PARAGRAPH)- for title, anchor in (- ("Primary entry", "_TocPrimary"),- ("Alias entry", "_TocAlias"),- ):- paragraph = document.add_paragraph(style=toc_style)- _append_toc_complex_field(- paragraph,- title=title,- page_number="1",- anchor=anchor,- include_outer_toc=False,- split_hyperlink_instruction=True,- )-- heading = document.add_heading("Shared target", level=1)- insert_at = 1 if heading._p.pPr is not None else 0- for offset, (bookmark_id, anchor) in enumerate(- ((10, "_TocPrimary"), (11, "_TocAlias")),- ):- start = OxmlElement("w:bookmarkStart")- start.set(qn("w:id"), str(bookmark_id))- start.set(qn("w:name"), anchor)- heading._p.insert(insert_at + offset, start)- end = OxmlElement("w:bookmarkEnd")- end.set(qn("w:id"), str(bookmark_id))- heading._p.append(end)-- output = BytesIO()- document.save(output)- return output.getvalue()---def test_nested_complex_toc_fields_preserve_titles_and_strict_index_targets() -> None:- """验证拆分且嵌套的复杂域不会只剩页码,并按真实正文目标收敛目录 anchor。"""- file_bytes = _build_complex_toc_docx()- model_pages = DocxModel().predict(BytesIO(file_bytes))- raw_index = next(block for page in model_pages for block in page if block["type"] == "index")-- assert [inline_span_plain_text(child["content"]) for child in raw_index["content"]] == [- "一、建设项目基本情况\t1",- "二、缺失章节\t9",- ]- assert [child.get("anchor") for child in raw_index["content"]] == ["_TocTarget", "_TocMissing"]-- middle_json, _ = doc_analyze(file_bytes, effort="flash", parse_mode="auto", file_suffix="docx")- typed_index = next(block for page in middle_json.pages for block in page.blocks if isinstance(block, IndexBlock))- assert isinstance(typed_index.content[0], ParagraphTitleBlock)- assert typed_index.content[0].anchor == "_TocTarget"- assert inline_plain_text(typed_index.content[0].content) == "一、建设项目基本情况\t1"- assert isinstance(typed_index.content[1], TextBlock)- assert typed_index.content[1].anchor is None- assert inline_plain_text(typed_index.content[1].content) == "二、缺失章节\t9"---def test_external_complex_hyperlink_preserves_bookmark_switch() -> None:- """验证外部复杂字段把文档地址与 bookmark 合成为同一个链接目标。"""-- file_bytes = _build_external_bookmark_field_docx()- model_pages = DocxModel().predict(BytesIO(file_bytes))- raw_text = next(block for page in model_pages for block in page if block["type"] == "text")-- assert inline_span_plain_text(raw_text["content"]) == "Open section"- assert inline_urls(raw_text["content"]) == ["chapter.docx#Section1"]- assert [child["styles"] for child in raw_text["content"][0]["content"]] == [[], ["bold"]]-- middle_json, _ = doc_analyze(file_bytes, effort="flash", parse_mode="auto", file_suffix="docx")- typed_text = next(block for page in middle_json.pages for block in page.blocks if isinstance(block, TextBlock))- assert inline_plain_text(typed_text.content) == "Open section"- assert inline_urls(typed_text.content) == ["chapter.docx#Section1"]---def test_split_toc_bookmark_aliases_collapse_to_one_target_anchor() -> None:- """验证拆分字段引用的同段落 bookmark aliases 收敛为唯一公开 anchor。"""-- file_bytes = _build_multi_alias_toc_docx()- model_pages = DocxModel().predict(BytesIO(file_bytes))- raw_index = next(block for page in model_pages for block in page if block["type"] == "index")- raw_heading = next(- block- for page in model_pages- for block in page- if block["type"] == "paragraph_title" and inline_span_plain_text(block["content"]) == "Shared target"- )-- assert raw_heading["anchor"] == "_TocPrimary"- assert [child.get("anchor") for child in raw_index["content"]] == [- "_TocPrimary",- "_TocPrimary",- ]-- middle_json, _ = doc_analyze(- file_bytes,- effort="flash",- parse_mode="auto",- file_suffix="docx",- )- typed_index = next(block for page in middle_json.pages for block in page.blocks if isinstance(block, IndexBlock))- typed_heading = next(- block- for page in middle_json.pages- for block in page.blocks- if isinstance(block, ParagraphTitleBlock) and inline_plain_text(block.content) == "Shared target"- )- assert typed_heading.anchor == "_TocPrimary"- assert [child.anchor for child in typed_index.content] == [- "_TocPrimary",- "_TocPrimary",- ]---def test_native_hyperlink_preserves_spaces_between_formatted_runs() -> None:- """验证真实超链接跨格式 run 时保留内部空格并维持单一链接目标。"""-- document = Document()- paragraph = document.add_paragraph()- _append_native_hyperlink(- paragraph,- "https://example.test/section",- [("Open ", False), ("section", True)],- )- output = BytesIO()- document.save(output)-- model_pages = DocxModel().predict(BytesIO(output.getvalue()))- raw_text = next(block for page in model_pages for block in page if block["type"] == "text")-- assert inline_span_plain_text(raw_text["content"]) == "Open section"- assert inline_urls(raw_text["content"]) == ["https://example.test/section"]- assert [child["styles"] for child in raw_text["content"][0]["content"]] == [[], ["bold"]]---def test_native_hyperlink_moves_trailing_space_to_plain_text() -> None:- """验证链接尾部空格移到后续普通文本,既保留分隔也不扩大可点击范围。"""-- document = Document()- paragraph = document.add_paragraph()- _append_native_hyperlink(- paragraph,- "https://example.test/link",- [("link ", False)],- )- paragraph.add_run("after")- output = BytesIO()- document.save(output)-- model_pages = DocxModel().predict(BytesIO(output.getvalue()))- raw_text = next(block for page in model_pages for block in page if block["type"] == "text")-- assert inline_span_plain_text(raw_text["content"]) == "link after"- assert inline_urls(raw_text["content"]) == ["https://example.test/link"]- assert inline_span_plain_text(raw_text["content"][0]["content"]) == "link"- assert raw_text["content"][1] == {- "type": "text",- "content": " after",- }---def test_hyperlink_boundary_spaces_are_plain_and_only_paragraph_edges_trim() -> None:- """验证链接首尾空格移为普通元素,不同链接间保留间隔且仅段落外缘裁剪。"""-- first_target = "https://example.test/first"- second_target = "https://example.test/second"-- assert DocxConverter._normalize_hyperlink_group_boundaries(- [- ("before", None, None),- (" link ", None, first_target),- ("after", None, None),- ]- ) == [- ("before", None, None),- (" ", None, None),- ("link", None, first_target),- (" ", None, None),- ("after", None, None),- ]- assert DocxConverter._normalize_hyperlink_group_boundaries(- [- ("first ", None, first_target),- ("second", None, second_target),- ]- ) == [- ("first", None, first_target),- (" ", None, None),- ("second", None, second_target),- ]- assert DocxConverter._normalize_hyperlink_group_boundaries([(" link ", None, first_target)]) == [- ("link", None, first_target)- ]diff --git a/tests/unittest/test_docx_math.py b/tests/unittest/test_docx_math.pydeleted file mode 100644index 53c6e1d0..00000000--- a/tests/unittest/test_docx_math.py+++ /dev/null@@ -1,157 +0,0 @@-from __future__ import annotations--import pytest-from lxml import etree--from docvortex.render._internal.docx.math import DocxFormulaError-from docvortex.render._internal.docx.math import latex_to_omml-from docvortex.render._internal.docx.math import split_formula_tag--_OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"--- ("content", "expected"),- [- (r"x + y\tag{1}", ("x + y", "1")),- (r"x + y\tag { A_{n} } ", ("x + y", "A_{n}")),- (r"x + y\tag{\mathrm{A}_{n}}", ("x + y", r"\mathrm{A}_{n}")),- (r"x + y\tag{\{1\}}", ("x + y", r"\{1\}")),- ],-)-def test_split_formula_tag_strips_only_balanced_terminal_tag(- content: str,- expected: tuple[str, str | None],-) -> None:- """验证末端 tag 支持空白、嵌套花括号和转义花括号。"""- assert split_formula_tag(content) == expected--- "content",- [- r"x + y\tag{1} + z",- r"x + y\tag{1",- r"x + y\tag{1}}",- r"x + y\tagged{1}",- r"x + y\\tag{1}",- "plain formula ",- ],-)-def test_split_formula_tag_preserves_non_terminal_or_malformed_content(content: str) -> None:- """验证非末端、损坏或并非命令的 tag 文本不会被误剥离。"""- assert split_formula_tag(content) == (content, None)---def test_latex_to_omml_returns_inline_equation_with_bound_namespace() -> None:- """验证行内公式返回可独立序列化的 m:oMath 节点。"""- equation = latex_to_omml(r"x^2 + \frac{a}{b}", display=False)-- assert equation.tag == etree.QName(_OFFICE_MATH_NAMESPACE, "oMath")- assert equation.getparent() is None- assert equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}f") is not None- reparsed = etree.fromstring(etree.tostring(equation))- assert reparsed.tag == equation.tag---def test_latex_to_omml_wraps_display_matrix_in_math_paragraph() -> None:- """验证块公式以 m:oMathPara 包装,并保留矩阵 OMML。"""- paragraph = latex_to_omml(r"\begin{matrix}a&b\\c&d\end{matrix}", display=True)-- assert paragraph.tag == etree.QName(_OFFICE_MATH_NAMESPACE, "oMathPara")- equations = paragraph.findall(f"{{{_OFFICE_MATH_NAMESPACE}}}oMath")- assert len(equations) == 1- assert equations[0].find(f".//{{{_OFFICE_MATH_NAMESPACE}}}m") is not None--[email protected]("latex", [r"\bar p", r"\vec{u}"])-def test_latex_to_omml_repairs_group_character_property_closing_tag(latex: str) -> None:- """验证横线和向量符号不会因第三方库的错误闭合标签退化为文本。"""- equation = latex_to_omml(latex, display=False)-- assert equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}groupChr") is not None- etree.fromstring(etree.tostring(equation))---def test_latex_to_omml_hides_square_root_degree_placeholder() -> None:- """验证普通平方根包含隐藏 degree,避免 Word/LibreOffice 显示占位框。"""- equation = latex_to_omml(r"\sqrt{x}", display=False)-- radical = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}rad")- assert radical is not None- assert radical.find(f"{{{_OFFICE_MATH_NAMESPACE}}}deg") is not None- degree_hidden = radical.find(f"{{{_OFFICE_MATH_NAMESPACE}}}radPr/{{{_OFFICE_MATH_NAMESPACE}}}degHide")- assert degree_hidden is not None- assert degree_hidden.get(f"{{{_OFFICE_MATH_NAMESPACE}}}val") == "1"--[email protected]("latex", [r"^{2}", r"_{0}"])-def test_latex_to_omml_uses_zero_width_script_base(latex: str) -> None:- """验证无显式底数的上下标使用零宽字符抑制可见方框。"""- equation = latex_to_omml(latex, display=False)- base = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}sSup/{{{_OFFICE_MATH_NAMESPACE}}}e")- if base is None:- base = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}sSub/{{{_OFFICE_MATH_NAMESPACE}}}e")-- assert base is not None- assert "\u200b" in "".join(base.itertext())---def test_latex_to_omml_removes_explicitly_empty_operator_limits() -> None:- """验证空上下限不会在积分或其他算子旁生成可见占位框。"""- equation = latex_to_omml(r"\int_{}^{} x + E_{}", display=False)- serialized = etree.tostring(equation, encoding="unicode")-- assert "<m:t></m:t>" not in serialized- assert "<m:sub>" not in serialized and "<m:sup>" not in serialized---def test_latex_to_omml_normalizes_no_bar_genfrac_in_binomial_formula() -> None:- """验证 Office 无横线分式可转为带定界符的双行 OMML matrix。"""- formula = (- r"\left(x+a\right)^{n}=\sum_{k=0}^{n}"- r"\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}"- )-- equation = latex_to_omml(formula, display=False)- matrix = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}m")- delimiter = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}d")-- assert matrix is not None- assert delimiter is not None- rows = matrix.findall(f"{{{_OFFICE_MATH_NAMESPACE}}}mr")- assert ["".join(row.itertext()) for row in rows] == ["n", "k"]--- ("latex", "expected_matrix_count"),- [- (r"\genfrac{}{}{0pt}{}{a_{i}}{\frac{b}{c}}", 1),- (r"\genfrac{}{}{0pt}{}{a}{b}+\genfrac{}{}{0pt}{}{c}{d}", 2),- (r"\genfrac{}{}{0pt}{}{\genfrac{}{}{0pt}{}{a}{b}}{c}", 2),- ],-)-def test_latex_to_omml_normalizes_nested_and_multiple_genfrac(- latex: str,- expected_matrix_count: int,-) -> None:- """验证 genfrac 参数可含嵌套结构,且一条公式可转换多个实例。"""- equation = latex_to_omml(latex, display=False)-- assert len(equation.findall(f".//{{{_OFFICE_MATH_NAMESPACE}}}m")) == expected_matrix_count--- "latex",- [- r"\frac{a",- r"\genfrac{(}{)}{1pt}{}{a}{b}",- "x\x00y",- ],-)-def test_latex_to_omml_wraps_conversion_failures_with_original_cause(latex: str) -> None:- """验证损坏或非规范输入失败时保留原异常链。"""- with pytest.raises(DocxFormulaError, match="无法转换为 OMML") as exc_info:- latex_to_omml(latex, display=True)-- assert exc_info.value.__cause__ is not Nonediff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.pydeleted file mode 100644index 308e935a..00000000--- a/tests/unittest/test_docx_render.py+++ /dev/null@@ -1,1026 +0,0 @@-from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inline--import base64-from copy import deepcopy-from io import BytesIO-from unittest.mock import Mock-import zipfile--from docx import Document-from docx.shared import Mm, Twips-from lxml import etree-from PIL import Image-import pytest--from mineru.render import DocxRenderError, render_docx-from mineru.types import (- ChartBlock,- ChartBodyBlock,- CodeBlock,- EquationBlock,- ImageBlock,- ImageBodyBlock,- IndexBlock,- ListBlock,- MiddleJson,- PageAuxTextBlock,- PageBlock,- PageFootnoteBlock,- PageInfo,- ParagraphTitleBlock,- TableAnnotationBlock,- TableBlock,- TableBodyBlock,- TextBlock,-)---def _middle(*pages: PageInfo) -> MiddleJson:- """构造最小严格 MiddleJson 测试对象。"""- return MiddleJson(- pages=list(pages),- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:- """构造保持调用方 block 顺序的严格页面。"""- return PageInfo(page_idx=page_idx, blocks=list(blocks))---def _png_bytes(*, size: tuple[int, int] = (12, 8)) -> bytes:- """生成可被 Pillow 和 python-docx 完整读取的 PNG。"""- output = BytesIO()- Image.new("RGB", size, (30, 60, 90)).save(output, format="PNG")- return output.getvalue()---def _png_uri(*, size: tuple[int, int] = (12, 8)) -> str:- """生成严格 PNG data URI。"""- payload = base64.b64encode(_png_bytes(size=size)).decode("ascii")- return f"data:image/png;base64,{payload}"---def _generated_svg_uri(*, logical_size: tuple[int, int] = (12, 8), fallback_size: tuple[int, int] = (96, 64)) -> str:- """生成带高密度 PNG fallback 的 DocVortex SVG data URI。"""- width, height = logical_size- fallback = base64.b64encode(_png_bytes(size=fallback_size)).decode("ascii")- svg = (- f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '- f'viewBox="0 0 {width} {height}" data-metafile-render="wmf-emf">'- f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{fallback}</metadata>'- f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'- "</svg>"- ).encode()- return f"data:image/svg+xml;base64,{base64.b64encode(svg).decode('ascii')}"---def _part(docx_bytes: bytes, name: str) -> str:- """读取 DOCX ZIP 中一个 XML part。"""- with zipfile.ZipFile(BytesIO(docx_bytes)) as archive:- return archive.read(name).decode("utf-8")---def test_public_contract_returns_reopenable_docx_without_mutation() -> None:- """验证严格入口、可重开 bytes 和输入无副作用。"""- middle = _middle(_page(0, TextBlock(type="text", index=0, content=_inline("hello"))))- original = deepcopy(middle)-- result = render_docx(middle)-- assert result.startswith(b"PK\x03\x04")- assert Document(BytesIO(result)).paragraphs[0].text == "hello"- assert middle == original- with pytest.raises(TypeError, match="MiddleJson"):- render_docx(middle.to_dict()) # type: ignore[arg-type]- with pytest.raises(TypeError, match="unexpected keyword argument 'mode'"):- render_docx(middle, mode="full") # type: ignore[arg-type]---def test_xml_incompatible_text_is_replaced_with_visible_marker() -> None:- """验证真实语料中的 XML 控制字符会转为 U+FFFD,而不是中止或静默删除。"""- middle = _middle(_page(0, TextBlock(type="text", index=0, content=_inline("before\x01after"))))-- document = Document(BytesIO(render_docx(middle)))-- assert document.paragraphs[0].text == "before\ufffdafter"---def test_heading_bookmark_forward_index_link_and_rich_inline_ooxml() -> None:- """验证 Heading、前向目录链接、外链、组合样式和行内 OMML。"""- index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(- type="paragraph_title",- level=2,- anchor="section a",- content=_inline("Section\t12"),- )- ],- )- text = TextBlock(- type="text",- index=1,- content=[- {- "type": "text",- "content": "Styled",- "styles": ["bold", "italic", "underline", "strikethrough", "emphasis"],- },- {"type": "text", "content": "2", "styles": ["superscript"]},- {"type": "text", "content": "i", "styles": ["subscript"]},- {"type": "hyperlink", "url": "https://example.com/a", "content": _inline("Link")},- {"type": "equation_inline", "content": "x^2"},- ],- )- title = ParagraphTitleBlock(- type="paragraph_title",- index=2,- level=2,- anchor="section a",- content=_inline("Section"),- )-- result = render_docx(_middle(_page(0, index, text, title)))- document_xml = _part(result, "word/document.xml")- relationships = _part(result, "word/_rels/document.xml.rels")-- assert 'w:pStyle w:val="Heading2"' in document_xml- assert 'w:bookmarkStart w:id="0" w:name="section_a"' in document_xml- assert 'w:hyperlink w:anchor="section_a"' in document_xml- assert "https://example.com/a" in relationships- assert "<w:b" in document_xml and "<w:i" in document_xml- assert "<w:u" in document_xml and "<w:strike" in document_xml- assert '<w:vertAlign w:val="superscript"' in document_xml- assert '<w:vertAlign w:val="subscript"' in document_xml- assert '<w:em w:val="underDot"' in document_xml- assert "<m:oMath" in document_xml---def test_docx_uses_page_footnote_bookmark_and_style() -> None:- """验证固定默认 Word 输出页面脚注书签、内部链接和专用样式。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "See "},- {"type": "hyperlink", "url": "#note-one", "content": _inline("[1]")},- {"type": "text", "content": " and "},- {"type": "hyperlink", "url": "#missing-note", "content": _inline("[x]")},- {"type": "text", "content": "."},- ],- ),- PageFootnoteBlock(- type="page_footnote",- index=1,- content=_inline("Footnote body."),- anchor="note-one",- ),- )- )-- result = render_docx(middle)- document_xml = _part(result, "word/document.xml")- relationships = _part(result, "word/_rels/document.xml.rels")- document = Document(BytesIO(result))- footnote = next(paragraph for paragraph in document.paragraphs if paragraph.text == "Footnote body.")-- assert 'w:bookmarkStart w:id="0" w:name="note_one"' in document_xml- assert 'w:hyperlink w:anchor="note_one"' in document_xml- assert document_xml.count("<w:hyperlink") == 1- assert footnote.style.name == "DocVortex Footnote"- assert "missing-note" not in relationships- assert "#note-one" not in relationships---def test_visible_styled_boundary_spaces_use_nbsp_without_mutating_input() -> None:- """验证可见样式的边界空格转为等量 NBSP,普通样式和内部空格保持原样。"""- content = [- {"type": "text", "content": " left", "styles": ["underline"]},- {"type": "text", "content": "|"},- {"type": "text", "content": "right ", "styles": ["strikethrough"]},- {"type": "text", "content": "|"},- {"type": "text", "content": " ", "styles": ["underline", "strikethrough"]},- {"type": "text", "content": "|"},- {"type": "text", "content": " emphasis ", "styles": ["emphasis"]},- {"type": "text", "content": "|"},- {"type": "text", "content": " bold ", "styles": ["bold"]},- {"type": "text", "content": "|"},- {"type": "text", "content": "a b", "styles": ["underline"]},- ]- middle = _middle(_page(0, TextBlock(type="text", index=0, content=content)))- original = deepcopy(middle)-- result = render_docx(middle)- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")-- assert document.paragraphs[0].text == (- "\u00a0\u00a0left|right\u00a0\u00a0|\u00a0\u00a0\u00a0|\u00a0\u00a0emphasis\u00a0\u00a0| bold |a b"- )- assert document.paragraphs[0].text.count("\u00a0") == 11- assert '<w:em w:val="underDot"' in document_xml- assert '<w:em w:val="dot"' not in document_xml- assert middle == original---def test_bookmark_names_are_sanitized_and_collision_safe() -> None:- """验证不同原 anchor 清洗后冲突时仍生成唯一 Word bookmark。"""- first = ParagraphTitleBlock(- type="paragraph_title",- index=0,- level=2,- anchor="section-a",- content=_inline("First"),- )- second = ParagraphTitleBlock(- type="paragraph_title",- index=1,- level=2,- anchor="section a",- content=_inline("Second"),- )-- document_xml = _part(render_docx(_middle(_page(0, first, second))), "word/document.xml")-- assert 'w:name="section_a"' in document_xml- assert document_xml.count("<w:bookmarkStart") == 2- names = document_xml.split('w:bookmarkStart w:id="')[1:]- assert len({value.split('w:name="', 1)[1].split('"', 1)[0] for value in names}) == 2---def test_index_only_anchor_falls_back_to_plain_text_without_dangling_link() -> None:- """验证目录独有 anchor 不会被误注册为没有正文 bookmark 的内部链接。"""- index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(- type="paragraph_title",- level=2,- anchor="missing-target",- content=_inline("Missing target\t8"),- )- ],- )-- document_xml = _part(render_docx(_middle(_page(0, index))), "word/document.xml")-- assert "Missing target" in document_xml- assert "w:anchor=" not in document_xml- assert "w:bookmarkStart" not in document_xml---def test_docx_uses_default_planner_without_source_page_boundaries() -> None:- """验证固定默认 DOCX 隐藏辅助块、合并续段且不写源页硬分页。"""- middle = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("international")),- PageAuxTextBlock(type="header", index=1, content=_inline("HEADER")),- ),- _page(1, TextBlock(type="text", index=0, content=_inline("continuation"), continues_prev=True)),- )-- result = render_docx(middle)- document = Document(BytesIO(result))-- assert [paragraph.text for paragraph in document.paragraphs] == ["international continuation"]- assert "HEADER" not in [paragraph.text for paragraph in document.paragraphs]- assert 'w:br w:type="page"' not in _part(result, "word/document.xml")---def test_list_preserves_markers_and_uses_hanging_indents_without_numbering() -> None:- """验证列表不重建 numbering.xml,只保留 marker 和递归缩进。"""- nested = ListBlock(- type="list",- content=[TextBlock(type="text", content=_inline("- nested item"))],- )- block = ListBlock(- type="list",- index=0,- content=[TextBlock(type="text", content=_inline("1. first item")), nested],- )-- result = render_docx(_middle(_page(0, block)))- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")-- assert [paragraph.text for paragraph in document.paragraphs] == ["1. first item", "- nested item"]- assert abs(int(document.paragraphs[0].paragraph_format.left_indent) - int(Mm(6))) < 635- assert abs(int(document.paragraphs[0].paragraph_format.first_line_indent) + int(Mm(6))) < 635- assert abs(int(document.paragraphs[1].paragraph_format.left_indent) - int(Mm(12))) < 635- assert "<w:numPr" not in document_xml---def test_display_formula_tag_uses_center_and_right_tabs() -> None:- """验证公式主体为 OMML,tag 通过右对齐 tab 单独输出。"""- block = EquationBlock(type="equation", index=0, content=r"x^2=1\tag{9}")-- result = render_docx(_middle(_page(0, block)))- document_xml = _part(result, "word/document.xml")- document = Document(BytesIO(result))-- assert "<m:oMath" in document_xml- assert "<m:oMathPara" not in document_xml- assert document.paragraphs[0].text == "\t\t(9)"- assert document_xml.count("<w:tab/>") == 2- assert 'w:val="center"' in document_xml- assert 'w:val="right"' in document_xml---def test_display_formula_without_tag_uses_math_paragraph() -> None:- """验证无编号块公式使用居中的 m:oMathPara。"""- result = render_docx(_middle(_page(0, EquationBlock(type="equation", index=0, content=r"x^2=1"))))- document_xml = _part(result, "word/document.xml")- root = etree.fromstring(document_xml.encode("utf-8"))- namespace = {- "m": "http://schemas.openxmlformats.org/officeDocument/2006/math",- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",- }- math_paragraph = root.find(".//m:oMathPara", namespaces=namespace)-- assert "<m:oMathPara" in document_xml- assert '<m:jc m:val="center"' in document_xml- assert math_paragraph is not None- assert math_paragraph.getparent().tag == f"{{{namespace['w']}}}p"---def test_formula_conversion_failure_falls_back_to_image_then_visible_latex() -> None:- """验证块公式优先图片回退,行内公式保留可见 LaTeX。"""- unsupported = r"\frac{a"- middle = _middle(- _page(- 0,- EquationBlock(- type="equation",- index=0,- content=unsupported,- image_base64=_png_uri(),- ),- TextBlock(type="text", index=1, content=_inline(f"before <eq>{unsupported}</eq> after")),- )- )-- result = render_docx(middle)- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")-- assert len(document.inline_shapes) == 1- assert unsupported in "".join(paragraph.text for paragraph in document.paragraphs)- assert "<a:blip" in document_xml---def test_genfrac_formula_renders_native_omml_in_title_and_list() -> None:- """验证正文标题和列表中的规范 genfrac 均输出原生双行 OMML。"""- formula = (- r"\left(x+a\right)^{n}=\sum_{k=0}^{n}"- r"\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}"- )- title = ParagraphTitleBlock(- type="paragraph_title",- index=0,- level=2,- content=[{"type": "text", "content": "Title "}, {"type": "equation_inline", "content": formula}],- )- list_block = ListBlock(- type="list",- index=1,- content=[- TextBlock(- type="text",- content=[- {"type": "text", "content": "1. before "},- {"type": "equation_inline", "content": formula},- {"type": "text", "content": " after"},- ],- )- ],- )-- result = render_docx(_middle(_page(0, title, list_block)))- document_xml = _part(result, "word/document.xml")-- assert document_xml.count("<m:oMath") == 2- assert document_xml.count("<m:m>") == 2- assert document_xml.count("<m:d>") >= 2- assert r"\genfrac" not in document_xml---def test_inline_bare_scripts_use_word_superscript_runs_without_placeholder_boxes() -> None:- """验证无底数公式片段改用上下标 run,避免 OMML 可见占位框。"""- block = TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "S K"},- {"type": "equation_inline", "content": "^{1/2}"},- {"type": "text", "content": "/cm"},- {"type": "equation_inline", "content": "^{-1}"},- ],- )-- result = render_docx(_middle(_page(0, block)))- document_xml = _part(result, "word/document.xml")-- assert Document(BytesIO(result)).paragraphs[0].text == "S K1/2/cm-1"- assert document_xml.count('w:vertAlign w:val="superscript"') == 2- assert "<m:oMath" not in document_xml---def test_required_image_error_contains_public_block_location() -> None:- """验证缺少 resolver 的必需图片通过公共异常暴露完整定位。"""- image = ImageBlock(- type="image",- index=3,- content=[- ImageBodyBlock(- type="image_body",- index=3,- content="description",- image_path="images/missing.png",- )- ],- )-- with pytest.raises(DocxRenderError, match="asset_resolver") as exc_info:- render_docx(_middle(_page(7, image)))-- assert exc_info.value.page_idx == 7- assert exc_info.value.block_index == 3- assert exc_info.value.block_type == "image"---def test_image_alt_text_and_visual_child_order_are_preserved() -> None:- """验证图片 alt description 及 caption/body/footnote 源顺序。"""- image = ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "content": [- {"type": "image_caption", "content": _inline("before")},- {- "type": "image_body",- "index": 0,- "content": "<p>diagram description</p>",- "image_base64": _png_uri(),- },- {"type": "image_footnote", "content": _inline("after")},- ],- }- )-- document_xml = _part(render_docx(_middle(_page(0, image))), "word/document.xml")-- assert document_xml.index("before") < document_xml.index("diagram description")- assert document_xml.index("diagram description") < document_xml.index("after")- assert 'descr="diagram description"' in document_xml---def test_mineru_svg_writes_native_svg_relationship_with_png_fallback() -> None:- """验证 DOCX DrawingML 同时引用原生 SVG 与高密度 PNG fallback。"""- image = ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "content": [- {- "type": "image_body",- "index": 0,- "content": "vector formula",- "image_base64": _generated_svg_uri(),- }- ],- }- )-- result = render_docx(_middle(_page(0, image)))- with zipfile.ZipFile(BytesIO(result)) as archive:- media = sorted(name for name in archive.namelist() if name.startswith("word/media/"))- document_xml = etree.fromstring(archive.read("word/document.xml"))- relationships = etree.fromstring(archive.read("word/_rels/document.xml.rels"))- content_types = archive.read("[Content_Types].xml").decode("utf-8")-- assert any(name.endswith(".png") for name in media)- assert any(name.endswith(".svg") for name in media)- namespace = {- "a": "http://schemas.openxmlformats.org/drawingml/2006/main",- "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",- "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",- }- fallback_id = document_xml.xpath("string(.//a:blip/@r:embed)", namespaces=namespace)- svg_id = document_xml.xpath("string(.//asvg:svgBlip/@r:embed)", namespaces=namespace)- targets = {relationship.get("Id"): relationship.get("Target") for relationship in relationships}- assert fallback_id != svg_id- assert targets[fallback_id].endswith(".png")- assert targets[svg_id].endswith(".svg")- assert "image/svg+xml" in content_types---def test_html_table_materializes_merges_inline_content_link_and_image() -> None:- """验证复杂 HTML 表格生成合并几何,并复用单元格行内与素材 visitor。"""- html = (- "<table><thead><tr><th rowspan='2'>A</th><th colspan='2'>B</th></tr></thead>"- "<tbody><tr><td><strong>x</strong><eq>y</eq>"- "<a href='https://example.com/table'>link</a></td>"- f"<td><img src='{_png_uri()}' alt='cell image'/></td></tr></tbody></table>"- )- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- result = render_docx(_middle(_page(0, table)))- document_xml = _part(result, "word/document.xml")- relationships = _part(result, "word/_rels/document.xml.rels")- document = Document(BytesIO(result))-- assert len(document.tables) == 1- assert '<w:gridSpan w:val="2"' in document_xml- assert "<w:vMerge" in document_xml- assert "<w:tblHeader" in document_xml- assert "<m:oMath" in document_xml- assert "<a:blip" in document_xml- assert "https://example.com/table" in relationships---def test_html_table_does_not_restore_legacy_text_style_tags() -> None:- """验证旧 text-style 容器只保留文字,标准 strong 标签继续恢复粗体。"""- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=('<table><tr><td><text style="bold">legacy</text><strong>standard</strong></td></tr></table>'),- )- ],- )-- document = Document(BytesIO(render_docx(_middle(_page(0, table)))))- runs = [run for paragraph in document.tables[0].cell(0, 0).paragraphs for run in paragraph.runs if run.text]-- assert [(run.text, bool(run.bold)) for run in runs] == [("legacy", False), ("standard", True)]---def test_html_table_cell_lists_keep_item_boundaries() -> None:- """验证 HTML 单元格中的有序和无序列表不会串成连续文本。"""- html = (- "<table><tr><td>Items:<ul><li>first</li><li>second</li></ul>"- "<ol start='3'><li>third</li><li>fourth</li></ol></td></tr></table>"- )- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- document = Document(BytesIO(render_docx(_middle(_page(0, table)))))-- assert document.tables[0].cell(0, 0).text == "Items:\n- first\n- second\n3. third\n4. fourth"---def test_html_table_direct_nested_table_is_materialized_recursively() -> None:- """验证单元格直接子 table 通过绑定 writer 递归物化,而不是压成纯文本。"""- html = "<table><tr><td>before<table><tr><td>nested</td></tr></table>after</td></tr></table>"- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- result = render_docx(_middle(_page(0, table)))- document_xml = _part(result, "word/document.xml")- cell = Document(BytesIO(result)).tables[0].cell(0, 0)-- assert document_xml.count("<w:tbl>") == 2- assert "before" in document_xml and "nested" in document_xml and "after" in document_xml- assert len(cell.tables) == 1- assert [paragraph.text for paragraph in cell.paragraphs if paragraph.text] == ["before", "after"]---def test_html_table_nested_inside_wrapper_keeps_table_and_source_order() -> None:- """验证 div 等包装层中的嵌套表格不会被压平成连续文本。"""- html = "<table><tr><td><div>before<table><tr><td>nested</td></tr></table>after</div></td></tr></table>"- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- result = render_docx(_middle(_page(0, table)))- cell = Document(BytesIO(result)).tables[0].cell(0, 0)-- assert len(cell.tables) == 1- assert [paragraph.text for paragraph in cell.paragraphs if paragraph.text] == ["before", "after"]- assert _part(result, "word/document.xml").count("<w:tbl>") == 2---def test_html_table_fallback_rolls_back_partial_table_and_relationships() -> None:- """验证单元格素材失败时移除半成品表格和其新增关系,再只写整体图片。"""- html = f"<table><tr><td><img src='{_png_uri(size=(8, 8))}'/></td><td><img src='images/missing.png'/></td></tr></table>"- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=html,- image_base64=_png_uri(size=(10, 10)),- )- ],- )-- result = render_docx(_middle(_page(0, table)))- document = Document(BytesIO(result))- with zipfile.ZipFile(BytesIO(result)) as archive:- media = [name for name in archive.namelist() if name.startswith("word/media/")]-- assert len(document.tables) == 0- assert len(document.inline_shapes) == 1- assert len(media) == 1---def test_html_table_remote_cell_image_uses_safe_link_fallback() -> None:- """验证远程单元格图片输出可点击 alt,而不是中断整份 DOCX。"""- html = '<table><tr><td><img src="https://example.com/logo.png" alt="Logo"></td></tr></table>'- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- result = render_docx(_middle(_page(0, table)))- document = Document(BytesIO(result))-- assert document.tables[0].cell(0, 0).text == "Logo"- assert len(document.inline_shapes) == 0- assert "https://example.com/logo.png" in _part(result, "word/_rels/document.xml.rels")---def test_html_table_cell_image_is_limited_to_merged_cell_width() -> None:- """验证窄列图片宽度不超过扣除单元格左右内边距后的 tcW。"""- cells = [f"<td>{'<img src=' + repr(_png_uri(size=(300, 100))) + '/>' if index == 0 else index}</td>" for index in range(10)]- html = f"<table><tr>{''.join(cells)}</tr></table>"- table = TableBlock(- type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content=html)],- )-- document = Document(BytesIO(render_docx(_middle(_page(0, table)))))- cell = document.tables[0].cell(0, 0)- cell_width_twips = int(cell._tc.get_or_add_tcPr().get_or_add_tcW().w)- available_width_emu = int(Twips(cell_width_twips - 240))-- assert len(document.inline_shapes) == 1- assert int(document.inline_shapes[0].width) <= available_width_emu---def test_invalid_html_table_falls_back_to_table_image() -> None:- """验证 HTML 占位网格非法时使用表格图片,不留下损坏表格。"""- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content="<table><tr><td rowspan='2'>A</td></tr></table>",- image_base64=_png_uri(),- )- ],- )-- result = render_docx(_middle(_page(0, table)))- document = Document(BytesIO(result))-- assert len(document.tables) == 0- assert len(document.inline_shapes) == 1-- without_fallback = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content="<table><tr><td rowspan='2'>A</td></tr></table>",- )- ],- )- with pytest.raises(DocxRenderError, match="no image fallback"):- render_docx(_middle(_page(0, without_fallback)))--- "image_payload",- [- pytest.param({}, id="without-image"),- pytest.param({"image_base64": _png_uri()}, id="base64-image"),- pytest.param({"image_path": "images/table.png"}, id="sidecar-image"),- ],-)-def test_spatial_table_preserves_preformatted_text_without_assets(image_payload: dict[str, str]) -> None:- """验证空间表格原样保留排版字符,并完全忽略可选图片素材。"""- content = " A B\t说明\n\n1 2\t中\x01文\n" + "X" * 240- spatial = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=content,- **image_payload,- )- ],- )- resolver = Mock(side_effect=AssertionError("空间表格不应解析图片"))-- result = render_docx(_middle(_page(0, spatial)), asset_resolver=resolver)- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")- relationships = _part(result, "word/_rels/document.xml.rels")-- resolver.assert_not_called()- assert document.paragraphs[0].text == content.replace("\x01", "\ufffd")- assert document.paragraphs[0].style.name == "DocVortex Spatial Table"- assert document.styles["DocVortex Spatial Table"].font.name == document.styles["DocVortex Code"].font.name- assert document.styles["DocVortex Spatial Table"].font.size == document.styles["DocVortex Code"].font.size- assert document.styles["DocVortex Spatial Table"].paragraph_format.line_spacing == 1.0- assert 'w:pStyle w:val="DocVortexSpatialTable"' in document_xml- assert 'xml:space="preserve"' in document_xml- assert "<w:tab/>" in document_xml- assert document_xml.count("<w:br/>") == 3- assert len(document.inline_shapes) == 0- assert "relationships/image" not in relationships- with zipfile.ZipFile(BytesIO(result)) as archive:- assert not any(name.startswith("word/media/") for name in archive.namelist())--[email protected]("content", ["", " \n\t"])-def test_spatial_table_without_text_uses_preferred_sidecar_image(content: str) -> None:- """验证空或纯空白空间表格遵循 image_path 优先的公共图片契约。"""- spatial = TableBlock(- type="table",- index=7,- content=[- TableBodyBlock(- type="table_body",- index=7,- content=content,- image_base64=_png_uri(),- image_path="images/unused.png",- )- ],- )- resolver = Mock(return_value=_png_bytes(size=(16, 10)))-- document = Document(BytesIO(render_docx(_middle(_page(3, spatial)), asset_resolver=resolver)))-- resolver.assert_called_once_with("images/unused.png")- assert len(document.inline_shapes) == 1---def test_spatial_table_without_text_uses_sidecar_resolver() -> None:- """验证空空间表格的相对图片路径只通过注入的 resolver 加载。"""- spatial = TableBlock(- type="table",- index=7,- content=[- TableBodyBlock(- type="table_body",- index=7,- content="",- image_path="images/table.png",- )- ],- )- resolver = Mock(return_value=_png_bytes())-- document = Document(BytesIO(render_docx(_middle(_page(3, spatial)), asset_resolver=resolver)))-- resolver.assert_called_once_with("images/table.png")- assert len(document.inline_shapes) == 1---def test_remote_only_equation_table_and_chart_use_docx_link_fallbacks() -> None:- """验证所有远程-only 图片载荷都会进入 DOCX 可点击链接回退。"""- middle = _middle(- _page(- 0,- EquationBlock(- type="equation",- index=0,- content="",- image_url="https://example.com/formula.png",- ),- TableBlock(- type="table",- index=1,- content=[- TableBodyBlock(- type="table_body",- index=1,- content="",- image_url="https://example.com/table.png",- )- ],- ),- ChartBlock(- type="chart",- index=2,- sub_type="bar",- content=[- ChartBodyBlock(- type="chart_body",- index=2,- content="",- image_url="https://example.com/chart.png",- )- ],- ),- )- )-- result = render_docx(middle)- document = Document(BytesIO(result))- relationships = _part(result, "word/_rels/document.xml.rels")-- assert [paragraph.text for paragraph in document.paragraphs] == ["formula", "table", "bar"]- assert all(- target in relationships- for target in (- "https://example.com/formula.png",- "https://example.com/table.png",- "https://example.com/chart.png",- )- )--[email protected]("content", ["", " \n\t"])-def test_spatial_table_without_text_or_image_raises_contextual_error(content: str) -> None:- """验证空间表格既无有效文本也无图片时抛出带父表格定位的异常。"""- spatial = TableBlock(- type="table",- index=7,- content=[TableBodyBlock(type="table_body", index=7, content=content)],- )-- with pytest.raises(DocxRenderError, match="does not contain text content or image") as exc_info:- render_docx(_middle(_page(3, spatial)))-- assert exc_info.value.page_idx == 3- assert exc_info.value.block_index == 7- assert exc_info.value.block_type == "table"---def test_spatial_table_without_text_rejects_invalid_fallback_image() -> None:- """验证空空间表格的损坏图片不会被静默忽略。"""- spatial = TableBlock(- type="table",- index=7,- content=[- TableBodyBlock(- type="table_body",- index=7,- content="",- image_base64="data:image/png;base64,bm90LWEtcG5n",- )- ],- )-- with pytest.raises(DocxRenderError) as exc_info:- render_docx(_middle(_page(3, spatial)))-- assert exc_info.value.page_idx == 3- assert exc_info.value.block_index == 7- assert exc_info.value.block_type == "table"---def test_spatial_table_preserves_caption_body_footnote_order() -> None:- """验证空间表格正文仍严格位于原始 caption 与 footnote 之间。"""- spatial = TableBlock(- type="table",- index=1,- content=[- TableAnnotationBlock(type="table_caption", index=0, content=_inline("Table caption")),- TableBodyBlock(type="table_body", index=1, content=" A B\n 1 2"),- TableAnnotationBlock(type="table_footnote", index=2, content=_inline("Table footnote")),- ],- )-- document = Document(BytesIO(render_docx(_middle(_page(0, spatial)))))-- assert [paragraph.text for paragraph in document.paragraphs] == [- "Table caption",- " A B\n 1 2",- "Table footnote",- ]- assert [paragraph.style.name for paragraph in document.paragraphs] == [- "DocVortex Caption",- "DocVortex Spatial Table",- "DocVortex Footnote",- ]---def test_chart_renders_image_then_structured_html_table() -> None:- """验证图表图片后继续输出可编辑的 HTML 数据表。"""- chart = ChartBlock(- type="chart",- index=0,- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",- image_base64=_png_uri(),- )- ],- )-- result = render_docx(_middle(_page(0, chart)))- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")-- assert len(document.inline_shapes) == 1- assert len(document.tables) == 1- assert document_xml.index("<a:blip") < document_xml.index("<w:tbl>")---def test_chart_invalid_html_keeps_successful_image_fallback() -> None:- """验证图表结构表损坏时保留已成功写入的图片,而不是终止文档。"""- chart = ChartBlock(- type="chart",- index=0,- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="<table><tr><td rowspan='2'>broken</td></tr></table>",- image_base64=_png_uri(),- )- ],- )-- document = Document(BytesIO(render_docx(_middle(_page(0, chart)))))-- assert len(document.inline_shapes) == 1- assert len(document.tables) == 0---def test_code_and_algorithm_keep_line_breaks_styles_and_inline_math() -> None:- """验证代码换行与算法行内公式、上下标均保留。"""- code = CodeBlock.model_validate(- {- "type": "code",- "index": 0,- "sub_type": "code",- "guess_lang": "python",- "content": [{"type": "code_body", "index": 0, "content": "a = 1\nb = 2"}],- }- )- algorithm = CodeBlock.model_validate(- {- "type": "code",- "index": 1,- "sub_type": "algorithm",- "content": [- {- "type": "algorithm_body",- "index": 1,- "content": [- {"type": "text", "content": "T"},- {"type": "text", "content": "n", "styles": ["subscript"]},- {"type": "text", "content": " = "},- {"type": "equation_inline", "content": "x^2"},- {"type": "text", "content": "\nnext"},- ],- }- ],- }- )-- result = render_docx(_middle(_page(0, code, algorithm)))- document = Document(BytesIO(result))- document_xml = _part(result, "word/document.xml")-- assert [paragraph.style.name for paragraph in document.paragraphs] == ["DocVortex Code", "DocVortex Code"]- assert "a = 1\nb = 2" == document.paragraphs[0].text- assert "<m:oMath" in document_xml- assert 'w:vertAlign w:val="subscript"' in document_xmldiff --git a/tests/unittest/test_docx_special_char_tables.py b/tests/unittest/test_docx_special_char_tables.pydeleted file mode 100644index 8de732ec..00000000--- a/tests/unittest/test_docx_special_char_tables.py+++ /dev/null@@ -1,210 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from io import BytesIO--from docx import Document-from docx.oxml.ns import qn-from lxml import etree--from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter---NO_BREAK_HYPHEN = "‑"-SOFT_HYPHEN = ""---def _save_docx_bytes(doc: Document) -> bytes:- """将内存中的 DOCX 文档序列化为字节。"""- buffer = BytesIO()- doc.save(buffer)- return buffer.getvalue()---def _convert_docx_bytes(file_bytes: bytes) -> list[dict]:- """调用当前 Flash DOCX Converter 并拉平分页块。"""- converter = DocxConverter()- converter.convert(BytesIO(file_bytes))- return [block for page in converter.pages for block in page]---def _table_blocks(blocks: list[dict]) -> list[dict]:- """从拉平块列表中筛选表格块。"""- return [block for block in blocks if block["type"] == "table"]---def _build_docx_with_no_break_hyphen_table() -> bytes:- """构造同时含不间断连字符和编号列表的整表丢失用例。"""- doc = Document()- doc.add_heading("1 项目概述", level=1)-- table = doc.add_table(rows=2, cols=2)- paragraph = table.cell(0, 0).paragraphs[0]- run = paragraph.add_run("NCI")- etree.SubElement(run._r, qn("w:noBreakHyphen"))- paragraph.add_run("CTCAE 标准")- numbered = table.cell(0, 1).paragraphs[0]- numbered.style = doc.styles["List Number"]- numbered.add_run("第一条编号内容")-- doc.add_heading("2 进度安排", level=1)- plain = doc.add_table(rows=1, cols=2)- plain.cell(0, 0).paragraphs[0].add_run("里程碑")- plain.cell(0, 1).paragraphs[0].add_run("2026-08-01")- return _save_docx_bytes(doc)---def _build_docx_with_sym_table(*, char: str) -> bytes:- """构造同时含 Symbol 字符和编号列表的表格。"""- doc = Document()- doc.add_heading("符号表格", level=1)- table = doc.add_table(rows=1, cols=2)- paragraph = table.cell(0, 0).paragraphs[0]- run = paragraph.add_run("符号")- etree.SubElement(- run._r,- qn("w:sym"),- {qn("w:char"): char, qn("w:font"): "Symbol"},- )- paragraph.add_run("结束")- numbered = table.cell(0, 1).paragraphs[0]- numbered.style = doc.styles["List Number"]- numbered.add_run("编号项")- return _save_docx_bytes(doc)---def _build_plain_docx_table() -> bytes:- """构造不含特殊字符的普通表格对照组。"""- doc = Document()- table = doc.add_table(rows=1, cols=2)- table.cell(0, 0).paragraphs[0].add_run("APTT")- table.cell(0, 1).paragraphs[0].add_run("部分凝血酶时间")- return _save_docx_bytes(doc)---def _build_nested_merged_docx_table() -> bytes:- """构造含嵌套行、纵向合并和编号样式的完整上下文表格。"""- doc = Document()- table = doc.add_table(rows=2, cols=2)- merged = table.cell(0, 0).merge(table.cell(1, 0))- merged.paragraphs[0].add_run("纵向合并")- nested = table.cell(0, 1).add_table(rows=2, cols=1)- nested.cell(0, 0).paragraphs[0].add_run("嵌套首行")- numbered = nested.cell(1, 0).paragraphs[0]- numbered.style = doc.styles["List Number"]- numbered.add_run("嵌套编号行")- table.cell(1, 1).paragraphs[0].add_run("外层尾行")- return _save_docx_bytes(doc)---def test_no_break_hyphen_table_not_lost() -> None:- """验证不间断连字符与编号列表并存时整表不会丢失。"""- tables = _table_blocks(_convert_docx_bytes(_build_docx_with_no_break_hyphen_table()))-- assert len(tables) == 2- assert f"NCI{NO_BREAK_HYPHEN}CTCAE" in tables[0]["content"]- assert "<li>" in tables[0]["content"]- assert "第一条编号内容" in tables[0]["content"]- assert "里程碑" in tables[1]["content"]---def test_mapped_sym_table_takes_mammoth_path() -> None:- """验证普通 Symbol 映射字符与 Mammoth 表格签名保持一致。"""- tables = _table_blocks(_convert_docx_bytes(_build_docx_with_sym_table(char="0022")))-- assert len(tables) == 1- assert "∀" in tables[0]["content"]- assert "<li>" in tables[0]["content"]---def test_f0_sym_table_takes_low_byte_fallback() -> None:- """验证 F0 前缀 Symbol 字符按 Mammoth 规则使用低字节回退映射。"""- tables = _table_blocks(_convert_docx_bytes(_build_docx_with_sym_table(char="F0B7")))-- assert len(tables) == 1- assert "•" in tables[0]["content"]- assert "<li>" in tables[0]["content"]---def test_plain_table_still_emitted() -> None:- """验证特殊字符签名修复不影响普通表格。"""- tables = _table_blocks(_convert_docx_bytes(_build_plain_docx_table()))-- assert len(tables) == 1- assert "APTT" in tables[0]["content"]---def test_nested_merged_table_uses_recursive_row_signature_and_full_context() -> None:- """验证 XML/HTML 递归行数对齐后不会进入缺少编号上下文的孤立回退。"""- file_bytes = _build_nested_merged_docx_table()- converter = DocxConverter()- preparsed = converter._preparse_tables_with_mammoth(file_bytes)-- assert len(preparsed) == 1- assert preparsed[0] is not None- tables = _table_blocks(_convert_docx_bytes(file_bytes))- assert len(tables) == 1- assert "纵向合并" in tables[0]["content"]- assert "嵌套首行" in tables[0]["content"]- assert "嵌套编号行" in tables[0]["content"]- assert "外层尾行" in tables[0]["content"]---def test_xml_table_signature_renders_special_chars() -> None:- """验证 XML 签名保留不间断连字符和软连字符。"""- doc = Document()- table = doc.add_table(rows=1, cols=2)- paragraph = table.cell(0, 0).paragraphs[0]- run = paragraph.add_run("NCI")- etree.SubElement(run._r, qn("w:noBreakHyphen"))- paragraph.add_run("CTCAE")- second_paragraph = table.cell(0, 1).paragraphs[0]- second_run = second_paragraph.add_run("软连")- etree.SubElement(second_run._r, qn("w:softHyphen"))- second_paragraph.add_run("字符")-- signature = DocxConverter._xml_table_signature(table._tbl)-- assert f"NCI{NO_BREAK_HYPHEN}CTCAE" in signature["text"]- assert f"软连{SOFT_HYPHEN}字符" in signature["text"]---def test_xml_table_signature_renders_sym_like_mammoth() -> None:- """验证已映射 Symbol 输出字符,真正未映射 Symbol 输出空字符串。"""- doc = Document()- table = doc.add_table(rows=1, cols=2)- paragraph = table.cell(0, 0).paragraphs[0]- run = paragraph.add_run("映射")- etree.SubElement(- run._r,- qn("w:sym"),- {qn("w:char"): "0022", qn("w:font"): "Symbol"},- )- paragraph.add_run("结束")- second_paragraph = table.cell(0, 1).paragraphs[0]- second_run = second_paragraph.add_run("未映射")- etree.SubElement(- second_run._r,- qn("w:sym"),- {qn("w:char"): "F0B7", qn("w:font"): "UnknownFont"},- )- second_paragraph.add_run("结束")-- signature = DocxConverter._xml_table_signature(table._tbl)-- assert signature["text"] == "映射∀结束未映射结束"---def test_xml_table_signature_excludes_omml_equation_text() -> None:- """验证 Mammoth 不渲染的 OMML 公式文本不参与表格签名。"""- doc = Document()- table = doc.add_table(rows=1, cols=2)- paragraph = table.cell(0, 0).paragraphs[0]- run = paragraph.add_run("正文")- equation = etree.SubElement(run._r, qn("m:oMath"))- equation_run = etree.SubElement(equation, qn("m:r"))- etree.SubElement(equation_run, qn("m:t")).text = "E=mc2"- table.cell(0, 1).paragraphs[0].add_run("单元格")-- signature = DocxConverter._xml_table_signature(table._tbl)-- assert "正文" in signature["text"]- assert "E=mc2" not in signature["text"]diff --git a/tests/unittest/test_docx_table.py b/tests/unittest/test_docx_table.pydeleted file mode 100644index a92cb028..00000000--- a/tests/unittest/test_docx_table.py+++ /dev/null@@ -1,250 +0,0 @@-from __future__ import annotations--from collections.abc import Callable--import pytest-from bs4.element import Tag-from docx import Document-from docx.oxml.ns import qn-from docx.table import _Cell--from docvortex.render._internal.docx.table import DocxTableError-from docvortex.render._internal.docx.table import NestedTableWriter-from docvortex.render._internal.docx.table import materialize_docx_table-from docvortex.render._internal.docx.table import materialize_docx_tables-from docvortex.render._internal.docx.table import parse_html_table-from docvortex.render._internal.docx.table import parse_html_tables---def _text_filler(- observed: list[tuple[str, str]],-) -> Callable[[_Cell, Tag, NestedTableWriter], None]:- """构造记录原始 Tag 并把直接文本写入 Word 单元格的测试回调。"""-- def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:- """记录回调来源,并忽略本用例不涉及的嵌套写入器。"""- del write_nested- observed.append((source.name, source.get_text(" ", strip=True)))- cell.paragraphs[0].add_run(source.get_text(" ", strip=True))-- return fill_cell---def _xml_value(element: object, attribute: str) -> str | None:- """读取测试 XML 元素中的 WordprocessingML 属性。"""- return element.get(qn(attribute)) # type: ignore[union-attr]---def test_parse_and_materialize_simple_table_with_header_tags() -> None:- """验证简单表格、th 回调、Table Grid 和重复表头标记。"""- html = (- '<table><thead><tr><th data-id="h1">Name</th><th data-id="h2">Value</th></tr></thead>'- '<tbody><tr><td data-id="c1">A</td><td data-id="c2">1</td></tr></tbody></table>'- )- grid = parse_html_tables(html)[0]-- assert (grid.row_count, grid.column_count) == (2, 2)- assert grid.header_rows == (0,)- assert [(cell.row, cell.column, cell.is_header) for cell in grid.cells] == [- (0, 0, True),- (0, 1, True),- (1, 0, False),- (1, 1, False),- ]-- document = Document()- observed: list[tuple[str, str]] = []- table = materialize_docx_table(- document,- grid,- width_twips=6000,- fill_cell=_text_filler(observed),- )-- assert observed == [("th", "Name"), ("th", "Value"), ("td", "A"), ("td", "1")]- assert table.style.name == "Table Grid"- assert table.cell(0, 0).text == "Name"- assert table.cell(1, 1).text == "1"- assert len(table.rows[0]._tr.xpath("./w:trPr/w:tblHeader")) == 1---def test_materialize_rowspan_and_colspan_as_gridspan_and_vmerge() -> None:- """验证二维合并写出一致的 gridSpan、vMerge 和 origin 回调。"""- html = '<table><tr><th rowspan="2" colspan="2">A</th><th>B</th></tr><tr><td>C</td></tr></table>'- document = Document()- observed: list[tuple[str, str]] = []-- table = materialize_docx_tables(- document,- html,- width_twips=6000,- fill_cell=_text_filler(observed),- )[0]-- assert observed == [("th", "A"), ("th", "B"), ("td", "C")]- first_row_cells = table._tbl.tr_lst[0].tc_lst- second_row_cells = table._tbl.tr_lst[1].tc_lst- assert _xml_value(first_row_cells[0].tcPr.gridSpan, "w:val") == "2"- assert _xml_value(first_row_cells[0].tcPr.vMerge, "w:val") == "restart"- assert _xml_value(second_row_cells[0].tcPr.gridSpan, "w:val") == "2"- assert _xml_value(second_row_cells[0].tcPr.vMerge, "w:val") is None- assert first_row_cells[0].tcPr.tcW.w == 4000- assert second_row_cells[0].tcPr.tcW.w == 4000---def test_parse_and_materialize_multiple_top_level_tables() -> None:- """验证同一 HTML 片段中的多个顶层表格按源码顺序独立创建。"""- html = '<table data-id="one"><tr><td>A</td></tr></table><div><table data-id="two"><tr><td>B</td></tr></table></div>'- grids = parse_html_tables(html)- assert [grid.tag.get("data-id") for grid in grids] == ["one", "two"]-- document = Document()- observed: list[tuple[str, str]] = []- tables = materialize_docx_tables(document, html, fill_cell=_text_filler(observed))-- assert len(tables) == 2- assert len(document.tables) == 2- assert [table.cell(0, 0).text for table in tables] == ["A", "B"]--- "html",- [- "<table></table>",- "<table><tr></tr></table>",- ],-)-def test_parse_rejects_table_without_cells(html: str) -> None:- """验证无行或无任何单元格的表格被安全拒绝。"""- with pytest.raises(DocxTableError):- parse_html_tables(html)--- ("attribute", "value"),- [- ("rowspan", "0"),- ("rowspan", "-1"),- ("rowspan", "1.5"),- ("rowspan", "x"),- ("colspan", "0"),- ("colspan", ""),- ],-)-def test_parse_rejects_invalid_spans(attribute: str, value: str) -> None:- """验证 rowspan/colspan 只接受严格正整数。"""- html = f'<table><tr><td {attribute}="{value}">A</td></tr></table>'-- with pytest.raises(DocxTableError, match=f"Invalid {attribute}"):- parse_html_tables(html)---def test_parse_rejects_rowspan_out_of_bounds() -> None:- """验证跨出最后一行的 rowspan 被判定为越界。"""- with pytest.raises(DocxTableError, match="rowspan exceeds table bounds"):- parse_html_tables('<table><tr><td rowspan="2">A</td></tr></table>')---def test_parse_rejects_span_overlap_after_skipping_occupied_coordinate() -> None:- """验证跳过行首占位后,colspan 仍不得覆盖后方 rowspan 占位。"""- html = '<table><tr><td rowspan="2">A</td><td>B</td><td rowspan="2">C</td></tr><tr><td colspan="2">D</td></tr></table>'-- with pytest.raises(DocxTableError, match="overlaps an occupied coordinate"):- parse_html_tables(html)---def test_parse_rejects_non_rectangular_occupancy() -> None:- """验证逻辑行宽不一致且没有 rowspan 补位时拒绝非矩形表格。"""- html = "<table><tr><td>A</td><td>B</td></tr><tr><td>C</td></tr></table>"-- with pytest.raises(DocxTableError, match="occupancy must be rectangular"):- parse_html_tables(html)---def test_materialized_geometry_uses_exact_dxa_widths_without_fixed_row_height() -> None:- """验证 tblW、tblGrid、每行 tcW 的总宽完全一致且不存在固定行高。"""- html = '<table><tr><td colspan="2">A</td><td>B</td></tr><tr><td>C</td><td>D</td><td>E</td></tr></table>'- document = Document()- table = materialize_docx_tables(- document,- html,- width_twips=10001,- fill_cell=_text_filler([]),- )[0]-- table_width = table._tbl.tblPr.find(qn("w:tblW"))- table_layout = table._tbl.tblPr.find(qn("w:tblLayout"))- assert table_width is not None- assert (_xml_value(table_width, "w:type"), _xml_value(table_width, "w:w")) == (- "dxa",- "10001",- )- assert table_layout is not None- assert _xml_value(table_layout, "w:type") == "fixed"-- grid_widths = [column.w.twips for column in table._tbl.tblGrid.gridCol_lst]- assert grid_widths == [3334, 3334, 3333]- for row in table._tbl.tr_lst:- assert sum(cell.tcPr.tcW.w for cell in row.tc_lst) == 10001- assert row.xpath("./w:trPr/w:trHeight") == []---def test_callback_can_materialize_four_nested_table_levels() -> None:- """验证回调可使用绑定写入器递归创建最多四层嵌套表格。"""- html = _nested_table_html(4)- document = Document()- seen_levels: list[str] = []-- def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:- """记录当前层级,并递归写入当前单元格中的直接子表。"""- parent_table = source.find_parent("table")- assert parent_table is not None- seen_levels.append(str(parent_table.get("data-level")))- for nested in source.find_all("table"):- if nested.find_parent("table") is parent_table:- write_nested(nested)- cell.paragraphs[0].add_run(f"L{parent_table.get('data-level')}")-- materialize_docx_tables(document, html, width_twips=6000, fill_cell=fill_cell)-- assert seen_levels == ["1", "2", "3", "4"]- assert len(document.element.body.xpath(".//w:tbl")) == 4---def test_callback_rejects_fifth_nested_table_level() -> None:- """验证第五层嵌套表格在回调尝试写入时抛出明确错误。"""- document = Document()-- def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:- """只递归写入直接子表,以触发统一深度保护。"""- del cell- parent_table = source.find_parent("table")- assert parent_table is not None- for nested in source.find_all("table"):- if nested.find_parent("table") is parent_table:- write_nested(nested)-- with pytest.raises(DocxTableError, match="depth exceeds 4"):- materialize_docx_tables(- document,- _nested_table_html(5),- width_twips=6000,- fill_cell=fill_cell,- )---def test_parse_single_tag_preserves_the_original_cell_tag_objects() -> None:- """验证中性解析器保留调用方提供的原始 td/th Tag,而不是复制文本。"""- soup_grid = parse_html_tables('<table><tr><th data-key="a">A</th><td data-key="b">B</td></tr></table>')[0]- table_tag = soup_grid.tag- parsed_again = parse_html_table(table_tag)- source_cells = table_tag.find_all(("th", "td"), recursive=True)-- assert [cell.tag is source for cell, source in zip(parsed_again.cells, source_cells)] == [True, True]- assert [cell.tag.get("data-key") for cell in parsed_again.cells] == ["a", "b"]---def _nested_table_html(depth: int, level: int = 1) -> str:- """生成指定总层数的单单元格嵌套表格 HTML。"""- nested = _nested_table_html(depth - 1, level + 1) if depth > 1 else ""- return f'<table data-level="{level}"><tr><td>{nested}</td></tr></table>'diff --git a/tests/unittest/test_emfplus_integration.py b/tests/unittest/test_emfplus_integration.pydeleted file mode 100644index 06e1c475..00000000--- a/tests/unittest/test_emfplus_integration.py+++ /dev/null@@ -1,55 +0,0 @@-"""验证 metafile-render 0.3 的 Only 图片经 Office 解析与四种消费者输出。"""--from __future__ import annotations--from io import BytesIO-from pathlib import Path-from unittest.mock import Mock-from zipfile import ZipFile--import pytest-from _office_image_mtef_test_utils import build_image_docx-from PIL import Image-from pypdf import PdfReader--from mineru.backend.analyze import doc_analyze-from docvortex.analyzers.native.office import image as office_image-from mineru.render import render_docx, render_epub, render_html, render_pdf--_FIXTURES = Path(__file__).parent / "fixtures" / "emfplus"--[email protected]("scene", ["geometry", "fallback"])-def test_only_docx_flows_into_html_docx_pdf_epub(scene: str, monkeypatch: pytest.MonkeyPatch) -> None:- """真实 Only 图片经 DOCX 解析进入全部消费端,安全 SVG 仍可提取 PNG fallback。"""- package = build_image_docx((_FIXTURES / f"{scene}-only.emf").read_bytes())- middle, _ = doc_analyze(package, effort="flash", image_analysis=False, file_suffix="docx")- html = render_html(middle)- assert "data:image/svg+xml;base64," in html- for payload in (render_docx(middle), render_epub(middle)):- with ZipFile(BytesIO(payload)) as archive:- images = [archive.read(name) for name in archive.namelist() if name.endswith(".png")]- assert images- with Image.open(BytesIO(images[0])) as image:- assert image.width > 100 and image.height > 100- assert image.convert("RGB").getextrema() != ((255, 255), (255, 255), (255, 255))- pdf = PdfReader(BytesIO(render_pdf(middle)))- assert pdf.pages- assert any(page.images for page in pdf.pages)---def test_only_partial_reports_diagnostics_and_keeps_image(monkeypatch: pytest.MonkeyPatch) -> None:- """样式近似的 Only 仍输出 SVG,并把部分结果诊断交给 Office 日志。"""- warning = Mock()- monkeypatch.setattr(office_image.logger, "warning", warning)- result = office_image.serialize_office_image((_FIXTURES / "fallback-only.emf").read_bytes())- assert result is not None and result.startswith("data:image/svg+xml;base64,")- assert any(- "Rendered partial EMF" in str(call) and "emfplus_brush_approximation" in str(call) for call in warning.call_args_list- )---def test_broken_only_uses_existing_placeholder(monkeypatch: pytest.MonkeyPatch) -> None:- """签名有效但损坏的 Only 文件沿用原有失败兜底。"""- data = (_FIXTURES / "geometry-only.emf").read_bytes()[:48]- assert office_image.serialize_office_image(data) == office_image.get_standard_vector_placeholder_data_uri()diff --git a/tests/unittest/test_epub_render.py b/tests/unittest/test_epub_render.pydeleted file mode 100644index aebde1bd..00000000--- a/tests/unittest/test_epub_render.py+++ /dev/null@@ -1,617 +0,0 @@-from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata--import base64-from copy import deepcopy-from datetime import datetime, timezone-from io import BytesIO-from unittest.mock import MagicMock-from zipfile import ZIP_STORED, ZipFile--from lxml import etree-from PIL import Image-import pytest--from mineru.backend.analyze import doc_analyze-from docvortex.analyzers.native.epub import EpubPackage-from mineru.render import render_epub-from docvortex.render._internal.epub import assets as epub_assets-from mineru.types import (- AlgorithmBodyBlock,- ChartBlock,- ChartBodyBlock,- CodeBlock,- CodeBodyBlock,- DocTitleBlock,- EquationBlock,- ImageBlock,- ImageBodyBlock,- IndexBlock,- MiddleJson,- PageAuxTextBlock,- PageBlock,- PageFootnoteBlock,- PageInfo,- ParagraphTitleBlock,- TableBlock,- TableBodyBlock,- TextBlock,-)-from docvortex.foundation.image_payload import MAX_DECODED_RASTER_DIMENSION-from docvortex.foundation.image_payload import MAX_DECODED_RASTER_PIXELS-from docvortex.foundation.image_payload import validate_decoded_raster_size-from docvortex.foundation import image_payload as image_payload_utils--from _epub_test_utils import build_epub_fixture-from _span_test_utils import equation, hyperlink, inline--_FIXED_TIME = datetime(2026, 1, 2, 3, 4, 6, tzinfo=timezone.utc)-_PNG_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="-_PNG_BYTES = base64.b64decode(_PNG_URI.split(",", 1)[1])-_NS = {- "container": "urn:oasis:names:tc:opendocument:xmlns:container",- "dc": "http://purl.org/dc/elements/1.1/",- "epub": "http://www.idpf.org/2007/ops",- "math": "http://www.w3.org/1998/Math/MathML",- "opf": "http://www.idpf.org/2007/opf",- "xhtml": "http://www.w3.org/1999/xhtml",-}---def _middle(*pages: PageInfo) -> MiddleJson:- """构造无需固定版式 bbox 的测试 MiddleJson。"""- return MiddleJson(- pages=list(pages),- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:- """按调用方顺序构造一页测试内容。"""- return PageInfo(page_idx=page_idx, blocks=list(blocks))---def _archive(payload: bytes) -> ZipFile:- """从内存字节打开 EPUB ZIP,供测试读取成员。"""- return ZipFile(BytesIO(payload))---def _xml(archive: ZipFile, name: str) -> etree._Element:- """使用禁用网络和实体的 parser 读取 EPUB XML 成员。"""- parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True, recover=False)- return etree.fromstring(archive.read(name), parser=parser)---def _text(element: etree._Element) -> str:- """合并 XML 节点全部可见文本,便于断言。"""- return "".join(element.itertext())---def test_epub_package_is_single_spine_epub33_with_stable_metadata_and_mathml() -> None:- """验证 OCF、必需元数据、单正文 spine、导航和确定性输出。"""- middle = _middle(- _page(- 0,- DocTitleBlock(type="doc_title", index=0, level=1, anchor="chapter-one", content=inline("Book Title")),- TextBlock(- type="text",- index=1,- content=[*inline("Inline "), equation("x^2"), *inline(" and text")],- ),- EquationBlock(type="equation", index=2, content=r"\frac{a}{b}"),- )- )-- first = render_epub(- middle,- authors=("Alice", "Bob"),- language="en-US",- modified_at=_FIXED_TIME,- )- second = render_epub(- middle,- authors=("Alice", "Bob"),- language="en-US",- modified_at=_FIXED_TIME,- )- assert first == second- later = render_epub(- middle,- authors=("Alice", "Bob"),- language="en-US",- modified_at=datetime(2027, 2, 3, tzinfo=timezone.utc),- )-- with _archive(first) as archive:- members = archive.infolist()- assert members[0].filename == "mimetype"- assert members[0].compress_type == ZIP_STORED- assert members[0].extra == b""- assert archive.read("mimetype") == b"application/epub+zip"- assert [item.filename for item in members if item.filename.endswith(".xhtml")] == [- "EPUB/nav.xhtml",- "EPUB/text/content.xhtml",- ]-- container = _xml(archive, "META-INF/container.xml")- assert (- container.xpath("string(container:rootfiles/container:rootfile/@full-path)", namespaces=_NS) == "EPUB/package.opf"- )-- package = _xml(archive, "EPUB/package.opf")- assert package.xpath("string(opf:metadata/dc:title)", namespaces=_NS) == "Book Title"- assert package.xpath("string(opf:metadata/dc:language)", namespaces=_NS) == "en-US"- assert package.xpath("opf:metadata/dc:creator/text()", namespaces=_NS) == ["Alice", "Bob"]- assert package.xpath("string(opf:metadata/opf:meta[@property='dcterms:modified'])", namespaces=_NS) == (- "2026-01-02T03:04:06Z"- )- assert package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS).startswith("urn:uuid:")- assert package.xpath("count(opf:spine/opf:itemref)", namespaces=_NS) == 1.0- assert package.xpath("string(opf:manifest/opf:item[@id='content']/@properties)", namespaces=_NS) == "mathml"-- navigation = _xml(archive, "EPUB/nav.xhtml")- assert navigation.xpath("count(xhtml:body/xhtml:nav[@epub:type='toc'])", namespaces=_NS) == 1.0- assert navigation.xpath("string(//xhtml:nav[@epub:type='toc']//xhtml:a/@href)", namespaces=_NS) == (- "text/content.xhtml#chapter-one"- )- content = _xml(archive, "EPUB/text/content.xhtml")- assert content.xpath("count(//math:math)", namespaces=_NS) == 2.0- assert not content.xpath("//xhtml:script", namespaces=_NS)- with _archive(later) as archive:- later_package = _xml(archive, "EPUB/package.opf")- later_identifier = later_package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS)- with _archive(first) as archive:- first_package = _xml(archive, "EPUB/package.opf")- first_identifier = first_package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS)- assert later_identifier == first_identifier---def test_epub_table_preserves_standard_inline_style_tags() -> None:- """验证表格中的标准文字样式标签安全复制为 XHTML。"""- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=(- "<table><tr><td><strong>bold</strong><em>italic</em><u>under</u>"- "<s>strike</s><sup>sup</sup><sub>sub</sub></td></tr></table>"- ),- )- ],- )-- with _archive(render_epub(_middle(_page(0, table)), modified_at=_FIXED_TIME)) as archive:- content = _xml(archive, "EPUB/text/content.xhtml")-- assert [- content.xpath(f"string(//xhtml:td/xhtml:{tag})", namespaces=_NS) for tag in ("strong", "em", "u", "s", "sup", "sub")- ] == [- "bold",- "italic",- "under",- "strike",- "sup",- "sub",- ]---def test_epub_uses_default_planner_without_source_page_boundaries() -> None:- """验证固定默认 EPUB 连续阅读、隐藏辅助块且不保留源页边界。"""- middle = _middle(- _page(- 0,- PageAuxTextBlock(type="header", index=0, content=inline("HEADER")),- TextBlock(type="text", index=1, content=inline("inter-")),- ),- _page(5),- _page(- 9,- TextBlock(type="text", index=0, content=inline("national"), continues_prev=True),- PageAuxTextBlock(type="footer", index=1, content=inline("FOOTER")),- ),- )- original = deepcopy(middle)-- payload = render_epub(middle, modified_at=_FIXED_TIME)-- with _archive(payload) as archive:- content = _xml(archive, "EPUB/text/content.xhtml")- paragraphs = content.xpath("//xhtml:p[contains(@class, 'docvortex-text')]", namespaces=_NS)- assert [_text(item) for item in paragraphs] == ["international"]- assert content.xpath("string(//xhtml:article/@class)", namespaces=_NS) == "docvortex-document"- assert not content.xpath("//xhtml:section[contains(@class, 'docvortex-page')]", namespaces=_NS)- assert not content.xpath("//xhtml:hr[contains(@class, 'docvortex-page-break')]", namespaces=_NS)- assert "HEADER" not in _text(content) and "FOOTER" not in _text(content)- with pytest.raises(TypeError, match="unexpected keyword argument 'mode'"):- render_epub(middle, mode="default") # type: ignore[call-arg]- assert middle == original---def test_epub_navigation_prefers_valid_index_then_falls_back_to_heading_hierarchy() -> None:- """验证源目录优先、无效项过滤和标题层级回退。"""- source_index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(type="paragraph_title", level=2, anchor="a", content=inline("Source A\t1")),- IndexBlock(- type="index",- content=[- ParagraphTitleBlock(type="paragraph_title", level=3, anchor="b", content=inline("Source B\t2")),- ParagraphTitleBlock(type="paragraph_title", level=3, anchor="missing", content=inline("Missing")),- ],- ),- ],- )- indexed = _middle(- _page(- 0,- source_index,- ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="a", content=inline("Heading A")),- ParagraphTitleBlock(type="paragraph_title", index=2, level=3, anchor="b", content=inline("Heading B")),- )- )- with _archive(render_epub(indexed, modified_at=_FIXED_TIME)) as archive:- navigation = _xml(archive, "EPUB/nav.xhtml")- toc = navigation.xpath("//xhtml:nav[@epub:type='toc']", namespaces=_NS)[0]- assert toc.xpath(".//xhtml:a/text()", namespaces=_NS) == ["Source A", "Source B"]- assert toc.xpath(".//xhtml:a/@href", namespaces=_NS) == [- "text/content.xhtml#a",- "text/content.xhtml#b",- ]- assert toc.xpath("count(./xhtml:ol/xhtml:li/xhtml:ol/xhtml:li)", namespaces=_NS) == 1.0-- fallback = _middle(- _page(- 0,- ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="same", content=inline("First")),- ParagraphTitleBlock(type="paragraph_title", index=1, level=4, anchor="child", content=inline("Child")),- ParagraphTitleBlock(type="paragraph_title", index=2, level=2, anchor="same", content=inline("Second")),- )- )- with _archive(render_epub(fallback, modified_at=_FIXED_TIME)) as archive:- navigation = _xml(archive, "EPUB/nav.xhtml")- toc = navigation.xpath("//xhtml:nav[@epub:type='toc']", namespaces=_NS)[0]- assert toc.xpath(".//xhtml:a/text()", namespaces=_NS) == ["First", "Child", "Second"]- content = _xml(archive, "EPUB/text/content.xhtml")- assert content.xpath("//xhtml:h2/@id | //xhtml:h4/@id", namespaces=_NS) == ["same", "child", "same-2"]---def test_epub_assets_are_embedded_deduplicated_and_missing_sources_degrade_to_text() -> None:- """验证 resolver/base64 去重、富 HTML 图片重写及缺图文字降级。"""- requested: list[str] = []-- def resolve_asset(path: str) -> bytes:- """记录 sidecar 请求,并仅为已知图片返回有效 PNG。"""- requested.append(path)- if path != "images/shared.png":- raise FileNotFoundError(path)- return _PNG_BYTES-- middle = _middle(- _page(- 0,- ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "content": [- {"type": "image_caption", "content": inline("Primary caption")},- {- "type": "image_body",- "index": 0,- "content": "Primary OCR",- "image_path": "images/shared.png",- "image_base64": _PNG_URI,- },- ],- }- ),- TableBlock(- type="table",- index=1,- content=[- TableBodyBlock(- type="table_body",- index=1,- content=(- '<table><tr><td><img src="images/shared.png" alt="Cell image"/></td></tr></table>'- "<ul>Loose text<div>Nested text</div><li>List item</li></ul><!--hidden comment-->"- '<script>alert(1)</script><a href="missing.xhtml">Relative link text</a>'- ),- )- ],- ),- ImageBlock(- type="image",- index=2,- content=[- ImageBodyBlock(- type="image_body",- index=2,- content="Remote OCR",- image_url="https://example.com/remote.png",- )- ],- ),- ImageBlock(- type="image",- index=3,- content=[- ImageBodyBlock(- type="image_body",- index=3,- content="Broken OCR",- image_path="images/missing.png",- image_base64="data:image/png;base64,broken",- )- ],- ),- )- )-- payload = render_epub(middle, asset_resolver=resolve_asset, modified_at=_FIXED_TIME)- with _archive(payload) as archive:- assets = [name for name in archive.namelist() if name.startswith("EPUB/assets/")]- assert len(assets) == 1- content = _xml(archive, "EPUB/text/content.xhtml")- sources = content.xpath("//xhtml:img/@src", namespaces=_NS)- assert len(sources) == 2 and len(set(sources)) == 1- assert all(source.startswith("../assets/") for source in sources)- visible = _text(content)- assert all(value in visible for value in ("Primary OCR", "Primary caption", "Remote OCR", "Broken OCR"))- assert "Relative link text" in visible- assert "Loose textNested textList item" in visible- assert "hidden comment" not in visible- assert not content.xpath("//xhtml:script", namespaces=_NS)- assert not content.xpath("//xhtml:a[@href='missing.xhtml']", namespaces=_NS)- assert "https://example.com/remote.png" not in archive.read("EPUB/text/content.xhtml").decode()- assert requested == ["images/shared.png", "images/missing.png"]--- ("width", "height", "is_valid"),- [- (4_000, 4_000, True),- (8_192, 1, True),- (4_001, 4_000, False),- (8_193, 1, False),- (0, 1, False),- (-1, 1, False),- ],-)-def test_decoded_raster_size_uses_shared_dimension_and_pixel_limits(width: int, height: int, is_valid: bool) -> None:- """验证共享 raster 解码预算固定为单边 8192 与总像素 1600 万。"""- assert MAX_DECODED_RASTER_DIMENSION == 8_192- assert MAX_DECODED_RASTER_PIXELS == 16_000_000- if is_valid:- validate_decoded_raster_size(width, height)- return- with pytest.raises(ValueError, match="Decoded raster image exceeds limits"):- validate_decoded_raster_size(width, height)---def test_image_data_uri_enforces_encoded_and_decoded_byte_budgets(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 raster data URI 会在 Base64 前后分别执行固定字节预算。"""- decode = MagicMock(return_value=b"\x89PNG\r\n\x1a\nx")- monkeypatch.setattr(image_payload_utils, "MAX_RASTER_IMAGE_BYTES", 8)- monkeypatch.setattr(image_payload_utils.base64, "b64decode", decode)-- with pytest.raises(ValueError, match="Raster image payload exceeds its byte limit"):- image_payload_utils.parse_image_data_uri_strict("data:image/png;base64,AAAAAAAAAAAAAAAA")- decode.assert_not_called()-- with pytest.raises(ValueError, match="Raster image payload exceeds its byte limit"):- image_payload_utils.parse_image_data_uri_strict("data:image/png;base64,AAAA")- decode.assert_called_once_with("AAAA", validate=True)---def test_epub_oversized_data_uri_is_omitted_before_hashing(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 EPUB 在缓存键哈希前拒绝超过编码预算的 data URI。"""- digest = MagicMock(side_effect=AssertionError("oversized data URI must not be hashed"))- monkeypatch.setattr(epub_assets, "MAX_IMAGE_DATA_URI_BYTES", len(_PNG_URI) - 1)- monkeypatch.setattr(epub_assets.hashlib, "sha256", digest)- registry = epub_assets.EpubAssetRegistry(None)-- href = registry.resolve_block(ImageBodyBlock(type="image_body", index=0, content="OCR", image_base64=_PNG_URI))-- assert href is None- assert registry.assets == ()- digest.assert_not_called()---def test_epub_oversized_image_is_omitted_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 EPUB 超限 raster 在 load 前省略且保留图片识别文字。"""- image = MagicMock()- image.__enter__.return_value = image- image.format = "PNG"- image.size = (4_001, 4_000)- image.load.side_effect = AssertionError("oversized image must not be decoded")- monkeypatch.setattr(epub_assets.Image, "open", lambda _source: image)- middle = _middle(- _page(- 0,- ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="Oversized OCR",- image_path="images/oversized.png",- )- ],- ),- )- )-- payload = render_epub(middle, asset_resolver=lambda _path: b"oversized", modified_at=_FIXED_TIME)-- with _archive(payload) as archive:- assert not [name for name in archive.namelist() if name.startswith("EPUB/assets/")]- assert "Oversized OCR" in _text(_xml(archive, "EPUB/text/content.xhtml"))- image.load.assert_not_called()---def test_epub_mathml_failure_uses_visible_latex_without_false_manifest_property() -> None:- """验证无效 LaTeX 回退为可见文本且不会误声明 mathml。"""- middle = _middle(_page(0, EquationBlock(type="equation", index=0, content="{")))- with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:- package = _xml(archive, "EPUB/package.opf")- assert package.xpath("string(opf:manifest/opf:item[@id='content']/@properties)", namespaces=_NS) == ""- content = _xml(archive, "EPUB/text/content.xhtml")- assert not content.xpath("//math:math", namespaces=_NS)- fallback = content.xpath("//xhtml:code[contains(@class, 'docvortex-latex-fallback')]", namespaces=_NS)- assert len(fallback) == 1 and _text(fallback[0]) == "{"---def test_epub_static_chart_code_and_algorithm_cover_remaining_visual_bodies() -> None:- """验证 chart、空代码和带行内公式算法均有无脚本静态表示。"""- middle = _middle(- _page(- 0,- ChartBlock(- type="chart",- index=0,- sub_type="bar",- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="| A | B |\n| --- | --- |\n| 1 | 2 |",- )- ],- ),- CodeBlock(- type="code",- index=1,- sub_type="code",- guess_lang="python",- content=[CodeBodyBlock(type="code_body", index=1, content="")],- ),- CodeBlock(- type="code",- index=2,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=2,- content=[*inline("Step ", styles=["bold"]), equation("x+1")],- )- ],- ),- )- )- with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:- content = _xml(archive, "EPUB/text/content.xhtml")- assert "| A | B |" in _text(content)- code = content.xpath("//xhtml:pre[contains(@class, 'docvortex-code')]/xhtml:code", namespaces=_NS)- assert len(code) == 1 and code[0].get("class") == "language-python"- assert content.xpath("//xhtml:div[contains(@class, 'docvortex-algorithm')]//xhtml:strong", namespaces=_NS)- assert content.xpath("//xhtml:div[contains(@class, 'docvortex-algorithm')]//math:math", namespaces=_NS)- assert not content.xpath("//xhtml:script", namespaces=_NS)---def test_epub_resolver_converts_webp_to_manifested_png() -> None:- """验证 reader 兼容性较弱的 WebP sidecar 会在内存中转为 PNG。"""- source = BytesIO()- Image.new("RGBA", (2, 2), (10, 20, 30, 128)).save(source, format="WEBP", lossless=True)- middle = _middle(- _page(- 0,- ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="WebP image",- image_path="images/source.webp",- )- ],- ),- )- )- payload = render_epub(- middle,- modified_at=_FIXED_TIME,- asset_resolver=lambda _: source.getvalue(),- )- with _archive(payload) as archive:- asset_names = [name for name in archive.namelist() if name.startswith("EPUB/assets/")]- assert len(asset_names) == 1 and asset_names[0].endswith(".png")- assert archive.read(asset_names[0]).startswith(b"\x89PNG\r\n\x1a\n")- package = _xml(archive, "EPUB/package.opf")- assert package.xpath("string(opf:manifest/opf:item[starts-with(@id, 'asset-')]/@media-type)", namespaces=_NS) == (- "image/png"- )---def test_real_epub_middlejson_renders_and_roundtrips_through_existing_flash_parser() -> None:- """验证丰富 EPUB fixture 的所有核心结构可生成并由现有 parser 回读。"""- source, _ = doc_analyze(build_epub_fixture(), file_suffix="epub")- payload = render_epub(source, modified_at=_FIXED_TIME)-- package = EpubPackage(payload)- try:- assert len(package.spine) == 1- assert package.metadata.title == "Chapter One"- finally:- package.close()-- with _archive(payload) as archive:- content = _xml(archive, "EPUB/text/content.xhtml")- assert content.xpath("//xhtml:table", namespaces=_NS)- assert content.xpath("//math:math", namespaces=_NS)- assert content.xpath("//xhtml:aside[@epub:type='footnote']", namespaces=_NS)- assert content.xpath("//xhtml:pre", namespaces=_NS)- assert content.xpath("//xhtml:ol | //xhtml:ul", namespaces=_NS)- assert content.xpath("//xhtml:img", namespaces=_NS)-- roundtrip, _ = doc_analyze(payload, file_suffix="epub")- assert len(roundtrip.pages) == 1- visible = " ".join(str(block.content) for page in roundtrip.pages for block in page.blocks if hasattr(block, "content"))- assert "Chapter One" in visible and "Section Two" in visible and "Footnote body" in visible---def test_epub_fragment_links_gain_noteref_semantics_and_external_links_remain() -> None:- """验证脚注 fragment 被标为 noteref,安全外链保持可点击。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- *inline("See "),- hyperlink("#note", "[1]"),- *inline(" and "),- hyperlink("https://example.com/a b", "external"),- ],- ),- PageFootnoteBlock(- type="page_footnote",- index=1,- anchor="note",- content=inline("Footnote body"),- ),- )- )- with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:- content = _xml(archive, "EPUB/text/content.xhtml")- note_link = content.xpath("//xhtml:a[@href='#note']", namespaces=_NS)[0]- assert note_link.get(f"{{{_NS['epub']}}}type") == "noteref"- assert note_link.get("role") == "doc-noteref"- assert content.xpath("string(//xhtml:a[normalize-space(.)='external']/@href)", namespaces=_NS) == (- "https://example.com/a%20b"- )diff --git a/tests/unittest/test_flash_csv.py b/tests/unittest/test_flash_csv.pyindex 727ec701..57ed8e41 100644--- a/tests/unittest/test_flash_csv.py+++ b/tests/unittest/test_flash_csv.py@@ -1,181 +1,18 @@from __future__ import annotationsimport asyncio-import codecsimport json-from io import BytesIOfrom pathlib import Pathimport pytest-from bs4 import BeautifulSoup+from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import CsvModel-from docvortex.analyzers.native import csv as csv_module-from mineru.parser import parse, parse_async-from mineru.parser import api_server+from mineru.parser import api_server, parse, parse_asyncfrom mineru.parser.api_server import CreateJobRequest, FileStore-from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.render.html import render_htmlfrom mineru.render.markdown import render_markdown-from mineru.types import BlockType, TableBlock, TableBodyBlock---def _raw_table_html(payload: bytes) -> str:- """解析 CSV 并返回 model-list 中唯一表格的 HTML。"""- pages = CsvModel().predict(BytesIO(payload))- assert len(pages) == 1- assert len(pages[0]) == 1- assert pages[0][0]["type"] == BlockType.TABLE- return pages[0][0]["content"]---def _html_rows(payload: bytes) -> list[list[str]]:- """把 CSV 投影 HTML 还原为逐行单元格纯文本,方便断言语义。"""- soup = BeautifulSoup(_raw_table_html(payload), "html.parser")- return [[cell.get_text("\n") for cell in row.find_all(["th", "td"])] for row in soup.find_all("tr")]--- ("payload", "expected"),- [- (codecs.BOM_UTF8 + "姓名,年龄\n张三,30\n".encode(), [["姓名", "年龄"], ["张三", "30"]]),- (codecs.BOM_UTF16_LE + "姓名;年龄\n张三;30\n".encode("utf-16le"), [["姓名", "年龄"], ["张三", "30"]]),- ("姓名|年龄\n张三|30\n".encode("gb18030"), [["姓名", "年龄"], ["张三", "30"]]),- ("name\tcity\nAndré\tZürich\n".encode("cp1252"), [["name", "city"], ["André", "Zürich"]]),- ],-)-def test_csv_decodes_common_encodings_and_delimiters(payload: bytes, expected: list[list[str]]) -> None:- """验证常见中西文编码和四种分隔符都进入同一表格语义。"""- assert _html_rows(payload) == expected---def test_csv_sep_directive_overrides_delimiter_sniffing() -> None:- """验证 Excel sep 指令只控制分隔符,不作为数据行输出。"""- payload = 'sep=;\r\nname;note\r\nAlice;"1,2"\r\n'.encode()-- assert _html_rows(payload) == [["name", "note"], ["Alice", "1,2"]]---def test_csv_preserves_multiline_quotes_padding_ragged_rows_and_safe_text() -> None:- """验证多行字段、引号、前导零、首尾空格、短行补齐和 HTML 转义。"""- payload = (- 'name,note,code,markup\nAlice,"line 1\nline 2",001,"<script>alert(1)</script>"\nBob," say ""hi"" ",02\n'- ).encode()-- table_html = _raw_table_html(payload)- assert "line 1<br>line 2" in table_html- assert "<script>" not in table_html- assert "<script>alert(1)</script>" in table_html- assert _html_rows(payload) == [- ["name", "note", "code", "markup"],- ["Alice", "line 1\nline 2", "001", "<script>alert(1)</script>"],- ["Bob", ' say "hi" ', "02", ""],- ]-- middle, _ = doc_analyze(payload, file_suffix="csv")- markdown = render_markdown(middle)- standalone_html = render_html(middle)- assert "<script>alert(1)</script>" not in markdown- assert "<script>alert(1)</script>" in markdown- assert "<script>alert(1)</script>" not in standalone_html--- ("payload", "expected_header"),- [- (b"name,age\nAlice,30\nBob,40\n", True),- (b"name,city\nAlice,London\nBob,Paris\n", True),- (b"1,10\n2,20\n3,30\n", False),- (b"only,one,row\n", False),- ],-)-def test_csv_header_inference_is_deterministic(payload: bytes, expected_header: bool) -> None:- """验证有类型证据、纯文本标签、纯数据和单行文件的表头边界。"""- soup = BeautifulSoup(_raw_table_html(payload), "html.parser")- assert bool(soup.find("th")) is expected_header---def test_csv_empty_single_column_and_blank_records_keep_one_logical_page() -> None:- """验证空 CSV、单列 CSV 和空记录都保留确定的一页语义。"""- assert CsvModel().predict(BytesIO(b"")) == [[]]- assert _html_rows(b"value\none\n\ntwo\n") == [["value"], ["one"], [""], ["two"]]--- "payload",- [- b'a,b\n1,"unterminated\n',- b"a,b\n1,\x81\n",- ],-)-def test_csv_rejects_malformed_syntax_and_unsupported_encoding(payload: bytes) -> None:- """验证损坏引号或无法严格解码的字节会让整份 CSV 失败。"""- with pytest.raises(ValueError):- CsvModel().predict(BytesIO(payload))--- ("constant", "limit", "payload", "message"),- [- ("MAX_CSV_BYTES", 3, b"a,b\n", "max_bytes"),- ("MAX_CSV_ROWS", 1, b"a\nb\n", "max_rows"),- ("MAX_CSV_COLUMNS", 1, b"a,b\n", "max_columns"),- ("MAX_CSV_GRID_SLOTS", 3, b"a,b\n1,2\n", "max_grid_slots"),- ],-)-def test_csv_enforces_resource_limits(- monkeypatch: pytest.MonkeyPatch,- constant: str,- limit: int,- payload: bytes,- message: str,-) -> None:- """验证输入、行、列和规则化网格限制都采用显式失败。"""- monkeypatch.setattr(csv_module, constant, limit)-- with pytest.raises(ValueError, match=message):- CsvModel().predict(BytesIO(payload))---def test_csv_grid_limit_short_circuits_before_trailing_malformed_record(monkeypatch: pytest.MonkeyPatch) -> None:- """验证网格超限后立即失败,不再继续读取尾部损坏记录。"""- monkeypatch.setattr(csv_module, "MAX_CSV_GRID_SLOTS", 3)-- with pytest.raises(ValueError, match="max_grid_slots"):- CsvModel().predict(BytesIO(b'a,b\n1,2\n"unterminated'))---def test_csv_rendered_budget_fails_before_materializing_escaped_field(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 HTML 展开超限时不会先创建放大的字段字符串。"""- monkeypatch.setattr(csv_module, "MAX_CSV_RENDERED_BYTES", 64)-- def unexpected_escape(_value: str) -> str:- """输出预算应在进入 html.escape 前拒绝字段。"""- pytest.fail("oversized CSV field reached HTML escaping")-- monkeypatch.setattr(csv_module, "_render_field_html", unexpected_escape)-- with pytest.raises(ValueError, match="max_rendered_bytes"):- csv_module._rows_to_html([["&" * 20]], has_header=False)---def test_csv_rendered_size_estimator_matches_html_escape_semantics() -> None:- """验证特殊字符、换行、控制符和非 ASCII 文本的 UTF-8 预算精确。"""- value = "&<>\"'\r\n\x01中"- rendered = csv_module._render_field_html(value)-- assert csv_module._rendered_field_utf8_bytes(value, 1_000) == len(rendered.encode())---def test_csv_default_grid_budget_rejects_wide_dom_before_rendering() -> None:- """验证默认预算在宽空表生成数十万 HTML 节点前拒绝输入。"""- assert csv_module.MAX_CSV_GRID_SLOTS == 250_000- wide_empty_row = b"," * (csv_module.MAX_CSV_COLUMNS - 1) + b"\n"- payload = wide_empty_row * 16-- with pytest.raises(ValueError, match="max_grid_slots"):- CsvModel().predict(BytesIO(payload))+from mineru.types import TableBlock, TableBodyBlockdef test_csv_doc_analyze_sync_async_and_render_contracts_match() -> None:diff --git a/tests/unittest/test_flash_docx_equationxml.py b/tests/unittest/test_flash_docx_equationxml.pyindex 873b751c..ed44b3f0 100644--- a/tests/unittest/test_flash_docx_equationxml.py+++ b/tests/unittest/test_flash_docx_equationxml.py@@ -1,34 +1,16 @@from __future__ import annotations-from docvortex.export.middle import export_middle_jsonimport asynciofrom io import BytesIO-from pathlib import Path-from zipfile import ZIP_DEFLATED, ZipFile-from docx import Document-from lxml import etree # type: ignore[reportAttributeAccessIssue]-import pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import DocxModel-from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter-from docvortex.analyzers.native.office.docx.equationxml import DocxEquationXmlDecoder-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.render._internal.docx.math import latex_to_omml-from mineru.types import BlockType, MiddleJson, ModelJson--import docvortex.analyzers.native.office.docx.equationxml as equationxml_modulefrom _docx_equationxml_test_utils import (- M_NS,- WORD_2003_NS,build_equationxml_docx,- build_word_2003_equation_xml,- build_word_2003_equation_xml_from_omml,build_word_2003_fraction_equation_xml,)-from _mtef_test_utils import formula_corpus-from _span_test_utils import equation, inline as text_spans+from docvortex.analyzers.native import DocxModel++from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.types import BlockType, MiddleJson, ModelJsondef _equation_contents(pages: list[list[dict]]) -> list[str]:@@ -37,322 +19,6 @@ def _equation_contents(pages: list[list[dict]]) -> list[str]:return [block["content"] for page in pages for block in page if block["type"] == BlockType.EQUATION]-def _invalid_equationxml_with_multiple_math() -> str:- """构造包含两个 ``m:oMath`` 的非规范 Equation XML。"""-- root = etree.fromstring(build_word_2003_equation_xml("x").encode())- math_paragraph = root.find(f".//{{{M_NS}}}oMathPara")- assert math_paragraph is not None- second = etree.SubElement(math_paragraph, f"{{{M_NS}}}oMath")- run = etree.SubElement(second, f"{{{M_NS}}}r")- etree.SubElement(run, f"{{{M_NS}}}t").text = "y"- return etree.tostring(root, encoding="unicode")---def _doctype_equationxml() -> str:- """构造带外部实体声明的 Equation XML,验证解析器不会读取实体。"""-- return (- '<!DOCTYPE w:wordDocument [<!ENTITY probe SYSTEM "file:///etc/passwd">]>'- f'<w:wordDocument xmlns:w="{WORD_2003_NS}" xmlns:m="{M_NS}">'- "<w:body><w:p><m:oMathPara><m:oMath><m:r><m:t>&probe;</m:t>"- "</m:r></m:oMath></m:oMathPara></w:p></w:body></w:wordDocument>"- )---def _equationxml_with_forbidden_pict() -> str:- """构造包含 Word 2003 ``pict`` 的不可恢复 Equation XML。"""-- root = etree.fromstring(build_word_2003_equation_xml("x").encode())- run = root.find(f".//{{{M_NS}}}r")- assert run is not None- etree.SubElement(run, f"{{{WORD_2003_NS}}}pict")- return etree.tostring(root, encoding="unicode")---def _fallback_shape_text_docx(text: str) -> bytes:- """构造只可由 shape-text fallback 读取文字的 DOCX。"""- document = Document()- document.add_paragraph("before")- source_buffer = BytesIO()- document.save(source_buffer)- with ZipFile(BytesIO(source_buffer.getvalue())) as source:- members = {name: source.read(name) for name in source.namelist()}-- word_namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- drawing_namespace = "http://schemas.openxmlformats.org/drawingml/2006/main"- root = etree.fromstring(members["word/document.xml"])- body = root.find(f"{{{word_namespace}}}body")- assert body is not None- drawing = etree.Element(f"{{{word_namespace}}}drawing")- text_body = etree.SubElement(drawing, f"{{{drawing_namespace}}}txBody")- etree.SubElement(text_body, f"{{{drawing_namespace}}}bodyPr")- etree.SubElement(text_body, f"{{{drawing_namespace}}}t").text = text- body.insert(max(0, len(body) - 1), drawing)- members["word/document.xml"] = etree.tostring(- root,- xml_declaration=True,- encoding="UTF-8",- standalone=True,- )-- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as target:- for name, payload in members.items():- target.writestr(name, payload)- return output.getvalue()---def test_equationxml_decoder_converts_spec_document_and_fraction() -> None:- """验证规范 Word 2003 XML 包装可复用现有 OMML 转换器。"""-- decoder = DocxEquationXmlDecoder()-- assert decoder.decode(build_word_2003_equation_xml()) == "x+y"- assert decoder.decode(build_word_2003_fraction_equation_xml()) == r"\frac{a}{b}"---def test_docx_fallback_shape_text_uses_inline_spans() -> None:- """验证非标准 shape 文字 fallback 输出 Span 而不会中断整份解析。"""- pages = DocxModel().predict(BytesIO(_fallback_shape_text_docx(" shape text ")))-- assert pages[0][-1] == {- "type": BlockType.TEXT,- "content": text_spans("shape text"),- }--- ("source_latex", "expected_latex"),- [- (r"\sqrt{x}", r"\sqrt{x}"),- (r"x^2", r"x^{2}"),- (r"\int_0^1 x", r"\int_{0}^{1}x"),- (r"\left(x\right)", r"\left(x\right)"),- (- r"\begin{matrix}a&b\\c&d\end{matrix}",- r"\begin{matrix}a&b\\c&d\end{matrix}",- ),- ("α+β", r"\alpha +\beta"),- ],-)-def test_equationxml_decoder_reuses_omml_formula_coverage(- source_latex: str,- expected_latex: str,-) -> None:- """验证根式、脚本、积分、定界符、矩阵和 Unicode 沿用 OMML 能力。"""-- equation = latex_to_omml(source_latex, display=False)- equation_xml = build_word_2003_equation_xml_from_omml(equation)-- assert DocxEquationXmlDecoder().decode(equation_xml) == expected_latex--- "payload",- [- "<broken",- "<m:oMath xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math'/>",- _invalid_equationxml_with_multiple_math(),- _doctype_equationxml(),- _equationxml_with_forbidden_pict(),- "<!--comment-->" + build_word_2003_equation_xml("x"),- ],-)-def test_equationxml_decoder_rejects_malformed_or_unsafe_documents(- payload: str,-) -> None:- """验证损坏、裸 OMML、多公式和实体文档整体回退。"""-- assert DocxEquationXmlDecoder().decode(payload) is None---def test_equationxml_decoder_enforces_entry_total_and_cache_budget(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证单属性、累计资源限制及相同 payload 缓存不重复计费。"""-- first = build_word_2003_equation_xml("x")- second = build_word_2003_equation_xml("y")- monkeypatch.setattr(equationxml_module, "MAX_ENTRY_BYTES", len(first.encode()) + 10)- monkeypatch.setattr(equationxml_module, "MAX_ASSET_TOTAL_BYTES", len(first.encode()) + 1)- decoder = DocxEquationXmlDecoder()-- assert decoder.decode(first) == "x"- assert decoder.decode(first) == "x"- with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):- decoder.decode(second)-- monkeypatch.setattr(equationxml_module, "MAX_ENTRY_BYTES", 8)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_entry_bytes"):- DocxEquationXmlDecoder().decode(first)---def test_docx_equationxml_standalone_inline_table_and_textbox_flows() -> None:- """验证正文独立、行内、表格和文本框 Equation XML 输出语义。"""-- equation_xml = build_word_2003_equation_xml()- standalone = DocxModel().predict(BytesIO(build_equationxml_docx([equation_xml])))- inline = DocxModel().predict(BytesIO(build_equationxml_docx([equation_xml], inline=True)))- table = DocxModel().predict(BytesIO(build_equationxml_docx([equation_xml], table=True)))- textbox = DocxModel().predict(BytesIO(build_equationxml_docx([equation_xml], textbox=True)))-- assert standalone == [[{"type": BlockType.EQUATION, "content": "x+y"}]]- assert inline == [- [- {- "type": BlockType.TEXT,- "content": [*text_spans("before "), equation("x+y"), *text_spans(" after")],- }- ]- ]- assert table[0][0]["type"] == BlockType.TABLE- assert "<eq>x+y</eq>" in table[0][0]["content"]- assert "<img" not in table[0][0]["content"]- assert textbox == [[{"type": BlockType.EQUATION, "content": "x+y"}]]---def test_docx_equationxml_title_list_header_and_footer_flows() -> None:- """验证标题、列表及页眉页脚沿用现有公式内容重建路径。"""-- first = build_word_2003_equation_xml("x")- second = build_word_2003_fraction_equation_xml()- title = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [first],- inline=True,- paragraph_style="Title",- )- )- )- bullet = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [first],- inline=True,- paragraph_style="ListBullet",- )- )- )- header_footer = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [first, second],- header_footer=True,- )- )- )-- assert title[0][0] == {- "type": BlockType.DOC_TITLE,- "level": 1,- "content": [*text_spans("before "), equation("x"), *text_spans(" after")],- }- assert bullet == [- [- {- "type": BlockType.LIST,- "attribute": "unordered",- "content": [- {- "type": BlockType.TEXT,- "content": [*text_spans("before "), equation("x"), *text_spans(" after")],- }- ],- "ilevel": 0,- }- ]- ]- assert header_footer == [- [- {"type": BlockType.HEADER, "content": [equation("x")]},- {- "type": BlockType.FOOTER,- "content": [equation(r"\frac{a}{b}")],- },- ]- ]---def test_docx_equationxml_precedence_and_preview_fallback() -> None:- """验证 OMML、Equation XML、MTEF 和预览图片的确定优先级。"""-- equation_xml = build_word_2003_equation_xml("x")- _name, mtef, mtef_latex = formula_corpus()[1]- native_omml = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [equation_xml],- alternate_omml=True,- keep_mtef=True,- mtef_payloads=[mtef],- )- )- )- equationxml_over_mtef = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [equation_xml],- keep_mtef=True,- mtef_payloads=[mtef],- )- )- )- mtef_over_bad_equationxml = DocxModel().predict(- BytesIO(- build_equationxml_docx(- ["<broken"],- keep_mtef=True,- mtef_payloads=[mtef],- )- )- )- preview = DocxModel().predict(BytesIO(build_equationxml_docx(["<broken"])))-- assert native_omml == [[{"type": BlockType.EQUATION, "content": "z"}]]- assert equationxml_over_mtef == [[{"type": BlockType.EQUATION, "content": "x"}]]- assert mtef_over_bad_equationxml == [[{"type": BlockType.EQUATION, "content": mtef_latex}]]- assert len(preview[0]) == 1- assert preview[0][0]["type"] == BlockType.IMAGE---def test_docx_equationxml_same_payload_is_not_semantically_deduplicated() -> None:- """验证缓存只减少解码成本,不合并两个独立公式 shape。"""-- equation_xml = build_word_2003_equation_xml("x")- pages = DocxModel().predict(BytesIO(build_equationxml_docx([equation_xml, equation_xml])))-- assert _equation_contents(pages) == ["x", "x"]---def test_docx_equationxml_shared_preview_is_suppressed_per_shape() -> None:- """验证共享图片关系只抑制有效公式所属 shape,不全局删除图片。"""-- pages = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [build_word_2003_equation_xml("x"), "<broken"],- share_preview=True,- )- )- )-- assert [block["type"] for block in pages[0]] == [- BlockType.EQUATION,- BlockType.IMAGE,- ]- assert pages[0][0]["content"] == "x"---def test_docx_equationxml_attribute_is_unescaped_exactly_once() -> None:- """验证外层属性和内层 XML 实体各解码一次,不发生二次展开。"""-- pages = DocxModel().predict(BytesIO(build_equationxml_docx([build_word_2003_equation_xml("x&y")])))-- assert _equation_contents(pages) == [r"x\&y"]--def test_docx_equationxml_analyze_lifecycle_and_strict_contracts() -> None:"""验证 Equation XML 贯穿同步异步 Analyze 且调用方流保持打开。"""@@ -371,31 +37,3 @@ def test_docx_equationxml_analyze_lifecycle_and_strict_contracts() -> None:assert middle.pages[0].blocks[0].content == r"\frac{a}{b}"assert async_model == modelassert async_middle == middle---def test_docx_equationxml_converter_reuse_resets_decoder_state() -> None:- """验证 converter 复用时页、缓存、资源预算和告警状态均重置。"""-- converter = DocxConverter()- converter.convert(BytesIO(build_equationxml_docx([build_word_2003_equation_xml("x")])))- assert _equation_contents(converter.pages) == ["x"]-- converter.convert(BytesIO(build_equationxml_docx([build_word_2003_equation_xml("y")])))- assert _equation_contents(converter.pages) == ["y"]---def test_invalid_docx_equationxml_preview_exports_to_sidecar(- tmp_path: Path,-) -> None:- """验证坏 Equation XML 的图片回退导出后无 base64 JSON 残留。"""-- middle, _model = doc_analyze(- build_equationxml_docx(["<broken"]),- file_suffix="docx",- )-- result = export_middle_json(middle, tmp_path / "docx-equationxml")-- assert len(result.image_paths) == 1- assert result.image_paths[0].stat().st_size > 0- assert "base64," not in result.json_path.read_text(encoding="utf-8")diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.pyindex 83efaabe..019e2cbd 100644--- a/tests/unittest/test_flash_epub.py+++ b/tests/unittest/test_flash_epub.py@@ -6,46 +6,24 @@ import subprocessimport sysfrom io import BytesIOfrom pathlib import Path-from zipfile import ZIP_DEFLATED, ZipFileimport pytest-from bs4 import BeautifulSoup-from lxml import etree-from loguru import logger+from _epub_test_utils import (+ build_epub_fixture,+)+from docvortex.analyzers.native import EpubModel+from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_path-import docvortex.analyzers.native.epub.package as epub_package_modulefrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.postprocess.lists import fix_office_list_blocks-from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.db import DatabaseManager+from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.fts import FTSManagerfrom mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestError-from docvortex.analyzers.native import EpubModel-from docvortex.analyzers.native.epub import EpubEncryptedError-from docvortex.analyzers.native.epub import EpubPackage-from docvortex.analyzers.native.epub import EpubParseError-from docvortex.analyzers.native.epub import EpubResourceLimitError-from docvortex.analyzers.native.epub import detect_epub-from docvortex.analyzers.native._shared.markup import MarkupStylesheet-from docvortex.analyzers.native._shared.markup import TextStyle-from docvortex.analyzers.native.epub.xhtml import EpubChapterConverter-from docvortex.analyzers.native.epub.xhtml import build_anchor_registry-from docvortex.analyzers.native.epub.xhtml import convert_svg_spine-from mineru.parser import MinerUParser, parse, parse_async-from mineru.parser import api_server+from mineru.parser import MinerUParser, api_server, parse, parse_asyncfrom mineru.parser.api_server import CreateJobRequest, FileStore-from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_path-from mineru.render import RenderMode, render_docx, render_html, render_markdown, render_structured_content-from mineru.types import BlockType, PageFootnoteBlock--from _epub_test_utils import (- build_epub2_fixture,- build_epub_fixture,- build_epub_notes_fixture,- build_epub_table_toc_fixture,-)-from _span_test_utils import inline, inline_text, inline_urls, visible_content+from mineru.render import render_docx, render_html, render_markdown, render_structured_content+from mineru.types import BlockTypedef test_epub_model_analyze_and_renderers_preserve_structured_content() -> None:@@ -101,316 +79,6 @@ def test_epub_model_analyze_and_renderers_preserve_structured_content() -> None:assert docx.startswith(b"PK")-def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:- """验证 Footnote/Endnote、ARIA role、重复 ID 与跨章节 noteref 的统一语义。"""- middle, model = doc_analyze(build_epub_notes_fixture(), file_suffix="epub")- blocks = [block for page in middle.pages for block in page.blocks]- footnotes = [block for block in blocks if block.type == BlockType.PAGE_FOOTNOTE]- assert all(isinstance(block, PageFootnoteBlock) for block in footnotes)- footnote_by_text = {inline_text(block.content): block for block in footnotes} # type: ignore[union-attr]-- first = footnote_by_text["First footnote paragraph back."]- second = footnote_by_text["Second footnote paragraph."]- endnote = footnote_by_text["First endnote paragraph."]- duplicate_first = footnote_by_text["First duplicate note."]- duplicate_second = footnote_by_text["Second duplicate note."]- assert first.anchor and endnote.anchor and duplicate_first.anchor # type: ignore[union-attr]- assert first.anchor == "epub-5da65ec1e273b731b44c" # type: ignore[union-attr]- assert endnote.anchor == "epub-b7ab2fcf9373c09c71d6" # type: ignore[union-attr]- assert duplicate_first.anchor == "epub-2bd2576dd7c5d3cf58f4" # type: ignore[union-attr]- assert duplicate_second.anchor == "epub-2b154ee53d6a59bb32f7" # type: ignore[union-attr]- assert second.anchor is None # type: ignore[union-attr]- assert duplicate_second.anchor and duplicate_second.anchor != duplicate_first.anchor # type: ignore[union-attr]- assert footnote_by_text["ARIA footnote."].anchor # type: ignore[union-attr]- assert footnote_by_text["ARIA endnote."].anchor # type: ignore[union-attr]- assert footnote_by_text["Legacy rearnote."].anchor # type: ignore[union-attr]- assert footnote_by_text["Anonymous endnote."].anchor # type: ignore[union-attr]-- body_text = next(- block- for block in middle.pages[0].blocks- if block.type == BlockType.TEXT and "Same-page" in inline_text(block.content) # type: ignore[union-attr]- )- assert f"#{first.anchor}" in inline_urls(body_text.content) # type: ignore[union-attr]- assert f"#{endnote.anchor}" in inline_urls(body_text.content) # type: ignore[union-attr]- assert f"#{duplicate_first.anchor}" in inline_urls(body_text.content) # type: ignore[union-attr]- assert "empty [4]" in inline_text(body_text.content) # type: ignore[union-attr]- assert not inline_urls(first.content) # type: ignore[union-attr]-- assert any(block.type == BlockType.TEXT and inline_text(block.content) == "Ordinary aside." for block in blocks) # type: ignore[union-attr]- assert any(block.type == BlockType.TEXT and inline_text(block.content) == "Footnotes collection label." for block in blocks) # type: ignore[union-attr]- assert any(block.type == BlockType.LIST and "Footnote sibling list" in str(block.content) for block in blocks) # type: ignore[union-attr]- assert any(block.type == BlockType.TABLE and "Complex only" in str(block.content) for block in blocks) # type: ignore[union-attr]- assert all(- block.get("type") != BlockType.REF_TEXT- for page in model.pages- for block in page- if "footnote" in str(block.get("content", "")).casefold() or "endnote" in str(block.get("content", "")).casefold()- )-- default_markdown = render_markdown(middle)- full_markdown = render_markdown(middle, mode=RenderMode.FULL)- assert "First footnote paragraph" in default_markdown- assert f"](#{first.anchor})" in default_markdown- assert f'id="{first.anchor}" class="docvortex-page-footnote"' in default_markdown- assert f'id="{first.anchor}" class="docvortex-page-footnote"' in full_markdown- assert "Page footnote:" not in default_markdown-- for html_output in (- render_html(middle, standalone=False),- render_html(middle, mode=RenderMode.FULL, standalone=False),- ):- assert f'href="#{first.anchor}"' in html_output- assert f'id="{first.anchor}"' in html_output- assert 'class="docvortex-page-footnote"' in html_output-- structured = render_structured_content(middle)- structured_blocks = [block for page in structured["pages"] for block in page["blocks"]]- structured_footnote = next(block for block in structured_blocks if block.get("anchor") == first.anchor)- assert structured_footnote["type"] == BlockType.PAGE_FOOTNOTE- assert structured_footnote["content"] == "First footnote paragraph back."- assert any(f"](#{first.anchor})" in str(block.get("content", "")) for block in structured_blocks)---def test_epub_internal_links_and_lists_use_cross_renderer_projection() -> None:- """验证 spine 链接保留,列表规范为连续阿拉伯序号且不注入目录页。"""- middle, _ = doc_analyze(build_epub_fixture(), file_suffix="epub")- first_page = middle.pages[0]- second_page = middle.pages[1]- first_title = first_page.blocks[0]- second_title = second_page.blocks[0]- assert first_title.anchor and second_title.anchor # type: ignore[union-attr]- assert first_title.anchor == "epub-1daacccca5bf43833643" # type: ignore[union-attr]- assert second_title.anchor == "epub-8d7fe965e2d714cf08ae" # type: ignore[union-attr]- markdown = render_markdown(middle)- assert markdown.startswith(f'<a id="{first_title.anchor}"></a>\n# Chapter One') # type: ignore[union-attr]- assert "NAV Chapter One" not in markdown- assert "NCX Chapter One" not in markdown- assert "Landmark" not in markdown- assert f"](#{second_title.anchor})" in markdown # type: ignore[union-attr]- assert f"](#{first_title.anchor})" in markdown # type: ignore[union-attr]- assert "3. Three" in markdown- assert "4. Two" in markdown- list_block = next(block for block in first_page.blocks if block.type == BlockType.LIST)- assert [inline_text(child.content) for child in list_block.content] == ["3. Three", "4. Two"]- assert all(label in render_html(middle, standalone=False) for label in ("Three", "Two"))- structured = render_structured_content(middle)- assert any(block.get("content") == "3. Three\n4. Two" for page in structured["pages"] for block in page["blocks"])- assert render_docx(middle).startswith(b"PK")---def test_epub_hidden_list_items_do_not_consume_normalized_numbers() -> None:- """验证隐藏条目先被过滤,统一列表后处理再为可见内容连续编号。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch1.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- ordered_list = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}ol"))- ordered_list.attrib.pop("start", None)- ordered_list.attrib.pop("reversed", None)- ordered_list.attrib.pop("type", None)- items = [child for child in ordered_list if isinstance(child.tag, str) and child.tag.endswith("}li")]- items[0].set("hidden", "hidden")- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()- list_block = next(block for block in blocks if block["type"] == BlockType.LIST)-- assert list_block["start"] == 1- assert list_block["content"] == [{"type": BlockType.TEXT, "content": inline("Two")}]- fix_office_list_blocks([list_block])- assert inline_text(list_block["content"][0]["content"]) == "1. Two"- finally:- package.close()--- ("attribute", "value"),- [- ("hidden", "hidden"),- ("aria-hidden", "true"),- ("style", "display: none"),- ("class", "hidden"),- ],-)-def test_epub_anchor_registry_excludes_hidden_headings(attribute: str, value: str) -> None:- """验证 registry 不为 converter 会丢弃的隐藏标题生成悬空 anchor。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch1.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- heading = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}h1"))- heading.set(attribute, value)- heading.text = "Hidden target"- body = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}body"))- namespace = etree.QName(body).namespace- paragraph = etree.SubElement(body, f"{{{namespace}}}p")- link = etree.SubElement(paragraph, f"{{{namespace}}}a", href="#chapter-one")- link.text = "Hidden link"-- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()-- assert anchors.resolve_link("#chapter-one", base_part=chapter_path) is None- assert "Hidden target" not in str(blocks)- assert "Hidden link" in str(blocks)- assert "<hyperlink>Hidden link" not in str(blocks)- finally:- package.close()--- ("attribute", "value"),- [- ("hidden", "hidden"),- ("aria-hidden", "true"),- ("style", "display: none"),- ("class", "hidden"),- ],-)-def test_epub_anchor_registry_excludes_hidden_notes(attribute: str, value: str) -> None:- """验证隐藏 note 不生成 converter 无法兑现的 fragment target。"""- package = EpubPackage(build_epub_notes_fixture())- try:- chapters: list[tuple[str, etree._Element]] = []- note_path = ""- hidden_note: etree._Element | None = None- for item in package.spine:- if not item.path or not item.media_type or "xhtml" not in item.media_type:- continue- root = package.xml_part(item.path, allow_external_doctype=True)- chapters.append((item.path, root))- for element in root.iter():- if element.get("id") == "fn-one":- hidden_note = element- note_path = item.path- assert hidden_note is not None- hidden_note.set(attribute, value)- if attribute == "class":- namespace = etree.QName(hidden_note.getroottree().getroot()).namespace- style = etree.SubElement(hidden_note.getroottree().getroot(), f"{{{namespace}}}style")- style.text = ".hidden { display: none; }"-- anchors = build_anchor_registry(chapters, package)- blocks = [- block- for chapter_path, root in chapters- for block in EpubChapterConverter(package, chapter_path, root, anchors).convert()- ]-- assert anchors.resolve_link("#fn-one", base_part=note_path) is None- assert "First footnote paragraph" not in str(blocks)- assert "Same-page [1]" in str(blocks)- assert "<hyperlink>[1]" not in str(blocks)- finally:- package.close()---def test_epub_table_contents_resolve_title_marker_and_expand_only_exact_single_target_rows() -> None:- """验证标题内部 marker 可跳转,且目录表格只扩展严格匹配的单目标行。"""- middle, model = doc_analyze(build_epub_table_toc_fixture(), file_suffix="epub")- assert len(middle.pages) == 2- assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)- table = next(block for block in model.pages[0] if block["type"] == BlockType.TABLE)- soup = BeautifulSoup(str(table["content"]), "html.parser")- rows = soup.find_all("tr")-- positive_links = rows[0].find_all("a", href=True)- assert [link.get_text(strip=True) for link in positive_links] == ["CHAPTER I.", "Target Chapter"]- assert len({link["href"] for link in positive_links}) == 1- assert rows[1].find_all("a", href=True)[0].get_text(strip=True) == "Mismatch"- assert len(rows[1].find_all("a", href=True)) == 1- assert rows[2].find("a", href=True)["href"] == "https://example.com" # type: ignore[index]- assert len(rows[2].find_all("a", href=True)) == 1- assert len(rows[3].find_all("a", href=True)) == 2-- rendered = BeautifulSoup(render_html(middle, standalone=False), "html.parser")- chapter_link = rendered.find("a", string="Target Chapter")- chapter_title = rendered.find(id=positive_links[0]["href"].removeprefix("#"))- assert chapter_link is not None and chapter_title is not None- assert chapter_link["href"] == f"#{chapter_title['id']}"---def test_epub_table_spans_are_bounded_before_downstream_grid_parsing() -> None:- """验证超大 EPUB colspan 在进入 DOCX 占位网格前被移除。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch2.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- cell = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}td"))- cell.set("colspan", "100000000")-- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()- table = next(block for block in blocks if block["type"] == BlockType.TABLE)- parsed_cell = BeautifulSoup(str(table["content"]), "html.parser").find("td", string="1")-- assert parsed_cell is not None- assert parsed_cell["rowspan"] == "2"- assert not parsed_cell.has_attr("colspan")- finally:- package.close()--- ("attribute", "value"),- [- ("hidden", "hidden"),- ("aria-hidden", "true"),- ("style", "display: none"),- ("class", "hidden"),- ],-)-def test_epub_figure_skips_hidden_direct_images(attribute: str, value: str) -> None:- """验证 figure 的直接图片同样遵守元素属性、内联样式和 CSS 隐藏规则。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch1.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- figure = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}figure"))- image = next(child for child in figure if isinstance(child.tag, str) and child.tag.endswith("}img"))- image.set(attribute, value)-- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()-- assert all(block["type"] != BlockType.IMAGE for block in blocks)- assert "Dot caption" in str(blocks)- finally:- package.close()---def test_epub_figure_preserves_direct_text_and_child_tails() -> None:- """验证共享 projector 不丢弃 XHTML figure 的直属文本及图片、caption tail。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch1.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- figure = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}figure"))- image = next(child for child in figure if isinstance(child.tag, str) and child.tag.endswith("}img"))- caption = next(child for child in figure if isinstance(child.tag, str) and child.tag.endswith("}figcaption"))- figure.text = "Before"- image.tail = "After"- caption.tail = "Tail"-- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()- relevant = [- block- for block in blocks- if block.get("type") in {BlockType.IMAGE, BlockType.IMAGE_CAPTION}- or visible_content(block.get("content")) in {"Before", "AfterTail"}- ]-- assert [(block["type"], visible_content(block.get("content"))) for block in relevant] == [- (BlockType.TEXT, "Before"),- (BlockType.IMAGE, ""),- (BlockType.IMAGE_CAPTION, "Dot caption"),- (BlockType.TEXT, "AfterTail"),- ]- finally:- package.close()--def test_public_parser_rejects_epub_page_range(tmp_path: Path) -> None:"""验证 EPUB 公共 Parser 只接受整本解析。"""source = tmp_path / "book.epub"@@ -453,78 +121,6 @@ def test_non_pdf_public_parser_rejects_page_range(assert exc_info.value.code == "page_range_invalid"-def test_epub2_and_mimetype_less_compatibility_packages_parse() -> None:- """验证 EPUB 2 common subset 和缺 mimetype 的 container 兼容分支。"""- epub2 = build_epub2_fixture()- compatibility = build_epub_fixture(omit_mimetype=True)- assert detect_epub(epub2)- assert detect_epub(compatibility)- epub2_middle = doc_analyze(epub2, file_suffix="epub")[0]- assert inline_text(epub2_middle.pages[0].blocks[0].content) == "EPUB Two Chapter" # type: ignore[union-attr]- assert inline_text(epub2_middle.pages[0].blocks[1].content) == "Legacy\u00a0body" # type: ignore[union-attr]- assert len(doc_analyze(compatibility, file_suffix="epub")[0].pages) == 3---def test_epub_spine_foreign_resource_uses_xhtml_fallback_chain() -> None:- """验证 foreign spine item 缺失时仍沿 manifest fallback 到 XHTML。"""- middle, _ = doc_analyze(build_epub_fixture(use_foreign_fallback=True), file_suffix="epub")- assert inline_text(middle.pages[1].blocks[0].content) == "Section Two" # type: ignore[union-attr]---def test_epub_spine_missing_supported_resource_uses_xhtml_fallback_chain() -> None:- """验证缺失的 XHTML 主资源不会阻断可用 fallback 链。"""- middle, _ = doc_analyze(build_epub_fixture(use_missing_supported_fallback=True), file_suffix="epub")- assert inline_text(middle.pages[1].blocks[0].content) == "Section Two" # type: ignore[union-attr]---def test_epub_nav_and_ncx_outside_spine_do_not_create_synthetic_page() -> None:- """验证 spine 外的损坏 nav 与有效 NCX 都不会生成合成目录页。"""- middle, _ = doc_analyze(build_epub_fixture(corrupt_nav=True), file_suffix="epub")- markdown = render_markdown(middle)- assert len(middle.pages) == 3- assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)- assert "NCX Chapter One" not in markdown- assert "NAV Chapter One" not in markdown---def test_epub_without_authored_toc_keeps_only_spine_pages_and_titles() -> None:- """验证缺失 nav/NCX 时不从正文标题生成额外目录页。"""- middle, _ = doc_analyze(- build_epub_fixture(include_nav=False, include_ncx=False),- file_suffix="epub",- )- assert len(middle.pages) == 3- assert middle.pages[0].blocks[0].type == BlockType.DOC_TITLE- assert middle.pages[1].blocks[0].type == BlockType.PARAGRAPH_TITLE- assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)---def test_epub_without_toc_or_headings_does_not_add_empty_page() -> None:- """验证没有任何有效目录条目时不生成空 IndexBlock 专页。"""- middle, _ = doc_analyze(- build_epub_fixture(- include_nav=False,- include_ncx=False,- strip_headings=True,- ),- file_suffix="epub",- )- assert len(middle.pages) == 3- assert middle.pages[0].blocks[0].type != BlockType.INDEX---def test_epub_navigation_in_spine_preserves_page_order_and_extra_body_content() -> None:- """验证 spine 中的 nav 作为普通 XHTML 页保留目录和额外正文。"""- middle, _ = doc_analyze(- build_epub_fixture(nav_in_spine=True, nav_extra_body_text="Publisher front matter"),- file_suffix="epub",- )- assert len(middle.pages) == 4- assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)- assert any(inline_text(getattr(block, "content", None)) == "Publisher front matter" for block in middle.pages[0].blocks)- assert inline_text(middle.pages[1].blocks[0].content) == "Chapter One" # type: ignore[union-attr]--def test_epub_content_detection_precedes_extension_and_rejects_fake_packages(tmp_path: Path) -> None:"""验证 EPUB 强内容身份覆盖伪装扩展名,而普通 ZIP/文本不能依赖扩展名通过。"""payload = build_epub_fixture()@@ -540,337 +136,6 @@ def test_epub_content_detection_precedes_extension_and_rejects_fake_packages(tmpparse(fake)-def test_epub_corrupt_chapter_keeps_empty_spine_placeholder() -> None:- """验证局部 XHTML 损坏不移动后续 spine 页号。"""- middle, model = doc_analyze(build_epub_fixture(corrupt_second_chapter=True), file_suffix="epub")- assert len(model.pages) == 3- assert model.pages[1] == []- assert [page.page_idx for page in middle.pages] == [0, 1, 2]- assert middle.pages[1].blocks == []- assert "SVG text" in inline_text(middle.pages[2].blocks[0].content) # type: ignore[union-attr]---def test_epub_malformed_xhtml_warns_and_recovers_without_relaxing_xml_part() -> None:- """验证正文 XHTML 严格失败后告警恢复,而通用 XML 入口仍保持严格。"""- payload = build_epub_fixture(unclosed_br_second_chapter=True)- package = EpubPackage(payload)- try:- assert package.xml_part("EPUB/text/ch2.xhtml", allow_external_doctype=True) is None- recovered = package.xhtml_part("EPUB/text/ch2.xhtml", allow_external_doctype=True)- assert recovered is not None- assert etree.QName(recovered).localname == "html"- finally:- package.close()-- warning_messages: list[str] = []- sink_id = logger.add(lambda message: warning_messages.append(str(message)), level="WARNING", format="{message}")- try:- middle, model = doc_analyze(payload, file_suffix="epub")- finally:- logger.remove(sink_id)-- assert len(model.pages) == 3- assert model.pages[1]- assert "Recovered before" in str(model.pages[1])- assert "Recovered after" in str(model.pages[1])- assert middle.pages[1].blocks- assert any("Recovered malformed EPUB XHTML part path='EPUB/text/ch2.xhtml'" in message for message in warning_messages)---def test_epub_svg_extraction_skips_hidden_descendants_and_hidden_root() -> None:- """验证 standalone SVG 不提取隐藏文本、隐藏图片或隐藏祖先子树。"""- package = EpubPackage(build_epub_fixture())- path = "EPUB/fixed/page.svg"- try:- root = package.xml_part(path)- assert root is not None- namespace = etree.QName(root).namespace- original_text = next(root.iter(f"{{{namespace}}}text"))- original_text.set("style", "display: none")- original_image = next(root.iter(f"{{{namespace}}}image"))- original_image.set("style", "visibility: hidden")- hidden_group = etree.SubElement(root, f"{{{namespace}}}g", style="display: none")- etree.SubElement(hidden_group, f"{{{namespace}}}text").text = "hidden group text"- etree.SubElement(root, f"{{{namespace}}}text").text = "visible graphic label"-- blocks = convert_svg_spine(package, path, root)-- assert "visible graphic label" in str(blocks)- assert "SVG text" not in str(blocks)- assert "hidden group text" not in str(blocks)- assert all(block["type"] != BlockType.IMAGE for block in blocks)-- root.set("style", "display: none")- assert convert_svg_spine(package, path, root) == []- finally:- package.close()---def test_epub_malformed_resource_and_link_references_degrade_locally() -> None:- """验证非法 URI 只丢弃样式、图片或链接目标,不阻断章节正文。"""- package = EpubPackage(build_epub_fixture())- chapter_path = "EPUB/text/ch1.xhtml"- try:- root = package.xml_part(chapter_path, allow_external_doctype=True)- assert root is not None- stylesheet = next(element for element in root.iter() if etree.QName(element).localname == "link")- hyperlink = next(element for element in root.iter() if etree.QName(element).localname == "a")- image = next(element for element in root.iter() if etree.QName(element).localname == "img")- stylesheet.set("href", "http://[")- hyperlink.set("href", "http://[")- image.set("src", "http://[")-- anchors = build_anchor_registry([(chapter_path, root)], package)- blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()-- assert "Chapter One" in str(blocks)- assert "chapter two" in str(blocks)- assert "Remote image" in str(blocks)- assert "<hyperlink>chapter two" not in str(blocks)- finally:- package.close()---def test_epub_rejects_encrypted_unsafe_and_dtd_inputs() -> None:- """验证选中正文加密、上跳成员和 DTD 在语义解析前稳定失败。"""- encrypted = build_epub_fixture(encrypted_paths=("EPUB/text/ch1.xhtml",))- with pytest.raises(EpubEncryptedError, match="Encrypted EPUB resource"):- EpubModel().predict(BytesIO(encrypted))-- unsafe = build_epub_fixture(unsafe_member="../escape")- with pytest.raises(EpubParseError, match="unsafe member path"):- EpubPackage(unsafe)-- dtd_package = EpubPackage(build_epub_fixture(dtd_first_chapter=True))- try:- with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):- dtd_package.xml_part("EPUB/text/ch1.xhtml")- with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):- dtd_package.xhtml_part("EPUB/text/ch1.xhtml", allow_external_doctype=True)- finally:- dtd_package.close()-- malformed_dtd_package = EpubPackage(- build_epub_fixture(- dtd_first_chapter=True,- unclosed_br_first_chapter=True,- )- )- try:- with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):- malformed_dtd_package.xhtml_part("EPUB/text/ch1.xhtml", allow_external_doctype=True)- finally:- malformed_dtd_package.close()---def test_epub_resource_limits_fail_before_semantic_conversion(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 ZIP 条目与 XML 深度预算在正文遍历前生效。"""- payload = build_epub_fixture()- monkeypatch.setattr(epub_package_module, "MAX_ENTRY_BYTES", 32)- with pytest.raises(EpubResourceLimitError, match="max_entry_bytes"):- EpubPackage(payload)-- monkeypatch.setattr(epub_package_module, "MAX_ENTRY_BYTES", 128 * 1024 * 1024)- monkeypatch.setattr(epub_package_module, "MAX_XML_DEPTH", 2)- with pytest.raises(EpubResourceLimitError, match="max_xml_depth"):- EpubPackage(payload)---def test_epub_stylesheet_indexes_repeated_selectors_and_preserves_cascade_order() -> None:- """验证重复 selector 按属性聚合,交错同优先级规则仍遵守源码顺序。"""- stylesheet = MarkupStylesheet()- stylesheet.add(- ".x { font-weight: bold; display: none; }"- ".y { font-weight: normal; display: block; }"- ".x { font-style: italic; }" + ".unused { text-decoration: underline; }" * 10_000- )- element = etree.fromstring(b'<span class="x y"/>')-- resolved = stylesheet.resolve(element, TextStyle())-- assert resolved.text.bold is False- assert resolved.text.italic is True- assert resolved.hidden is False- assert len(stylesheet._class_cascades) == 3---def test_epub_stylesheet_honors_important_before_specificity_and_source_order() -> None:- """验证 important 声明优先于后续普通规则和普通 inline,并允许 inline important 覆盖。"""- stylesheet = MarkupStylesheet()- stylesheet.add(- ".secret { display: none !important; font-weight: bold !important; }.secret { display: block; font-weight: normal; }"- )-- normal_inline = stylesheet.resolve(- etree.fromstring(b'<span class="secret" style="display: block; font-weight: normal"/>'),- TextStyle(),- )- important_inline = stylesheet.resolve(- etree.fromstring(b'<span class="secret" style="display: block !important; font-weight: normal !important"/>'),- TextStyle(),- )-- assert normal_inline.hidden is True- assert normal_inline.text.bold is True- assert important_inline.hidden is False- assert important_inline.text.bold is False--- ("css", "expected_hidden"),- [- (".secret { display: none; visibility: visible; }", True),- (".secret { display: block; visibility: hidden; }", True),- (".secret { display: block; visibility: collapse; }", True),- (- ".secret { display: none !important; visibility: hidden; }"- ".secret { display: block; visibility: visible !important; }",- True,- ),- (".secret { display: block; visibility: visible; }", False),- ],-)-def test_epub_stylesheet_tracks_display_and_visibility_independently(css: str, expected_hidden: bool) -> None:- """验证 display 与 visibility 各自级联,任一计算结果隐藏时都不输出元素。"""- stylesheet = MarkupStylesheet()- stylesheet.add(css)-- resolved = stylesheet.resolve(etree.fromstring(b'<span class="secret"/>'), TextStyle())-- assert resolved.hidden is expected_hidden---def test_epub_combined_visibility_rule_does_not_export_hidden_content() -> None:- """验证真实 EPUB 中 visibility:visible 不会覆盖同规则的 display:none。"""- source = BytesIO(build_epub_fixture())- rewritten = BytesIO()- with ZipFile(source) as archive, ZipFile(rewritten, "w", ZIP_DEFLATED) as output:- for info in archive.infolist():- data = archive.read(info.filename)- if info.filename == "EPUB/styles/book.css":- data = b".hidden { display: none; visibility: visible; }"- output.writestr(info, data)-- pages = EpubModel().predict(BytesIO(rewritten.getvalue()))-- assert "hidden secret" not in str(pages)---def test_epub_stylesheet_allows_visible_descendant_to_override_inherited_visibility() -> None:- """验证 visibility 可继承且显式 visible 后代能够恢复自身输出。"""- stylesheet = MarkupStylesheet()- stylesheet.add(".parent { visibility: hidden; } .child { visibility: visible; }")- parent = etree.fromstring(b'<div class="parent"><span class="child"/></div>')- child = parent[0]-- parent_style = stylesheet.resolve(parent, TextStyle())- child_style = stylesheet.resolve(child, parent_style.text, parent_style.visibility_hidden)-- assert parent_style.subtree_hidden is False- assert parent_style.visibility_hidden is True- assert child_style.subtree_hidden is False- assert child_style.visibility_hidden is False---def test_epub_visibility_visible_descendants_survive_hidden_containers() -> None:- """验证真实 EPUB 的块、行内、列表、表格、SVG 和标题锚点均可从 visibility:hidden 恢复。"""- source = BytesIO(build_epub_fixture())- rewritten = BytesIO()- replacement = b"""<div class="visibility-parent">- hidden parent text- <h2 id="visibility-heading">hidden heading text <span class="visibility-child">Visible descendant heading</span></h2>- <p>hidden paragraph</p>- <p class="visibility-child">visible block text</p>- <p>hidden before <span class="visibility-child">visible inline text</span> hidden after</p>- <ol><li class="visibility-child">visible list item</li><li>hidden list item</li></ol>- <table><tbody><tr><td class="visibility-child">visible table cell</td><td>hidden table cell</td></tr></tbody></table>- <svg xmlns="http://www.w3.org/2000/svg"><g><text class="visibility-child">visible SVG text</text>- <text>hidden SVG text</text></g></svg>-</div>-<div class="display-parent"><p class="visibility-child">display-hidden descendant</p></div>-<div hidden="hidden"><p class="visibility-child">attribute-hidden descendant</p></div>-<p><a href="#visibility-heading">jump to visible heading</a></p>"""- with ZipFile(source) as archive, ZipFile(rewritten, "w", ZIP_DEFLATED) as output:- for info in archive.infolist():- data = archive.read(info.filename)- if info.filename == "EPUB/text/ch1.xhtml":- data = data.replace(b'<p class="hidden">hidden secret</p>', replacement)- elif info.filename == "EPUB/styles/book.css":- data = (- b".visibility-parent { visibility: hidden; }"- b".visibility-child { visibility: visible; }"- b".display-parent { display: none; }"- )- output.writestr(info, data)-- pages = EpubModel().predict(BytesIO(rewritten.getvalue()))- blocks = [block for page in pages for block in page]- flattened = str(blocks)-- for visible_text in (- "Visible descendant heading",- "visible block text",- "visible inline text",- "visible list item",- "visible table cell",- "visible SVG text",- ):- assert visible_text in flattened- for hidden_text in (- "hidden parent text",- "hidden heading text",- "hidden paragraph",- "hidden before",- "hidden after",- "hidden list item",- "hidden table cell",- "hidden SVG text",- "display-hidden descendant",- "attribute-hidden descendant",- ):- assert hidden_text not in flattened-- heading = next(block for block in blocks if inline_text(block.get("content")) == "Visible descendant heading")- assert f"#{heading['anchor']}" in [url for block in blocks for url in inline_urls(block.get("content"))]---def test_epub_visibility_hidden_body_still_visits_visible_children() -> None:- """验证 body 自身 visibility:hidden 时不会在显式可见子节点之前剪枝。"""- source = BytesIO(build_epub_fixture())- rewritten = BytesIO()- with ZipFile(source) as archive, ZipFile(rewritten, "w", ZIP_DEFLATED) as output:- for info in archive.infolist():- data = archive.read(info.filename)- if info.filename == "EPUB/text/ch1.xhtml":- data = data.replace(b"<body>", b'<body class="visibility-parent">', 1)- data = data.replace(b'<h1 id="chapter-one">', b'<h1 id="chapter-one" class="visibility-child">', 1)- elif info.filename == "EPUB/styles/book.css":- data = (- b".visibility-parent { visibility: hidden; }"- b".visibility-child { visibility: visible; }"- b".hidden { display: none; }"- )- output.writestr(info, data)-- first_page = str(EpubModel().predict(BytesIO(rewritten.getvalue()))[0])-- assert "Chapter One" in first_page- assert "Hello" not in first_page---def test_epub_stylesheet_rejects_overlong_numeric_font_weight_before_int() -> None:- """验证超长或越界数字字重作为无效声明忽略且不会覆盖继承样式。"""- stylesheet = MarkupStylesheet()- stylesheet.add(f".x {{ font-weight: {'9' * 100_000}; }} .y {{ font-weight: 1001; }}")-- inherited = TextStyle(bold=True)- overlong = stylesheet.resolve(etree.fromstring(b'<span class="x"/>'), inherited)- out_of_range = stylesheet.resolve(etree.fromstring(b'<span class="y"/>'), inherited)-- assert overlong.text.bold is True- assert out_of_range.text.bold is True--def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:"""验证 doclib 从 OPF 读取元数据和 spine 逻辑页数。"""source = tmp_path / "book.epub"diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.pyindex a3fa93b4..1f6d6d79 100644--- a/tests/unittest/test_flash_html.py+++ b/tests/unittest/test_flash_html.py@@ -1,12 +1,8 @@from __future__ import annotations-from mineru.integrations.docvortex import from_mineru_middle-from docvortex.export.middle import export_middle_jsonimport asyncio-import base64-from copy import copy-from io import BytesIOimport json+from io import BytesIOfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -14,38 +10,24 @@ from zipfile import ZipFileimport httpximport pytest-from bs4 import BeautifulSoup+from _span_test_utils import inline_text+from docvortex.analyzers.native import HtmlModel+from docvortex.analyzers.native.html import HtmlResourceLimitError+from docvortex.analyzers.native.html import converter as html_converter_module+from docvortex.export.middle import export_middle_jsonfrom fastapi.testclient import TestClient-from lxml import etree, html as lxml_html # type: ignore[reportMissingImports]from PIL import Imagefrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from mineru.errors import InvalidRequestErrorfrom mineru.doclib.services.parse_svc import ParseService-from docvortex.analyzers.native import HtmlModel-from docvortex.analyzers.native._shared.markup import MarkupProjector-from docvortex.analyzers.native.html import HtmlResourceLimitError-from docvortex.analyzers.native.html import HtmlSourceContext-from docvortex.analyzers.native.html import converter as html_converter_module-from docvortex.analyzers.native.html import document as html_document_module-from docvortex.analyzers.native.html import resources as html_resources_module-from docvortex.analyzers.native.html import selector as html_selector_module-from docvortex.analyzers.native.html.resources import HtmlResourceContext-from docvortex.codecs.html import decode_docvortex_html_wire-from mineru.parser import ParseResult, parse, parse_async-from mineru.parser import api_server+from mineru.errors import InvalidRequestError+from mineru.parser import ParseResult, api_server, parse, parse_asyncfrom mineru.parser.api_server import CreateJobRequest, FileStore-from mineru.render import RenderModefrom mineru.render.docx import render_docxfrom mineru.render.html import render_htmlfrom mineru.render.markdown import render_markdownfrom mineru.render.structured_content import render_structured_content-from mineru.types import BlockBase, BlockType, CodeBlock, CodeBodyBlock, ImageBlock, ImageBodyBlock, MiddleJson--from _span_test_utils import equation, hyperlink, inline, inline_items, inline_text, visible_content---_PNG_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII="+from mineru.types import BlockType, ImageBlock, ImageBodyBlock, MiddleJsondef _all_raw_blocks(model_pages: list[list[dict[str, object]]]) -> list[dict[str, object]]:@@ -59,169 +41,6 @@ def _image_body(middle: MiddleJson) -> ImageBodyBlock:return next(child for child in image.content if isinstance(child, ImageBodyBlock))-def _wire_contract_middle() -> MiddleJson:- """构造覆盖全部顶层类型、visual child、列表和目录叶子的严格文档。"""- return from_mineru_middle(- {- "pages": [- {- "page_idx": 3,- "blocks": [- {"type": "doc_title", "index": 0, "level": 1, "anchor": "doc-anchor", "content": inline("Document")},- {- "type": "paragraph_title",- "index": 1,- "level": 2,- "anchor": "section-anchor",- "content": inline("Section"),- },- {- "type": "text",- "index": 2,- "content": [- *inline("Text & value < 3 "),- equation("x+1"),- *inline(" <eq>literal</eq>"),- ],- },- {"type": "ref_text", "index": 3, "content": inline("Reference text")},- {- "type": "list",- "index": 4,- "sub_type": "ref_text",- "content": [- {"type": "ref_text", "content": inline("[1] Reference")},- {- "type": "list",- "content": [{"type": "text", "content": inline("- Nested item")}],- },- ],- },- {- "type": "index",- "index": 5,- "content": [- {- "type": "paragraph_title",- "level": 2,- "anchor": "section-anchor",- "content": inline("Section\t9"),- },- {- "type": "index",- "content": [{"type": "text", "content": inline("Unlinked entry")}],- },- ],- },- {- "type": "image",- "index": 6,- "sub_type": "diagram",- "content": [- {- "type": "image_body",- "index": 6,- "content": "Image body",- "image_base64": _PNG_URI,- },- {"type": "image_caption", "index": 7, "content": inline("Image caption")},- {"type": "image_footnote", "index": 8, "content": inline("Image footnote")},- ],- },- {- "type": "table",- "index": 9,- "content": [- {- "type": "table_body",- "index": 9,- "content": "<table><tr><td>A</td></tr></table>",- },- {"type": "table_caption", "index": 10, "content": inline("Table caption")},- {"type": "table_footnote", "index": 11, "content": inline("Table footnote")},- ],- },- {- "type": "chart",- "index": 12,- "sub_type": "bar",- "content": [- {- "type": "chart_body",- "index": 12,- "content": "| A | B |\n| - | - |\n| 1 | 2 |",- "image_base64": _PNG_URI,- },- {"type": "chart_caption", "index": 13, "content": inline("Chart caption")},- {"type": "chart_footnote", "index": 14, "content": inline("Chart footnote")},- ],- },- {- "type": "code",- "index": 15,- "sub_type": "code",- "guess_lang": "python",- "content": [- {"type": "code_body", "index": 15, "content": "print('ok')"},- {"type": "code_caption", "index": 16, "content": inline("Code caption")},- {"type": "code_footnote", "index": 17, "content": inline("Code footnote")},- ],- },- {- "type": "code",- "index": 18,- "sub_type": "algorithm",- "content": [- {- "type": "algorithm_body",- "index": 18,- "content": [*inline("if x < y:\n z="), equation("a")],- },- {"type": "code_caption", "index": 19, "content": inline("Algorithm caption")},- {"type": "code_footnote", "index": 20, "content": inline("Algorithm footnote")},- ],- },- {"type": "equation", "index": 21, "content": "y^2\\tag{1}"},- {- "type": "page_footnote",- "index": 22,- "anchor": "note-anchor",- "content": inline("Page footnote"),- },- {"type": "header", "index": 23, "content": inline("Header")},- {"type": "footer", "index": 24, "content": inline("Footer")},- {"type": "page_number", "index": 25, "content": inline("3")},- {"type": "aside_text", "index": 26, "content": inline("Aside")},- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )---def _semantic_block_signature(block: object) -> tuple[object, ...]:- """提取往返测试关心的类型、元数据和递归 child 类型。"""- content = getattr(block, "content", None)- children = (- tuple(_semantic_block_signature(child) for child in content if isinstance(child, BlockBase))- if isinstance(content, list)- else ()- )- return (- str(getattr(block, "type")),- getattr(block, "sub_type", None),- getattr(block, "guess_lang", None),- getattr(block, "anchor", None),- getattr(block, "level", None),- children,- )--def test_html_doc_analyze_projects_static_semantics_and_renderers() -> None:"""验证 HTML 主链路保留正文结构、行内语义、公式、图片 URL 与固定元数据。"""payload = b"""<!doctype html>@@ -286,41 +105,6 @@ def test_html_doc_analyze_projects_static_semantics_and_renderers() -> None:assert "https://cdn.example.com/a.png" in relationships-def test_html_charsetless_utf8_preserves_non_ascii_text() -> None:- """验证无 charset 的 UTF-8 字节不会被 lxml 按单字节旧编码解释。"""- payload = "<html><body><p>中文内容 café</p></body></html>".encode()-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "中文内容 café" in markdown--- "inert_markup",- [- '<!-- <meta charset="windows-1252"> -->',- '<script>const marker = `<meta charset="windows-1252">`;</script>',- ],- ids=["comment", "script"],-)-def test_html_charsetless_utf8_ignores_inert_encoding_declarations(inert_markup: str) -> None:- """验证注释和脚本中的伪编码声明不会绕过无 charset UTF-8 回退。"""- payload = f"{inert_markup}<html><body><p>中文内容 café</p></body></html>".encode()-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "中文内容 café" in markdown---def test_html_declared_legacy_charset_remains_supported() -> None:- """验证显式声明的旧编码仍交由 lxml 按声明解码。"""- payload = '<html><head><meta charset="windows-1252"></head><body><p>café</p></body></html>'.encode("windows-1252")-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "café" in markdown--def test_html_parse_server_url_preserves_http_declared_charset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""验证 URL HTML 使用 HTTP Content-Type 声明编码而不依赖文档内 meta。"""expected = "日本語テスト"@@ -480,763 +264,6 @@ def test_html_parse_server_no_flash_rejects_extensionless_text_html_after_fetch(parse_async_mock.assert_not_awaited()-def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:- """验证重复 article 场景不会只保留论坛中的首个帖子。"""- payload = b"""<html><body><header>Forum</header><main>- <article class="post"><h2>First post</h2><p>First body with enough useful discussion text.</p></article>- <article class="post"><h2>Second post</h2><p>Second body with another useful discussion answer.</p></article>- </main><footer>footer</footer></body></html>"""-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "First post" in markdown and "First body" in markdown- assert "Second post" in markdown and "Second body" in markdown---def test_html_auto_selection_preserves_ancestor_text_styles() -> None:- """验证正文候选复制后仍继承 body 与外层容器的受支持文字样式。"""- detail = "Inherited text " * 20- payload = f"""<html><body style="font-weight:bold"><aside style="font-style:italic;text-decoration:underline">- <main><p>{detail}</p></main></aside></body></html>""".encode()-- _, model = doc_analyze(payload, file_suffix="html")-- assert inline_text(model.pages[0][0]["content"]) == detail.strip()- assert model.pages[0][0]["content"][0]["styles"] == ["bold", "italic", "underline"]---def test_html_auto_selection_handles_colonized_candidate_ancestor() -> None:- """验证正文候选位于 Office 冒号标签下时可复制祖先链且不会抛出非法标签异常。"""- detail = "Colonized ancestor content " * 20- payload = f"""<html><body><o:smarttag style="font-style:italic">- <main><p>{detail}</p></main></o:smarttag></body></html>""".encode()-- _, model = doc_analyze(payload, file_suffix="html")-- assert inline_text(model.pages[0][0]["content"]) == detail.strip()- assert model.pages[0][0]["content"][0]["styles"] == ["italic"]---def test_html_auto_selection_rejects_single_section_from_document_index() -> None:- """验证多个同级 section 构成的文档索引会保留全部章节而非选择最长一节。"""- detail = b" useful explanatory content with enough words to qualify as an independent scored candidate" * 4- payload = (- b"<html><body><h1>Review index</h1>"- + b"<section><h2>First</h2><p>First section"- + detail- + b"</p><pre>first code</pre></section>"- + b"<section><h2>Second</h2><p>Second section"- + detail- + b"</p><pre>second code</pre></section>"- + b"<section><h2>Third</h2><p>Third section"- + detail- + b"</p><pre>third code</pre></section></body></html>"- )-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "First section" in markdown and "first code" in markdown- assert "Second section" in markdown and "second code" in markdown- assert "Third section" in markdown and "third code" in markdown---def test_html_auto_selection_precomputes_repeated_candidate_groups(monkeypatch: pytest.MonkeyPatch) -> None:- """验证大量异构重复候选只线性计算同级 token,不为每个候选重扫全部兄弟节点。"""- item_count = 200- original_tokens = html_selector_module._tokens- token_calls = 0-- def counted_tokens(element: etree._Element) -> frozenset[str]:- """统计正文选择期间的 token 计算次数。"""- nonlocal token_calls- token_calls += 1- return original_tokens(element)-- monkeypatch.setattr(html_selector_module, "_tokens", counted_tokens)- items = "".join(- f'<{tag} class="post"><p>{"candidate text " * 16}</p></{tag}>' for tag in ("div", "section") * (item_count // 2)- )-- doc_analyze(f"<html><body>{items}</body></html>".encode(), file_suffix="html")-- assert token_calls < item_count * 20---def test_html_auto_selection_precomputes_nested_subtree_penalties(monkeypatch: pytest.MonkeyPatch) -> None:- """验证嵌套候选共享子树的短同级惩罚只线性统计文本。"""- depth = 20- leaf_count = 500- original_normalized_text = html_selector_module._normalized_text- normalization_calls = 0-- def counted_normalized_text(value: str | None) -> str:- """统计正文选择期间的文本规范化次数。"""- nonlocal normalization_calls- normalization_calls += 1- return original_normalized_text(value)-- monkeypatch.setattr(html_selector_module, "_normalized_text", counted_normalized_text)- nested_start = '<div class="content">' * depth- nested_end = "</div>" * depth- leaves = "".join(f"<span>item {index}</span>" for index in range(leaf_count))-- doc_analyze(f"<html><body>{nested_start}{leaves}{nested_end}</body></html>".encode(), file_suffix="html")-- assert normalization_calls < leaf_count * 8---def test_html_soft_prune_precomputes_deep_subtree_text(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 soft prune 只线性扫描深层候选中的大段文本。"""- depth = 200- text = "x" * 4096- root = lxml_html.fromstring("<main>" + "<div>" * depth + f"<p>{text}</p>" + "</div>" * depth + "</main>")- original_normalized_text = html_selector_module._normalized_text- normalized_input_chars = 0-- def counted_normalized_text(value: str | None) -> str:- """累计送入文本规范化函数的原始字符数。"""- nonlocal normalized_input_chars- normalized_input_chars += len(value or "")- return original_normalized_text(value)-- monkeypatch.setattr(html_selector_module, "_normalized_text", counted_normalized_text)-- html_selector_module._soft_prune(root)-- assert normalized_input_chars <= len(text) * 2- assert text in "".join(root.itertext())---def test_html_referenced_external_footnote_keeps_anchor_and_content() -> None:- """验证正文候选外但被引用的 HTML footnote 会追加并生成可兑现 anchor。"""- payload = b"""<html><body><article><h1>Notes</h1>- <p>Claim <a href="#note-1">[1]</a>.</p></article>- <footer><aside id="note-1" role="doc-footnote"><p>Footnote body.</p></aside></footer>- </body></html>"""-- middle, _ = doc_analyze(payload, file_suffix="html")- markdown = render_markdown(middle)- footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)-- assert footnote.anchor is not None # type: ignore[union-attr]- assert footnote.anchor == "html-e31e5112c08d4945a7af" # type: ignore[union-attr]- assert "Footnote body." in inline_text(footnote.content) # type: ignore[union-attr]- assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]- assert f'id="{footnote.anchor}" class="docvortex-page-footnote"' in markdown # type: ignore[union-attr]---def test_html_structured_only_footnote_does_not_create_dangling_anchor() -> None:- """验证只投影为结构化 block 的脚注不会把正文引用改写为悬空 fragment。"""- payload = b"""<html><body><main><p>Claim <a href="#fn">[1]</a>.</p>- <aside id="fn" role="doc-footnote"><ul><li>Only item</li></ul></aside></main></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")- markdown = render_markdown(middle)- rendered_html = render_html(middle, standalone=False)-- assert inline_text(model.pages[0][0]["content"]) == "Claim [1]."- assert model.pages[0][1]["type"] == BlockType.LIST- assert "Only item" in markdown- assert "](#html-" not in markdown- assert 'href="#html-' not in rendered_html--- "ancestor_attributes",- ['style="display:none"', 'style="opacity:0"', "hidden", 'aria-hidden="true"'],-)-def test_html_referenced_external_footnote_respects_hidden_ancestor(ancestor_attributes: str) -> None:- """验证正文外引用脚注不会脱离原始整树隐藏祖先后泄漏到输出。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><h1>Title</h1><p>{detail}<a href="#fn1">[1]</a></p></main>- <aside {ancestor_attributes}><div id="fn1" role="doc-footnote">HIDDEN NOTE</div></aside>- </body></html>""".encode()-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)-- assert "HIDDEN NOTE" not in markdown- assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)---def test_html_referenced_external_footnote_preserves_inherited_visibility() -> None:- """验证复制脚注保留祖先 visibility:hidden,同时允许后代显式恢复可见。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><h1>Title</h1><p>{detail}<a href="#fn1">[1]</a></p></main>- <aside style="visibility:hidden"><div id="fn1" role="doc-footnote">HIDDEN NOTE- <span style="visibility:visible">VISIBLE NOTE</span></div></aside></body></html>""".encode()-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)- footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)-- assert "HIDDEN NOTE" not in markdown- assert inline_text(footnote.content) == "VISIBLE NOTE" # type: ignore[union-attr]- assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]---def test_html_referenced_external_footnote_preserves_inherited_text_styles() -> None:- """验证正文外引用脚注复制后仍携带祖先提供的受支持文字样式。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><p>{detail}<a href="#fn1">[1]</a></p></main>- <aside style="font-weight:bold;font-style:italic;text-decoration:underline line-through">- <div id="fn1" role="doc-footnote">Styled note</div></aside></body></html>""".encode()-- _, model = doc_analyze(payload, file_suffix="html")- footnote = next(block for block in model.pages[0] if block["type"] == BlockType.PAGE_FOOTNOTE)-- assert footnote["content"] == inline(- "Styled note",- styles=["bold", "italic", "underline", "strikethrough"],- )--- "href",- [- "#fn1",- "page.html#fn1",- "https://example.com/page.html#fn1",- ],-)-def test_html_auto_selection_appends_notes_for_all_same_document_url_forms(href: str) -> None:- """验证 auto 正文外脚注可由纯 fragment、相对或绝对同文档 URL 引用。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}- <a href="{href}">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/page.html")-- middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]- markdown = render_markdown(middle)- footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)-- assert inline_text(footnote.content) == "Outside footnote." # type: ignore[union-attr]- assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]- assert "https://example.com/page.html#fn1" not in markdown--- ("href", "note_id"),- [- ("#fn%31", "fn1"),- ("page.html#note%20one", "note one"),- ("https://example.com/page.html#%E8%84%9A%E6%B3%A8", "脚注"),- ],-)-def test_html_auto_selection_decodes_same_document_note_fragments(href: str, note_id: str) -> None:- """验证数字、空格与非 ASCII fragment 解码后可关联正文外脚注。"""- detail = "Useful main article text " * 20- payload = f"""<html><head><meta charset="utf-8"></head><body><main><article><h1>Title</h1><p>{detail}- <a href="{href}">[1]</a></p></article></main>- <footer><aside id="{note_id}" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/page.html")-- middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]- markdown = render_markdown(middle)- footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)-- assert inline_text(footnote.content) == "Outside footnote." # type: ignore[union-attr]- assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]- assert href not in markdown--- ("href", "expected_target"),- [- ("other.html#fn1", "https://example.com/other.html#fn1"),- ("https://other.example/page.html#fn1", "https://other.example/page.html#fn1"),- ("page.html?view=2#fn1", "https://example.com/page.html?view=2#fn1"),- ],-)-def test_html_auto_selection_does_not_append_notes_for_other_documents(href: str, expected_target: str) -> None:- """验证不同 path、origin 或 query 的 URL 不会借 fragment 追加当前文档脚注。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}- <a href="{href}">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/page.html")-- middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]- markdown = render_markdown(middle)-- assert "Outside footnote." not in markdown- assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)- assert expected_target in markdown--- ("base_href", "expected_note"),- [- ("/docs/", True),- ("/other/", False),- ],-)-def test_html_same_document_note_resolution_honors_base_href(base_href: str, expected_note: bool) -> None:- """验证 base href 参与相对脚注 URL 的文档身份判定。"""- detail = "Useful main article text " * 20- payload = f"""<html><head><base href="{base_href}"></head><body><main><article><h1>Title</h1>- <p>{detail}<a href="page.html#fn1">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/docs/page.html")-- markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])-- assert ("Outside footnote." in markdown) is expected_note---def test_html_fragment_only_link_honors_external_base_document() -> None:- """验证 fragment-only 链接按外部 base 解析,不会误关联当前 DOM 中同名脚注。"""- detail = "Useful main article text " * 20- payload = f"""<html><head><base href="other.html"></head><body><main><article><h1>Title</h1>- <p>{detail}<a href="#fn1">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Unrelated local footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/page.html")-- middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]- markdown = render_markdown(middle)-- assert "Unrelated local footnote." not in markdown- assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)- assert "https://example.com/other.html#fn1" in markdown---def test_html_ignores_base_inside_discarded_template() -> None:- """验证惰性 template 中的 base 不会改写正文相对链接。"""- payload = b"""<html><head><template><base href="https://discarded.example/assets/"></template></head>- <body><main><h1>Title</h1><p><a href="article.html">Relative link</a></p></main></body></html>"""- context = HtmlSourceContext(source_uri="https://origin.example/docs/page.html")-- markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])-- assert "https://origin.example/docs/article.html" in markdown- assert "discarded.example" not in markdown---def test_html_formula_wrapper_stops_after_second_non_nested_carrier(monkeypatch: pytest.MonkeyPatch) -> None:- """验证通用公式 wrapper 发现第二个并列 carrier 后立即失败,不继续扫描全部公式。"""- wrapper = lxml_html.fromstring('<div class="math">' + "<math></math>" * 1_000 + "</div>")- original_is_carrier = html_document_module._is_formula_carrier- carrier_checks = 0-- def counted_is_carrier(element: etree._Element) -> bool:- """统计 wrapper 唯一 carrier 判定次数。"""- nonlocal carrier_checks- carrier_checks += 1- return original_is_carrier(element)-- monkeypatch.setattr(html_document_module, "_is_formula_carrier", counted_is_carrier)-- assert html_document_module._formula_wrapper_contains_only_carrier(wrapper) is False- assert carrier_checks == 2---def test_html_local_self_url_appends_referenced_note(tmp_path: Path) -> None:- """验证本地 HTML 使用自身文件名 fragment 时同样保留正文选择外脚注。"""- detail = "Useful main article text " * 20- source = tmp_path / "page.html"- source.write_text(- f"""<html><body><main><article><h1>Title</h1><p>{detail}- <a href="page.html#fn1">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""",- encoding="utf-8",- )-- markdown = parse(source).markdown()-- assert "Outside footnote." in markdown- assert "file:" not in markdown--[email protected]("href", ["javascript:alert(1)#fn1", "http://["])-def test_html_unsafe_or_malformed_note_urls_do_not_append_notes(href: str) -> None:- """验证危险协议与畸形 URL 不参与同文档脚注关联,且不会中断正文解析。"""- detail = "Useful main article text " * 20- payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}- <a href="{href}">[1]</a></p></article></main>- <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>- </body></html>""".encode()- context = HtmlSourceContext(source_uri="https://example.com/page.html")-- markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])-- assert "Title" in markdown and "[1]" in markdown- assert "Outside footnote." not in markdown- assert href not in markdown---def test_html_formula_sources_are_normalized_without_duplicate_katex_text() -> None:- """验证 MathML、公式生成器 wrapper 与 data-expr 按统一公式协议输出且不重复。"""- payload = rb"""<html><body><h1>Math</h1><p>Inline- <math><semantics><mi>x</mi><annotation encoding="application/x-tex">x+1</annotation></semantics></math>- <span class="katex"><span class="katex-mathml"><math><semantics><mi>y</mi>- <annotation encoding="application/x-tex">y^2</annotation></semantics></math></span>- <span class="katex-html">duplicate visible</span></span>- <span class="mathjax"><math><semantics><mi>q</mi>- <annotation encoding="application/x-tex">q_4</annotation></semantics></math>- <span>mathjax duplicate</span></span>- <span data-expr="z_3">formula fallback</span></p>- <div class="docvortex-math docvortex-math--block">\[w^4\]</div></body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)-- assert "x+1" in markdown and "y^2" in markdown and "q_4" in markdown and "z_3" in markdown and "w^4" in markdown- assert any(block.type == BlockType.EQUATION and block.content == "w^4" for block in middle.pages[0].blocks) # type: ignore[union-attr]- assert "duplicate visible" not in markdown- assert "mathjax duplicate" not in markdown- assert "formula fallback" not in markdown---def test_html_generic_formula_class_wrappers_preserve_mixed_content() -> None:- """验证通用公式 class 只规范化真实 carrier,不吞掉外层说明内容。"""- payload = b"""<html><body><main>- <div class="math"><p>Before explanation.</p><math><mi>x</mi></math><p>After explanation.</p></div>- <div class="formula">Prefix <span><math data-tex="y"></math></span> suffix.</div>- <div class="tex"><p>Script before.</p><script type="math/tex; mode=display">z</script>- <p>Script after.</p></div>- <p>Exclusive before<span class="math math-display"><span><math data-tex="u"></math></span></span>Exclusive after</p>- <div class="math"><math data-tex="a"></math><math data-tex="b"></math></div></main></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")- raw = [- (- block["type"],- block.get("content") if block["type"] == BlockType.LIST else visible_content(block.get("content")),- )- for block in model.pages[0]- ]-- assert raw == [- (BlockType.TEXT, "Before explanation."),- (BlockType.EQUATION, "x"),- (BlockType.TEXT, "After explanation."),- (BlockType.TEXT, "Prefix y suffix."),- (BlockType.TEXT, "Script before."),- (BlockType.EQUATION, "z"),- (BlockType.TEXT, "Script after."),- (BlockType.TEXT, "Exclusive before"),- (BlockType.EQUATION, "u"),- (BlockType.TEXT, "Exclusive after"),- (BlockType.EQUATION, "a"),- (BlockType.EQUATION, "b"),- ]- mixed_spans = model.pages[0][3]["content"]- assert any(- (span.get("type") if isinstance(span, dict) else getattr(span, "type", None)) == "equation_inline"- and (span.get("content") if isinstance(span, dict) else getattr(span, "content", None)) == "y"- for span in inline_items(mixed_spans)- )- markdown = render_markdown(middle)- assert markdown.index("Before explanation.") < markdown.index("$$\nx\n$$") < markdown.index("After explanation.")- assert markdown.index("Script before.") < markdown.index("$$\nz\n$$") < markdown.index("Script after.")---def test_html_mineru_page_footnote_marker_roundtrips_as_page_footnote() -> None:- """验证 DocVortex HTML renderer 的轻量脚注 marker 可恢复统一 page_footnote block。"""- payload = b"""<html><body><h1>Footnote</h1>- <div class="docvortex-page-footnote" data-block-type="page_footnote">Rendered footnote.</div>- </body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]-- footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)- assert inline_text(footnote.content) == "Rendered footnote." # type: ignore[union-attr]---def test_html_malformed_urls_degrade_without_aborting_document() -> None:- """验证 urlsplit 无法解析的链接与图片只降级标签文本,不中断整份 HTML。"""- payload = (- b'<html><body><h1>URLs</h1><p><a href="http://[">Broken link</a></p>'- b'<img src="http://[" alt="Broken image"></body></html>'- )-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "Broken link" in markdown and "Broken image" in markdown- assert "http://[" not in markdown---def test_html_arbitrary_svg_data_image_degrades_to_alt_text() -> None:- """验证来源 HTML 不能把可能含活动内容的任意 SVG data URI带入输出。"""- svg = base64.b64encode(b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>').decode()- payload = f'<html><body><h1>SVG</h1><img src="data:image/svg+xml;base64,{svg}" alt="Safe alt"></body></html>'.encode()-- middle = doc_analyze(payload, file_suffix="html")[0]-- assert not any(isinstance(block, ImageBlock) for block in middle.pages[0].blocks)- assert "Safe alt" in render_markdown(middle)- assert "alert(1)" not in middle.to_json()---def test_html_mineru_figure_keeps_real_caption_without_exposing_alt_as_caption() -> None:- """验证 MinerU renderer 图片只恢复真实 caption,不重复显示用于无障碍的长 alt。"""- payload = b"""<html><body><h1>Figure</h1><figure class="docvortex-figure docvortex-figure--image">- <img src="https://example.com/image.png" alt="Long internal image description">- <p class="docvortex-caption">Visible figure caption</p></figure></body></html>"""-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "Visible figure caption" in markdown- assert "Long internal image description" not in markdown---def test_html_mineru_table_figure_rebinds_renderer_caption() -> None:- """验证 MinerU table figure 的独立 caption 恢复为 table_caption 且只输出一次。"""- payload = b"""<html><body><h1>Table figure</h1><figure class="docvortex-figure docvortex-figure--table">- <table><tr><th>A</th></tr><tr><td>1</td></tr></table>- <p class="docvortex-caption">Visible table caption</p></figure></body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)-- table = next(block for block in middle.pages[0].blocks if block.type == BlockType.TABLE)- assert any(child.type == BlockType.TABLE_CAPTION for child in table.content) # type: ignore[union-attr]- assert markdown.count("Visible table caption") == 1---def test_html_figure_preserves_direct_and_inline_text_around_visuals() -> None:- """验证 figure 的直属文本、行内容器和 child tail 按 visual 前后顺序进入 raw blocks。"""- payload = b"""<html><body><figure>Before<span>Inline</span>- <a href="https://example.com/full"><img src="https://example.com/a.png"></a>After- <figcaption>Cap</figcaption>Tail</figure></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")- raw_blocks = model.pages[0]- markdown = render_markdown(middle)-- assert [block["type"] for block in raw_blocks] == [- BlockType.TEXT,- BlockType.IMAGE,- BlockType.IMAGE_CAPTION,- BlockType.TEXT,- ]- assert [visible_content(block.get("content")) for block in raw_blocks] == ["BeforeInline", "", "Cap", "After Tail"]- assert [block.type for block in middle.pages[0].blocks] == [BlockType.TEXT, BlockType.IMAGE, BlockType.TEXT]- assert markdown.index("BeforeInline") < markdown.index("Cap") < markdown.index("After Tail")---def test_html_colonized_office_svg_and_math_tags_preserve_visible_content() -> None:- """验证 legacy HTML 冒号标签不会触发 QName 异常,并按本地名恢复正文、SVG 与公式。"""- payload = b"""<html><body><o:p>Legacy Office text</o:p>- <svg:svg><svg:text>Visible SVG text</svg:text></svg:svg>- <m:math><m:mi>x</m:mi></m:math></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")-- assert [(block["type"], visible_content(block.get("content"))) for block in model.pages[0]] == [- (BlockType.TEXT, "Legacy Office text"),- (BlockType.TEXT, "Visible SVG text"),- (BlockType.EQUATION, "x"),- ]- markdown = render_markdown(middle)- assert "Legacy Office text" in markdown and "Visible SVG text" in markdown- assert "$$\nx\n$$" in markdown---def test_html_interleaved_figure_captions_bind_to_each_nearest_image() -> None:- """验证同一 figure 的多张图片分别保留其相邻 caption,不会全部归到末图。"""- payload = b"""<html><body><figure>- <img src="https://example.com/a.png"><figcaption>Caption A</figcaption>- <img src="https://example.com/b.png"><figcaption>Caption B</figcaption>- </figure></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")-- assert [(block["type"], visible_content(block.get("content"))) for block in model.pages[0]] == [- (BlockType.IMAGE, ""),- (BlockType.IMAGE_CAPTION, "Caption A"),- (BlockType.IMAGE, ""),- (BlockType.IMAGE_CAPTION, "Caption B"),- ]- images = [block for block in middle.pages[0].blocks if isinstance(block, ImageBlock)]- assert len(images) == 2- assert [inline_text(child.content) for child in images[0].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption A"]- assert [inline_text(child.content) for child in images[1].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption B"]---def test_html_figure_annotation_targets_use_one_batched_scan() -> None:- """验证大量 figure 说明通过一次批量绑定保持最近前序 visual 关系。"""- pair_count = 1_000- figure = etree.Element("figure")- annotations: set[etree._Element] = set()- visual_blocks_by_child: dict[etree._Element, list[dict[str, object]]] = {}- expected_targets: list[dict[str, object]] = []- for index in range(pair_count):- image = etree.SubElement(figure, "img")- visual = {"type": BlockType.IMAGE, "content": "", "index": index}- visual_blocks_by_child[image] = [visual]- caption = etree.SubElement(figure, "figcaption")- annotations.add(caption)- expected_targets.append(visual)-- targets = MarkupProjector._figure_annotation_targets(figure, annotations, visual_blocks_by_child)-- captions = [child for child in figure if child.tag == "figcaption"]- assert len(targets) == pair_count- assert [targets[caption] for caption in captions] == expected_targets--- ("visual_markup", "parent_type", "body_type", "annotation_markup", "annotation_type"),- [- (- '<img src="https://example.com/a.png">',- BlockType.IMAGE,- BlockType.IMAGE_BODY,- "<figcaption><p>A</p><p>B</p></figcaption>",- BlockType.IMAGE_CAPTION,- ),- (- '<img src="https://example.com/a.png">',- BlockType.IMAGE,- BlockType.IMAGE_BODY,- '<div class="footnote"><p>A</p><p>B</p></div>',- BlockType.IMAGE_FOOTNOTE,- ),- (- "<table><tr><td>X</td></tr></table>",- BlockType.TABLE,- BlockType.TABLE_BODY,- "<figcaption><p>A</p><p>B</p></figcaption>",- BlockType.TABLE_CAPTION,- ),- (- "<table><tr><td>X</td></tr></table>",- BlockType.TABLE,- BlockType.TABLE_BODY,- '<div class="footnote"><p>A</p><p>B</p></div>',- BlockType.TABLE_FOOTNOTE,- ),- ],-)-def test_html_figure_block_children_keep_visual_annotation_relationship(- visual_markup: str,- parent_type: BlockType,- body_type: BlockType,- annotation_markup: str,- annotation_type: BlockType,-) -> None:- """验证 figure 中的块级说明文本仍按目标 visual 类型保留 caption/footnote 关系。"""- payload = f"<html><body><figure>{visual_markup}{annotation_markup}</figure></body></html>".encode()-- middle, model = doc_analyze(payload, file_suffix="html")-- assert [block["type"] for block in model.pages[0]] == [parent_type, annotation_type, annotation_type]- assert [visible_content(block.get("content")) for block in model.pages[0][1:]] == ["A", "B"]- assert len(middle.pages[0].blocks) == 1- visual = middle.pages[0].blocks[0]- assert visual.type == parent_type- assert [child.type for child in visual.content] == [body_type, annotation_type, annotation_type] # type: ignore[union-attr]- assert [inline_text(child.content) for child in visual.content[1:]] == ["A", "B"] # type: ignore[union-attr]---def test_html_auto_selected_contextual_div_keeps_figure_caption_relation() -> None:- """验证 auto 直接选中 visual wrapper div 时仍执行根节点 caption 关联。"""- payload = b"""<html><body><div><figure><img src="https://example.com/a.png"></figure>- <p class="caption">Div caption</p></div></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")-- assert [(block["type"], visible_content(block.get("content"))) for block in model.pages[0]] == [- (BlockType.IMAGE, ""),- (BlockType.IMAGE_CAPTION, "Div caption"),- ]- image = next(block for block in middle.pages[0].blocks if isinstance(block, ImageBlock))- assert [inline_text(child.content) for child in image.content if child.type == BlockType.IMAGE_CAPTION] == ["Div caption"]---def test_html_caption_does_not_cross_unrelated_parent_container() -> None:- """验证 caption 与 visual 不共享明确语义父容器时不会跨容器猜测归属。"""- detail = b"Useful main article text " * 20- payload = (- b'<html><body><main><div><figure><img src="https://example.com/a.png"></figure></div>'- b'<p class="caption">Outside caption</p><p>' + detail + b"</p></main></body></html>"- )-- middle = doc_analyze(payload, file_suffix="html")[0]- image = next(block for block in middle.pages[0].blocks if isinstance(block, ImageBlock))-- assert all(child.type != BlockType.IMAGE_CAPTION for child in image.content)- assert "Outside caption" in render_markdown(middle)---def test_html_alt_caption_fallback_policy_distinguishes_generic_and_mineru_figures() -> None:- """验证普通图片可用 alt 兜底,但显式 caption 与 MinerU figure 不重复提升 alt。"""- payload = b"""<html><body>- <figure><img src="https://example.com/a.png" alt="Generic alt"></figure>- <figure><img src="https://example.com/b.png" alt="Hidden alt"><figcaption>Explicit caption</figcaption></figure>- <figure class="docvortex-figure"><img src="https://example.com/c.png" alt="Accessibility alt"></figure>- </body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- images = [block for block in middle.pages[0].blocks if isinstance(block, ImageBlock)]- captions = [- [inline_text(child.content) for child in image.content if child.type == BlockType.IMAGE_CAPTION] for image in images- ]-- assert captions == [["Generic alt"], ["Explicit caption"], []]- markdown = render_markdown(middle)- assert "Generic alt" in markdown and "Explicit caption" in markdown- assert "Hidden alt" not in markdown and "Accessibility alt" not in markdown---def test_html_inline_visual_splits_paragraph_text_in_dom_order() -> None:- """验证段落内 visual 会切开前后文本,而不是把图片移到合并文本之后。"""- payload = b'<html><body><p>Before<img src="https://example.com/a.png">After</p></body></html>'-- middle, model = doc_analyze(payload, file_suffix="html")-- assert [(block["type"], visible_content(block.get("content"))) for block in model.pages[0]] == [- (BlockType.TEXT, "Before"),- (BlockType.IMAGE, ""),- (BlockType.TEXT, "After"),- ]- assert [block.type for block in middle.pages[0].blocks] == [BlockType.TEXT, BlockType.IMAGE, BlockType.TEXT]---def test_html_inline_visual_splits_ordered_list_without_renumbering_following_items() -> None:- """验证列表项内 visual 提升为页面兄弟,并保持前后阅读顺序及后续有序编号。"""- payload = b"""<html><body><ol start="3"><li>Before<img src="https://example.com/a.png">After</li>- <li>Next</li></ol></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")- raw_blocks = model.pages[0]-- assert [block["type"] for block in raw_blocks] == [BlockType.LIST, BlockType.IMAGE, BlockType.TEXT, BlockType.LIST]- assert raw_blocks[0]["start"] == 3 and raw_blocks[3]["start"] == 4- assert raw_blocks[0]["content"] == [{"type": BlockType.TEXT, "content": inline("Before")}]- assert inline_text(raw_blocks[2]["content"]) == "After"- assert raw_blocks[3]["content"] == [{"type": BlockType.TEXT, "content": inline("Next")}]- assert [block.type for block in middle.pages[0].blocks] == [- BlockType.LIST,- BlockType.IMAGE,- BlockType.TEXT,- BlockType.LIST,- ]- assert inline_text(middle.pages[0].blocks[0].content[0].content) == "3. Before" # type: ignore[union-attr]- assert inline_text(middle.pages[0].blocks[3].content[0].content) == "4. Next" # type: ignore[union-attr]---def test_html_list_block_children_keep_semantic_text_boundaries() -> None:- """验证一个列表项内的多个块级段落不会粘连成错误单词边界。"""- payload = b"<html><body><ul><li><p>First paragraph.</p><p>Second paragraph.</p></li></ul></body></html>"-- middle, model = doc_analyze(payload, file_suffix="html")- content = model.pages[0][0]["content"][0]["content"]- markdown = render_markdown(middle)-- assert inline_text(content) == "First paragraph.\nSecond paragraph."- assert "First paragraph.Second paragraph." not in markdown- assert "First paragraph.\nSecond paragraph." in markdown--def test_html_local_base_images_styles_and_escape_are_bounded(tmp_path: Path) -> None:"""验证本地 base、CSS、栅格图可读取,但父目录逃逸图片只保留说明。"""assets = tmp_path / "assets"@@ -1270,69 +297,6 @@ def test_html_local_base_images_styles_and_escape_are_bounded(tmp_path: Path) ->assert _image_body(exported.middle_json).image_path is not None-def test_html_local_base_resolves_relative_links(tmp_path: Path) -> None:- """验证本地 HTML 的普通相对链接同样按安全 base 目录解析。"""- (tmp_path / "subdir").mkdir()- source = tmp_path / "sample.html"- source.write_text(- '<html><head><base href="subdir/"></head><body><p><a href="next.html">Next</a></p></body></html>',- encoding="utf-8",- )-- markdown = parse(source).markdown()-- assert "[Next](subdir/next.html)" in markdown---def test_html_remote_source_resolves_relative_links_without_fetching_images() -> None:- """验证 URL 来源只把相对链接与图片规范为绝对 URL,不下载远程图片。"""- context = HtmlSourceContext(source_uri="https://example.com/news/page.html")- payload = b'<html><body><h1 id="top">Remote</h1><p><a href="next.html">Next</a></p><img src="../img/a.png"></body></html>'-- middle, _ = doc_analyze(payload, file_suffix="html", source_context=context)- markdown = render_markdown(middle)-- assert "https://example.com/news/next.html" in markdown- assert _image_body(middle).image_url == "https://example.com/img/a.png"- assert _image_body(middle).image_base64 is None---def test_html_remote_source_resolves_protocol_relative_links() -> None:- """验证远程来源按其安全协议补全协议相对链接。"""- context = HtmlSourceContext(source_uri="https://example.com/news/page.html")- payload = b'<html><body><p><a href="//cdn.example/path">Protocol link</a></p></body></html>'-- markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])-- assert "[Protocol link](https://cdn.example/path)" in markdown---def test_html_local_image_symlink_cannot_escape_resource_root(tmp_path: Path) -> None:- """验证本地图片 symlink resolve 到根目录外时只保留 alt 文本。"""- outside = tmp_path.parent / "outside-symlink-image.png"- Image.new("RGB", (1, 1), "black").save(outside)- link = tmp_path / "linked.png"- try:- link.symlink_to(outside)- except OSError:- pytest.skip("symlink is unavailable on this platform")- source = tmp_path / "sample.html"- source.write_text('<html><body><h1>Link</h1><img src="linked.png" alt="Escaped"></body></html>', encoding="utf-8")-- middle = parse(source).middle_json-- assert not any(isinstance(block, ImageBlock) for block in middle.pages[0].blocks)- assert "Escaped" in render_markdown(middle)---def test_html_model_empty_document_keeps_one_logical_page() -> None:- """验证空 HTML 仍返回确定的一页,不制造伪 bbox 或标题。"""- assert HtmlModel().predict(BytesIO(b"")) == [[]]- middle, model = doc_analyze(b"", file_suffix="html")- assert model.pages == [[]]- assert len(middle.pages) == 1 and middle.pages[0].blocks == []--def test_html_parse_server_local_source_keeps_relative_assets(tmp_path: Path) -> None:"""验证 parse-server 本地来源把原目录上下文传入 HTML 模型并输出严格结果。"""image_path = tmp_path / "pixel.png"@@ -1401,1017 +365,3 @@ def test_html_rejects_page_range_and_resource_overflow(tmp_path: Path, monkeypatmonkeypatch.setattr(html_converter_module, "MAX_HTML_BYTES", 4)with pytest.raises(HtmlResourceLimitError, match="max_html_bytes"):HtmlModel().predict(BytesIO(b"<p>x</p>"))---def test_html_comments_count_toward_dom_node_budget(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 comment 等非元素 DOM 节点同样受总节点预算约束。"""- monkeypatch.setattr(html_document_module, "MAX_HTML_NODES", 4)-- with pytest.raises(HtmlResourceLimitError, match="max_html_nodes"):- doc_analyze(b"<html><body><!--1--><!--2--><!--3--></body></html>", file_suffix="html")--[email protected]("container", ["template", "form"])-def test_html_ignores_stylesheets_beneath_discarded_active_subtrees(container: str) -> None:- """验证待删除活动子树内的 stylesheet 不会污染正文样式。"""- payload = f"<html><body><{container}><style>p{{display:none}}</style></{container}><p>Visible</p></body></html>".encode()-- markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])-- assert "Visible" in markdown--- ("styles", "single_limit", "total_limit", "expected_limit"),- [- ("<style>.large{display:none}</style>", 8, 128, "max_html_stylesheet_bytes"),- (- "<style>.a{display:none}</style><style>.b{display:none}</style>",- 16,- 24,- "max_html_stylesheet_total_bytes",- ),- ],-)-def test_html_inline_stylesheets_enforce_resource_budgets(- styles: str,- single_limit: int,- total_limit: int,- expected_limit: str,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证内联 CSS 同时受单份和整文档 stylesheet 字节预算约束。"""- monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_BYTES", single_limit)- monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_TOTAL_BYTES", total_limit)- payload = f"<html><head>{styles}</head><body><p>Visible</p></body></html>".encode()-- with pytest.raises(HtmlResourceLimitError, match=expected_limit):- doc_analyze(payload, file_suffix="html")---def test_html_inline_and_local_stylesheets_share_total_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """验证内联与本地外链 CSS 按文档顺序共享累计 stylesheet 预算。"""- (tmp_path / "styles.css").write_text(".a{display:none}", encoding="utf-8")- monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_BYTES", 16)- monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_TOTAL_BYTES", 24)- payload = b"""<html><head><link rel="stylesheet" href="styles.css">- <style>.b{display:none}</style></head><body><p>Visible</p></body></html>"""- context = HtmlSourceContext(local_resource_root=tmp_path)-- with pytest.raises(HtmlResourceLimitError, match="max_html_stylesheet_total_bytes"):- doc_analyze(payload, file_suffix="html", source_context=context)--- "image_url",- [- "javascript:alert(1)",- "//example.com/a.png",- "https://user:[email protected]/a.png",- "file:///tmp/a.png",- ],-)-def test_html_remote_image_url_contract_rejects_unsafe_sources(image_url: str) -> None:- """验证 image_url 公共字段只接受无凭据 HTTP(S) 绝对地址。"""- with pytest.raises(ValueError):- ImageBodyBlock(type=BlockType.IMAGE_BODY, content="", image_url=image_url)---def test_html_versioned_wire_roundtrips_empty_code_body() -> None:- """验证空代码主体仍携带 wire marker,并在 HTML 往返后保留代码块元数据。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "code",- "index": 0,- "sub_type": "code",- "guess_lang": "python",- "content": [{"type": "code_body", "index": 0, "content": ""}],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )-- rendered = render_html(source, standalone=False)- marker = BeautifulSoup(rendered, "html.parser").select_one('[data-block-type="code_body"]')- roundtrip = doc_analyze(rendered.encode(), file_suffix="html")[0]- code = next(block for block in roundtrip.pages[0].blocks if isinstance(block, CodeBlock))- body = next(child for child in code.content if isinstance(child, CodeBodyBlock))-- assert marker is not None and marker.get("data-block-index") == "0"- assert code.sub_type == BlockType.CODE and code.guess_lang == "python"- assert body.content == ""---def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:- """验证新版 DocVortex HTML 在 DEFAULT/FULL 中精确恢复公开类型和关键元数据。"""- source = _wire_contract_middle()- default_html = render_html(source, standalone=False)- full_html = render_html(source, mode=RenderMode.FULL, standalone=False)- standalone_html = render_html(source, standalone=True)- default_root = BeautifulSoup(default_html, "html.parser").select_one(".docvortex-document")- full_root = BeautifulSoup(full_html, "html.parser").select_one(".docvortex-document")-- assert default_root["data-docvortex-html-version"] == "1"- assert default_root["data-render-mode"] == "default"- assert full_root["data-render-mode"] == "full"- assert full_root.select_one('[data-block-type="chart_body"]') is not None- assert full_root.select_one('[data-block-type="image_footnote"]') is not None- assert full_root.select_one('[data-block-sub-type="algorithm"]') is not None- assert "y^2\\tag{1}" in [element.get("data-docvortex-latex") for element in full_root.select("[data-docvortex-latex]")]-- default_middle = doc_analyze(default_html.encode(), file_suffix="html")[0]- full_middle = doc_analyze(full_html.encode(), file_suffix="html")[0]- standalone_middle = doc_analyze(standalone_html.encode(), file_suffix="html")[0]- auxiliary_types = {BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT}- expected_default = [- _semantic_block_signature(block) for block in source.pages[0].blocks if block.type not in auxiliary_types- ]- expected_full = [_semantic_block_signature(block) for block in source.pages[0].blocks]-- assert [_semantic_block_signature(block) for block in default_middle.pages[0].blocks] == expected_default- assert [_semantic_block_signature(block) for block in standalone_middle.pages[0].blocks] == expected_default- assert [_semantic_block_signature(block) for block in full_middle.pages[0].blocks] == expected_full- assert len(full_middle.pages) == 1 and full_middle.pages[0].page_idx == 0- assert next(block for block in full_middle.pages[0].blocks if block.type == BlockType.EQUATION).content == "y^2\\tag{1}" # type: ignore[union-attr]- roundtrip_text = next(block for block in full_middle.pages[0].blocks if block.type == BlockType.TEXT).content # type: ignore[union-attr]- source_text = next(block for block in source.pages[0].blocks if block.type == BlockType.TEXT).content # type: ignore[union-attr]- assert roundtrip_text == source_text---def test_html_wire_decode_distinguishes_absent_empty_and_noncanonical() -> None:- """验证单一 decode 入口区分普通 HTML、合法空 wire 与非 canonical v1。"""- source = from_mineru_middle(- {- "pages": [{"page_idx": 0, "blocks": []}],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- ordinary = html_document_module.parse_html_document(b"<html><body><p>ordinary</p></body></html>")- empty = html_document_module.parse_html_document(render_html(source, standalone=False).encode())- edited_soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- edited_soup.select_one(".docvortex-document").append("EDITED")- edited = html_document_module.parse_html_document(str(edited_soup).encode())-- ordinary_result = decode_docvortex_html_wire(- ordinary.body,- HtmlResourceContext(ordinary.source_context),- )- empty_result = decode_docvortex_html_wire(empty.body, HtmlResourceContext(empty.source_context))- edited_result = decode_docvortex_html_wire(edited.body, HtmlResourceContext(edited.source_context))-- assert ordinary_result.blocks is None and ordinary_result.fallback_reason is None- assert empty_result.blocks == [] and empty_result.fallback_reason is None- assert edited_result.blocks is None and edited_result.fallback_reason == "non_canonical_wire"--[email protected](("parent_type", "body_type"), [("image", "image_body"), ("chart", "chart_body")])[email protected]("with_main_image", [False, True])-def test_html_versioned_wire_preserves_visual_rich_content(- parent_type: str,- body_type: str,- with_main_image: bool,-) -> None:- """验证 visual 富内容及嵌套图片按语义往返且不升级为主图片载荷。"""- body: dict[str, object] = {- "type": body_type,- "index": 0,- "content": (- '<p>Recognized <eq>x+1</eq> <a href="https://example.com/a">link</a></p>'- '<img src="https://example.com/nested.png" alt="Nested">'- ),- }- if with_main_image:- body["image_url"] = "https://example.com/main.png"- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": parent_type,- "index": 0,- "sub_type": "diagram",- "content": [body],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- rendered = render_html(source, standalone=False)-- middle, model = doc_analyze(rendered.encode(), file_suffix="html")- raw_body = model.pages[0][0]- normalized = render_html(middle, standalone=False)- normalized_body = BeautifulSoup(normalized, "html.parser").select_one(f'[data-block-type="{body_type}"]')- normalized_middle = doc_analyze(normalized.encode(), file_suffix="html")[0]- stable_body = BeautifulSoup(render_html(normalized_middle, standalone=False), "html.parser").select_one(- f'[data-block-type="{body_type}"]'- )-- assert '<p>Recognized <eq>x+1</eq> <a href="https://example.com/a">link</a></p>' in str(raw_body["content"])- assert '<img alt="Nested" src="https://example.com/nested.png">' in str(raw_body["content"])- assert raw_body.get("image_url") == ("https://example.com/main.png" if with_main_image else None)- assert normalized_body is not None- nested_images = [image for image in normalized_body.find_all("img") if not image.get("class")]- assert [image.get("src") for image in nested_images] == ["https://example.com/nested.png"]- assert str(normalized_body) == str(stable_body)---def test_html_versioned_wire_roundtrips_canonical_visual_body_variants() -> None:- """验证 flowchart 与 table 的固定载荷分支都通过 exact typed plan 往返。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "image",- "index": 0,- "sub_type": "flowchart",- "content": [- {- "type": "image_body",- "index": 0,- "content": "```mermaid\ngraph TD\nA-->B\n```",- }- ],- },- {- "type": "image",- "index": 1,- "sub_type": "flowchart",- "content": [- {- "type": "image_body",- "index": 1,- "content": "Plain non-Mermaid content",- "image_url": "https://example.com/plain.png",- }- ],- },- {- "type": "table",- "index": 2,- "content": [{"type": "table_body", "index": 2, "content": "A B\n1 2"}],- },- {- "type": "table",- "index": 3,- "content": [- {- "type": "table_body",- "index": 3,- "content": "",- "image_url": "https://example.com/table.png",- }- ],- },- {- "type": "table",- "index": 4,- "content": [{"type": "table_body", "index": 4, "content": ""}],- },- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- rendered = render_html(source, standalone=False)- document = html_document_module.parse_html_document(rendered.encode())-- decode_result = decode_docvortex_html_wire(document.body, HtmlResourceContext(document.source_context))- middle, _ = doc_analyze(rendered.encode(), file_suffix="html")- bodies = [block.content[0] for block in middle.pages[0].blocks]-- assert decode_result.blocks is not None and decode_result.fallback_reason is None- assert bodies[0].content == "```mermaid\ngraph TD\nA-->B\n```"- assert bodies[1].content == "Plain non-Mermaid content" and bodies[1].image_url == "https://example.com/plain.png"- assert bodies[2].content == "A B\n1 2"- assert bodies[3].content == "" and bodies[3].image_url == "https://example.com/table.png"- assert bodies[4].content == "" and bodies[4].image_url is None---def test_html_versioned_wire_distinguishes_index_carrier_from_inline_link() -> None:- """验证未链接目录项中的普通 anchor 不会被误认为 renderer 目录外壳。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "index",- "index": 0,- "content": [- {- "type": "text",- "content": [hyperlink("https://example.com/docs", "External")],- }- ],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- rendered = render_html(source, standalone=False)- document = html_document_module.parse_html_document(rendered.encode())-- decode_result = decode_docvortex_html_wire(document.body, HtmlResourceContext(document.source_context))- middle = doc_analyze(rendered.encode(), file_suffix="html")[0]-- assert decode_result.blocks is not None and decode_result.fallback_reason is None- assert "[External](https://example.com/docs)" in render_markdown(middle)--[email protected]("edit_kind", ["index_sibling", "visual_sibling"])-def test_html_noncanonical_wire_structural_edits_use_generic_fallback(edit_kind: str) -> None:- """验证 carrier 外结构统一触发 generic fallback,而不是增加逐 case 物化兼容。"""- if edit_kind == "index_sibling":- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "paragraph_title",- "index": 0,- "anchor": "target",- "level": 2,- "content": inline("Target"),- },- {- "type": "index",- "index": 1,- "content": [- {- "type": "paragraph_title",- "index": 2,- "anchor": "target",- "level": 2,- "content": inline("Title"),- }- ],- },- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- target = soup.select_one('.docvortex-index li[data-block-type="paragraph_title"]')- assert target is not None- target.append(" ADDED")- else:- soup = BeautifulSoup(render_html(_wire_contract_middle(), standalone=False), "html.parser")- target = soup.select_one('[data-block-type="image_body"]')- assert target is not None- target.append(soup.new_tag("img", src="https://example.com/added.png", alt="Added"))- document = html_document_module.parse_html_document(str(soup).encode())-- decode_result = decode_docvortex_html_wire(document.body, HtmlResourceContext(document.source_context))- middle, model = doc_analyze(str(soup).encode(), file_suffix="html")-- assert decode_result.blocks is None and decode_result.fallback_reason == "non_canonical_wire"- if edit_kind == "index_sibling":- assert "ADDED" in render_markdown(middle)- else:- image_urls = [str(block["image_url"]) for block in model.pages[0] if block.get("image_url")]- assert "https://example.com/added.png" in image_urls--[email protected]("outside_kind", ["text", "inline"])-def test_html_versioned_list_content_outside_carrier_falls_back_without_loss(outside_kind: str) -> None:- """验证列表 carrier 外的编辑内容触发通用投影并完整保留。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "list",- "index": 0,- "content": [{"type": "text", "index": 0, "content": inline("- Original")}],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- item = soup.select_one('li[data-block-type="text"]')- assert item is not None- if outside_kind == "text":- item.append(" ADDED")- else:- added = soup.new_tag("span")- added.string = " ADDED"- item.append(added)-- middle, model = doc_analyze(str(soup).encode(), file_suffix="html")-- assert inline_text(model.pages[0][0]["content"][0]["content"]) == "Original ADDED"- assert render_markdown(middle) == "- Original ADDED"---def test_html_invalid_versioned_markers_fallback_without_partial_results() -> None:- """验证未知版本和多类非法 marker 都整体回退,且可见正文不会重复。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "text",- "index": 0,- "content": [*inline("WIRESENTINEL "), equation("WIREFORMULA")],- },- {- "type": "image",- "index": 1,- "content": [- {- "type": "image_body",- "index": 1,- "content": "Image body",- "image_url": "https://example.com/wire.png",- },- {"type": "image_caption", "index": 2, "content": inline("Visible caption")},- ],- },- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- base = render_html(source, standalone=False)- variants: list[str] = []-- unknown = BeautifulSoup(base, "html.parser")- unknown.select_one(".docvortex-document")["data-docvortex-html-version"] = "999"- variants.append(str(unknown))-- illegal_type = BeautifulSoup(base, "html.parser")- illegal_type.select_one(".docvortex-block")["data-block-type"] = "not_a_block"- variants.append(str(illegal_type))-- missing_body = BeautifulSoup(base, "html.parser")- missing_body.select_one('[data-block-type="image_body"]').decompose()- variants.append(str(missing_body))-- duplicate_body = BeautifulSoup(base, "html.parser")- visual_body = duplicate_body.select_one('[data-block-type="image_body"]')- visual_body.parent.append(copy(visual_body))- variants.append(str(duplicate_body))-- parent_mismatch = BeautifulSoup(base, "html.parser")- parent_mismatch.select_one('[data-block-type="image_caption"]')["data-block-type"] = "table_caption"- variants.append(str(parent_mismatch))-- block_nested_formula = BeautifulSoup(base, "html.parser")- block_nested_formula.select_one('[data-block-type="equation"][data-formula-display="inline"]')["data-formula-display"] = (- "block"- )- variants.append(str(block_nested_formula))-- for variant in variants:- markdown = render_markdown(doc_analyze(variant.encode(), file_suffix="html")[0])- assert markdown.count("WIRESENTINEL") == 1- assert markdown.count("WIREFORMULA") == 1- assert markdown.count("Visible caption") == 1--- ("parent_type", "body_type", "sub_type", "owned_class"),- [- ("image", "image_body", "diagram", "docvortex-image"),- ("chart", "chart_body", "bar", "docvortex-chart-image"),- ],-)-def test_html_versioned_wire_multiple_owned_images_fall_back_without_loss(- parent_type: str,- body_type: str,- sub_type: str,- owned_class: str,-) -> None:- """验证普通图片和图表 body 被追加 renderer 图片时回退并保留全部载荷。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": parent_type,- "index": 0,- "sub_type": sub_type,- "content": [- {- "type": body_type,- "index": 0,- "content": "Original visual content",- "image_url": "https://example.com/original.png",- }- ],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- extra = soup.new_tag(- "img",- attrs={"class": owned_class, "src": "https://example.com/added.png", "alt": "Added visual"},- )- soup.select_one(f'[data-block-type="{body_type}"]').append(extra)-- _, model = doc_analyze(str(soup).encode(), file_suffix="html")- image_urls = [str(block["image_url"]) for block in model.pages[0] if block.get("image_url")]-- assert image_urls == ["https://example.com/original.png", "https://example.com/added.png"]---def test_html_versioned_wire_visible_structural_text_falls_back_without_loss() -> None:- """验证机器结构容器中新增的可见文本会整体回退,并保留编辑内容。"""- source = from_mineru_middle(- {- "pages": [{"page_idx": 0, "blocks": [{"type": "text", "index": 0, "content": inline("Original wire text")}]}],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- default_html = render_html(source, standalone=False)- full_html = render_html(source, mode=RenderMode.FULL, standalone=False)- variants: list[tuple[str, str]] = []-- root_text = BeautifulSoup(default_html, "html.parser")- root_text.select_one(".docvortex-document").insert(0, "ROOT EDIT ")- variants.append((str(root_text), "ROOT EDIT"))-- section_text = BeautifulSoup(full_html, "html.parser")- section_text.select_one(".docvortex-page").insert(0, "SECTION EDIT ")- variants.append((str(section_text), "SECTION EDIT"))-- wrapper_text = BeautifulSoup(default_html, "html.parser")- wrapper_text.select_one(".docvortex-block").insert(0, "WRAPPER EDIT ")- variants.append((str(wrapper_text), "WRAPPER EDIT"))-- child_tail = BeautifulSoup(default_html, "html.parser")- child_tail.select_one(".docvortex-block > p").insert_after(" CHILD TAIL EDIT")- variants.append((str(child_tail), "CHILD TAIL EDIT"))-- for variant, edited_text in variants:- markdown = render_markdown(doc_analyze(variant.encode(), file_suffix="html")[0])- assert "Original wire text" in markdown- assert edited_text in markdown--[email protected]("position", ["before", "after"])-def test_html_versioned_wire_visible_sibling_falls_back_without_loss(position: str) -> None:- """验证 wire 根前后的可见兄弟会整体回退,避免精确物化静默丢弃正文。"""- source = from_mineru_middle(- {- "pages": [{"page_idx": 0, "blocks": [{"type": "text", "index": 0, "content": inline("Original wire text")}]}],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- sibling = soup.new_tag("p")- sibling.string = "VISIBLE SIBLING"- wire_root = soup.select_one(".docvortex-document")- if position == "before":- wire_root.insert_before(sibling)- else:- wire_root.insert_after(sibling)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "Original wire text" in markdown- assert "VISIBLE SIBLING" in markdown---def test_html_versioned_wire_markerless_block_child_falls_back_without_crash() -> None:- """验证行内容器内新增的无 marker 块节点会事务式回退,而不是在物化阶段抛错。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "page_footnote",- "index": 0,- "anchor": "note",- "content": inline("Original note"),- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- paragraph = soup.new_tag("p")- paragraph.string = "EXTRA NOTE"- soup.select_one(".docvortex-page-footnote").append(paragraph)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "Original note" in markdown- assert "EXTRA NOTE" in markdown---def test_html_versioned_wire_edited_code_body_falls_back_without_loss() -> None:- """验证普通代码 body 中新增可见节点会整体回退并保留代码与编辑内容。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "code",- "index": 0,- "sub_type": "code",- "guess_lang": "python",- "content": [{"type": "code_body", "index": 0, "content": "print(1)"}],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- paragraph = soup.new_tag("p")- paragraph.string = "NEW NOTE"- soup.select_one('[data-block-type="code_body"]').append(paragraph)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "print(1)" in markdown- assert "NEW NOTE" in markdown---def test_html_versioned_wire_edited_algorithm_body_falls_back_without_loss() -> None:- """验证 algorithm body 中新增可见节点会整体回退并保留算法与编辑内容。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "code",- "index": 0,- "sub_type": "algorithm",- "content": [- {- "type": "algorithm_body",- "index": 0,- "content": [*inline("Step A "), equation("x+1")],- }- ],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- paragraph = soup.new_tag("p")- paragraph.string = "NEW NOTE"- soup.select_one('[data-block-type="algorithm_body"]').append(paragraph)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "Step A" in markdown and "x+1" in markdown- assert "NEW NOTE" in markdown---def test_html_versioned_wire_edited_table_body_falls_back_without_loss() -> None:- """验证表格 body 中新增可见节点会整体回退并保留表格与编辑内容。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "table",- "index": 0,- "content": [- {- "type": "table_body",- "index": 0,- "content": "<table><tr><td>A</td></tr></table>",- }- ],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- paragraph = soup.new_tag("p")- paragraph.string = "NEW NOTE"- soup.select_one('[data-block-type="table_body"]').append(paragraph)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "| A |" in markdown- assert "NEW NOTE" in markdown---def test_html_versioned_wire_edited_flowchart_body_falls_back_without_loss() -> None:- """验证流程图 body 中新增可见节点会整体回退并保留源码与编辑内容。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "image",- "index": 0,- "sub_type": "flowchart",- "content": [- {- "type": "image_body",- "index": 0,- "content": "```mermaid\ngraph TD\nA-->B\n```",- }- ],- }- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- paragraph = soup.new_tag("p")- paragraph.string = "NEW NOTE"- soup.select_one('[data-block-type="image_body"]').append(paragraph)-- markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])-- assert "graph TD" in markdown- assert "NEW NOTE" in markdown---def test_html_marker_fallback_does_not_double_resolve_images(monkeypatch: pytest.MonkeyPatch) -> None:- """验证结构校验先于资源物化,非法 marker 回退只解析一次图片。"""- source = from_mineru_middle(- {- "pages": [- {- "page_idx": 0,- "blocks": [- {"type": "text", "index": 0, "content": inline("Fallback")},- {- "type": "image",- "index": 1,- "content": [- {- "type": "image_body",- "index": 1,- "content": "",- "image_url": "https://example.com/once.png",- }- ],- },- ],- }- ],- "is_full_document": True,- "file_suffix": "html",- "effort": "flash",- "parse_mode": "txt",- "mineru_version": "test",- }- )- soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")- soup.select_one('[data-block-type="text"]')["data-block-type"] = "invalid"- original = HtmlResourceContext.resolve_image- calls: list[str] = []-- def counted_resolve_image(self: HtmlResourceContext, image_source: str, *, alt: str = "") -> object:- """记录图片解析次数后调用真实安全实现。"""- calls.append(image_source)- return original(self, image_source, alt=alt)-- monkeypatch.setattr(HtmlResourceContext, "resolve_image", counted_resolve_image)- middle = doc_analyze(str(soup).encode(), file_suffix="html")[0]-- assert "Fallback" in render_markdown(middle)- assert calls == ["https://example.com/once.png"]---def test_html_generic_div_soup_attaches_contextual_caption_and_footnote() -> None:- """验证非标准 div visual 容器按完整 token 和父子上下文恢复 caption/footnote。"""- payload = b"""<html><body><main><h1>Soup</h1>- <div class="photo-card"><img src="https://example.com/a.png" alt="Alt only">- <p id="caption">Context caption</p><div class="footnote">Context footnote</div></div>- <div><img src="https://example.com/b.png"><p class="captionish">Not exact caption</p></div>- </main></body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- images = [block for block in middle.pages[0].blocks if isinstance(block, ImageBlock)]-- assert len(images) == 2- assert [child.type for child in images[0].content] == [- BlockType.IMAGE_BODY,- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_FOOTNOTE,- ]- assert "Context caption" in render_markdown(middle)- assert "Context footnote" in render_markdown(middle)- assert all(child.type != BlockType.IMAGE_CAPTION for child in images[1].content)---def test_html_formula_priority_delimiters_and_supported_mathml_are_normalized() -> None:- """验证所有受支持公式来源按统一优先级输出裸 LaTeX,并保留内部 tag。"""- payload = rb"""<html><body><h1>Formula matrix</h1><p>- <span class="formula"><span data-docvortex-latex="\(producer\)" data-tex="data-low"><math alttext="alt-low">- <annotation encoding="application/x-tex">annotation-low</annotation></math></span></span>- <math data-tex="data-low"><semantics><mi>x</mi>- <annotation encoding="application/x-tex">annotation-high</annotation></semantics></math>- <span data-expr="$$z_3\tag{3}$$">fallback text</span>- <math alttext="\[alt_value\]"><unknown>ignored</unknown></math>- <span class="katex"><math><msup><mi>k</mi><mn>2</mn></msup></math><span>duplicate</span></span>- <math><mfrac><mi>a</mi><mi>b</mi></mfrac></math></p>- <script type="math/tex; mode=display">\[display_value\]</script></body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- text = next(block for block in middle.pages[0].blocks if block.type == BlockType.TEXT).content # type: ignore[union-attr]- equations = [block.content for block in middle.pages[0].blocks if block.type == BlockType.EQUATION] # type: ignore[union-attr]-- inline_equations = [- getattr(span, "content", "") for span in inline_items(text) if str(getattr(span, "type", "")) == "equation_inline"- ]- assert inline_equations == ["producer", "annotation-high", "z_3\\tag{3}", "alt_value", "{k}^{2}", r"\frac{a}{b}"]- visible_text = inline_text(text)- assert "data-low" not in visible_text and "annotation-low" not in visible_text and "duplicate" not in visible_text- assert equations == ["display_value"]--- ("attributes", "stylesheet"),- [- ("hidden", ""),- ('aria-hidden="true"', ""),- ('style="display:none"', ""),- ('class="hidden-formula"', "<style>.hidden-formula{display:none}</style>"),- ],- ids=["hidden", "aria-hidden", "inline-style", "stylesheet-class"],-)-def test_html_formula_normalization_preserves_direct_visibility(attributes: str, stylesheet: str) -> None:- """验证公式 carrier 归一化后仍保留直接声明的隐藏语义。"""- payload = (- f"<html><head>{stylesheet}</head><body><p>Before <math {attributes} data-tex='x'></math> After</p></body></html>"- ).encode()-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)-- assert "$x$" not in markdown- assert "Before" in markdown and "After" in markdown---def test_html_block_formulas_nested_in_text_containers_preserve_dom_order() -> None:- """验证文本容器内的 display 公式切成独立 Equation,并保留前后阅读顺序。"""- payload = b"""<html><body><p>Before<script type="math/tex; mode=display">x</script>Between- <span><math display="block" data-tex="y"></math></span>After</p>- <ul><li>Item before<math display="block" data-tex="z"></math>Item after</li></ul></body></html>"""-- middle, model = doc_analyze(payload, file_suffix="html")- raw = [- (- block["type"],- block.get("content") if block["type"] == BlockType.LIST else visible_content(block.get("content")),- )- for block in model.pages[0]- ]-- assert raw[:5] == [- (BlockType.TEXT, "Before"),- (BlockType.EQUATION, "x"),- (BlockType.TEXT, "Between"),- (BlockType.EQUATION, "y"),- (BlockType.TEXT, "After"),- ]- assert raw[5][0] == BlockType.LIST- assert inline_text(raw[5][1][0]["content"]) == "Item before"- assert raw[6:] == [(BlockType.EQUATION, "z"), (BlockType.TEXT, "Item after")]- assert [block.type for block in middle.pages[0].blocks] == [- BlockType.TEXT,- BlockType.EQUATION,- BlockType.TEXT,- BlockType.EQUATION,- BlockType.TEXT,- BlockType.LIST,- BlockType.EQUATION,- BlockType.TEXT,- ]---def test_html_invalid_mathml_and_asciimath_remain_visible_text() -> None:- """验证未知 MathML 与本轮未支持 AsciiMath 不会伪装为 Equation 或被静默删除。"""- payload = b"""<html><body><h1>Fallback math</h1>- <math><unknown>not-latex</unknown></math>- <script type="math/asciimath">sqrt(2)</script></body></html>"""-- middle = doc_analyze(payload, file_suffix="html")[0]- markdown = render_markdown(middle)-- assert "not-latex" in markdown and "sqrt(2)" in markdown- assert not any(block.type == BlockType.EQUATION for block in middle.pages[0].blocks)diff --git a/tests/unittest/test_flash_image_mtef.py b/tests/unittest/test_flash_image_mtef.pydeleted file mode 100644index 4764fc82..00000000--- a/tests/unittest/test_flash_image_mtef.py+++ /dev/null@@ -1,239 +0,0 @@-from __future__ import annotations--import pytest--from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.equation import image as image_equation_module-from docvortex.analyzers.native.office.equation.image import OfficeImageEquationDecoder-from docvortex.analyzers.native.office.equation.image import decode_image_embedded_equation--from _image_mtef_test_utils import (- apps_mfcc_comment,- apps_mfcc_comments,- baseline_wmf_comment,- build_baseline_only_gif,- build_gif_with_extensions,- build_gif_with_mtef,- build_wmf,- gif_mtef_extension,- pre6_wmf_comment,-)-from _mtef_test_utils import formula_corpus-from _mtef_v5_test_utils import v5_equation, v5_formula_corpus, v5_text--- ("mtef", "expected"),- [- (formula_corpus()[1][1], formula_corpus()[1][2]),- (v5_formula_corpus()[1][1], v5_formula_corpus()[1][2]),- ],- ids=["v3", "v5"],-)-def test_pre6_wmf_comment_decodes_mtef_versions(- mtef: bytes,- expected: str,-) -> None:- """验证带/不带 placeable header 的 pre-6 WMF 可恢复 v3/v5。"""-- comment = pre6_wmf_comment(mtef)-- assert (- decode_image_embedded_equation(- build_wmf([comment]),- part_name="image.wmf",- )- == expected- )- assert (- decode_image_embedded_equation(- build_wmf([comment], placeable=True),- content_type="image/x-wmf",- )- == expected- )--- "signature",- [- "Design Science, Inc./MTEF",- "Wiris/MTEF/MathType7",- "Acme/MTEF",- "Design Science, Inc.",- "Wiris",- ],-)-def test_apps_mfcc_single_and_multi_chunk_signatures(signature: str) -> None:- """验证规范及历史 signature 的单/多 chunk AppsMFCC。"""-- _name, mtef, expected = v5_formula_corpus()[2]-- single = build_wmf(- apps_mfcc_comments(- mtef,- chunk_size=len(mtef),- signature=signature,- )- )- multiple = build_wmf(- apps_mfcc_comments(- mtef,- chunk_size=7,- signature=signature,- )- )-- assert decode_image_embedded_equation(single) == expected- assert decode_image_embedded_equation(multiple) == expected---def test_apps_mfcc_reassembles_mtef_larger_than_32k() -> None:- """验证 AppsMFCC 可跨 WMF 单 comment 上限重组大型 MTEF。"""-- mtef = v5_equation(v5_text("x" * 7000))- assert len(mtef) > 0x7FFE- image = build_wmf(- apps_mfcc_comments(- mtef,- chunk_size=30_000,- )- )-- assert decode_image_embedded_equation(image) == "x" * 7000--- ("mtef", "expected"),- [- (formula_corpus()[0][1], formula_corpus()[0][2]),- (v5_formula_corpus()[0][1], v5_formula_corpus()[0][2]),- ],- ids=["v3", "v5"],-)-def test_gif_mathtype_001_decodes_across_subblocks(- mtef: bytes,- expected: str,-) -> None:- """验证 GIF MathType/001 跨 sub-block 恢复 v3/v5。"""-- image = build_gif_with_mtef(- mtef,- chunk_size=5,- include_baseline=True,- )-- assert decode_image_embedded_equation(image) == expected---def test_wmf_gif_decode_full_v3_v5_formula_corpora() -> None:- """验证两种图片载体复用全部既有 v3/v5 公式语料。"""-- for _name, mtef, expected in formula_corpus():- assert decode_image_embedded_equation(build_wmf([pre6_wmf_comment(mtef)])) == expected- assert decode_image_embedded_equation(build_gif_with_mtef(mtef, chunk_size=5)) == expected- for _name, mtef, expected in v5_formula_corpus():- assert decode_image_embedded_equation(build_wmf(apps_mfcc_comments(mtef, chunk_size=7))) == expected- assert decode_image_embedded_equation(build_gif_with_mtef(mtef, chunk_size=5)) == expected---def test_baseline_comments_and_ordinary_images_are_ignored() -> None:- """验证 WMF baseline、GIF/002 和普通图片不被误判为公式。"""-- assert decode_image_embedded_equation(build_wmf([baseline_wmf_comment(12)])) is None- assert decode_image_embedded_equation(build_baseline_only_gif()) is None- assert decode_image_embedded_equation(b"\x89PNG\r\n\x1a\n") is None---def test_conflicting_wmf_and_gif_candidates_fail_closed() -> None:- """验证同一图片中互相冲突的公式 candidates 整体回退。"""-- v3 = formula_corpus()[0][1]- v5 = v5_formula_corpus()[1][1]- wmf = build_wmf(- [- pre6_wmf_comment(v3),- apps_mfcc_comment(v5, total_length=len(v5)),- ]- )- gif = build_gif_with_extensions(- [- gif_mtef_extension(v3),- gif_mtef_extension(v5),- ]- )-- assert decode_image_embedded_equation(wmf) is None- assert decode_image_embedded_equation(gif) is None--- "image",- [- build_wmf([pre6_wmf_comment(bytes([4, 1, 0, 3, 5, 0]))]),- build_wmf(- [- apps_mfcc_comment(- b"truncated",- total_length=100,- )- ]- ),- build_gif_with_mtef(bytes([4, 1, 0, 3, 5, 0])),- build_gif_with_mtef(v5_formula_corpus()[0][1])[:-1],- ],-)-def test_unsupported_or_truncated_image_comments_fail_closed(- image: bytes,-) -> None:- """验证 v4、缺 chunk 和截断 GIF 不输出部分公式。"""-- assert decode_image_embedded_equation(image) is None---def test_reordered_apps_chunks_and_strict_image_prefixes_fail_closed() -> None:- """验证 AppsMFCC 乱序及任意 WMF/GIF 截断不会输出部分公式。"""-- mtef = v5_formula_corpus()[1][1]- comments = apps_mfcc_comments(mtef, chunk_size=7)- reordered = build_wmf(list(reversed(comments)))- valid_wmf = build_wmf(comments)- valid_gif = build_gif_with_mtef(mtef, chunk_size=5)-- assert decode_image_embedded_equation(reordered) is None- assert all(decode_image_embedded_equation(valid_wmf[:end]) is None for end in range(len(valid_wmf)))- assert all(decode_image_embedded_equation(valid_gif[:end]) is None for end in range(len(valid_gif)))---def test_image_equation_decoder_cache_and_total_budget(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证相同图片缓存不重复计费,唯一图片受累计预算限制。"""-- first_mtef = v5_formula_corpus()[0][1]- second_mtef = v5_formula_corpus()[1][1]- first = build_gif_with_mtef(first_mtef)- second = build_gif_with_mtef(second_mtef)- monkeypatch.setattr(- image_equation_module,- "MAX_ASSET_TOTAL_BYTES",- len(first) + 1,- )- decoder = OfficeImageEquationDecoder()-- assert decoder.decode(first) == v5_formula_corpus()[0][2]- assert decoder.decode(first) == v5_formula_corpus()[0][2]- with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):- decoder.decode(second)---def test_image_equation_record_limit_raises_stable_error(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 WMF/GIF record 超限抛稳定 resource-limit 错误。"""-- monkeypatch.setattr(image_equation_module, "MAX_PICTURE_RECORDS", 1)- image = build_gif_with_mtef(v5_formula_corpus()[0][1], chunk_size=1)-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_picture_records"):- decode_image_embedded_equation(image)diff --git a/tests/unittest/test_flash_legacy_chart_data.py b/tests/unittest/test_flash_legacy_chart_data.pydeleted file mode 100644index 41faa551..00000000--- a/tests/unittest/test_flash_legacy_chart_data.py+++ /dev/null@@ -1,192 +0,0 @@-from __future__ import annotations--import struct-import zlib--from bs4 import BeautifulSoup--from mineru.backend.analyze import doc_analyze-from docvortex.analyzers.native.office.ppt import parser as ppt_parser-from docvortex.analyzers.native.office.ppt.records import PptRecord-from docvortex.analyzers.native.office.xls.embedded_chart import extract_embedded_chart_html-from mineru.types import BlockType, ChartBlock--from _legacy_ppt_test_utils import _build_cfb-from _legacy_xls_test_utils import biff_bof, biff_record, label_cell, number_cell-from _span_test_utils import inline_text---def _boundsheet(offset: int, name: str, sheet_type: int, *, visible: bool = True) -> bytes:- """构造带指定工作表类型的 BoundSheet8。"""-- encoded = name.encode("utf-16le")- payload = struct.pack("<IBB", offset, 0 if visible else 1, sheet_type)- payload += struct.pack("<BB", len(encoded) // 2, 1) + encoded- return biff_record(0x0085, payload)---def _chart_brai(row_last: int, col_last: int) -> bytes:- """构造引用第二个 BoundSheet 数据范围的 PtgArea3d BRAI。"""-- tokens = struct.pack("<BH4H", 0x3B, 0, 0, row_last, 0, col_last)- payload = struct.pack("<BBHHH", 1, 2, 0, 0, len(tokens)) + tokens- return biff_record(0x1051, payload)---def _excel_chart_workbook() -> bytes:- """构造一个独立 Chart1 引用 Sheet1!A1:B3 的 BIFF8 Workbook。"""-- prefix = biff_bof(0x0005)- prefix += biff_record(0x0042, struct.pack("<H", 1200))- prefix += biff_record(0x01AE, struct.pack("<HH", 2, 0x0401))- prefix += biff_record(0x0017, struct.pack("<H3H", 1, 0, 1, 1))- window = bytearray(18)- struct.pack_into("<H", window, 10, 0)- prefix += biff_record(0x003D, bytes(window))-- chart_stream = biff_bof(0x0020) + _chart_brai(2, 1) + biff_record(0x000A)- data_records = (- label_cell(0, 0, "类别")- + label_cell(0, 1, "系列")- + label_cell(1, 0, "A")- + number_cell(1, 1, 1.5)- + label_cell(2, 0, "B")- + number_cell(2, 1, 2.5)- )- data_stream = biff_bof(0x0010) + data_records + biff_record(0x000A)- placeholders = _boundsheet(0, "Chart1", 0x02) + _boundsheet(0, "Sheet1", 0x00)- globals_size = len(prefix) + len(placeholders) + len(biff_record(0x000A))- chart_offset = globals_size- data_offset = chart_offset + len(chart_stream)- directory = _boundsheet(chart_offset, "Chart1", 0x02) + _boundsheet(- data_offset,- "Sheet1",- 0x00,- )- return prefix + directory + biff_record(0x000A) + chart_stream + data_stream---def _graph_label(row: int, col: int, text: str) -> bytes:- """构造 MS-OGRAPH Label datasheet 单元格。"""-- encoded = text.encode("utf-16le")- payload = struct.pack("<HHBHBB", row, col, 0, 0, len(text), 1) + encoded- return biff_record(0x0204, payload)---def _graph_number(row: int, col: int, value: float) -> bytes:- """构造 MS-OGRAPH Number datasheet 单元格。"""-- return biff_record(0x0003, struct.pack("<HHBHd", row, col, 0, 0, value))---def _graph_chart_workbook(*, exclude_last_row: bool = False) -> bytes:- """构造一个含两行两列 datasheet 的 MS-OGRAPH Workbook。"""-- globals_stream = biff_bof(0x0005, version=0x0680) + biff_record(0x000A)- datasheet = (- biff_record(0x1052, b"\x00" * 4)- + _graph_label(0, 0, "类别")- + _graph_label(0, 1, "系列")- + _graph_label(1, 0, "A")- + _graph_number(1, 1, 3.5)- )- if exclude_last_row:- datasheet += _graph_label(2, 0, "B") + _graph_number(2, 1, 4.5)- datasheet += biff_record(0x1053, struct.pack("<2H", 0, 2))- chart_stream = biff_bof(0x8000, version=0x0680) + datasheet + biff_record(0x000A)- return globals_stream + chart_stream---def _table_rows(content: str) -> list[list[str]]:- """把 chart HTML 归一化为二维文本矩阵。"""-- soup = BeautifulSoup(content, "html.parser")- return [- [cell.get_text(" ", strip=True) for cell in row.find_all(["th", "td"], recursive=False)] for row in soup.find_all("tr")- ]---def test_excel_chart_workbook_uses_chart_sheet_brai_selection() -> None:- """验证 Excel.Chart 独立 chart sheet 精确恢复引用范围。"""-- content = extract_embedded_chart_html(_excel_chart_workbook())-- assert content is not None- assert _table_rows(content) == [["类别", "系列"], ["A", "1.5"], ["B", "2.5"]]---def test_msgraph_chart_workbook_recovers_embedded_datasheet() -> None:- """验证 MS-OGRAPH 专用 Label/Number 记录恢复为 HTML 表格。"""-- content = extract_embedded_chart_html(_graph_chart_workbook())-- assert content is not None- assert _table_rows(content) == [["类别", "系列"], ["A", "3.5"]]---def test_msgraph_chart_applies_excluded_row_boundaries() -> None:- """验证 MS-OGRAPH ExcludeRows 不把未参与 chart 的 datasheet 行输出。"""-- content = extract_embedded_chart_html(_graph_chart_workbook(exclude_last_row=True))-- assert content is not None- assert _table_rows(content) == [["类别", "系列"], ["A", "3.5"]]---def test_xls_standalone_chart_sheet_keeps_workbook_order() -> None:- """验证独立 Chart Sheet 按 BoundSheet 顺序输出单独逻辑页。"""-- middle, model = doc_analyze(- _build_cfb([("Workbook", _excel_chart_workbook())]),- file_suffix="xls",- )-- assert len(model.pages) == len(middle.pages) == 2- assert [block.get("type") for block in model.pages[0]] == [- BlockType.PARAGRAPH_TITLE,- BlockType.CHART,- ]- assert isinstance(middle.pages[0].blocks[1], ChartBlock)- assert _table_rows(middle.pages[0].blocks[1].content[0].content) == [- ["类别", "系列"],- ["A", "1.5"],- ["B", "2.5"],- ]- assert inline_text(model.pages[1][0]["content"]) == "Sheet1"---def test_excel_chart_single_visible_sheet_fallback_uses_nonempty_extent() -> None:- """验证没有可解析 chart sheet 时仅对唯一可见 worksheet 使用安全回退。"""-- workbook = _excel_chart_workbook().replace(_chart_brai(2, 1), biff_record(0x1051, b"\x00" * 8))- content = extract_embedded_chart_html(workbook)-- assert content is not None- assert _table_rows(content) == [["类别", "系列"], ["A", "1.5"], ["B", "2.5"]]---def test_ppt_sync_flush_chart_storage_is_accepted_only_at_declared_cfb_size() -> None:- """验证真实 Office 风格无 trailer 压缩流在严格 CFB 门下恢复。"""-- storage = _build_cfb([("Workbook", _excel_chart_workbook())])- compressor = zlib.compressobj()- compressed = compressor.compress(storage) + compressor.flush(zlib.Z_SYNC_FLUSH)- record = PptRecord(- offset=0,- version=0,- instance=1,- record_type=ppt_parser.RT_EXTERNAL_OLE_OBJECT_STG,- payload=struct.pack("<I", len(storage)) + compressed,- )-- assert ppt_parser._decompress_ole_storage(record) == storage-- truncated = PptRecord(- offset=0,- version=0,- instance=1,- record_type=ppt_parser.RT_EXTERNAL_OLE_OBJECT_STG,- payload=struct.pack("<I", len(storage) - 1) + compressed,- )- assert ppt_parser._decompress_ole_storage(truncated) is Nonediff --git a/tests/unittest/test_flash_legacy_doc.py b/tests/unittest/test_flash_legacy_doc.pyindex 918dd0cc..00bf53ca 100644--- a/tests/unittest/test_flash_legacy_doc.py+++ b/tests/unittest/test_flash_legacy_doc.py@@ -1,71 +1,14 @@from __future__ import annotationsimport asyncio-from io import BytesIOfrom pathlib import Path-from unittest.mock import Mock-import pytest+from _legacy_doc_test_utils import build_doc+from _span_test_utils import inline_textfrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.postprocess.lists import fix_office_list_blocks-from docvortex.analyzers.native import DocModel-from docvortex.analyzers.native._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES-from docvortex.analyzers.native._shared.hyperlink import sanitize_hyperlink_target-from docvortex.analyzers.native.office.doc.models import DocCharStyle-from docvortex.analyzers.native.office.doc.models import DocTableCell-from docvortex.analyzers.native.office.doc.images import ImageStore-from docvortex.analyzers.native.office.doc.parser import _RawTableRow-from docvortex.analyzers.native.office.doc.parser import _materialize_table_rows-from docvortex.analyzers.native.office.doc.records import DocBudget-from docvortex.analyzers.native.office.doc.sprm import apply_character_sprms-from docvortex.analyzers.native.office.errors import LegacyOfficeEncryptedError-from docvortex.analyzers.native.office.errors import LegacyOfficeMalformedError-from docvortex.analyzers.native.office.errors import LegacyOfficeMissingPartError-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.legacy.officeart import OfficeImagePayloadfrom mineru.parser import parse-from mineru.types import BlockType, MiddleJson, ModelJson--from _legacy_doc_test_utils import build_doc, utf16_cp-from _legacy_ppt_test_utils import _build_cfb-from _span_test_utils import inline, inline_items, inline_text, inline_urls---def test_doc_image_store_distinguishes_render_size_without_double_accounting() -> None:- """验证相同图片的不同 ptSize 独立缓存,但原始 bytes 只计费和解码一次。"""- decoder = Mock()- decoder.decode.return_value = None- store = ImageStore(equation_decoder=decoder)- data = b"same-standard-wmf"-- landscape = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (914_400, 457_200)))- portrait = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (457_200, 914_400)))- landscape_again = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (914_400, 457_200)))-- assert landscape.render_size_emu == (914_400, 457_200)- assert portrait.render_size_emu == (457_200, 914_400)- assert portrait is not landscape- assert landscape_again is landscape- assert store.total == len(data)- decoder.decode.assert_called_once()---def test_doc_model_preserves_empty_sections_and_ignores_page_breaks() -> None:- """验证 section 是唯一分页来源,空 section 保留且分页符不额外切页。"""-- text = "\fFirst\rSecond\r"- first_end = utf16_cp("\fFirst\r")- stream = BytesIO(build_doc(text, section_ends=[0, first_end, utf16_cp(text)]))-- pages = DocModel().predict(stream)-- assert not stream.closed- assert pages == [- [],- [{"type": BlockType.TEXT, "content": inline("First")}],- [{"type": BlockType.TEXT, "content": inline("Second")}],- ]+from mineru.types import MiddleJson, ModelJsondef test_doc_analyze_sync_and_async_return_strict_doc_contract() -> None:@@ -84,183 +27,6 @@ def test_doc_analyze_sync_and_async_return_strict_doc_contract() -> None:assert async_middle == middle- ("text", "compressed", "kwargs"),- [- ("A😀B\r", False, {}),- ("café\r", True, {}),- ("Привет, мир!\r", True, {"codec": "cp1251", "lid": 0x0419}),- ("こんにちは世界。\r", True, {"codec": "cp932", "lid": 0x0411, "flags_extra": 0x4000}),- ],-)-def test_doc_piece_text_preserves_non_bmp_and_compressed_codepage(- text: str,- compressed: bool,- kwargs: dict[str, object],-) -> None:- """验证 UTF-16 非 BMP CP 和压缩 ANSI piece 均恢复原文本。"""-- pages = DocModel().predict(BytesIO(build_doc(text, compressed=compressed, **kwargs)))-- assert pages == [[{"type": BlockType.TEXT, "content": inline(text.rstrip("\r"))}]]---def test_doc_footnote_reference_and_body_bind_to_reference_section() -> None:- """验证脚注引用使用上标样式,脚注正文追加到引用所在 section。"""-- pages = DocModel().predict(- BytesIO(- build_doc(- "Body\x02\rTail\r",- section_ends=[6, 11],- footnote_text="Foot note\r",- )- )- )-- assert any(- isinstance(span, dict) and span.get("content") == "[1]" and "superscript" in span.get("styles", [])- for span in inline_items(pages[0][0]["content"])- )- assert pages[0][-1] == {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] Foot note")}- assert all(block.get("type") != BlockType.PAGE_FOOTNOTE for block in pages[1])---def test_doc_hyperlink_field_keeps_safe_target_and_drops_dangerous_target() -> None:- """验证字段缓存结果保留,危险 URL 只降级为普通文本。"""-- text = '\x13 HYPERLINK "https://example.test/a" \x14Safe\x15\r\x13 HYPERLINK "javascript:alert(1)" \x14Danger\x15\r'- pages = DocModel().predict(BytesIO(build_doc(text)))-- assert inline_urls(pages[0][0]["content"]) == ["https://example.test/a"]- assert pages[0][1] == {"type": BlockType.TEXT, "content": inline("Danger")}--- ("target", "expected"),- [- ("https://example.test", "https://example.test"),- ("#bookmark", "#bookmark"),- ("docs/readme.doc", "docs/readme.doc"),- ("file:///tmp/a.doc", None),- (r"C:\\docs\\a.doc", None),- (r"\\server\\share\\a.doc", None),- ("data:text/plain,x", None),- ],-)-def test_doc_hyperlink_security_policy(target: str, expected: str | None) -> None:- """验证 DOC 链接白名单拒绝本地和可执行目标。"""-- assert (- sanitize_hyperlink_target(- target,- allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,- allow_relative=True,- allow_fragment=True,- )- == expected- )---def test_doc_character_sprms_preserve_visible_styles_and_hide_revisions() -> None:- """验证常见 CHPX 样式、上下标、隐藏和删除修订状态。"""-- grpprl = (- b"\x35\x08\x01" # bold- b"\x36\x08\x01" # italic- b"\x3e\x2a\x01" # underline- b"\x37\x08\x01" # strike- b"\x48\x2a\x01" # superscript- b"\x3c\x08\x01" # hidden- b"\x00\x08\x01" # deleted revision- )-- style = apply_character_sprms(grpprl, DocCharStyle(), DocCharStyle())-- assert style.bold and style.italic and style.underline and style.strike- assert style.superscript and not style.subscript- assert style.hidden and style.deleted---def test_doc_exact_list_label_is_consumed_before_strict_projection() -> None:- """验证 Roman/复合列表标签优先于通用十进制编号且私有字段被删除。"""-- blocks = [- {- "type": BlockType.LIST,- "attribute": "ordered",- "start": 4,- "ilevel": 0,- "content": [- {"type": BlockType.TEXT, "content": inline("item"), "list_label": "IV."},- ],- }- ]-- assert inline_text(fix_office_list_blocks(blocks)[0]["content"][0]["content"]) == "IV. item"---def test_doc_table_grid_materializes_colspan_and_rowspan() -> None:- """验证 Word table edge 网格能同时恢复横向和纵向合并。"""-- from docvortex.analyzers.native.office.doc.models import DocTableCellFormat- from docvortex.analyzers.native.office.doc.models import DocTableFormat-- first = DocTableCell(blocks=[])- raw_rows = [- _RawTableRow(- [first, DocTableCell()],- DocTableFormat(- boundaries=(0, 100, 200),- cells=(- DocTableCellFormat(100, horizontal_first=True, vertical_first=True),- DocTableCellFormat(200, horizontal_continue=True),- ),- ),- ),- _RawTableRow(- [DocTableCell(), DocTableCell()],- DocTableFormat(- boundaries=(0, 100, 200),- cells=(- DocTableCellFormat(100, vertical_continue=True),- DocTableCellFormat(200),- ),- ),- ),- ]-- rows = _materialize_table_rows(raw_rows, DocBudget())-- assert rows[0].cells[0].col_span == 2- assert rows[0].cells[0].row_span == 2---def test_doc_rejects_word95_encryption_rtf_and_missing_word_stream() -> None:- """验证不支持版本、加密、RTF 冒充和缺失核心 stream 使用稳定错误。"""-- with pytest.raises(LegacyOfficeMalformedError, match="Word 95"):- DocModel().predict(BytesIO(build_doc("old\r", n_fib=0x0065)))- with pytest.raises(LegacyOfficeEncryptedError):- DocModel().predict(BytesIO(build_doc("secret\r", flags_extra=0x0100)))- with pytest.raises(LegacyOfficeMalformedError):- DocModel().predict(BytesIO(b"{\\rtf1 renamed}"))- with pytest.raises(LegacyOfficeMissingPartError):- DocModel().predict(BytesIO(_build_cfb([("1Table", b"table")])))---def test_doc_budget_uses_stable_resource_limit(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 DOC 记录预算超过固定上限时使用共享错误类型。"""-- import docvortex.analyzers.native.office.doc.records as records-- monkeypatch.setattr(records, "MAX_RECORDS", 1)- budget = records.DocBudget()- budget.charge()- with pytest.raises(LegacyOfficeResourceLimitError):- budget.charge()--def test_doc_is_supported_by_public_parser(tmp_path: Path) -> None:"""验证公共 parser 通过统一 MinerUParser 路由 DOC。"""diff --git a/tests/unittest/test_flash_legacy_doc_mtef.py b/tests/unittest/test_flash_legacy_doc_mtef.pyindex 3a3f4c25..dbd85849 100644--- a/tests/unittest/test_flash_legacy_doc_mtef.py+++ b/tests/unittest/test_flash_legacy_doc_mtef.py@@ -1,86 +1,18 @@from __future__ import annotationsimport asyncio-from io import BytesIO-import pytest+from _mtef_test_utils import (+ build_equation_doc,+ formula_corpus,+)from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import DocModel-from docvortex.analyzers.native.office.equation.mtef import decode_equation_native-from docvortex.analyzers.native.office.equation.mtef import decode_equation_object-from docvortex.analyzers.native.office.equation.mtef import decode_mtef_v3from mineru.render.contracts import RenderModefrom mineru.render.html import render_htmlfrom mineru.render.markdown import render_markdownfrom mineru.types import BlockType, MiddleJson, ModelJson-from _mtef_test_utils import (- build_equation_doc,- build_equation_object,- equation_native,- formula_corpus,- mtef_equation,- mtef_line,- mtef_template,- mtef_text,-)--_CAPTURED_EQUATION_NATIVE = bytes.fromhex(- """- 1c0000000200d4c0410000000000000050a414003cbc14000000000003010103- 010a0112836300030f01000b01128376000011000a030f00000b110102883200- 00000a028612220288340012836d0012836b0002863c00028830000000- """-)--- ("name", "mtef", "expected"),- formula_corpus(),- ids=[name for name, _mtef, _expected in formula_corpus()],-)-def test_mtef_v3_corpus_decodes_to_exact_latex(- name: str,- mtef: bytes,- expected: str,-) -> None:- """验证各类手工 MTEF v3 结构精确转换为预期 LaTeX。"""-- assert name- assert decode_mtef_v3(mtef) == expected---def test_equation_native_header_and_standalone_ole_object_decode() -> None:- """验证 28 字节 EQNOLEFILEHDR 和独立 Equation.3 OLE 对象均可读取。"""-- _name, mtef, expected = formula_corpus()[1]- native = equation_native(mtef)- equation_object = build_equation_object(mtef)-- assert decode_equation_native(native) == expected- assert decode_equation_object(equation_object) == expected---def test_captured_equation_editor_native_stream_decodes_independently() -> None:- """验证独立采集的 Equation.3 stream 恢复上下标、减号和关系式。"""-- assert decode_equation_native(_CAPTURED_EQUATION_NATIVE) == "c_{v}^{2}-4mk<0"---def test_equation_editor_object_doc_integrates_as_native_equation_blocks() -> None:- """验证 ObjectPool storage id、字段分隔符和 MTEF 形成完整 DOC 原生公式链。"""-- corpus = formula_corpus()- file_bytes = build_equation_doc([(1000 + index, mtef) for index, (_name, mtef, _expected) in enumerate(corpus)])- stream = BytesIO(file_bytes)-- pages = DocModel().predict(stream)-- assert not stream.closed- assert pages == [[{"type": BlockType.EQUATION, "content": expected} for _name, _mtef, expected in corpus]]- assert all(block.get("type") != BlockType.IMAGE for block in pages[0])-def test_equation_editor_doc_sync_async_middle_json_and_renderers() -> None:"""验证原生公式贯穿同步/异步 Analyze、严格 MiddleJson、Markdown 和 HTML。"""@@ -100,64 +32,3 @@ def test_equation_editor_doc_sync_async_middle_json_and_renderers() -> None:for _name, _mtef, expected in corpus:assert expected in markdownassert expected.replace("&", "&") in html or expected in html---def test_native_equation_wins_over_preview_and_invalid_native_keeps_preview() -> None:- """验证有效 MTEF 抑制缓存图,坏 MTEF 则安全回退到原图片。"""-- _name, mtef, expected = formula_corpus()[0]- native_pages = DocModel().predict(- BytesIO(- build_equation_doc(- [(42, mtef)],- preview_storage_ids={42},- )- )- )- fallback_pages = DocModel().predict(- BytesIO(- build_equation_doc(- [(43, b"invalid MTEF")],- preview_storage_ids={43},- )- )- )-- assert native_pages == [[{"type": BlockType.EQUATION, "content": expected}]]- assert fallback_pages[0][0]["type"] == BlockType.IMAGE- assert fallback_pages[0][0]["image_base64"].startswith("data:image/")--- "payload",- [- b"",- b"\x02\x01\x01\x03\x00\x00",- mtef_equation(mtef_template(49, mtef_line(mtef_text("x")))),- bytes([3, 1, 1, 3, 0, 5, 0, 0, 0, 255, 255]),- bytes([3, 1, 1, 3, 0, 8, 131, 0x41]),- ],-)-def test_invalid_or_unsupported_mtef_fails_closed(payload: bytes) -> None:- """验证截断、未知 template、异常矩阵和坏 FONT 不制造错误 LaTeX。"""-- assert decode_mtef_v3(payload) is None---def test_invalid_equation_native_header_fails_closed() -> None:- """验证错误 header size、版本和对象长度均被拒绝。"""-- _name, mtef, _expected = formula_corpus()[0]- valid = bytearray(equation_native(mtef))- cases: list[bytes] = []- broken = bytearray(valid)- broken[0:2] = (27).to_bytes(2, "little")- cases.append(bytes(broken))- broken = bytearray(valid)- broken[2:6] = (0x0001_0000).to_bytes(4, "little")- cases.append(bytes(broken))- broken = bytearray(valid)- broken[8:12] = (len(mtef) + 100).to_bytes(4, "little")- cases.append(bytes(broken))-- assert all(decode_equation_native(case) is None for case in cases)diff --git a/tests/unittest/test_flash_legacy_ppt.py b/tests/unittest/test_flash_legacy_ppt.pyindex 67191f45..ecadb2c5 100644--- a/tests/unittest/test_flash_legacy_ppt.py+++ b/tests/unittest/test_flash_legacy_ppt.py@@ -1,51 +1,13 @@from __future__ import annotationsimport asyncio-from io import BytesIOfrom pathlib import Path-import struct-import pytest+from _legacy_ppt_test_utils import build_sparse_notes_pptfrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import PptModel-from docvortex.analyzers.native._shared.hyperlink import sanitize_hyperlink_target-from docvortex.analyzers.native.office.errors import LegacyOfficeEncryptedError-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.ppt import parser as ppt_parser-from docvortex.analyzers.native.office.ppt.models import PptPresentation-from docvortex.analyzers.native.office.ppt.models import PptSlide-from docvortex.analyzers.native.office.ppt.ppt_converter import PptConverter-from docvortex.analyzers.native.office.ppt.records import PptRecord-from docvortex.analyzers.native.office.ppt.records import RecordBudget-from docvortex.analyzers.native.office.ppt.style_text import CharacterRun-from docvortex.analyzers.native.office.ppt.style_text import StyleRunsfrom mineru.parser import parse-from mineru.types import BlockType, MiddleJson, ModelJson--from _legacy_ppt_test_utils import build_deep_nested_ppt, build_multimaster_ppt, build_sparse_notes_ppt-from _span_test_utils import inline---def test_ppt_model_preserves_slide_pages_and_sparse_notes() -> None:- """验证旧版 PPT 始终逐 slide 分页,并按 slide id 绑定稀疏备注。"""-- pages = PptModel().predict(BytesIO(build_sparse_notes_ppt()))-- assert len(pages) == 2- assert pages[0] == [{"type": BlockType.TEXT, "content": inline("First slide text")}]- assert pages[1] == [- {"type": BlockType.TEXT, "content": inline("Second slide text")},- {"type": BlockType.PAGE_FOOTNOTE, "content": inline("Notes for the second slide")},- ]---def test_ppt_converter_preserves_empty_slide_positions() -> None:- """验证空白或隐藏 slide 仍在 model-list 中保留对应空页。"""-- presentation = PptPresentation(slides=[PptSlide(slide_id=1), PptSlide(slide_id=2, hidden=True)])-- assert PptConverter._presentation_to_pages(presentation) == [[], []]+from mineru.types import MiddleJson, ModelJsondef test_backend_analyze_accepts_ppt_and_async_contract() -> None:@@ -67,52 +29,6 @@ def test_backend_analyze_accepts_ppt_and_async_contract() -> None:assert async_model_json == model_json-def test_ppt_model_applies_per_slide_master_styles() -> None:- """验证每页按自身 master id 继承 bullet、粗体和斜体,而不是固定首个母版。"""-- pages = PptModel().predict(BytesIO(build_multimaster_ppt()))-- assert pages == [- [- {- "type": BlockType.LIST,- "attribute": "unordered",- "ilevel": 0,- "content": [- {- "type": BlockType.TEXT,- "content": inline("Alpha master body text", styles=["bold"]),- }- ],- }- ],- [- {- "type": BlockType.TEXT,- "content": inline("Beta master body text", styles=["italic"]),- }- ],- ]---def test_ppt_record_depth_is_a_hard_resource_limit() -> None:- """验证恶意深层 PPT records 在递归前触发固定资源限制。"""-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):- PptModel().predict(BytesIO(build_deep_nested_ppt()))---def test_ppt_encryption_marker_is_rejected_before_record_parsing() -> None:- """验证 Current User 加密标志在读取文档记录前返回稳定错误。"""-- current_user = bytearray(20)- struct.pack_into("<H", current_user, 2, 0x0FF6)- struct.pack_into("<I", current_user, 12, 0xF3D1_C4DF)-- with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):- ppt_parser.parse_ppt_document(b"not parsed", current_user=bytes(current_user))--def test_ppt_is_supported_by_public_parser(tmp_path: Path) -> None:"""验证公共 parser 通过统一 MinerUParser 路由 PPT。"""@@ -123,62 +39,3 @@ def test_ppt_is_supported_by_public_parser(tmp_path: Path) -> None:assert result.middle_json.file_suffix == "ppt"assert len(result.pages) == 2---def test_safe_ppt_hyperlink_schemes_are_explicit() -> None:- """验证外链白名单保留 Web/邮件链接并拒绝本地或脚本目标。"""-- assert sanitize_hyperlink_target("https://example.com/a", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) == (- "https://example.com/a"- )- assert sanitize_hyperlink_target("mailto:[email protected]", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) == (- "mailto:[email protected]"- )- assert sanitize_hyperlink_target("file:///tmp/a", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) is None- assert sanitize_hyperlink_target("javascript:alert(1)", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) is None---def test_ppt_hyperlink_range_splits_utf16_and_style_boundaries() -> None:- """验证非 BMP 字符的 UTF-16 链接范围可跨字符样式边界准确拆分。"""-- interactive_atom = struct.pack("<II8x", 0, 7)- container_payload = struct.pack("<HHI", 0, ppt_parser.RT_INTERACTIVE_INFO_ATOM, len(interactive_atom)) + interactive_atom- records = [- PptRecord(- offset=0,- version=0xF,- instance=0,- record_type=ppt_parser.RT_INTERACTIVE_INFO,- payload=container_payload,- ),- PptRecord(- offset=0,- version=0,- instance=0,- record_type=ppt_parser.RT_TEXT_INTERACTIVE_INFO_ATOM,- payload=struct.pack("<II", 1, 4),- ),- ]- spans = ppt_parser._interactive_spans(- records,- {7: "https://example.com"},- RecordBudget(),- )- paragraphs = ppt_parser._build_paragraphs(- "A😀BC",- StyleRuns(- characters=[- CharacterRun(count=3, bold=True),- CharacterRun(count=2, italic=True),- ]- ),- [],- spans,- )-- assert [(run.text, run.bold, run.italic, run.hyperlink) for run in paragraphs[0].runs] == [- ("A", True, False, None),- ("😀", True, False, "https://example.com"),- ("B", False, True, "https://example.com"),- ("C", False, True, None),- ]diff --git a/tests/unittest/test_flash_legacy_xls.py b/tests/unittest/test_flash_legacy_xls.pyindex a9c93872..f61ad11b 100644--- a/tests/unittest/test_flash_legacy_xls.py+++ b/tests/unittest/test_flash_legacy_xls.py@@ -1,63 +1,18 @@from __future__ import annotationsimport asyncio-from io import BytesIOfrom pathlib import Path-import struct--from bs4 import BeautifulSoup-import pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import XlsModel-from docvortex.analyzers.native._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES-from docvortex.analyzers.native._shared.hyperlink import sanitize_hyperlink_target-from docvortex.analyzers.native.office.errors import LegacyOfficeEncryptedError-from docvortex.analyzers.native.office.errors import LegacyOfficeMissingPartError-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.limits import MAX_RECORDS-from docvortex.analyzers.native.office.xls import xls_converter as xls_converter_module-from docvortex.analyzers.native.office.xls.number_format import format_number-from docvortex.analyzers.native.office.xls.number_format import format_text-from docvortex.analyzers.native.office.xls.records import RecordBudget-from mineru.parser import parse-from mineru.types import BlockType, MiddleJson, ModelJsonfrom _legacy_xls_test_utils import (SheetFixture,- biff_record,- build_biff5_xls,build_xls,- continued_rich_sst,- font_record,- formula_number_cell,- formula_string_cell,label_cell,- labelsst_cell,- merged_cells,- rich_sst,- url_hyperlink,)-from _legacy_ppt_test_utils import _build_cfb-from _span_test_utils import inline, inline_text---def test_xls_model_preserves_visible_empty_pages_and_skips_hidden_sheet() -> None:- """验证可见空表保留页位而隐藏 sheet 不输出。"""-- file_bytes = build_xls(- [- SheetFixture("Visible", label_cell(0, 0, "visible")),- SheetFixture("Empty"),- SheetFixture("Secret", label_cell(0, 0, "secret"), visible=False),- ]- )- stream = BytesIO(file_bytes)-- pages = XlsModel().predict(stream)+from _span_test_utils import inline_text- assert not stream.closed- assert pages == [[{"type": BlockType.TEXT, "content": inline("visible")}], []]+from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.parser import parse+from mineru.types import MiddleJson, ModelJsondef test_backend_analyze_accepts_xls_and_async_contract() -> None:@@ -77,232 +32,6 @@ def test_backend_analyze_accepts_xls_and_async_contract() -> None:assert async_middle == middle_json-def test_xls_formula_cache_merge_and_hyperlink_flow_into_table() -> None:- """验证缓存公式、合并结构和安全链接进入同一 HTML 表格。"""-- records = (- label_cell(0, 0, "header")- + label_cell(0, 1, "link")- + formula_number_cell(1, 0, 21.0)- + formula_string_cell(1, 1, "#NAME?")- + url_hyperlink(0, 1, "link", "https://example.test/path")- + merged_cells((2, 0, 2, 1))- + label_cell(2, 0, "merged")- )-- pages = XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)])))- table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)- soup = BeautifulSoup(table["content"], "html.parser")-- assert soup.get_text(" ", strip=True).split() == [- "header",- "link",- "21",- "#NAME?",- "merged",- ]- assert soup.find("a")["href"] == "https://example.test/path"- assert soup.find(string="merged").find_parent(["th", "td"])["colspan"] == "2"---def test_xls_rich_sst_uses_utf16_ranges_across_non_bmp_text() -> None:- """验证非 BMP 字符的 UTF-16 rich run 边界不会偏移。"""-- globals_records = font_record(bold=True) + font_record(italic=True) + rich_sst([("A😀B", [(0, 1), (3, 2)])])- pages = XlsModel().predict(- BytesIO(- build_xls(- [SheetFixture("Rich", labelsst_cell(0, 0, 0))],- globals_records=globals_records,- )- )- )-- table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)- assert "<strong>A😀</strong>" in table["content"]- assert "<em>B</em>" in table["content"]---def test_xls_sst_character_data_can_cross_continue_records() -> None:- """验证 SST 在字符中间切入 CONTINUE 后重读压缩标志并继续 rich runs。"""-- globals_records = font_record(bold=True) + font_record(italic=True) + continued_rich_sst("A😀BC", [(0, 1), (3, 2)])- pages = XlsModel().predict(- BytesIO(- build_xls(- [SheetFixture("Rich", labelsst_cell(0, 0, 0))],- globals_records=globals_records,- )- )- )-- table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)- assert "<strong>A😀</strong>" in table["content"]- assert "<em>BC</em>" in table["content"]--- ("format_code", "value", "expected"),- [- ("0.0%", 0.075, "7.5%"),- ("#,##0.00", 1234.5, "1,234.50"),- ('"$"#,##0.00', 1234.5, "$1,234.50"),- ("0.00;(0.00)", -3.5, "(3.50)"),- ("0.00E+00", 12345.0, "1.23E+04"),- ("# ?/?", 5.25, "5 1/4"),- ("# ?/8", 5.25, "5 2/8"),- ("0.0,,", 12_345_678.0, "12.3"),- ("0.00_);(0.00)", 3.5, "3.50 "),- ('0.0\\ "m/s"', 3.51, "3.5 m/s"),- ('"~"General" kg"', 1234.5, "~1234.5 kg"),- ("yyyy-mm-dd", 46096.0, "2026-03-15"),- ("[h]:mm:ss", 1.5, "36:00:00"),- ],-)-def test_xls_number_formats_match_expected_visible_semantics(- format_code: str,- value: float,- expected: str,-) -> None:- """验证关键数值格式符合预期的稳定显示语义。"""-- assert format_number(value, format_code, date1904=False) == expected---def test_xls_text_format_and_unsafe_hyperlink_fallback() -> None:- """验证文本 section 生效且危险链接降级为普通文本。"""-- assert format_text("hi", '0;0;0;"* "@" *"') == "* hi *"- records = label_cell(0, 0, "unsafe") + url_hyperlink(- 0,- 0,- "unsafe",- "javascript:alert(1)",- )- pages = XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)])))- assert pages == [[{"type": BlockType.TEXT, "content": inline("unsafe")}]]- policy = {- "allowed_schemes": OFFICE_EXTERNAL_HYPERLINK_SCHEMES,- "allow_relative": True,- "allow_fragment": True,- }- assert sanitize_hyperlink_target("mailto:[email protected]", **policy) == "mailto:[email protected]"- assert sanitize_hyperlink_target("#Sheet2!A1", **policy) == "#Sheet2!A1"- assert sanitize_hyperlink_target("../relative/path", **policy) == "../relative/path"- assert sanitize_hyperlink_target("file:///tmp/local.xls", **policy) is None- assert sanitize_hyperlink_target("custom:payload", **policy) is None---def test_xls_filepass_and_broken_boundsheet_behaviors() -> None:- """验证加密硬失败,而损坏 sheet offset 可按 worksheet BOF 恢复。"""-- with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):- XlsModel().predict(BytesIO(build_xls([SheetFixture("Data")], encrypted=True)))-- pages = XlsModel().predict(- BytesIO(- build_xls(- [SheetFixture("Recovered", label_cell(0, 0, "ok"))],- corrupt_first_offset=True,- )- )- )- assert pages == [[{"type": BlockType.TEXT, "content": inline("ok")}]]---def test_xls_encrypted_ooxml_marker_and_missing_workbook_are_stable_errors() -> None:- """验证 OLE 加密包不会误判成 BIFF,缺失 Workbook/Book 返回稳定错误。"""-- encrypted = _build_cfb(- [- ("EncryptionInfo", b"marker"),- ("EncryptedPackage", b"payload"),- ]- )- with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):- XlsModel().predict(BytesIO(encrypted))-- with pytest.raises(LegacyOfficeMissingPartError, match="Book"):- XlsModel().predict(BytesIO(_build_cfb([("Other", b"payload")])))---def test_xls_biff5_codepage_and_hidden_rows_columns_are_preserved() -> None:- """验证 BIFF5 codepage 降级及用户选择的隐藏行列保留策略。"""-- assert XlsModel().predict(BytesIO(build_biff5_xls("légacy"))) == [[{"type": BlockType.TEXT, "content": inline("légacy")}]]-- row = bytearray(16)- struct.pack_into("<H", row, 0, 0)- row[12] = 0x20- colinfo = bytearray(12)- struct.pack_into("<HH", colinfo, 0, 0, 0)- colinfo[8] = 0x01- records = biff_record(0x0208, bytes(row)) + biff_record(0x007D, bytes(colinfo)) + label_cell(0, 0, "still visible")-- assert XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)]))) == [- [{"type": BlockType.TEXT, "content": inline("still visible")}]- ]---def test_xls_record_and_grid_limits_are_hard_failures(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证记录访问与工作簿网格预算均不可静默绕过。"""-- budget = RecordBudget(count=MAX_RECORDS)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):- budget.charge()-- monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 0)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):- XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", label_cell(0, 0, "value"))])))---def test_xls_rejects_oversized_merge_before_openpyxl_materialization(monkeypatch: pytest.MonkeyPatch) -> None:- """验证单个超限 BIFF merge 不会进入 openpyxl 单元格物化。"""- monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 4)-- def unexpected_merge(*_args: object, **_kwargs: object) -> None:- """超限 merge 不得调用 openpyxl。"""- pytest.fail("oversized BIFF merge reached openpyxl materialization")-- monkeypatch.setattr(xls_converter_module.Worksheet, "merge_cells", unexpected_merge)- source = build_xls([SheetFixture("Data", merged_cells((0, 0, 2, 1)))])-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):- XlsModel().predict(BytesIO(source))---def test_xls_charges_cumulative_merge_budget_before_each_materialization(monkeypatch: pytest.MonkeyPatch) -> None:- """验证多个合法 merge 的累计面积会在下一次物化前触发预算。"""- monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 4)- original_merge = xls_converter_module.Worksheet.merge_cells- materialized: list[tuple[object, ...]] = []-- def tracking_merge(self: object, *args: object, **kwargs: object) -> None:- """记录预算内实际进入 openpyxl 的 merge。"""- materialized.append(args or tuple(kwargs.values()))- original_merge(self, *args, **kwargs) # type: ignore[arg-type]-- monkeypatch.setattr(xls_converter_module.Worksheet, "merge_cells", tracking_merge)- source = build_xls(- [- SheetFixture(- "Data",- merged_cells(- (0, 0, 0, 1),- (1, 0, 1, 1),- (2, 0, 2, 1),- ),- )- ]- )-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):- XlsModel().predict(BytesIO(source))- assert len(materialized) == 2--def test_xls_is_supported_by_public_parser(tmp_path: Path) -> None:"""验证公共 parser 通过统一 MinerUParser 路由 XLS。"""diff --git a/tests/unittest/test_flash_legacy_xls_ppt_mtef.py b/tests/unittest/test_flash_legacy_xls_ppt_mtef.pyindex 550314c4..ea44ef9f 100644--- a/tests/unittest/test_flash_legacy_xls_ppt_mtef.py+++ b/tests/unittest/test_flash_legacy_xls_ppt_mtef.py@@ -1,109 +1,14 @@from __future__ import annotationsimport asyncio-from collections.abc import Callable-from io import BytesIOimport pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import PptModel-from docvortex.analyzers.native import XlsModel-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.limits import MAX_ENTRY_BYTES-from mineru.types import BlockType, MiddleJson, ModelJson-from _legacy_ppt_test_utils import build_equation_ppt-from _legacy_xls_test_utils import build_equation_xls, label_cell+from _legacy_xls_test_utils import build_equation_xlsfrom _mtef_test_utils import formula_corpus--def test_xls_equation_editor_corpus_decodes_to_exact_equation_blocks() -> None:- """验证 XLS 的 MBD/OBJ 绑定把完整公式语料恢复为精确 LaTeX。"""-- corpus = formula_corpus()- file_bytes = build_equation_xls(- [(100 + index, mtef) for index, (_name, mtef, _expected) in enumerate(corpus)],- preview=False,- )-- pages = XlsModel().predict(BytesIO(file_bytes))-- assert pages == [[{"type": BlockType.EQUATION, "content": expected} for _name, _mtef, expected in corpus]]---def test_ppt_equation_editor_corpus_stays_bound_to_its_slides() -> None:- """验证 PPT 的 ExObjRef/persist 绑定逐 slide 恢复完整公式语料。"""-- corpus = formula_corpus()- file_bytes = build_equation_ppt(- [mtef for _name, mtef, _expected in corpus],- preview=False,- )-- pages = PptModel().predict(BytesIO(file_bytes))-- assert pages == [[{"type": BlockType.EQUATION, "content": expected}] for _name, _mtef, expected in corpus]---def test_xls_equation_inside_table_is_not_duplicated_as_top_level_block() -> None:- """验证落在表格坐标内的 XLS 公式进入 cell HTML 且不重复输出。"""-- _name, mtef, expected = formula_corpus()[0]- pages = XlsModel().predict(- BytesIO(- build_equation_xls(- [(42, mtef)],- cell_records=label_cell(0, 0, "value"),- )- )- )-- assert len(pages[0]) == 1- assert pages[0][0]["type"] == BlockType.TABLE- assert f"<eq>{expected}</eq>" in pages[0][0]["content"]--- ("model", "valid_file", "invalid_file"),- [- (- XlsModel(),- lambda mtef: build_equation_xls([(42, mtef)]),- lambda: build_equation_xls([(43, b"invalid MTEF")]),- ),- (- PptModel(),- lambda mtef: build_equation_ppt([mtef]),- lambda: build_equation_ppt([b"invalid MTEF"]),- ),- ],- ids=["xls", "ppt"],-)-def test_native_equation_wins_and_invalid_native_keeps_preview(- model: XlsModel | PptModel,- valid_file: Callable[[bytes], bytes],- invalid_file: Callable[[], bytes],-) -> None:- """验证 XLS/PPT 都优先原生公式,坏 MTEF 则保留缓存预览。"""-- _name, mtef, expected = formula_corpus()[1]- native_pages = model.predict(BytesIO(valid_file(mtef)))- fallback_pages = model.predict(BytesIO(invalid_file()))-- assert native_pages == [[{"type": BlockType.EQUATION, "content": expected}]]- assert fallback_pages[0][0]["type"] == BlockType.IMAGE- assert fallback_pages[0][0]["image_base64"].startswith("data:image/")---def test_ppt_uncompressed_equation_storage_is_supported() -> None:- """验证 recInstance=0 的未压缩 ExOleObjStg 同样可以恢复公式。"""-- _name, mtef, expected = formula_corpus()[2]-- pages = PptModel().predict(BytesIO(build_equation_ppt([mtef], compressed=False, preview=False)))-- assert pages == [[{"type": BlockType.EQUATION, "content": expected}]]+from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.types import BlockType, MiddleJson, ModelJson@pytest.mark.parametrize("file_suffix", ["xls", "ppt"])@@ -128,17 +33,3 @@ def test_backend_analyze_preserves_native_equations_sync_and_async(assert middle.pages[0].blocks[0].content == expectedassert async_model == modelassert async_middle == middle---def test_ppt_equation_decompression_honors_shared_entry_limit() -> None:- """验证恶意 ExOleObjStg 声明长度触发稳定资源限制。"""-- _name, mtef, _expected = formula_corpus()[0]- file_bytes = build_equation_ppt(- [mtef],- declared_size=MAX_ENTRY_BYTES + 1,- preview=False,- )-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_entry_bytes"):- PptModel().predict(BytesIO(file_bytes))diff --git a/tests/unittest/test_flash_markup_anchors.py b/tests/unittest/test_flash_markup_anchors.pydeleted file mode 100644index 47b32518..00000000--- a/tests/unittest/test_flash_markup_anchors.py+++ /dev/null@@ -1,154 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass--from lxml import etree--from docvortex.analyzers.native._shared.markup import AnchorVisibilityScope-from docvortex.analyzers.native._shared.markup import MarkupAnchorDocument-from docvortex.analyzers.native._shared.markup import MarkupAnchorRegistry-from docvortex.analyzers.native._shared.markup import MarkupStylesheet-from docvortex.analyzers.native._shared.markup import canonical_anchor-from docvortex.analyzers.native._shared.markup import element_id-from docvortex.analyzers.native._shared.markup import visible_element_text---@dataclass(frozen=True, slots=True)-class _TestAnchorPolicy:- """为共享 anchor 单元测试提供可切换的脚注语义策略。"""-- anchor_prefix: str = "test"- register_document_start: bool = True- note_marker: str = "primary"-- @staticmethod- def heading_identity(element: etree._Element, ordinal: int) -> str:- """按源 ID 与文档内序号生成测试标题 identity。"""- return f"heading-{element_id(element) or 'anonymous'}-{ordinal}"-- def is_materializable_note(self, element: etree._Element, document: MarkupAnchorDocument) -> bool:- """只登记匹配当前策略且具有最终可见文本的测试脚注。"""- return element.get("data-note") == self.note_marker and bool(visible_element_text(element, document))-- @staticmethod- def note_identity(element: etree._Element, ordinal: int) -> str:- """按源 ID 与文档内序号生成测试脚注 identity。"""- return f"note-{element_id(element) or 'anonymous'}-{ordinal}"---def _document(- key: str,- root: etree._Element,- *,- visibility_scope: AnchorVisibilityScope = "all_ancestors",-) -> MarkupAnchorDocument:- """用空样式表构造一份共享 anchor 测试文档。"""- return MarkupAnchorDocument(- key=key,- root=root,- stylesheet=MarkupStylesheet(),- visibility_scope=visibility_scope,- )---def test_markup_anchor_element_id_and_canonical_digest_are_stable() -> None:- """验证 id/xml:id 优先级、空白清理及二十位 SHA-256 anchor 契约。"""- html_id = etree.fromstring(b'<p id=" html-id " xml:id="xml-id"/>')- xml_id = etree.fromstring(b'<p xml:id="xml-only"/>')- anonymous = etree.fromstring(b"<p/>")-- assert element_id(html_id) == "html-id"- assert element_id(xml_id) == "xml-only"- assert element_id(anonymous) is None- assert canonical_anchor("epub", "EPUB/text/ch1.xhtml", "chapter-one-0") == "epub-1daacccca5bf43833643"- assert canonical_anchor("html", "html", "heading-top-0") == "html-39fc7010518f54fa3fa9"---def test_markup_anchor_registry_filters_hidden_targets_and_keeps_visible_descendants() -> None:- """验证隐藏标题/脚注不注册,而 visibility:visible 后代仍可提供可落地文本。"""- root = etree.fromstring(- b"""<html><body>- <h1 id="visible">Visible title</h1>- <h2 id="hidden" hidden="hidden">Hidden title</h2>- <h3 id="recovered" style="visibility:hidden">Hidden <span style="visibility:visible">Recovered title</span></h3>- <aside id="visible-note" data-note="primary">Visible note</aside>- <aside id="hidden-note" data-note="primary" style="display:none">Hidden note</aside>- <aside data-note="primary" style="visibility:hidden"><span style="visibility:visible">Recovered note</span></aside>- </body></html>"""- )- registry = MarkupAnchorRegistry([_document("doc", root)], _TestAnchorPolicy())- elements = {element_id(element): element for element in root.iter() if element_id(element) is not None}- anonymous_note = next(element for element in root.iter("aside") if element_id(element) is None)-- visible_anchor = registry.heading_anchor(elements["visible"])- recovered_anchor = registry.heading_anchor(elements["recovered"])- assert visible_anchor is not None- assert recovered_anchor is not None- assert registry.heading_label(visible_anchor) == "Visible title"- assert registry.heading_label(recovered_anchor) == "Recovered title"- assert registry.heading_anchor(elements["hidden"]) is None- assert registry.resolve_target("doc", "hidden") is None- assert registry.note_anchor(elements["visible-note"]) is not None- assert registry.note_anchor(elements["hidden-note"]) is None- assert registry.note_anchor(anonymous_note) is not None---def test_markup_anchor_registry_resolves_direct_ancestor_descendant_and_duplicate_fragments() -> None:- """验证 fragment 依次映射到直接、最近祖先和首个后代目标,且重复 ID 首个映射优先。"""- first_root = etree.fromstring(- b"""<body>- <h1 id="direct">Direct</h1>- <h2>Ancestor target <span id="inside-heading">inside</span></h2>- <section id="container"><h3>Descendant target</h3></section>- <section id="duplicate"><h4>First duplicate</h4></section>- <h5 id="duplicate">Second duplicate</h5>- </body>"""- )- second_root = etree.fromstring(b'<body><h1 id="direct">Other document</h1></body>')- first_document = _document("doc-a", first_root)- second_document = _document("doc-b", second_root)- registry = MarkupAnchorRegistry([first_document, second_document], _TestAnchorPolicy())- headings = list(first_root.iter("h1", "h2", "h3", "h4", "h5"))- second_heading = next(second_root.iter("h1"))-- assert registry.resolve_target("doc-a", "direct") == registry.heading_anchor(headings[0])- assert registry.resolve_target("doc-a", "inside-heading") == registry.heading_anchor(headings[1])- assert registry.resolve_target("doc-a", "container") == registry.heading_anchor(headings[2])- assert registry.resolve_target("doc-a", "duplicate") == registry.heading_anchor(headings[3])- assert registry.resolve_target("doc-a", "duplicate") != registry.heading_anchor(headings[4])- assert registry.resolve_target("doc-b", "direct") == registry.heading_anchor(second_heading)- assert registry.resolve_target("doc-a", None) == registry.heading_anchor(headings[0])- assert registry.resolve_target("doc-b", None) == registry.heading_anchor(second_heading)---def test_markup_anchor_document_start_visibility_scope_and_policy_do_not_leak() -> None:- """验证可选文档起点、祖先范围和不同脚注 policy 彼此隔离。"""- root = etree.fromstring(- b"""<html hidden="hidden"><body><h1 id="title">Visible in body scope</h1>- <aside id="primary" data-note="primary">Primary note</aside>- <aside id="secondary" data-note="secondary">Secondary note</aside>- </body></html>"""- )- all_ancestors = _document("all", root)- body_scope = _document("body", root, visibility_scope="nearest_body")- assert visible_element_text(next(root.iter("h1")), all_ancestors) == ""- assert visible_element_text(next(root.iter("h1")), body_scope) == "Visible in body scope"-- primary = MarkupAnchorRegistry(- [body_scope],- _TestAnchorPolicy(anchor_prefix="primary", register_document_start=False, note_marker="primary"),- )- secondary = MarkupAnchorRegistry(- [body_scope],- _TestAnchorPolicy(anchor_prefix="secondary", register_document_start=True, note_marker="secondary"),- )- elements = {element_id(element): element for element in root.iter() if element_id(element) is not None}-- assert primary.resolve_target("body", None) is None- assert secondary.resolve_target("body", None) == secondary.heading_anchor(elements["title"])- assert primary.note_anchor(elements["primary"]) is not None- assert primary.note_anchor(elements["secondary"]) is None- assert secondary.note_anchor(elements["primary"]) is None- assert secondary.note_anchor(elements["secondary"]) is not None- assert primary.note_anchor(elements["primary"]).startswith("primary-") # type: ignore[union-attr]- assert secondary.note_anchor(elements["secondary"]).startswith("secondary-") # type: ignore[union-attr]diff --git a/tests/unittest/test_flash_model.py b/tests/unittest/test_flash_model.pyindex 60a5db06..6d32ff7d 100644--- a/tests/unittest/test_flash_model.py+++ b/tests/unittest/test_flash_model.py@@ -1,40 +1,9 @@from __future__ import annotationsimport importlib-from unittest.mock import MagicMockimport pytest-from docvortex.analyzers.native import PdfModel-from docvortex.analyzers.native.pdf import pipeline-from docvortex.document.pdf.document import PDFDocument---def test_pdf_model_predict_returns_native_model_list_without_owning_document(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证模型传递同一 PDFDocument,且不负责分类或关闭调用方文档。"""-- pdf_doc = MagicMock(spec=PDFDocument)- expected_model_list = [[{"type": "text", "content": "native"}]]- native_analyze = MagicMock(return_value=expected_model_list)- monkeypatch.setattr(pipeline, "_analyze_native_document", native_analyze)-- result = PdfModel().predict(pdf_doc)-- assert result is expected_model_list- native_analyze.assert_called_once_with(pdf_doc)- pdf_doc.classify.assert_not_called()- pdf_doc.close.assert_not_called()---def test_pdf_model_is_public_and_old_flash_model_is_removed() -> None:- """验证 PdfModel 公开可用,旧 FlashModel 名称不再兼容。"""-- flash_module = importlib.import_module("docvortex.analyzers.native")- assert flash_module.PdfModel is PdfModel- assert not hasattr(flash_module, "FlashModel")-def test_old_backend_native_pdf_import_is_removed() -> None:"""验证旧 backend native_pdf 路径不再兼容。"""diff --git a/tests/unittest/test_flash_mtef_v5.py b/tests/unittest/test_flash_mtef_v5.pydeleted file mode 100644index 1c804515..00000000--- a/tests/unittest/test_flash_mtef_v5.py+++ /dev/null@@ -1,316 +0,0 @@-from __future__ import annotations--import struct--import pytest--from docvortex.analyzers.native.office.equation import mtef_v5 as mtef_v5_module-from docvortex.analyzers.native.office.equation import mtef as mtef_module-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.equation.mtef import decode_equation_native-from docvortex.analyzers.native.office.equation.mtef import decode_equation_object-from docvortex.analyzers.native.office.equation.mtef import decode_mtef-from docvortex.analyzers.native.office.equation.mtef import decode_mtef_v3-from docvortex.analyzers.native.office.equation.mtef import decode_mtef_v5--from _mtef_test_utils import build_equation_object, equation_native, formula_corpus-from _mtef_v5_test_utils import (- v5_char,- v5_encoding_definition,- v5_equation,- v5_equation_preferences,- v5_font_definition,- v5_font_style_definition,- v5_formula_corpus,- v5_future_record,- v5_line,- v5_template,- v5_template_corpus,- v5_text,-)--# WIRIS MTEF v5 页面公布的 MathType 7 二次公式字节表。原网页第 133 行-# 被帮助文本覆盖,按 dimension nibble padding 归一化为 0;第 255 行误插入-# 的 HTML “&” 字节不属于 CHAR record,构造 golden 时予以移除。-_WIRIS_QUADRATIC_MTEF = bytes.fromhex(- "050100070044534d543700001357696e416c6c4261736963436f646550616765"- "7300110554696d6573204e657720526f6d616e00110353796d626f6c00110543"- "6f7572696572204e65770011044d5420457874726100120008212f458f442f41"- "50f4100f475f4150f21f1e4150f4150f4100f445f425f48f425f4100f4100f43"- "5f4100f21f00a5f20a25f48f41f4100f4000f40f48f417f48f4000f21a5f445f"- "45f45f45f45f410f0c0100010001020202020002000101010003000100040000"- "0a010003000b0000010002048612222d0200836200020486b100b103000a0000"- "0100020083620003001c00000b01010100020088320000000a02048612222d02"- "0088340002008361000200836300000b010100000a0100020088320002008361"- "0000000000"-)--- ("name", "mtef", "expected"),- v5_formula_corpus(),- ids=[name for name, _mtef, _expected in v5_formula_corpus()],-)-def test_mtef_v5_corpus_decodes_to_exact_latex(- name: str,- mtef: bytes,- expected: str,-) -> None:- """验证常见 MTEF v5 字符、模板、PILE 和 MATRIX 精确输出。"""-- assert name- assert decode_mtef_v5(mtef) == expected- assert decode_mtef(mtef) == expected--- ("name", "mtef", "expected"),- v5_template_corpus(),- ids=[name for name, _mtef, _expected in v5_template_corpus()],-)-def test_mtef_v5_template_selectors_decode_to_exact_latex(- name: str,- mtef: bytes,- expected: str,-) -> None:- """验证标准 fence、bar、big-op、script、vector 和 box templates。"""-- assert name- assert decode_mtef_v5(mtef) == expected---def test_mtef_dispatch_keeps_v3_and_rejects_v4() -> None:- """验证通用入口只按 header 分派 v3/v5,v3 输出保持不变。"""-- _name, v3, expected = formula_corpus()[1]-- assert decode_mtef(v3) == expected- assert decode_mtef_v3(v3) == expected- assert decode_mtef(bytes([4, 1, 0, 3, 5, 0])) is None---def test_wiris_mathtype_7_quadratic_golden_decodes_exactly() -> None:- """验证 WIRIS 公布的真实 MathType 7 v5 字节流恢复二次公式。"""-- assert decode_mtef_v5(_WIRIS_QUADRATIC_MTEF) == (- r"\frac{-\mathit{b}\pm \sqrt{\mathit{b}^{2}-4"- r"\mathit{a}\mathit{c}}}{2\mathit{a}}"- )---def test_equation_native_and_ole_object_decode_mtef_v5() -> None:- """验证 EQNOLEFILEHDR 与独立 OLE 对象均按首字节解码 v5。"""-- _name, mtef, expected = v5_formula_corpus()[1]-- assert decode_equation_native(equation_native(mtef)) == expected- assert decode_equation_object(build_equation_object(mtef)) == expected---def test_mtef_v5_known_symbol_font_position_and_style_definitions() -> None:- """验证无 MTCode 的 Symbol position 及显式 FONT_STYLE_DEF 粗体。"""-- symbol = v5_char(- "x",- typeface=6,- font_position=0x61,- omit_mtcode=True,- )- definitions = (- v5_encoding_definition("WinAllBasicCodePages"),- v5_font_definition(5, "Times New Roman"),- v5_font_style_definition(1, 1),- )- bold = v5_char("x", typeface=-1)- mt_extra = v5_char(- "x",- typeface=11,- font_position=0x68,- omit_mtcode=True,- )-- assert decode_mtef_v5(v5_equation(symbol)) == r"\alpha"- assert decode_mtef_v5(v5_equation(bold, definitions=definitions)) == r"\mathbf{x}"- assert decode_mtef_v5(v5_equation(mt_extra)) == r"\hbar"--- ("mtcode", "expected"),- [- (0xE930, r"\leqslant"),- (0xF000, r"\mathfrak{A}"),- (0xF01A, r"\mathfrak{a}"),- (0xF080, r"\mathbb{A}"),- (0xF100, r"\mathcal{A}"),- ],-)-def test_mtef_v5_common_private_mtcode_mapping(- mtcode: int,- expected: str,-) -> None:- """验证常见 MathType PUA 关系符和数学字母可稳定映射。"""-- record = b"\x02\x00\x83" + struct.pack("<H", mtcode)-- assert decode_mtef_v5(v5_equation(record)) == expected--- ("embellishment", "expected"),- [- (7, "{}'x"),- (14, r"\overrightharpoon{x}"),- (15, r"\overleftharpoon{x}"),- (21, r"\xcancel{x}"),- (29, r"\underline{x}"),- (33, r"\underrightarrow{x}"),- ],-)-def test_mtef_v5_extended_embellishment_mapping(- embellishment: int,- expected: str,-) -> None:- """验证 v5 新增的反向 prime、harpoon、strike 和下方修饰符。"""-- assert decode_mtef_v5(v5_equation(v5_char("x", embellishments=(embellishment,)))) == expected---def test_mtef_v5_16bit_font_position_and_large_future_record() -> None:- """验证 16 位 font position 和三字节 future length 保持同步。"""-- definitions = (- v5_font_definition(1, "MTCode Font"),- v5_font_style_definition(1, 0),- )- alpha = v5_char(- "x",- typeface=-1,- font_position=0x03B1,- omit_mtcode=True,- )- mtef = v5_equation(- v5_future_record(b"x" * 300),- alpha,- definitions=definitions,- )-- assert decode_mtef_v5(mtef) == r"\alpha"---def test_mtef_v5_color_and_size_metadata_stays_synchronized() -> None:- """验证 COLOR_DEF、COLOR 和 SIZE 只校验结构而不改变公式内容。"""-- color_definition = b"\x10\x00" + struct.pack("<HHH", 0, 0, 0)- color_reference = b"\x0f\x01"- size = b"\x09\x00\x80"-- assert (- decode_mtef_v5(- v5_equation(- v5_char("x"),- definitions=(color_definition, color_reference, size),- )- )- == "x"- )- assert decode_mtef_v5(v5_equation(v5_char("x"), definitions=(color_reference,))) is None---def test_mtef_v5_function_start_groups_function_style_characters() -> None:- """验证 FUNC_START 将连续 FUNCTION 字符恢复为 LaTeX operator。"""-- function = (- v5_char("s", typeface=2, function_start=True) + v5_char("i", typeface=2) + v5_char("n", typeface=2) + v5_char("x")- )-- assert decode_mtef_v5(v5_equation(function)) == r"\sin x"---def test_mtef_v5_text_style_groups_and_escapes_visible_text() -> None:- """验证 TEXT/TEXT_FE 连续字符使用单一 text 节点并安全转义。"""-- assert decode_mtef_v5(v5_equation(v5_text("rate_1 & rate_2", typeface=1))) == r"\text{rate\_1 \& rate\_2}"--- "payload",- [- b"",- b"\x05\x01\x00\x07\x00unterminated",- v5_equation(v5_template(35, v5_line(v5_char("x")))),- v5_equation(v5_template(37, v5_line(v5_char("x")), variation=1)),- v5_equation(v5_char("\ue000")),- v5_equation(v5_char("x", font_position=1, omit_mtcode=True, typeface=11)),- v5_equation(b"\x14"),- v5_equation(b"\x64\xff\xff\xff"),- v5_equation(b"\x02\x14\x83\x78\x00\x01\x00"),- v5_equation(b"\x02\x00\x80\x78\x00"),- v5_equation(b"\x06\x00\x02"),- v5_equation(b"\x05\x00\x00\x02\x00\x00\x01"),- v5_equation(v5_char("x")) + b"\x00",- ],-)-def test_mtef_v5_invalid_or_unsupported_payload_fails_closed(- payload: bytes,-) -> None:- """验证坏 header、未知语义、PUA、MTExtra 和尾随字节不生成残缺 LaTeX。"""-- assert decode_mtef_v5(payload) is None---def test_every_strict_prefix_of_mtef_v5_fails_closed() -> None:- """验证任意位置截断的 v5 对象都不会输出部分公式。"""-- _name, mtef, _expected = v5_formula_corpus()[1]-- assert all(decode_mtef_v5(mtef[:end]) is None for end in range(len(mtef)))---def test_mtef_v5_invalid_equation_native_lengths_fail_closed() -> None:- """验证 v5 仍受 EQNOLEFILEHDR 对象边界约束。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- native = bytearray(equation_native(mtef))- struct.pack_into("<I", native, 8, len(mtef) + 1)-- assert decode_equation_native(bytes(native)) is None---def test_mtef_v5_record_and_depth_limits_raise_stable_error(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 v5 record/depth 超限抛稳定 resource-limit 错误。"""-- monkeypatch.setattr(mtef_v5_module, "MAX_RECORDS", 2)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):- decode_mtef_v5(v5_equation(v5_char("x")))-- monkeypatch.setattr(mtef_v5_module, "MAX_RECORDS", 100)- monkeypatch.setattr(mtef_v5_module, "MAX_RECORD_DEPTH", 1)- nested = v5_equation(v5_template(11, v5_line(v5_char("a")), v5_line(v5_char("b"))))- with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):- decode_mtef_v5(nested)---def test_mtef_v3_record_and_depth_limits_also_raise_stable_error(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证共享资源超限语义同时覆盖原有 v3 reader。"""-- _name, mtef, _expected = formula_corpus()[1]- monkeypatch.setattr(mtef_module, "MAX_RECORDS", 2)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):- decode_mtef_v3(mtef)-- monkeypatch.setattr(mtef_module, "MAX_RECORDS", 100)- monkeypatch.setattr(mtef_module, "MAX_RECORD_DEPTH", 0)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):- decode_mtef_v3(mtef)---def test_mtef_v5_equation_preferences_style_reference_is_validated() -> None:- """验证 EQN_PREFS style 引用不存在的 FONT_DEF 时整体回退。"""-- invalid_preferences = v5_equation_preferences([(1, 0)])-- assert decode_mtef_v5(v5_equation(v5_char("x"), definitions=(invalid_preferences,))) is Nonediff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex f2f14c86..59102180 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -1,44 +1,25 @@from __future__ import annotationsimport asyncio-import importlib.utilimport json-import subprocess-import sysfrom io import BytesIOfrom pathlib import Pathfrom typing import Any-from zipfile import ZIP_DEFLATED, ZipFileimport pytest-from lxml import etree+from _odf_test_utils import build_odf_package, build_odp_fixture, build_ods_fixture, build_odt_fixture+from docvortex.analyzers.native import OdpModel, OdsModel, OdtModel+from docvortex.analyzers.native.office.odf.metadata import MAX_ODT_METADATA_PAGE_COUNT, extract_odf_metadata+from docvortex.document.detection import guess_suffix_by_path-import docvortex.analyzers.native.office.odf.table as odf_table_module-import docvortex.analyzers.native.office.odf.text as odf_text_modulefrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.db import DatabaseManager+from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.fts import FTSManagerfrom mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestError-from docvortex.analyzers.native import OdpModel-from docvortex.analyzers.native import OdsModel-from docvortex.analyzers.native import OdtModel-from docvortex.analyzers.native.office.odf.errors import OdfEncryptedError-from docvortex.analyzers.native.office.odf.errors import OdfParseError-from docvortex.analyzers.native.office.odf.errors import OdfResourceLimitError-from docvortex.analyzers.native.office.odf.metadata import MAX_ODT_METADATA_PAGE_COUNT-from docvortex.analyzers.native.office.odf.metadata import extract_odf_metadata-from docvortex.analyzers.native.office.odf.package import OdfPackage-from mineru.parser import parse, parse_async-from mineru.parser import api_server+from mineru.parser import api_server, parse, parse_asyncfrom mineru.parser.api_server import CreateJobRequest, FileStore-from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_path-from mineru.render import render_docx, render_html, render_markdown, render_structured_content-from mineru.types import BlockType--from _odf_test_utils import _PIXEL_PNG, build_odf_package, build_odp_fixture, build_ods_fixture, build_odt_fixture-from _span_test_utils import inline, inline_text, visible_content@pytest.mark.parametrize(@@ -48,6 +29,7 @@ from _span_test_utils import inline, inline_text, visible_content("ods", OdsModel, build_ods_fixture(), 2),("odp", OdpModel, build_odp_fixture(), 3),],+ ids=["odt", "ods", "odp"],)def test_odf_models_and_analyze_keep_flash_contract(suffix: str,@@ -72,560 +54,6 @@ def test_odf_models_and_analyze_keep_flash_contract(assert model.extensions["mineru"]["parse_mode"] == middle.extensions["mineru"]["parse_mode"] == "txt"-def test_odt_recovers_structure_and_all_renderers() -> None:- """验证 ODT 标题、富文本、列表、合并表、连续排版、脚注、公式和图片。"""- middle, model = doc_analyze(build_odt_fixture(), file_suffix="odt")- raw_blocks = [block for page in model.pages for block in page]- raw_types = [block["type"] for block in raw_blocks]- assert len(model.pages) == 1- assert BlockType.DOC_TITLE in raw_types- assert BlockType.PARAGRAPH_TITLE in raw_types- assert BlockType.LIST in raw_types- assert BlockType.TABLE in raw_types- assert BlockType.EQUATION in raw_types- assert BlockType.IMAGE in raw_types- assert BlockType.PAGE_FOOTNOTE in raw_types- assert BlockType.HEADER in raw_types- assert BlockType.FOOTER in raw_types- assert any(- any(isinstance(span, dict) and "bold" in span.get("styles", []) for span in block.get("content", []))- for block in raw_blocks- if isinstance(block.get("content"), list)- )- assert any(- "rowspan" not in str(block.get("content")) and 'colspan="2"' in str(block.get("content")) for block in raw_blocks- )- assert any(block.get("content") == r"\frac{x}{2}" for block in raw_blocks)- assert any(- block.get("type") == BlockType.PAGE_FOOTNOTE and "Note body" in visible_content(block.get("content"))- for block in raw_blocks- )-- markdown = render_markdown(middle)- html_output = render_html(middle)- structured = render_structured_content(middle)- assert "ODT Title" in markdown- assert "<script>alert(1)</script>" not in markdown- assert "<script>alert(1)</script>" not in html_output- assert "<table" in html_output- assert structured["pages"][0]["blocks"][0]["type"] == "doc_title"---def test_odt_promotes_numbered_heading_inside_list() -> None:- """验证 LibreOffice 编码在 list-item 中的 text:h 恢复为编号章节标题。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">- <office:automatic-styles><text:list-style style:name="L1">- <text:list-level-style-number text:level="1" style:num-format="1"/>- </text:list-style></office:automatic-styles>- <office:body><office:text><text:list text:style-name="L1"><text:list-item>- <text:h text:outline-level="1">Chapter</text:h>- </text:list-item></text:list></office:text></office:body>-</office:document-content>"""- middle, _ = doc_analyze(build_odf_package("odt", content), file_suffix="odt")- assert middle.pages[0].blocks[0].type == BlockType.PARAGRAPH_TITLE- assert inline_text(middle.pages[0].blocks[0].content) == "1 Chapter" # type: ignore[union-attr]---def test_odt_inherits_document_title_semantics_from_parent_style() -> None:- """验证自定义段落样式沿 parent-style-name 继承标准文档标题语义。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:p text:style-name="CustomTitle">Inherited title</text:p></office:text></office:body>-</office:document-content>"""- styles = """<office:document-styles- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">- <office:styles>- <style:style style:name="Title" style:display-name="Title" style:family="paragraph"/>- <style:style style:name="CustomTitle" style:family="paragraph" style:parent-style-name="Title"/>- </office:styles>-</office:document-styles>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))-- assert pages == [[{"type": BlockType.DOC_TITLE, "level": 1, "content": inline("Inherited title")}]]---def test_odt_preserves_explicit_space_count() -> None:- """验证 text:s 的显式重复空格不会被普通 XML 空白规则折叠。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:p>A<text:s text:c="4"/>B</text:p></office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("A B")}]]---def test_odt_bounds_overlong_explicit_space_count_before_integer_conversion() -> None:- """验证超长 text:c 在整数转换前按单节点上限截断,不依赖解释器数字保护。"""- assert odf_text_module._positive_space_count("9" * 100_000) == 10_000- assert odf_text_module._positive_space_count("+0004") == 4- assert odf_text_module._positive_space_count("-4") == 1---def test_odt_explicit_space_expansion_uses_document_budget(monkeypatch: pytest.MonkeyPatch) -> None:- """验证多个 text:s 共享文档级预算,并在超限分配前稳定失败。"""- monkeypatch.setattr(odf_text_module, "MAX_EXPANSION_TEXT_BYTES", 5)- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text>- <text:p>A<text:s text:c="3"/>B</text:p><text:p>C<text:s text:c="3"/>D</text:p>- </office:text></office:body>-</office:document-content>"""-- with pytest.raises(OdfResourceLimitError, match="max_expansion_text_bytes=5"):- OdtModel().predict(BytesIO(build_odf_package("odt", content)))---def test_odt_list_lifts_visual_blocks_outside_strict_list() -> None:- """验证列表段落图片保留原类型并提升为 LIST 的有序兄弟块。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:automatic-styles><text:list-style style:name="L1">- <text:list-level-style-number text:level="1" style:num-format="1"/>- </text:list-style></office:automatic-styles>- <office:body><office:text><text:list text:style-name="L1"><text:list-item text:start-value="3">- <text:p>Illustrated item<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame></text:p>- </text:list-item><text:list-item><text:p>Next item</text:p></text:list-item></text:list></office:text></office:body>-</office:document-content>"""-- middle, _ = doc_analyze(- build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG}),- file_suffix="odt",- )-- assert [block.type for block in middle.pages[0].blocks] == [BlockType.LIST, BlockType.IMAGE, BlockType.LIST]- assert [inline_text(child.content) for child in middle.pages[0].blocks[0].content] == [ # type: ignore[union-attr]- "3. Illustrated item"- ]- assert [inline_text(child.content) for child in middle.pages[0].blocks[2].content] == ["4. Next item"] # type: ignore[union-attr]---def test_odt_ordered_list_normalizes_marker_format_and_item_restarts() -> None:- """验证 ODF 列表只保留列表级 start,并连续输出阿拉伯序号。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">- <office:automatic-styles><text:list-style style:name="L1">- <text:list-level-style-number text:level="1" style:num-format="A" style:num-prefix="(" style:num-suffix=")"/>- </text:list-style></office:automatic-styles>- <office:body><office:text><text:list text:style-name="L1">- <text:list-item text:start-value="2"><text:p>First</text:p></text:list-item>- <text:list-item text:start-value="9"><text:p>Second</text:p></text:list-item>- <text:list-item><text:p>Third</text:p></text:list-item>- </text:list></office:text></office:body>-</office:document-content>"""- middle, _ = doc_analyze(build_odf_package("odt", content), file_suffix="odt")- expected = ["2. First", "3. Second", "4. Third"]- list_block = middle.pages[0].blocks[0]-- assert [inline_text(child.content) for child in list_block.content] == expected # type: ignore[union-attr]- assert render_markdown(middle).splitlines() == expected- assert all(label in render_html(middle, standalone=False) for label in ("First", "Second", "Third"))- structured = render_structured_content(middle)- assert structured["pages"][0]["blocks"][0]["content"] == "\n".join(expected)- with ZipFile(BytesIO(render_docx(middle))) as package:- document_xml = package.read("word/document.xml").decode("utf-8")- document_root = etree.fromstring(document_xml.encode("utf-8"))- paragraph_texts = ["".join(paragraph.itertext()) for paragraph in document_root.xpath("//*[local-name()='p']")]- assert all(label in paragraph_texts for label in expected)---def test_odt_list_item_joins_multiple_paragraphs_before_markers() -> None:- """验证一个源 list-item 的多个段落只生成一个 LIST 文本叶子和一个 marker。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:list>- <text:list-item><text:p>First paragraph</text:p><text:p>Second paragraph</text:p></text:list-item>- <text:list-item><text:p>Next item</text:p></text:list-item>- </text:list></office:text></office:body>-</office:document-content>"""-- middle, _ = doc_analyze(build_odf_package("odt", content), file_suffix="odt")- list_block = middle.pages[0].blocks[0]-- assert list_block.type == BlockType.LIST- assert [inline_text(child.content) for child in list_block.content] == [ # type: ignore[union-attr]- "- First paragraph\nSecond paragraph",- "- Next item",- ]- assert render_markdown(middle).count("- ") == 2---def test_odt_table_cell_renders_inline_image_once() -> None:- """验证 ODT/ODP 单元格内联图片不会再被对应段外 image block 重复输出。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><table:table><table:table-row><table:table-cell>- <text:p>Cell<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame></text:p>- </table:table-cell></table:table-row></table:table></office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})))-- assert pages[0][0]["type"] == BlockType.TABLE- assert pages[0][0]["content"].count("<img") == 1---def test_odt_soft_page_break_is_ignored_with_inline_visual() -> None:- """验证 soft-page-break 不拆页、不换行且段内视觉块继续保留。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p>- Before<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame><text:soft-page-break/>After- </text:p></office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})))-- assert [[block["type"] for block in page] for page in pages] == [[BlockType.TEXT, BlockType.IMAGE]]- assert inline_text(pages[0][0]["content"]) == "BeforeAfter"---def test_odt_list_ignores_soft_page_break_and_keeps_note_on_current_page() -> None:- """验证列表软分页不拆页,连续文本与脚注仍保留在当前章节页。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:list>- <text:list-item><text:p>Before<text:soft-page-break/>After- <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>After note</text:p></text:note-body></text:note>- </text:p></text:list-item>- <text:list-item><text:p>Next</text:p></text:list-item>- </text:list></office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert len(pages) == 1- assert pages[0][0]["type"] == BlockType.LIST- assert [inline_text(child["content"]) for child in pages[0][0]["content"]] == ["BeforeAfter [1]", "Next"]- assert pages[0][1] == {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] After note")}---def test_odt_ignores_physical_breaks_and_pages_only_on_master_change() -> None:- """验证普通分页样式无效,只有 master-page 章节变化形成虚拟页。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">- <office:automatic-styles>- <style:style style:name="ChapterA" style:family="paragraph" style:master-page-name="MasterA"/>- <style:style style:name="PhysicalBreak" style:family="paragraph" style:parent-style-name="ChapterA">- <style:paragraph-properties fo:break-before="page" fo:break-after="page"/>- </style:style>- <style:style style:name="ChapterB" style:family="paragraph" style:master-page-name="MasterB"/>- </office:automatic-styles>- <office:body><office:text>- <text:p text:style-name="ChapterA">Before<text:soft-page-break/>Soft</text:p>- <text:section><text:p text:style-name="PhysicalBreak">Physical</text:p></text:section>- <text:p text:style-name="ChapterB">After</text:p>- </office:text></office:body>-</office:document-content>"""- styles = """<office:document-styles- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:master-styles>- <style:master-page style:name="MasterA"><style:header><text:p>Header A</text:p></style:header></style:master-page>- <style:master-page style:name="MasterB"><style:header><text:p>Header B</text:p></style:header></style:master-page>- </office:master-styles>-</office:document-styles>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))-- assert [[visible_content(block.get("content")) for block in page] for page in pages] == [- ["BeforeSoft", "Physical", "Header A"],- ["After", "Header B"],- ]---def test_odt_list_master_changes_split_pages_and_preserve_numbering_notes() -> None:- """验证列表条目中的 master 变化会切页并保持编号、脚注和页眉归属。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:automatic-styles>- <style:style style:name="A" style:family="paragraph" style:master-page-name="MasterA"/>- <style:style style:name="B" style:family="paragraph" style:master-page-name="MasterB"/>- <text:list-style style:name="L1">- <text:list-level-style-number text:level="1" style:num-format="1" text:start-value="3"/>- </text:list-style>- </office:automatic-styles>- <office:body><office:text>- <text:p text:style-name="A">Before list</text:p>- <text:list text:style-name="L1">- <text:list-item><text:p>First <text:note><text:note-citation>1</text:note-citation>- <text:note-body><text:p>First note</text:p></text:note-body></text:note></text:p></text:list-item>- <text:list-item><text:p text:style-name="B">Second <text:note><text:note-citation>2</text:note-citation>- <text:note-body><text:p>Second note</text:p></text:note-body></text:note></text:p></text:list-item>- <text:list-item><text:p>Third</text:p></text:list-item>- </text:list>- </office:text></office:body></office:document-content>"""- styles = """<office:document-styles- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:master-styles>- <style:master-page style:name="MasterA">- <style:header><text:p>Header A</text:p></style:header>- </style:master-page>- <style:master-page style:name="MasterB">- <style:header><text:p>Header B</text:p></style:header>- </style:master-page>- </office:master-styles></office:document-styles>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))-- assert len(pages) == 2- first_list = next(block for block in pages[0] if block["type"] == BlockType.LIST)- second_list = next(block for block in pages[1] if block["type"] == BlockType.LIST)- assert first_list["start"] == 3- assert second_list["start"] == 4- assert [inline_text(child["content"]) for child in first_list["content"]] == ["First [1]"]- assert [inline_text(child["content"]) for child in second_list["content"]] == ["Second [2]", "Third"]- assert any(block["type"] == BlockType.PAGE_FOOTNOTE and "First note" in inline_text(block["content"]) for block in pages[0])- assert any(- block["type"] == BlockType.PAGE_FOOTNOTE and "Second note" in inline_text(block["content"]) for block in pages[1]- )- assert any(block["type"] == BlockType.HEADER and inline_text(block["content"]) == "Header A" for block in pages[0])- assert any(block["type"] == BlockType.HEADER and inline_text(block["content"]) == "Header B" for block in pages[1])---def test_odt_list_can_select_nondefault_master_on_first_page() -> None:- """验证文档从列表开始时使用首个列表段落请求的 master-page。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:automatic-styles>- <style:style style:name="B" style:family="paragraph" style:master-page-name="MasterB"/>- </office:automatic-styles>- <office:body><office:text><text:list><text:list-item>- <text:p text:style-name="B">First list item</text:p>- </text:list-item></text:list></office:text></office:body></office:document-content>"""- styles = """<office:document-styles- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:master-styles>- <style:master-page style:name="MasterA">- <style:header><text:p>Header A</text:p></style:header>- </style:master-page>- <style:master-page style:name="MasterB">- <style:header><text:p>Header B</text:p></style:header>- </style:master-page>- </office:master-styles></office:document-styles>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))-- assert len(pages) == 1- assert any(block["type"] == BlockType.HEADER and inline_text(block["content"]) == "Header B" for block in pages[0])- assert all(visible_content(block.get("content")) != "Header A" for block in pages[0])---def test_odf_covered_placeholder_reuses_colspan_coordinate() -> None:- """验证 colspan 后的 covered placeholder 不会额外扩宽表格。"""- table = etree.fromstring(- """<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <table:table-row>- <table:table-cell table:number-columns-spanned="2"><text:p>Merged</text:p></table:table-cell>- <table:covered-table-cell/><table:table-cell><text:p>Tail</text:p></table:table-cell>- </table:table-row>- <table:table-row>- <table:table-cell><text:p>A</text:p></table:table-cell>- <table:table-cell><text:p>B</text:p></table:table-cell>- <table:table-cell><text:p>C</text:p></table:table-cell>- </table:table-row>-</table:table>""".encode()- )-- grid = odf_table_module.parse_table_grid(table, lambda cell: "".join(cell.itertext()).strip())-- assert grid.width == 3- assert grid.covered == {(0, 1)}- assert grid.rows[0][0] is not None and grid.rows[0][0].col_span == 2- assert grid.rows[0][2] is not None and grid.rows[0][2].html == "Tail"- assert [cell.html if cell is not None else None for cell in grid.rows[1]] == ["A", "B", "C"]---def test_odt_note_after_soft_page_break_stays_on_current_page() -> None:- """验证 soft-page-break 被忽略后 note reference 和正文仍归属当前章节页。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:p>Before<text:soft-page-break/>After- <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>After note</text:p></text:note-body></text:note>- </text:p></office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert pages == [- [- {"type": BlockType.TEXT, "content": inline("BeforeAfter [1]")},- {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] After note")},- ]- ]---def test_ods_cell_note_emits_page_footnote() -> None:- """验证 ODS cell citation 对应的 note body 在当前 sheet 页末输出。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">- <office:body><office:spreadsheet><table:table table:name="Sheet1"><table:table-row><table:table-cell><text:p>Cell- <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>Cell note</text:p></text:note-body></text:note>- </text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body>-</office:document-content>"""-- pages = OdsModel().predict(BytesIO(build_odf_package("ods", content)))-- assert [block["type"] for block in pages[0]] == [BlockType.TABLE, BlockType.PAGE_FOOTNOTE]- assert "Cell [1]" in pages[0][0]["content"]- assert inline_text(pages[0][1]["content"]) == "[1] Cell note"---def test_odp_slide_inline_note_emits_page_footnote() -> None:- """验证 ODP slide 正文中的 note body 不会被 presentation notes 路径遗漏。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:presentation><draw:page draw:name="Slide1"><draw:frame><draw:text-box><text:p>Slide- <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>Inline note</text:p></text:note-body></text:note>- </text:p></draw:text-box></draw:frame></draw:page></office:presentation></office:body>-</office:document-content>"""-- pages = OdpModel().predict(BytesIO(build_odf_package("odp", content)))-- assert pages == [- [- {"type": BlockType.TEXT, "content": inline("Slide [1]")},- {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] Inline note")},- ]- ]---def test_odp_preserves_empty_slide_chart_preview_and_notes() -> None:- """验证 ODP 空 slide 不丢失,图表同时保留数据和预览,备注归属原页。"""- middle, model = doc_analyze(build_odp_fixture(), file_suffix="odp")- assert len(model.pages) == 3- assert model.pages[1] == []- assert model.pages[0][0]["type"] == BlockType.DOC_TITLE- chart = next(block for block in model.pages[2] if block["type"] == BlockType.CHART)- assert "Category" in chart["content"]- assert "Value" in chart["content"]- assert chart["image_base64"].startswith("data:image/")- assert any(- block["type"] == BlockType.PAGE_FOOTNOTE and "Speaker note" in inline_text(block["content"]) for block in model.pages[2]- )- assert len(middle.pages) == 3---def test_ods_skips_hidden_sheet_and_emits_tables_images_and_charts() -> None:- """验证 ODS 可见 sheet 边界、typed value、合并结构和图表对象。"""- middle, model = doc_analyze(build_ods_fixture(), file_suffix="ods")- assert len(model.pages) == 2- assert [inline_text(page[0]["content"]) for page in model.pages] == ["Visible A", "Visible B"]- flattened = [block for page in model.pages for block in page]- assert "secret" not in str(flattened)- assert "50%" in str(flattened)- assert 'colspan="2"' in str(flattened)- assert any(block["type"] == BlockType.CHART for block in flattened)- assert len(middle.pages) == 2---def test_ods_resolves_inherited_table_visibility_with_child_override() -> None:- """验证 table display 沿父样式继承,且子样式显式显示可以覆盖隐藏。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:automatic-styles>- <style:style style:name="HiddenParent" style:family="table">- <style:table-properties table:display="false"/>- </style:style>- <style:style style:name="InheritedHidden" style:family="table" style:parent-style-name="HiddenParent"/>- <style:style style:name="ExplicitVisible" style:family="table" style:parent-style-name="HiddenParent">- <style:table-properties table:display="true"/>- </style:style>- </office:automatic-styles>- <office:body><office:spreadsheet>- <table:table table:name="Secret" table:style-name="InheritedHidden">- <table:table-row><table:table-cell><text:p>secret</text:p></table:table-cell></table:table-row>- </table:table>- <table:table table:name="Override" table:style-name="ExplicitVisible">- <table:table-row><table:table-cell><text:p>override</text:p></table:table-cell></table:table-row>- </table:table>- <table:table table:name="DefaultVisible">- <table:table-row><table:table-cell><text:p>default</text:p></table:table-cell></table:table-row>- </table:table>- </office:spreadsheet></office:body>-</office:document-content>"""- payload = build_odf_package("ods", content)-- pages = OdsModel().predict(BytesIO(payload))- metadata = extract_odf_metadata(BytesIO(payload), "ods")-- assert len(pages) == 2- assert "secret" not in str(pages)- assert "override" in str(pages)- assert "default" in str(pages)- assert metadata["page_count"] == 2--- ("suffix", "payload"),- [("odt", build_odt_fixture()), ("ods", build_ods_fixture()), ("odp", build_odp_fixture())],-)-def test_odf_content_detection_precedes_csv_extension(- tmp_path: Path,- suffix: str,- payload: bytes,-) -> None:- """验证 ODF 强内容身份覆盖伪装扩展名和 CSV 无签名兜底。"""- disguised = tmp_path / "disguised.csv"- disguised.write_bytes(payload)- assert guess_suffix_by_bytes(payload, str(disguised)) == suffix- assert guess_suffix_by_path(disguised) == suffix---def test_rtf_signature_still_precedes_odf_extension(tmp_path: Path) -> None:- """验证新增 ZIP 探测不改变 RTF 强签名的最高优先级。"""- source = tmp_path / "disguised.odt"- source.write_bytes(rb"{\rtf1\ansi visible}")- assert guess_suffix_by_path(source) == "rtf"- assert guess_suffix_by_bytes(source.read_bytes(), str(source)) == "rtf"--def test_plain_text_renamed_to_odf_is_not_accepted(tmp_path: Path) -> None:"""验证 ODF 扩展名本身不能把普通文本升级为结构化文档。"""source = tmp_path / "fake.odt"@@ -635,562 +63,6 @@ def test_plain_text_renamed_to_odf_is_not_accepted(tmp_path: Path) -> None:parse(source)-def test_odf_rejects_mismatched_encrypted_and_expanding_packages() -> None:- """验证格式错配、manifest 加密和超大重复行在分配前稳定失败。"""- with pytest.raises(OdfParseError, match="expected"):- OdtModel().predict(BytesIO(build_ods_fixture()))-- encrypted_content = (- '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0">'- "<office:body><office:text/></office:body></office:document-content>"- )- encrypted = build_odf_package("odt", encrypted_content, encrypted=True)- with pytest.raises(OdfEncryptedError, match="Encrypted ODF"):- OdtModel().predict(BytesIO(encrypted))-- expanding_content = (- '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '- 'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" '- 'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">'- '<office:body><office:spreadsheet><table:table><table:table-row table:number-rows-repeated="4000001">'- "<table:table-cell><text:p>x</text:p></table:table-cell>"- "</table:table-row></table:table></office:spreadsheet></office:body></office:document-content>"- )- expanding = build_odf_package("ods", expanding_content)- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- OdsModel().predict(BytesIO(expanding))--[email protected]("span_attribute", ["number-rows-spanned", "number-columns-spanned"])-def test_odf_rejects_oversized_cell_spans_before_grid_materialization(- monkeypatch: pytest.MonkeyPatch,- span_attribute: str,-) -> None:- """验证超大行列跨度在渲染单元格或扩容网格前立即失败。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)-- def unexpected_materialization(*_args: object, **_kwargs: object) -> None:- """超限 span 不得进入单元格渲染或网格扩容。"""- pytest.fail("oversized span reached grid materialization")-- monkeypatch.setattr(odf_table_module, "_ensure_row", unexpected_materialization)- table = etree.fromstring(- f'<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'- f'<table:table-row><table:table-cell table:{span_attribute}="5"/></table:table-row>'- "</table:table>"- )-- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- odf_table_module.parse_table_grid(table, unexpected_materialization)---def test_odf_rejects_projected_span_extent_before_extending_existing_row(monkeypatch: pytest.MonkeyPatch) -> None:- """验证单个 span 合法但累计宽度超限时不会先扩展现有行。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)- original_ensure_row = odf_table_module._ensure_row- observed_widths: list[int] = []-- def tracking_ensure_row(grid: object, row_index: int, width: int = 0) -> object:- """记录实际扩容宽度,确保失败前未越过共享预算。"""- observed_widths.append(width)- return original_ensure_row(grid, row_index, width) # type: ignore[arg-type]-- monkeypatch.setattr(odf_table_module, "_ensure_row", tracking_ensure_row)- table = etree.fromstring(- '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'- '<table:table-row><table:table-cell table:number-columns-spanned="3"/>'- '<table:table-cell table:number-columns-spanned="2"/></table:table-row>'- "</table:table>"- )-- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- odf_table_module.parse_table_grid(table, lambda _cell: "x")- assert observed_widths and max(observed_widths) <= 3---def test_odf_rejects_overlong_repeat_before_integer_conversion(monkeypatch: pytest.MonkeyPatch) -> None:- """验证超长 repeat 计数在 int 和单元格渲染前触发网格预算。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)-- def unexpected_render(_cell: object) -> str:- """超限 repeat 不得进入单元格渲染。"""- pytest.fail("oversized ODF repeat reached cell rendering")-- table = etree.fromstring(- (- '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'- f'<table:table-row table:number-rows-repeated="{"9" * 100_000}">'- "<table:table-cell/>"- "</table:table-row></table:table>"- ).encode()- )-- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- odf_table_module.parse_table_grid(table, unexpected_render)---def test_odf_document_grid_budget_is_shared_across_tables(monkeypatch: pytest.MonkeyPatch) -> None:- """验证多个独立表格共同消耗同一个文档网格预算。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)- budget = odf_table_module.OdfTableExpansionBudget()- table_xml = (- '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'- '<table:table-row table:number-rows-repeated="2">'- '<table:table-cell table:number-columns-repeated="2"/>'- "</table:table-row></table:table>"- )-- first = odf_table_module.parse_table_grid(- etree.fromstring(table_xml.encode()),- lambda _cell: "x",- expansion_budget=budget,- )- assert len(first.rows) * first.width == 4- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- odf_table_module.parse_table_grid(- etree.fromstring(table_xml.encode()),- lambda _cell: "x",- expansion_budget=budget,- )---def test_odf_document_text_expansion_budget_is_shared_across_tables(monkeypatch: pytest.MonkeyPatch) -> None:- """验证多个表格的重复单元格文本共同消耗文档级字节预算。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 100)- monkeypatch.setattr(odf_table_module, "MAX_EXPANSION_TEXT_BYTES", 4)- budget = odf_table_module.OdfTableExpansionBudget()- table_xml = (- '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'- '<table:table-row><table:table-cell table:number-columns-repeated="2"/></table:table-row>'- "</table:table>"- )-- odf_table_module.parse_table_grid(- etree.fromstring(table_xml.encode()),- lambda _cell: "xxx",- expansion_budget=budget,- )- with pytest.raises(OdfResourceLimitError, match="max_expansion_text_bytes"):- odf_table_module.parse_table_grid(- etree.fromstring(table_xml.encode()),- lambda _cell: "xxx",- expansion_budget=budget,- )---def test_odt_parser_wires_one_table_budget_across_document(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 ODT 中多个普通表格通过 parser 共享同一文档预算。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)- table = """<table:table><table:table-row table:number-rows-repeated="2">- <table:table-cell table:number-columns-repeated="2"><text:p>x</text:p></table:table-cell>- </table:table-row></table:table>"""- content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text>{table}{table}</office:text></office:body>- </office:document-content>"""-- with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):- OdtModel().predict(BytesIO(build_odf_package("odt", content)))---def test_odf_rejects_overlong_chart_columns_before_bigint_conversion(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 chart A1 列名在大整数转换前受共享网格预算约束。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)-- assert odf_table_module.parse_cell_range_bounds("local-table.D1:D2") == (0, 1, 3, 3)- assert odf_table_module.parse_cell_range_bounds("local-table.E1:E2") is None- assert odf_table_module.parse_cell_range_bounds(f"local-table.{'A' * 100_000}1") is None---def test_odf_rejects_overlong_chart_rows_before_bigint_conversion(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 chart A1 行号在 int 转换前受共享网格预算约束。"""- monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)-- assert odf_table_module.parse_cell_range_bounds("local-table.A4:B4") == (3, 3, 0, 1)- assert odf_table_module.parse_cell_range_bounds("local-table.A5:B5") is None- assert odf_table_module.parse_cell_range_bounds(f"local-table.A{'9' * 100_000}") is None--- "target",- [- "javascript:alert(1)",- "JaVaScRiPt:alert(1)",- "data:text/plain,unsafe",- "vbscript:msgbox(1)",- "file:///tmp/unsafe",- "ftp://example.com/file",- "//example.com/path",- "\\\\server\\share",- ],-)-def test_odf_rejects_unsafe_hyperlinks_before_shared_renderers(target: str) -> None:- """验证危险 ODF 链接在 Raw 阶段降级,Markdown 与 DOCX 不再携带目标。"""- content = f'''<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p>before <text:a xlink:href="{target}">click</text:a> after</text:p>- </office:text></office:body></office:document-content>'''- payload = build_odf_package("odt", content)- pages = OdtModel().predict(BytesIO(payload))- middle, _ = doc_analyze(payload, file_suffix="odt")- markdown = render_markdown(middle)- docx = render_docx(middle)- with ZipFile(BytesIO(docx)) as package:- relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")-- assert pages == [[{"type": BlockType.TEXT, "content": inline("before click after")}]]- assert markdown == "before click after"- assert target not in relationships--- "target",- [- "https://example.com/path",- "mailto:[email protected]",- "tel:+123456",- "chapter.odt#section-one",- ],-)-def test_odf_preserves_allowed_external_and_relative_hyperlinks(target: str) -> None:- """验证允许协议、相对地址和 fragment 直接进入 HyperlinkSpan。"""- content = f'''<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p><text:a xlink:href="{target}">click</text:a></text:p>- </office:text></office:body></office:document-content>'''- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert pages[0][0]["type"] == BlockType.TEXT- assert len(pages[0][0]["content"]) == 1- link = pages[0][0]["content"][0]- assert link["type"] == "hyperlink"- assert link["url"] == target- assert inline_text(link["content"]) == "click"---def test_odf_preserves_title_fragment_and_drops_unemittable_text_fragment() -> None:- """验证本地 fragment 仅链接到标题类 block 实际公开的 bookmark。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text>- <text:p><text:a xlink:href="#title-target">Title jump</text:a> / <text:a xlink:href="#text-target">Text jump</text:a></text:p>- <text:h text:outline-level="1"><text:bookmark-start text:name="title-target"/>Heading</text:h>- <text:p><text:bookmark text:name="text-target"/>Ordinary target</text:p>- </office:text></office:body>-</office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert inline_text(pages[0][0]["content"]) == "Title jump / Text jump"- assert pages[0][0]["content"][0]["type"] == "hyperlink"- assert pages[0][0]["content"][0]["url"] == "#title-target"- assert pages[0][1]["type"] == BlockType.PARAGRAPH_TITLE- assert pages[0][1]["anchor"] == "title-target"- assert pages[0][2] == {"type": BlockType.TEXT, "content": inline("Ordinary target")}---def test_odf_corrupt_optional_styles_and_external_image_degrade_locally() -> None:- """验证可选样式损坏和外部图片不会阻断正文或触发网络读取。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p>visible</text:p>- <draw:frame><draw:image xlink:href="https://example.com/external.png"/></draw:frame>- </office:text></office:body></office:document-content>"""- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml="<broken")))- assert pages == [[{"type": BlockType.TEXT, "content": inline("visible")}]]---def test_odf_malformed_image_and_object_references_degrade_locally() -> None:- """验证非法图片和对象 URI 仅丢弃资源,不阻断 ODF 正文。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p>visible</text:p><draw:frame>- <draw:object xlink:href="http://["/><draw:image xlink:href="http://["/>- </draw:frame></office:text></office:body></office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("visible")}]]---def test_odf_flattened_titles_and_notes_keep_tag_literals_as_text_spans() -> None:- """验证标题、演讲者备注和行内脚注保留标签外观原文但不生成链接 Span。"""- literal = "<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>"- odp_content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:presentation><draw:page draw:name="Slide 1">- <draw:frame presentation:class="title"><draw:text-box><text:p>{literal}</text:p></draw:text-box></draw:frame>- <presentation:notes><draw:frame><draw:text-box><text:p>{literal}</text:p></draw:text-box></draw:frame></presentation:notes>- </draw:page></office:presentation></office:body></office:document-content>"""- odt_content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:text><text:p>Body<text:note><text:note-citation>{literal}</text:note-citation>- <text:note-body><text:p>Footnote body {literal}</text:p></text:note-body>- </text:note></text:p></office:text></office:body></office:document-content>"""-- for suffix, payload in (- ("odp", build_odf_package("odp", odp_content)),- ("odt", build_odf_package("odt", odt_content)),- ):- middle, model = doc_analyze(payload, file_suffix=suffix) # type: ignore[arg-type]- flattened = [- inline_text(block["content"])- for page in model.pages- for block in page- if block.get("type") in {BlockType.DOC_TITLE, BlockType.PAGE_FOOTNOTE}- ]- markdown = render_markdown(middle)- docx = render_docx(middle)- with ZipFile(BytesIO(docx)) as package:- relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")-- assert flattened- assert all("<hyperlink>" in content for content in flattened)- assert "](javascript:alert(1))" not in markdown- assert "javascript:alert(1)" not in relationships--- ("weight", "expected_bold"),- [- ("normal", False),- ("bold", True),- ("599", False),- ("600", True),- ("1000", True),- ("1001", False),- ("9" * 100_000, False),- ],- ids=("normal", "bold", "below-threshold", "threshold", "upper-bound", "out-of-range", "overlong"),-)-def test_odf_font_weight_is_bounded_before_numeric_conversion(weight: str, expected_bold: bool) -> None:- """验证数字字重只在有限 CSS 范围内转换,超长输入不会依赖解释器保护。"""- content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">- <office:automatic-styles><style:style style:name="W" style:family="text">- <style:text-properties fo:font-weight="{weight}"/>- </style:style></office:automatic-styles>- <office:body><office:text><text:p><text:span text:style-name="W">weighted</text:span></text:p>- </office:text></office:body></office:document-content>"""- previous_limit = sys.get_int_max_str_digits() if hasattr(sys, "get_int_max_str_digits") else None- if hasattr(sys, "set_int_max_str_digits"):- sys.set_int_max_str_digits(0)- try:- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))- finally:- if previous_limit is not None:- sys.set_int_max_str_digits(previous_limit)-- expected_content = inline("weighted", styles=["bold"] if expected_bold else None)- assert pages == [[{"type": BlockType.TEXT, "content": expected_content}]]---def test_odf_inline_image_alt_keeps_literal_hyperlink_text_inert() -> None:- """验证行内图片 title/desc 保留标签外观原文但不会生成活动链接。"""- literal = "<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>"- content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><text:p>Before <draw:frame>- <draw:image xlink:href="Pictures/pixel.png"/><svg:title>{literal}</svg:title>- </draw:frame> After</text:p></office:text></office:body></office:document-content>"""- payload = build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})- middle, model = doc_analyze(payload, file_suffix="odt")-- raw_content = model.pages[0][0]["content"]- markdown = render_markdown(middle)- docx = render_docx(middle)- with ZipFile(BytesIO(docx)) as package:- relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")-- assert "<hyperlink>" in inline_text(raw_content)- assert all(span.get("type") == "text" for span in raw_content)- assert "](javascript:" not in markdown- assert "javascript:alert(1)" not in relationships--- ("href", "extra_parts"),- [- ("Pictures/missing.png", None),- ("https://example.com/external.png", None),- ("Pictures/corrupt.png", {"Pictures/corrupt.png": b"not-an-image"}),- ],-)-def test_odf_unavailable_image_preserves_safe_alt_text(- href: str,- extra_parts: dict[str, bytes] | None,-) -> None:- """验证缺失、外部或损坏图片无法物化时仍以安全文本保留 title/desc 语义。"""- literal = "<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>"- content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"- xmlns:xlink="http://www.w3.org/1999/xlink">- <office:body><office:text><draw:frame><draw:image xlink:href="{href}"/>- <svg:title>{literal}</svg:title><svg:desc>semantic description</svg:desc>- </draw:frame></office:text></office:body>-</office:document-content>"""-- middle, model = doc_analyze(- build_odf_package("odt", content, extra_parts=extra_parts),- file_suffix="odt",- )- raw_content = model.pages[0][0]["content"]- markdown = render_markdown(middle)-- assert model.pages[0][0]["type"] == BlockType.TEXT- assert "<hyperlink>" in inline_text(raw_content)- assert all(span.get("type") == "text" for span in raw_content)- assert "semantic description" in inline_text(raw_content)- assert "](javascript:" not in markdown---def test_odf_annotation_emits_page_footnote_without_metadata_in_body() -> None:- """验证标准 annotation 正文作为页脚注保留,作者日期不拼入周围正文。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:dc="http://purl.org/dc/elements/1.1/">- <office:body><office:text><text:p>Before <office:annotation office:name="comment-1">- <dc:creator>Alice</dc:creator><dc:date>2026-01-01</dc:date><text:p>Review note</text:p>- </office:annotation>After<office:annotation-end office:name="comment-1"/></text:p>- </office:text></office:body></office:document-content>"""-- pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))-- body = next(block for block in pages[0] if block["type"] == BlockType.TEXT)- annotation = next(block for block in pages[0] if block["type"] == BlockType.PAGE_FOOTNOTE)- assert inline_text(body["content"]) == "Before After"- assert inline_text(annotation["content"]) == "Review note"- assert "Alice" not in str(pages) and "2026-01-01" not in str(pages)---def test_ods_sheet_titles_escape_literal_inline_protocol() -> None:- """验证多 sheet 标题不会把名称中的内部协议重建为活动链接。"""- literal = "<hyperlink><text>x</text><url>javascript:alert(1)</url></hyperlink>"- content = f"""<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:body><office:spreadsheet>- <table:table table:name="{literal}"><table:table-row><table:table-cell>- <text:p>A</text:p>- </table:table-cell></table:table-row></table:table>- <table:table table:name="Safe"><table:table-row><table:table-cell>- <text:p>B</text:p>- </table:table-cell></table:table-row></table:table>- </office:spreadsheet></office:body></office:document-content>"""- middle, model = doc_analyze(build_odf_package("ods", content), file_suffix="ods")-- title = model.pages[0][0]["content"]- markdown = render_markdown(middle)- docx = render_docx(middle)- with ZipFile(BytesIO(docx)) as package:- relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")-- assert inline_text(title).startswith("<hyperlink>")- assert all(span.get("type") == "text" for span in title)- assert "](javascript:" not in markdown- assert "javascript:alert(1)" not in relationships---def test_odp_skips_hidden_drawing_page_styles_in_output_and_metadata() -> None:- """验证 ODP converter 与 metadata 共用 drawing-page 可见性解析。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"- xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"- xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">- <office:automatic-styles>- <style:style style:name="HiddenPage" style:family="drawing-page">- <style:drawing-page-properties presentation:visibility="hidden"/>- </style:style>- </office:automatic-styles>- <office:body><office:presentation>- <draw:page draw:name="Visible"><draw:frame><draw:text-box>- <text:p>visible slide</text:p>- </draw:text-box></draw:frame></draw:page>- <draw:page draw:name="StyledHidden" draw:style-name="HiddenPage"><draw:frame><draw:text-box>- <text:p>styled hidden slide</text:p>- </draw:text-box></draw:frame></draw:page>- <draw:page draw:name="DirectHidden" presentation:visibility="hidden"><draw:frame><draw:text-box>- <text:p>direct hidden slide</text:p>- </draw:text-box></draw:frame></draw:page>- </office:presentation></office:body></office:document-content>"""- payload = build_odf_package("odp", content)-- pages = OdpModel().predict(BytesIO(payload))- metadata = extract_odf_metadata(BytesIO(payload), "odp")-- assert len(pages) == 1- assert "visible slide" in str(pages)- assert "hidden slide" not in str(pages)- assert metadata["page_count"] == 1---def test_odf_style_cycle_is_bounded_and_preserves_text() -> None:- """验证循环 parent-style-name 在有限链路内降级,不阻塞正文解析。"""- content = """<office:document-content- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">- <office:body><office:text><text:p text:style-name="A">visible</text:p></office:text></office:body>-</office:document-content>"""- styles = """<office:document-styles- xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"- xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">- <office:styles><style:style style:name="A" style:family="paragraph" style:parent-style-name="B"/>- <style:style style:name="B" style:family="paragraph" style:parent-style-name="A"/>- </office:styles></office:document-styles>"""- assert OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles))) == [- [{"type": BlockType.TEXT, "content": inline("visible")}]- ]---def test_odf_package_rejects_unsafe_member_paths_and_dtd() -> None:- """验证 ZIP 上跳成员和 XML DTD 在进入语义解析前失败。"""- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as package:- package.writestr("mimetype", "application/vnd.oasis.opendocument.text")- package.writestr("../escape", b"unsafe")- with pytest.raises(OdfParseError, match="unsafe member path"):- OdfPackage(output.getvalue())-- dtd_content = """<!DOCTYPE doc [<!ENTITY x "hidden">]>-<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0">- <office:body><office:text/></office:body></office:document-content>"""- with pytest.raises(OdfParseError, match="DTD is not allowed"):- OdtModel().predict(BytesIO(build_odf_package("odt", dtd_content)))--@pytest.mark.parametrize(("suffix", "payload", "expected"),[@@ -1198,6 +70,7 @@ def test_odf_package_rejects_unsafe_member_paths_and_dtd() -> None:("ods", build_ods_fixture(), {"page_count": 2}),("odp", build_odp_fixture(), {"page_count": 3}),],+ ids=["odt", "ods", "odp"],)def test_doclib_extracts_odf_metadata(tmp_path: Path,@@ -1234,6 +107,7 @@ def test_odt_metadata_page_count_is_bounded_before_doclib_range_expansion() -> N@pytest.mark.parametrize(("suffix", "payload"),[("odt", build_odt_fixture()), ("ods", build_ods_fixture()), ("odp", build_odp_fixture())],+ ids=["odt", "ods", "odp"],)def test_public_parser_handles_odf_sync_and_async(tmp_path: Path,@@ -1285,6 +159,7 @@ def test_odf_parse_server_job_emits_flash_outputs(tmp_path: Path) -> None:@pytest.mark.parametrize(("suffix", "payload", "page_count"),[("odt", build_odt_fixture(), 3), ("ods", build_ods_fixture(), 2), ("odp", build_odp_fixture(), 3)],+ ids=["odt", "ods", "odp"],)def test_doclib_ingests_odf_as_local_flash(tmp_path: Path,@@ -1355,25 +230,3 @@ def test_doclib_rejects_odf_remote_parse(tmp_path: Path) -> None:assert exc_info.value.param == "remote"asyncio.run(run())---def test_csv_and_rtf_runtime_do_not_load_odf_modules() -> None:- """验证新增 ODF converter 不进入既有 CSV/RTF 的惰性导入边界。"""- script = "\n".join(- [- "import io, sys",- "from docvortex.analyzers.native import CsvModel, RtfModel",- "CsvModel().predict(io.BytesIO(b'a,b\\n1,2\\n'))",- "RtfModel().predict(io.BytesIO(b'{\\\\rtf1 ok}'))",- "assert not any(name.startswith('docvortex.analyzers.native.office.odf') for name in sys.modules)",- ]- )- result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False)- assert result.returncode == 0, result.stderr---def test_odf_subpackage_does_not_export_models() -> None:- """验证 ODF 模型只从 Flash 根包公开,不形成第二套公共路径。"""- assert importlib.util.find_spec("docvortex.analyzers.native.office.odf.model") is None- package = __import__("docvortex.analyzers.native.office.odf", fromlist=["__all__"])- assert package.__all__ == []diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.pyindex 75f16053..dde45289 100644--- a/tests/unittest/test_flash_ofd.py+++ b/tests/unittest/test_flash_ofd.py@@ -1,73 +1,27 @@from __future__ import annotationsimport asyncio-import hashlibimport jsonfrom io import BytesIOfrom pathlib import Path-from unittest.mock import MagicMock-from zipfile import ZIP_DEFLATED, ZipFile-from bs4 import BeautifulSoup-from docx import Document-from lxml import etree-from PIL import Imageimport pytest+from _ofd_test_utils import build_ofd_package, page_xml, text_object+from docvortex.analyzers.native import OfdModel+from docvortex.analyzers.native.ofd import detect_ofd+from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.backend.analyze import aio_doc_analyze, doc_analyze-from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.db import DatabaseManager+from mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.fts import FTSManagerfrom mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestError-from docvortex.analyzers.native import OfdModel-from docvortex.analyzers.native.ofd import OfdParseError-from docvortex.analyzers.native.ofd import OfdResourceLimitError-from docvortex.analyzers.native.ofd import detect_ofd-from docvortex.analyzers.native.ofd import images as ofd_images-from docvortex.analyzers.native.ofd import metadata as ofd_metadata-from docvortex.analyzers.native.ofd import scene as ofd_scene-from docvortex.analyzers.native.ofd import table as ofd_table-from docvortex.analyzers.native.ofd import text as ofd_text-from docvortex.analyzers.native.ofd.constants import MAX_DELTA_TOKENS-from docvortex.analyzers.native.ofd.constants import MAX_DOCUMENT_COUNT-from docvortex.analyzers.native.ofd.constants import MAX_DRAW_PARAM_INHERITANCE-from docvortex.analyzers.native.ofd.constants import MAX_EXPANDED_GLYPHS-from docvortex.analyzers.native.ofd.constants import MAX_GLYPH_TOKENS-from docvortex.analyzers.native.ofd.constants import MAX_PAGE_COUNT-from docvortex.analyzers.native.ofd.constants import MAX_PATH_TOKENS-from docvortex.analyzers.native.ofd.geometry import Affine-from docvortex.analyzers.native.ofd.geometry import canonical_angle-from docvortex.analyzers.native.ofd.images import build_image_item-from docvortex.analyzers.native.ofd.models import AxisLine-from docvortex.analyzers.native.ofd.models import MediaResource-from docvortex.analyzers.native.ofd.models import OfdPageScene-from docvortex.analyzers.native.ofd.models import ResourceRegistry-from docvortex.analyzers.native.ofd.models import TextLine-from docvortex.analyzers.native.ofd.package import OfdPackage-from docvortex.analyzers.native.ofd.path import OfdPathBudget-from docvortex.analyzers.native.ofd.path import _segments-from docvortex.analyzers.native.ofd.path import build_axis_lines-from docvortex.analyzers.native.ofd.reading_order import OfdReadingOrderProjector-from docvortex.analyzers.native.ofd.resources import parse_resource_part-from docvortex.analyzers.native.ofd.resources import resolve_draw_param-from docvortex.analyzers.native.ofd.text import FontMetricResolver-from docvortex.analyzers.native.ofd.text import OfdTextBudget-from docvortex.analyzers.native.ofd.text import build_text_lines-from docvortex.analyzers.native.ofd.text import parse_delta-from mineru.parser import MinerUParser-from mineru.parser import api_server+from mineru.parser import MinerUParser, api_serverfrom mineru.parser.api_server import CreateJobRequest, FileStore-from docvortex.document.detection import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.render import render_docx, render_html, render_markdown, render_structured_contentfrom mineru.types import BlockType-from _ofd_test_utils import build_multi_document_ofd, build_ofd_package, page_xml, path_object, text_object-from _span_test_utils import inline_text--_PROJECT_ROOT = Path(__file__).resolve().parents[2]-_LOCAL_SAMPLE_DIR = _PROJECT_ROOT / "tmp" / "ofd_samples" / "ofdrw_issues_20260828" / "ofd"-def _minimal_payload(*, namespace: str = "http://www.ofdspec.org/2016", version: str = "1.0") -> bytes:"""构造包含单行文字的最小 OFD。"""@@ -79,20 +33,6 @@ def _minimal_payload(*, namespace: str = "http://www.ofdspec.org/2016", version:)-def _replace_package_part(payload: bytes, part_name: str, replacement: bytes | None) -> bytes:- """替换或删除测试 OFD ZIP 中的单个成员。"""- source_buffer = BytesIO(payload)- output_buffer = BytesIO()- with ZipFile(source_buffer) as source, ZipFile(output_buffer, "w", ZIP_DEFLATED) as output:- for info in source.infolist():- if info.filename == part_name:- if replacement is not None:- output.writestr(info, replacement)- continue- output.writestr(info, source.read(info.filename))- return output_buffer.getvalue()--def test_ofd_model_analyze_detection_and_renderers(tmp_path: Path) -> None:"""验证 OFD 从内容识别到统一四类 renderer 的完整链路。"""payload = _minimal_payload()@@ -120,770 +60,6 @@ def test_ofd_model_analyze_detection_and_renderers(tmp_path: Path) -> None:assert render_docx(middle).startswith(b"PK")-def test_ofd_legacy_namespace_and_declared_page_order() -> None:- """验证旧命名空间、非目录排序页树和空页保持声明顺序。"""- namespace = "http://www.ofdspec.org"- pages = [- (- "Pages/Page_0/Content.xml",- page_xml(text_object(1, "first", boundary="10 10 30 10"), namespace=namespace),- ),- (- "Pages/Page_2/Content.xml",- page_xml(text_object(2, "second", boundary="10 10 30 10"), namespace=namespace),- ),- ("Pages/Page_1/Content.xml", page_xml("", namespace=namespace)),- ]- middle, _model = doc_analyze(- build_ofd_package(pages, namespace=namespace, version="1.2"),- file_suffix="ofd",- )-- assert [page.page_idx for page in middle.pages] == [0, 1, 2]- assert [inline_text(page.blocks[0].content) if page.blocks else "" for page in middle.pages] == ["first", "second", ""]---def test_ofd_multiple_doc_bodies_flatten_in_declared_order() -> None:- """验证多个 DocBody 按声明顺序展开为连续物理页。"""- middle, model = doc_analyze(build_multi_document_ofd(), file_suffix="ofd")-- assert [page.page_idx for page in middle.pages] == [0, 1]- assert [inline_text(page[0]["content"]) for page in model.pages] == ["doc-zero", "doc-one"]---def test_ofd_declared_page_count_is_bounded_for_parser_and_metadata() -> None:- """验证重复引用同一页面 part 也受全文页数预算限制。"""- payload = build_ofd_package([("Pages/Page_0/Content.xml", page_xml(""))])- source_buffer = BytesIO(payload)- output_buffer = BytesIO()- with ZipFile(source_buffer) as source, ZipFile(output_buffer, "w", ZIP_DEFLATED) as output:- document_root = etree.fromstring(source.read("Doc_0/Document.xml"))- pages = next(element for element in document_root.iter() if etree.QName(element).localname == "Pages")- pages.clear()- namespace = etree.QName(document_root).namespace- for page_index in range(MAX_PAGE_COUNT + 1):- etree.SubElement(- pages,- f"{{{namespace}}}Page",- ID=str(page_index + 1),- BaseLoc="Pages/Page_0/Content.xml",- )- replacement = etree.tostring(document_root, xml_declaration=True, encoding="UTF-8")- for info in source.infolist():- output.writestr(info, replacement if info.filename == "Doc_0/Document.xml" else source.read(info.filename))- oversized = output_buffer.getvalue()-- with pytest.raises(OfdResourceLimitError, match="max_page_count"):- OfdModel().predict(BytesIO(oversized))- with pytest.raises(OfdResourceLimitError, match="max_page_count"):- ofd_metadata.extract_ofd_metadata(BytesIO(oversized))---def test_ofd_page_count_budget_is_shared_across_doc_bodies(monkeypatch: pytest.MonkeyPatch) -> None:- """验证多个 DocBody 共用解析和元数据页数预算。"""- monkeypatch.setattr(ofd_scene, "MAX_PAGE_COUNT", 1)- monkeypatch.setattr(ofd_metadata, "MAX_PAGE_COUNT", 1)- payload = build_multi_document_ofd()-- with pytest.raises(OfdResourceLimitError, match="max_page_count"):- OfdModel().predict(BytesIO(payload))- with pytest.raises(OfdResourceLimitError, match="max_page_count"):- ofd_metadata.extract_ofd_metadata(BytesIO(payload))---def test_ofd_declared_document_count_is_bounded_before_page_parsing() -> None:- """验证大量空 DocBody 在物化文档引用前受独立预算限制。"""- payload = build_ofd_package([("Pages/Page_0/Content.xml", page_xml(""))])- source_buffer = BytesIO(payload)- output_buffer = BytesIO()- with ZipFile(source_buffer) as source, ZipFile(output_buffer, "w", ZIP_DEFLATED) as output:- ofd_root = etree.fromstring(source.read("OFD.xml"))- for child in list(ofd_root):- ofd_root.remove(child)- namespace = etree.QName(ofd_root).namespace- for _document_index in range(MAX_DOCUMENT_COUNT + 1):- doc_body = etree.SubElement(ofd_root, f"{{{namespace}}}DocBody")- doc_root = etree.SubElement(doc_body, f"{{{namespace}}}DocRoot")- doc_root.text = "Doc_0/Document.xml"- document_root = etree.fromstring(source.read("Doc_0/Document.xml"))- pages = next(element for element in document_root.iter() if etree.QName(element).localname == "Pages")- pages.clear()- replacements = {- "OFD.xml": etree.tostring(ofd_root, xml_declaration=True, encoding="UTF-8"),- "Doc_0/Document.xml": etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),- }- for info in source.infolist():- content = replacements[info.filename] if info.filename in replacements else source.read(info.filename)- output.writestr(info, content)- oversized = output_buffer.getvalue()-- with pytest.raises(OfdResourceLimitError, match="max_document_count"):- OfdModel().predict(BytesIO(oversized))- with pytest.raises(OfdResourceLimitError, match="max_document_count"):- ofd_metadata.extract_ofd_metadata(BytesIO(oversized))---def test_ofd_textcode_geometry_does_not_use_oversized_boundary() -> None:- """验证 Foxit 风格超大 Boundary 不会成为最终文字 bbox。"""- content = text_object(- 81,- "661016910189",- boundary="-8.8175 -170.35411 361.51749 399.96179",- size=9,- x=83.00001,- y=168.00009,- delta_x="g 11 4.158",- ctm="0.3527 0 0 0.3527 0 139.66919",- )- middle, _model = doc_analyze(- build_ofd_package([("Pages/Page_0/Content.xml", page_xml(content, physical_box="0 0 210 140"))]),- file_suffix="ofd",- )-- bbox = middle.pages[0].blocks[0].bbox- assert bbox is not None- assert bbox[2] - bbox[0] < 0.5- assert bbox[3] - bbox[1] < 0.2---def test_ofd_cardinal_text_directions_keep_geometry_and_angle() -> None:- """验证 ReadDirection/CharDirection 参与字形 quad 与排序方向。"""- content = (- '<ofd:TextObject ID="8" Boundary="20 20 20 50" Font="1" Size="5" '- 'ReadDirection="90" CharDirection="90">'- '<ofd:TextCode X="2" Y="-5" DeltaX="g 3 6">竖排文</ofd:TextCode>'- "</ofd:TextObject>"- )- _middle, model = doc_analyze(- build_ofd_package([("Pages/Page_0/Content.xml", page_xml(content))]),- file_suffix="ofd",- )-- assert model.pages[0][0]["angle"] == 90- assert model.pages[0][0]["bbox"][2] > model.pages[0][0]["bbox"][0]- assert model.pages[0][0]["bbox"][3] > model.pages[0][0]["bbox"][1]--[email protected](("second_x", "expected"), [(16.0, "Hello"), (17.0, "Hel lo")])-def test_ofd_same_baseline_ascii_fragments_use_measured_gap(second_x: float, expected: str) -> None:- """验证相邻英文 run 仅在存在可见词间距时补空格。"""- content = "".join(- [- text_object(1, "Hel", boundary="10 10 10 10", size=4, y=5, delta_x="2 2"),- text_object(2, "lo", boundary=f"{second_x} 10 10 10", size=4, y=5, delta_x="2"),- ]- )-- _middle, model = doc_analyze(- build_ofd_package([("Pages/Page_0/Content.xml", page_xml(content))]),- file_suffix="ofd",- )-- assert len(model.pages[0]) == 1- assert inline_text(model.pages[0][0]["content"]) == expected---def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> None:- """验证 TextCode 首尾空格参与 Delta 展开和 CGTransform 全局位置映射。"""- text_element = etree.fromstring(- b'<TextObject ID="9" Boundary="10 10 50 10" Font="1" Size="5">'- b'<TextCode X="1" Y="5" DeltaX="5 7"> A </TextCode>'- b'<CGTransform CodePosition="1" CodeCount="1"><Glyphs>42</Glyphs></CGTransform>'- b"</TextObject>"- )- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")- package = OfdPackage(package_buffer.getvalue())-- lines = build_text_lines(- text_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(),- package=package,- font_metrics=FontMetricResolver(package),- budget=OfdTextBudget(),- paint_order=0,- layer_type="body",- template_id=None,- )-- assert len(lines) == 1- assert lines[0].text == " A "- assert [glyph.glyph_id for glyph in lines[0].glyphs] == [None, 42, None]- assert [glyph.origin[0] for glyph in lines[0].glyphs] == pytest.approx([11.0, 16.0, 23.0])---def test_ofd_cgtransform_expands_only_actual_text_positions() -> None:- """验证超大 CodeCount 只映射 TextCode 实际存在的字符位置。"""- glyphs = "42 " + "999 " * 100_000- text_element = etree.fromstring(- (- '<TextObject ID="10" Boundary="0 0 10 10" Font="1" Size="5">'- '<TextCode X="1" Y="5">A</TextCode>'- f'<CGTransform CodePosition="0" CodeCount="1000000000"><Glyphs>{glyphs}</Glyphs></CGTransform>'- "</TextObject>"- ).encode()- )- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")- package = OfdPackage(package_buffer.getvalue())- budget = OfdTextBudget()-- lines = build_text_lines(- text_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(),- package=package,- font_metrics=FontMetricResolver(package),- budget=budget,- paint_order=0,- layer_type="body",- template_id=None,- )-- assert budget.glyph_count == 1- assert budget.glyph_mapping_count == 1- assert budget.glyph_token_count == 1- assert len(lines) == 1- assert [glyph.glyph_id for glyph in lines[0].glyphs] == [42]-- exhausted_budget = OfdTextBudget(glyph_mapping_count=MAX_EXPANDED_GLYPHS)- with pytest.raises(OfdResourceLimitError, match="max_expanded_glyphs"):- build_text_lines(- text_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(),- package=package,- font_metrics=FontMetricResolver(package),- budget=exhausted_budget,- paint_order=0,- layer_type="body",- template_id=None,- )-- token_exhausted_budget = OfdTextBudget(glyph_token_count=MAX_GLYPH_TOKENS)- with pytest.raises(OfdResourceLimitError, match="max_glyph_tokens"):- build_text_lines(- text_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(),- package=package,- font_metrics=FontMetricResolver(package),- budget=token_exhausted_budget,- paint_order=0,- layer_type="body",- template_id=None,- )---def test_ofd_delta_tokens_are_streamed_and_bounded() -> None:- """验证 Delta 只扫描所需 token,并在全文累计超限时受控失败。"""- budget = OfdTextBudget()-- assert parse_delta("1 " + "2 " * 100_000, 1, budget) == [1.0]- assert budget.delta_token_count == 1- assert parse_delta("g 3 2", 4, budget) == [2.0, 2.0, 2.0, 2.0]-- exhausted = OfdTextBudget(delta_token_count=MAX_DELTA_TOKENS)- with pytest.raises(OfdResourceLimitError, match="max_delta_tokens"):- parse_delta("invalid 1", 1, exhausted)---def test_ofd_textcode_is_decoded_and_charged_in_bounded_chunks(monkeypatch: pytest.MonkeyPatch) -> None:- """验证十六进制转义可跨分片恢复,超限时不会先解码完整 TextCode。"""- monkeypatch.setattr(ofd_text, "_TEXT_CODE_DECODE_CHUNK_SIZE", 3)- escaped = etree.fromstring(b"<TextCode>before\\00<Part>41</Part>after</TextCode>")- budget = OfdTextBudget()-- assert ofd_text._decode_text_code_element(escaped, budget) == "beforeAafter"- assert budget.glyph_count == len("beforeAafter")-- monkeypatch.setattr(ofd_text, "_TEXT_CODE_DECODE_CHUNK_SIZE", 16)- oversized = etree.fromstring(f"<TextCode>{'A' * 100_000}</TextCode>".encode())- original_decode = ofd_text.decode_text_code- decoded_chunk_lengths: list[int] = []-- def record_decode(value: str) -> str:- """记录单次解码规模并委托真实转义实现。"""- decoded_chunk_lengths.append(len(value))- return original_decode(value)-- monkeypatch.setattr(ofd_text, "decode_text_code", record_decode)- exhausted = OfdTextBudget(glyph_count=MAX_EXPANDED_GLYPHS)- with pytest.raises(OfdResourceLimitError, match="max_expanded_glyphs"):- ofd_text._decode_text_code_element(oversized, exhausted)-- assert decoded_chunk_lengths == [16]---def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:- """验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")- package = OfdPackage(package_buffer.getvalue())- font_metrics = FontMetricResolver(package)- common = {- "parent_transform": Affine(),- "parent_clip": (0.0, 0.0, 100.0, 100.0),- "resources": ResourceRegistry(),- "package": package,- "font_metrics": font_metrics,- "budget": OfdTextBudget(),- "paint_order": 0,- "layer_type": "body",- "template_id": None,- }-- partial = etree.fromstring(- b'<TextObject ID="10" Boundary="0 0 10 10" Size="5"><TextCode X="2" Y="5" DeltaX="20">AB</TextCode></TextObject>'- )- outside = etree.fromstring(- b'<TextObject ID="11" Boundary="0 0 10 10" Size="5"><TextCode X="20" Y="5">X</TextCode></TextObject>'- )-- partial_lines = build_text_lines(partial, **common)- outside_lines = build_text_lines(outside, **common)-- assert len(partial_lines) == 1- assert partial_lines[0].text == "A"- assert [glyph.text for glyph in partial_lines[0].glyphs] == ["A"]- assert outside_lines == []---def test_ofd_draw_param_inheritance_is_ordered_and_bounded() -> None:- """验证 DrawParam 保持父到子覆盖顺序,并在继承链超限时受控失败。"""- ordered = ResourceRegistry(- draw_params={- 1: {"ID": "1", "Relative": "2", "LineWidth": "2"},- 2: {"ID": "2", "LineWidth": "1", "Color": "red"},- }- )- assert resolve_draw_param(ordered, 1) == {"LineWidth": "2", "Color": "red"}-- chain_length = MAX_DRAW_PARAM_INHERITANCE + 1- oversized = ResourceRegistry(- draw_params={- resource_id: (- {"ID": str(resource_id), "Relative": str(resource_id + 1)}- if resource_id + 1 < chain_length- else {"ID": str(resource_id), "LineWidth": "1"}- )- for resource_id in range(chain_length)- }- )- with pytest.raises(OfdResourceLimitError, match="max_draw_param_inheritance"):- resolve_draw_param(oversized, 0)--- ("raw_angle", "expected_angle"),- [- (89.9, 90),- (90.1, 90),- (179.9, 180),- (180.1, 180),- (359.9, 0),- (0.1, 0),- ],-)-def test_ofd_image_near_cardinal_rotation_accepts_both_directions(raw_angle: float, expected_angle: int) -> None:- """验证图片旋转从直角两侧逼近时都保留载荷和阅读顺序 block。"""- image_buffer = BytesIO()- Image.new("RGB", (2, 2), "white").save(image_buffer, format="PNG")- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")- archive.writestr("Res/image.png", image_buffer.getvalue())- package = OfdPackage(package_buffer.getvalue())- transform = Affine.rotation(raw_angle)- ctm = " ".join(str(value) for value in (transform.a, transform.b, transform.c, transform.d, transform.e, transform.f))- image_element = etree.fromstring(f'<ImageObject ID="1" Boundary="0 0 10 10" ResourceID="1" CTM="{ctm}"/>'.encode())- resources = ResourceRegistry(- media={- 1: MediaResource(- resource_id=1,- media_type="Image",- media_format="PNG",- media_part="Res/image.png",- )- }- )-- item = build_image_item(- image_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=resources,- package=package,- paint_order=0,- layer_type="body",- template_id=None,- )-- assert item is not None- assert item.diagnostic is None- assert item.image_base64- scene = OfdPageScene(- page_idx=0,- physical_box=(0.0, 0.0, 100.0, 100.0),- content_box=None,- images=[item],- )- blocks = OfdReadingOrderProjector([scene]).project_page(scene)- assert len(blocks) == 1- assert blocks[0]["type"] == BlockType.IMAGE- assert blocks[0]["image_base64"] == item.image_base64- assert canonical_angle(raw_angle) == expected_angle---def test_ofd_oversized_image_is_rejected_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 OFD 超限 raster 在 Pillow load 前降级为无载荷 diagnostic。"""- image = MagicMock()- image.__enter__.return_value = image- image.size = (8_193, 1)- image.load.side_effect = AssertionError("oversized image must not be decoded")- monkeypatch.setattr(ofd_images.Image, "open", lambda _source: image)- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")- archive.writestr("Res/image.png", b"oversized")- package = OfdPackage(package_buffer.getvalue())- image_element = etree.fromstring(b'<ImageObject ID="1" Boundary="0 0 10 10" ResourceID="1"/>')-- item = build_image_item(- image_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(- media={1: MediaResource(1, "Image", "PNG", "Res/image.png")},- ),- package=package,- paint_order=0,- layer_type="body",- template_id=None,- )-- assert item is not None- assert item.image_base64 is None- assert item.diagnostic == "unsupported_image_payload"- image.load.assert_not_called()---def test_ofd_referenced_media_resource_and_part_are_required() -> None:- """验证正文 ImageObject 引用不存在的资源 ID 或成员时整份失败。"""- image_element = etree.fromstring(b'<ImageObject ID="7" Boundary="0 0 10 10" ResourceID="1"/>')- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")-- with OfdPackage(package_buffer.getvalue()) as package:- with pytest.raises(OfdParseError, match="missing media resource"):- build_image_item(- image_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(),- package=package,- paint_order=0,- layer_type="body",- template_id=None,- )-- with OfdPackage(package_buffer.getvalue()) as package:- with pytest.raises(OfdParseError, match="missing required part"):- build_image_item(- image_element,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- resources=ResourceRegistry(media={1: MediaResource(1, "Image", "PNG", "Res/missing.png")}),- package=package,- paint_order=0,- layer_type="body",- template_id=None,- )---def test_ofd_path_rejects_unexpected_numeric_tokens_without_hanging() -> None:- """验证无活动命令或 C 后的数字 token 直接使当前非法路径降级。"""- assert _segments("1 2", Affine(), OfdPathBudget()) == []- assert _segments("M 0 0 C 1 2 L 3 4", Affine(), OfdPathBudget()) == []- assert _segments("M 0 0 L 10 0", Affine(), OfdPathBudget()) == [((0.0, 0.0), (10.0, 0.0))]---def test_ofd_path_tokens_are_streamed_and_bounded() -> None:- """验证无活动命令时立即停止,并在路径 token 累计超限时失败。"""- stray_budget = OfdPathBudget()-- assert _segments("1 " * 100_000, Affine(), stray_budget) == []- assert stray_budget.token_count == 1- assert stray_budget.command_count == 0-- exhausted = OfdPathBudget(token_count=MAX_PATH_TOKENS)- with pytest.raises(OfdResourceLimitError, match="max_path_tokens"):- _segments("M 0 0", Affine(), exhausted)---def test_ofd_path_segments_are_clipped_to_object_boundary() -> None:- """验证完全越界路径被丢弃,穿越路径裁到对象与父级裁剪交集。"""- outside = etree.fromstring(- b'<PathObject ID="1" Boundary="10 10 10 1" LineWidth="0.2">'- b"<AbbreviatedData>M 20 0.5 L 30 0.5</AbbreviatedData></PathObject>"- )- outside_lines = build_axis_lines(- outside,- parent_transform=Affine(),- parent_clip=(0.0, 0.0, 100.0, 100.0),- paint_order=0,- template_id=None,- budget=OfdPathBudget(),- )- assert outside_lines == []-- cases = [- ("M -5 5 L 15 5", "horizontal", (12.0, 14.9, 18.0, 15.1)),- ("M 5 -5 L 5 15", "vertical", (14.9, 12.0, 15.1, 18.0)),- ]- for data, orientation, expected_bbox in cases:- crossing = etree.fromstring(- (- '<PathObject ID="2" Boundary="10 10 10 10" LineWidth="0.2">'- f"<AbbreviatedData>{data}</AbbreviatedData></PathObject>"- ).encode()- )- lines = build_axis_lines(- crossing,- parent_transform=Affine(),- parent_clip=(12.0, 12.0, 18.0, 18.0),- paint_order=0,- template_id=None,- budget=OfdPathBudget(),- )-- assert len(lines) == 1- assert lines[0].orientation == orientation- assert lines[0].bbox == pytest.approx(expected_bbox)---def test_ofd_template_grid_recovers_table() -> None:- """验证模板路径和页面文字共同恢复高置信全线表。"""- paths = "".join(- [- path_object(10, boundary="10 20 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(11, boundary="10 50 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(12, boundary="10 80 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(13, boundary="10 20 0.2 60", data="M 0.1 0 L 0.1 60"),- path_object(14, boundary="50 20 0.2 60", data="M 0.1 0 L 0.1 60"),- path_object(15, boundary="90 20 0.2 60", data="M 0.1 0 L 0.1 60"),- ]- )- template = page_xml(paths)- body = "".join(- [- text_object(21, "A", boundary="20 30 10 8", size=4, y=4),- text_object(22, "B", boundary="60 30 10 8", size=4, y=4),- text_object(23, "C", boundary="20 60 10 8", size=4, y=4),- text_object(24, "D", boundary="60 60 10 8", size=4, y=4),- ]- )- payload = build_ofd_package(- [("Pages/Page_0/Content.xml", page_xml(body, template_id=5))],- templates={5: ("Tpls/Tpl_0/Content.xml", template)},- )- middle, model = doc_analyze(payload, file_suffix="ofd")-- assert [block["type"] for block in model.pages[0]] == [BlockType.TABLE]- assert all(value in model.pages[0][0]["content"] for value in ("A", "B", "C", "D"))- assert middle.pages[0].blocks[0].type == BlockType.TABLE---def test_ofd_table_styles_use_standard_html_across_renderers() -> None:- """验证 OFD 表格直接输出标准标签,并由 Markdown、HTML、DOCX 保留样式。"""- paths = "".join(- [- path_object(10, boundary="10 20 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(11, boundary="10 50 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(12, boundary="10 80 80 0.2", data="M 0 0.1 L 80 0.1"),- path_object(13, boundary="10 20 0.2 60", data="M 0.1 0 L 0.1 60"),- path_object(14, boundary="50 20 0.2 60", data="M 0.1 0 L 0.1 60"),- path_object(15, boundary="90 20 0.2 60", data="M 0.1 0 L 0.1 60"),- ]- )- body = "".join(- [- text_object(21, "A", boundary="20 30 10 8", size=4, y=4),- text_object(22, "B", boundary="60 30 10 8", size=4, y=4),- text_object(23, "C", boundary="20 60 10 8", size=4, y=4),- text_object(24, "D", boundary="60 60 10 8", size=4, y=4),- ]- )- page_resource = (- '<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Fonts>'- '<ofd:Font ID="1" FontName="Styled" Bold="true" Italic="true"/></ofd:Fonts></ofd:Res>'- )- payload = build_ofd_package(- [("Pages/Page_0/Content.xml", page_xml(paths + body, page_res="PageRes.xml"))],- extra_parts={"Doc_0/Pages/Page_0/PageRes.xml": page_resource},- )-- middle, model = doc_analyze(payload, file_suffix="ofd")- table_html = model.pages[0][0]["content"]-- assert "<text" not in table_html- assert "<em><strong>A</strong></em>" in table_html- assert "***A***" in render_markdown(middle)- html_soup = BeautifulSoup(render_html(middle), "html.parser")- assert html_soup.select_one("td em strong").get_text() == "A"- document = Document(BytesIO(render_docx(middle)))- styled_run = next(run for paragraph in document.tables[0].cell(0, 0).paragraphs for run in paragraph.runs if run.text)- assert styled_run.text == "A" and styled_run.bold and styled_run.italic---def test_ofd_table_intersection_budget_is_shared_across_pages(monkeypatch: pytest.MonkeyPatch) -> None:- """验证表格线段比较预算由同一 projector 跨页累计。"""-- def scene(page_idx: int) -> OfdPageScene:- """构造需要六次两两比较的单格表页面。"""- axis_lines = [- AxisLine((0.0, 0.0, 10.0, 0.2), "horizontal", 0.2, 0, None),- AxisLine((0.0, 10.0, 10.0, 10.2), "horizontal", 0.2, 1, None),- AxisLine((0.0, 0.0, 0.2, 10.0), "vertical", 0.2, 2, None),- AxisLine((10.0, 0.0, 10.2, 10.0), "vertical", 0.2, 3, None),- ]- text_lines = [- TextLine("A", (2.0, 2.0, 4.0, 4.0), [], 0, 2.0, 4, 1, "Body", None),- TextLine("B", (2.0, 6.0, 4.0, 8.0), [], 0, 2.0, 5, 2, "Body", None),- ]- return OfdPageScene(page_idx, (0.0, 0.0, 20.0, 20.0), None, text_lines, axis_lines)-- monkeypatch.setattr(ofd_table, "MAX_TABLE_INTERSECTION_CHECKS", 8)-- with pytest.raises(OfdResourceLimitError, match="max_table_intersection_checks"):- OfdReadingOrderProjector([scene(0), scene(1)]).project()---def test_ofd_page_resource_overrides_document_resource() -> None:- """验证异常重复资源 ID 按 PageRes 高于 PublicRes 的规则解析。"""- page_resource = (- '<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Fonts>'- '<ofd:Font ID="1" FontName="Page Bold" Bold="true"/></ofd:Fonts></ofd:Res>'- )- payload = build_ofd_package(- [- (- "Pages/Page_0/Content.xml",- page_xml(text_object(1, "page-style", boundary="10 10 40 10"), page_res="PageRes.xml"),- )- ],- extra_parts={"Doc_0/Pages/Page_0/PageRes.xml": page_resource},- )- _middle, model = doc_analyze(payload, file_suffix="ofd")-- assert model.pages[0][0]["content"] == [{"type": "text", "content": "page-style", "styles": ["bold"]}]--- ("replacement", "error"),- [- (None, "invalid required location"),- (b"<broken", "invalid XML part"),- (b'<Res xmlns="urn:unsupported"/>', "unsupported namespace"),- ],-)-def test_ofd_declared_resource_part_is_required(replacement: bytes | None, error: str) -> None:- """验证已声明资源成员缺失、损坏或 namespace 错误时整份失败。"""- payload = _replace_package_part(_minimal_payload(), "Doc_0/PublicRes.xml", replacement)-- with pytest.raises(OfdParseError, match=error):- OfdModel().predict(BytesIO(payload))---def test_ofd_absent_resource_declaration_is_optional_but_empty_declaration_is_invalid() -> None:- """验证未声明资源合法,而显式空资源引用按损坏包处理。"""- payload = _minimal_payload()- with ZipFile(BytesIO(payload)) as package:- document_root = etree.fromstring(package.read("Doc_0/Document.xml"))- public_res = next(element for element in document_root.iter() if etree.QName(element).localname == "PublicRes")-- parent = public_res.getparent()- assert parent is not None- parent.remove(public_res)- without_declaration = _replace_package_part(- payload,- "Doc_0/Document.xml",- etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),- )- assert OfdModel().predict(BytesIO(without_declaration))-- public_res = etree.SubElement(parent, "{http://www.ofdspec.org/2016}PublicRes")- public_res.text = ""- empty_declaration = _replace_package_part(- payload,- "Doc_0/Document.xml",- etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),- )- with pytest.raises(OfdParseError, match="invalid required location"):- OfdModel().predict(BytesIO(empty_declaration))---def test_parse_resource_part_none_returns_empty_registry() -> None:- """验证调用方明确传入未声明资源时不会读取可选成员。"""- package_buffer = BytesIO()- with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:- archive.writestr("OFD.xml", "<OFD/>")-- with OfdPackage(package_buffer.getvalue()) as package:- registry = parse_resource_part(package, None)-- assert not registry.fonts and not registry.media and not registry.composites and not registry.draw_params---def test_ofd_does_not_open_malformed_unreferenced_custom_tag() -> None:- """验证损坏但未参与正文的扩展 XML 不会中断解析。"""- payload = build_ofd_package(- [("Pages/Page_0/Content.xml", page_xml(text_object(1, "visible", boundary="10 10 30 10")))],- extra_parts={"Doc_0/Tags/CustomTag.xml": "<broken"},- )-- middle, _model = doc_analyze(payload, file_suffix="ofd")- assert inline_text(middle.pages[0].blocks[0].content) == "visible"---def test_ofd_rejects_foreign_namespace_and_non_v1_version() -> None:- """验证未知命名空间和非 1.x 版本不会被宽松接受。"""- assert not detect_ofd(_minimal_payload(namespace="https://example.com/ofd"))- assert not detect_ofd(_minimal_payload(version="2.0"))- with pytest.raises(OfdParseError):- OfdModel().predict(BytesIO(_minimal_payload(namespace="https://example.com/ofd")))---def test_ofd_package_rejects_unsafe_member_and_dtd() -> None:- """验证 ZIP 上跳成员与任意 DTD 在正文解析前被拒绝。"""- unsafe = BytesIO()- with ZipFile(unsafe, "w", ZIP_DEFLATED) as package:- package.writestr("OFD.xml", '<ofd:OFD xmlns:ofd="http://www.ofdspec.org/2016" Version="1.0"/>')- package.writestr("../escape.xml", "unsafe")- with pytest.raises(OfdParseError, match="unsafe member"):- OfdPackage(unsafe.getvalue())-- dtd = BytesIO()- with ZipFile(dtd, "w", ZIP_DEFLATED) as package:- package.writestr(- "OFD.xml",- '<!DOCTYPE OFD [<!ENTITY x "boom">]><ofd:OFD xmlns:ofd="http://www.ofdspec.org/2016" '- 'Version="1.0" DocType="OFD"><ofd:DocBody><ofd:DocRoot>&x;</ofd:DocRoot></ofd:DocBody></ofd:OFD>',- )- with OfdPackage(dtd.getvalue()) as package:- with pytest.raises(OfdParseError, match="DTD"):- package.root()--def test_ofd_parser_rejects_page_range_and_doclib_reads_metadata(tmp_path: Path) -> None:"""验证 OFD 只支持整本解析且 Doclib 读取原生页数和标题。"""payload = _minimal_payload()@@ -969,34 +145,3 @@ def test_doclib_ingests_ofd_as_local_full_document_flash(tmp_path: Path) -> Noneassert parses == [{"tier": "flash", "status": "pending", "privacy": "local"}]asyncio.run(run())---_LOCAL_SAMPLE_CASES = [- ("issue_10_issue_10_a7b6f9eceb_ofdrw-converter_src_test_resources_helloworld_a7b6f9eceb.ofd", 1),- ("issue_200_issue_200_a2b9080ae3_ofdrw-converter_src_test_resources_999_a2b9080ae3.ofd", 5),- ("issue_208_issue_208_dfed483fa0_ofdrw-layout_src_test_resources_AddWatermarkAnnot_dfed483fa0.ofd", 6),- ("issue_208_issue_208_e7cac8d149_ofdrw-layout_src_test_resources_no_page_container_e7cac8d149.ofd", 1),- ("issue_385_issue_385_bff244b113_ofdrw-layout_src_test_resources_keyword2_bff244b113.ofd", 1),- ("issue_183_issue_183_08a57b9736_48.3_2_08a57b9736.ofd", 1),- ("issue_190_issue_190_6eadbaeb7b_文档2_6eadbaeb7b.ofd", 2),- ("issue_385_issue_385_2be07ec79d_ofdrw-layout_src_test_resources_1-1_2be07ec79d.ofd", 3),- ("issue_271_源文件_bfb11cbcab.ofd", 9),- ("issue_293_issue_293_87024f3f31_test.zip_test_fcb3a84887.ofd", 2),- ("issue_312_issue_312_b8973c8f48_测试_b8973c8f48.ofd", 1),-]--[email protected](("filename", "page_count"), _LOCAL_SAMPLE_CASES)-def test_ofd_local_real_samples_preserve_pages_and_normalized_bboxes(filename: str, page_count: int) -> None:- """在用户本地真实语料存在时验证页数、稳定解析和 bbox 契约。"""- source = _LOCAL_SAMPLE_DIR / filename- if not source.exists():- pytest.skip("local OFD sample corpus is unavailable")- payload = source.read_bytes()- assert hashlib.sha256(payload).hexdigest()[:10] in filename- middle, model = doc_analyze(payload, file_suffix="ofd")- assert len(model.pages) == len(middle.pages) == page_count- for page in middle.pages:- for block in page.blocks:- assert block.bbox is not None- assert all(0 <= value <= 1 for value in block.bbox)diff --git a/tests/unittest/test_flash_office_image_mtef.py b/tests/unittest/test_flash_office_image_mtef.pyindex 60b7b465..ca5eb0d1 100644--- a/tests/unittest/test_flash_office_image_mtef.py+++ b/tests/unittest/test_flash_office_image_mtef.py@@ -1,71 +1,25 @@from __future__ import annotations-from docvortex.export.middle import export_middle_jsonimport asyncio-from collections.abc import Callable-from io import BytesIO-from pathlib import Path-from zipfile import ZIP_DEFLATED, ZipFileimport pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import DocModel-from docvortex.analyzers.native import DocxModel-from docvortex.analyzers.native import PptModel-from docvortex.analyzers.native import PptxModel-from docvortex.analyzers.native import XlsModel-from docvortex.analyzers.native import XlsxModel-from docvortex.analyzers.native.office.doc.doc_converter import DocConverter-from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter-from docvortex.analyzers.native.office.doc.models import DocImage-from docvortex.analyzers.native.office.doc.models import DocImagePayload-from docvortex.analyzers.native.office.doc.models import DocParagraph-from docvortex.analyzers.native.office.doc.models import DocTable-from docvortex.analyzers.native.office.doc.models import DocTableCell-from docvortex.analyzers.native.office.doc.models import DocTableRow-from docvortex.analyzers.native.office.xlsx.xlsx_converter import XlsxConverter-from docvortex.analyzers.native.office.pptx.pptx_converter import PptxConverter-from mineru.types import BlockType, MiddleJson, ModelJson--from _docx_equationxml_test_utils import (- build_equationxml_docx,- build_word_2003_equation_xml,-)-from _span_test_utils import equation, inline as text_spans, inline_textfrom _image_mtef_test_utils import (apps_mfcc_comments,- baseline_wmf_comment,- build_baseline_only_gif,build_gif_with_mtef,build_wmf,)from _legacy_ppt_test_utils import build_equation_ppt-from _legacy_xls_test_utils import build_equation_xls, label_cell-from _mtef_test_utils import build_equation_doc, formula_corpus+from _legacy_xls_test_utils import build_equation_xls+from _mtef_test_utils import build_equation_docfrom _mtef_v5_test_utils import v5_formula_corpusfrom _office_image_mtef_test_utils import (build_image_docx,build_image_pptx,build_image_xlsx,)-from _ooxml_mtef_test_utils import (- build_equation_docx,- build_equation_pptx,- build_equation_xlsx,-)---def _equation_contents(pages: list[list[dict]]) -> list[str]:- """按分页顺序收集独立 equation block 内容。"""-- return [block["content"] for page in pages for block in page if block.get("type") == BlockType.EQUATION]--def _has_image(pages: list[list[dict]]) -> bool:- """判断 model-list 是否至少保留一个图片 block。"""-- return any(block.get("type") == BlockType.IMAGE for page in pages for block in page)+from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.types import BlockType, MiddleJson, ModelJsondef _wmf_formula(mtef: bytes) -> bytes:@@ -80,439 +34,6 @@ def _wmf_formula(mtef: bytes) -> bytes:)-def test_legacy_doc_ppt_xls_recover_wmf_comment_after_bad_native() -> None:- """验证旧三格式 Native 失败后用同一预览 WMF comment 恢复公式。"""-- _name, mtef, expected = v5_formula_corpus()[1]- preview = _wmf_formula(mtef)- invalid = b"invalid native"- cases = [- (- DocModel(),- build_equation_doc(- [(1, invalid)],- preview_storage_ids={1},- preview_payloads={1: preview},- ),- ),- (- PptModel(),- build_equation_ppt(- [invalid],- preview_payload=preview,- ),- ),- (- XlsModel(),- build_equation_xls(- [(1, invalid)],- preview_payload=preview,- ),- ),- ]-- for model, file_bytes in cases:- pages = model.predict(BytesIO(file_bytes))- assert _equation_contents(pages) == [expected]- assert not _has_image(pages)---def test_legacy_doc_direct_gif_comment_recovers_after_bad_native() -> None:- """验证 DOC PICF magic fallback 保留并解析原始 GIF/001。"""-- _name, mtef, expected = v5_formula_corpus()[0]- image = build_gif_with_mtef(mtef, chunk_size=3)- pages = DocModel().predict(- BytesIO(- build_equation_doc(- [(1, b"invalid native")],- preview_storage_ids={1},- preview_payloads={1: image},- )- )- )-- assert _equation_contents(pages) == [expected]- assert not _has_image(pages)---def test_legacy_native_mtef_precedes_conflicting_wmf_comment() -> None:- """验证旧三格式有效 Native 优先于内容不同的 WMF comment。"""-- _native_name, native, expected = formula_corpus()[0]- _image_name, image_mtef, _image_expected = v5_formula_corpus()[1]- preview = _wmf_formula(image_mtef)- cases = [- (- DocModel(),- build_equation_doc(- [(1, native)],- preview_storage_ids={1},- preview_payloads={1: preview},- ),- ),- (- PptModel(),- build_equation_ppt([native], preview_payload=preview),- ),- (- XlsModel(),- build_equation_xls([(1, native)], preview_payload=preview),- ),- ]-- for model, file_bytes in cases:- assert _equation_contents(model.predict(BytesIO(file_bytes))) == [expected]---def test_xls_wmf_comment_equation_enters_table_cell() -> None:- """验证 XLS 图片 comment 公式进入 cell HTML 且不重复输出。"""-- _name, mtef, expected = v5_formula_corpus()[0]- pages = XlsModel().predict(- BytesIO(- build_equation_xls(- [(1, b"invalid native")],- preview_payload=_wmf_formula(mtef),- cell_records=label_cell(0, 0, "value"),- )- )- )-- assert _equation_contents(pages) == []- assert len(pages[0]) == 1- assert pages[0][0]["type"] == BlockType.TABLE- assert f"<eq>{expected}</eq>" in pages[0][0]["content"]---def test_doc_image_comment_equation_enters_nested_table_html() -> None:- """验证 DOC 段落图片与独立图片在嵌套表格中都写入 eq。"""-- payload = DocImagePayload(- data=b"",- extension="wmf",- content_type="image/wmf",- equation_latex="x+y",- )- paragraph = DocParagraph(- cp_start=0,- cp_end=1,- images=[payload],- )- nested = DocTable(- cp_start=1,- cp_end=2,- rows=[DocTableRow(cells=[DocTableCell(blocks=[DocImage(cp=1, payload=payload)])])],- )- table = DocTable(- cp_start=0,- cp_end=2,- rows=[DocTableRow(cells=[DocTableCell(blocks=[paragraph, nested])])],- )-- html = DocConverter._table_html(table)-- assert html.count("<eq>x+y</eq>") == 2- assert "<img" not in html---def test_docx_picture_comment_flows_inline_table_header_and_standalone() -> None:- """验证 DOCX 普通 WMF/GIF 图片进入统一公式 token 重建链路。"""-- first = v5_formula_corpus()[0]- second = v5_formula_corpus()[1]- wmf = _wmf_formula(first[1])- gif = build_gif_with_mtef(second[1], chunk_size=5)- standalone = DocxModel().predict(BytesIO(build_image_docx(wmf)))- inline = DocxModel().predict(BytesIO(build_image_docx(gif, inline=True)))- table = DocxModel().predict(BytesIO(build_image_docx(gif, table=True)))- header = DocxModel().predict(BytesIO(build_image_docx(gif, header=True)))-- assert standalone == [[{"type": BlockType.EQUATION, "content": first[2]}]]- assert inline == [- [- {- "type": BlockType.TEXT,- "content": [*text_spans("before "), equation(second[2]), *text_spans(" after")],- }- ]- ]- assert table[0][0]["type"] == BlockType.TABLE- assert f"<eq>{second[2]}</eq>" in table[0][0]["content"]- assert "<img" not in table[0][0]["content"]- assert header == [- [- {- "type": BlockType.HEADER,- "content": [equation(second[2])],- }- ]- ]---def test_docx_picture_comment_flows_title_and_list() -> None:- """验证 DOCX 图片公式在标题和列表中保持 eq 行内语义。"""-- _name, mtef, expected = v5_formula_corpus()[0]- image = build_gif_with_mtef(mtef)- title = DocxModel().predict(- BytesIO(- build_image_docx(- image,- inline=True,- paragraph_style="Title",- )- )- )- bullet = DocxModel().predict(- BytesIO(- build_image_docx(- image,- inline=True,- paragraph_style="List Bullet",- )- )- )-- assert title[0][0] == {- "type": BlockType.DOC_TITLE,- "level": 1,- "content": [*text_spans("before "), equation(expected), *text_spans(" after")],- }- assert bullet[0][0]["type"] == BlockType.LIST- assert inline_text(bullet[0][0]["content"][0]["content"]) == f"before {expected} after"--[email protected]("carrier", ["wmf", "gif"])-def test_pptx_picture_comment_equation_keeps_shape_order(carrier: str) -> None:- """验证 PPTX 普通图片 comment 以原 shape 顺序输出 equation。"""-- _name, mtef, expected = v5_formula_corpus()[2]- image = _wmf_formula(mtef) if carrier == "wmf" else build_gif_with_mtef(mtef, chunk_size=7)-- pages = PptxModel().predict(BytesIO(build_image_pptx(image)))-- assert _equation_contents(pages) == [expected]- assert not _has_image(pages)--[email protected]("carrier", ["wmf", "gif"])-def test_pptx_notes_picture_comment_becomes_page_footnote(- carrier: str,-) -> None:- """验证 PPTX notes 中的 WMF/GIF 图片公式输出 page_footnote。"""-- _name, mtef, expected = v5_formula_corpus()[0]- image = _wmf_formula(mtef) if carrier == "wmf" else build_gif_with_mtef(mtef)- pages = PptxModel().predict(- BytesIO(- build_image_pptx(- image,- notes=True,- )- )- )-- assert pages == [- [- {- "type": BlockType.PAGE_FOOTNOTE,- "content": [equation(expected)],- }- ]- ]---def test_pptx_notes_bad_ole_native_uses_wmf_preview_comment() -> None:- """验证 notes 中 OLE Native 失败时继续解析同对象 WMF preview。"""-- _name, mtef, expected = v5_formula_corpus()[0]- pages = PptxModel().predict(- BytesIO(- build_equation_pptx(- [b"invalid native"],- notes=True,- preview_image=_wmf_formula(mtef),- )- )- )-- assert pages == [- [- {- "type": BlockType.PAGE_FOOTNOTE,- "content": [equation(expected)],- }- ]- ]--[email protected]("carrier", ["wmf", "gif"])-def test_xlsx_image_comment_equation_enters_visual_and_table_paths(- carrier: str,-) -> None:- """验证 XLSX 普通 WMF/GIF comment 按 anchor 输出或进入表格 cell。"""-- _name, mtef, expected = v5_formula_corpus()[0]- image = _wmf_formula(mtef) if carrier == "wmf" else build_gif_with_mtef(mtef, chunk_size=3)- standalone = XlsxModel().predict(BytesIO(build_image_xlsx(image)))- table = XlsxModel().predict(BytesIO(build_image_xlsx(image, cell_value="value")))-- assert _equation_contents(standalone) == [expected]- assert _equation_contents(table) == []- assert table[0][0]["type"] == BlockType.TABLE- assert f"<eq>{expected}</eq>" in table[0][0]["content"]---def test_xlsx_cell_image_comment_returns_eq_html() -> None:- """验证 XLSX cellimages media 在返回 img 前尝试 comment 公式。"""-- _name, mtef, expected = v5_formula_corpus()[0]- image = build_gif_with_mtef(mtef)- package = BytesIO()- with ZipFile(package, "w", ZIP_DEFLATED) as archive:- archive.writestr("xl/media/image1.gif", image)- converter = XlsxConverter()- converter.zf = ZipFile(BytesIO(package.getvalue()))- converter.cell_image_map = {"image-id": "media/image1.gif"}- try:- html = converter._resolve_cell_image('DISPIMG("image-id")')- finally:- converter.zf.close()-- assert html == f"<eq>{expected}</eq>"--- ("model", "builder"),- [- (DocxModel(), build_equation_docx),- (PptxModel(), build_equation_pptx),- (XlsxModel(), build_equation_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_ooxml_bad_native_recovers_from_wmf_preview_comment(- model: DocxModel | PptxModel | XlsxModel,- builder: Callable[..., bytes],-) -> None:- """验证现代三格式 OLE Native 失败后升级有效 WMF preview。"""-- _name, mtef, expected = v5_formula_corpus()[1]- pages = model.predict(- BytesIO(- builder(- [b"invalid native"],- prog_id="Equation.DSMT4",- preview_image=_wmf_formula(mtef),- )- )- )-- assert _equation_contents(pages) == [expected]- assert not _has_image(pages)--- ("model", "builder"),- [- (DocxModel(), build_equation_docx),- (PptxModel(), build_equation_pptx),- (XlsxModel(), build_equation_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_ooxml_native_precedes_conflicting_wmf_preview_comment(- model: DocxModel | PptxModel | XlsxModel,- builder: Callable[..., bytes],-) -> None:- """验证现代三格式有效 OLE Native 优先于图片 comment。"""-- _native_name, native, expected = formula_corpus()[0]- _image_name, image_mtef, _image_expected = v5_formula_corpus()[1]- pages = model.predict(- BytesIO(- builder(- [native],- prog_id="Equation.DSMT4",- preview_image=_wmf_formula(image_mtef),- )- )- )-- assert _equation_contents(pages) == [expected]---def test_docx_equationxml_and_ooxml_omml_precede_image_comment() -> None:- """验证 equationxml/OMML 继续高于同对象图片 comment。"""-- _name, image_mtef, _expected = v5_formula_corpus()[0]- preview = _wmf_formula(image_mtef)- docx = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [build_word_2003_equation_xml("x")],- keep_mtef=True,- mtef_payloads=[b"invalid native"],- preview_image=preview,- )- )- )- pptx = PptxModel().predict(- BytesIO(- build_equation_pptx(- [b"invalid native"],- alternate_omml=True,- preview_image=preview,- )- )- )- xlsx = XlsxModel().predict(- BytesIO(- build_equation_xlsx(- [b"invalid native"],- anchor_mode="drawing",- alternate_omml=True,- preview_image=preview,- )- )- )-- assert _equation_contents(docx) == ["x"]- assert _equation_contents(pptx) == ["z"]- assert _equation_contents(xlsx) == ["z"]---def test_bad_image_comment_keeps_original_picture_or_placeholder() -> None:- """验证 baseline-only WMF 不升级公式并继续输出图片。"""-- image = build_wmf([baseline_wmf_comment(0)], placeable=True)- cases = [- (DocxModel(), build_image_docx(image)),- (PptxModel(), build_image_pptx(image)),- ]-- for model, file_bytes in cases:- pages = model.predict(BytesIO(file_bytes))- assert _equation_contents(pages) == []- assert _has_image(pages)---def test_bad_image_comment_preview_exports_to_sidecar(tmp_path: Path) -> None:- """验证未升级的图片导出后 sidecar 完整且 JSON 不残留 base64。"""-- middle, _model = doc_analyze(- build_image_docx(build_baseline_only_gif()),- file_suffix="docx",- )-- result = export_middle_json(middle, tmp_path / "image-mtef-fallback")-- assert len(result.image_paths) == 1- assert result.image_paths[0].stat().st_size > 0- assert "base64," not in result.json_path.read_text(encoding="utf-8")--@pytest.mark.parametrize("file_suffix",["doc", "docx", "ppt", "pptx", "xls", "xlsx"],@@ -561,21 +82,3 @@ def test_image_comment_mtef_runs_through_sync_async_analyze(assert middle.pages[0].blocks[0].content == expectedassert async_model == modelassert async_middle == middle---def test_modern_converter_reuse_resets_image_comment_decoder() -> None:- """验证现代 converter 复用时图片公式缓存和资源预算不会串文档。"""-- first = v5_formula_corpus()[0]- second = v5_formula_corpus()[1]- cases = [- (DocxConverter(), build_image_docx),- (PptxConverter(), build_image_pptx),- (XlsxConverter(), build_image_xlsx),- ]-- for converter, builder in cases:- converter.convert(BytesIO(builder(build_gif_with_mtef(first[1]))))- assert _equation_contents(converter.pages) == [first[2]]- converter.convert(BytesIO(builder(build_gif_with_mtef(second[1]))))- assert _equation_contents(converter.pages) == [second[2]]diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.pydeleted file mode 100644index 4ed4b994..00000000--- a/tests/unittest/test_flash_office_metafile.py+++ /dev/null@@ -1,332 +0,0 @@-"""验证独立 WMF/EMF 渲染包的 Office 集成。"""--from __future__ import annotations--import base64-import struct-import zlib-from io import BytesIO-from unittest.mock import Mock-from zipfile import ZIP_DEFLATED, ZipFile--import pytest-from _legacy_ppt_test_utils import build_equation_ppt-from _legacy_xls_test_utils import build_equation_xls-from _metafile_test_utils import (- basic_wmf,- build_emf,- emf_create_brush,- emf_create_pen,- emf_font,- emf_rectangle,- emf_select_object,- emf_stretch_dib,- emf_text,-)-from _mtef_test_utils import build_equation_doc-from _odf_test_utils import build_odp_fixture, build_ods_fixture, build_odt_fixture-from _office_image_mtef_test_utils import build_image_docx, build_image_pptx, build_image_xlsx-from metafile_render import (- MetafileResourceLimitError,- render_metafile,-)-from PIL import Image--from docvortex.analyzers.native import DocModel-from docvortex.analyzers.native import DocxModel-from docvortex.analyzers.native import OdpModel-from docvortex.analyzers.native import OdsModel-from docvortex.analyzers.native import OdtModel-from docvortex.analyzers.native import PptModel-from docvortex.analyzers.native import PptxModel-from docvortex.analyzers.native import RtfModel-from docvortex.analyzers.native import XlsModel-from docvortex.analyzers.native import XlsxModel-from docvortex.analyzers.native.office import image as office_image-from docvortex.analyzers.native.office.legacy.officeart import OfficeArtRecord-from docvortex.analyzers.native.office.legacy.officeart import decode_blip-from docvortex.analyzers.native.office.pptx.pptx_converter import PptxConverter-from docvortex.analyzers.native.office.xlsx.xlsx_converter import XlsxConverter-from docvortex.foundation.image_payload import extract_generated_svg_fallback---def _open_result(payload: bytes) -> Image.Image:- """解码渲染结果并返回脱离 BytesIO 生命周期的 RGBA 图片。"""- with Image.open(BytesIO(payload)) as image:- image.load()- return image.convert("RGBA")---def _svg_data_uri_fallback(data_uri: str) -> tuple[Image.Image, tuple[int, int], bytes]:- """解析 MinerU SVG data URI,并返回 fallback 图片、逻辑尺寸和 SVG。"""- assert data_uri.startswith("data:image/svg+xml;base64,")- svg = base64.b64decode(data_uri.split(",", 1)[1])- fallback, logical_width, logical_height = extract_generated_svg_fallback(svg)- return _open_result(fallback), (logical_width, logical_height), svg---def _basic_emf_records() -> list[bytes]:- """返回覆盖画笔、画刷、文字和 DIB 的基础 EMF records。"""- return [- emf_create_pen(1, 0x00FF0000, width=2),- emf_create_brush(2, 0x0000FF00),- emf_select_object(1),- emf_select_object(2),- emf_rectangle(5, 5, 95, 95),- emf_stretch_dib(),- emf_font(3),- emf_select_object(3),- emf_text("EMF", 20, 50, dx=18),- ]---def _collect_image_data_uris(value: object) -> list[str]:- """递归收集 raw model-list 中的 image_base64 字段。"""- if isinstance(value, dict):- result = [value["image_base64"]] if isinstance(value.get("image_base64"), str) else []- for item in value.values():- result.extend(_collect_image_data_uris(item))- return result- if isinstance(value, list):- result: list[str] = []- for item in value:- result.extend(_collect_image_data_uris(item))- return result- return []---def _replace_zip_member(package: bytes, member_name: str, payload: bytes) -> bytes:- """替换测试 ZIP 中的单个成员并保留其他成员及压缩方式。"""- output = BytesIO()- with ZipFile(BytesIO(package)) as source, ZipFile(output, "w") as target:- for info in source.infolist():- target.writestr(info, payload if info.filename == member_name else source.read(info.filename))- return output.getvalue()---def _build_doc_with_wmf_preview(payload: bytes) -> bytes:- """构造 Native 失败后使用 WMF PICF 预览的 DOC。"""- return build_equation_doc(- [(1, b"invalid")],- preview_storage_ids={1},- preview_payloads={1: payload},- )---def _build_ppt_with_wmf_preview(payload: bytes) -> bytes:- """构造 Native 失败后使用 OfficeArt WMF 预览的 PPT。"""- return build_equation_ppt([b"invalid"], preview_payload=payload)---def _build_xls_with_wmf_preview(payload: bytes) -> bytes:- """构造 Native 失败后使用 OfficeArt WMF 预览的 XLS。"""- return build_equation_xls([(1, b"invalid")], preview_payload=payload)---def test_oversized_generated_svg_degrades_to_png_for_office_consumers(monkeypatch: pytest.MonkeyPatch) -> None:- """通过公开 API 的资源错误验证 Office 消费者可靠回退到 PNG。"""- data = build_emf([emf_stretch_dib()])- png = render_metafile(data, output_format="png")- render = Mock(side_effect=[MetafileResourceLimitError("generated SVG exceeds budget"), png])- monkeypatch.setattr(office_image, "render_metafile", render)- data_uri = office_image.serialize_office_image(data, part_name="image.emf", content_type="image/emf")- assert data_uri is not None- assert data_uri.startswith("data:image/png;base64,")- assert [call.kwargs["output_format"] for call in render.call_args_list] == ["svg", "png"]- assert all(call.kwargs["dpi"] == 200 and call.kwargs["backend"] == "auto" for call in render.call_args_list)---def test_office_serializer_returns_generated_svg(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 Office 图片入口返回安全 SVG 和 PNG fallback。"""- data_uri = office_image.serialize_office_image(- build_emf(_basic_emf_records()),- part_name="/word/media/image1.emf",- content_type="image/x-emf",- )-- assert data_uri is not None- fallback, logical_size, svg = _svg_data_uri_fallback(data_uri)- assert logical_size == (200, 200)- assert fallback.getbbox() is not None- assert b"<path" in svg---def test_officeart_emu_size_controls_standard_wmf_output(monkeypatch: pytest.MonkeyPatch) -> None:- """验证无 placeable header 的 OfficeArt WMF 使用 ptSize EMU 定标。"""- standard_wmf = basic_wmf()[22:]- data_uri = office_image.serialize_office_image(- standard_wmf,- part_name="picture.wmf",- content_type="image/wmf",- render_size_emu=(914_400, 457_200),- )-- assert data_uri is not None- fallback, logical_size, _svg = _svg_data_uri_fallback(data_uri)- assert logical_size == (200, 100)- assert fallback.size == (400, 200)---def test_officeart_metafile_header_preserves_payload_and_emu_size() -> None:- """验证 BLIP 解包保留 WMF bytes,并读取规范 ptSize EMU。"""- standard_wmf = basic_wmf()[22:]- compressed = zlib.compress(standard_wmf)- metafile_header = bytearray(34)- struct.pack_into("<I", metafile_header, 0, len(standard_wmf))- struct.pack_into("<ii", metafile_header, 20, 914_400, 457_200)- struct.pack_into("<I", metafile_header, 28, len(compressed))- metafile_header[32:34] = b"\x00\xfe"- record = OfficeArtRecord(- offset=0,- version=0,- instance=0,- record_type=0xF01B,- payload=b"\x00" * 16 + bytes(metafile_header) + compressed,- )-- decoded = decode_blip(record)-- assert decoded is not None- assert decoded.data == standard_wmf- assert decoded.render_size_emu == (914_400, 457_200)---def test_office_serializer_uses_only_library_backend(monkeypatch: pytest.MonkeyPatch) -> None:- """所有平台都只调用独立库,失败后直接使用占位图。"""- data = build_emf(_basic_emf_records())- generated = Mock(return_value="data:image/svg+xml;base64,generated")- pillow_open = Mock(side_effect=AssertionError("MinerU must not render metafiles with Pillow"))- monkeypatch.setattr(office_image, "_serialize_metafile", generated)- monkeypatch.setattr(office_image.Image, "open", pillow_open)- monkeypatch.setattr(office_image, "get_standard_vector_placeholder_data_uri", lambda: "placeholder")- assert office_image.serialize_office_image(data) == "data:image/svg+xml;base64,generated"- generated.return_value = None- assert office_image.serialize_office_image(data) == "placeholder"- pillow_open.assert_not_called()---def test_pptx_picture_path_uses_cross_platform_metafile_renderer(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 PPTX 普通 picture 不再绕过共享 WMF/EMF 序列化入口。"""- converter = PptxConverter()- data = build_emf(_basic_emf_records())-- def fake_image_data(_shape: object) -> tuple[bytes, str]:- """返回固定 EMF 载荷以隔离 shape relationship 解析。"""- return data, "image/x-emf"-- monkeypatch.setattr(converter, "_get_shape_image_data", fake_image_data)- converter._handle_pictures(object())-- assert converter.cur_page[0]["image_base64"].startswith("data:image/svg+xml;base64,")---def test_xlsx_wps_cell_image_uses_cross_platform_metafile_renderer(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 WPS DISPIMG 的 cell-image 分支统一调用 Office 图片序列化器。"""- package = BytesIO()- with ZipFile(package, "w", ZIP_DEFLATED) as archive:- archive.writestr("xl/media/image1.emf", build_emf(_basic_emf_records()))- converter = XlsxConverter()- converter.zf = ZipFile(BytesIO(package.getvalue()))- converter.cell_image_map = {"image-id": "media/image1.emf"}- try:- html = converter._resolve_cell_image('DISPIMG("image-id")')- finally:- converter.zf.close()-- assert html.startswith('<img src="data:image/svg+xml;base64,')--- ("model", "builder"),- [- (DocxModel(), build_image_docx),- (PptxModel(), build_image_pptx),- (XlsxModel(), build_image_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_modern_office_models_emit_rendered_emf_svg(- model: object,- builder: object,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 DOCX/PPTX/XLSX 完整模型链都产出安全 EMF SVG。"""- package = builder(build_emf(_basic_emf_records())) # type: ignore[operator]- pages = model.predict(BytesIO(package)) # type: ignore[attr-defined]- images = _collect_image_data_uris(pages)-- assert images- assert all(image.startswith("data:image/svg+xml;base64,") for image in images)- _fallback, logical_size, _svg = _svg_data_uri_fallback(images[0])- assert logical_size == (200, 200)--- ("model", "builder"),- [- (DocModel(), _build_doc_with_wmf_preview),- (PptModel(), _build_ppt_with_wmf_preview),- (XlsModel(), _build_xls_with_wmf_preview),- ],- ids=["doc", "ppt", "xls"],-)-def test_legacy_office_models_emit_rendered_wmf_svg(- model: object,- builder: object,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 DOC/PPT/XLS 的 OfficeArt/PICF WMF 预览进入跨平台 SVG。"""- pages = model.predict(BytesIO(builder(basic_wmf()))) # type: ignore[attr-defined,operator]- images = _collect_image_data_uris(pages)-- assert images- assert all(image.startswith("data:image/svg+xml;base64,") for image in images)- fallback, logical_size, _svg = _svg_data_uri_fallback(images[0])- assert logical_size == (200, 200)- assert fallback.size == (400, 400)---def test_rtf_model_emf_picture_emits_rendered_svg(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 RTF emfblip 从 pict 捕获一路进入跨平台 SVG。"""- emf = build_emf(_basic_emf_records())- rtf = b"{\\rtf1 before {\\pict\\emfblip " + emf.hex().encode("ascii") + b"} after\\par}"- images = _collect_image_data_uris(RtfModel().predict(BytesIO(rtf)))-- assert images- assert all(image.startswith("data:image/svg+xml;base64,") for image in images)--- ("model", "builder"),- [- (OdtModel(), build_odt_fixture),- (OdsModel(), build_ods_fixture),- (OdpModel(), build_odp_fixture),- ],- ids=["odt", "ods", "odp"],-)-def test_odf_models_emit_rendered_emf_svg(- model: object,- builder: object,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 ODT/ODS/ODP 包内 WMF/EMF 图片都复用统一渲染入口。"""- package = builder() # type: ignore[operator]- package = _replace_zip_member(package, "Pictures/pixel.png", build_emf(_basic_emf_records()))- images = _collect_image_data_uris(model.predict(BytesIO(package))) # type: ignore[attr-defined]-- assert images- assert all(image.startswith("data:image/svg+xml;base64,") for image in images)---def test_pillow_identified_metafile_is_routed_before_load(monkeypatch: pytest.MonkeyPatch) -> None:- """由 Pillow 补充识别的矢量图也交给库处理,禁止触发 MinerU 内部原生加载。"""- image = Mock(format="WMF")- generated = Mock(return_value="data:image/svg+xml;base64,generated")- monkeypatch.setattr(office_image.Image, "open", Mock(return_value=image))- monkeypatch.setattr(office_image, "_serialize_metafile", generated)- data = b"identified-by-pillow"- result = office_image.serialize_office_image(data, render_size_emu=(914400, 457200))- assert result == "data:image/svg+xml;base64,generated"- generated.assert_called_once_with(data, "WMF", size_hint=(200, 100))- image.load.assert_not_called()diff --git a/tests/unittest/test_flash_office_mtef_v5.py b/tests/unittest/test_flash_office_mtef_v5.pyindex 0db58601..f9782a5b 100644--- a/tests/unittest/test_flash_office_mtef_v5.py+++ b/tests/unittest/test_flash_office_mtef_v5.py@@ -2,246 +2,20 @@ from __future__ import annotationsimport asynciofrom collections.abc import Callable-from io import BytesIOimport pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import DocModel-from docvortex.analyzers.native import DocxModel-from docvortex.analyzers.native import PptModel-from docvortex.analyzers.native import PptxModel-from docvortex.analyzers.native import XlsModel-from docvortex.analyzers.native import XlsxModel-from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter-from docvortex.analyzers.native.office.pptx.pptx_converter import PptxConverter-from docvortex.analyzers.native.office.xlsx.xlsx_converter import XlsxConverter-from mineru.types import BlockType, MiddleJson, ModelJson--from _docx_equationxml_test_utils import (- build_equationxml_docx,- build_word_2003_equation_xml,-)from _legacy_ppt_test_utils import build_equation_ppt-from _legacy_xls_test_utils import build_equation_xls, label_cell-from _mtef_test_utils import build_equation_doc, formula_corpus+from _legacy_xls_test_utils import build_equation_xls+from _mtef_test_utils import build_equation_docfrom _mtef_v5_test_utils import v5_formula_corpusfrom _ooxml_mtef_test_utils import (build_equation_docx,build_equation_pptx,build_equation_xlsx,)-from _span_test_utils import equation---def _equation_contents(pages: list[list[dict]]) -> list[str]:- """按分页和 block 顺序收集独立公式内容。"""-- return [block["content"] for page in pages for block in page if block.get("type") == BlockType.EQUATION]---def _has_preview_image(pages: list[list[dict]]) -> bool:- """判断 model-list 是否至少保留一个图片回退。"""-- return any(block.get("type") == BlockType.IMAGE for page in pages for block in page)---def test_six_office_models_decode_the_full_mtef_v5_corpus() -> None:- """验证 DOC/DOCX/PPT/PPTX/XLS/XLSX 对完整 v5 语料输出一致。"""-- corpus = v5_formula_corpus()- formulas = [mtef for _name, mtef, _expected in corpus]- expected = [latex for _name, _mtef, latex in corpus]- prog_id = "Equation.DSMT4"- cases = [- (- DocModel(),- build_equation_doc(- [(1000 + index, mtef) for index, mtef in enumerate(formulas)],- prog_id=prog_id,- ),- ),- (- DocxModel(),- build_equation_docx(formulas, prog_id=prog_id),- ),- (- PptModel(),- build_equation_ppt(formulas, preview=False, prog_id=prog_id),- ),- (- PptxModel(),- build_equation_pptx(formulas, prog_id=prog_id),- ),- (- XlsModel(),- build_equation_xls(- [(2000 + index, mtef) for index, mtef in enumerate(formulas)],- preview=False,- prog_id=prog_id,- ),- ),- (- XlsxModel(),- build_equation_xlsx(formulas, prog_id=prog_id),- ),- ]-- for model, file_bytes in cases:- assert _equation_contents(model.predict(BytesIO(file_bytes))) == expected--- ("model", "builder"),- [- (DocxModel(), build_equation_docx),- (PptxModel(), build_equation_pptx),- (XlsxModel(), build_equation_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_ooxml_prog_id_and_mtef_version_are_orthogonal(- model: DocxModel | PptxModel | XlsxModel,- builder: Callable[..., bytes],-) -> None:- """验证 Equation.3 可承载 v5,DSMT4/Equation 也可承载 v3。"""-- _v5_name, v5, v5_expected = v5_formula_corpus()[1]- _v3_name, v3, v3_expected = formula_corpus()[1]-- assert _equation_contents(model.predict(BytesIO(builder([v5], prog_id="Equation.3")))) == [v5_expected]- assert _equation_contents(model.predict(BytesIO(builder([v3], prog_id="Equation.DSMT4")))) == [v3_expected]- assert _equation_contents(model.predict(BytesIO(builder([v5], prog_id="Equation")))) == [v5_expected]--- ("model", "builder"),- [- (DocxModel(), build_equation_docx),- (PptxModel(), build_equation_pptx),- (XlsxModel(), build_equation_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_non_equation_ooxml_prog_id_is_not_probed(- model: DocxModel | PptxModel | XlsxModel,- builder: Callable[..., bytes],-) -> None:- """验证非公式或空后缀 ProgID 不探测有效 v5 OLE 内容。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- for prog_id in ("Package", "Equation."):- pages = model.predict(BytesIO(builder([mtef], prog_id=prog_id)))- assert _equation_contents(pages) == []--- ("model", "builder"),- [- (DocxModel(), build_equation_docx),- (PptxModel(), build_equation_pptx),- (XlsxModel(), build_equation_xlsx),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_mtef_v5_icon_mode_keeps_icon_preview(- model: DocxModel | PptxModel | XlsxModel,- builder: Callable[..., bytes],-) -> None:- """验证图标模式不展开有效 v5,只保留原图标预览。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- pages = model.predict(- BytesIO(- builder(- [mtef],- prog_id="Equation.DSMT4",- show_as_icon=True,- )- )- )-- assert _equation_contents(pages) == []- assert _has_preview_image(pages)---def test_xlsx_linked_mtef_v5_object_never_loads_external_target() -> None:- """验证 XLSX 外链 MathType 对象只保留包内预览,不访问目标。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- pages = XlsxModel().predict(- BytesIO(- build_equation_xlsx(- [mtef],- prog_id="Equation.DSMT4",- linked=True,- )- )- )-- assert _equation_contents(pages) == []- assert _has_preview_image(pages)--- ("model", "file_bytes"),- [- (- DocModel(),- build_equation_doc(- [(1, bytes([4, 1, 0, 3, 5, 0]))],- preview_storage_ids={1},- prog_id="Equation.DSMT4",- ),- ),- (- DocxModel(),- build_equation_docx(- [bytes([4, 1, 0, 3, 5, 0])],- prog_id="Equation.DSMT4",- ),- ),- (- PptModel(),- build_equation_ppt(- [bytes([4, 1, 0, 3, 5, 0])],- prog_id="Equation.DSMT4",- ),- ),- (- PptxModel(),- build_equation_pptx(- [bytes([4, 1, 0, 3, 5, 0])],- prog_id="Equation.DSMT4",- ),- ),- (- XlsModel(),- build_equation_xls(- [(1, bytes([4, 1, 0, 3, 5, 0]))],- prog_id="Equation.DSMT4",- ),- ),- (- XlsxModel(),- build_equation_xlsx(- [bytes([4, 1, 0, 3, 5, 0])],- prog_id="Equation.DSMT4",- ),- ),- ],- ids=["doc", "docx", "ppt", "pptx", "xls", "xlsx"],-)-def test_mtef_v4_keeps_preview_in_all_six_formats(- model: DocModel | DocxModel | PptModel | PptxModel | XlsModel | XlsxModel,- file_bytes: bytes,-) -> None:- """验证六格式遇到 v4 均不猜测解析并保留缓存预览。"""-- pages = model.predict(BytesIO(file_bytes))- assert _equation_contents(pages) == []- assert _has_preview_image(pages)+from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.types import BlockType, MiddleJson, ModelJson@pytest.mark.parametrize(@@ -282,160 +56,3 @@ def test_mtef_v5_runs_through_sync_async_analyze(assert middle.pages[0].blocks[0].content == expectedassert async_model == modelassert async_middle == middle---def test_mtef_v5_enters_docx_xls_xlsx_table_cells() -> None:- """验证三种文档/表格格式的 v5 公式进入 cell HTML 且不重复输出。"""-- _name, mtef, expected = v5_formula_corpus()[0]- docx = DocxModel().predict(- BytesIO(- build_equation_docx(- [mtef],- table=True,- prog_id="Equation.DSMT4",- )- )- )- xls = XlsModel().predict(- BytesIO(- build_equation_xls(- [(10, mtef)],- cell_records=label_cell(0, 0, "value"),- prog_id="Equation.DSMT4",- )- )- )- xlsx = XlsxModel().predict(- BytesIO(- build_equation_xlsx(- [mtef],- cell_value="value",- prog_id="Equation.DSMT4",- )- )- )-- for pages in (docx, xls, xlsx):- assert _equation_contents(pages) == []- assert pages[0][0]["type"] == BlockType.TABLE- assert f"<eq>{expected}</eq>" in pages[0][0]["content"]---def test_docx_equationxml_and_ooxml_omml_precede_mtef_v5() -> None:- """验证 DOCX equationxml 以及 PPTX/XLSX OMML 都优先于有效 v5。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- docx = DocxModel().predict(- BytesIO(- build_equationxml_docx(- [build_word_2003_equation_xml("x")],- keep_mtef=True,- mtef_payloads=[mtef],- prog_id="Equation.DSMT4",- )- )- )- pptx = PptxModel().predict(- BytesIO(- build_equation_pptx(- [mtef],- alternate_omml=True,- prog_id="Equation.DSMT4",- )- )- )- xlsx = XlsxModel().predict(- BytesIO(- build_equation_xlsx(- [mtef],- anchor_mode="drawing",- alternate_omml=True,- prog_id="Equation.DSMT4",- )- )- )-- assert _equation_contents(docx) == ["x"]- assert _equation_contents(pptx) == ["z"]- assert _equation_contents(xlsx) == ["z"]---def test_docx_header_footer_and_pptx_notes_accept_mtef_v5() -> None:- """验证 v5 在 DOCX 页眉页脚和 PPTX notes 中保持归属。"""-- corpus = v5_formula_corpus()- first = corpus[0]- second = corpus[1]- docx = DocxModel().predict(- BytesIO(- build_equation_docx(- [first[1], second[1]],- header_footer=True,- prog_id="Equation.DSMT4",- )- )- )- pptx = PptxModel().predict(- BytesIO(- build_equation_pptx(- [first[1]],- notes=True,- prog_id="Equation.DSMT4",- )- )- )-- assert docx == [- [- {"type": BlockType.HEADER, "content": [equation(first[2])]},- {"type": BlockType.FOOTER, "content": [equation(second[2])]},- ]- ]- assert pptx == [- [- {- "type": BlockType.PAGE_FOOTNOTE,- "content": [equation(first[2])],- }- ]- ]---def test_mtef_v5_model_streams_remain_open_in_all_six_formats() -> None:- """验证六种 Model 的 v5 路径均不关闭调用方输入流。"""-- _name, mtef, _expected = v5_formula_corpus()[0]- prog_id = "Equation.DSMT4"- cases = [- (DocModel(), build_equation_doc([(1, mtef)], prog_id=prog_id)),- (DocxModel(), build_equation_docx([mtef], prog_id=prog_id)),- (PptModel(), build_equation_ppt([mtef], prog_id=prog_id)),- (PptxModel(), build_equation_pptx([mtef], prog_id=prog_id)),- (XlsModel(), build_equation_xls([(1, mtef)], prog_id=prog_id)),- (XlsxModel(), build_equation_xlsx([mtef], prog_id=prog_id)),- ]-- for model, file_bytes in cases:- stream = BytesIO(file_bytes)- model.predict(stream)- assert not stream.closed---def test_modern_office_converter_reuse_resets_v5_state() -> None:- """验证现代 Office converter 复用时 v5 缓存和分页状态不会串文档。"""-- first = v5_formula_corpus()[0]- second = v5_formula_corpus()[1]- prog_id = "Equation.DSMT4"- cases = [- (DocxConverter(), build_equation_docx),- (PptxConverter(), build_equation_pptx),- (XlsxConverter(), build_equation_xlsx),- ]-- for converter, builder in cases:- converter.convert(BytesIO(builder([first[1]], prog_id=prog_id)))- assert _equation_contents(converter.pages) == [first[2]]- converter.convert(BytesIO(builder([second[1]], prog_id=prog_id)))- assert _equation_contents(converter.pages) == [second[2]]diff --git a/tests/unittest/test_flash_office_package_normalizers.py b/tests/unittest/test_flash_office_package_normalizers.pydeleted file mode 100644index 54803a69..00000000--- a/tests/unittest/test_flash_office_package_normalizers.py+++ /dev/null@@ -1,76 +0,0 @@-from __future__ import annotations--from io import BytesIO-from zipfile import ZIP_DEFLATED, ZipFile-import xml.etree.ElementTree as ET--from lxml import etree--from docvortex.analyzers.native.office.docx.package_normalizer import normalize_docx_package-from docvortex.analyzers.native.office.pptx.package_normalizer import normalize_pptx_package-from docvortex.analyzers.native.office.xlsx.package_normalizer import normalize_xlsx_package---_PACKAGE_RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"-_SPREADSHEETML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"---def _zip_bytes(members: dict[str, bytes]) -> bytes:- """把合成成员写成确定性的 OOXML 测试包。"""- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as archive:- for name, data in members.items():- archive.writestr(name, data)- return output.getvalue()---def test_docx_normalizer_removes_missing_internal_relationship() -> None:- """验证 DOCX 仍删除指向缺失成员的内部 relationship。"""- relationships = f"""- <Relationships xmlns="{_PACKAGE_RELATIONSHIPS_NS}">- <Relationship Id="rId1" Type="urn:test" Target="word/missing.xml"/>- </Relationships>- """.encode()- source = _zip_bytes(- {- "[Content_Types].xml": b"<Types/>",- "_rels/.rels": relationships,- }- )-- normalized = normalize_docx_package(source)-- with ZipFile(BytesIO(normalized)) as archive:- root = etree.fromstring(archive.read("_rels/.rels"))- assert list(root) == []---def test_pptx_normalizer_translates_strict_ooxml_uri() -> None:- """验证 PPTX 仍把 Strict PresentationML URI 转为 Transitional URI。"""- strict_uri = b"http://purl.oclc.org/ooxml/presentationml/main"- transitional_uri = b"http://schemas.openxmlformats.org/presentationml/2006/main"- source = _zip_bytes({"ppt/presentation.xml": b'<p:presentation xmlns:p="' + strict_uri + b'"/>'})-- normalized = normalize_pptx_package(source)-- with ZipFile(BytesIO(normalized)) as archive:- presentation = archive.read("ppt/presentation.xml")- assert strict_uri not in presentation- assert transitional_uri in presentation---def test_xlsx_normalizer_fills_empty_style_fill() -> None:- """验证 XLSX 仍为空 fill 补充 patternFill。"""- styles = f"""- <styleSheet xmlns="{_SPREADSHEETML_NS}">- <fills count="1"><fill/></fills>- </styleSheet>- """.encode()- source = _zip_bytes({"xl/styles.xml": styles})-- normalized = normalize_xlsx_package(source)-- with ZipFile(BytesIO(normalized)) as archive:- root = ET.fromstring(archive.read("xl/styles.xml"))- pattern_fill = root.find(f".//{{{_SPREADSHEETML_NS}}}patternFill")- assert pattern_fill is not Nonediff --git a/tests/unittest/test_flash_ooxml_mtef.py b/tests/unittest/test_flash_ooxml_mtef.pyindex 1fa8296a..f6a592a2 100644--- a/tests/unittest/test_flash_ooxml_mtef.py+++ b/tests/unittest/test_flash_ooxml_mtef.py@@ -1,309 +1,17 @@from __future__ import annotations-from docvortex.export.middle import export_middle_jsonimport asyncio-from collections.abc import Callable-from io import BytesIO-from pathlib import Path-from typing import Any-from docx import Document-from docx.enum.text import WD_BREAK-from docx.oxml import parse_xmlimport pytest--from mineru.backend.analyze import aio_doc_analyze, doc_analyze-from docvortex.analyzers.native import DocxModel-from docvortex.analyzers.native import PptxModel-from docvortex.analyzers.native import XlsxModel-from docvortex.analyzers.native.office.docx.docx_converter import DocxConverter-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.limits import MAX_ASSET_TOTAL_BYTES-from docvortex.analyzers.native.office.equation.ooxml import OoxmlEquationDecoder-from docvortex.analyzers.native.office.equation.ooxml import is_mathtype_equation_prog_id-from docvortex.analyzers.native.office.pptx.pptx_converter import PptxConverter-from docvortex.analyzers.native.office.xlsx.xlsx_converter import XlsxConverter-from mineru.types import BlockType, MiddleJson, ModelJson--from _mtef_test_utils import build_equation_object, formula_corpus+from _mtef_test_utils import formula_corpusfrom _ooxml_mtef_test_utils import (build_equation_docx,build_equation_pptx,build_equation_xlsx,)-from _span_test_utils import equation, inline as text_spans---def _equation_contents(pages: list[list[dict]]) -> list[str]:- """按分页顺序返回所有独立 equation block 内容。"""-- return [block["content"] for page in pages for block in page if block.get("type") == BlockType.EQUATION]---def test_ooxml_equation_decoder_enforces_scope_icon_and_total_budget() -> None:- """验证共享入口只接受公式 ProgID、非图标及预算内的 CFB。"""-- _name, mtef, expected = formula_corpus()[0]- blob = build_equation_object(mtef)- decoder = OoxmlEquationDecoder()-- assert decoder.decode(blob, prog_id="Equation.3") == expected- assert decoder.decode(blob, prog_id="equation.3") == expected- assert decoder.decode(blob, prog_id="Equation.DSMT4") == expected- assert decoder.decode(blob, prog_id="Equation") == expected- assert decoder.decode(blob, prog_id="Equation.") is None- assert decoder.decode(blob, prog_id="Package") is None- assert decoder.decode(blob, prog_id="Equation.3", show_as_icon=True) is None- assert decoder.decode(b"not CFB", prog_id="Equation.3") is None-- exhausted = OoxmlEquationDecoder(total_bytes=MAX_ASSET_TOTAL_BYTES)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):- exhausted.decode(blob, prog_id="Equation.3")--- ("prog_id", "expected"),- [- ("Equation", True),- ("equation.3", True),- ("EQUATION.DSMT4", True),- (" Equation.Custom ", True),- ("Equation.", False),- ("EquationXML", False),- ("Package", False),- (None, False),- ],-)-def test_mathtype_equation_prog_id_matching(- prog_id: object | None,- expected: bool,-) -> None:- """验证 OLE1 Equation 和 OLE2 Equation.* 的大小写无关匹配。"""-- assert is_mathtype_equation_prog_id(prog_id) is expected---def test_docx_pptx_xlsx_decode_the_full_mtef_corpus_exactly() -> None:- """验证三种 OOXML Model 对11类MTEF公式给出完全一致的LaTeX。"""-- corpus = formula_corpus()- formulas = [mtef for _name, mtef, _expected in corpus]- expected = [value for _name, _mtef, value in corpus]-- docx_pages = DocxModel().predict(BytesIO(build_equation_docx(formulas)))- pptx_pages = PptxModel().predict(BytesIO(build_equation_pptx(formulas)))- xlsx_pages = XlsxModel().predict(BytesIO(build_equation_xlsx(formulas)))-- assert _equation_contents(docx_pages) == expected- assert _equation_contents(pptx_pages) == expected- assert _equation_contents(xlsx_pages) == expected- assert len(pptx_pages) == len(corpus)---def test_docx_mtef_flows_inline_table_header_footer_and_omml_precedence() -> None:- """验证 DOCX 行内、表格、页眉页脚和 OMML 优先级语义。"""-- corpus = formula_corpus()- first = corpus[0]- second = corpus[1]-- inline = DocxModel().predict(BytesIO(build_equation_docx([first[1]], inline=True)))- table = DocxModel().predict(BytesIO(build_equation_docx([first[1]], table=True)))- header_footer = DocxModel().predict(BytesIO(build_equation_docx([first[1], second[1]], header_footer=True)))- alternate = DocxModel().predict(BytesIO(build_equation_docx([first[1]], alternate_omml=True)))- textbox = DocxModel().predict(BytesIO(build_equation_docx([first[1]], textbox=True)))-- assert inline == [[{"type": BlockType.TEXT, "content": [*text_spans("before "), equation("x+y"), *text_spans(" after")]}]]- assert table[0][0]["type"] == BlockType.TABLE- assert "<eq>x+y</eq>" in table[0][0]["content"]- assert header_footer == [- [- {"type": BlockType.HEADER, "content": [equation("x+y")]},- {- "type": BlockType.FOOTER,- "content": [equation(r"\frac{a+b}{c}")],- },- ]- ]- assert alternate == [[{"type": BlockType.EQUATION, "content": "z"}]]- assert textbox == [[{"type": BlockType.EQUATION, "content": "x+y"}]]--[email protected](("separator", "break_type"), [("\t", None), ("\n", WD_BREAK.LINE)])-def test_docx_equation_tokens_preserve_run_whitespace_offsets(separator: str, break_type: WD_BREAK | None) -> None:- """验证公式旁的 tab 和软换行参与样式 Span 的精确偏移。"""- document = Document()- paragraph = document.add_paragraph()- first = paragraph.add_run("A")- first.bold = True- if break_type is None:- first.add_tab()- else:- first.add_break(break_type)- paragraph._p.append(- parse_xml(- '<m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:r><m:t>x</m:t></m:r></m:oMath>'- )- )- last = paragraph.add_run("B")- last.italic = True- output = BytesIO()- document.save(output)-- pages = DocxModel().predict(BytesIO(output.getvalue()))-- assert pages == [- [- {- "type": BlockType.TEXT,- "content": [- *text_spans(f"A{separator}", styles=["bold"]),- equation("x"),- *text_spans("B", styles=["italic"]),- ],- }- ]- ]---def test_omml_precedes_mtef_and_preview_for_the_same_ooxml_object() -> None:- """验证三种 OOXML 兼容对象只输出 OMML 分支且不重复预览。"""-- _name, mtef, _expected = formula_corpus()[0]- cases = [- (- DocxModel(),- build_equation_docx([b"invalid MTEF"], alternate_omml=True),- ),- (- PptxModel(),- build_equation_pptx([mtef], alternate_omml=True),- ),- (- XlsxModel(),- build_equation_xlsx(- [mtef],- anchor_mode="drawing",- alternate_omml=True,- ),- ),- ]-- for model, file_bytes in cases:- assert model.predict(BytesIO(file_bytes)) == [[{"type": BlockType.EQUATION, "content": "z"}]]--- ("model", "valid_file", "invalid_file"),- [- (- DocxModel(),- lambda mtef: build_equation_docx([mtef]),- lambda: build_equation_docx([b"invalid MTEF"]),- ),- (- PptxModel(),- lambda mtef: build_equation_pptx([mtef]),- lambda: build_equation_pptx([b"invalid MTEF"]),- ),- (- XlsxModel(),- lambda mtef: build_equation_xlsx([mtef]),- lambda: build_equation_xlsx([b"invalid MTEF"]),- ),- ],- ids=["docx", "pptx", "xlsx"],-)-def test_valid_ooxml_mtef_suppresses_preview_and_invalid_keeps_it(- model: Any,- valid_file: Callable[[bytes], bytes],- invalid_file: Callable[[], bytes],-) -> None:- """验证有效原生公式胜出,坏 MTEF 在三种格式均保留缓存图。"""-- _name, mtef, expected = formula_corpus()[1]- valid_pages = model.predict(BytesIO(valid_file(mtef)))- invalid_pages = model.predict(BytesIO(invalid_file()))-- assert valid_pages == [[{"type": BlockType.EQUATION, "content": expected}]]- assert invalid_pages[0][0]["type"] == BlockType.IMAGE- assert invalid_pages[0][0]["image_base64"].startswith("data:image/")--[email protected]("file_suffix", ["docx", "pptx", "xlsx"])-def test_ooxml_icon_mode_preserves_preview_instead_of_expanding_formula(- file_suffix: str,-) -> None:- """验证 DrawAspect/showAsIcon/dvAspect 图标模式不展开公式。"""-- _name, mtef, _expected = formula_corpus()[0]- builders = {- "docx": build_equation_docx,- "pptx": build_equation_pptx,- "xlsx": build_equation_xlsx,- }- models = {- "docx": DocxModel(),- "pptx": PptxModel(),- "xlsx": XlsxModel(),- }-- pages = models[file_suffix].predict(BytesIO(builders[file_suffix]([mtef], show_as_icon=True)))-- assert pages[0][0]["type"] == BlockType.IMAGE- assert all(block["type"] != BlockType.EQUATION for block in pages[0])---def test_pptx_notes_equation_is_appended_as_page_footnote() -> None:- """验证 notesSlide 中的 Equation.3 公式精确归属当前幻灯片。"""-- _name, mtef, expected = formula_corpus()[0]-- pages = PptxModel().predict(BytesIO(build_equation_pptx([mtef], notes=True)))-- assert pages == [- [- {- "type": BlockType.PAGE_FOOTNOTE,- "content": [equation(expected)],- }- ]- ]--[email protected]("anchor_mode", ["objectPr", "drawing", "vml", "none"])-def test_xlsx_equation_anchor_variants_and_tail_fallback(anchor_mode: str) -> None:- """验证 XLSX objectPr、DrawingML、VML 与无 anchor 的稳定输出。"""-- _name, mtef, expected = formula_corpus()[0]-- pages = XlsxModel().predict(BytesIO(build_equation_xlsx([mtef], anchor_mode=anchor_mode)))-- assert pages == [[{"type": BlockType.EQUATION, "content": expected}]]---def test_xlsx_mtef_inside_table_and_hidden_sheet_behavior() -> None:- """验证表内公式不重复输出,隐藏公式工作表沿用现有跳过策略。"""-- _name, mtef, expected = formula_corpus()[0]- table_pages = XlsxModel().predict(BytesIO(build_equation_xlsx([mtef], cell_value="value")))- hidden_pages = XlsxModel().predict(BytesIO(build_equation_xlsx([mtef], hidden=True)))-- assert len(table_pages[0]) == 1- assert table_pages[0][0]["type"] == BlockType.TABLE- assert f"<eq>{expected}</eq>" in table_pages[0][0]["content"]- assert hidden_pages == [[]]---def test_xlsx_linked_equation_never_loads_external_target() -> None:- """验证外链 Equation.3 只保留包内预览,不访问外部对象。"""- _name, mtef, _expected = formula_corpus()[0]-- pages = XlsxModel().predict(BytesIO(build_equation_xlsx([mtef], linked=True)))-- assert pages[0][0]["type"] == BlockType.IMAGE- assert all(block["type"] != BlockType.EQUATION for block in pages[0])+from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.types import BlockType, MiddleJson, ModelJson@pytest.mark.parametrize("file_suffix", ["docx", "pptx", "xlsx"])@@ -329,59 +37,3 @@ def test_ooxml_mtef_backend_analyze_sync_async_contract(file_suffix: str) -> Nonassert middle.pages[0].blocks[0].content == expectedassert async_model == modelassert async_middle == middle---def test_ooxml_mtef_model_input_streams_remain_open() -> None:- """验证三种 Model 均不关闭调用方持有的输入流。"""-- _name, mtef, _expected = formula_corpus()[0]- cases = [- (DocxModel(), build_equation_docx([mtef])),- (PptxModel(), build_equation_pptx([mtef])),- (XlsxModel(), build_equation_xlsx([mtef])),- ]- for model, file_bytes in cases:- stream = BytesIO(file_bytes)- model.predict(stream)- assert not stream.closed---def test_ooxml_converter_reuse_does_not_leak_equations_between_documents() -> None:- """验证三个 converter 重用时公式缓存和分页状态都会重置。"""-- first = formula_corpus()[0]- second = formula_corpus()[1]- cases = [- (DocxConverter(), build_equation_docx),- (PptxConverter(), build_equation_pptx),- (XlsxConverter(), build_equation_xlsx),- ]- for converter, builder in cases:- converter.convert(BytesIO(builder([first[1]])))- assert _equation_contents(converter.pages) == [first[2]]- converter.convert(BytesIO(builder([second[1]])))- assert _equation_contents(converter.pages) == [second[2]]--[email protected]("file_suffix", ["docx", "pptx", "xlsx"])-def test_invalid_ooxml_mtef_preview_exports_to_sidecar(- file_suffix: str,- tmp_path: Path,-) -> None:- """验证三种格式的图片回退导出后没有 base64 残留。"""-- builders = {- "docx": build_equation_docx,- "pptx": build_equation_pptx,- "xlsx": build_equation_xlsx,- }- middle, _model = doc_analyze(- builders[file_suffix]([b"invalid MTEF"]),- file_suffix=file_suffix, # type: ignore[arg-type]- )-- result = export_middle_json(middle, tmp_path / file_suffix)-- assert len(result.image_paths) == 1- assert result.image_paths[0].stat().st_size > 0- assert "base64," not in result.json_path.read_text(encoding="utf-8")diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.pydeleted file mode 100644index 33cfd2ec..00000000--- a/tests/unittest/test_flash_pdf_auxiliary_text.py+++ /dev/null@@ -1,1848 +0,0 @@-from __future__ import annotations--import inspect--import pytest--from docvortex.analyzers.native.pdf import auxiliary_text-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import pipeline-from docvortex.analyzers.native.pdf import text_blocks---from _flash_pdf_test_utils import (- _prepared_text_page,- _text_line,-)---def test_page_footnote_uses_separator_and_stops_before_distant_footer_text() -> None:- """验证单栏页脚注由页底横线触发,并在较大行间隙前停止扩展。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("note one", (100.0, 770.0, 500.0, 780.0), 3),- _text_line("note two", (100.0, 788.0, 500.0, 798.0), 4),- _text_line("note three", (100.0, 806.0, 500.0, 816.0), 5),- _text_line("footer text", (100.0, 850.0, 600.0, 860.0), 6),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- models._AxisLine(- bbox=(100.0, 750.0, 260.0, 752.0),- width=1.0,- orientation="horizontal",- ),- models._AxisLine(- bbox=(100.0, 750.5, 260.0, 752.5),- width=1.0,- orientation="horizontal",- ),- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert [line.semantic_type for line in lines] == [- None,- None,- None,- "page_footnote",- "page_footnote",- "page_footnote",- None,- ]- assert page.page_footnote_groups == [{3, 4, 5}]--- ("page_index", "page_count"),- [(0, 1), (1, 3)],-)-def test_page_footnote_trailing_footer_applies_on_any_page(- page_index: int,- page_count: int,-) -> None:- """验证单页或非首页脚注投影内、越过续行阈值的紧凑尾段可标为页脚。"""-- body_lines = [- _text_line(- f"body {index}",- (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),- index,- effective_height=10.0,- )- for index in range(3)- ]- footnote_lines = [- _text_line(- "note one",- (100.0, 770.0, 800.0, 778.0),- 3,- effective_height=8.0,- semantic_type="page_footnote",- ),- _text_line(- "note two",- (100.0, 790.0, 500.0, 798.0),- 4,- effective_height=8.0,- semantic_type="page_footnote",- ),- _text_line(- "note three",- (100.0, 810.0, 450.0, 818.0),- 5,- effective_height=8.0,- semantic_type="page_footnote",- ),- ]- footer_lines = [- _text_line(- "footer first",- (100.0, 834.0, 600.0, 842.0),- 6,- effective_height=8.0,- ),- _text_line(- "footer second",- (100.0, 846.0, 400.0, 854.0),- 7,- effective_height=8.0,- ),- ]- page = _prepared_text_page(- *body_lines,- *footnote_lines,- *footer_lines,- page_size=(1000.0, 1000.0),- )- page.page_footnote_groups = [{3, 4, 5}]-- pages = [_prepared_text_page() for _index in range(page_count)]- pages[page_index] = page- auxiliary_text._classify_page_footnote_trailing_footers(pages)-- assert [line.semantic_type for line in footnote_lines] == [- "page_footnote",- ] * 3- assert [line.semantic_type for line in footer_lines] == ["footer"] * 2--- "case",- [- "other_lane",- "within_continuation",- "body_sized",- "split_tail",- "container_overlap",- "missing_anchor",- ],-)-def test_page_footnote_trailing_footer_rejects_weak_geometry(case: str) -> None:- """验证跨栏正文、弱分隔、正文尺度、多尾段和容器重叠均不能猜成页脚。"""-- body_lines = [- _text_line(- f"body {index}",- (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),- index,- effective_height=10.0,- )- for index in range(3)- ]- footnote_lines = [- _text_line(- f"note {index}",- (100.0, 770.0 + 20.0 * index, 500.0, 778.0 + 20.0 * index),- 3 + index,- effective_height=8.0,- semantic_type="page_footnote",- )- for index in range(3)- ]- first_top, second_top = (828.0, 840.0) if case == "within_continuation" else (834.0, 846.0)- if case == "split_tail":- second_top = 870.0- tail_height = 10.0 if case == "body_sized" else 8.0- tail_lines = [- _text_line(- "tail first",- (100.0, first_top, 600.0, first_top + tail_height),- 6,- effective_height=tail_height,- ),- _text_line(- "tail second",- (100.0, second_top, 400.0, second_top + tail_height),- 7,- effective_height=tail_height,- ),- ]- extra_lines = (- [- _text_line(- "right column body",- (700.0, 835.0, 950.0, 845.0),- 8,- effective_height=10.0,- )- ]- if case == "other_lane"- else []- )- page = _prepared_text_page(- *body_lines,- *footnote_lines,- *tail_lines,- *extra_lines,- page_size=(1000.0, 1000.0),- )- if case != "missing_anchor":- page.page_footnote_groups = [{3, 4, 5}]- if case == "container_overlap":- page.fixed_blocks = [- {- "type": "image",- "bbox": (80.0, 825.0, 620.0, 860.0),- "angle": 0,- "content": "",- }- ]-- auxiliary_text._classify_page_footnote_trailing_footers([page])-- assert all(line.semantic_type is None for line in tail_lines)- assert all(line.semantic_type is None for line in extra_lines)---def test_image_footnote_requires_image_rule_and_smaller_text() -> None:- """验证图表脚注必须同时具备图片、下缘长横线和字号收缩证据。"""-- lines = [- _text_line(- f"body {index}",- (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- note = _text_line(- "chart source",- (50.0, 325.0, 180.0, 333.0),- 4,- effective_height=8.0,- )- lines.append(note)- page = _prepared_text_page(*lines, page_size=(500.0, 500.0))- page.fixed_blocks = [- {- "type": "image",- "bbox": (50.0, 140.0, 300.0, 315.0),- "angle": 0,- "content": "",- }- ]- page.drawing_lines = [models._AxisLine((50.0, 318.0, 300.0, 319.0), 1.0, "horizontal")]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert note.semantic_type == "footnote"- assert page.page_footnote_groups == []---def test_sparse_image_footnotes_retry_with_document_body_height() -> None:- """验证稀疏图片页可用全文正文尺度恢复两个被自身字号污染的图表脚注。"""-- caption = _text_line(- "chart caption",- (50.0, 40.0, 300.0, 48.0),- 0,- effective_height=8.0,- )- notes = [- _text_line(- "left source",- (50.0, 255.0, 300.0, 262.0),- 1,- effective_height=7.0,- ),- _text_line(- "right source",- (550.0, 255.0, 800.0, 262.0),- 2,- effective_height=7.0,- ),- ]- page = _prepared_text_page(caption, *notes, page_size=(1000.0, 500.0))- page.fixed_blocks = [- {"type": "image", "bbox": bbox, "angle": 0, "content": ""}- for bbox in [- (50.0, 80.0, 450.0, 250.0),- (550.0, 80.0, 950.0, 250.0),- ]- ]- page.drawing_lines = [- models._AxisLine((50.0, 252.0, 450.0, 253.0), 1.0, "horizontal"),- models._AxisLine((550.0, 252.0, 950.0, 253.0), 1.0, "horizontal"),- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert [line.semantic_type for line in notes] == [None, None]-- auxiliary_text._classify_deferred_image_footnotes([page], body_height=10.0)-- assert [line.semantic_type for line in notes] == ["footnote", "footnote"]- assert page.page_footnote_groups == []--- "missing_evidence",- ["image", "rule", "small_text", "table_rule"],-)-def test_image_footnote_rejects_incomplete_visual_evidence(- missing_evidence: str,-) -> None:- """验证缺少任一联合证据时普通图下文字不会晋升为图表脚注。"""-- body = [- _text_line(- f"body {index}",- (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- note = _text_line(- "candidate",- (50.0, 325.0, 180.0, 333.0),- 4,- effective_height=10.0 if missing_evidence == "small_text" else 8.0,- )- page = _prepared_text_page(*body, note, page_size=(500.0, 500.0))- if missing_evidence != "image":- page.fixed_blocks = [- {- "type": "image",- "bbox": (50.0, 140.0, 300.0, 315.0),- "angle": 0,- "content": "",- }- ]- if missing_evidence != "rule":- page.drawing_lines = [models._AxisLine((50.0, 318.0, 300.0, 319.0), 1.0, "horizontal")]- if missing_evidence == "table_rule":- page.table_bboxes = [(40.0, 300.0, 310.0, 340.0)]-- auxiliary_text._classify_page_auxiliary_text(page)- auxiliary_text._classify_deferred_image_footnotes([page], body_height=10.0)-- assert note.semantic_type is None---def test_page_footnote_supports_independent_column_rules() -> None:- """验证左右栏各自的短横线只认领本栏连续页脚注。"""-- lines = [- *[- _text_line(f"left body {index}", (80.0, 100.0 + 30.0 * index, 460.0, 110.0 + 30.0 * index), index)- for index in range(3)- ],- *[- _text_line(- f"right body {index}",- (540.0, 100.0 + 30.0 * index, 920.0, 110.0 + 30.0 * index),- index + 3,- )- for index in range(3)- ],- _text_line("left note one", (80.0, 820.0, 400.0, 830.0), 6),- _text_line("left note two", (80.0, 838.0, 400.0, 848.0), 7),- _text_line("right note one", (540.0, 820.0, 860.0, 830.0), 8),- _text_line("right note two", (540.0, 838.0, 860.0, 848.0), 9),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- models._AxisLine((80.0, 800.0, 220.0, 802.0), 1.0, "horizontal"),- models._AxisLine((540.0, 800.0, 680.0, 802.0), 1.0, "horizontal"),- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines[:6])- assert all(line.semantic_type == "page_footnote" for line in lines[6:])- assert page.page_footnote_groups == [{6, 7}, {8, 9}]---def test_page_footnote_accepts_slightly_left_shifted_rule_with_two_small_rows() -> None:- """验证轻微早于栏左缘的短横线可凭高覆盖和连续小字号行确认脚注。"""-- body = [- _text_line(- f"body {index}",- (122.0, 180.0 + 90.0 * index, 622.0, 190.0 + 90.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- notes = [- _text_line(- "note one",- (122.0, 862.0, 550.0, 870.0),- 4,- effective_height=8.0,- ),- _text_line(- "note two",- (122.0, 874.0, 520.0, 882.0),- 5,- effective_height=8.0,- ),- ]- page = _prepared_text_page(- *body,- *notes,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (100.0, 850.0, 300.0, 852.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in body)- assert all(line.semantic_type == "page_footnote" for line in notes)- assert page.page_footnote_groups == [{4, 5}]---def test_page_footnote_rejects_left_shifted_rule_with_single_or_body_size_row() -> None:- """验证轻微左偏横线缺少两行或字号收缩证据时不触发脚注。"""-- for note_rows, note_height in ((1, 8.0), (2, 10.0)):- lines = [- *[- _text_line(- f"body {index}",- (122.0, 180.0 + 90.0 * index, 622.0, 190.0 + 90.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ],- *[- _text_line(- f"note {index}",- (122.0, 862.0 + 12.0 * index, 550.0, 862.0 + 12.0 * index + note_height),- 4 + index,- effective_height=note_height,- )- for index in range(note_rows)- ],- ]- page = _prepared_text_page(- *lines,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (100.0, 850.0, 300.0, 852.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert page.page_footnote_groups == []- assert all(line.semantic_type is None for line in lines)---def test_page_footnote_accepts_centered_short_rule_with_small_rows() -> None:- """验证栏内居中短横线可凭页面位置和小字号连续行确认脚注。"""-- body = [- _text_line(- f"body {index}",- (100.0, 180.0 + 80.0 * index, 500.0, 190.0 + 80.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- notes = [- _text_line(- "note one",- (100.0, 862.0, 490.0, 870.0),- 4,- effective_height=8.0,- ),- _text_line(- "note two",- (100.0, 874.0, 460.0, 882.0),- 5,- effective_height=8.0,- ),- ]- page = _prepared_text_page(- *body,- *notes,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (200.0, 850.0, 400.0, 852.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in body)- assert all(line.semantic_type == "page_footnote" for line in notes)- assert page.page_footnote_groups == [{4, 5}]---def test_page_footnote_rejects_centered_fraction_rule_without_upper_clearance() -> None:- """验证夹在上下公式层级之间的居中横线不会触发页脚注。"""-- body = [- _text_line(- f"body {index}",- (100.0, 180.0 + 80.0 * index, 500.0, 190.0 + 80.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- formula_rows = [- _text_line(- "formula numerator",- (100.0, 842.0, 500.0, 852.0),- 4,- effective_height=10.0,- ),- _text_line(- "formula denominator",- (100.0, 854.0, 490.0, 862.0),- 5,- effective_height=8.0,- ),- _text_line(- "formula tail",- (100.0, 866.0, 460.0, 874.0),- 6,- effective_height=8.0,- ),- ]- page = _prepared_text_page(- *body,- *formula_rows,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (200.0, 850.0, 400.0, 852.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert page.page_footnote_groups == []- assert all(line.semantic_type is None for line in formula_rows)---def test_page_footnote_accepts_lower_half_column_width_rule_with_smaller_text() -> None:- """验证页面下半部的栏宽横线可凭字号收缩识别单栏脚注。"""-- lines = [- _text_line(- f"body {index}",- (100.0, 180.0 + 24.0 * index, 900.0, 190.0 + 24.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- lines.extend(- [- _text_line(- "note one",- (100.0, 620.0, 650.0, 628.0),- 4,- effective_height=8.0,- ),- _text_line(- "note two",- (100.0, 632.0, 620.0, 640.0),- 5,- effective_height=8.0,- ),- ]- )- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [models._AxisLine((100.0, 600.0, 900.0, 602.0), 1.0, "horizontal")]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines[:4])- assert [line.semantic_type for line in lines[4:]] == [- "page_footnote",- "page_footnote",- ]- assert page.page_footnote_groups == [{4, 5}]---def test_page_footnote_stops_at_next_aligned_column_rule() -> None:- """验证同栏第二条分隔线会把贡献说明和作者单位拆成两个脚注组。"""-- lines = [- *[- _text_line(- f"body {index}",- (100.0, 150.0 + 30.0 * index, 500.0, 160.0 + 30.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ],- _text_line(- "contribution one",- (100.0, 590.0, 430.0, 598.0),- 4,- effective_height=8.0,- ),- _text_line(- "contribution two",- (100.0, 602.0, 240.0, 610.0),- 5,- effective_height=8.0,- ),- _text_line(- "affiliation one",- (120.0, 640.0, 460.0, 648.0),- 6,- effective_height=8.0,- ),- _text_line(- "affiliation two",- (120.0, 652.0, 400.0, 660.0),- 7,- effective_height=8.0,- ),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- models._AxisLine((100.0, 570.0, 500.0, 572.0), 1.0, "horizontal"),- models._AxisLine((100.0, 620.0, 500.0, 622.0), 1.0, "horizontal"),- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert page.page_footnote_groups == [{4, 5}, {6, 7}]- assert all(line.semantic_type == "page_footnote" for line in lines[4:])---def test_page_footnote_rejects_column_width_rule_without_size_contraction() -> None:- """验证栏宽横线下的正常字号正文不会仅凭下半页位置变成脚注。"""-- lines = [- _text_line(- f"body {index}",- (100.0, 180.0 + 24.0 * index, 900.0, 190.0 + 24.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- lines.append(- _text_line(- "continued body",- (100.0, 620.0, 700.0, 630.0),- 4,- effective_height=10.0,- )- )- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [models._AxisLine((100.0, 600.0, 900.0, 602.0), 1.0, "horizontal")]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines)---def test_page_footnote_unions_aligned_regular_and_span_lanes_only() -> None:- """验证同左缘 regular/span 栏可联合认领,但不会吞掉右侧正文栏。"""-- lines = [- *[- _text_line(f"left body {index}", (100.0, 100.0 + 30.0 * index, 480.0, 110.0 + 30.0 * index), index)- for index in range(3)- ],- *[- _text_line(- f"right body {index}",- (520.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),- index + 3,- )- for index in range(3)- ],- _text_line("span note one", (100.0, 810.0, 900.0, 820.0), 6),- _text_line("span note two", (100.0, 830.0, 900.0, 840.0), 7),- _text_line("span note three", (100.0, 850.0, 900.0, 860.0), 8),- _text_line("left note one", (100.0, 812.0, 480.0, 822.0), 9),- _text_line("left note two", (100.0, 832.0, 480.0, 842.0), 10),- _text_line("right body below rule", (520.0, 812.0, 900.0, 822.0), 11),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [models._AxisLine((100.0, 800.0, 305.0, 802.0), 1.0, "horizontal")]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert {line.source_index for line in lines if line.semantic_type == "page_footnote"} == {- 6,- 7,- 8,- 9,- 10,- }- assert page.page_footnote_groups == [{6, 7, 8, 9, 10}]- assert lines[11].semantic_type is None---def test_page_footnote_entries_split_first_line_indent_without_text() -> None:- """验证首行缩进模式把两个脚注起始行拆开,并吸收左对齐续行。"""-- lines = [- _text_line("first", (87.0, 732.0, 245.0, 742.0), 0, effective_height=8.0, median_glyph_width=4.5),- _text_line("second", (83.0, 743.0, 293.0, 753.0), 1, effective_height=8.0, median_glyph_width=4.5),- _text_line("continuation", (70.0, 755.0, 276.0, 763.0), 2, effective_height=7.0, median_glyph_width=5.0),- _text_line("tail", (70.0, 766.0, 146.0, 773.0), 3, effective_height=7.0, median_glyph_width=5.0),- ]-- entries = text_blocks._split_page_footnote_entries(- lines,- (595.0, 842.0),- )-- assert [[line.source_index for line in entry] for entry in entries] == [- [0],- [1, 2, 3],- ]---def test_page_footnote_entries_keep_same_left_compact_continuation() -> None:- """验证同左缘的次满首行与紧邻续行仍保留在同一脚注块。"""-- lines = [- _text_line(- "first",- (70.0, 732.0, 220.0, 740.0),- 0,- effective_height=8.0,- median_glyph_width=4.0,- font_signature=("NoteFont", 0),- font_coverage=1.0,- ),- _text_line(- "continuation",- (70.0, 743.0, 270.0, 751.0),- 1,- effective_height=8.0,- median_glyph_width=4.0,- font_signature=("NoteFont", 0),- font_coverage=1.0,- ),- ]-- entries = text_blocks._split_page_footnote_entries(- lines,- (595.0, 842.0),- )-- assert [[line.source_index for line in entry] for entry in entries] == [- [0, 1],- ]---def test_page_footnote_single_geometric_marker_keeps_group_together() -> None:- """验证 row id 缺失的单个窄编号首行仍可聚合整组连续脚注。"""-- note_font = ("NoteFont", 0)- lines = [- _text_line(- "1",- (10.0, 80.0, 12.0, 88.0),- 0,- visual_row_id=10,- effective_height=8.0,- font_signature=note_font,- font_coverage=1.0,- median_glyph_width=2.0,- semantic_type="page_footnote",- ),- _text_line(- "first source",- (14.0, 80.5, 60.0, 88.5),- 1,- visual_row_id=11,- effective_height=8.0,- font_signature=note_font,- font_coverage=1.0,- median_glyph_width=2.0,- semantic_type="page_footnote",- ),- _text_line(- "second source",- (10.0, 92.0, 70.0, 100.0),- 2,- effective_height=8.0,- font_signature=note_font,- font_coverage=1.0,- median_glyph_width=2.0,- semantic_type="page_footnote",- ),- _text_line(- "third source",- (10.0, 104.0, 65.0, 112.0),- 3,- effective_height=8.0,- font_signature=note_font,- font_coverage=1.0,- median_glyph_width=2.0,- semantic_type="page_footnote",- ),- ]-- entries = text_blocks._split_page_footnote_entries(- lines,- (100.0, 140.0),- )-- assert [[line.source_index for line in entry] for entry in entries] == [- [0, 1, 2, 3],- ]---def test_page_footnote_entries_split_hanging_indent_and_tighten_boxes() -> None:- """验证 Boosting 型续行缩进拆成四条脚注,且异常高字符框不再互相覆盖。"""-- page_size = (612.2833862304688, 858.8975830078125)- lines = [- _text_line(- "receipt",- (81.2767, 740.0383, 238.2958, 758.6347),- 66,- effective_height=18.5964,- median_glyph_width=3.92,- semantic_type="page_footnote",- ),- _text_line(- "fund start",- (81.2767, 750.5583, 546.9993, 769.1547),- 67,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- _text_line(- "fund continuation",- (119.6767, 761.0783, 364.8372, 779.6747),- 68,- effective_height=10.38,- median_glyph_width=4.78,- semantic_type="page_footnote",- ),- _text_line(- "author",- (81.2767, 771.5983, 385.9195, 790.1947),- 69,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- _text_line(- "corresponding",- (81.2767, 782.1183, 439.2661, 800.7147),- 70,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- ]- page = _prepared_text_page(*lines, page_size=page_size)- page.page_footnote_groups = [{line.source_index for line in lines}]-- blocks = [block for block in pipeline._finalize_prepared_page(page, page_index=0) if block["type"] == "page_footnote"]-- assert [block["content"] for block in blocks] == [- "receipt",- "fund start fund continuation",- "author",- "corresponding",- ]- assert [block["bbox"] for block in blocks] == [- [0.133, 0.867, 0.389, 0.878],- [0.133, 0.879, 0.893, 0.902],- [0.133, 0.904, 0.63, 0.914],- [0.133, 0.916, 0.717, 0.927],- ]- assert all(previous["bbox"][3] < current["bbox"][1] for previous, current in zip(blocks, blocks[1:]))--- ("rule_bbox", "table_bboxes"),- [- ((100.0, 750.0, 125.0, 752.0), []),- ((400.0, 750.0, 550.0, 752.0), []),- ((100.0, 750.0, 260.0, 752.0), [(90.0, 730.0, 500.0, 850.0)]),- (None, []),- ],-)-def test_page_footnote_rejects_decorative_formula_table_and_missing_rules(- rule_bbox: tuple[float, float, float, float] | None,- table_bboxes: list[tuple[float, float, float, float]],-) -> None:- """验证装饰短线、居中公式线、表格线和无横线页底正文均不触发脚注。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("bottom body", (100.0, 770.0, 500.0, 780.0), 3),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.table_bboxes = table_bboxes- if rule_bbox is not None:- page.drawing_lines = [models._AxisLine(rule_bbox, 1.0, "horizontal")]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines)---def test_page_footnote_rejects_collinear_rule_segment_next_to_table() -> None:- """验证表格框外的同高近邻断裂横线不会独立触发页脚注。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("bottom table row", (100.0, 770.0, 500.0, 780.0), 3),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.table_bboxes = [(280.0, 730.0, 900.0, 850.0)]- page.drawing_lines = [- models._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal"),- models._AxisLine((280.0, 750.0, 900.0, 752.0), 1.0, "horizontal"),- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines)- assert page.page_footnote_groups == []--- ("angle", "bbox"),- [- (270, (20.0, 250.0, 50.0, 650.0)),- (90, (930.0, 250.0, 960.0, 650.0)),- ],-)-def test_aside_text_accepts_tall_vertical_text_in_either_edge_band(- angle: int,- bbox: tuple[float, float, float, float],-) -> None:- """验证横排正文占主导时,左右边缘的高占比垂直文字均标为侧栏。"""-- lines = [- *[_text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index) for index in range(6)],- _text_line("aside", bbox, 6, angle=angle, effective_height=20.0),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))-- auxiliary_text._classify_page_auxiliary_text(page)-- assert lines[-1].semantic_type == "aside_text"- assert all(line.semantic_type is None for line in lines[:-1])---def test_aside_text_rejects_short_internal_wide_and_non_dominant_rotated_text() -> None:- """验证短旋转行、页内旋转行、过宽边缘行及旋转正文均不误报侧栏。"""-- upright_lines = [- _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index) for index in range(10)- ]- rejected = [- _text_line("short", (20.0, 250.0, 50.0, 350.0), 10, angle=270, effective_height=20.0),- _text_line("internal", (400.0, 200.0, 430.0, 600.0), 11, angle=270, effective_height=20.0),- _text_line("wide", (0.0, 200.0, 100.0, 600.0), 12, angle=270, effective_height=20.0),- ]- page = _prepared_text_page(*upright_lines, *rejected, page_size=(1000.0, 1000.0))- auxiliary_text._classify_page_auxiliary_text(page)- assert all(line.semantic_type is None for line in rejected)-- rotated_body = [- _text_line(f"upright {index}", (100.0, 100.0 + 20.0 * index, 300.0, 110.0 + 20.0 * index), index) for index in range(4)- ]- rotated_body.append(_text_line("edge but not aside", (20.0, 200.0, 50.0, 700.0), 4, angle=270, effective_height=20.0))- rotated_page = _prepared_text_page(*rotated_body, page_size=(1000.0, 1000.0))- auxiliary_text._classify_page_auxiliary_text(rotated_page)- assert rotated_body[-1].semantic_type is None---def test_auxiliary_text_classification_is_content_independent() -> None:- """验证替换全部行文本不会改变页脚注空间分类结果。"""-- geometries = [- (100.0, 100.0, 900.0, 110.0),- (100.0, 130.0, 900.0, 140.0),- (100.0, 160.0, 900.0, 170.0),- (100.0, 770.0, 500.0, 780.0),- (100.0, 788.0, 500.0, 798.0),- ]- first_lines = [_text_line(f"alpha {index}", bbox, index) for index, bbox in enumerate(geometries)]- second_lines = [_text_line(f"完全不同 {index}", bbox, index) for index, bbox in enumerate(geometries)]- first_page = _prepared_text_page(*first_lines, page_size=(1000.0, 1000.0))- second_page = _prepared_text_page(*second_lines, page_size=(1000.0, 1000.0))- for page in (first_page, second_page):- page.drawing_lines = [models._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal")]- auxiliary_text._classify_page_auxiliary_text(page)-- assert [line.semantic_type for line in first_lines] == [line.semantic_type for line in second_lines]- assert first_page.page_footnote_groups == second_page.page_footnote_groups---def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:- """静态守卫侧栏和页脚注分类函数不访问文本内容。"""-- source = "\n".join(- inspect.getsource(function)- for function in (- auxiliary_text._classify_page_auxiliary_text,- auxiliary_text._classify_aside_text,- auxiliary_text._geometric_text_support_by_angle,- auxiliary_text._classify_image_footnotes,- auxiliary_text._classify_deferred_image_footnotes,- auxiliary_text._image_footnote_members,- auxiliary_text._classify_page_footnotes,- auxiliary_text._classify_page_footnote_trailing_footers,- auxiliary_text._page_footnote_trailing_footer_members,- auxiliary_text._page_footnote_continuation_gap_limit,- auxiliary_text._augment_footnote_groups_with_edge_markers,- auxiliary_text._classify_rule_delimited_headers,- auxiliary_text._classify_page_number_outer_companions,- auxiliary_text._rule_belongs_to_confirmed_table,- auxiliary_text._merge_overlapping_source_groups,- auxiliary_text._footnote_lane_members,- text_blocks._split_page_footnote_entries,- text_blocks._tight_page_footnote_bboxes,- )- )-- assert ".text" not in source---def test_finalize_preserves_preclassified_auxiliary_text_types() -> None:- """验证单页终结阶段不会丢失已标注的侧栏和页脚注。"""-- page = _prepared_text_page(- _text_line("note", (10.0, 80.0, 40.0, 90.0), 0, semantic_type="page_footnote"),- _text_line("chart note", (10.0, 65.0, 40.0, 75.0), 2, semantic_type="footnote"),- _text_line(- "aside",- (2.0, 20.0, 5.0, 60.0),- 1,- angle=270,- effective_height=3.0,- semantic_type="aside_text",- ),- )-- blocks = pipeline._finalize_prepared_page(page, page_index=0)-- assert {block["type"] for block in blocks} == {- "footnote",- "page_footnote",- "aside_text",- }---def test_repeated_marginals_require_cross_page_evidence_and_separate_page_numbers() -> None:- """验证重复页眉页脚与递增镜像页码被标注,孤立边缘行和正文不变。"""-- margin_font = ("Margin", 0)- pages = [- _prepared_text_page(- _text_line("Quarterly report 2024 - 1", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Only on first page", (20.0, 11.0, 80.0, 16.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("1", (4.0, 48.0, 6.0, 53.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("10", (5.0, 89.0, 10.0, 94.0), 4, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 5, font_signature=margin_font, font_coverage=1.0),- ),- _prepared_text_page(- _text_line("Quarterly report 2024 - 2", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("2", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("11", (90.0, 89.0, 95.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),- ),- _prepared_text_page(- _text_line("Quarterly report 2024 - 3", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("3", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("12", (5.0, 89.0, 10.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),- ),- ]-- auxiliary_text._classify_repeated_page_marginals(pages)-- assert [[line.semantic_type for line in page.remaining_lines] for page in pages] == [- ["header", None, None, None, "page_number", "footer"],- ["header", None, None, "page_number", "footer"],- ["header", None, None, "page_number", "footer"],- ]---def test_top_rule_marks_only_unclassified_text_above_it_as_header() -> None:- """验证页码先保留类型,长横线上方其余文本补标页眉且线下正文不变。"""-- page_number = _text_line(- "7",- (900.0, 30.0, 920.0, 40.0),- 0,- semantic_type="page_number",- )- journal = _text_line("journal", (100.0, 30.0, 600.0, 40.0), 1)- doi = _text_line("doi", (100.0, 44.0, 500.0, 54.0), 2)- body = _text_line("body", (100.0, 80.0, 700.0, 90.0), 3)- page = _prepared_text_page(- page_number,- journal,- doi,- body,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [models._AxisLine((80.0, 60.0, 920.0, 62.0), 1.0, "horizontal")]-- auxiliary_text._classify_rule_delimited_headers([page])-- assert [line.semantic_type for line in page.remaining_lines] == [- "page_number",- "header",- "header",- None,- ]---def test_top_rule_uses_first_separator_before_later_section_rule() -> None:- """验证页首多条长横线只采用最上方有效页眉分隔线。"""-- header = _text_line("header", (100.0, 30.0, 300.0, 40.0), 0)- section = _text_line("section", (100.0, 90.0, 300.0, 110.0), 1)- body = _text_line("body", (100.0, 150.0, 700.0, 160.0), 2)- page = _prepared_text_page(- header,- section,- body,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (80.0, 60.0, 920.0, 62.0),- 1.0,- "horizontal",- ),- models._AxisLine(- (80.0, 120.0, 920.0, 122.0),- 1.0,- "horizontal",- ),- ]-- auxiliary_text._classify_rule_delimited_headers([page])-- assert header.semantic_type == "header"- assert section.semantic_type is None- assert body.semantic_type is None---def test_top_decorative_rule_does_not_precede_real_header_separator() -> None:- """验证顶部无上方文字的装饰线不会抢占刊头文字下方的真实分隔线。"""-- header = _text_line("letterhead", (100.0, 30.0, 400.0, 40.0), 0)- body = _text_line("body", (100.0, 80.0, 700.0, 90.0), 1)- page = _prepared_text_page(- header,- body,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (80.0, 8.0, 920.0, 10.0),- 1.0,- "horizontal",- ),- models._AxisLine(- (80.0, 60.0, 920.0, 62.0),- 1.0,- "horizontal",- ),- ]-- auxiliary_text._classify_rule_delimited_headers([page])-- assert header.semantic_type == "header"- assert body.semantic_type is None---def test_top_rule_uses_ink_bbox_when_loose_bbox_crosses_separator() -> None:- """验证 loose 框穿过页首横线时仍按真实字形区分线上日期和线下 DOI。"""-- date = _text_line(- "2026 年 4 月",- (100.0, 30.0, 240.0, 64.0),- 0,- effective_height=10.0,- )- date.ink_bbox = (100.0, 34.0, 240.0, 45.0)- doi = _text_line(- "DOI:10.1000/example",- (100.0, 58.0, 500.0, 76.0),- 1,- effective_height=10.0,- )- doi.ink_bbox = (100.0, 64.0, 500.0, 74.0)- body = _text_line(- "body",- (100.0, 90.0, 700.0, 100.0),- 2,- effective_height=10.0,- )- page = _prepared_text_page(- date,- doi,- body,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine(- (80.0, 60.0, 920.0, 62.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_rule_delimited_headers([page])-- assert date.semantic_type == "header"- assert doi.semantic_type is None- assert body.semantic_type is None---def test_top_rule_inside_graphic_does_not_mark_header() -> None:- """验证图形容器内的页首长横线不会把其上方普通文本误标为页眉。"""-- upper_text = _text_line("upper text", (100.0, 30.0, 600.0, 40.0), 0)- body = _text_line("body", (100.0, 80.0, 700.0, 90.0), 1)- page = _prepared_text_page(- upper_text,- body,- page_size=(1000.0, 1000.0),- )- page.fixed_blocks = [- {- "type": "image",- "bbox": (50.0, 50.0, 950.0, 70.0),- "angle": 0,- "content": "",- }- ]- page.drawing_lines = [models._AxisLine((80.0, 60.0, 920.0, 62.0), 1.0, "horizontal")]-- auxiliary_text._classify_rule_delimited_headers([page])-- assert upper_text.semantic_type is None- assert body.semantic_type is None---def test_page_number_outer_companions_classify_top_and_bottom_text_and_images() -> None:- """验证上下页码外侧的文本和空内容图片对称转换为页眉页脚。"""-- top_page = _prepared_text_page(- _text_line("top visual", (20.0, 1.0, 80.0, 5.0), 0),- _text_line(- "1",- (90.0, 8.0, 95.0, 13.0),- 1,- semantic_type="page_number",- ),- _text_line("top body", (20.0, 18.0, 80.0, 28.0), 2),- )- top_page.fixed_blocks = [- {- "type": "image",- "bbox": (40.0, 0.0, 60.0, 5.0),- "angle": 0,- "content": "",- }- ]- bottom_page = _prepared_text_page(- _text_line("bottom body", (20.0, 70.0, 80.0, 80.0), 0),- _text_line(- "2",- (90.0, 82.0, 95.0, 87.0),- 1,- semantic_type="page_number",- ),- _text_line("bottom visual", (20.0, 91.0, 80.0, 96.0), 2),- )- bottom_page.fixed_blocks = [- {- "type": "image",- "bbox": (40.0, 90.0, 60.0, 99.0),- "angle": 0,- "content": "",- }- ]-- auxiliary_text._classify_page_number_outer_companions([top_page, bottom_page])-- assert [line.semantic_type for line in top_page.remaining_lines] == [- "header",- "page_number",- None,- ]- assert top_page.fixed_blocks[0]["type"] == "header"- assert [line.semantic_type for line in bottom_page.remaining_lines] == [- None,- "page_number",- "footer",- ]- assert bottom_page.fixed_blocks[0]["type"] == "footer"-- blocks = pipeline._finalize_prepared_page(bottom_page, page_index=1)- assert any(block["type"] == "footer" and block["content"] == "" for block in blocks)---def test_page_number_sequence_survives_portrait_to_landscape_edge_change() -> None:- """验证横竖版切换时连续页码可从底边迁移到侧边,且后续侧边序列继续命中。"""-- pages = [- _prepared_text_page(- _text_line("2", (45.0, 126.0, 55.0, 131.0), 0),- page_size=(100.0, 140.0),- ),- _prepared_text_page(- _text_line("3", (126.0, 75.0, 131.0, 80.0), 0),- page_size=(140.0, 100.0),- ),- _prepared_text_page(- _text_line("4", (126.0, 75.0, 131.0, 80.0), 0),- page_size=(140.0, 100.0),- ),- ]-- auxiliary_text._classify_repeated_page_marginals(pages)-- assert [page.remaining_lines[0].semantic_type for page in pages] == ["page_number"] * 3---def test_single_page_marginal_content_remains_text() -> None:- """验证单页顶部和底部文字不会仅凭位置被猜成页眉、页脚或页码。"""-- page = _prepared_text_page(- _text_line("Page 7", (45.0, 3.0, 55.0, 8.0), 0),- _text_line("Copyright notice", (20.0, 92.0, 80.0, 98.0), 1),- )-- auxiliary_text._classify_repeated_page_marginals([page])-- assert [line.semantic_type for line in page.remaining_lines] == [None, None]---def test_extreme_page_footnotes_can_be_overridden_by_repeated_marginals() -> None:- """验证只有极底脚注可凭跨页重复和递增证据改判为页脚、页码。"""-- pages = []- for page_index in range(3):- pages.append(- _prepared_text_page(- _text_line(- "stable footer",- (20.0, 95.0, 70.0, 99.0),- 0,- effective_height=4.0,- font_signature=("Margin", 0),- font_coverage=1.0,- semantic_type="page_footnote",- ),- _text_line(- str(page_index + 10),- (90.0, 95.0, 95.0, 99.0),- 1,- effective_height=4.0,- font_signature=("Margin", 0),- font_coverage=1.0,- semantic_type="page_footnote",- ),- _text_line(- "local note",- (20.0, 86.0, 60.0, 90.0),- 2,- semantic_type="page_footnote",- ),- )- )-- auxiliary_text._classify_repeated_page_marginals(pages)-- assert [[line.semantic_type for line in page.remaining_lines] for page in pages] == [- ["footer", "page_number", "page_footnote"]- ] * 3---def test_single_page_compound_header_requires_small_split_row_and_body_edge() -> None:- """验证单页顶部的小字号拆分同行可由正文栏右缘确认为页眉。"""-- header_name = _text_line(- "journal",- (60.0, 2.0, 85.0, 4.0),- 0,- visual_row_id=7,- run_index=0,- split_from_row=True,- effective_height=2.0,- )- header_number = _text_line(- "5",- (96.0, 2.0, 98.0, 4.0),- 1,- visual_row_id=7,- run_index=1,- split_from_row=True,- effective_height=2.0,- )- page = _prepared_text_page(- header_name,- header_number,- *[- _text_line(- f"body-{index}",- (50.0, 10.0 + 12.0 * index, 98.0, 20.0 + 12.0 * index),- 2 + index,- effective_height=10.0,- )- for index in range(4)- ],- )-- auxiliary_text._classify_single_page_compound_headers([page])-- assert header_name.semantic_type == "header"- assert header_number.semantic_type == "header"---def test_isolated_first_page_footer_uses_multi_page_geometry_only() -> None:- """验证多页首页唯一极底短行可补标页脚,而单页相同布局保持正文。"""-- def build_page() -> tuple[models._PreparedPage, models._LineItem]:- """构造带四行下延正文和一个孤立极底候选的页面。"""-- footer = _text_line(- "neutral notice",- (37.5, 98.0, 62.5, 100.0),- 4,- effective_height=2.0,- )- return (- _prepared_text_page(- *[- _text_line(- f"body-{index}",- (0.0, 55.0 + 10.0 * index, 100.0, 60.0 + 10.0 * index),- index,- effective_height=5.0,- )- for index in range(4)- ],- footer,- ),- footer,- )-- multi_page, multi_footer = build_page()- single_page, single_footer = build_page()-- auxiliary_text._classify_isolated_first_page_footer([multi_page, _prepared_text_page()])- auxiliary_text._classify_isolated_first_page_footer([single_page])-- assert multi_footer.semantic_type == "footer"- assert single_footer.semantic_type is None---def test_repeated_visual_headers_use_geometry_and_skip_first_page() -> None:- """验证重复页首图片仅按几何重标,空 content 也可保留为 header。"""-- pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(5)]- contents = ["cover", "", "beta", "", "delta"]- for page, content in zip(pages, contents, strict=True):- page.fixed_blocks = [- {- "type": "image",- "bbox": (10.0, 0.0, 90.0, 10.0),- "angle": 0,- "content": content,- }- ]-- auxiliary_text._classify_repeated_visual_headers(pages)-- assert pages[0].fixed_blocks[0]["type"] == "image"- assert [page.fixed_blocks[0]["type"] for page in pages[1:]] == ["header"] * 4---def test_repeated_visual_headers_require_three_top_geometry_matches() -> None:- """验证两页重复、非页首图片和明显漂移的 bbox 均不形成视觉页眉。"""-- pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(6)]- bboxes = [- (10.0, 0.0, 90.0, 10.0),- (10.0, 0.0, 90.0, 10.0),- (10.0, 0.0, 90.0, 10.0),- (10.0, 20.0, 90.0, 30.0),- (30.0, 0.0, 90.0, 10.0),- (10.0, 0.0, 90.0, 10.0),- ]- for page, bbox in zip(pages, bboxes, strict=True):- page.fixed_blocks = [- {- "type": "image",- "bbox": bbox,- "angle": 0,- "content": "value",- }- ]-- auxiliary_text._classify_repeated_visual_headers(pages)-- assert [page.fixed_blocks[0]["type"] for page in pages] == ["image"] * 6---def test_repeated_visual_headers_support_alternating_pages() -> None:- """验证同奇偶页间隔为二的重复图片仍可形成视觉页眉簇。"""-- pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(7)]- for page_index, page in enumerate(pages):- if page_index in {2, 4, 6}:- page.fixed_blocks = [- {- "type": "image",- "bbox": (10.0, 0.0, 90.0, 10.0),- "angle": 0,- "content": f"page-{page_index}",- }- ]-- auxiliary_text._classify_repeated_visual_headers(pages)-- assert [pages[index].fixed_blocks[0]["type"] for index in (2, 4, 6)] == ["header"] * 3---def test_repeated_visual_headers_require_matching_orientation() -> None:- """验证 bbox 相同但方向不一致的三页图片不会形成同一视觉页眉簇。"""-- pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(4)]- for page_index, page in enumerate(pages[1:], start=1):- page.fixed_blocks = [- {- "type": "image",- "bbox": (10.0, 0.0, 90.0, 10.0),- "angle": 90 if page_index == 3 else 0,- "content": f"page-{page_index}",- }- ]-- auxiliary_text._classify_repeated_visual_headers(pages)-- assert [page.fixed_blocks[0]["type"] for page in pages[1:]] == ["image"] * 3---def test_image_bottom_border_does_not_create_image_or_page_footnote() -> None:- """验证图片下沿自身的坐标轴横线不会把紧邻图中文字判成脚注。"""-- body = [- _text_line(- f"body {index}",- (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- axis_label = _text_line(- "T -1/4",- (150.0, 317.0, 230.0, 325.0),- 4,- effective_height=8.0,- )- page = _prepared_text_page(- *body,- axis_label,- page_size=(500.0, 500.0),- )- page.fixed_blocks = [- {- "type": "image",- "bbox": (50.0, 140.0, 300.0, 315.0),- "angle": 0,- "content": "",- }- ]- page.drawing_lines = [- models._AxisLine(- (50.0, 314.0, 300.0, 315.0),- 1.0,- "horizontal",- )- ]-- auxiliary_text._classify_page_auxiliary_text(page)-- assert axis_label.semantic_type is None- assert page.page_footnote_groups == []---def test_two_bottom_rules_classify_centered_url_as_footer() -> None:- """验证页面底部两条同跨度横线把其间居中网址标为页脚。"""-- body = [- _text_line(- f"body {index}",- (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),- index,- effective_height=10.0,- )- for index in range(4)- ]- url = _text_line(- "https://example.test/journal",- (350.0, 920.0, 650.0, 930.0),- 10,- effective_height=10.0,- )- page = _prepared_text_page(- *body,- url,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [- models._AxisLine((300.0, 900.0, 700.0, 901.0), 1.0, "horizontal"),- models._AxisLine((300.0, 950.0, 700.0, 951.0), 1.0, "horizontal"),- ]-- auxiliary_text._classify_rule_delimited_footers([page])-- assert url.semantic_type == "footer"---def test_single_bottom_rule_classifies_small_right_lane_rows_as_footer() -> None:- """验证底部单横线下方的右栏连续小字被标为页脚。"""-- body = [- _text_line(- f"body {column}-{row}",- (- 80.0 + 500.0 * column,- 100.0 + 25.0 * row,- 420.0 + 500.0 * column,- 110.0 + 25.0 * row,- ),- 10 * column + row,- effective_height=10.0,- )- for column in range(2)- for row in range(5)- ]- footer_rows = [- _text_line(- f"footer {index}",- (600.0, 858.0 + 10.0 * index, 880.0, 866.0 + 10.0 * index),- 20 + index,- effective_height=8.0,- )- for index in range(3)- ]- page = _prepared_text_page(- *body,- *footer_rows,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [models._AxisLine((580.0, 850.0, 900.0, 851.0), 1.0, "horizontal")]-- auxiliary_text._classify_rule_delimited_footers([page])-- assert [line.semantic_type for line in footer_rows] == ["footer"] * 3- assert all(line.semantic_type is None for line in body)--[email protected]("inside_image", [False, True])-def test_single_bottom_rule_rejects_body_sized_or_container_rows(- inside_image: bool,-) -> None:- """验证正文大小的行和图片内部横线均不能触发单横线页脚。"""-- body = [- _text_line(- f"body {index}",- (100.0, 100.0 + 25.0 * index, 900.0, 110.0 + 25.0 * index),- index,- effective_height=10.0,- )- for index in range(6)- ]- bottom_rows = [- _text_line(- f"bottom {index}",- (150.0, 858.0 + 12.0 * index, 850.0, 868.0 + 12.0 * index),- 10 + index,- effective_height=8.0 if inside_image else 10.0,- )- for index in range(2)- ]- page = _prepared_text_page(- *body,- *bottom_rows,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [models._AxisLine((100.0, 850.0, 900.0, 851.0), 1.0, "horizontal")]- if inside_image:- page.fixed_blocks = [- {- "type": "image",- "bbox": (80.0, 800.0, 920.0, 900.0),- "angle": 0,- "content": "",- }- ]-- auxiliary_text._classify_rule_delimited_footers([page])-- assert all(line.semantic_type is None for line in bottom_rows)---def test_single_bottom_rule_rejects_formula_fragments_with_unstable_left_edges() -> None:- """验证分数线下横向起点离散的公式碎片不能被误判为页脚。"""-- body = [- _text_line(- f"body {column}-{row}",- (- 80.0 + 500.0 * column,- 100.0 + 25.0 * row,- 420.0 + 500.0 * column,- 110.0 + 25.0 * row,- ),- 10 * column + row,- effective_height=10.0,- )- for column in range(2)- for row in range(5)- ]- formula_fragments = [- _text_line(- f"fragment {index}",- (left, 858.0 + 9.0 * index, left + 80.0, 866.0 + 9.0 * index),- 20 + index,- effective_height=8.0,- )- for index, left in enumerate((590.0, 710.0, 620.0))- ]- page = _prepared_text_page(- *body,- *formula_fragments,- page_size=(1000.0, 1000.0),- )- page.drawing_lines = [models._AxisLine((600.0, 850.0, 850.0, 851.0), 1.0, "horizontal")]-- auxiliary_text._classify_rule_delimited_footers([page])-- assert all(line.semantic_type is None for line in formula_fragments)---def test_split_footer_row_fragments_inherit_stable_anchor_type() -> None:- """验证同一页脚视觉行的左右碎片从稳定锚点继承 footer 类型。"""-- fragments = [- _text_line(- "journal",- (100.0, 930.0, 300.0, 940.0),- 0,- visual_row_id=8,- split_from_row=True,- ),- _text_line(- "Vol. 1",- (420.0, 930.0, 500.0, 940.0),- 1,- visual_row_id=8,- split_from_row=True,- semantic_type="footer",- ),- _text_line(- "No. 2",- (650.0, 930.0, 750.0, 940.0),- 2,- visual_row_id=8,- split_from_row=True,- ),- ]- page = _prepared_text_page(- *fragments,- page_size=(1000.0, 1000.0),- )-- auxiliary_text._classify_split_marginal_row_companions([page])-- assert [line.semantic_type for line in fragments] == ["footer"] * 3---def test_distant_same_row_text_inherits_top_page_number_header_type() -> None:- """验证页码与远距运行标题同基线时不依赖水平距离也能标为页眉。"""-- page_number = _text_line(- "8",- (10.0, 10.0, 15.0, 15.0),- 0,- semantic_type="page_number",- )- running_title = _text_line(- "running title",- (60.0, 10.0, 90.0, 15.0),- 1,- )- page = _prepared_text_page(- page_number,- running_title,- page_size=(100.0, 100.0),- )-- auxiliary_text._classify_page_number_outer_companions([page])-- assert page_number.semantic_type == "page_number"- assert running_title.semantic_type == "header"diff --git a/tests/unittest/test_flash_pdf_document_profile.py b/tests/unittest/test_flash_pdf_document_profile.pydeleted file mode 100644index b25f2a0c..00000000--- a/tests/unittest/test_flash_pdf_document_profile.py+++ /dev/null@@ -1,594 +0,0 @@-from __future__ import annotations--from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import titles--from _flash_pdf_test_utils import _prepared_text_page, _text_line---def test_document_body_profile_prefers_cross_page_body_and_regular_fonts() -> None:- """验证全文画像优先跨页正文行高,并排除反复出现的明显粗体字体。"""-- body_font = ("BodyRegular", 0)- mono_font = ("MonoRegular", 0)- italic_font = ("BodyItalic", 1 << 6)- bold_font = ("HeadingBold", 1)- pages = []- for page_index in range(4):- lines = [- _text_line(- "body",- (0.0, 10.0, 80.0, 20.0),- page_index * 10,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- )- ]- if page_index < 3:- lines.extend(- [- _text_line(- "mono",- (0.0, 30.0, 80.0, 38.0),- page_index * 10 + 1,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "bold",- (0.0, 50.0, 80.0, 60.0),- page_index * 10 + 2,- effective_height=10.0,- font_signature=bold_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- _text_line(- "italic",- (0.0, 70.0, 80.0, 78.0),- page_index * 10 + 3,- effective_height=8.0,- font_signature=italic_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- ]- )- pages.append(_prepared_text_page(*lines))-- profile = titles._infer_document_body_profile(pages)-- assert profile is not None- assert profile.body_height == 10.0- assert profile.body_weight == 400.0- # 正文字体画像只统计正文高度带,较矮的等宽和斜体样本不再进入 regular_fonts。- assert profile.regular_fonts == frozenset({body_font})---def test_sparse_repeated_font_is_not_document_regular_style() -> None:- """验证只在多页短标题中反复出现的字体不会被并入全文常规字体。"""-- body_font = ("BodyRegular", 0)- sparse_font = ("SparseHeading", 1)- pages = [- _prepared_text_page(- _text_line(- "body",- (0.0, 10.0, 100.0, 20.0),- page_index * 2,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=0.0,- ),- _text_line(- "short",- (0.0, 40.0, 50.0, 50.0),- page_index * 2 + 1,- font_signature=sparse_font,- font_coverage=1.0,- dominant_font_weight=0.0,- ),- )- for page_index in range(5)- ]-- profile = titles._infer_document_body_profile(pages)-- assert profile is not None- assert body_font in profile.regular_fonts- assert sparse_font not in profile.regular_fonts---def test_document_regular_font_suppresses_code_page_false_title() -> None:- """验证代码页中的全文常规字体说明保持正文,粗体步骤标签仍识别为标题。"""-- mono_font = ("MonoRegular", 0)- regular_font = ("BodyRegular", 0)- bold_font = ("HeadingBold", 1)- lines = [- _text_line(- "code one",- (0.0, 5.0, 100.0, 13.0),- 0,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "code two",- (0.0, 15.0, 100.0, 23.0),- 1,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "ordinary instruction",- (0.0, 40.0, 45.0, 50.0),- 2,- effective_height=10.0,- font_signature=regular_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "code three",- (0.0, 62.0, 100.0, 70.0),- 3,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "code four",- (0.0, 72.0, 100.0, 80.0),- 4,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "bold step",- (0.0, 100.0, 35.0, 110.0),- 5,- effective_height=10.0,- font_signature=bold_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- _text_line(- "code five",- (0.0, 122.0, 100.0, 130.0),- 6,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({mono_font, regular_font}),- )-- titles._classify_page_titles(- lines,- (100.0, 150.0),- page_index=1,- container_bboxes=[],- document_body_profile=profile,- )-- assert lines[2].semantic_type is None- assert lines[5].semantic_type == "paragraph_title"---def test_document_title_profile_promotes_table_adjacent_style_but_not_container_label() -> None:- """验证跨页标题原型可越过邻表抑制,但容器内部同样式标签仍保持正文。"""-- heading_font = ("Heading", 0)- heading = _text_line(- "heading",- (0.0, 10.0, 40.0, 24.0),- 0,- effective_height=14.0,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=600.0,- )- container_label = _text_line(- "container label",- (0.0, 40.0, 40.0, 54.0),- 1,- effective_height=14.0,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=600.0,- )- body_profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({("Body", 0)}),- )- title_profile = models._DocumentTitleProfile(- (- models._TitleStylePrototype(- font_family="heading",- font_flags=0,- height_ratio=1.4,- weight=600.0,- alignment="left",- anchor_offset=0.0,- support_count=4,- support_pages=3,- ),- )- )-- titles._classify_page_titles(- [heading, container_label],- (100.0, 100.0),- page_index=1,- container_bboxes=[(0.0, 28.0, 100.0, 90.0)],- document_body_profile=body_profile,- document_title_profile=title_profile,- )-- assert heading.semantic_type == "paragraph_title"- assert container_label.semantic_type is None---def test_document_title_profile_promotes_body_height_centered_section() -> None:- """验证与正文同字体字号的居中章节行可凭重复标题原型和邻表关系晋升。"""-- regular_font = ("Body", 0)- heading = _text_line(- "section",- (30.0, 24.0, 70.0, 34.0),- 0,- effective_height=10.0,- font_signature=regular_font,- font_coverage=1.0,- dominant_font_weight=400.0,- )- body = _text_line(- "body",- (0.0, 40.0, 100.0, 50.0),- 1,- effective_height=10.0,- font_signature=regular_font,- font_coverage=1.0,- dominant_font_weight=400.0,- )- body_profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({regular_font}),- )- title_profile = models._DocumentTitleProfile(- (- models._TitleStylePrototype(- font_family="body",- font_flags=0,- height_ratio=1.0,- weight=400.0,- alignment="center",- anchor_offset=0.0,- support_count=5,- support_pages=3,- ),- )- )-- titles._classify_page_titles(- [heading, body],- (100.0, 100.0),- page_index=1,- container_bboxes=[(0.0, 0.0, 100.0, 20.0)],- document_body_profile=body_profile,- document_title_profile=title_profile,- )-- assert heading.semantic_type == "paragraph_title"- assert body.semantic_type is None---def test_document_title_profile_infers_repeated_large_left_aligned_style() -> None:- """验证两页重复的大字号左对齐样式可形成文档级标题原型。"""-- body_font = ("Body", 0)- heading_font = ("RepeatedHeading", 0)- pages = [- _prepared_text_page(- _text_line(- "body cover",- (0.0, 20.0, 100.0, 30.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- page_size=(100.0, 100.0),- )- ]- for page_index in range(1, 3):- pages.append(- _prepared_text_page(- _text_line(- f"heading {page_index}",- (0.0, 10.0, 45.0, 24.0),- page_index * 10,- effective_height=14.0,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=600.0,- ),- _text_line(- f"body {page_index}",- (0.0, 40.0, 100.0, 50.0),- page_index * 10 + 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- page_size=(100.0, 100.0),- )- )- body_profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- profile = titles._infer_document_title_profile(pages, body_profile)-- assert profile is not None- assert len(profile.prototypes) == 1- assert profile.prototypes[0].font_family == "repeatedheading"- assert profile.prototypes[0].support_pages == 2---def test_regular_pitch_style_change_does_not_become_title() -> None:- """验证仅有字体变化、但没有额外段间净空的正文续行不会误判标题。"""-- body_font = ("Body", 0)- alternate_font = ("Alternate", 0)- lines = [- _text_line(- "body one",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "continuation",- (0.0, 16.0, 80.0, 26.0),- 1,- font_signature=alternate_font,- font_coverage=1.0,- ),- _text_line(- "body two",- (0.0, 32.0, 100.0, 42.0),- 2,- font_signature=body_font,- font_coverage=1.0,- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._classify_page_titles(- lines,- (100.0, 100.0),- page_index=1,- container_bboxes=[],- document_body_profile=profile,- )-- assert lines[1].semantic_type is None---def test_title_font_at_body_size_does_not_override_document_size_profile() -> None:- """验证标题字体落入正文字号带时不会仅凭大留白继续误判为标题。"""-- heading_font = ("Heading", 0)- lines = [- _text_line(- "body one",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=("Body", 0),- font_coverage=1.0,- ),- _text_line(- "weak heading",- (0.0, 35.0, 45.0, 46.0),- 1,- effective_height=11.0,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body two",- (0.0, 60.0, 100.0, 70.0),- 2,- font_signature=("Body", 0),- font_coverage=1.0,- ),- ]- body_profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({("Body", 0)}),- )- title_profile = models._DocumentTitleProfile(- (- models._TitleStylePrototype(- font_family="heading",- font_flags=0,- height_ratio=1.4,- weight=400.0,- alignment="left",- anchor_offset=0.0,- support_count=4,- support_pages=3,- ),- )- )-- titles._classify_page_titles(- lines,- (100.0, 100.0),- page_index=1,- container_bboxes=[],- document_body_profile=body_profile,- document_title_profile=title_profile,- )-- assert lines[1].semantic_type is None---def test_smaller_recurrent_regular_font_does_not_gain_title_style_signal() -> None:- """验证较小的跨页常规代码字体即使留白较大,也不会仅凭字体切换升为标题。"""-- body_font = ("BodyRegular", 0)- mono_font = ("MonoRegular", 0)- lines = [- _text_line(- "body one",- (0.0, 5.0, 100.0, 15.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body two",- (0.0, 17.0, 100.0, 27.0),- 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "small regular command",- (2.0, 45.0, 98.0, 53.0),- 2,- effective_height=8.0,- font_signature=mono_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body three",- (0.0, 70.0, 100.0, 80.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body four",- (0.0, 82.0, 100.0, 92.0),- 4,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font, mono_font}),- )-- titles._classify_page_titles(- lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- document_body_profile=profile,- )-- assert lines[2].semantic_type is None---def test_document_profile_finds_cover_title_without_promoting_bottom_metadata() -> None:- """验证全文正文基准可识别纯封面标题,底部版本元数据仍保持普通文本。"""-- title_font = ("TitleBold", 1)- metadata_font = ("MetadataBold", 1)- lines = [- _text_line(- "cover title one",- (15.0, 55.0, 85.0, 80.0),- 0,- effective_height=25.0,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- _text_line(- "cover title two",- (25.0, 85.0, 75.0, 110.0),- 1,- effective_height=25.0,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- _text_line(- "version metadata",- (35.0, 168.0, 65.0, 178.0),- 2,- effective_height=10.0,- font_signature=metadata_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- _text_line(- "date metadata",- (30.0, 180.0, 70.0, 190.0),- 3,- effective_height=10.0,- font_signature=metadata_font,- font_coverage=1.0,- dominant_font_weight=800.0,- ),- ]- profile = models._DocumentBodyProfile(10.0, 400.0, frozenset())-- titles._classify_page_titles(- lines,- (100.0, 200.0),- page_index=0,- container_bboxes=[],- document_body_profile=profile,- )-- assert [line.semantic_type for line in lines] == [- "doc_title",- "doc_title",- None,- None,- ]diff --git a/tests/unittest/test_flash_pdf_extractor.py b/tests/unittest/test_flash_pdf_extractor.pydeleted file mode 100644index b98c2a11..00000000--- a/tests/unittest/test_flash_pdf_extractor.py+++ /dev/null@@ -1,46 +0,0 @@-from docvortex.analyzers.native.pdf import pipeline---def test_marginal_header_row_does_not_break_two_column_reading_order() -> None:- """验证边缘页眉按视觉行排序且正文保持先左栏后右栏。"""- blocks = [- {"type": "header", "bbox": (80.0, 2.0, 120.0, 12.0), "angle": 0, "content": "center"},- {"type": "page_number", "bbox": (2.0, 0.0, 12.0, 14.0), "angle": 0, "content": "page"},- {"type": "header", "bbox": (175.0, 1.0, 198.0, 13.0), "angle": 0, "content": "volume"},- {"type": "text", "bbox": (0.0, 20.0, 80.0, 40.0), "angle": 0, "content": "left one"},- {"type": "text", "bbox": (0.0, 45.0, 80.0, 65.0), "angle": 0, "content": "left two"},- {"type": "text", "bbox": (120.0, 20.0, 200.0, 40.0), "angle": 0, "content": "right one"},- {"type": "text", "bbox": (120.0, 45.0, 200.0, 65.0), "angle": 0, "content": "right two"},- ]-- sorted_blocks = pipeline._sort_blocks_with_visual_row_groups(blocks, (200.0, 100.0))-- assert [block["content"] for block in sorted_blocks] == [- "page",- "center",- "volume",- "left one",- "left two",- "right one",- "right two",- ]---def test_overlapping_span_captions_follow_visual_center_order() -> None:- """验证跨栏带中轻微重叠的图注按视觉中心稳定排序。"""- common = {- "type": "text",- "angle": 0,- "_lane_interval": (20.0, 180.0),- "_lane_is_span": True,- "_line_heights": [10.0],- }- later = {**common, "bbox": (30.0, 58.0, 170.0, 70.0), "content": "later"}- earlier = {**common, "bbox": (70.0, 50.0, 130.0, 62.0), "content": "earlier"}-- stabilized = pipeline._stabilize_overlapping_lane_order(- [later, earlier],- (200.0, 100.0),- )-- assert [block["content"] for block in stabilized] == ["earlier", "later"]diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.pydeleted file mode 100644index 63c4b98b..00000000--- a/tests/unittest/test_flash_pdf_formulas.py+++ /dev/null@@ -1,1773 +0,0 @@-from __future__ import annotations---from dataclasses import replace--import pytest--from docvortex.analyzers.native.pdf import formulas-from docvortex.analyzers.native.pdf import geometry-from docvortex.analyzers.native.pdf import line_merging-from docvortex.analyzers.native.pdf import models-from docvortex.document.pdf.document import PDFPathInfo---from _flash_pdf_test_utils import (- _text_line,-)---def _formula_member(- text: str,- bbox: tuple[float, float, float, float],- source_index: int,-) -> tuple[models._LineItem, tuple[float, float, float, float]]:- """构造公式块序列化测试使用的文本行及其局部几何。"""-- return (- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=bbox[3] - bbox[1],- ),- bbox,- )---def test_formula_members_expose_union_of_tight_bboxes_with_one_point_padding() -> None:- """验证文本公式聚合后保留全部成员的 tight+1pt 输出包络。"""-- body, body_bbox = _formula_member(- "x=1",- (10.0, 20.0, 50.0, 40.0),- 0,- )- number, number_bbox = _formula_member(- "(1)",- (80.0, 25.0, 90.0, 35.0),- 1,- )- body.ink_bbox = (12.0, 25.0, 48.0, 35.0)- number.ink_bbox = (82.0, 27.0, 89.0, 33.0)-- block = formulas._formula_members_to_block(- [(body, body_bbox), (number, number_bbox)],- (100.0, 100.0),- 0,- anchor_source_index=1,- )-- assert block is not None- assert block["_tight_output_bbox"] == (- 11.0,- 24.0,- 90.0,- 36.0,- )--- "text",- [- "(℃/hm),用 I 表示:I=ΔT",- "温度可表示为T=ΔT",- "The temperature value T=ΔT",- ],- ids=["chinese-with-unit", "chinese-without-punctuation", "english-without-keyword"],-)-def test_formula_component_rejects_left_aligned_prose_prefix(text: str) -> None:- """验证同栏左缘带通用正文前缀的复杂行内分式不升级为行间公式。"""-- prose = _text_line(- text,- (0.0, 20.0, 55.0, 30.0),- 0,- effective_height=10.0,- )- numerator = _text_line(- "×100%",- (56.0, 20.0, 78.0, 30.0),- 1,- effective_height=10.0,- )- denominator = _text_line(- "ΔH",- (45.0, 30.0, 55.0, 38.0),- 2,- effective_height=8.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (prose, prose.bbox),- (numerator, numerator.bbox),- (denominator, denominator.bbox),- ],- )-- assert formulas._formula_component_has_left_prose(- lane.lines,- lane,- 10.0,- )--- "text",- [- "I=ΔT",- "x+y=z",- "Score=MLP(vCLS)",- "conf(Bm)=1",- "(摄氏度)=T",- "(temperature value)=T",- ],- ids=[- "single-variable",- "symbolic-expression",- "single-identifier",- "function-identifier",- "chinese-bracketed-unit",- "english-bracketed-unit",- ],-)-def test_formula_component_keeps_left_aligned_formula_identifiers(text: str) -> None:- """验证变量、符号表达式、无空白标识符和纯括号单位仍保留为独立公式。"""-- formula = _text_line(- text,- (0.0, 20.0, 55.0, 30.0),- 0,- effective_height=10.0,- )- denominator = _text_line(- "ΔH",- (45.0, 30.0, 55.0, 38.0),- 1,- effective_height=8.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (formula, formula.bbox),- (denominator, denominator.bbox),- ],- )-- assert not formulas._formula_component_has_left_prose(- [(formula, formula.bbox), (denominator, denominator.bbox)],- lane,- 10.0,- )---def test_inline_prose_formula_component_returns_to_paragraph_context() -> None:- """验证同行正文公式不生成公式块,并标记为后续正文聚合上下文。"""-- body_font = ("Body", 0)- prose_formula = _text_line(- "温度可表示为T=ΔT",- (0.0, 40.0, 58.0, 50.0),- 0,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- )- denominator = _text_line(- "ΔH",- (25.0, 51.0, 55.0, 61.0),- 1,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- )- number = _text_line(- "(5)",- (91.0, 49.0, 100.0, 59.0),- 2,- effective_height=10.0,- )- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- 3 + index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((76.0, 88.0, 100.0, 112.0))- ]-- blocks, remaining = formulas._build_formula_like_blocks(- [prose_formula, denominator, number, *body_lines],- [],- (100.0, 140.0),- )-- assert blocks == []- assert prose_formula.paragraph_formula_context- assert denominator.paragraph_formula_context- assert number.paragraph_formula_context- assert {line.source_index for line in remaining} == set(range(7))---def test_isolated_numbered_fraction_overrides_left_prose_shape() -> None:- """验证带分数线和上下净空的编号多层公式不被变量名误判为正文。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "preceding body",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "FZ SSEs KSSEc=SSEx",- (0.0, 25.0, 60.0, 35.0),- 1,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line(- "SSEc=dfc",- (25.0, 36.0, 45.0, 46.0),- 2,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line(- "(7)",- (91.0, 31.0, 100.0, 41.0),- 3,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "following body",- (0.0, 60.0, 100.0, 70.0),- 4,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- assert formulas._formula_component_has_left_prose(- [(line, line.bbox) for line in lines[1:4]],- lane,- 10.0,- )- assert formulas._formula_component_has_isolated_numbered_fraction(- [(line, line.bbox) for line in lines[1:4]],- lane,- 10.0,- [(10.0, 34.5, 60.0, 35.0)],- )---def _vector_path(- bbox: tuple[float, float, float, float],- source_index: int,- *,- segment_count: int = 16,- fill_visible: bool = True,- stroke_visible: bool = False,- form_depth: int = 0,-) -> PDFPathInfo:- """构造矢量公式检测测试使用的 Path 信息。"""-- return PDFPathInfo(- bbox=bbox,- segment_count=segment_count,- fill_visible=fill_visible,- stroke_visible=stroke_visible,- form_depth=form_depth,- source_index=source_index,- )---def _vector_formula_body_paths(- *,- left: float = 20.0,- top: float = 50.0,- source_start: int = 0,-) -> list[PDFPathInfo]:- """构造满足复杂度和尺寸约束的六字形矢量公式主体。"""-- return [- _vector_path(- (left + index * 6.0, top, left + index * 6.0 + 4.0, top + 12.0),- source_start + index,- )- for index in range(6)- ]---def _vector_formula_source(- *path_infos: PDFPathInfo,- page_size: tuple[float, float] = (100.0, 120.0),- extra_lines: list[models._LineItem] | None = None,-) -> models._PageSource:- """构造具有稳定正文栏带且公式所在高度留白的页面源。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 20.0, 80.0, 100.0))- ]- lines.extend(extra_lines or [])- return models._PageSource(- page_size=page_size,- lines=lines,- chars=[],- drawing_lines=[],- path_infos=list(path_infos),- )---def test_single_line_formula_requires_numeric_trailing_marker() -> None:- """验证同行公式只把数字编号识别为 tag,不把函数参数当编号。"""-- numbered = _text_line(- "score=f(x) (3)",- (15.0, 30.0, 90.0, 40.0),- 0,- effective_height=10.0,- )- parenthesized_argument = _text_line(- "Score=MLP(vCLS)",- (15.0, 50.0, 90.0, 60.0),- 1,- effective_height=10.0,- )- numbered.style_scale_repaired = True- parenthesized_argument.style_scale_repaired = True- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (numbered, numbered.bbox),- (parenthesized_argument, parenthesized_argument.bbox),- ],- )-- assert formulas._is_single_line_numbered_formula(- (numbered, numbered.bbox),- lane,- 10.0,- )- assert not formulas._is_single_line_numbered_formula(- (parenthesized_argument, parenthesized_argument.bbox),- lane,- 10.0,- )---def test_single_line_numbered_formula_absorbs_connected_math_sidecars() -> None:- """验证带编号公式核心吸收等号前缀和窄分子,但不吸收后续正文。"""-- core = _text_line(- "|Bm| sum(yi) (1)",- (40.0, 20.0, 95.0, 35.0),- 0,- effective_height=10.0,- )- prefix = _text_line(- "acc(Bm)=",- (10.0, 24.0, 39.5, 34.0),- 1,- effective_height=10.0,- )- numerator = _text_line(- "1",- (55.0, 15.0, 60.0, 23.0),- 2,- effective_height=8.0,- )- body = _text_line(- "ordinary following prose",- (0.0, 40.0, 100.0, 50.0),- 3,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- core.style_scale_repaired = True- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (core, core.bbox),- (prefix, prefix.bbox),- (numerator, numerator.bbox),- (body, body.bbox),- ],- )-- members = formulas._expand_single_line_numbered_formula_members(- (core, core.bbox),- lane,- set(),- [],- ("Body", 0),- 10.0,- )- block = formulas._formula_members_to_block(- members,- (100.0, 100.0),- 0,- anchor_source_index=core.source_index,- )-- assert {line.source_index for line, _bbox in members} == {0, 1, 2}- assert block is not None- assert "acc(Bm)=" in block["content"]- assert block["content"].count("\\tag{1}") == 1---def test_vector_formula_paths_and_detached_path_number_form_one_empty_equation() -> None:- """验证矢量主体与远距栏右缘路径编号形成一个空内容公式。"""-- body_paths = _vector_formula_body_paths()- number_paths = [_vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), 10 + index) for index in range(3)]- blocks, claimed = formulas._build_vector_formula_blocks(- _vector_formula_source(*body_paths, *number_paths),- [],- set(),- )-- assert claimed == set()- assert blocks == [- {- "type": "equation",- "bbox": (19.0, 49.0, 100.0, 63.0),- "angle": 0,- "content": "",- }- ]---def test_vector_formula_claims_text_number_but_keeps_content_empty() -> None:- """验证可提取的独立编号并入路径公式并唯一认领,但不充当公式正文。"""-- number = _text_line("(12)", (91.0, 51.0, 99.0, 60.0), 20, effective_height=9.0)- blocks, claimed = formulas._build_vector_formula_blocks(- _vector_formula_source(*_vector_formula_body_paths(), extra_lines=[number]),- [],- set(),- )-- assert claimed == {20}- assert blocks[0]["type"] == "equation"- assert blocks[0]["content"] == ""- assert blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 100.0, 63.0))---def test_vector_formula_rejects_unmatched_number_rules_strokes_forms_and_inline_paths() -> None:- """验证无主体编号、细规则、描边、Form 图标和正文同行路径均不会误报。"""-- unmatched_number = [_vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), index) for index in range(3)]- rules = [- _vector_path((10.0 + index * 12.0, 70.0, 20.0 + index * 12.0, 70.5), 10 + index, segment_count=5) for index in range(6)- ]- excluded = [- _vector_path((20.0, 50.0, 24.0, 62.0), 30, stroke_visible=True),- _vector_path((26.0, 50.0, 30.0, 62.0), 31, form_depth=1),- ]- inline_paths = _vector_formula_body_paths(top=20.0, source_start=40)- blocks, claimed = formulas._build_vector_formula_blocks(- _vector_formula_source(*unmatched_number, *rules, *excluded, *inline_paths),- [],- set(),- )-- assert blocks == []- assert claimed == set()---def test_vector_formula_respects_columns_and_existing_containers() -> None:- """验证同高双栏主体不互连,且高优先级容器覆盖的主体被排除。"""-- left_lines = [- _text_line(f"left-{index}", (0.0, top, 100.0, top + 10.0), index, effective_height=10.0)- for index, top in enumerate((0.0, 20.0, 80.0, 100.0))- ]- right_lines = [- _text_line(- f"right-{index}",- (120.0, top, 220.0, top + 10.0),- 10 + index,- effective_height=10.0,- )- for index, top in enumerate((0.0, 20.0, 80.0, 100.0))- ]- source = models._PageSource(- page_size=(220.0, 120.0),- lines=[*left_lines, *right_lines],- chars=[],- drawing_lines=[],- path_infos=[- *_vector_formula_body_paths(left=20.0, source_start=0),- *_vector_formula_body_paths(left=140.0, source_start=20),- ],- )-- column_blocks, column_claimed = formulas._build_vector_formula_blocks(- source,- [],- set(),- )- blocks, claimed = formulas._build_vector_formula_blocks(- source,- [{"type": "image", "bbox": (130.0, 45.0, 180.0, 67.0), "content": ""}],- set(),- )-- assert column_claimed == set()- assert len(column_blocks) == 2- assert column_blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 55.0, 63.0))- assert column_blocks[1]["bbox"] == pytest.approx((139.0, 49.0, 175.0, 63.0))- assert claimed == set()- assert len(blocks) == 1- assert blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 55.0, 63.0))---def test_detached_formula_sidecar_sharing_middle_row_moves_to_trailing_line() -> None:- """验证纯 bbox 规则会后置与正文共享中间视觉行的远距窄幅 sidecar。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),- _formula_member("marker", (100.0, 10.0, 110.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator\nbody\ndenominator\nmarker",- }--[email protected]("marker", ["(4)", "(4)", "﹙4﹚", "(4)"])-def test_adjacent_parenthesized_formula_number_serializes_as_tag(marker: str) -> None:- """验证贴近公式主体的多种圆括号序号转为 tag,且前导逗号留在正文。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),- _formula_member(f", {marker}", (91.0, 0.0, 110.0, 10.0), 1),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator,\nbody\ndenominator\\tag{4}",- }---def test_adjacent_square_bracket_formula_sidecar_keeps_visual_order() -> None:- """验证方括号内容不触发圆括号公式序号规则。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),- _formula_member(", [4]", (91.0, 0.0, 110.0, 10.0), 1),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator, [4]\nbody\ndenominator",- }---def test_detached_formula_sidecar_on_middle_row_moves_after_denominator() -> None:- """验证独占中间视觉行的远距窄幅 sidecar 排到分母后且不留下空行。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 70.0, 10.0), 0),- _formula_member("sidecar", (100.0, 10.0, 110.0, 20.0), 1),- _formula_member("denominator", (30.0, 20.0, 65.0, 30.0), 2),- ]-- block = formulas._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (20.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator\ndenominator\nsidecar",- }---def test_detached_formula_sidecar_already_at_end_keeps_visual_row() -> None:- """验证已经处于内容末尾的离散 sidecar 保持原视觉行格式。"""-- members = [- _formula_member("formula", (10.0, 0.0, 40.0, 10.0), 0),- _formula_member("terminal", (100.0, 0.0, 110.0, 10.0), 1),- ]-- block = formulas._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 10.0),- "angle": 0,- "content": "formula terminal",- }---def test_attached_formula_sidecar_keeps_visual_order() -> None:- """验证与公式主体净空不足的右侧锚点保持原视觉顺序。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),- _formula_member("sidecar", (85.0, 10.0, 95.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (120.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 95.0, 30.0),- "angle": 0,- "content": "numerator\nbody sidecar\ndenominator",- }---def test_wide_formula_sidecar_keeps_visual_order() -> None:- """验证宽度超过中位行高限制的远距锚点不会被后置。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),- _formula_member("wide", (100.0, 10.0, 126.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (140.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 126.0, 30.0),- "angle": 0,- "content": "numerator\nbody wide\ndenominator",- }---def test_non_rightmost_formula_sidecar_keeps_visual_order() -> None:- """验证未处于公式分量最右侧的锚点不会被后置。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 120.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),- _formula_member("sidecar", (90.0, 10.0, 100.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = formulas._formula_members_to_block(- members,- (140.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 120.0, 30.0),- "angle": 0,- "content": "numerator\nbody sidecar\ndenominator",- }---def test_detached_formula_anchor_collects_multiline_formula_but_not_body_prefix() -> None:- """验证低位右缘锚点上溯多行公式,并排除左对齐正文与靠右句点。"""-- body_font = ("Body", 0)- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 24.0))- ]- body_prefix = _text_line(- "regular prose before formula",- (0.0, 60.0, 60.0, 70.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- formula_lines = [- _text_line("numerator", (20.0, 42.0, 50.0, 52.0), 4, effective_height=10.0),- _text_line("Fp =", (15.0, 52.0, 45.0, 62.0), 5, effective_height=10.0),- _text_line("otherwise", (20.0, 65.0, 65.0, 75.0), 6, effective_height=10.0),- _text_line("0,", (68.0, 72.0, 78.0, 82.0), 7, effective_height=10.0),- ]- punctuation = _text_line(".", (93.0, 45.0, 96.0, 55.0), 8, effective_height=10.0)- number = _text_line("(7)", (91.0, 75.0, 100.0, 85.0), 9, effective_height=10.0)- lane_lines = [*body_lines, body_prefix, *formula_lines, punctuation, number]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lane_lines],- )-- anchors = formulas._find_formula_spatial_anchors(lane, 10.0)-- assert len(anchors) == 1- assert anchors[0].line is number- assert anchors[0].detached_below_body-- anchor_center = geometry._bbox_center_y(anchors[0].bbox)- dominant_font = formulas._infer_formula_body_font(lane, 10.0)- members = formulas._grow_formula_spatial_component(- lane,- anchors[0],- anchor_center - 4.75 * 10.0,- anchor_center + 2.25 * 10.0,- set(),- [],- dominant_font,- 10.0,- )- member_texts = {line.text for line, _bbox in members}-- assert member_texts == {"numerator", "Fp =", "otherwise", "0,", "(7)"}- assert body_prefix.text not in member_texts- assert punctuation.text not in member_texts---def test_formula_above_dense_body_collects_math_but_stops_at_title_barrier() -> None:- """验证正文密集区上方的公式可聚合,且不会吸收紧邻的章节标题。"""-- body_font = ("Body", 0)- formula_lines = [- _text_line(- "formula numerator",- (20.0, 8.0, 58.0, 18.0),- 0,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line(- "formula denominator",- (25.0, 19.0, 55.0, 29.0),- 1,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- ),- ]- number = _text_line("(5)", (91.0, 17.0, 100.0, 27.0), 2, effective_height=10.0)- heading = _text_line(- "neutral section heading",- (0.0, 28.0, 40.0, 42.0),- 3,- effective_height=14.0,- font_signature=("Heading", 0),- font_coverage=1.0,- )- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- 4 + index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((44.0, 56.0, 68.0, 80.0))- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- *((line, line.bbox) for line in formula_lines),- (number, number.bbox),- (heading, heading.bbox),- *((line, line.bbox) for line in body_lines),- ],- )-- anchors = formulas._find_formula_spatial_anchors(lane, 10.0, body_font)-- assert len(anchors) == 1- assert anchors[0].detached_above_body- members = formulas._grow_formula_spatial_component(- lane,- anchors[0],- 0.0,- 100.0,- set(),- [],- body_font,- 10.0,- )-- assert {line.text for line, _bbox in members} == {- "formula numerator",- "formula denominator",- "(5)",- }---def test_formula_number_cannot_upgrade_ordinary_body_row() -> None:- """验证括号编号缺少独立公式主体时不能把普通正文升级为公式。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 48.0, 60.0))- ]- ordinary = _text_line(- "ordinary body row",- (0.0, 30.0, 70.0, 40.0),- 4,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- number = _text_line("(9)", (91.0, 30.0, 100.0, 40.0), 5, effective_height=10.0)-- blocks, remaining = formulas._build_formula_like_blocks(- [*lines, ordinary, number],- [],- (100.0, 80.0),- )-- assert blocks == []- assert ordinary in remaining- assert number in remaining---def test_overlapping_denominator_cannot_become_short_formula_anchor() -> None:- """验证与正文横向重叠的右缘分母字符不会成为非编号公式锚点。"""-- body_font = ("Body", 0)- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 92.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 24.0))- ]- formula_body = _text_line(- "Pr = cp mu",- (25.0, 36.0, 90.0, 46.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=0.8,- )- denominator = _text_line(- "k",- (88.0, 38.0, 92.0, 45.0),- 4,- effective_height=7.0,- font_signature=("Math", 1),- font_coverage=1.0,- )- lane = models._TextLane(- left=0.0,- right=92.0,- lines=[- *((line, line.bbox) for line in body_lines),- (formula_body, formula_body.bbox),- (denominator, denominator.bbox),- ],- )-- assert formulas._find_formula_spatial_anchors(lane, 10.0, body_font) == []---def test_compact_multiline_cluster_becomes_one_isolated_equation() -> None:- """验证可提取的紧凑 F/G 多行簇形成单个公式块且不进入前后正文。"""-- body_font = ("Body", 0)- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- visual_row_id=index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 24.0))- ]- fragments = [- _text_line(- "F = numerator",- (10.0, 36.0, 25.0, 49.0),- 3,- visual_row_id=3,- effective_height=8.0,- font_signature=("Math", 1),- font_coverage=0.5,- ),- _text_line(- "denominator, G =",- (20.0, 39.0, 40.0, 52.0),- 4,- visual_row_id=4,- split_from_row=True,- effective_height=9.5,- font_signature=("Math", 1),- font_coverage=0.4,- ),- _text_line(- "numerator",- (46.0, 36.0, 52.0, 43.0),- 5,- visual_row_id=4,- split_from_row=True,- effective_height=7.0,- font_signature=("Math", 1),- font_coverage=0.5,- ),- _text_line(- "denominator",- (46.0, 39.0, 53.0, 52.0),- 6,- visual_row_id=5,- effective_height=7.0,- font_signature=("Math", 1),- font_coverage=0.33,- ),- ]- following = _text_line(- "following body",- (0.0, 54.0, 100.0, 64.0),- 7,- visual_row_id=6,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )-- merged = line_merging._merge_overlapping_inline_text_clusters(- [*body_lines, *fragments, following],- (120.0, 100.0),- [],- )- compact_cluster = next(line for line in merged if line.source_index == 3)- blocks, remaining = formulas._build_formula_like_blocks(- merged,- [],- (120.0, 100.0),- )-- assert compact_cluster.compact_formula_cluster- assert blocks == [- {- "type": "equation",- "bbox": (10.0, 36.0, 53.0, 52.0),- "angle": 0,- "content": "F = numerator denominator, G = numerator denominator",- }- ]- assert compact_cluster not in remaining--- ("candidate_bbox", "expected_equation_count"),- [- ((5.0, 36.0, 38.0, 46.0), 1),- ((0.0, 36.0, 33.0, 46.0), 0),- ],- ids=["deliberate-indent", "flush-left"],-)-def test_compact_formula_accepts_deliberate_indent_but_rejects_flush_left(- candidate_bbox: tuple[float, float, float, float],- expected_equation_count: int,-) -> None:- """验证正文间紧凑公式可按明确左缩进升级,贴栏短文本仍保留为正文。"""-- body_font = ("Body", 0)- candidate = replace(- _text_line(- "F = dY, G = dX",- candidate_bbox,- 2,- effective_height=10.0,- font_signature=("Math", 1),- font_coverage=0.5,- ),- compact_formula_cluster=True,- )- lines = [- _text_line(- "body above",- (0.0, 20.0, 100.0, 30.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- candidate,- _text_line(- "body below",- (0.0, 52.0, 100.0, 62.0),- 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- blocks, remaining = formulas._build_formula_like_blocks(- lines,- [],- (100.0, 100.0),- )-- assert len(blocks) == expected_equation_count- assert (candidate in remaining) is (expected_equation_count == 0)---def test_hanging_indent_reference_tail_is_not_unnumbered_equation() -> None:- """验证同字体续行后接左突新条目的短尾行不会因偶然居中升级为公式。"""-- body_font = ("Body", 0)- reference_font = ("Reference", 0)- candidate = _text_line(- "short reference tail",- (15.0, 36.0, 85.0, 46.0),- 2,- effective_height=10.0,- font_signature=reference_font,- font_coverage=0.5,- )- lines = [- _text_line(- "body above",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "long reference continuation",- (15.0, 24.0, 95.0, 34.0),- 1,- effective_height=10.0,- font_signature=reference_font,- font_coverage=1.0,- ),- candidate,- _text_line(- "next reference entry",- (0.0, 48.0, 100.0, 58.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body below",- (0.0, 60.0, 100.0, 70.0),- 4,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- blocks, remaining = formulas._build_formula_like_blocks(- lines,- [],- (100.0, 100.0),- )-- assert blocks == []- assert candidate in remaining---def _build_compact_margin_case(- candidate_bbox: tuple[float, float, float, float],- above_bbox: tuple[float, float, float, float],- below_bbox: tuple[float, float, float, float],-) -> tuple[- models._LineItem,- list[dict[str, object]],- list[models._LineItem],-]:- """构造上下都有稳定正文行的紧凑公式页边用例。"""-- body_font = ("Body", 0)- above = _text_line(- "body above",- above_bbox,- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- candidate = replace(- _text_line(- "formula cluster",- candidate_bbox,- 1,- effective_height=10.0,- font_signature=("Math", 1),- font_coverage=0.5,- ),- compact_formula_cluster=True,- )- below = _text_line(- "body below",- below_bbox,- 2,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- blocks, remaining = formulas._build_formula_like_blocks(- [above, candidate, below],- [],- (100.0, 1000.0),- )- return candidate, blocks, remaining---def _build_text_formula_margin_case(- formula_bboxes: tuple[- tuple[float, float, float, float],- tuple[float, float, float, float],- tuple[float, float, float, float],- ],- body_tops: tuple[float, float, float, float],-) -> tuple[list[dict[str, object]], list[models._LineItem]]:- """构造带右缘编号和稳定正文栏带的文本公式页边用例。"""-- body_font = ("Body", 0)- formula_lines = [- _text_line(- "formula numerator",- formula_bboxes[0],- 0,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line(- "formula denominator",- formula_bboxes[1],- 1,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line("(5)", formula_bboxes[2], 2, effective_height=10.0),- ]- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- 3 + index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate(body_tops)- ]- return formulas._build_formula_like_blocks(- [*formula_lines, *body_lines],- [],- (100.0, 1000.0),- )--- ("candidate_bbox", "above_bbox", "below_bbox"),- [- ((25.0, 20.0, 65.0, 30.0), (0.0, 0.0, 100.0, 10.0), (0.0, 40.0, 100.0, 50.0)),- (- (25.0, 970.0, 65.0, 980.0),- (0.0, 940.0, 100.0, 950.0),- (0.0, 990.0, 100.0, 1000.0),- ),- ],- ids=["top", "bottom"],-)-def test_compact_formula_fully_in_page_margin_remains_text(- candidate_bbox: tuple[float, float, float, float],- above_bbox: tuple[float, float, float, float],- below_bbox: tuple[float, float, float, float],-) -> None:- """验证紧凑公式簇整体落入顶部或底部 5% 时不升级为公式。"""-- candidate, blocks, remaining = _build_compact_margin_case(- candidate_bbox,- above_bbox,- below_bbox,- )-- assert blocks == []- assert candidate in remaining---def test_compact_formula_crossing_page_margin_boundary_remains_equation() -> None:- """验证跨过顶部 5% 分界的紧凑真公式仍能输出公式块。"""-- candidate, blocks, remaining = _build_compact_margin_case(- (25.0, 45.0, 65.0, 55.0),- (0.0, 30.0, 100.0, 40.0),- (0.0, 60.0, 100.0, 70.0),- )-- assert blocks == [- {- "type": "equation",- "bbox": candidate.bbox,- "angle": 0,- "content": "formula cluster",- }- ]- assert candidate not in remaining--- ("formula_bboxes", "body_tops"),- [- (- (- (20.0, 8.0, 58.0, 18.0),- (25.0, 19.0, 55.0, 29.0),- (91.0, 17.0, 100.0, 27.0),- ),- (44.0, 56.0, 68.0, 80.0),- ),- (- (- (20.0, 955.0, 58.0, 965.0),- (25.0, 966.0, 55.0, 976.0),- (91.0, 973.0, 100.0, 983.0),- ),- (900.0, 912.0, 924.0, 936.0),- ),- ],- ids=["top", "bottom"],-)-def test_text_formula_fully_in_page_margin_remains_text(- formula_bboxes: tuple[- tuple[float, float, float, float],- tuple[float, float, float, float],- tuple[float, float, float, float],- ],- body_tops: tuple[float, float, float, float],-) -> None:- """验证文本公式空间分量整体落入页边 5% 时不认领原文本行。"""-- blocks, remaining = _build_text_formula_margin_case(- formula_bboxes,- body_tops,- )-- assert blocks == []- assert {line.source_index for line in remaining} == set(range(7))--- ("formula_bboxes", "body_tops", "expected_bbox"),- [- (- (- (20.0, 40.0, 58.0, 50.0),- (25.0, 51.0, 55.0, 61.0),- (91.0, 49.0, 100.0, 59.0),- ),- (76.0, 88.0, 100.0, 112.0),- (20.0, 40.0, 100.0, 61.0),- ),- (- (- (20.0, 940.0, 58.0, 950.0),- (25.0, 951.0, 55.0, 961.0),- (91.0, 958.0, 100.0, 968.0),- ),- (885.0, 897.0, 909.0, 921.0),- (20.0, 940.0, 100.0, 968.0),- ),- ],- ids=["top", "bottom"],-)-def test_text_formula_crossing_page_margin_boundary_remains_equation(- formula_bboxes: tuple[- tuple[float, float, float, float],- tuple[float, float, float, float],- tuple[float, float, float, float],- ],- body_tops: tuple[float, float, float, float],- expected_bbox: tuple[float, float, float, float],-) -> None:- """验证跨过顶部或底部 5% 分界的文本真公式仍能输出。"""-- blocks, remaining = _build_text_formula_margin_case(- formula_bboxes,- body_tops,- )-- assert len(blocks) == 1- assert blocks[0]["type"] == "equation"- assert blocks[0]["bbox"] == expected_bbox- assert {line.source_index for line in remaining} == {3, 4, 5, 6}---def test_justified_mixed_font_visual_row_before_body_is_not_formula_anchor() -> None:- """验证粗体短语与常规字体混排的满栏同行不会因右缘短词误判公式。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 1)- lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- visual_row_id=index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 24.0))- ]- fragments = [- _text_line(- "label",- (0.0, 36.0, 20.0, 46.0),- 10,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=heading_font,- font_coverage=1.0,- ),- _text_line(- "one",- (24.0, 36.0, 38.0, 46.0),- 11,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "two",- (43.0, 36.0, 57.0, 46.0),- 12,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "three",- (63.0, 36.0, 80.0, 46.0),- 13,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "contains",- (86.0, 36.0, 100.0, 46.0),- 14,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]- continuation = _text_line(- "continuation body row",- (0.0, 46.0, 100.0, 56.0),- 15,- visual_row_id=11,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )-- blocks, remaining = formulas._build_formula_like_blocks(- [*lines, *fragments, continuation],- [],- (100.0, 100.0),- )-- assert blocks == []- assert {line.source_index for line in remaining} == {- 0,- 1,- 2,- 10,- 11,- 12,- 13,- 14,- 15,- }---def test_split_visual_row_with_right_number_forms_one_equation() -> None:- """验证多字体同行公式及其右侧编号在栏推断前合成一个公式块。"""-- body_font = ("Body", 0)- math_font = ("Math", 0)- lines = [- _text_line(- "body above",- (0.0, 10.0, 100.0, 20.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "E =",- (20.0, 35.0, 40.0, 45.0),- 1,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=math_font,- font_coverage=0.6,- ),- _text_line(- "mc2",- (42.0, 35.0, 65.0, 45.0),- 2,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=("MathItalic", 0),- font_coverage=0.6,- ),- _text_line(- "(8)",- (90.0, 35.0, 100.0, 45.0),- 3,- visual_row_id=10,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body below",- (0.0, 60.0, 100.0, 70.0),- 4,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- blocks, remaining = formulas._build_formula_like_blocks(- lines,- [],- (100.0, 100.0),- )-- assert len(blocks) == 1- assert blocks[0]["type"] == "equation"- assert blocks[0]["content"].endswith(r"\tag{8}")- assert "(8)" not in blocks[0]["content"]- assert {line.source_index for line in remaining} == {0, 4}---def test_split_visual_row_formula_tail_defers_to_spatial_growth() -> None:- """验证分式尾部同行时延后认领,并由空间锚点收齐完整公式。"""-- body_font = ("Body", 0)- math_font = ("Math", 0)- italic_font = ("MathItalic", 0)- bracket_font = ("Bracket", 0)- lines = [- _text_line(- "body above 1",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body above 2",- (0.0, 12.0, 100.0, 22.0),- 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "formula intro",- (0.0, 36.0, 100.0, 46.0),- 2,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "at = 1",- (10.0, 63.0, 28.0, 73.0),- 3,- effective_height=10.0,- font_signature=italic_font,- font_coverage=0.5,- ),- _text_line(- "2 ln",- (30.0, 67.0, 42.0, 77.0),- 4,- effective_height=10.0,- font_signature=math_font,- font_coverage=1.0,- ),- _text_line(- "( 1 - εt",- (45.0, 52.0, 65.0, 82.0),- 5,- effective_height=10.0,- font_signature=bracket_font,- font_coverage=0.2,- ),- _text_line(- "εt",- (58.0, 72.0, 62.0, 80.0),- 6,- visual_row_id=10,- run_index=0,- split_from_row=True,- effective_height=8.0,- font_signature=italic_font,- font_coverage=0.5,- ),- _text_line(- ")",- (67.0, 52.0, 70.0, 82.0),- 7,- visual_row_id=10,- run_index=1,- split_from_row=True,- effective_height=30.0,- font_signature=bracket_font,- font_coverage=1.0,- ),- _text_line(- "(3)",- (90.0, 67.0, 100.0, 77.0),- 8,- visual_row_id=10,- run_index=2,- split_from_row=True,- effective_height=10.0,- font_signature=body_font,- font_coverage=0.67,- ),- _text_line(- "body below 1",- (0.0, 86.0, 100.0, 96.0),- 9,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body below 2",- (0.0, 98.0, 100.0, 108.0),- 10,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- early_blocks, early_claimed = formulas._build_split_visual_row_formula_blocks(- lines,- [],- (100.0, 120.0),- )- blocks, remaining = formulas._build_formula_like_blocks(- lines,- [],- (100.0, 120.0),- )-- assert early_blocks == []- assert early_claimed == set()- assert blocks == [- {- "type": "equation",- "bbox": (10.0, 52.0, 100.0, 82.0),- "angle": 0,- "content": "at = 1 ( 1 - εt)\n2 ln\nεt\\tag{3}",- }- ]- assert {line.source_index for line in remaining} == {0, 1, 2, 9, 10}---def test_centered_low_body_font_line_forms_unnumbered_equation() -> None:- """验证上下正文之间居中且低正文覆盖的数学字体行形成无编号公式。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body {index}",- (0.0, top, 100.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 14.0, 58.0, 72.0))- ]- lines.append(- _text_line(- "|E(X) - M| < n-1",- (25.0, 36.0, 75.0, 46.0),- 10,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.5,- )- )-- blocks, remaining = formulas._build_formula_like_blocks(- lines,- [],- (100.0, 100.0),- )-- assert len(blocks) == 1- assert blocks[0]["type"] == "equation"- assert blocks[0]["content"] == "|E(X) - M| < n-1"- assert {line.source_index for line in remaining} == {0, 1, 2, 3}---def test_punctuated_number_anchor_protects_stacked_formula_member() -> None:- """验证右侧短标点编号会阻止分式成员被提前识别成无编号公式。"""-- candidate = _text_line(- "fraction numerator",- (20.0, 30.0, 65.0, 40.0),- 1,- effective_height=10.0,- font_signature=("Math", 0),- font_coverage=0.5,- )- number_anchor = _text_line(- ", (4)",- (66.0, 32.0, 78.0, 42.0),- 2,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (candidate, candidate.bbox),- (number_anchor, number_anchor.bbox),- ],- )-- assert formulas._has_nearby_punctuated_formula_number_anchor(- (candidate, candidate.bbox),- lane,- median_height=10.0,- )diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.pydeleted file mode 100644index 3b86a22b..00000000--- a/tests/unittest/test_flash_pdf_graphics.py+++ /dev/null@@ -1,791 +0,0 @@-from __future__ import annotations--import inspect--import pytest---from docvortex.analyzers.native.pdf import graphics-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import pipeline-from docvortex.document.pdf.document import PDFPathInfo---from _flash_pdf_test_utils import (- _text_line,-)---def _drawing_axis_line(- orientation: str,- bbox: tuple[float, float, float, float],-) -> models._AxisLine:- """构造图形容器测试使用的 PDF 绘图线。"""-- return models._AxisLine(- bbox=bbox,- width=0.5,- orientation=orientation, # type: ignore[arg-type]- )---def _path_info(- bbox: tuple[float, float, float, float],- source_index: int,- *,- segment_count: int = 5,- fill_visible: bool = True,- stroke_visible: bool = False,- form_depth: int = 0,-) -> PDFPathInfo:- """构造强图形核心测试使用的根层 PDF Path。"""-- return PDFPathInfo(- bbox=bbox,- segment_count=segment_count,- fill_visible=fill_visible,- stroke_visible=stroke_visible,- form_depth=form_depth,- source_index=source_index,- )---def test_vertical_raster_tiles_merge_before_area_filter() -> None:- """验证同宽纵向切片先合并成完整图片,再应用单图面积门槛。"""-- tiles = [(20.0, float(top), 180.0, float(top + 4)) for top in range(20, 60, 4)]-- assert graphics._merge_vertical_raster_tiles(- tiles,- (200.0, 200.0),- ) == [(20.0, 20.0, 180.0, 60.0)]---def test_full_page_raster_tiles_stay_separate() -> None:- """验证整页扫描图切片不合成单个容器,保留既有逐片输出。"""-- tiles = [(0.0, float(top), 200.0, float(top + 10)) for top in range(0, 200, 10)]-- assert (- graphics._merge_vertical_raster_tiles(- tiles,- (200.0, 200.0),- )- == tiles- )---def _parallel_rule_split_fixture(- *,- cross_gutter: bool = False,-) -> tuple[- models._LineItem,- list[models._AxisLine],- list[tuple[float, float, float, float]],-]:- """构造无语义文本、成对图形、独立横线和可选栏沟干扰字符。"""-- left_chars = [- {- "char": "L",- "bbox": (- 100.0 + 40.0 * index,- 80.0,- 120.0 + 40.0 * index,- 89.0,- ),- }- for index in range(8)- ]- if cross_gutter:- left_chars[-1]["bbox"] = (475.0, 80.0, 505.0, 89.0)- right_chars = [- {- "char": "R",- "bbox": (- 540.0 + 40.0 * index,- 80.0,- 560.0 + 40.0 * index,- 89.0,- ),- }- for index in range(8)- ]- line = _text_line(- "LLLLLLLL RRRRRRRR",- (100.0, 80.0, 840.0, 89.0),- 7,- visual_row_id=12,- effective_height=10.0,- )- line.chars = [*left_chars, {"char": " ", "bbox": (400.0, 80.0, 540.0, 89.0)}, *right_chars]- rules = [- _drawing_axis_line("horizontal", (80.0, 90.0, 480.0, 90.5)),- _drawing_axis_line("horizontal", (520.0, 90.0, 920.0, 90.5)),- ]- images = [- (100.0, 100.0, 470.0, 300.0),- (530.0, 100.0, 900.0, 300.0),- ]- return line, rules, images---def test_parallel_graphic_rule_rows_split_without_reading_text_content() -> None:- """验证完整空间证据把同一视觉行拆成左右两个受保护 run。"""-- line, rules, images = _parallel_rule_split_fixture()-- split = graphics._split_parallel_graphic_rule_rows(- [line],- rules,- images,- [],- (1000.0, 500.0),- source_index_start=50,- )-- assert [(item.text, item.bbox) for item in split] == [- ("LLLLLLLL", (100.0, 80.0, 400.0, 89.0)),- ("RRRRRRRR", (540.0, 80.0, 840.0, 89.0)),- ]- assert [item.source_index for item in split] == [7, 50]- assert [item.run_index for item in split] == [0, 1]- assert {item.visual_row_id for item in split} == {12}- assert all(item.split_from_row for item in split)- assert all(item.preserve_split_boundary for item in split)-- source = "\n".join(- inspect.getsource(function)- for function in (- graphics._parallel_graphic_rule_pairs,- graphics._parallel_graphic_row_split_boundary,- graphics._split_parallel_graphic_rule_rows,- )- )- assert ".text" not in source--- "missing_evidence",- ["right_rule", "right_image", "independent_rules", "clear_gutter", "outside_table"],-)-def test_parallel_graphic_rule_rows_require_all_spatial_evidence(- missing_evidence: str,-) -> None:- """验证横线、图形、栏沟或表格排除任一不成立时都不拆分。"""-- line, rules, images = _parallel_rule_split_fixture(cross_gutter=missing_evidence == "clear_gutter")- table_bboxes: list[tuple[float, float, float, float]] = []- if missing_evidence == "right_rule":- rules = rules[:1]- elif missing_evidence == "right_image":- images = images[:1]- elif missing_evidence == "independent_rules":- rules = [_drawing_axis_line("horizontal", (80.0, 90.0, 920.0, 90.5))]- elif missing_evidence == "outside_table":- table_bboxes = [(70.0, 70.0, 930.0, 310.0)]-- output = graphics._split_parallel_graphic_rule_rows(- [line],- rules,- images,- table_bboxes,- (1000.0, 500.0),- )-- assert output == [line]---def _graphic_source_fixture() -> models._PageSource:- """构造双框图形、六个标签、拆分 caption 与邻近正文。"""-- lines = [- _text_line("p = (x, y)", (378.0, 302.0, 421.0, 312.0), 0, visual_row_id=10),- _text_line("pbar = (xbar, y)", (445.0, 302.0, 488.0, 312.0), 1, visual_row_id=10),- _text_line("dp", (382.0, 282.0, 403.0, 292.0), 2, visual_row_id=11),- _text_line("x", (468.0, 282.0, 475.0, 292.0), 3, visual_row_id=11),- _text_line("Left camera", (360.0, 339.0, 411.0, 350.0), 4, visual_row_id=12),- _text_line("Right camera", (458.0, 339.0, 509.0, 350.0), 5, visual_row_id=12),- _text_line(- "Figure 1: a deliberately long caption that must remain",- (312.0, 359.0, 500.0, 371.0),- 6,- visual_row_id=20,- split_from_row=True,- ),- _text_line(- "independent.",- (510.0, 359.0, 563.0, 371.0),- 7,- visual_row_id=20,- split_from_row=True,- ),- _text_line("Nearby prose", (370.0, 225.0, 430.0, 237.0), 8, visual_row_id=9),- ]- drawing_lines = [- _drawing_axis_line("horizontal", (348.0, 272.0, 430.0, 272.5)),- _drawing_axis_line("horizontal", (348.0, 331.5, 430.0, 332.0)),- _drawing_axis_line("vertical", (348.0, 272.0, 348.5, 332.0)),- _drawing_axis_line("vertical", (429.5, 272.0, 430.0, 332.0)),- _drawing_axis_line("horizontal", (436.0, 272.0, 526.0, 272.5)),- _drawing_axis_line("horizontal", (436.0, 331.5, 526.0, 332.0)),- _drawing_axis_line("vertical", (436.0, 272.0, 436.5, 332.0)),- _drawing_axis_line("vertical", (525.5, 272.0, 526.0, 332.0)),- ]- return models._PageSource(- page_size=(612.0, 792.0),- lines=lines,- chars=[],- drawing_lines=drawing_lines,- )---def test_double_box_graphic_claims_six_labels_but_not_caption_or_body() -> None:- """验证双框图形整行聚合六个标签,拆分 caption 和邻近正文均不被部分认领。"""-- blocks, claimed = graphics._build_graphic_like_blocks(- _graphic_source_fixture(),- [],- set(),- )-- assert len(blocks) == 1- assert claimed == set(range(6))- assert blocks[0]["type"] == "image"- for expected_text in ("dp", "x", "p = (x, y)", "pbar = (xbar, y)", "Left camera", "Right camera"):- assert expected_text in blocks[0]["content"]- assert blocks[0]["content"].count("Left camera") == 1- assert blocks[0]["content"].count("Right camera") == 1- assert "Figure 1" not in blocks[0]["content"]- assert "Nearby prose" not in blocks[0]["content"]---def test_graphic_label_accepts_only_near_diagonal_corner_text() -> None:- """验证无轴向重叠的短标签仅在严格角部距离内归入图形。"""-- core_bbox = (20.0, 20.0, 80.0, 80.0)- near_corner = _text_line("unit", (5.0, 5.0, 15.0, 15.0), 0)- distant_corner = _text_line("unit", (-5.0, -5.0, 5.0, 5.0), 1)- long_title = _text_line(- "deliberately wide title",- (0.0, 5.0, 80.0, 15.0),- 2,- )-- assert graphics._is_graphic_label_member(- near_corner,- core_bbox,- 10.0,- )- assert not graphics._is_graphic_label_member(- distant_corner,- core_bbox,- 10.0,- )- assert not graphics._is_graphic_label_member(- long_title,- core_bbox,- 10.0,- )---def test_materialized_table_bbox_has_priority_over_graphic_candidate() -> None:- """验证绘图组件与成功表格框重叠时跳过图形容器并保留全部文本身份。"""-- blocks, claimed = graphics._build_graphic_like_blocks(- _graphic_source_fixture(),- [(340.0, 265.0, 535.0, 355.0)],- set(),- )-- assert blocks == []- assert claimed == set()---def test_complex_path_container_builds_graphic_without_drawing_lines() -> None:- """验证大 Path 容器和内部二维复杂轮廓可直接形成图形核心。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("10", (15.0, 20.0, 25.0, 25.0), 0, visual_row_id=1),- _text_line("label", (30.0, 55.0, 50.0, 60.0), 1, visual_row_id=2),- ],- chars=[],- drawing_lines=[],- path_infos=[- _path_info((10.0, 10.0, 90.0, 70.0), 0),- _path_info((20.0, 20.0, 75.0, 50.0), 1, segment_count=12),- _path_info((25.0, 25.0, 35.0, 35.0), 2),- _path_info((40.0, 25.0, 50.0, 40.0), 3),- _path_info((55.0, 20.0, 65.0, 45.0), 4),- ],- )-- core_bboxes = graphics._detect_strong_graphic_bboxes(source)- blocks, claimed = graphics._build_graphic_like_blocks(- source,- [],- set(),- core_bboxes,- )-- assert core_bboxes == [(10.0, 10.0, 90.0, 70.0)]- assert claimed == {0, 1}- assert blocks[0]["bbox"] == (10.0, 10.0, 90.0, 70.0)- assert blocks[0]["content"] == "10\nlabel"---def test_strong_graphic_core_binds_only_to_unique_containing_lane() -> None:- """验证单栏强图形不会吸收邻栏文本,而真正跨栏核心仍保持跨栏。"""-- lanes = [- models._TextLane(left=50.0, right=290.0),- models._TextLane(left=305.0, right=545.0),- ]-- assert (- graphics._strong_graphic_lane_index(- (73.0, 516.0, 281.0, 655.0),- lanes,- 10.0,- )- == 0- )- assert (- graphics._strong_graphic_lane_index(- (73.0, 516.0, 520.0, 655.0),- lanes,- 10.0,- )- == -1- )---def test_axis_pair_requires_internal_two_dimensional_complex_path() -> None:- """验证相交坐标轴须有二维复杂曲线支撑,规则矩形行带不会误报图形。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("0", (12.0, 65.0, 17.0, 70.0), 0),- _text_line("x", (78.0, 72.0, 83.0, 77.0), 1),- ],- chars=[],- drawing_lines=[],- path_infos=[- _path_info((20.0, 20.0, 21.0, 70.0), 0, segment_count=2, fill_visible=False, stroke_visible=True),- _path_info((20.0, 69.0, 80.0, 70.0), 1, segment_count=2, fill_visible=False, stroke_visible=True),- _path_info((25.0, 30.0, 75.0, 60.0), 2, segment_count=12, fill_visible=False, stroke_visible=True),- ],- )-- assert graphics._detect_strong_graphic_bboxes(source) == [(20.0, 20.0, 80.0, 70.0)]-- source.path_infos[2] = _path_info(- (25.0, 30.0, 75.0, 31.0),- 2,- segment_count=12,- fill_visible=False,- stroke_visible=True,- )- assert graphics._detect_strong_graphic_bboxes(source) == []---def test_form_image_claims_internal_text_and_small_table_but_not_caption() -> None:- """验证有效 Form 吞并图内文字与小表候选,外部 caption 仍保留。"""-- form_bbox = (10.0, 10.0, 90.0, 65.0)- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside row one", (15.0, 20.0, 70.0, 30.0), 0, visual_row_id=1),- _text_line("inside row two", (15.0, 35.0, 80.0, 45.0), 1, visual_row_id=2),- _text_line("Figure 1: outside", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[- _drawing_axis_line("horizontal", (20.0, 15.0, 80.0, 15.5)),- _drawing_axis_line("horizontal", (20.0, 55.0, 80.0, 55.5)),- _drawing_axis_line("vertical", (20.0, 15.0, 20.5, 55.0)),- _drawing_axis_line("vertical", (79.5, 15.0, 80.0, 55.0)),- ],- form_bboxes=[form_bbox],- )-- selected = graphics._select_form_image_bboxes(source)- blocks, claimed = graphics._build_form_image_blocks(source, selected, set())-- assert selected == [form_bbox]- assert graphics._form_supersedes_nested_bbox(- form_bbox,- (20.0, 20.0, 40.0, 35.0),- )- assert not graphics._form_supersedes_nested_bbox(- form_bbox,- (15.0, 15.0, 85.0, 60.0),- )- assert claimed == {0, 1}- assert blocks == [- {- "type": "image",- "bbox": form_bbox,- "angle": 0,- "content": "inside row one\ninside row two",- }- ]---def test_form_image_bbox_tightens_to_supported_internal_evidence() -> None:- """验证含充分嵌套 Path 的 Form 去除空白边缘,文本轻微越界仍纳入证据并裁到页面。"""-- source = models._PageSource(- page_size=(120.0, 120.0),- lines=[- _text_line("top label", (20.0, 25.0, 70.0, 34.0), 0),- _text_line("bottom label", (25.0, 68.0, 80.0, 81.0), 1),- ],- chars=[],- drawing_lines=[- _drawing_axis_line("horizontal", (20.0, 25.0, 85.0, 25.5)),- _drawing_axis_line("horizontal", (20.0, 75.0, 85.0, 75.5)),- _drawing_axis_line("vertical", (20.0, 25.0, 20.5, 75.0)),- _drawing_axis_line("vertical", (84.5, 25.0, 85.0, 75.0)),- ],- form_bboxes=[(10.0, 10.0, 100.0, 80.0)],- path_infos=[- _path_info((20.0, 25.0, 80.0, 70.0), 0, form_depth=1),- _path_info((25.0, 30.0, 85.0, 75.0), 1, form_depth=1),- ],- )-- assert graphics._select_form_image_bboxes(source) == [(20.0, 25.0, 85.0, 81.0)]---def test_graphic_label_absorbs_short_axis_title_but_rejects_long_caption() -> None:- """验证上下坐标轴标题可放宽到八倍行高,长图注仍被图形容器拒绝。"""-- core_bbox = (20.0, 30.0, 140.0, 80.0)- top_axis_title = _text_line(- "axis title",- (20.0, 17.0, 70.0, 25.0),- 0,- effective_height=8.0,- )- bottom_axis_title = _text_line(- "axis title",- (80.0, 85.0, 115.0, 91.0),- 1,- effective_height=6.0,- )- long_caption = _text_line(- "a deliberately long figure caption",- (20.0, 85.0, 140.0, 93.0),- 2,- effective_height=8.0,- )-- assert graphics._is_graphic_label_member(- top_axis_title,- core_bbox,- 8.0,- margin_scale=1.0,- )- assert graphics._is_graphic_label_member(- bottom_axis_title,- core_bbox,- 8.0,- margin_scale=1.0,- )- assert not graphics._is_graphic_label_member(- long_caption,- core_bbox,- 8.0,- margin_scale=1.0,- )---def _inline_raster_sequence_source() -> models._PageSource:- """构造四张点阵图、三个同行间隔符及其右侧三行正文。"""-- return models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line(- "、",- (20.0, 22.0, 22.0, 25.0),- 0,- visual_row_id=7,- run_index=0,- split_from_row=True,- ),- _text_line(- "、",- (32.0, 22.0, 34.0, 25.0),- 1,- visual_row_id=7,- run_index=1,- split_from_row=True,- ),- _text_line(- "、",- (48.0, 22.0, 50.0, 25.0),- 2,- visual_row_id=7,- run_index=2,- split_from_row=True,- ),- _text_line(- "尾随文字",- (60.0, 22.0, 90.0, 25.0),- 3,- visual_row_id=7,- run_index=3,- split_from_row=True,- ),- _text_line("正文第一行", (10.0, 27.0, 90.0, 30.0), 4, visual_row_id=8),- _text_line("正文第二行", (10.0, 32.0, 50.0, 35.0), 5, visual_row_id=9),- ],- chars=[],- drawing_lines=[],- image_bboxes=[- (10.0, 20.0, 20.0, 24.0),- (22.0, 20.0, 32.0, 24.0),- (34.0, 20.0, 48.0, 24.0),- (50.0, 20.0, 60.0, 24.0),- ],- )---def test_raster_image_threshold_accepts_point_38_percent_only() -> None:- """验证页面面积达到 0.38% 时准入,略低于阈值的孤立图片仍过滤。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[],- chars=[],- drawing_lines=[],- image_bboxes=[- (0.0, 0.0, 9.5, 4.0),- (20.0, 0.0, 29.49, 4.0),- ],- )-- blocks, claimed = graphics._build_raster_image_blocks(source, [], set())-- assert [block["bbox"] for block in blocks] == [(0.0, 0.0, 9.5, 4.0)]- assert claimed == set()---def test_signature_images_bypass_raster_threshold_and_deduplicate_same_geometry() -> None:- """验证小签名仍输出,且签名间及签名与点阵图的同框候选只保留一次。"""-- source = models._PageSource(- page_size=(1000.0, 1000.0),- lines=[],- chars=[],- drawing_lines=[],- image_bboxes=[(100.0, 100.0, 200.0, 200.0)],- signature_bboxes=[- (10.0, 10.0, 30.0, 30.0),- (10.2, 10.1, 30.1, 30.2),- (100.0, 100.0, 200.0, 200.0),- ],- )-- blocks, claimed = graphics._build_raster_image_blocks(source, [], set())-- assert [block["bbox"] for block in blocks] == [- (10.0, 10.0, 30.0, 30.0),- (100.0, 100.0, 200.0, 200.0),- ]- assert claimed == set()---def test_inline_raster_images_and_gap_runs_form_one_composite_image() -> None:- """验证四张已准入图片与三个同行间隔符合成一个复合 image。"""-- source = _inline_raster_sequence_source()-- blocks, claimed = graphics._build_raster_image_blocks(source, [], set())-- assert len(blocks) == 1- assert blocks[0]["bbox"] == (10.0, 20.0, 60.0, 25.0)- assert blocks[0]["content"].replace(" ", "") == "、、、"- assert blocks[0]["_inline_visual_row_id"] == 7- assert claimed == {0, 1, 2}- assert 3 not in claimed--- "failure_mode",- [- "misaligned",- "wide_gap",- "missing_gap",- "inconsistent_row",- "too_few_images",- "container_bridge",- ],-)-def test_inline_raster_composite_requires_complete_spatial_sequence(- failure_mode: str,-) -> None:- """验证图片或间隔符结构不完整时保留独立图片而不生成复合容器。"""-- source = _inline_raster_sequence_source()- container_blocks: list[dict[str, object]] = []- if failure_mode == "misaligned":- source.image_bboxes[1] = (22.0, 10.0, 32.0, 14.0)- elif failure_mode == "wide_gap":- source.image_bboxes[2] = (42.0, 20.0, 56.0, 24.0)- source.image_bboxes[3] = (58.0, 20.0, 68.0, 24.0)- source.lines[2].bbox = (56.0, 22.0, 58.0, 25.0)- elif failure_mode == "missing_gap":- source.lines = [line for line in source.lines if line.source_index != 1]- elif failure_mode == "inconsistent_row":- source.lines[1].visual_row_id = 8- elif failure_mode == "too_few_images":- source.image_bboxes = source.image_bboxes[:2]- else:- container_blocks = [- {- "type": "table",- "bbox": (32.5, 20.0, 33.5, 25.0),- "angle": 0,- "content": "",- }- ]-- blocks, claimed = graphics._build_raster_image_blocks(- source,- container_blocks,- set(),- )-- assert len(blocks) == len(source.image_bboxes)- assert not [block for block in blocks if "_inline_visual_row_id" in block]- assert claimed == set()---def test_inline_composite_sorts_before_overlapping_multiline_text() -> None:- """验证复合图片与含同行首行的多行正文绑定后始终先输出图片。"""-- blocks = [- {- "type": "image",- "bbox": (10.0, 20.0, 60.0, 25.0),- "angle": 0,- "content": "、、、",- "_inline_visual_row_id": 7,- },- {- "type": "text",- "bbox": (10.0, 22.0, 90.0, 35.0),- "angle": 0,- "content": "尾随文字正文第一行正文第二行",- "_visual_row_ids": {7, 8, 9},- "_local_line_bboxes": [- (60.0, 22.0, 90.0, 25.0),- (10.0, 27.0, 90.0, 30.0),- (10.0, 32.0, 50.0, 35.0),- ],- },- {- "type": "paragraph_title",- "bbox": (10.0, 40.0, 30.0, 44.0),- "angle": 0,- "content": "下一节",- },- ]-- sorted_blocks = pipeline._sort_blocks_with_visual_row_groups(- blocks,- (100.0, 100.0),- )-- assert [block["type"] for block in sorted_blocks] == [- "image",- "text",- "paragraph_title",- ]---def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once() -> None:- """验证点阵图过滤、容器优先、空 content 和重叠对象的唯一文本归属。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside", (25.0, 25.0, 35.0, 35.0), 0, visual_row_id=1),- _text_line("outside caption", (10.0, 52.0, 50.0, 60.0), 1, visual_row_id=2),- _text_line("covered container text", (20.0, 70.0, 40.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[],- image_bboxes=[- (10.0, 10.0, 50.0, 50.0),- (20.0, 20.0, 40.0, 40.0),- (60.0, 10.0, 90.0, 40.0),- (0.0, 90.0, 9.0, 94.0),- (10.0, 60.0, 50.0, 90.0),- ],- )-- blocks, claimed = graphics._build_raster_image_blocks(- source,- [{"type": "table", "bbox": (10.0, 60.0, 50.0, 90.0), "angle": 0, "content": "table"}],- set(),- )-- assert len(blocks) == 3- assert all(block["type"] == "image" and block["angle"] == 0 for block in blocks)- assert [block["bbox"] for block in blocks] == [- (10.0, 10.0, 50.0, 50.0),- (60.0, 10.0, 90.0, 40.0),- (20.0, 20.0, 40.0, 40.0),- ]- assert [block["content"] for block in blocks] == ["", "", "inside"]- assert claimed == {0}---def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept() -> None:- """验证图内文本只进入 image,独立 caption 正确标记,纯图片页仍输出空 content。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside row one", (20.0, 20.0, 50.0, 30.0), 0, visual_row_id=1),- _text_line("inside row two", (20.0, 35.0, 50.0, 45.0), 1, visual_row_id=2),- _text_line("Figure 1: outside caption", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[],- image_bboxes=[(10.0, 10.0, 60.0, 60.0)],- )-- blocks = pipeline._analyze_page_source(source)- image_block = next(block for block in blocks if block["type"] == "image")- caption_block = next(block for block in blocks if block["type"] == "caption")-- assert image_block["content"] == "inside row one\ninside row two"- assert caption_block["content"] == "Figure 1: outside caption"- assert sum("inside row" in block["content"] for block in blocks) == 1-- empty_page_blocks = pipeline._analyze_page_source(- models._PageSource(- page_size=(100.0, 100.0),- lines=[],- chars=[],- drawing_lines=[],- image_bboxes=[(10.0, 10.0, 60.0, 60.0)],- )- )- assert empty_page_blocks == [- {- "type": "image",- "bbox": [0.1, 0.1, 0.6, 0.6],- "angle": 0,- "content": "",- }- ]diff --git a/tests/unittest/test_flash_pdf_index_blocks.py b/tests/unittest/test_flash_pdf_index_blocks.pydeleted file mode 100644index 90ad9db8..00000000--- a/tests/unittest/test_flash_pdf_index_blocks.py+++ /dev/null@@ -1,160 +0,0 @@-from __future__ import annotations--import pytest--from docvortex.analyzers.native.pdf import index_blocks--from _flash_pdf_test_utils import _text_line---def _directory_lines(- numeric_rows: set[int],- *,- row_count: int = 10,-) -> list[index_blocks._LineItem]:- """构造带居中标题、宽目录条目和右侧页码片段的视觉行。"""-- lines = [- _text_line(- "centered heading",- (40.0, 5.0, 60.0, 15.0),- 100,- visual_row_id=100,- )- ]- for row_index in range(row_count):- top = 30.0 + 12.0 * row_index- lines.extend(- [- _text_line(- f"entry {row_index} . . . .",- (10.0, top, 80.0, top + 10.0),- row_index * 2,- visual_row_id=row_index,- run_index=0,- split_from_row=True,- ),- _text_line(- str(row_index + 1) if row_index in numeric_rows else "continuation",- (92.0, top, 96.0, top + 10.0),- row_index * 2 + 1,- visual_row_id=row_index,- run_index=1,- split_from_row=True,- ),- ]- )- return lines--- "content",- [- "entry 12",- "entry 12",- "entry xiv",- "entry IV。",- "entry 9 )",- ],-)-def test_index_page_number_suffix_supports_expected_forms(content: str) -> None:- """验证目录行尾支持半角、全角、罗马页码及有限尾随标点。"""-- assert index_blocks._index_row_ends_in_page_number(content)--[email protected]("content", ["entry", "version A12x", "word LIVE"])-def test_index_page_number_suffix_rejects_non_page_number_tail(content: str) -> None:- """验证普通词尾和字母数字混合标识不会被当作目录页码。"""-- assert not index_blocks._index_row_ends_in_page_number(content)---def test_index_block_merges_split_rows_and_preserves_heading() -> None:- """验证目录正文合成一个换行块,居中目录标题保持段落标题。"""-- lines = _directory_lines(set(range(6)), row_count=6)-- blocks, remaining = index_blocks._extract_index_blocks(- lines,- (100.0, 130.0),- [],- )-- assert len(blocks) == 1- assert blocks[0]["type"] == "index"- assert blocks[0]["content"] == "\n".join(f"entry {row_index} . . . . {row_index + 1}" for row_index in range(6))- assert not str(blocks[0]["content"]).endswith("\n")- assert [line.text for line in remaining] == ["centered heading"]- assert remaining[0].semantic_type == "paragraph_title"- assert all(line.semantic_type == "index" for line in lines if line is not remaining[0])---def test_index_prepass_requires_geometric_heading_but_fallback_keeps_legacy_detection() -> None:- """验证公式前目录预判拒绝无标题编号行,公式后的兼容识别仍可处理无标题目录。"""-- lines = _directory_lines(set(range(6)), row_count=6)[1:]-- prepass_blocks, prepass_remaining = index_blocks._extract_index_blocks(- lines,- (100.0, 130.0),- [],- require_heading=True,- )- fallback_blocks, fallback_remaining = index_blocks._extract_index_blocks(- lines,- (100.0, 130.0),- [],- )-- assert prepass_blocks == []- assert prepass_remaining == lines- assert len(fallback_blocks) == 1- assert fallback_remaining == []--- ("numeric_rows", "expected_block_count"),- [- ({0, 1, 2, 4, 6, 8, 9}, 1),- ({0, 1, 2, 4, 6, 9}, 0),- ],-)-def test_index_block_requires_seventy_percent_numeric_rows(- numeric_rows: set[int],- expected_block_count: int,-) -> None:- """验证目录候选在 70% 页码行尾阈值处命中,低于阈值则拒绝。"""-- lines = _directory_lines(numeric_rows)-- blocks, _remaining = index_blocks._extract_index_blocks(- lines,- (100.0, 160.0),- [],- )-- assert len(blocks) == expected_block_count---def test_numeric_lines_without_directory_width_or_sidecars_are_rejected() -> None:- """验证仅有大量数字行尾而缺少宽行及页码侧栏时不会误判目录。"""-- lines = [- _text_line(- f"value {row_index}",- (50.0, 10.0 + 12.0 * row_index, 90.0, 20.0 + 12.0 * row_index),- row_index,- visual_row_id=row_index,- )- for row_index in range(8)- ]-- blocks, remaining = index_blocks._extract_index_blocks(- lines,- (100.0, 120.0),- [],- )-- assert blocks == []- assert remaining == linesdiff --git a/tests/unittest/test_flash_pdf_line_metadata.py b/tests/unittest/test_flash_pdf_line_metadata.pydeleted file mode 100644index 0d12c892..00000000--- a/tests/unittest/test_flash_pdf_line_metadata.py+++ /dev/null@@ -1,165 +0,0 @@-from __future__ import annotations--import pytest--from docvortex.analyzers.native.pdf import line_layout-from docvortex.analyzers.native.pdf import pipeline-from docvortex.analyzers.native.pdf import text_blocks--from _flash_pdf_test_utils import _text_line---def test_line_tight_output_bbox_adds_one_point_padding_and_clips_page() -> None:- """验证可靠 tight 字形框四边各扩 1pt,并在页面边缘安全裁剪。"""-- line = _text_line(- "value",- (0.0, 0.0, 80.0, 40.0),- 0,- ink_bbox=(0.5, 0.25, 40.0, 20.0),- )-- assert line_layout._line_tight_output_bbox(- line,- (100.0, 100.0),- ) == (0.0, 0.0, 41.0, 21.0)---def test_text_block_applies_tight_output_bbox_after_aggregation() -> None:- """验证文本先按 layout 聚合,再同步应用 tight+1pt 的 block 与 line bbox。"""-- line = _text_line(- "value",- (10.0, 20.0, 90.0, 80.0),- 0,- ink_bbox=(20.0, 30.0, 40.0, 50.0),- )- blocks = text_blocks._build_text_blocks(- [line],- [],- (100.0, 100.0),- )-- assert len(blocks) == 1- assert blocks[0]["bbox"] == (10.0, 20.0, 90.0, 80.0)- pipeline._apply_post_aggregation_tight_bboxes(- blocks,- (100.0, 100.0),- )-- assert blocks[0]["bbox"] == (19.0, 29.0, 41.0, 51.0)- assert blocks[0]["_local_line_bboxes"] == [- (19.0, 29.0, 41.0, 51.0),- ]---def test_direct_formula_tight_bbox_is_applied_and_internal_key_removed() -> None:- """验证文本公式的聚合后候选替换公开框,且内部字段不会继续外泄。"""-- blocks = [- {- "type": "equation",- "bbox": (10.0, 20.0, 90.0, 80.0),- "angle": 0,- "content": "x=1",- "_tight_output_bbox": (19.0, 29.0, 41.0, 51.0),- }- ]-- pipeline._apply_post_aggregation_tight_bboxes(- blocks,- (100.0, 100.0),- )-- assert blocks[0]["bbox"] == (19.0, 29.0, 41.0, 51.0)- assert "_tight_output_bbox" not in blocks[0]--- "block_type",- ["text", "ref_text", "doc_title", "paragraph_title", "caption", "footnote"],-)-def test_output_normalization_exposes_lines_for_pdf_text_types(- block_type: str,-) -> None:- """验证 Flash 对包括 ref_text 在内的 PDF 文本块公开归一化行框。"""-- block = pipeline._normalize_output_block(- {- "type": block_type,- "bbox": (10.0, 20.0, 90.0, 80.0),- "angle": 0,- "content": "line one\nline two",- "_local_line_bboxes": [- (10.0, 20.0, 90.0, 40.0),- (20.0, 50.0, 80.0, 80.0),- ],- },- (100.0, 200.0),- )-- assert block is not None- assert block["lines"] == [- {"bbox": [0.1, 0.1, 0.9, 0.2]},- {"bbox": [0.2, 0.25, 0.8, 0.4]},- ]--- ("angle", "expected_bbox"),- [- (0, [0.2, 0.05, 0.4, 0.15]),- (90, [0.7, 0.1, 0.9, 0.2]),- (270, [0.1, 0.8, 0.3, 0.9]),- ],-)-def test_output_normalization_restores_rotated_line_bbox_to_page(- angle: int,- expected_bbox: list[float],-) -> None:- """验证局部行框会按 block 方向逆变换到原页面坐标。"""-- block = pipeline._normalize_output_block(- {- "type": "text",- "bbox": (10.0, 10.0, 90.0, 190.0),- "angle": angle,- "content": "value",- "_local_line_bboxes": [(20.0, 10.0, 40.0, 30.0)],- },- (100.0, 200.0),- )-- assert block is not None- assert block["lines"] == [{"bbox": expected_bbox}]--[email protected]("block_type", ["text", "ref_text"])- "local_line_bboxes",- [- None,- [],- [(10.0, 20.0, 40.0, 30.0), (1.0, 2.0, 1.0, 3.0)],- [(40.0, 20.0, 10.0, 30.0)],- ],-)-def test_output_normalization_fails_closed_for_invalid_line_bboxes(- block_type: str,- local_line_bboxes: object,-) -> None:- """验证 text/ref_text 内部行框缺失、为空或任一非法时输出空 lines。"""-- block = pipeline._normalize_output_block(- {- "type": block_type,- "bbox": (10.0, 20.0, 40.0, 50.0),- "angle": 0,- "content": "value",- "_local_line_bboxes": local_line_bboxes,- },- (100.0, 100.0),- )-- assert block is not None- assert block["lines"] == []diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.pydeleted file mode 100644index 9c1cde4f..00000000--- a/tests/unittest/test_flash_pdf_native_text.py+++ /dev/null@@ -1,392 +0,0 @@-from __future__ import annotations--import math-from typing import Any--import pytest--from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import native_text---def _span(- text: str,- bbox: tuple[float, float, float, float],- angle_degrees: float,- *,- chars: list[dict[str, Any]] | None = None,-) -> dict[str, Any]:- """构造只包含方向、文本和 bbox 的最小 pdftext span。"""-- return {- "text": text,- "bbox": bbox,- "rotation": math.radians(angle_degrees),- "chars": chars or [],- }---def _char(- value: str,- bbox: tuple[float, float, float, float],-) -> dict[str, Any]:- """构造字符基线方向测试使用的最小 pdftext 字符。"""-- return {"char": value, "bbox": bbox}---def _line(- spans: list[dict[str, Any]],- angle_degrees: float,- bbox: tuple[float, float, float, float] = (0.0, 0.0, 100.0, 100.0),-) -> dict[str, Any]:- """构造测试混合方向拆分使用的最小 pdftext line。"""-- return {- "spans": spans,- "bbox": bbox,- "rotation": math.radians(angle_degrees),- }---def test_inline_script_scale_cache_is_linear_and_local_to_each_pass(monkeypatch: pytest.MonkeyPatch) -> None:- """每轮字号计算随行数线性增长,后续轮次重新读取已变化的字符字号。"""-- lines = [- models._LineItem(- text="body",- bbox=(10.0, index * 30.0, 30.0, index * 30.0 + 10.0),- angle=0,- source_index=index,- visual_row_id=index,- effective_height=10.0,- chars=[{"char": "a", "font": {"size": 10.0}}],- )- for index in range(20)- ]- observed: list[float] = []- original = native_text._native_typographic_scale-- def record_scale(line: models._LineItem) -> float:- """记录真实字号计算,验证缓存不跨越行变更边界。"""-- value = original(line)- observed.append(value)- return value-- monkeypatch.setattr(native_text, "_native_typographic_scale", record_scale)- native_text._merge_native_inline_scripts(lines, (100.0, 700.0))- assert observed == [10.0] * 20- lines[0].chars[0]["font"]["size"] = 12.0- observed.clear()- native_text._merge_native_inline_scripts(lines, (100.0, 700.0))- assert observed == [12.0, *([10.0] * 19)]---def test_private_use_decorative_rule_becomes_axis_line() -> None:- """验证页首宽幅私用区重复字形不再进入文本输出。"""-- decorative = models._LineItem(- text="\ue123" * 24,- bbox=(10.0, 12.0, 190.0, 16.0),- angle=0,- source_index=0,- )- body = models._LineItem(- text="body",- bbox=(10.0, 40.0, 80.0, 50.0),- angle=0,- source_index=1,- )-- retained, rules = native_text._extract_decorative_text_rules(- [decorative, body],- (200.0, 200.0),- )-- assert retained == [body]- assert [(rule.orientation, rule.bbox) for rule in rules] == [("horizontal", decorative.bbox)]---def test_mixed_footer_and_315_degree_watermark_are_split_before_filtering() -> None:- """验证接近 315 度的 span 不会继续借用父行 0 度方向与巨型 bbox。"""-- pdf_line = _line(- [- _span("文档问题反馈: [email protected]", (30.0, 90.0, 80.0, 98.0), 0.0),- _span("通用测试文档", (5.0, 10.0, 25.0, 95.0), 315.000019),- _span("\r\n", (26.0, 20.0, 26.0, 20.0), 0.0),- ],- 0.0,- )-- children = native_text._split_pdftext_line_by_rotation(pdf_line)- items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))-- assert [round(math.degrees(child["rotation"]), 6) for child in children] == [0.0, 315.000019]- assert children[0]["bbox"] == (30.0, 90.0, 80.0, 98.0)- assert children[1]["bbox"] == (5.0, 10.0, 25.0, 95.0)- assert [(item.text, item.bbox, item.angle) for item in items] == [- ("文档问题反馈: [email protected]", (30.0, 90.0, 80.0, 98.0), 0)- ]---def test_small_oblique_span_stays_inside_standard_direction_line() -> None:- """验证约 19 度的仿斜体 span 不触发方向拆分且沿用父行 0 度。"""-- pdf_line = _line(- [- _span("normal ", (10.0, 20.0, 40.0, 30.0), 0.0),- _span("oblique", (40.0, 18.0, 75.0, 30.0), 19.0),- ],- 0.0,- )-- children = native_text._split_pdftext_line_by_rotation(pdf_line)- items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))-- assert len(children) == 1- assert math.degrees(children[0]["rotation"]) == pytest.approx(0.0)- assert [(item.text, item.angle) for item in items] == [("normal oblique", 0)]---def test_sheared_horizontal_line_uses_char_baseline_and_splits_far_sidecar() -> None:- """验证仿斜体粗行可由水平字符基线恢复,并继续拆开远端页码。"""-- chars = [_char(value, (10.0 + index * 5.0, 80.0, 14.0 + index * 5.0, 88.0)) for index, value in enumerate("NOTICE")]- chars.append(_char("2", (90.0, 80.2, 94.0, 88.2)))- pdf_line = _line(- [- _span(- "NOTICE 2",- (10.0, 80.0, 94.0, 88.2),- 18.433,- chars=chars,- )- ],- 18.433,- bbox=(10.0, 80.0, 94.0, 88.2),- )-- items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))-- assert [(item.text, item.angle) for item in items] == [- ("NOTICE", 0),- ("2", 0),- ]- assert all(item.split_from_row for item in items)---def test_true_diagonal_char_baseline_is_not_recovered_as_horizontal() -> None:- """验证真实斜向字符中心不会因字符数量和长宽比被恢复为水平正文。"""-- chars = [- _char(value, (10.0 + index * 8.0, 70.0 - index * 6.0, 14.0 + index * 8.0, 78.0 - index * 6.0))- for index, value in enumerate("WATERMARK")- ]- pdf_line = _line(- [- _span(- "WATERMARK",- (10.0, 22.0, 78.0, 78.0),- 315.0,- chars=chars,- )- ],- 315.0,- bbox=(10.0, 22.0, 78.0, 78.0),- )-- assert native_text._build_native_line_items([pdf_line], (100.0, 100.0)) == []---def test_small_shear_formula_line_is_retained_as_formula_only() -> None:- """验证带数学运算符的小角度多基线粗行只进入 formula-only 流。"""- chars = [- _char("x", (10.0, 20.0, 15.0, 28.0)),- _char("=", (18.0, 24.0, 24.0, 30.0)),- ]- pdf_line = _line(- [_span("x=", (10.0, 20.0, 24.0, 30.0), 10.0, chars=chars)],- 10.0,- bbox=(10.0, 20.0, 24.0, 30.0),- )-- items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))-- assert [(item.text, item.angle, item.formula_candidate_only) for item in items] == [("x=", 0, True)]---def test_formula_only_rows_do_not_shift_existing_source_indices() -> None:- """验证新增公式候选使用尾部 source index,不改变既有自然文本身份。"""- first = _line([_span("first", (10.0, 10.0, 35.0, 18.0), 0.0)], 0.0)- formula = _line([_span("x=", (10.0, 20.0, 24.0, 30.0), 10.0)], 10.0)- second = _line([_span("second", (10.0, 32.0, 40.0, 40.0), 0.0)], 0.0)-- items = native_text._build_native_line_items([first, formula, second], (100.0, 100.0))-- assert {item.text: item.source_index for item in items} == {"first": 0, "second": 1, "x=": 2}---def test_small_true_diagonal_without_formula_evidence_stays_rejected() -> None:- """验证缺少公式证据的短斜向文字不会借 formula-only 流回到正文。"""- chars = [- _char(value, (10.0 + index * 5.0, 30.0 - index * 2.0, 14.0 + index * 5.0, 38.0 - index * 2.0))- for index, value in enumerate("mark")- ]- pdf_line = _line(- [_span("mark", (10.0, 24.0, 29.0, 38.0), 10.0, chars=chars)],- 10.0,- bbox=(10.0, 24.0, 29.0, 38.0),- )-- assert native_text._build_native_line_items([pdf_line], (100.0, 100.0)) == []--- ("line_angle", "page_rotation", "expected_angle"),- [- (0.0, 0, 0),- (90.0, 0, 90),- (270.0, 0, 270),- (180.0, 0, None),- (315.000019, 0, None),- (180.0, 90, 270),- (90.0, 90, None),- ],-)-def test_only_supported_visual_line_directions_are_retained(- line_angle: float,- page_rotation: int,- expected_angle: int | None,-) -> None:- """验证方向白名单在页面旋转后生效,且不会先把斜向行归一为 0 度。"""-- pdf_line = _line([_span("value", (10.0, 20.0, 40.0, 30.0), line_angle)], line_angle)-- items = native_text._build_native_line_items(- [pdf_line],- (100.0, 100.0),- page_rotation=page_rotation,- )-- assert [item.angle for item in items] == ([] if expected_angle is None else [expected_angle])---def test_native_line_builder_can_opt_in_to_180_degree_visual_runs() -> None:- """验证 Low/TXT 可显式扩展方向白名单且不改变 Flash 默认行为。"""-- pdf_line = _line(- [_span("upside down", (10.0, 20.0, 60.0, 30.0), 180.0)],- 180.0,- bbox=(10.0, 20.0, 60.0, 30.0),- )-- default_items = native_text._build_native_line_items(- [pdf_line],- (100.0, 100.0),- )- low_txt_items = native_text._build_native_line_items(- [pdf_line],- (100.0, 100.0),- supported_angles=(0.0, 90.0, 180.0, 270.0),- )-- assert default_items == []- assert [(item.text, item.angle) for item in low_txt_items] == [("upside down", 180)]--- "separator",- [- "\u00a0",- "\u1680",- "\u2000",- "\u2001",- "\u2002",- "\u2003",- "\u2004",- "\u2005",- "\u2006",- "\u2007",- "\u2008",- "\u2009",- "\u200a",- "\u202f",- "\u205f",- "\u3000",- ],-)-def test_pdf_unicode_separator_spaces_are_normalized_to_ascii(separator: str) -> None:- """验证所有 Unicode Zs 排版空格均转换为普通 ASCII 空格。"""-- assert (- native_text._sanitize_pdf_control_text(- f"left{separator}right",- preserve_newlines=True,- )- == "left right"- )---def test_pdf_unicode_line_separators_follow_newline_policy() -> None:- """验证 NEXT LINE、行分隔符和段分隔符统一遵循物理换行保留策略。"""-- content = "first\u0085second\u2028third\u2029fourth"-- assert (- native_text._sanitize_pdf_control_text(- content,- preserve_newlines=True,- )- == "first\nsecond\nthird\nfourth"- )- assert (- native_text._sanitize_pdf_control_text(- content,- preserve_newlines=False,- )- == "firstsecondthirdfourth"- )---def test_pdf_safe_invisible_and_control_characters_are_removed_idempotently() -> None:- """验证无正文语义的零宽字符和 C0/C1 控制字符被稳定删除。"""-- content = "A\u200bB\u2060C\ufeffD\x00E\x07F\x7fG\x80H\x9fI"- normalized = native_text._sanitize_pdf_control_text(- content,- preserve_newlines=True,- )-- assert normalized == "ABCDEFGHI"- assert (- native_text._sanitize_pdf_control_text(- normalized,- preserve_newlines=True,- )- == normalized- )---def test_pdf_soft_hyphens_keep_only_latin_line_end_breaks() -> None:- """验证两类 PDF 软断词仅在拉丁字母行末转成 ASCII hyphen。"""-- assert native_text._normalize_native_run_text("inter\u00ad") == "inter-"- assert native_text._normalize_native_run_text("co\u00adoperate") == "cooperate"- assert native_text._normalize_native_run_text("word\x02") == "word-"- assert native_text._normalize_native_run_text("A\x02B") == "AB"---def test_pdf_semantic_joiners_and_decode_markers_are_preserved() -> None:- """验证语言连接符、私用区字形和解码占位符不会被通用清理静默删除。"""-- content = "a\u200cb\u200dc\uf8f1d\ufffde"-- assert (- native_text._sanitize_pdf_control_text(- content,- preserve_newlines=True,- )- == content- )diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pydeleted file mode 100644index 6dece5c1..00000000--- a/tests/unittest/test_flash_pdf_pipeline.py+++ /dev/null@@ -1,814 +0,0 @@-from __future__ import annotations--import ast-import inspect-import weakref--import pytest--from docvortex.analyzers.native import PdfModel-from docvortex.analyzers.native.pdf import auxiliary_text-from docvortex.analyzers.native.pdf import char_geometry-from docvortex.analyzers.native.pdf import formulas-from docvortex.analyzers.native.pdf import geometry-from docvortex.analyzers.native.pdf import graphics-from docvortex.analyzers.native.pdf import index_blocks-from docvortex.analyzers.native.pdf import line_layout-from docvortex.analyzers.native.pdf import line_merging-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import native_text-from docvortex.analyzers.native.pdf import pipeline-from docvortex.analyzers.native.pdf import tables-from docvortex.analyzers.native.pdf import text_blocks-from docvortex.analyzers.native.pdf import text_styles-from docvortex.analyzers.native.pdf import titles-from docvortex.analyzers.native.pdf import visual_annotations-from docvortex.document.pdf.document import PDFImageInfo-from docvortex.document.pdf.document import PDFPageTextGeometry--from _flash_pdf_test_utils import (- _prepared_text_page,- _text_line,-)---def _image_info(- fingerprint: str | None,- bbox: tuple[float, float, float, float],-) -> PDFImageInfo:- """构造跨页图片水印规则使用的轻量图片信息。"""-- return PDFImageInfo(bbox=bbox, fingerprint=fingerprint)---def test_prepare_page_materializes_table_against_original_semantic_lines(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证表格检测避开预分类行,但物化阶段可看到 core 内误标页脚。"""-- body = _text_line("body", (10.0, 10.0, 90.0, 20.0), 0)- footer = _text_line(- "table tail",- (10.0, 80.0, 40.0, 90.0),- 1,- semantic_type="footer",- )- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[body, footer],- chars=[],- drawing_lines=[],- )- observed: dict[str, list[int]] = {}-- def fake_detect(- analysis_source: models._PageSource,- *,- excluded_bboxes: list[tuple[float, float, float, float]],- ) -> list[models._TableCandidate]:- """记录候选检测阶段可见的来源行。"""-- assert excluded_bboxes == []- observed["detect"] = [line.source_index for line in analysis_source.lines]- return []-- def fake_materialize(- materialization_source: models._PageSource,- candidates: list[models._TableCandidate],- **_kwargs: object,- ) -> tuple[list[dict[str, object]], list[dict[str, object]], set[int]]:- """记录表格物化阶段可见的来源行。"""-- assert candidates == []- observed["materialize"] = [line.source_index for line in materialization_source.lines]- return [], [], set()-- monkeypatch.setattr(pipeline, "_detect_table_candidates", fake_detect)- monkeypatch.setattr(pipeline, "_materialize_table_blocks", fake_materialize)-- pipeline._prepare_page_source(source)-- assert observed == {"detect": [0], "materialize": [0, 1]}---def test_prepare_page_uses_only_table_body_bbox_and_keeps_annotations_fixed(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Pipeline 仅用表体框作容器屏障,同时把预分类注释送入固定块。"""-- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[],- chars=[],- drawing_lines=[],- )- table_block = {- "type": "table",- "bbox": (10.0, 30.0, 90.0, 70.0),- "angle": 0,- "content": "body",- }- caption_block = {- "type": "caption",- "bbox": (10.0, 10.0, 50.0, 20.0),- "angle": 0,- "content": "Table 1",- }-- monkeypatch.setattr(- pipeline,- "_detect_table_candidates",- lambda *_args, **_kwargs: [],- )- monkeypatch.setattr(- pipeline,- "_materialize_table_blocks",- lambda *_args, **_kwargs: ([table_block], [caption_block], set()),- )-- prepared = pipeline._prepare_page_source(source)-- assert prepared.table_bboxes == [table_block["bbox"]]- assert [block["type"] for block in prepared.fixed_blocks] == [- "caption",- "table",- ]---def test_prepare_page_resplits_repaired_cross_column_row_before_text_classification(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证生产页面准备会按修复字符框重切跨栏粗行并分配唯一来源序号。"""-- positions = (0.0, 6.0, 12.0, 18.0, 62.0, 68.0, 74.0, 80.0)- chars = [- {- "char": character,- "bbox": (position, 10.0, position + 20.0, 20.0),- "font": {- "name": "ABCDEF+Body",- "flags": 0,- "weight": 400,- "size": 10.0,- },- "char_idx": index,- }- for index, (character, position) in enumerate(- zip("ABCDEFGH", positions, strict=True),- )- ]- line = models._LineItem(- text="ABCDEFGH",- bbox=(0.0, 10.0, 100.0, 20.0),- angle=0,- source_index=5,- chars=chars, # type: ignore[arg-type]- visual_row_id=3,- effective_height=10.0,- em_height=10.0,- )- plan = char_geometry.DocumentGeometryPlan(- char_repairs={- (0, index): char_geometry.CharLayoutGeometry(- source_bbox=tuple(float(value) for value in char["bbox"]), # type: ignore[arg-type]- tight_bbox=(position, 10.0, position + 5.0, 20.0),- origin=(position, 20.0),- layout_bbox=(position, 10.0, position + 5.0, 20.0),- ink_bbox=(position, 10.0, position + 5.0, 20.0),- baseline=20.0,- advance=6.0,- em_height=10.0,- x_state="abnormal",- y_state="healthy",- confidence=1.0,- )- for index, (char, position) in enumerate(- zip(chars, positions, strict=True),- )- },- )- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[line],- chars=chars, # type: ignore[arg-type]- drawing_lines=[],- )- observed_next_indices: list[int] = []- untouched_style = text_styles.PDFTextStyleLine(- bbox=(0.0, 30.0, 20.0, 40.0),- text="plain",- style_ranges=(),- source_index=4,- )- style_lines = [- untouched_style,- text_styles.PDFTextStyleLine(- bbox=line.bbox,- text="ABCDEFGH",- style_ranges=(- text_styles.PDFTextStyleRange(0, 2, ("bold",)),- text_styles.PDFTextStyleRange(2, 6, ("bold", "underline")),- text_styles.PDFTextStyleRange(6, 8, ("underline",)),- ),- source_index=5,- ),- ]- link_lines = [- text_styles.PDFTextLinkLine(- bbox=line.bbox,- text="ABCDEFGH",- link_ranges=(- text_styles.PDFTextLinkRange(- 2,- 6,- "https://example.test/split",- ),- ),- source_index=5,- ),- ]-- def record_graphic_split_start(- lines: list[models._LineItem],- *_args: object,- source_index_start: int,- ) -> list[models._LineItem]:- """记录跨栏重切后传给后续 graphic split 的下一来源序号。"""-- observed_next_indices.append(source_index_start)- return lines-- monkeypatch.setattr(- pipeline,- "_split_parallel_graphic_rule_rows",- record_graphic_split_start,- )-- prepared = pipeline._prepare_page_source(- source,- geometry_plan=plan,- page_index=0,- style_lines=style_lines,- link_lines=link_lines,- )-- assert [member.text for member in prepared.remaining_lines] == ["ABCD", "EFGH"]- assert [member.source_index for member in prepared.remaining_lines] == [5, 6]- assert all(member.split_from_row for member in prepared.remaining_lines)- assert observed_next_indices == [7]- assert style_lines[0] is untouched_style- assert style_lines[1:] == [- text_styles.PDFTextStyleLine(- bbox=(0.0, 10.0, 23.0, 20.0),- text="ABCD",- style_ranges=(- text_styles.PDFTextStyleRange(0, 2, ("bold",)),- text_styles.PDFTextStyleRange(2, 4, ("bold", "underline")),- ),- source_index=5,- ),- text_styles.PDFTextStyleLine(- bbox=(62.0, 10.0, 85.0, 20.0),- text="EFGH",- style_ranges=(- text_styles.PDFTextStyleRange(0, 2, ("bold", "underline")),- text_styles.PDFTextStyleRange(2, 4, ("underline",)),- ),- source_index=6,- ),- ]- assert link_lines == [- text_styles.PDFTextLinkLine(- bbox=(0.0, 10.0, 23.0, 20.0),- text="ABCD",- link_ranges=(- text_styles.PDFTextLinkRange(- 2,- 4,- "https://example.test/split",- ),- ),- source_index=5,- ),- text_styles.PDFTextLinkLine(- bbox=(62.0, 10.0, 85.0, 20.0),- text="EFGH",- link_ranges=(- text_styles.PDFTextLinkRange(- 0,- 2,- "https://example.test/split",- ),- ),- source_index=6,- ),- ]- split_blocks = [- {- "type": "text",- "bbox": member.bbox,- "content": member.text,- }- for member in prepared.remaining_lines- ]- assert {- block_index: [line.source_index for line in lines]- for block_index, lines in text_styles._assign_lines_to_blocks(- split_blocks,- style_lines[1:],- source.page_size,- ).items()- } == {0: [5], 1: [6]}- assert {- block_index: [line.source_index for line in lines]- for block_index, lines in text_styles._assign_lines_to_blocks(- split_blocks,- link_lines,- source.page_size,- ).items()- } == {0: [5], 1: [6]}---def test_prepare_page_realigns_unsplit_repaired_text_evidence() -> None:- """验证普通修复行未重切时,样式和链接 evidence 仍使用最终布局框。"""-- line = _text_line("linked", (0.0, 80.0, 200.0, 100.0), 5)- source = models._PageSource(- page_size=(200.0, 200.0),- lines=[line],- chars=[],- drawing_lines=[],- )- repaired_bbox = (20.0, 80.0, 60.0, 100.0)- plan = char_geometry.DocumentGeometryPlan(- line_repairs={- (0, 5): char_geometry.LineGeometryRepair(- source_bbox=line.bbox,- layout_bbox=repaired_bbox,- ink_bbox=repaired_bbox,- baseline=100.0,- em_height=20.0,- state="repair_x",- )- }- )- style_lines = [- text_styles.PDFTextStyleLine(- bbox=line.bbox,- text=line.text,- style_ranges=(text_styles.PDFTextStyleRange(0, len(line.text), ("bold",)),),- source_index=line.source_index,- )- ]- link_lines = [- text_styles.PDFTextLinkLine(- bbox=line.bbox,- text=line.text,- link_ranges=(text_styles.PDFTextLinkRange(0, len(line.text), "https://example.test/repaired"),),- source_index=line.source_index,- )- ]-- prepared = pipeline._prepare_page_source(- source,- geometry_plan=plan,- page_index=0,- style_lines=style_lines,- link_lines=link_lines,- )-- assert [item.bbox for item in prepared.remaining_lines] == [repaired_bbox]- assert [item.bbox for item in style_lines] == [repaired_bbox]- assert [item.bbox for item in link_lines] == [repaired_bbox]- block = {"type": "text", "bbox": repaired_bbox, "content": line.text}- assert text_styles._assign_lines_to_blocks([block], style_lines, source.page_size)- assert text_styles._assign_lines_to_blocks([block], link_lines, source.page_size)---def _repeated_separator_source(- header_text: str,- *,- connected_grid: bool = False,-) -> models._PageSource:- """构造重复页首横线,并可把该横线作为闭合表格的真实顶边。"""-- lines = [- _text_line(header_text, (20.0, 15.0, 180.0, 25.0), 0),- _text_line(f"{header_text} detail", (20.0, 30.0, 180.0, 40.0), 1),- ]- drawing_lines = [- models._AxisLine(- bbox=(10.0, 50.0, 190.0, 50.1),- width=0.1,- orientation="horizontal",- )- ]- if connected_grid:- lines.extend(- [- _text_line("left cell", (20.0, 65.0, 80.0, 75.0), 2),- _text_line("right cell", (110.0, 65.0, 170.0, 75.0), 3),- ]- )- drawing_lines.extend(- [- models._AxisLine((10.0, 90.0, 190.0, 90.1), 0.1, "horizontal"),- models._AxisLine((10.0, 50.0, 10.1, 90.0), 0.1, "vertical"),- models._AxisLine((100.0, 50.0, 100.1, 90.0), 0.1, "vertical"),- models._AxisLine((189.9, 50.0, 190.0, 90.0), 0.1, "vertical"),- ]- )- return models._PageSource(- page_size=(200.0, 400.0),- lines=lines,- chars=[],- drawing_lines=drawing_lines,- )---def test_repeated_header_separator_requires_repeated_header_text() -> None:- """验证只有横线重复、而上方普通文本不重复时不会移除表格规则。"""-- sources = [_repeated_separator_source(text) for text in ("alpha banner", "beta notice", "gamma heading")]-- assert pipeline._detect_repeated_header_separator_bboxes(sources) == [set(), set(), set()]---def test_repeated_header_separator_supports_alternating_headers() -> None:- """验证奇偶页各自重复的刊头可以共同确认同一页眉分隔线。"""-- sources = [_repeated_separator_source("even journal" if page_index % 2 == 0 else "odd article") for page_index in range(4)]- expected = {(10.0, 50.0, 190.0, 50.1)}-- assert pipeline._detect_repeated_header_separator_bboxes(sources) == [expected] * 4---def test_repeated_table_top_rule_is_not_header_separator() -> None:- """验证重复表单的闭合网格顶边不会因上方重复标题而被删除。"""-- sources = [_repeated_separator_source("repeated form", connected_grid=True) for _page_index in range(3)]-- assert pipeline._detect_repeated_header_separator_bboxes(sources) == [set(), set(), set()]- assert [candidate.bbox for candidate in tables._detect_table_candidates(sources[0])] == [(10.0, 50.0, 190.0, 90.1)]---def test_table_detection_excludes_confirmed_masthead_separator() -> None:- """验证页首通栏分隔线不与下方真表格边界组成巨型候选。"""-- source = models._PageSource(- page_size=(200.0, 300.0),- lines=[- _text_line("left masthead", (10.0, 10.0, 60.0, 20.0), 0),- _text_line("center masthead", (70.0, 10.0, 130.0, 20.0), 1),- _text_line("body", (10.0, 50.0, 190.0, 60.0), 2),- ],- chars=[],- drawing_lines=[- models._AxisLine(- bbox=(10.0, 30.0, 190.0, 31.0),- width=1.0,- orientation="horizontal",- ),- models._AxisLine(- bbox=(10.0, 100.0, 190.0, 101.0),- width=1.0,- orientation="horizontal",- ),- ],- )-- retained = pipeline._table_detection_drawing_lines(- source,- {(10.0, 30.0, 190.0, 31.0)},- )-- assert [line.bbox for line in retained] == [(10.0, 100.0, 190.0, 101.0)]---def test_repeated_large_image_requires_three_distinct_pages() -> None:- """验证同页重复只计一次,面积恰好 8% 且跨三页时才命中水印。"""-- page_sizes = [(100.0, 100.0)] * 4- page_image_infos = [- [- _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),- _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),- _image_info("two-pages", (0.0, 0.0, 50.0, 20.0)),- ],- [_image_info("watermark", (10.0, 10.0, 50.0, 30.0))],- [_image_info("watermark", (20.0, 20.0, 60.0, 40.0))],- [_image_info("two-pages", (0.0, 0.0, 50.0, 20.0))],- ]-- fingerprints = pipeline._detect_repeated_raster_watermark_fingerprints(- page_image_infos,- page_sizes,- )-- assert fingerprints == {"watermark"}---def test_repeated_watermark_filter_keeps_small_or_unfingerprinted_images() -> None:- """验证已命中指纹也只删除大图,小图和指纹读取失败的图片继续进入现有流程。"""-- image_infos = [- _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),- _image_info("watermark", (0.0, 0.0, 39.9, 20.0)),- _image_info(None, (0.0, 0.0, 80.0, 80.0)),- _image_info("ordinary", (0.0, 0.0, 80.0, 80.0)),- ]-- filtered = pipeline._filter_repeated_raster_watermark_bboxes(- image_infos,- (100.0, 100.0),- {"watermark"},- )-- assert filtered == [- (0.0, 0.0, 39.9, 20.0),- (0.0, 0.0, 80.0, 80.0),- (0.0, 0.0, 80.0, 80.0),- ]---def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:- """守卫 Flash extractor 不再引入或实现本地 OCR 运行时逻辑。"""-- source = "\n".join(- inspect.getsource(module)- for module in (- PdfModel,- auxiliary_text,- formulas,- geometry,- graphics,- index_blocks,- line_layout,- line_merging,- models,- native_text,- pipeline,- tables,- text_blocks,- titles,- visual_annotations,- )- )- forbidden_tokens = (- "import numpy",- "import cv2",- "project_ocr_table_text",- "_load_ocr_runtime",- "_run_full_page_ocr",- "_project_ocr_candidate",- "_recognize_rotated_ocr_table",- "AtomModelSingleton",- "run_ocr_inference",- "get_processing_window_size",- "bgr_image",- "pixel_quad",- "ocr_model",- )-- assert not [token for token in forbidden_tokens if token in source]---def test_native_pdf_domain_modules_do_not_import_each_other() -> None:- """守卫领域处理器只依赖共享层,跨领域组合统一留在 pipeline。"""-- domain_modules = (- auxiliary_text,- formulas,- graphics,- index_blocks,- tables,- text_blocks,- titles,- visual_annotations,- )- domain_names = {module.__name__.rsplit(".", 1)[-1] for module in domain_modules}- for module in domain_modules:- tree = ast.parse(inspect.getsource(module))- relative_imports = {- node.module- for node in ast.walk(tree)- if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module is not None- }- assert not relative_imports & domain_names, module.__name__--- "block_type",- [- "doc_title",- "paragraph_title",- "ref_text",- "header",- "footer",- "page_number",- "caption",- "footnote",- "page_footnote",- "aside_text",- "index",- "equation",- ],-)-def test_output_normalization_preserves_new_flash_types(block_type: str) -> None:- """验证 Flash 文本语义类型和公式类型不会在归一化阶段退回 text。"""-- block = pipeline._normalize_output_block(- {"type": block_type, "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": "value"},- (100.0, 100.0),- )-- assert block is not None- assert block["type"] == block_type---def test_output_normalization_keeps_empty_equation_but_drops_empty_text() -> None:- """验证纯矢量公式可保留空 content,普通空文本仍不会进入 model_list。"""-- equation = pipeline._normalize_output_block(- {"type": "equation", "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": ""},- (100.0, 100.0),- )- text = pipeline._normalize_output_block(- {"type": "text", "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": ""},- (100.0, 100.0),- )-- assert equation == {- "type": "equation",- "bbox": [0.1, 0.2, 0.4, 0.5],- "angle": 0,- "content": "",- }- assert text is None---def test_output_normalization_applies_unicode_content_safety_net() -> None:- """验证最终 model_list 归一化会兜底清理排版空格和安全零宽字符。"""-- block = pipeline._normalize_output_block(- {- "type": "text",- "bbox": (10.0, 20.0, 40.0, 50.0),- "angle": 0,- "content": "alpha\u00a0beta\u200bgamma",- },- (100.0, 100.0),- )-- assert block is not None- assert block["content"] == "alpha betagamma"---def test_index_is_claimed_before_formula_anchor_growth() -> None:- """验证目录右缘页码先形成完整 index,不再扩张为重叠公式。"""-- heading = _text_line(- "contents",- (40.0, 5.0, 60.0, 10.0),- 0,- effective_height=5.0,- )- rows = []- source_index = 1- for row_index, top in enumerate((20.0, 30.0, 40.0, 50.0, 60.0, 70.0)):- visual_row_id = 10 + row_index- rows.extend(- [- _text_line(- f"entry-{row_index}",- (10.0, top, 80.0, top + 5.0),- source_index,- visual_row_id=visual_row_id,- run_index=0,- split_from_row=True,- effective_height=5.0,- ),- _text_line(- str(row_index + 1),- (90.0, top, 95.0, top + 5.0),- source_index + 1,- visual_row_id=visual_row_id,- run_index=1,- split_from_row=True,- effective_height=5.0,- ),- ]- )- source_index += 2- page = _prepared_text_page(heading, *rows)-- blocks = pipeline._finalize_prepared_page(page, page_index=1)-- assert [block["type"] for block in blocks].count("index") == 1- assert not [block for block in blocks if block["type"] == "equation"]- assert next(block for block in blocks if block["type"] == "index")["content"].count("entry-") == 6- assert next(block for block in blocks if block["content"] == "contents")["type"] == "paragraph_title"---def test_numbered_formula_rows_are_not_claimed_as_index() -> None:- """验证连续编号公式先保留公式语义,不被无标题目录候选吞并。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "ordinary body row",- (0.0, 10.0 * index, 100.0, 10.0 * index + 7.0),- index,- effective_height=7.0,- font_signature=body_font,- font_coverage=1.0,- )- for index in range(10)- ]- source_index = 10- for row_index, top in enumerate((102.0, 113.0, 124.0, 135.0, 146.0, 157.0)):- visual_row_id = 100 + row_index- lines.extend(- [- _text_line(- f"x{row_index}=y{row_index}",- (20.0, top, 55.0, top + 7.0),- source_index,- visual_row_id=visual_row_id,- run_index=0,- split_from_row=True,- effective_height=7.0,- font_signature=("Math", 0),- font_coverage=0.6,- ),- _text_line(- f"({row_index + 1})",- (91.0, top, 100.0, top + 7.0),- source_index + 1,- visual_row_id=visual_row_id,- run_index=1,- split_from_row=True,- effective_height=7.0,- ),- ]- )- source_index += 2-- blocks = pipeline._finalize_prepared_page(- _prepared_text_page(*lines, page_size=(100.0, 200.0)),- page_index=1,- )-- assert sum(block["type"] == "equation" for block in blocks) == 6- assert not [block for block in blocks if block["type"] == "index"]--[email protected]("retain_formula", [False, True])-def test_document_preparation_releases_sources_but_keeps_formula_evidence(- monkeypatch: pytest.MonkeyPatch,- retain_formula: bool,-) -> None:- """页面准备释放原始字符所有者,同时保留公式重建明确持有的独立副本。"""-- class TrackedChar(dict):- """允许弱引用观察字符字典的实际存活期。"""-- references: list[weakref.ReferenceType[TrackedChar]] = []-- def sources() -> pipeline._DocumentSources:- """在独立作用域构建字符来源,避免测试局部变量额外延长存活期。"""-- chars = [TrackedChar(char="x", char_idx=0, bbox=(10.0, 20.0, 20.0, 30.0))]- references.append(weakref.ref(chars[0]))- return pipeline._DocumentSources(- [models._PageSource((100.0, 100.0), [], chars, [])],- [PDFPageTextGeometry(chars, {}, {})],- [(100.0, 100.0)],- [[]],- [[]],- )-- def prepare(source: models._PageSource, **kwargs: object) -> models._PreparedPage:- """仅保留模拟公式重建需要的字符副本,其它原始引用应被释放。"""-- prepared = models._PreparedPage(source.page_size, [], [], [], [])- if retain_formula:- prepared.canonical_formula_source_lines.append(- models._LineItem(- text="x",- bbox=(10.0, 20.0, 20.0, 30.0),- angle=0,- source_index=0,- chars=list(source.chars),- )- )- return prepared-- monkeypatch.setattr(pipeline, "_prepare_page_source", prepare)- raw = sources()- prepared = pipeline._prepare_document_sources(raw)- assert raw.page_sources == []- assert raw.page_text_geometries == []- assert (references[0]() is not None) == retain_formula- prepared[0].canonical_formula_source_lines.clear()- assert references[0]() is Nonediff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.pydeleted file mode 100644index 50ac701b..00000000--- a/tests/unittest/test_flash_pdf_tables.py+++ /dev/null@@ -1,2014 +0,0 @@-from __future__ import annotations--from unittest.mock import MagicMock--import pytest--from docvortex.analyzers.native.pdf import geometry-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import tables-from docvortex.analyzers.native.pdf import table_materialization-from docvortex.document.pdf.document import PDFPathInfo---def _axis_line(- orientation: str,- bbox: tuple[float, float, float, float],-) -> models._LocalAxisLine:- """构造表格候选测试使用的局部横竖线。"""-- return models._LocalAxisLine(- bbox=bbox,- original_bbox=bbox,- orientation=orientation, # type: ignore[arg-type]- width=0.0,- )---def _path_info(- bbox: tuple[float, float, float, float],- source_index: int,- *,- form_depth: int = 0,-) -> PDFPathInfo:- """构造填充网格测试使用的矩形 Path。"""-- return PDFPathInfo(- bbox=bbox,- segment_count=5,- fill_visible=True,- stroke_visible=False,- form_depth=form_depth,- source_index=source_index,- )---def test_continuation_marker_is_externalized_above_precise_rule_grid() -> None:- """验证续表标记成为独立 caption,表体从连通竖轨支撑的网格顶线开始。"""-- continuation = models._LineItem(- text="续表",- bbox=(80.0, 10.0, 95.0, 18.0),- angle=0,- source_index=0,- effective_height=8.0,- )- source = models._PageSource(- page_size=(100.0, 100.0),- lines=[continuation],- chars=[],- drawing_lines=[- models._AxisLine(- bbox=(0.0, 30.0, 100.0, 30.5),- width=0.5,- orientation="horizontal",- ),- models._AxisLine(- bbox=(0.0, 60.0, 100.0, 60.5),- width=0.5,- orientation="horizontal",- ),- models._AxisLine(- bbox=(0.0, 30.0, 0.5, 60.5),- width=0.5,- orientation="vertical",- ),- models._AxisLine(- bbox=(99.5, 30.0, 100.0, 60.5),- width=0.5,- orientation="vertical",- ),- ],- )- candidate = models._TableCandidate(- bbox=(0.0, 0.0, 100.0, 60.5),- local_bbox=(0.0, 0.0, 100.0, 60.5),- angle=0,- score=1.0,- core_bbox=(0.0, 0.0, 100.0, 60.5),- line_indices={0},- )-- tables._externalize_table_continuation_captions(- source,- [candidate],- )-- assert candidate.core_bbox == (0.0, 30.0, 100.0, 60.5)- assert candidate.line_indices == set()- assert len(candidate.annotations) == 1- assert candidate.annotations[0].kind == "caption"- assert candidate.annotations[0].line_indices == {0}---def _filled_grid_path_fixture(- *,- band_count: int = 5,- cell_gap: float = 0.0,- right_edge: float = 495.0,- form_depth: int = 0,-) -> list[PDFPathInfo]:- """构造含重复 Path、半行底纹和边缘细条的五行双列填充网格。"""-- output = [- _path_info((100.0, 100.0, 500.0, 400.0), 0, form_depth=form_depth),- _path_info((105.0, 101.0, 495.0, 104.0), 1, form_depth=form_depth),- _path_info((105.0, 396.0, 495.0, 399.0), 2, form_depth=form_depth),- ]- row_bounds = [- (105.0, 160.0),- (160.0, 230.0),- (230.0, 280.0),- (280.0, 335.0),- (335.0, 395.0),- ]- source_index = len(output)- for row_index, (top, bottom) in enumerate(row_bounds[:band_count]):- cells = [- (105.0, top, 300.0, bottom),- (300.0 + cell_gap, top, right_edge, bottom),- ]- for cell in cells:- output.append(_path_info(cell, source_index, form_depth=form_depth))- source_index += 1- if row_index == 0:- output.append(_path_info(cells[0], source_index, form_depth=form_depth))- source_index += 1- if row_index % 2 == 1:- middle = 0.5 * (top + bottom)- for left, _top, right, _bottom in cells:- for half_bbox in (- (left, top, right, middle),- (left, middle, right, bottom),- ):- output.append(- _path_info(- half_bbox,- source_index,- form_depth=form_depth,- )- )- source_index += 1- return output---def test_filled_grid_geometry_detects_exact_outer_bbox_without_text() -> None:- """验证纯 Path 网格在没有文本时仍保留精确外框并清除嵌套副本。"""-- path_infos = _filled_grid_path_fixture()- rectangles = [path_info.bbox for path_info in path_infos]- candidates = tables._detect_filled_grid_table_candidates(- path_infos,- (1000.0, 1000.0),- )- cells = tables._select_maximal_filled_grid_cells(- rectangles,- (100.0, 100.0, 500.0, 400.0),- )-- assert len(cells) == 10- assert len(candidates) == 1- assert candidates[0].bbox == (100.0, 100.0, 500.0, 400.0)- assert candidates[0].core_bbox == candidates[0].bbox- assert candidates[0].line_indices == set()-- source = models._PageSource(- page_size=(1000.0, 1000.0),- lines=[],- chars=[],- drawing_lines=[],- path_infos=path_infos,- )- assert [candidate.bbox for candidate in tables._detect_table_candidates(source)] == [(100.0, 100.0, 500.0, 400.0)]-- source.lines = [- models._LineItem(- text="任意替换内容",- bbox=(120.0, 120.0, 260.0, 140.0),- angle=0,- source_index=0,- effective_height=20.0,- )- ]- assert [candidate.bbox for candidate in tables._detect_table_candidates(source)] == [(100.0, 100.0, 500.0, 400.0)]---def test_filled_grid_geometry_rejects_incomplete_or_interfering_paths() -> None:- """验证行带不足、横向破损、非根层和强图形重叠均不能生成外框。"""-- page_size = (1000.0, 1000.0)- assert (- tables._detect_filled_grid_table_candidates(- _filled_grid_path_fixture(band_count=3),- page_size,- )- == []- )- assert (- tables._detect_filled_grid_table_candidates(- _filled_grid_path_fixture(right_edge=450.0),- page_size,- )- == []- )- assert (- tables._detect_filled_grid_table_candidates(- _filled_grid_path_fixture(cell_gap=10.0),- page_size,- )- == []- )- assert (- tables._detect_filled_grid_table_candidates(- _filled_grid_path_fixture(form_depth=1),- page_size,- )- == []- )- assert (- tables._detect_filled_grid_table_candidates(- _filled_grid_path_fixture(),- page_size,- [(120.0, 120.0, 480.0, 380.0)],- )- == []- )---def test_filled_grid_candidate_prevents_rule_bbox_expansion() -> None:- """验证填充网格优先后,重叠横线候选不能扩大其 Path 外框。"""-- lines: list[models._LineItem] = []- source_index = 0- for row_index, top in enumerate((120.0, 190.0, 260.0, 330.0)):- for left, right in ((120.0, 280.0), (320.0, 480.0)):- lines.append(- models._LineItem(- text=f"cell-{source_index}",- bbox=(left, top, right, top + 20.0),- angle=0,- source_index=source_index,- effective_height=20.0,- visual_row_id=row_index,- )- )- source_index += 1- source = models._PageSource(- page_size=(1000.0, 1000.0),- lines=lines,- chars=[],- drawing_lines=[- models._AxisLine(- bbox=(80.0, 90.0, 520.0, 91.0),- width=1.0,- orientation="horizontal",- ),- models._AxisLine(- bbox=(80.0, 410.0, 520.0, 411.0),- width=1.0,- orientation="horizontal",- ),- ],- path_infos=_filled_grid_path_fixture(),- )-- candidates = tables._detect_table_candidates(source)-- assert [candidate.bbox for candidate in candidates] == [(100.0, 100.0, 500.0, 400.0)]---def test_filled_grid_materialization_uses_existing_spatial_projection(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证空成员候选由 core bbox 收集文本,不需要建立单元格归属。"""-- lines = [- models._LineItem(- text="inside-left",- bbox=(120.0, 120.0, 240.0, 140.0),- angle=0,- source_index=0,- effective_height=20.0,- ),- models._LineItem(- text="inside-right",- bbox=(330.0, 120.0, 480.0, 140.0),- angle=0,- source_index=1,- effective_height=20.0,- ),- models._LineItem(- text="outside",- bbox=(120.0, 430.0, 240.0, 450.0),- angle=0,- source_index=2,- effective_height=20.0,- ),- ]- source = models._PageSource(- page_size=(1000.0, 1000.0),- lines=lines,- chars=[],- drawing_lines=[],- path_infos=_filled_grid_path_fixture(),- )- candidate = tables._detect_filled_grid_table_candidates(- source.path_infos,- source.page_size,- )[0]- projection = MagicMock(return_value="inside-left inside-right")- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert claimed == {0, 1}- assert annotation_blocks == []- assert blocks == [- {- "type": "table",- "bbox": (100.0, 100.0, 500.0, 400.0),- "angle": 0,- "content": "inside-left inside-right",- }- ]- assert projection.call_args.args[0] is source.chars---def test_table_materialization_preserves_raw_page_line_breaks() -> None:- """验证短末列与下一行轻微重叠时使用原始换行,禁止跨行拼接。"""-- def build_chars(- text: str,- left: float,- top: float,- start_index: int,- ) -> list[dict[str, object]]:- """构造带稳定字符序号和紧凑字符框的空间投影测试字符。"""-- return [- {- "char": char,- "bbox": (- left + 2.0 * offset,- top,- left + 2.0 * (offset + 1),- top + 10.0,- ),- "char_idx": start_index + offset,- }- for offset, char in enumerate(text)- ]-- error_chars = build_chars("6.20", 80.0, 10.0, 0)- method_chars = build_chars("CostFilter [10]", 10.0, 19.8, 6)- source = models._PageSource(- page_size=(100.0, 40.0),- lines=[- models._LineItem(- text="6.20",- bbox=(80.0, 10.0, 88.0, 20.0),- angle=0,- source_index=0,- chars=error_chars,- effective_height=10.0,- visual_row_id=0,- ),- models._LineItem(- text="CostFilter [10]",- bbox=(10.0, 19.8, 40.0, 29.8),- angle=0,- source_index=1,- chars=method_chars,- effective_height=10.0,- visual_row_id=1,- ),- ],- chars=[- *error_chars,- {"char": "\r", "bbox": (88.0, 18.0, 88.0, 18.0), "char_idx": 4},- {"char": "\n", "bbox": (88.0, 18.0, 88.0, 18.0), "char_idx": 5},- *method_chars,- ],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(0.0, 0.0, 100.0, 40.0),- local_bbox=(0.0, 0.0, 100.0, 40.0),- angle=0,- score=1.0,- core_bbox=(0.0, 0.0, 100.0, 40.0),- line_indices={0, 1},- )-- blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert annotation_blocks == []- assert claimed == {0, 1}- assert len(blocks) == 1- assert blocks[0]["content"].splitlines() == [- " 6.20",- "CostFilter [10]",- ]- assert "6.20CostFilter" not in blocks[0]["content"]---def test_table_core_reclaims_semantic_line_without_touching_outer_marginals(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 core 内预标页脚可被表格认领,表框外页脚与页码保持未认领。"""-- lines = [- models._LineItem(- text="cell",- bbox=(10.0, 10.0, 40.0, 20.0),- angle=0,- source_index=0,- effective_height=10.0,- ),- models._LineItem(- text="table tail",- bbox=(10.0, 40.0, 40.0, 50.0),- angle=0,- source_index=1,- effective_height=10.0,- semantic_type="footer",- ),- models._LineItem(- text="disclaimer",- bbox=(10.0, 70.0, 60.0, 80.0),- angle=0,- source_index=2,- effective_height=10.0,- semantic_type="footer",- ),- models._LineItem(- text="1",- bbox=(90.0, 70.0, 95.0, 80.0),- angle=0,- source_index=3,- effective_height=10.0,- semantic_type="page_number",- ),- ]- source = models._PageSource(- page_size=(100.0, 100.0),- lines=lines,- chars=[],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(0.0, 0.0, 80.0, 60.0),- local_bbox=(0.0, 0.0, 80.0, 60.0),- angle=0,- score=1.0,- core_bbox=(0.0, 0.0, 80.0, 60.0),- line_indices={0},- )- projection = MagicMock(return_value="cell\ntable tail")- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert len(blocks) == 1- assert annotation_blocks == []- assert claimed == {0, 1}- assert projection.call_args.args[0] is source.chars- assert {line.source_index for line in lines if line.source_index not in claimed} == {- 2,- 3,- }--- ("median_height", "rejected_length", "accepted_length"),- [- (3.0, 39.99, 40.0),- (5.0, 49.99, 50.0),- ],-)-def test_long_rule_group_uses_40pt_or_ten_times_height_threshold(- median_height: float,- rejected_length: float,- accepted_length: float,-) -> None:- """验证长横线沿用 40pt 或十倍行高门槛,竖线不参与分组。"""-- rejected_lines = [- _axis_line("horizontal", (0.0, 10.0, rejected_length, 10.1)),- _axis_line("horizontal", (0.0, 20.0, accepted_length, 20.1)),- _axis_line("horizontal", (0.0, 30.0, accepted_length, 30.1)),- _axis_line("vertical", (10.0, 0.0, 10.1, 40.0)),- ]- accepted_lines = [_axis_line("horizontal", (0.0, top, accepted_length, top + 0.1)) for top in (10.0, 20.0, 30.0)]-- grouped = tables._group_long_horizontal_rules(rejected_lines, median_height)- assert len(grouped) == 1- assert [line.bbox for line in grouped[0]] == [- (0.0, 20.0, accepted_length, 20.1),- (0.0, 30.0, accepted_length, 30.1),- ]- assert len(tables._group_long_horizontal_rules(accepted_lines, median_height)) == 1---def test_connected_rule_grid_expands_core_and_reclaims_sparse_bottom_row() -> None:- """验证连续物理网格会补全候选底边,并重新认领稀疏末行文本。"""-- bottom_bbox = (10.0, 66.0, 35.0, 72.0)- bottom_line = models._LineItem(- text="sparse bottom",- bbox=bottom_bbox,- angle=0,- source_index=9,- effective_height=6.0,- visual_row_id=3,- )- bottom_row = models._VisualRow(- fragments=[- models._Fragment(- text=bottom_line.text,- bbox=bottom_bbox,- local_bbox=bottom_bbox,- line_index=9,- visual_row_id=3,- )- ],- center_y=69.0,- bbox=bottom_bbox,- visual_row_id=3,- )- candidate = models._TableCandidate(- bbox=(0.0, 8.0, 110.0, 58.1),- local_bbox=(0.0, 8.0, 110.0, 58.1),- angle=0,- score=8.0,- core_bbox=(0.0, 8.0, 110.0, 58.1),- line_indices=set(range(9)),- )- axis_lines = [- *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 58.0, 80.0)],- *[_axis_line("vertical", (left, 8.0, left + 0.1, 80.1)) for left in (0.0, 55.0, 109.9)],- ]-- expanded = tables._expand_candidates_to_connected_rule_grids(- [candidate],- [bottom_row],- (150.0, 100.0),- 0,- 5.0,- axis_lines,- [],- )-- assert expanded[0].core_bbox == pytest.approx((0.0, 8.0, 110.0, 80.1))- assert expanded[0].bbox == pytest.approx((0.0, 8.0, 110.0, 80.1))- assert 9 in expanded[0].line_indices---def test_disconnected_stacked_rule_grids_remain_separate() -> None:- """验证竖轨未跨越空白间距时,同跨度上下网格仍保持为两张表。"""-- axis_lines = [- *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 58.0, 90.0, 140.0)],- *[_axis_line("vertical", (left, 8.0, left + 0.1, 58.1)) for left in (0.0, 55.0, 109.9)],- *[_axis_line("vertical", (left, 90.0, left + 0.1, 140.1)) for left in (0.0, 55.0, 109.9)],- ]-- grid_bboxes = tables._connected_rule_grid_bboxes(axis_lines, 5.0)-- assert grid_bboxes == pytest.approx(- [- (0.0, 8.0, 110.0, 58.1),- (0.0, 90.0, 110.0, 140.1),- ]- )---def _closed_sparse_grid_fixture(- *,- horizontal_count: int = 3,-) -> tuple[- list[models._VisualRow],- list[models._LineItem],- list[models._LocalAxisLine],-]:- """构造仅有少量文本、但外轨完整闭合的物理网格。"""-- fragment_bboxes = (- (10.0, 10.0, 30.0, 15.0),- (75.0, 10.0, 95.0, 15.0),- )- fragments = [- models._Fragment(- text=f"cell-{index}",- bbox=bbox,- local_bbox=bbox,- line_index=index,- visual_row_id=0,- )- for index, bbox in enumerate(fragment_bboxes)- ]- rows = [- models._VisualRow(- fragments=fragments,- center_y=12.5,- bbox=geometry._bbox_union_many(fragment_bboxes),- visual_row_id=0,- )- ]- lines = [- models._LineItem(- text=fragment.text,- bbox=fragment.bbox,- angle=0,- source_index=fragment.line_index,- effective_height=5.0,- visual_row_id=0,- )- for fragment in fragments- ]- horizontal_tops = (0.0, 20.0, 40.0) if horizontal_count == 3 else (0.0, 40.0)- axis_lines = [- *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in horizontal_tops],- *[_axis_line("vertical", (left, 0.0, left + 0.1, 40.1)) for left in (0.0, 55.0, 109.9)],- ]- return rows, lines, axis_lines---def test_closed_grid_accepts_sparse_single_column_form_with_empty_row() -> None:- """验证三条横边界和完整外轨可接纳有空数据行的单列表单。"""-- rows, lines, axis_lines = _closed_sparse_grid_fixture()- rows[0].fragments = rows[0].fragments[:1]- rows[0].bbox = rows[0].fragments[0].bbox- lines = lines[:1]-- candidates = tables._build_closed_rule_grid_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- [],- )-- assert len(candidates) == 1- assert candidates[0].core_bbox == pytest.approx((0.0, 0.0, 110.0, 40.1))- assert candidates[0].line_indices == {0}---def test_closed_two_boundary_grid_requires_text_in_two_physical_columns() -> None:- """验证两条横边界只有在三条贯穿竖轨且文字占两列时才接纳。"""-- rows, lines, axis_lines = _closed_sparse_grid_fixture(- horizontal_count=2,- )-- candidates = tables._build_closed_rule_grid_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- [],- )-- assert len(candidates) == 1- assert candidates[0].line_indices == {0, 1}--- "failure_mode",- [- "no_text",- "short_outer_tracks",- "only_two_vertical_tracks",- "one_occupied_column",- "excluded_graphic",- ],-)-def test_closed_sparse_grid_rejects_incomplete_or_excluded_geometry(- failure_mode: str,-) -> None:- """验证空框、短外轨、单格框、单列文字和强图形区域不会误报表格。"""-- rows, lines, axis_lines = _closed_sparse_grid_fixture(- horizontal_count=2,- )- excluded_bboxes: list[tuple[float, float, float, float]] = []- if failure_mode == "no_text":- rows = []- lines = []- elif failure_mode == "short_outer_tracks":- axis_lines = [- _axis_line("vertical", (line.bbox[0], 5.0, line.bbox[2], 35.0)) if line.orientation == "vertical" else line- for line in axis_lines- ]- elif failure_mode == "only_two_vertical_tracks":- axis_lines = [line for line in axis_lines if line.orientation != "vertical" or line.bbox[0] != 55.0]- elif failure_mode == "one_occupied_column":- rows[0].fragments[1].bbox = (32.0, 10.0, 48.0, 15.0)- rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox- rows[0].bbox = geometry._bbox_union_many([fragment.bbox for fragment in rows[0].fragments])- else:- excluded_bboxes = [(0.0, 0.0, 110.0, 40.1)]-- assert (- tables._build_closed_rule_grid_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- excluded_bboxes,- )- == []- )---def test_closed_grid_inside_form_bbox_is_not_a_table_candidate() -> None:- """验证 Form 容器内的闭合线框继续由图片分支处理而不生成表格。"""-- rows, lines, axis_lines = _closed_sparse_grid_fixture()- source = models._PageSource(- page_size=(150.0, 100.0),- lines=lines,- chars=[],- drawing_lines=[- models._AxisLine(- bbox=line.bbox,- width=line.width,- orientation=line.orientation,- )- for line in axis_lines- ],- form_bboxes=[(0.0, 0.0, 110.0, 40.1)],- )-- assert tables._detect_table_candidates(source) == []---def _rule_table_fixture(- rule_count: int = 3,- *,- centered_columns: bool = False,-) -> tuple[- list[models._VisualRow],- list[models._LineItem],- list[models._LocalAxisLine],-]:- """构造无 caption 的规则表格,并可切换为宽度变化的居中列。"""-- rows: list[models._VisualRow] = []- lines: list[models._LineItem] = []- source_index = 0- for row_index, top in enumerate((10.0, 30.0, 50.0)):- fragments: list[models._Fragment] = []- if centered_columns:- half_width = (2.0, 8.0, 14.0)[row_index]- column_bounds = (- (30.0 - half_width, 30.0 + half_width),- (90.0 - half_width, 90.0 + half_width),- )- else:- column_bounds = ((10.0, 20.0), (50.0, 60.0), (90.0, 100.0))- for column_index, (left, right) in enumerate(column_bounds):- bbox = (left, top, right, top + 5.0)- text = f"r{row_index}c{column_index}"- fragments.append(- models._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- lines.append(- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=5.0,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- models._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=(10.0, top, 100.0, top + 5.0),- visual_row_id=row_index,- )- )- rule_tops = (8.0, 58.0) if rule_count == 2 else (8.0, 33.0, 58.0)- axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in rule_tops]- return rows, lines, axis_lines---def _compact_fully_ruled_table_fixture() -> tuple[- list[models._VisualRow],- list[models._LineItem],- list[models._LocalAxisLine],-]:- """构造两行四列、三横五竖的紧凑全封闭网格。"""-- rows: list[models._VisualRow] = []- lines: list[models._LineItem] = []- column_bounds = (- (5.0, 20.0),- (32.0, 48.0),- (60.0, 75.0),- (87.0, 105.0),- )- source_index = 0- for row_index, top in enumerate((10.0, 22.0)):- fragments: list[models._Fragment] = []- for column_index, (left, right) in enumerate(column_bounds):- bbox = (left, top, right, top + 5.0)- text = f"cell-{row_index}-{column_index}"- fragments.append(- models._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- lines.append(- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=5.0,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- models._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=geometry._bbox_union_many([fragment.bbox for fragment in fragments]),- visual_row_id=row_index,- )- )-- axis_lines = [- *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 20.0, 32.0)],- *[_axis_line("vertical", (left, 8.1, left + 0.1, 32.0)) for left in (0.0, 27.5, 55.0, 82.5, 109.9)],- ]- return rows, lines, axis_lines---def test_rule_table_candidate_accepts_captionless_regular_text_distribution() -> None:- """验证三横线和连续稳定列足以识别没有显式标题的表格。"""-- rows, lines, axis_lines = _rule_table_fixture()-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(9))---def test_rule_table_candidate_accepts_center_aligned_columns_with_varying_widths() -> None:- """验证左右边界变化但中心稳定的两列表格仍可形成候选。"""-- rows, lines, axis_lines = _rule_table_fixture(centered_columns=True)-- assert tables._count_stable_columns(rows, 5.0) == (2, 1.0)- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(6))---def test_compact_fully_ruled_two_row_table_is_accepted() -> None:- """验证两行表格在三横五竖形成完整网格时可通过严格候选准入。"""-- rows, lines, axis_lines = _compact_fully_ruled_table_fixture()-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(8))- assert candidates[0].score == 8.0---def test_caption_anchored_two_row_three_line_table_is_accepted() -> None:- """验证强表题可与三横线、两行稳定多列共同确认无竖线表格。"""-- rows, lines, axis_lines = _compact_fully_ruled_table_fixture()- axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]- lines.append(- models._LineItem(- text="Table 1 Results",- bbox=(20.0, 0.0, 90.0, 6.0),- angle=0,- source_index=100,- effective_height=5.0,- )- )- rows.append(- models._VisualRow(- fragments=[- models._Fragment(- text="Table 1 Results",- bbox=(20.0, 0.0, 90.0, 6.0),- local_bbox=(20.0, 0.0, 90.0, 6.0),- line_index=100,- visual_row_id=100,- )- ],- center_y=3.0,- bbox=(20.0, 0.0, 90.0, 6.0),- visual_row_id=100,- )- )- rows.sort(key=lambda row: row.center_y)-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 200.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(8))- assert [annotation.kind for annotation in candidates[0].annotations] == ["caption"]---def test_compact_grid_deduplicates_repeated_vertical_paths() -> None:- """验证同位置重复竖线路径不会扩大紧凑表格的物理列数和评分。"""-- rows, lines, axis_lines = _compact_fully_ruled_table_fixture()- axis_lines.extend(_axis_line("vertical", (left + 0.3, 8.1, left + 0.4, 32.0)) for left in (0.0, 27.5, 55.0, 82.5, 109.9))-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].score == 8.0--- "failure_mode",- [- "horizontal_only",- "short_verticals",- "missing_outer",- "same_cell",- "center_on_boundary",- ],-)-def test_compact_two_row_layout_requires_complete_grid(- failure_mode: str,-) -> None:- """验证两行文本缺少完整竖向网格或唯一单元格映射时仍保持非表格。"""-- rows, lines, axis_lines = _compact_fully_ruled_table_fixture()- if failure_mode == "horizontal_only":- axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]- elif failure_mode == "short_verticals":- axis_lines = [- _axis_line("vertical", (line.bbox[0], 13.0, line.bbox[2], 27.0)) if line.orientation == "vertical" else line- for line in axis_lines- ]- elif failure_mode == "missing_outer":- axis_lines = [line for line in axis_lines if line.orientation != "vertical" or line.bbox[0] > 1.0]- elif failure_mode == "same_cell":- rows[0].fragments[1].bbox = (8.0, 10.0, 18.0, 15.0)- rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox- else:- rows[0].fragments[1].bbox = (26.5, 10.0, 28.5, 15.0)- rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert candidates == []---def test_compact_admission_does_not_accept_two_row_column_prose() -> None:- """验证两行普通双栏文本不会因紧凑表格分支而降低准入门槛。"""-- rows, lines, axis_lines = _compact_fully_ruled_table_fixture()- for row in rows:- row.fragments = [row.fragments[0], row.fragments[-1]]- row.bbox = geometry._bbox_union_many([fragment.bbox for fragment in row.fragments])- retained_indices = {fragment.line_index for row in rows for fragment in row.fragments}- lines = [line for line in lines if line.source_index in retained_indices]- axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert candidates == []---def test_two_horizontal_rule_grid_is_accepted_by_spatial_distribution() -> None:- """验证两条长横线结合密集稳定列即可形成表格候选。"""-- rows, lines, axis_lines = _rule_table_fixture(rule_count=2)- axis_lines.extend(- [- _axis_line("vertical", (0.0, 8.0, 0.1, 58.0)),- _axis_line("vertical", (55.0, 8.0, 55.1, 58.0)),- _axis_line("vertical", (109.9, 8.0, 110.0, 58.0)),- ]- )-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(9))---def test_duplicate_horizontal_paths_count_as_one_boundary() -> None:- """验证同一 y 位置的重复 PDF path 只计为一条边界。"""-- axis_lines = [- _axis_line("horizontal", (0.0, 10.0, 100.0, 10.1)),- _axis_line("horizontal", (0.0, 10.5, 100.0, 10.6)),- _axis_line("horizontal", (0.0, 30.0, 100.0, 30.1)),- ]-- groups = tables._group_long_horizontal_rules(axis_lines, 5.0)-- assert len(groups) == 1- assert len(groups[0]) == 2- assert [line.bbox[1] for line in groups[0]] == [10.0, 30.0]- assert tables._group_long_horizontal_rules(axis_lines[:2], 5.0) == []---def test_nearest_rule_pair_excludes_header_line_from_table_bbox() -> None:- """验证页首横线与表格上边界间没有多单元行时,不扩张表格 bbox。"""-- rows, lines, axis_lines = _rule_table_fixture(rule_count=2)- axis_lines.insert(0, _axis_line("horizontal", (0.0, 0.0, 110.0, 0.1)))-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].core_bbox is not None- assert candidates[0].core_bbox[1] == pytest.approx(8.0)---def test_chart_tick_rows_fail_dense_multi_cell_distribution() -> None:- """验证多个图表刻度行因纵向不连续而不能冒充规则表格。"""-- rows: list[models._VisualRow] = []- lines: list[models._LineItem] = []- source_index = 0- for row_index, (top, anchors) in enumerate(- (- (10.0, (10.0, 30.0, 50.0, 70.0, 90.0)),- (20.0, (50.0,)),- (30.0, (45.0,)),- (75.0, (10.0, 30.0, 50.0, 70.0, 90.0)),- (85.0, (50.0,)),- (95.0, (45.0,)),- )- ):- fragments: list[models._Fragment] = []- for anchor in anchors:- bbox = (anchor, top, anchor + 5.0, top + 5.0)- text = f"tick-{source_index}"- fragments.append(- models._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- lines.append(- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=5.0,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- models._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=geometry._bbox_union_many([fragment.bbox for fragment in fragments]),- visual_row_id=row_index,- )- )- axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (0.0, 55.0, 110.0)]-- candidates = tables._build_rule_table_candidates(- rows,- lines,- (150.0, 120.0),- 0,- 5.0,- axis_lines,- )-- assert candidates == []---def test_long_sparse_rule_interval_cannot_bridge_two_low_column_tables() -> None:- """验证低列数表格之间仅有一行稀疏文本时不能跨长区间合并。"""-- rows: list[models._VisualRow] = []- source_index = 0- for row_index, (top, anchors) in enumerate(- (- (10.0, (10.0, 50.0, 90.0)),- (20.0, (10.0, 50.0, 90.0)),- (30.0, (10.0, 50.0, 90.0)),- (80.0, (10.0, 90.0)),- (130.0, (10.0, 50.0, 90.0)),- (140.0, (10.0, 50.0, 90.0)),- )- ):- fragments = []- for anchor in anchors:- bbox = (anchor, top, anchor + 5.0, top + 5.0)- fragments.append(- models._Fragment(- text=f"cell-{source_index}",- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- models._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=geometry._bbox_union_many([fragment.bbox for fragment in fragments]),- visual_row_id=row_index,- )- )- rules = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (0.0, 40.0, 120.0, 150.0)]-- assert not tables._rule_intervals_are_column_compatible(rows, rules, 5.0)---def test_split_table_footnote_marker_is_joined_before_matching() -> None:- """验证旋转表拆开的 For 与星号脚注在视觉行拼接后可被识别。"""-- row = models._VisualRow(- fragments=[- models._Fragment("For", (0.0, 0.0, 10.0, 5.0), (0.0, 0.0, 10.0, 5.0), 0),- models._Fragment("*rainfall", (12.0, 0.0, 35.0, 5.0), (12.0, 0.0, 35.0, 5.0), 1),- ],- center_y=2.5,- bbox=(0.0, 0.0, 35.0, 5.0),- )-- assert tables._is_table_note_text(tables._visual_row_text(row))- assert not tables._is_table_note_text("1 Numeric table footnote")---def test_table_candidate_merge_keeps_body_and_annotation_roles_disjoint() -> None:- """验证重复候选合并时表体身份优先,并据逐行框收紧 caption 边界。"""-- caption_bbox = (10.0, 10.0, 50.0, 20.0)- header_bbox = (10.0, 25.0, 90.0, 35.0)- primary = models._TableCandidate(- bbox=(0.0, 0.0, 100.0, 80.0),- local_bbox=(0.0, 0.0, 100.0, 80.0),- angle=0,- score=2.0,- core_bbox=(0.0, 25.0, 100.0, 80.0),- line_indices={2},- annotations=[- models._TableAnnotation(- kind="caption",- bbox=geometry._bbox_union(caption_bbox, header_bbox),- line_indices={0, 1},- line_bboxes={0: caption_bbox, 1: header_bbox},- )- ],- )- secondary = models._TableCandidate(- bbox=(0.0, 0.0, 100.0, 80.0),- local_bbox=(0.0, 0.0, 100.0, 80.0),- angle=0,- score=1.0,- core_bbox=(0.0, 25.0, 100.0, 80.0),- line_indices={1, 2},- annotations=[- models._TableAnnotation(- kind="caption",- bbox=caption_bbox,- line_indices={0},- line_bboxes={0: caption_bbox},- )- ],- )-- merged = tables._merge_table_candidates([primary, secondary])-- assert len(merged) == 1- assert merged[0].line_indices == {1, 2}- assert len(merged[0].annotations) == 1- assert merged[0].annotations[0].line_indices == {0}- assert merged[0].annotations[0].bbox == caption_bbox---def test_materialize_table_externalizes_multiline_annotations_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证拆分编号 caption、多行数字脚注和表体按来源行各物化并认领一次。"""-- line_specs = (- ("Table", (10.0, 10.0, 35.0, 20.0), 0),- ("2: Metrics", (38.0, 10.0, 80.0, 20.0), 1),- ("Header Body", (10.0, 30.0, 90.0, 60.0), 2),- ("1 Numeric note", (10.0, 70.0, 70.0, 80.0), 3),- ("* Symbol note", (10.0, 80.0, 70.0, 90.0), 4),- )- lines = [- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=10.0,- font_signature=("Test", 0),- font_coverage=1.0,- )- for text, bbox, source_index in line_specs- ]- source = models._PageSource(- page_size=(100.0, 100.0),- lines=lines,- chars=[],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(10.0, 10.0, 90.0, 90.0),- local_bbox=(10.0, 10.0, 90.0, 90.0),- angle=0,- score=1.0,- core_bbox=(10.0, 30.0, 90.0, 60.0),- line_indices={2},- annotations=[- models._TableAnnotation(- kind="caption",- bbox=(10.0, 10.0, 80.0, 20.0),- line_indices={0, 1},- ),- models._TableAnnotation(- kind="footnote",- bbox=(10.0, 70.0, 70.0, 90.0),- line_indices={3, 4},- ),- ],- )- projection = MagicMock(return_value="Header Body")- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- table_blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert table_blocks == [- {- "type": "table",- "bbox": (10.0, 30.0, 90.0, 60.0),- "angle": 0,- "content": "Header Body",- }- ]- assert [block["type"] for block in annotation_blocks] == [- "caption",- "footnote",- ]- assert [block["content"] for block in annotation_blocks] == [- "Table 2: Metrics",- "1 Numeric note * Symbol note",- ]- assert all(- block["_table_annotation_complete"] is True- and block["_font_signatures"] == {("Test", 0)}- and len(block["_line_heights"]) == 2- for block in annotation_blocks- )- assert projection.call_args.args[0] is source.chars- assert projection.call_args.args[1] == (10.0, 30.0, 90.0, 60.0)- assert claimed == {0, 1, 2, 3, 4}---def test_table_annotation_splits_short_tail_before_wide_font_family_reset() -> None:- """验证表下注短尾后的宽行字体族重启形成两个独立注释块。"""-- lines = [- models._LineItem(- "first body",- (10.0, 70.0, 90.0, 80.0),- 0,- 0,- effective_height=10.0,- em_height=10.0,- font_signature=("FirstFont", 0),- font_coverage=1.0,- ),- models._LineItem(- "tail",- (10.0, 82.0, 30.0, 92.0),- 0,- 1,- effective_height=10.0,- em_height=10.0,- font_signature=("FirstFont", 0),- font_coverage=1.0,- ),- models._LineItem(- "second body",- (12.0, 94.0, 88.0, 104.0),- 0,- 2,- effective_height=10.0,- em_height=10.0,- font_signature=("SecondFont", 0),- font_coverage=1.0,- ),- ]- source = models._PageSource(- page_size=(120.0, 120.0),- lines=lines,- chars=[],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(5.0, 10.0, 110.0, 110.0),- local_bbox=(5.0, 10.0, 110.0, 110.0),- angle=0,- score=1.0,- core_bbox=(5.0, 10.0, 110.0, 60.0),- line_indices=set(),- )- annotation = models._TableAnnotation(- kind="footnote",- bbox=(10.0, 70.0, 90.0, 104.0),- line_indices={0, 1, 2},- line_bboxes={line.source_index: line.bbox for line in lines},- )-- blocks = tables._build_table_annotation_blocks(- source,- candidate,- annotation,- )- lines[2].font_signature = ("FirstFont", 0)- control = tables._build_table_annotation_blocks(- source,- candidate,- annotation,- )-- assert [block["content"] for block in blocks] == [- "first body tail",- "second body",- ]- assert [block["type"] for block in blocks] == [- "footnote",- "footnote",- ]- assert [block["content"] for block in control] == [- "first body tail second body",- ]---def test_invalid_table_annotation_falls_back_to_full_table_projection(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证无法形成内容的注释行留在表体投影,表框与认领均不收缩。"""-- lines = [- models._LineItem("body", (10.0, 30.0, 90.0, 60.0), 0, 0),- models._LineItem("", (10.0, 10.0, 90.0, 20.0), 0, 1),- ]- source = models._PageSource(- page_size=(100.0, 100.0),- lines=lines,- chars=[],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(10.0, 10.0, 90.0, 60.0),- local_bbox=(10.0, 10.0, 90.0, 60.0),- angle=0,- score=1.0,- core_bbox=(10.0, 30.0, 90.0, 60.0),- line_indices={0},- annotations=[- models._TableAnnotation(- kind="caption",- bbox=(10.0, 10.0, 90.0, 20.0),- line_indices={1},- )- ],- )- projection = MagicMock(return_value="body")- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- table_blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert annotation_blocks == []- assert table_blocks[0]["bbox"] == candidate.bbox- assert projection.call_args.args[0] is source.chars- assert projection.call_args.args[1] == candidate.bbox- assert claimed == {0, 1}---def _table_note_reference_fixture(- marker: str,- reference_mode: str,- *,- angle: int = 0,- note_height: float = 8.0,-) -> tuple[- list[models._VisualRow],- list[models._LineItem],- tuple[float, float, float, float],- set[int],- tuple[float, float],-]:- """构造含中性表内引用、表注首行和正文高度样本的局部坐标夹具。"""-- page_size = (200.0, 200.0)- rule_bbox = (0.0, 20.0, 100.0, 50.0)- core_local_bbox = (10.0, 25.0, 70.0, 35.0)- core_chars: list[dict[str, object]] = []- if reference_mode == "superscript":- core_text = f"cell{marker}"- x_position = 10.0- for raw_char in "cell":- local_bbox = (x_position, 25.0, x_position + 7.0, 35.0)- core_chars.append(- {- "char": raw_char,- "bbox": geometry._rotate_bbox_from_upright(local_bbox, page_size, angle),- }- )- x_position += 8.0- for raw_char in marker:- local_bbox = (x_position, 22.0, x_position + 5.0, 28.0)- core_chars.append(- {- "char": raw_char,- "bbox": geometry._rotate_bbox_from_upright(local_bbox, page_size, angle),- }- )- x_position += 5.5- elif reference_mode == "compact":- core_text = marker- else:- core_text = "neutral value"-- core_line = models._LineItem(- text=core_text,- bbox=geometry._rotate_bbox_from_upright(core_local_bbox, page_size, angle),- angle=angle,- source_index=0,- chars=core_chars, # type: ignore[arg-type]- effective_height=10.0,- font_signature=("Table", 0),- font_coverage=1.0,- )- note_local_bbox = (0.0, 51.0, 80.0, 51.0 + note_height)- note_line = models._LineItem(- text=f"{marker} neutral explanation",- bbox=geometry._rotate_bbox_from_upright(note_local_bbox, page_size, angle),- angle=angle,- source_index=1,- effective_height=note_height,- font_signature=("Note", 0),- font_coverage=1.0,- )- body_lines = [- models._LineItem(- text=f"body-{source_index}",- bbox=geometry._rotate_bbox_from_upright(- (110.0, top, 190.0, top + 10.0),- page_size,- angle,- ),- angle=angle,- source_index=source_index,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- for source_index, top in enumerate((140.0, 152.0, 164.0, 176.0), start=2)- ]- rows = [- models._VisualRow(- fragments=[models._Fragment(core_text, core_local_bbox, core_local_bbox, 0, 0)],- center_y=geometry._bbox_center_y(core_local_bbox),- bbox=core_local_bbox,- visual_row_id=0,- ),- models._VisualRow(- fragments=[models._Fragment(note_line.text, note_local_bbox, note_local_bbox, 1, 1)],- center_y=geometry._bbox_center_y(note_local_bbox),- bbox=note_local_bbox,- visual_row_id=1,- ),- ]- return rows, [core_line, note_line, *body_lines], rule_bbox, {0}, page_size--- ("text", "expected"),- (("7 neutral", "7"), ("(q) neutral", "q"), ("xy: neutral", "xy")),-)-def test_auxiliary_table_note_marker_is_unicode_generic(text: str, expected: str) -> None:- """验证辅助标记仅受通用 Unicode 形态约束,具体字符变化不影响提取。"""-- assert tables._extract_auxiliary_table_note_marker(text) == expected--- ("marker", "reference_mode"),- (("7", "superscript"), ("q", "compact"), ("xy", "compact")),-)-def test_auxiliary_table_note_requires_neutral_core_reference(- marker: str,- reference_mode: str,-) -> None:- """验证中性标记经上标或紧凑单元格确认后可以启动表注链。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- marker,- reference_mode,- )-- selected = tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )-- assert [tables._visual_row_text(row) for row in selected] == [f"{marker} neutral explanation"]---def test_auxiliary_table_note_rejects_marker_without_core_reference() -> None:- """验证紧邻表格的短标记正文在缺少表内引用时不能启动表注链。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "7",- "none",- )-- assert (- tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )- == []- )---def test_superscript_reference_requires_smaller_raised_glyph() -> None:- """验证普通基线上的同字符不能被当成表内上标引用。"""-- _rows, lines, _rule_bbox, _core_indices, page_size = _table_note_reference_fixture(- "7",- "superscript",- )- core_line = lines[0]- for char in core_line.chars:- if str(char.get("char")) == "7":- char["bbox"] = (42.0, 25.0, 49.0, 35.0)-- assert not tables._line_has_superscript_marker(core_line, "7", page_size, 0)--[email protected]("note_height", [10.0, 14.0])-def test_auxiliary_table_note_rejects_body_or_title_sized_first_row(- note_height: float,-) -> None:- """验证具有表内引用的普通正文或标题字号行仍不能启动表注链。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "q",- "compact",- note_height=note_height,- )-- assert (- tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )- == []- )---def test_auxiliary_table_note_rejects_loose_first_gap() -> None:- """验证辅助标记首行距超过四分之三局部行高时立即停止扩张。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "q",- "compact",- )- late_bbox = (0.0, 57.0, 80.0, 65.0)- lines[1].bbox = late_bbox- rows[1] = models._VisualRow(- fragments=[models._Fragment(lines[1].text, late_bbox, late_bbox, 1, 1)],- center_y=geometry._bbox_center_y(late_bbox),- bbox=late_bbox,- visual_row_id=1,- )-- assert (- tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )- == []- )---def test_auxiliary_table_note_requires_smaller_than_body_reference() -> None:- """验证辅助标记首行还必须显著小于同方向正文参考高度。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "q",- "compact",- )- for line in lines[2:]:- line.effective_height = 8.5-- assert (- tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )- == []- )---def test_auxiliary_table_note_uses_clipped_corridor_projection() -> None:- """验证另一栏短标记不能借表格栏内片段制造虚假的整行投影证据。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "q",- "compact",- )- outside_bbox = (140.0, 51.0, 190.0, 59.0)- inside_bbox = (10.0, 51.0, 70.0, 59.0)- rows[1] = models._VisualRow(- fragments=[- models._Fragment("q outside", outside_bbox, outside_bbox, 1, 1),- models._Fragment("inside continuation", inside_bbox, inside_bbox, 6, 1),- ],- center_y=55.0,- bbox=geometry._bbox_union(outside_bbox, inside_bbox),- visual_row_id=1,- )- lines.append(- models._LineItem(- text="inside continuation",- bbox=inside_bbox,- angle=0,- source_index=6,- effective_height=8.0,- font_signature=("Note", 0),- font_coverage=1.0,- )- )-- assert (- tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 0,- )- == []- )---def test_rotated_auxiliary_table_note_uses_local_superscript_geometry() -> None:- """验证旋转表格先转入局部正向坐标后仍可确认上标引用。"""-- rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(- "7",- "superscript",- angle=90,- )-- selected = tables._collect_footnote_rows(- rows,- lines,- rule_bbox,- 8.0,- core_indices,- page_size,- 90,- )-- assert [tables._visual_row_text(row) for row in selected] == ["7 neutral explanation"]---def test_table_note_chain_cannot_expand_beyond_ten_line_heights() -> None:- """验证表注续行链即使字体和行距稳定也不能无限向页面底部扩张。"""-- lines: list[models._LineItem] = []- rows: list[models._VisualRow] = []- specs = [("Note: neutral", (0.0, 51.0, 80.0, 59.0))]- specs.extend((f"continuation-{index}", (0.0, 59.5 + 8.5 * index, 80.0, 67.5 + 8.5 * index)) for index in range(12))- for source_index, (text, bbox) in enumerate(specs):- lines.append(- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=8.0,- font_signature=("Note", 0),- font_coverage=1.0,- )- )- rows.append(- models._VisualRow(- fragments=[models._Fragment(text, bbox, bbox, source_index, source_index)],- center_y=geometry._bbox_center_y(bbox),- bbox=bbox,- visual_row_id=source_index,- )- )-- selected = tables._collect_footnote_rows(- rows,- lines,- (0.0, 0.0, 100.0, 50.0),- 8.0,- set(),- (200.0, 200.0),- 0,- )-- assert selected- assert len(selected) < len(rows)- assert selected[-1].bbox[3] <= 130.0---def test_table_note_chain_stops_at_font_and_size_transition() -> None:- """验证表注续行不能跨越字体字号突变的标题或后续正文。"""-- specs = [- ("Note: neutral marker", (0.0, 52.0, 60.0, 60.0), ("Note", 0), 8.0),- ("neutral continuation", (0.0, 61.0, 65.0, 69.0), ("Note", 0), 8.0),- ("section barrier", (0.0, 70.0, 45.0, 84.0), ("Heading", 0), 14.0),- ("ordinary body", (10.0, 85.0, 100.0, 95.0), ("Body", 0), 10.0),- ]- lines: list[models._LineItem] = []- rows: list[models._VisualRow] = []- for source_index, (text, bbox, font, height) in enumerate(specs):- lines.append(- models._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=height,- font_signature=font,- font_coverage=1.0,- )- )- fragment = models._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=source_index,- )- rows.append(- models._VisualRow(- fragments=[fragment],- center_y=geometry._bbox_center_y(bbox),- bbox=bbox,- visual_row_id=source_index,- )- )-- selected = tables._collect_footnote_rows(- rows,- lines,- (0.0, 0.0, 100.0, 50.0),- 10.0,- set(),- (100.0, 100.0),- 0,- )-- assert [tables._visual_row_text(row) for row in selected] == [- "Note: neutral marker",- "neutral continuation",- ]---def test_numeric_body_row_cannot_start_table_note_chain() -> None:- """验证数字开头正文即使紧邻表格下边界也不能独立启动表注扩张。"""-- bbox = (0.0, 52.0, 80.0, 62.0)- line = models._LineItem(- text="5 ordinary numbered body",- bbox=bbox,- angle=0,- source_index=0,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- row = models._VisualRow(- fragments=[models._Fragment(line.text, bbox, bbox, 0, 0)],- center_y=geometry._bbox_center_y(bbox),- bbox=bbox,- visual_row_id=0,- )-- assert (- tables._collect_footnote_rows(- [row],- [line],- (0.0, 0.0, 100.0, 50.0),- 10.0,- set(),- (100.0, 100.0),- 0,- )- == []- )--[email protected]("projection_mode", ["empty", "error"])-def test_failed_table_projection_does_not_claim_text(- monkeypatch: pytest.MonkeyPatch,- projection_mode: str,-) -> None:- """验证投影为空或抛错时完整回滚候选,文本行仍可进入正文路径。"""-- lines = [- models._LineItem(- text="cell",- bbox=(10.0, 20.0, 30.0, 30.0),- angle=0,- source_index=0,- effective_height=10.0,- ),- models._LineItem(- text="Table 1",- bbox=(10.0, 5.0, 30.0, 15.0),- angle=0,- source_index=1,- effective_height=10.0,- ),- ]- source = models._PageSource(- page_size=(100.0, 100.0),- lines=lines,- chars=[],- drawing_lines=[],- )- candidate = models._TableCandidate(- bbox=(0.0, 0.0, 50.0, 50.0),- local_bbox=(0.0, 0.0, 50.0, 50.0),- angle=0,- score=1.0,- core_bbox=(0.0, 20.0, 50.0, 50.0),- line_indices={0},- annotations=[- models._TableAnnotation(- kind="caption",- bbox=(10.0, 5.0, 30.0, 15.0),- line_indices={1},- )- ],- )- projection = MagicMock(return_value="")- if projection_mode == "error":- projection.side_effect = RuntimeError("projection failed")- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- blocks, annotation_blocks, claimed = tables._materialize_table_blocks(- source,- [candidate],- )-- assert blocks == []- assert annotation_blocks == []- assert claimed == set()- assert projection.call_args.args[0] is source.charsdiff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pydeleted file mode 100644index 343eb8ba..00000000--- a/tests/unittest/test_flash_pdf_text_blocks.py+++ /dev/null@@ -1,3662 +0,0 @@-from __future__ import annotations--from dataclasses import replace--import pytest--from docvortex.analyzers.native.pdf import geometry-from docvortex.analyzers.native.pdf import line_layout-from docvortex.analyzers.native.pdf import line_merging-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import native_text-from docvortex.analyzers.native.pdf import pipeline-from docvortex.analyzers.native.pdf import text_blocks---from _flash_pdf_test_utils import (- _text_line,-)---def _span_text_block(- content: str,- bbox: tuple[float, float, float, float],-) -> dict[str, object]:- """构造全宽 span 正文回并测试使用的最小内部文本块。"""-- return {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": content,- "_visual_row_ids": set(),- "_single_run_row_id": None,- "_local_line_bboxes": [bbox],- "_line_heights": [4.0],- "_font_signatures": {("Body", 0)},- "_inline_math_regions": [],- "_lane_interval": (0.0, 100.0),- "_lane_is_span": True,- "_hard_break_before": False,- "_protected_hard_break_before": False,- "_hanging_indent_group": None,- "_leading_emphasis_start": False,- }---def test_hanging_indent_groups_neutral_entries_and_ignores_centered_heading() -> None:- """验证不含序号的重复悬挂缩进逐条分组,且居中标题不参与条目。"""-- body_font = ("Body", 0)- italic_font = ("BodyItalic", 1)- lines = [- _text_line(- "Centered heading",- (35.0, 0.0, 85.0, 10.0),- 0,- font_signature=("Heading", 0),- font_coverage=1.0,- ),- _text_line("Alpha begins", (0.0, 20.0, 100.0, 30.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "alpha italic continuation",- (15.0, 30.0, 100.0, 40.0),- 2,- font_signature=italic_font,- font_coverage=1.0,- ),- _text_line("alpha closes", (15.0, 40.0, 70.0, 50.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("Beta begins", (0.0, 50.0, 100.0, 60.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("beta continues", (15.0, 60.0, 100.0, 70.0), 5, font_signature=body_font, font_coverage=1.0),- _text_line("Gamma begins", (0.0, 70.0, 100.0, 80.0), 6, font_signature=body_font, font_coverage=1.0),- _text_line("gamma continues", (15.0, 80.0, 100.0, 90.0), 7, font_signature=body_font, font_coverage=1.0),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 120.0))-- assert 0 not in group_map- assert [group_map[index] for index in range(1, 8)] == [0, 0, 0, 1, 1, 2, 2]- assert [block["content"] for block in blocks] == [- "Centered heading",- "Alpha begins alpha italic continuation alpha closes",- "Beta begins beta continues",- "Gamma begins gamma continues",- ]---def test_nested_columns_ignore_intervening_full_width_metadata_band() -> None:- """验证左右栏行交错时,中间全宽元数据簇不阻断局部双栏推断。"""-- lines = [- _text_line("full width", (0.0, 0.0, 100.0, 10.0), 0),- *[- _text_line(- f"left {index}",- (0.0, 30.0 + 12.0 * index, 45.0, 40.0 + 12.0 * index),- 1 + 2 * index,- )- for index in range(4)- ],- *[- _text_line(- f"right {index}",- (55.0, 30.0 + 12.0 * index, 100.0, 40.0 + 12.0 * index),- 2 + 2 * index,- )- for index in range(4)- ],- _text_line("author one", (20.0, 100.0, 80.0, 110.0), 20),- _text_line("author two", (20.0, 112.0, 80.0, 122.0), 21),- _text_line("author three", (20.0, 124.0, 80.0, 134.0), 22),- ]-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 100.0,- 10.0,- )- regular = sorted(- (- lane- for lane in lanes- if not lane.is_span and len(lane.lines) >= 4 and min(item[1][1] for item in lane.lines) >= 30.0- ),- key=lambda lane: lane.left,- )-- assert [(lane.left, lane.right) for lane in regular[:2]] == [- (0.0, 45.0),- (55.0, 100.0),- ]---def test_paragraph_formula_context_merges_dense_same_lane_text() -> None:- """验证复杂行内分式及其同栏前后正文恢复为一个文本块。"""-- def block(- content: str,- bbox: tuple[float, float, float, float],- ) -> dict[str, object]:- """构造含栏带和行框的最小文本块。"""-- return {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": content,- "_local_line_bboxes": [bbox],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (0.0, 100.0),- "_lane_is_span": False,- "_hard_break_before": False,- "_leading_emphasis_start": False,- }-- blocks = [- block("prefix", (0.0, 0.0, 30.0, 10.0)),- block("body:", (0.0, 10.0, 100.0, 20.0)),- block("I=ΔT/ΔH", (0.0, 21.0, 100.0, 31.0)),- block("tail", (0.0, 32.0, 100.0, 42.0)),- {- **block("other lane", (120.0, 0.0, 220.0, 10.0)),- "_lane_interval": (120.0, 220.0),- },- ]- blocks[2]["_paragraph_formula_context"] = True-- merged = text_blocks._merge_paragraph_formula_context_blocks(- blocks,- (220.0, 100.0),- )-- assert [item["content"] for item in merged] == [- "prefix body: I=ΔT/ΔH tail",- "other lane",- ]--[email protected]("angle", [90, 270])-def test_rotated_paragraph_formula_context_uses_upright_gap(- angle: int,-) -> None:- """验证旋转公式上下文只合并正向坐标中真正相邻的同栏正文。"""-- page_size = (200.0, 200.0)-- def block(- content: str,- local_bbox: tuple[float, float, float, float],- *,- formula_context: bool = False,- ) -> dict[str, object]:- """构造页面框与正向行框分离的旋转文本块。"""-- return {- "type": "text",- "bbox": geometry._rotate_bbox_from_upright(- local_bbox,- page_size,- angle,- ),- "angle": angle,- "content": content,- "_local_line_bboxes": [local_bbox],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (0.0, 80.0),- "_lane_is_span": False,- "_hard_break_before": False,- "_paragraph_formula_context": formula_context,- }-- adjacent = text_blocks._merge_paragraph_formula_context_blocks(- [- block("formula", (0.0, 0.0, 80.0, 10.0), formula_context=True),- block("adjacent body", (0.0, 11.0, 80.0, 21.0)),- ],- page_size,- )- distant = text_blocks._merge_paragraph_formula_context_blocks(- [- block("formula", (0.0, 0.0, 80.0, 10.0), formula_context=True),- block("distant body", (0.0, 100.0, 80.0, 110.0)),- ],- page_size,- )- missing_geometry_seed = block(- "formula",- (0.0, 0.0, 80.0, 10.0),- formula_context=True,- )- missing_geometry_seed.pop("_local_line_bboxes")- missing_geometry = text_blocks._merge_paragraph_formula_context_blocks(- [- missing_geometry_seed,- block("adjacent body", (0.0, 11.0, 80.0, 21.0)),- ],- page_size,- )-- assert [item["content"] for item in adjacent] == ["formula adjacent body"]- assert adjacent[0]["bbox"] == geometry._rotate_bbox_from_upright(- (0.0, 0.0, 80.0, 21.0),- page_size,- angle,- )- assert [item["content"] for item in distant] == [- "formula",- "distant body",- ]- assert [item["content"] for item in missing_geometry] == [- "formula",- "adjacent body",- ]---def test_full_width_span_text_merges_without_terminal_punctuation_dependency() -> None:- """验证同栏满宽 span 正文可跨句号连续回并,并沿用英文断词恢复。"""-- blocks = [- _span_text_block(- "Abstract first sentence.",- (0.0, 0.0, 90.0, 10.0),- ),- _span_text_block(- "Continuation remains in the same paragraph.",- (0.0, 16.0, 90.0, 26.0),- ),- _span_text_block(- "Another impor-",- (0.0, 32.0, 90.0, 42.0),- ),- _span_text_block(- "tant detail",- (0.0, 48.0, 90.0, 58.0),- ),- {- **_span_text_block(- "Keywords: separate metadata",- (0.0, 64.0, 90.0, 74.0),- ),- "_lane_is_span": False,- "_hard_break_before": True,- "_protected_hard_break_before": True,- },- ]-- merged = text_blocks._merge_unterminated_text_components(- blocks,- )-- assert [block["content"] for block in merged] == [- "Abstract first sentence. Continuation remains in the same paragraph. Another important detail",- "Keywords: separate metadata",- ]--- "barrier",- [- "hard_break",- "protected_break",- "leading_emphasis",- "font_conflict",- "narrow_row",- "different_lane",- "different_angle",- "labelled_metadata",- "intervening_block",- "ordinary_lane_terminal",- ],-)-def test_full_width_span_text_respects_structural_barriers(- barrier: str,-) -> None:- """验证 span 回并仍受硬边界、栏带、字体、宽度和阻隔块约束。"""-- first = _span_text_block(- "First sentence.",- (0.0, 0.0, 90.0, 10.0),- )- second = _span_text_block(- "Second sentence",- (0.0, 16.0, 90.0, 26.0),- )- blocks = [first, second]- if barrier == "hard_break":- second["_hard_break_before"] = True- elif barrier == "protected_break":- second["_protected_hard_break_before"] = True- elif barrier == "leading_emphasis":- second["_leading_emphasis_start"] = True- elif barrier == "font_conflict":- second["_font_signatures"] = {("Other", 0)}- elif barrier == "narrow_row":- second["bbox"] = (0.0, 16.0, 79.0, 26.0)- second["_local_line_bboxes"] = [second["bbox"]]- elif barrier == "different_lane":- second["_lane_interval"] = (0.0, 120.0)- elif barrier == "different_angle":- second["angle"] = 90- elif barrier == "labelled_metadata":- second["content"] = "Keywords: separate metadata"- elif barrier == "intervening_block":- blocks.insert(- 1,- {- **_span_text_block(- "visual barrier",- (0.0, 11.0, 90.0, 15.0),- ),- "type": "caption",- },- )- elif barrier == "ordinary_lane_terminal":- first["_lane_is_span"] = False- second["_lane_is_span"] = False-- merged = text_blocks._merge_unterminated_text_components(- blocks,- )-- assert not any(- "First sentence." in str(block.get("content") or "") and "Second sentence" in str(block.get("content") or "")- for block in merged- )---def test_hanging_indent_accepts_reference_spacing_and_italic_tail() -> None:- """验证 1.25 倍行高的参考文献间距不会拆掉前一条斜体尾行。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "Alpha begins",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "alpha continues",- (15.0, 10.0, 100.0, 20.0),- 1,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "alpha italic tail",- (15.0, 20.0, 75.0, 30.0),- 2,- font_signature=("BodyItalic", 1),- font_coverage=1.0,- ),- _text_line(- "Beta begins",- (0.0, 42.5, 100.0, 52.5),- 3,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "beta continues",- (15.0, 52.5, 100.0, 62.5),- 4,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "Gamma begins",- (0.0, 75.0, 100.0, 85.0),- 5,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "gamma continues",- (15.0, 85.0, 100.0, 95.0),- 6,- font_signature=body_font,- font_coverage=1.0,- ),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 120.0))-- assert [group_map[index] for index in range(7)] == [0, 0, 0, 1, 1, 2, 2]- assert [block["content"] for block in blocks] == [- "Alpha begins alpha continues alpha italic tail",- "Beta begins beta continues",- "Gamma begins gamma continues",- ]---def test_first_line_indent_and_large_gap_do_not_form_hanging_indent_groups() -> None:- """验证普通首行缩进及跨越大间距的行不会误触发悬挂缩进模式。"""-- lines = [- _text_line("First paragraph", (15.0, 0.0, 100.0, 10.0), 0),- _text_line("first continuation", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("Second paragraph", (15.0, 20.0, 100.0, 30.0), 2),- _text_line("second continuation", (0.0, 30.0, 100.0, 40.0), 3),- _text_line("Detached start", (0.0, 70.0, 100.0, 80.0), 4),- _text_line("detached continuation", (15.0, 80.0, 100.0, 90.0), 5),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- assert text_blocks._build_hanging_indent_group_map(lane, [], []) == {}---def test_hanging_indent_keeps_confirmed_entries_before_plain_trailing_paragraph() -> None:- """验证尾随普通左对齐段落不会让此前已确认的悬挂缩进条目整体失效。"""-- lines = [- _text_line("entry one", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("entry one tail", (15.0, 10.0, 100.0, 20.0), 1),- _text_line("entry two", (0.0, 20.0, 100.0, 30.0), 2),- _text_line("entry two tail", (15.0, 30.0, 100.0, 40.0), 3),- _text_line("entry three", (0.0, 40.0, 100.0, 50.0), 4),- _text_line("entry three tail", (15.0, 50.0, 100.0, 60.0), 5),- _text_line("plain trailing paragraph", (0.0, 60.0, 100.0, 70.0), 6),- _text_line("plain continuation", (0.0, 70.0, 100.0, 80.0), 7),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])-- assert [group_map[index] for index in range(6)] == [0, 0, 1, 1, 2, 2]- assert 6 not in group_map- assert 7 not in group_map---def test_full_width_hanging_entries_can_start_after_aligned_prose() -> None:- """验证近满栏的重复悬挂条目可在同左缘正文之后启动,普通单行仍留在前文。"""-- lines = [- _text_line("plain disclosure", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("plain single row", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("first entry", (0.0, 20.0, 100.0, 30.0), 2),- _text_line("first entry tail", (15.0, 30.0, 70.0, 40.0), 3),- _text_line("second entry", (0.0, 40.0, 100.0, 50.0), 4),- _text_line("second entry tail", (15.0, 50.0, 80.0, 60.0), 5),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])-- assert 0 not in group_map- assert 1 not in group_map- assert [group_map[index] for index in range(2, 6)] == [0, 0, 1, 1]---def test_bullet_rows_remain_independent_text_blocks() -> None:- """验证近满栏项目符号为显式段界,连续披露条目不会在后处理阶段串联。"""-- lines = [- _text_line("• first disclosure.", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("• second disclosure.", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("• third disclosure.", (0.0, 20.0, 100.0, 30.0), 2),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))-- assert [block["content"] for block in blocks] == [- "• first disclosure.",- "• second disclosure.",- "• third disclosure.",- ]---def test_compact_bullet_rows_keep_one_list_block() -> None:- """验证短项目符号列表继续按紧凑列表成块,不套用近满栏披露条目的边界。"""-- lines = [- _text_line("• first tool", (0.0, 0.0, 45.0, 10.0), 0),- _text_line("• second tool", (0.0, 10.0, 48.0, 20.0), 1),- _text_line("• third tool", (0.0, 20.0, 42.0, 30.0), 2),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- assert text_blocks._explicit_text_break_sources(lane) == set()---def test_adjacent_compact_label_rows_remain_separate() -> None:- """验证连续的短键值元数据行形成独立块,不因缺少句末标点而串联。"""-- lines = [- _text_line("递交截止时间:09:30", (0.0, 0.0, 55.0, 10.0), 0),- _text_line("递交方式:paper", (0.0, 10.0, 60.0, 20.0), 1),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- assert text_blocks._explicit_text_break_sources(lane) == {1}---def test_twelve_point_gutter_keeps_two_text_lanes_and_paragraphs_separate() -> None:- """验证约 12pt 行高和栏沟仍识别为双栏,左右正文不会交叉拼接。"""-- lines: list[models._LineItem] = []- for row_index, top in enumerate((100.0, 112.0, 124.0)):- lines.extend(- [- _text_line(f"left-{row_index}", (49.0, top, 300.0, top + 12.0), row_index * 2),- _text_line(f"right-{row_index}", (312.0, top, 563.0, top + 12.0), row_index * 2 + 1),- ]- )-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 612.0,- 12.0,- )- blocks = text_blocks._build_text_blocks(lines, [], (612.0, 792.0))-- regular_lanes = [lane for lane in lanes if not lane.is_span]- assert [(lane.left, lane.right) for lane in regular_lanes] == [- (49.0, 300.0),- (312.0, 563.0),- ]- assert len(blocks) == 2- assert all("right-" not in block["content"] for block in blocks if "left-" in block["content"])- assert all("left-" not in block["content"] for block in blocks if "right-" in block["content"])---def test_cross_column_caption_tail_stays_in_span_lane_and_one_text_block() -> None:- """验证仅占单栏宽的短 caption 尾行仍回收到连续跨栏 caption。"""-- lines: list[models._LineItem] = [- _text_line("caption line one", (0.0, 10.0, 200.0, 20.0), 0),- _text_line("caption line two", (0.0, 22.0, 200.0, 32.0), 1),- _text_line("caption tail", (0.0, 34.0, 70.0, 44.0), 2),- _text_line("ordinary left short line", (0.0, 70.0, 70.0, 80.0), 3),- ]- for row_index, top in enumerate((100.0, 112.0, 124.0, 136.0, 148.0)):- lines.extend(- [- _text_line(- f"left body {row_index}",- (0.0, top, 90.0, top + 10.0),- 4 + 2 * row_index,- ),- _text_line(- f"right body {row_index}",- (110.0, top, 200.0, top + 10.0),- 5 + 2 * row_index,- ),- ]- )-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 200.0,- 10.0,- )- blocks = text_blocks._build_text_blocks(lines, [], (200.0, 180.0))-- span_lane = next(lane for lane in lanes if lane.is_span)- assert {line.source_index for line, _bbox in span_lane.lines} == {0, 1, 2}- assert all(line.source_index != 3 for line, _bbox in span_lane.lines)- caption_blocks = [block for block in blocks if "caption line one" in block["content"]]- assert len(caption_blocks) == 1- assert "caption tail" in caption_blocks[0]["content"]---def test_slight_bbox_overlap_contributes_to_gap_estimate_and_separates_caption() -> None:- """验证轻微纵向重叠按零净空统计,短图例不会与后续长 caption 合并。"""-- body_lines = [- _text_line("body-0", (312.0, 0.0, 563.0, 12.0), 0),- _text_line("body-1", (312.0, 11.95, 563.0, 23.95), 1),- _text_line("body-2", (312.0, 23.9, 563.0, 35.9), 2),- ]- legend = _text_line("Right camera", (458.0, 60.0, 509.0, 72.0), 3)- caption = _text_line(- "Figure 1: a long caption spanning the full column",- (312.0, 79.0, 563.0, 91.0),- 4,- )- lane = models._TextLane(- left=312.0,- right=563.0,- lines=[*((line, line.bbox) for line in body_lines), (legend, legend.bbox), (caption, caption.bbox)],- )-- regular_gap, gap_mad = line_layout._estimate_lane_gap(lane)-- assert (regular_gap, gap_mad) == (0.0, 0.0)- assert not line_layout._should_connect_text_rows(- (legend, legend.bbox),- (caption, caption.bbox),- lane,- regular_gap,- gap_mad,- [],- [],- )---def test_local_previous_left_edge_exposes_first_line_indent() -> None:- """验证局部版心左移后仍能识别下一行相对前一物理行的首行缩进。"""-- previous = _text_line(- "previous paragraph without punctuation",- (0.0, 0.0, 80.0, 10.0),- 0,- )- current = _text_line(- "Indented new paragraph",- (10.0, 12.0, 100.0, 22.0),- 1,- )- lane = models._TextLane(- left=20.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert not line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 2.0,- 0.0,- [],- [],- )---def test_terminal_full_lane_row_breaks_after_abnormal_clearance() -> None:- """验证满栏句末行后的净空超过常规间距半行高时强制另起段落。"""-- previous = _text_line("Figure caption ends.", (0.0, 0.0, 100.0, 10.0), 0)- current = _text_line("new paragraph fills the lane", (0.0, 17.0, 100.0, 27.0), 1)- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert not line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 1.0,- 0.0,- [],- [],- )---def test_effective_height_connects_body_line_after_tall_math_glyph() -> None:- """验证高数学字形拉长原始 bbox 时仍按有效行高连接下一正文行。"""-- previous = _text_line(- "support window Ωp centered at the pixel",- (312.0, 100.0, 563.0, 118.82),- 0,- effective_height=12.0,- )- current = _text_line(- "by",- (312.0, 112.0, 325.0, 124.0),- 1,- effective_height=12.0,- )- lane = models._TextLane(- left=312.0,- right=563.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert current.bbox[1] - previous.bbox[3] == pytest.approx(-6.82)- assert line_layout._effective_text_row_gap(- (previous, previous.bbox),- (current, current.bbox),- ) == pytest.approx(0.0)- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_body_row_gap_uses_canonical_baseline_without_changing_semantic_gap() -> None:- """验证正文连接使用 baseline 节奏,而其它语义路径仍保留 bbox 净空。"""-- previous = _text_line(- "previous full body row",- (0.0, 0.0, 100.0, 24.0),- 0,- effective_height=24.0,- )- current = _text_line(- "current full body row",- (0.0, 30.0, 100.0, 54.0),- 1,- effective_height=24.0,- )- for line, baseline in ((previous, 20.0), (current, 36.0)):- line.em_height = 10.0- line.style_scale_repaired = True- line.baseline = baseline- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert (- line_layout._effective_text_row_gap(- (previous, previous.bbox),- (current, current.bbox),- )- == 20.0- )- assert (- line_layout._effective_body_text_row_gap(- (previous, previous.bbox),- (current, current.bbox),- )- == 6.0- )- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 6.0,- 0.0,- [],- [],- )---def test_cross_lane_short_tail_returns_to_unique_preceding_lane() -> None:- """验证完整落在唯一正文栏内的短尾不会继续停留在 span lane。"""-- previous = _text_line(- "full preceding row",- (0.0, 10.0, 100.0, 20.0),- 0,- visual_row_id=1,- effective_height=10.0,- )- tail = _text_line(- "short tail",- (0.0, 20.0, 40.0, 30.0),- 1,- visual_row_id=2,- effective_height=10.0,- )- previous.baseline = 20.0- tail.baseline = 30.0- body_lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox)],- )- span_lane = models._TextLane(- left=0.0,- right=180.0,- lines=[(tail, tail.bbox)],- is_span=True,- )-- line_layout._reattach_cross_lane_short_tails(- [body_lane, span_lane],- 10.0,- )-- assert [line.text for line, _bbox in body_lane.lines] == [- "full preceding row",- "short tail",- ]- assert span_lane.lines == []---def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:- """验证紧贴上下标与低覆盖率同行后缀恢复,同时保留外置公式编号。"""-- script_lines = [- _text_line("O(ω", (0.0, 0.0, 100.0, 18.8), 0, visual_row_id=0, effective_height=12.0),- _text_line("2", (100.3, 0.8, 104.0, 7.0), 1, visual_row_id=1, effective_height=6.0),- _text_line("Di", (0.0, 40.0, 100.0, 52.0), 2, visual_row_id=2, effective_height=12.0),- _text_line("p", (96.9, 46.0, 101.0, 53.0), 3, visual_row_id=3, effective_height=7.0),- ]-- merged_scripts = native_text._merge_native_inline_scripts(script_lines, (200.0, 100.0))-- assert [line.text for line in merged_scripts] == ["O(ω2", "Dip"]- assert not any(line.restored_inline_cluster for line in merged_scripts)-- caption_prefix = _text_line(- "(4",- (0.0, 70.0, 12.0, 82.0),- 4,- font_signature=("Body", 0),- font_coverage=1.0,- )- caption_suffix = _text_line(- "th row).",- (12.1, 70.0, 50.0, 82.0),- 5,- font_signature=("Body", 0),- font_coverage=0.7,- )- formula_body = _text_line(- "formula",- (0.0, 90.0, 50.0, 102.0),- 6,- font_signature=("Math", 0),- font_coverage=1.0,- )- formula_number = _text_line(- "(4)",- (51.2, 90.0, 60.0, 102.0),- 7,- font_signature=("Body", 0),- font_coverage=1.0,- )-- assert line_merging._can_merge_same_baseline_pair(- caption_prefix,- caption_prefix.bbox,- caption_suffix,- caption_suffix.bbox,- [],- )- assert not line_merging._can_merge_same_baseline_pair(- formula_body,- formula_body.bbox,- formula_number,- formula_number.bbox,- [],- )---def test_title_resolved_visual_row_merges_sparse_short_prefix() -> None:- """验证同视觉行的短前缀与远端宽正文按字体族和基线恢复。"""-- lines = [- _text_line(- "prefix",- (0.0, 0.0, 15.0, 10.0),- 0,- visual_row_id=7,- run_index=0,- split_from_row=True,- font_signature=("SimSun", 0),- font_coverage=1.0,- ),- _text_line(- "wide body",- (60.0, 0.0, 140.0, 10.0),- 1,- visual_row_id=7,- run_index=1,- split_from_row=True,- font_signature=("ABCDEF+SimSun", 0),- font_coverage=1.0,- ),- ]-- merged = line_merging._merge_title_resolved_visual_rows(- lines,- (200.0, 100.0),- )-- assert len(merged) == 1- assert merged[0].text == "prefix wide body"--- "failure_mode",- [- "font-conflict",- "different-row",- "protected-boundary",- "two-wide-runs",- ],-)-def test_title_resolved_visual_row_rejects_weak_sparse_prefix(- failure_mode: str,-) -> None:- """验证字体、行身份、保护边界或前缀宽度不符时保留拆分。"""-- prefix_bbox = (0.0, 0.0, 40.0, 10.0) if failure_mode == "two-wide-runs" else (0.0, 0.0, 15.0, 10.0)- lines = [- _text_line(- "prefix",- prefix_bbox,- 0,- visual_row_id=7,- run_index=0,- split_from_row=True,- preserve_split_boundary=(failure_mode == "protected-boundary"),- font_signature=("SimSun", 0),- font_coverage=1.0,- ),- _text_line(- "wide body",- (85.0, 0.0, 165.0, 10.0) if failure_mode == "two-wide-runs" else (60.0, 0.0, 140.0, 10.0),- 1,- visual_row_id=(8 if failure_mode == "different-row" else 7),- run_index=1,- split_from_row=True,- font_signature=(("OtherFont", 0) if failure_mode == "font-conflict" else ("ABCDEF+SimSun", 0)),- font_coverage=1.0,- ),- ]-- merged = line_merging._merge_title_resolved_visual_rows(- lines,- (200.0, 100.0),- )-- assert [line.text for line in merged] == [- "prefix",- "wide body",- ]---def test_canonical_reference_scale_merges_bracket_marker_but_not_plain_number() -> None:- """验证 loose 高度相同的括号引用可按 PDF 字号并入宿主,普通数字保持独立。"""-- def sized_line(- text: str,- bbox: tuple[float, float, float, float],- source_index: int,- font_size: float,- ) -> models._LineItem:- """构造带 PDF 字号证据的单字符原生行。"""-- line = _text_line(- text,- bbox,- source_index,- visual_row_id=source_index,- effective_height=12.0,- )- line.chars = [- {- "char": text[0],- "bbox": bbox,- "font": {- "name": "Fixture",- "flags": 0,- "size": font_size,- "weight": 400,- },- }- ] # type: ignore[list-item]- return line-- base = sized_line(- "TriviaQA",- (0.0, 10.0, 50.0, 22.0),- 0,- 10.0,- )- reference = sized_line(- "[38]",- (50.1, 5.0, 57.1, 14.0),- 1,- 6.0,- )- plain_number = sized_line(- "1",- (50.1, 5.0, 57.1, 14.0),- 2,- 6.0,- )-- merged_reference = native_text._merge_native_inline_scripts(- [base, reference],- (120.0, 100.0),- )- separate_number = native_text._merge_native_inline_scripts(- [- sized_line(- "TriviaQA",- (0.0, 10.0, 50.0, 22.0),- 0,- 10.0,- ),- plain_number,- ],- (120.0, 100.0),- )-- assert [line.text for line in merged_reference] == [- "TriviaQA[38]",- ]- assert [line.text for line in separate_number] == [- "TriviaQA",- "1",- ]---def test_same_repeated_indent_continues_after_terminal_punctuation() -> None:- """验证同一悬挂缩进锚点的紧邻尾行不会因前行句号被再次切开。"""-- previous = _text_line(- "first indented line.",- (20.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- )- current = _text_line(- "second indented line",- (20.0, 10.0, 80.0, 20.0),- 1,- effective_height=10.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_sparse_lane_terminal_gap_remains_paragraph_boundary() -> None:- """验证稀疏页不会把唯一的句号后大间距反向估计成常规行距。"""-- previous = _text_line(- "first generated paragraph.",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- )- current = _text_line(- "second generated paragraph",- (0.0, 18.0, 100.0, 28.0),- 1,- effective_height=10.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert not line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 8.0,- 0.0,- [],- [],- )---def test_list_intro_chain_splits_before_item_and_keeps_intro_together() -> None:- """验证列表前的连续引导段与冒号短尾合并,而编号项保持硬边界。"""-- lines = [- _text_line("paragraph continues", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("paragraph closes.", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("list introduction", (10.0, 20.0, 100.0, 30.0), 2),- _text_line("directions:", (0.0, 30.0, 25.0, 40.0), 3),- _text_line("(1) first item", (10.0, 40.0, 100.0, 50.0), 4),- _text_line("item continuation", (0.0, 50.0, 100.0, 60.0), 5),- ]-- blocks = text_blocks._build_text_blocks(- lines,- [],- (120.0, 100.0),- )-- assert [block["content"] for block in blocks] == [- "paragraph continues paragraph closes. list introduction directions:",- "(1) first item item continuation",- ]---def test_single_numbered_tail_merges_back_into_colon_line() -> None:- """验证没有续行的单个编号尾项回并冒号行,不被稀疏页段界永久拆开。"""-- lines = [- _text_line("scope includes:", (0.0, 0.0, 90.0, 10.0), 0),- _text_line("(001) only entry;", (10.0, 23.0, 70.0, 33.0), 1),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))-- assert [block["content"] for block in blocks] == [- "scope includes: (001) only entry;",- ]---def test_multiline_component_absorbs_aligned_short_tail() -> None:- """验证多行正文吸收同左缘的单行短尾,不要求短尾达到正文满栏宽度。"""-- lines = [- _text_line("body starts", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("body continues", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("short tail", (0.0, 35.0, 35.0, 45.0), 2),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))-- assert [block["content"] for block in blocks] == [- "body starts body continues short tail",- ]---def test_url_rows_continue_colon_introduction() -> None:- """验证冒号引导后的 URL 行继续属于前一正文块,即使 URL 自身不满栏。"""-- lines = [- _text_line("reference link:", (0.0, 0.0, 80.0, 10.0), 0),- _text_line("https://example.test/path", (0.0, 24.0, 55.0, 34.0), 1),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))-- assert [block["content"] for block in blocks] == [- "reference link: https://example.test/path",- ]---def test_low_overlap_detached_script_preserves_following_row_gap() -> None:- """验证低重叠外置字形按几何归入主体,且抬高的顶边不会拆断后继行。"""-- base = _text_line(- "Alpha",- (10.0, 10.0, 70.0, 20.8),- 0,- visual_row_id=0,- effective_height=10.8,- )- detached_script = _text_line(- "◇",- (70.0, 3.6, 74.2, 11.1),- 1,- visual_row_id=1,- effective_height=7.5,- )- following = _text_line(- "Beta",- (35.0, 22.0, 80.0, 34.0),- 2,- visual_row_id=2,- effective_height=10.8,- )-- merged = native_text._merge_native_inline_scripts(- [base, detached_script, following],- (120.0, 100.0),- )-- assert [line.text for line in merged] == ["Alpha◇", "Beta"]- assert merged[0].bbox == (10.0, 3.6, 74.2, 20.8)- assert merged[0].restored_inline_cluster- assert line_layout._effective_text_row_gap(- (merged[0], merged[0].bbox),- (following, following.bbox),- ) == pytest.approx(1.2)--- ("small_text", "small_bbox"),- [- pytest.param("wide", (50.0, 3.5, 62.0, 11.0), id="wide-token"),- pytest.param("◇", (53.0, 3.5, 57.2, 11.0), id="horizontal-gap"),- pytest.param("◇", (50.0, 0.0, 54.2, 7.5), id="vertical-gap"),- pytest.param("◇", (50.0, 12.0, 54.2, 19.5), id="same-baseline-cell"),- ],-)-def test_detached_script_geometry_rejects_ambiguous_small_runs(- small_text: str,- small_bbox: tuple[float, float, float, float],-) -> None:- """验证宽文本、远距文本和同行小单元格不能仅凭小字号并入主体。"""-- base = _text_line(- "Base",- (0.0, 10.0, 50.0, 22.0),- 0,- visual_row_id=0,- effective_height=12.0,- )- small = _text_line(- small_text,- small_bbox,- 1,- visual_row_id=1,- effective_height=7.5,- )-- merged = native_text._merge_native_inline_scripts([base, small], (120.0, 100.0))-- assert [line.text for line in merged] == ["Base", small_text]- assert not any(line.restored_inline_cluster for line in merged)---def test_full_lane_large_height_mismatch_only_recovers_aligned_continuation() -> None:- """验证满栏混合字体 URL 可续接,而短公式与显式字体样式边界仍分离。"""-- previous = _text_line(- "video sequences have been made avail-",- (0.0, 0.0, 100.0, 12.0),- 0,- effective_height=12.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- full_width_url = _text_line(- "able at http://example.test/data",- (0.0, 12.0, 100.0, 24.0),- 1,- effective_height=7.69,- font_signature=("Mono", 0),- font_coverage=1.0,- )- short_formula = _text_line(- "x = 1",- (0.0, 12.0, 60.0, 24.0),- 2,- effective_height=7.69,- font_signature=("Math", 0),- font_coverage=1.0,- )- styled_reference = _text_line(- "italic bibliography continuation",- (0.0, 12.0, 100.0, 24.0),- 3,- effective_height=7.69,- font_signature=("BodyItalic", 1),- font_coverage=1.0,- )- lane = models._TextLane(left=0.0, right=100.0)-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (full_width_url, full_width_url.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert not line_layout._should_connect_text_rows(- (previous, previous.bbox),- (short_formula, short_formula.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert not line_layout._should_connect_text_rows(- (previous, previous.bbox),- (styled_reference, styled_reference.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_pdf_subset_font_variants_keep_full_rows_and_short_tail_connected() -> None:- """验证同字体族的 PDF 子集签名差异不会拆断满栏正文及其短尾行。"""-- first = _text_line(- "first full row",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=("ABCDEF+TimesNewRomanPSMT", 1),- font_coverage=1.0,- )- second = _text_line(- "second full row",- (0.0, 10.0, 100.0, 20.0),- 1,- font_signature=("TimesNewRomanPSMT", 29),- font_coverage=1.0,- )- tail = _text_line(- "short tail",- (0.0, 20.0, 45.0, 30.0),- 2,- font_signature=("GHIJKL+TimesNewRomanPSMT", 17),- font_coverage=1.0,- )- lane = models._TextLane(left=0.0, right=100.0)-- assert line_layout._should_connect_text_rows(- (first, first.bbox),- (second, second.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert line_layout._should_connect_text_rows(- (second, second.bbox),- (tail, tail.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_pdf_subset_font_short_tail_keeps_significant_weight_barrier() -> None:- """验证字体族相同但字重显著变化时,短尾续行仍保持硬分段。"""-- body = _text_line(- "full body row",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=("ABCDEF+Body", 1),- font_coverage=1.0,- dominant_font_weight=400.0,- )- emphasized_tail = _text_line(- "bold short row",- (0.0, 10.0, 45.0, 20.0),- 1,- font_signature=("GHIJKL+Body", 29),- font_coverage=1.0,- dominant_font_weight=700.0,- )- lane = models._TextLane(left=0.0, right=100.0)-- assert not line_layout._should_connect_text_rows(- (body, body.bbox),- (emphasized_tail, emphasized_tail.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_smaller_footnote_after_abnormal_gap_forces_text_block_break() -> None:- """验证字号不足前行 88% 且净空偏大时,正文与脚注强制分块。"""-- body = _text_line(- "body continuation",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- footnote = _text_line(- "small footnote",- (0.0, 16.0, 100.0, 24.7),- 1,- effective_height=8.7,- font_signature=("Body", 0),- font_coverage=1.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(body, body.bbox), (footnote, footnote.bbox)],- )-- assert not line_layout._should_connect_text_rows(- (body, body.bbox),- (footnote, footnote.bbox),- lane,- 3.0,- 0.0,- [],- [],- )---def test_overlapping_fraction_fragments_merge_with_ha_and_nb_body_hosts() -> None:- """验证 Ha、Nb 的上下分式碎片并回正文宿主,且普通后续行保持独立。"""-- body_font = ("Body", 0)- math_font = ("Math", 1)- lines = [- _text_line(- "Ha =",- (0.0, 10.0, 20.0, 20.0),- 0,- visual_row_id=0,- split_from_row=True,- effective_height=10.0,- font_signature=math_font,- font_coverage=0.67,- ),- _text_line(- "root",- (30.0, 0.0, 40.0, 12.0),- 1,- visual_row_id=0,- split_from_row=True,- effective_height=9.0,- font_signature=math_font,- font_coverage=0.57,- ),- _text_line(- "sigma",- (30.0, 9.0, 34.0, 16.0),- 2,- visual_row_id=1,- effective_height=7.0,- font_signature=math_font,- font_coverage=1.0,- ),- _text_line(- "mu",- (30.0, 16.0, 34.0, 23.0),- 3,- visual_row_id=2,- effective_height=7.0,- font_signature=math_font,- font_coverage=1.0,- ),- _text_line(- "denotes the Hartmann number",- (22.0, 3.0, 100.0, 25.0),- 4,- visual_row_id=3,- effective_height=10.0,- font_signature=body_font,- font_coverage=0.9,- ),- _text_line(- "Nb = numerator",- (0.0, 40.0, 42.0, 53.0),- 5,- visual_row_id=4,- effective_height=8.0,- font_signature=math_font,- font_coverage=0.6,- ),- _text_line(- "mu",- (30.0, 48.0, 34.0, 55.0),- 6,- visual_row_id=5,- effective_height=7.0,- font_signature=math_font,- font_coverage=1.0,- ),- _text_line(- "denotes the Brownian parameter",- (46.0, 43.0, 100.0, 53.0),- 7,- visual_row_id=6,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "ordinary following row",- (0.0, 70.0, 100.0, 80.0),- 8,- visual_row_id=7,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- merged = line_merging._merge_overlapping_inline_text_clusters(- lines,- (120.0, 100.0),- [],- )-- assert [line.source_index for line in merged] == [0, 5, 8]- assert merged[0].text == "Ha = root sigma mu denotes the Hartmann number"- assert merged[1].text == "Nb = numerator mu denotes the Brownian parameter"- assert all(line.restored_inline_cluster for line in merged[:2])- assert not any(line.text in {"sigma", "mu"} for line in merged)---def test_overlapping_delta_fraction_and_tail_form_one_text_block() -> None:- """验证同一物理行的分子分母恢复后可与下一行幅值说明组成单块。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "where, delta = numerator",- (0.0, 0.0, 32.0, 13.0),- 0,- visual_row_id=0,- effective_height=10.0,- font_signature=body_font,- font_coverage=0.73,- ),- _text_line(- "denominator displays the amplitude",- (28.0, 3.0, 100.0, 16.0),- 1,- visual_row_id=1,- effective_height=10.0,- font_signature=body_font,- font_coverage=0.86,- ),- _text_line(- "ratio.",- (0.0, 18.0, 20.0, 28.0),- 2,- visual_row_id=2,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- merged = line_merging._merge_overlapping_inline_text_clusters(- lines,- (120.0, 100.0),- [],- )- blocks = text_blocks._build_text_blocks(merged, [], (120.0, 100.0))-- assert len(merged) == 2- assert [block["content"] for block in blocks] == ["where, delta = numerator denominator displays the amplitude ratio."]---def test_overlapping_inline_pair_respects_table_and_physical_row_gap() -> None:- """验证二维碎片连接不会跨表格,也不会连接普通上下相邻正文行。"""-- first = _text_line("left", (0.0, 0.0, 40.0, 10.0), 0, effective_height=10.0)- same_row = _text_line("right", (60.0, 0.0, 100.0, 10.0), 1, effective_height=10.0)- next_row = _text_line("next", (0.0, 12.0, 40.0, 22.0), 2, effective_height=10.0)-- assert not line_merging._overlapping_inline_cluster_pair_is_connected(- (first, first.bbox),- (same_row, same_row.bbox),- 10.0,- [(45.0, -5.0, 55.0, 15.0)],- )- assert not line_merging._overlapping_inline_cluster_pair_is_connected(- (first, first.bbox),- (next_row, next_row.bbox),- 10.0,- [],- )---def test_hyphen_continuation_cannot_start_false_hanging_indent_entry() -> None:- """验证断词续行优先归前段,后续首行缩进说明和紧凑公式仍各自分块。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "linear equations in the trans-",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "verse direction.",- (0.0, 12.0, 40.0, 22.0),- 1,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "The expression starts here",- (12.0, 24.0, 100.0, 34.0),- 2,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "the stream function is given below:",- (0.0, 36.0, 75.0, 46.0),- 3,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "F = fraction",- (12.0, 48.0, 45.0, 55.0),- 4,- effective_height=7.0,- font_signature=("Math", 1),- font_coverage=0.5,- ),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])- blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))-- assert 1 not in group_map- assert [block["content"] for block in blocks] == [- "linear equations in the transverse direction.",- "The expression starts here the stream function is given below:",- "F = fraction",- ]---def test_local_two_column_band_survives_full_width_body_below() -> None:- """验证页面顶部局部双栏不会被下方通栏正文覆盖。"""-- lines: list[models._LineItem] = []- for row_index, top in enumerate((0.0, 12.0, 24.0, 36.0)):- lines.extend(- [- _text_line(f"left-{row_index}", (10.0, top, 90.0, top + 10.0), row_index * 2),- _text_line(f"right-{row_index}", (110.0, top, 190.0, top + 10.0), row_index * 2 + 1),- ]- )- lines.extend(- _text_line(f"wide-{row_index}", (10.0, top, 190.0, top + 10.0), 20 + row_index)- for row_index, top in enumerate((70.0, 82.0, 94.0, 106.0))- )-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 200.0,- 10.0,- )-- lane_texts = [{line.text for line, _bbox in lane.lines} for lane in lanes]- assert {f"left-{index}" for index in range(4)} in lane_texts- assert {f"right-{index}" for index in range(4)} in lane_texts- assert {f"wide-{index}" for index in range(4)} in lane_texts---def test_nested_lane_accepts_wider_one_sided_rows_and_expands_interval() -> None:- """验证窄图注推断的局部栏仍可接纳未进入另一栏的宽正文行。"""-- lines: list[models._LineItem] = []- for row_index, top in enumerate((0.0, 10.0, 20.0, 30.0, 40.0)):- lines.extend(- [- _text_line(- f"narrow-left-{row_index}",- (10.0, top, 55.0, top + 8.0),- row_index * 2,- ),- _text_line(- f"right-{row_index}",- (115.0, top, 190.0, top + 8.0),- row_index * 2 + 1,- ),- ]- )- lines.extend(- [- _text_line("wide-left-one", (10.0, 32.0, 105.0, 40.0), 20),- _text_line("wide-left-two", (10.0, 42.0, 105.0, 50.0), 21),- ]- )- lines.extend(- _text_line(- f"outer-{row_index}",- (10.0, top, 190.0, top + 8.0),- 30 + row_index,- )- for row_index, top in enumerate((90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0))- )-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 200.0,- 8.0,- )-- left_lane = next(lane for lane in lanes if any(line.text == "wide-left-one" for line, _bbox in lane.lines))- assert not left_lane.is_span- assert left_lane.right == pytest.approx(105.0)- assert {line.text for line, _bbox in left_lane.lines if line.text.startswith("wide-left")} == {- "wide-left-one",- "wide-left-two",- }---def test_regular_lanes_accept_wider_one_sided_rows_but_keep_gutter_crossing_span() -> None:- """验证普通双栏会扩展单侧栏宽,同时不吸收越过栏沟的通栏行。"""-- lines: list[models._LineItem] = []- for row_index, top in enumerate((0.0, 10.0, 20.0, 30.0, 40.0)):- lines.extend(- [- _text_line(- f"narrow-left-{row_index}",- (10.0, top, 55.0, top + 8.0),- row_index * 2,- ),- _text_line(- f"right-{row_index}",- (115.0, top, 190.0, top + 8.0),- row_index * 2 + 1,- ),- ]- )- lines.extend(- [- _text_line("wide-left-one", (10.0, 52.0, 105.0, 60.0), 20),- _text_line("wide-left-two", (10.0, 62.0, 105.0, 70.0), 21),- _text_line("crosses-gutter", (10.0, 74.0, 130.0, 82.0), 22),- ]- )-- lanes = line_layout._infer_text_lanes(- [(line, line.bbox) for line in lines],- 200.0,- 8.0,- )-- left_lane = next(lane for lane in lanes if any(line.text == "wide-left-one" for line, _bbox in lane.lines))- span_lane = next(lane for lane in lanes if any(line.text == "crosses-gutter" for line, _bbox in lane.lines))- assert not left_lane.is_span- assert left_lane.right == pytest.approx(105.0)- assert span_lane.is_span---def test_short_span_tail_reattaches_before_later_cross_layout_region() -> None:- """验证局部通栏段的短尾行不会因页面后续另有通栏行而留在单栏。"""-- first = _text_line("wide one", (10.0, 0.0, 190.0, 10.0), 0)- second = _text_line("wide two", (10.0, 10.0, 190.0, 20.0), 1)- tail = _text_line("tail", (10.0, 20.0, 50.0, 30.0), 2)- later = _text_line("later wide", (10.0, 80.0, 190.0, 90.0), 3)- parallel = _text_line("parallel", (110.0, 50.0, 190.0, 60.0), 4)- left_lane = models._TextLane(left=10.0, right=90.0, lines=[(tail, tail.bbox)])- right_lane = models._TextLane(left=110.0, right=190.0, lines=[(parallel, parallel.bbox)])- span_lane = models._TextLane(- left=10.0,- right=190.0,- lines=[(first, first.bbox), (second, second.bbox), (later, later.bbox)],- is_span=True,- )-- line_layout._reattach_span_lane_continuations(- [left_lane, right_lane, span_lane],- 10.0,- )-- assert tail not in [line for line, _bbox in left_lane.lines]- assert tail in [line for line, _bbox in span_lane.lines]---def test_repeated_indented_span_tails_reattach_and_form_separate_entries() -> None:- """验证重复的跨栏首行与缩进尾行迁回 span 后仍逐条分组。"""-- body_font = ("Body", 0)- first = _text_line(- "first wide",- (10.0, 0.0, 190.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- )- first_tail = _text_line(- "first tail",- (25.0, 10.0, 90.0, 20.0),- 1,- font_signature=body_font,- font_coverage=1.0,- )- second = _text_line(- "second wide",- (10.0, 20.0, 190.0, 30.0),- 2,- font_signature=body_font,- font_coverage=1.0,- )- second_tail = _text_line(- "second tail",- (25.0, 30.0, 80.0, 40.0),- 3,- font_signature=body_font,- font_coverage=1.0,- )- left_lane = models._TextLane(- left=10.0,- right=90.0,- lines=[(first_tail, first_tail.bbox), (second_tail, second_tail.bbox)],- )- right_marker = _text_line("peer", (110.0, 70.0, 190.0, 80.0), 4)- right_lane = models._TextLane(- left=110.0,- right=190.0,- lines=[(right_marker, right_marker.bbox)],- )- span_lane = models._TextLane(- left=10.0,- right=190.0,- lines=[(first, first.bbox), (second, second.bbox)],- is_span=True,- )-- line_layout._reattach_span_lane_continuations(- [left_lane, right_lane, span_lane],- 10.0,- )- group_map = text_blocks._build_hanging_indent_group_map(span_lane, [], [])-- assert not left_lane.lines- assert [group_map[index] for index in range(4)] == [0, 0, 1, 1]---def test_single_indented_span_tail_does_not_reattach() -> None:- """验证缺少重复结构支持时单个缩进行不会被猜测为跨栏续行。"""-- first = _text_line("wide", (10.0, 0.0, 190.0, 10.0), 0)- tail = _text_line("tail", (25.0, 10.0, 80.0, 20.0), 1)- peer = _text_line("peer", (110.0, 50.0, 190.0, 60.0), 2)- left_lane = models._TextLane(left=10.0, right=90.0, lines=[(tail, tail.bbox)])- right_lane = models._TextLane(left=110.0, right=190.0, lines=[(peer, peer.bbox)])- span_lane = models._TextLane(- left=10.0,- right=190.0,- lines=[(first, first.bbox)],- is_span=True,- )-- line_layout._reattach_span_lane_continuations(- [left_lane, right_lane, span_lane],- 10.0,- )-- assert tail in [line for line, _bbox in left_lane.lines]---def test_aligned_fallback_fonts_merge_but_style_conflict_stays_separate() -> None:- """验证紧邻地址与联系方式可跨字体族续接,而样式位变化仍形成边界。"""-- address = _text_line(- "address",- (0.0, 0.0, 70.0, 10.0),- 0,- font_signature=("CJK", 32),- font_coverage=1.0,- dominant_font_weight=250.0,- )- contact = _text_line(- "contact",- (0.0, 12.0, 80.0, 22.0),- 1,- font_signature=("Latin", 32),- font_coverage=1.0,- dominant_font_weight=220.0,- )- emphasized = _text_line(- "emphasized",- (0.0, 24.0, 80.0, 34.0),- 2,- font_signature=("LatinBold", 64),- font_coverage=1.0,- dominant_font_weight=650.0,- )-- blocks = text_blocks._build_text_blocks(- [address, contact, emphasized],- [],- (100.0, 100.0),- )-- assert [block["content"] for block in blocks] == [- "address contact",- "emphasized",- ]---def test_hanging_indent_uses_top_pitch_when_terminal_glyph_height_is_abnormal() -> None:- """验证异常偏高末字符不会把已重复的参考文献悬挂缩进拆开。"""-- lines = [- _text_line("entry one", (0.0, 0.0, 100.0, 10.0), 0),- _text_line("entry one tail", (15.0, 10.0, 90.0, 20.0), 1),- _text_line("entry two", (0.0, 20.0, 100.0, 30.0), 2),- _text_line(- "entry two tall tail",- (15.0, 30.0, 90.0, 40.0),- 3,- effective_height=18.6,- ),- _text_line("entry three", (0.0, 42.0, 100.0, 52.0), 4),- _text_line("entry three tail", (15.0, 52.0, 90.0, 62.0), 5),- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])-- assert [group_map[index] for index in range(6)] == [0, 0, 1, 1, 2, 2]---def test_spatial_post_merge_connects_short_opener_wide_body_and_tail() -> None:- """验证跨栏拆开的短首行、满宽正文和紧邻尾行仅按空间关系重新连接。"""-- blocks = [- {- "type": "text",- "bbox": (10.0, 10.0, 40.0, 20.0),- "angle": 0,- "content": "section",- "_visual_row_ids": {0},- "_local_line_bboxes": [(10.0, 10.0, 40.0, 20.0)],- "_line_heights": [10.0],- },- {- "type": "text",- "bbox": (10.0, 22.0, 190.0, 42.0),- "angle": 0,- "content": "wide body",- "_visual_row_ids": {1, 2},- "_local_line_bboxes": [- (10.0, 22.0, 190.0, 32.0),- (10.0, 32.0, 190.0, 42.0),- ],- "_line_heights": [10.0, 10.0],- },- {- "type": "text",- "bbox": (10.0, 44.0, 100.0, 54.0),- "angle": 0,- "content": "tail",- "_visual_row_ids": {3},- "_local_line_bboxes": [(10.0, 44.0, 100.0, 54.0)],- "_line_heights": [10.0],- },- ]-- merged = text_blocks._merge_spatial_text_components(- blocks,- (200.0, 100.0),- )-- assert len(merged) == 1- assert merged[0]["bbox"] == (10.0, 10.0, 190.0, 54.0)- assert merged[0]["content"] == "section wide body tail"- assert merged[0]["_visual_row_ids"] == {0, 1, 2, 3}---def test_spatial_post_merge_uses_compatible_local_lane_width() -> None:- """验证半页栏内的短首行可连接多段正文,并在下一分组起点停止。"""-- lane_metadata = {- "_lane_interval": (40.0, 370.0),- "_lane_is_span": False,- }- blocks = [- {- "type": "text",- "bbox": (40.0, 10.0, 80.0, 20.0),- "angle": 0,- "content": "opener",- "_visual_row_ids": {0},- "_local_line_bboxes": [(40.0, 10.0, 80.0, 20.0)],- "_line_heights": [10.0],- **lane_metadata,- },- {- "type": "text",- "bbox": (40.0, 22.0, 365.0, 42.0),- "angle": 0,- "content": "body one",- "_visual_row_ids": {1, 2},- "_local_line_bboxes": [- (40.0, 22.0, 365.0, 32.0),- (40.0, 32.0, 365.0, 42.0),- ],- "_line_heights": [10.0, 10.0],- **lane_metadata,- },- {- "type": "text",- "bbox": (40.0, 44.0, 365.0, 54.0),- "angle": 0,- "content": "body two",- "_visual_row_ids": {3},- "_local_line_bboxes": [(40.0, 44.0, 365.0, 54.0)],- "_line_heights": [10.0],- **lane_metadata,- },- {- "type": "text",- "bbox": (40.0, 56.0, 365.0, 76.0),- "angle": 0,- "content": "body three",- "_visual_row_ids": {4, 5},- "_local_line_bboxes": [- (40.0, 56.0, 365.0, 66.0),- (40.0, 66.0, 365.0, 76.0),- ],- "_line_heights": [10.0, 10.0],- **lane_metadata,- },- {- "type": "text",- "bbox": (40.0, 78.0, 230.0, 88.0),- "angle": 0,- "content": "body tail",- "_visual_row_ids": {6},- "_local_line_bboxes": [(40.0, 78.0, 230.0, 88.0)],- "_line_heights": [10.0],- **lane_metadata,- },- {- "type": "text",- "bbox": (40.0, 90.0, 365.0, 112.0),- "angle": 0,- "content": "next section body",- "_visual_row_ids": {7, 8},- "_local_line_bboxes": [- (40.0, 90.0, 90.0, 100.0),- (40.0, 102.0, 365.0, 112.0),- ],- "_line_heights": [10.0, 10.0],- **lane_metadata,- },- ]-- merged = text_blocks._merge_spatial_text_components(- blocks,- (600.0, 200.0),- )-- assert [block["content"] for block in merged] == [- "opener body one body two body three body tail",- "next section body",- ]- assert merged[0]["bbox"] == (40.0, 10.0, 365.0, 88.0)---def test_spatial_post_merge_does_not_share_incompatible_lane_width() -> None:- """验证左右栏区间不兼容时仍使用页面宽度,不能放宽首段合并。"""-- blocks = [- {- "type": "text",- "bbox": (40.0, 10.0, 80.0, 20.0),- "angle": 0,- "content": "left opener",- "_visual_row_ids": {0},- "_local_line_bboxes": [(40.0, 10.0, 80.0, 20.0)],- "_line_heights": [10.0],- "_lane_interval": (40.0, 370.0),- "_lane_is_span": False,- },- {- "type": "text",- "bbox": (270.0, 22.0, 590.0, 42.0),- "angle": 0,- "content": "right body",- "_visual_row_ids": {1, 2},- "_local_line_bboxes": [- (270.0, 22.0, 590.0, 32.0),- (270.0, 32.0, 590.0, 42.0),- ],- "_line_heights": [10.0, 10.0],- "_lane_interval": (270.0, 590.0),- "_lane_is_span": False,- },- ]-- merged = text_blocks._merge_spatial_text_components(- blocks,- (600.0, 100.0),- )-- assert [block["content"] for block in merged] == [- "left opener",- "right body",- ]---def test_spatial_post_merge_does_not_join_span_caption_to_column_body() -> None:- """验证跨栏图注即使紧邻单栏正文也不会在二次阶段合并。"""-- blocks = [- {- "type": "text",- "bbox": (40.0, 10.0, 560.0, 30.0),- "angle": 0,- "content": "wide caption",- "_visual_row_ids": {0, 1},- "_local_line_bboxes": [- (200.0, 10.0, 360.0, 20.0),- (40.0, 20.0, 560.0, 30.0),- ],- "_line_heights": [10.0, 10.0],- "_lane_interval": (40.0, 560.0),- "_lane_is_span": True,- },- {- "type": "text",- "bbox": (40.0, 35.0, 290.0, 65.0),- "angle": 0,- "content": "left column body",- "_visual_row_ids": {2, 3, 4},- "_local_line_bboxes": [- (40.0, 35.0, 290.0, 45.0),- (40.0, 45.0, 290.0, 55.0),- (40.0, 55.0, 290.0, 65.0),- ],- "_line_heights": [10.0, 10.0, 10.0],- "_lane_interval": (40.0, 290.0),- "_lane_is_span": False,- },- ]-- merged = text_blocks._merge_spatial_text_components(blocks, (600.0, 100.0))-- assert [block["content"] for block in merged] == [- "wide caption",- "left column body",- ]---def test_image_caption_marker_only_attaches_same_font_spatial_tail() -> None:- """验证通用图注标记仅确认图像邻近候选,并把同字体续行接回对应图注。"""-- common = {- "type": "text",- "angle": 0,- "_single_run_row_id": None,- "_lane_interval": (10.0, 90.0),- "_lane_is_span": True,- }- blocks = [- {- **common,- "bbox": (30.0, 50.0, 70.0, 60.0),- "content": "图1 neutral caption",- "_visual_row_ids": {1},- "_local_line_bboxes": [(30.0, 50.0, 70.0, 60.0)],- "_line_heights": [10.0],- "_font_signatures": {("Chinese", 0)},- },- {- **common,- "bbox": (10.0, 58.0, 90.0, 68.0),- "content": "Fig. 1 neutral caption;",- "_visual_row_ids": {2},- "_local_line_bboxes": [(10.0, 58.0, 90.0, 68.0)],- "_line_heights": [10.0],- "_font_signatures": {("English", 0)},- },- {- **common,- "bbox": (20.0, 67.0, 80.0, 77.0),- "content": "caption continuation",- "_visual_row_ids": {3},- "_local_line_bboxes": [(20.0, 67.0, 80.0, 77.0)],- "_line_heights": [10.0],- "_font_signatures": {("English", 0)},- },- ]-- merged = text_blocks._merge_image_caption_text_blocks(- blocks,- [(20.0, 10.0, 80.0, 50.0)],- )-- assert len(merged) == 2- chinese = next(block for block in merged if block["content"].startswith("图1"))- english = next(block for block in merged if block["content"].startswith("Fig. 1"))- assert "continuation" not in chinese["content"]- assert "caption continuation" in english["content"]- assert english["bbox"] == (10.0, 58.0, 90.0, 77.0)---def test_fragmented_center_header_merges_but_remote_volume_stays_separate() -> None:- """验证等距窄页眉字形形成一个逻辑块,远端卷期块不被吸收。"""-- blocks = []- for index, left in enumerate((40.0, 60.0, 80.0, 100.0)):- blocks.append(- {- "type": "header",- "bbox": (left, 5.0, left + 6.0, 15.0),- "angle": 0,- "content": f"h{index}",- "_visual_row_ids": {0},- "_single_run_row_id": 0,- "_local_line_bboxes": [(left, 5.0, left + 6.0, 15.0)],- "_line_heights": [10.0],- "_font_signatures": {("Header", 0)},- "_lane_interval": (0.0, 200.0),- "_lane_is_span": True,- }- )- blocks.append(- {- "type": "header",- "bbox": (170.0, 5.0, 190.0, 15.0),- "angle": 0,- "content": "volume",- "_visual_row_ids": {0},- "_single_run_row_id": 0,- "_local_line_bboxes": [(170.0, 5.0, 190.0, 15.0)],- "_line_heights": [10.0],- "_font_signatures": {("Header", 0)},- "_lane_interval": (0.0, 200.0),- "_lane_is_span": True,- }- )-- merged = text_blocks._merge_fragmented_header_blocks(blocks)-- assert len(merged) == 2- center = next(block for block in merged if block["content"].startswith("h0"))- assert center["content"] == "h0 h1 h2 h3"- assert center["bbox"] == (40.0, 5.0, 106.0, 15.0)- assert next(block for block in merged if block["content"] == "volume")---def test_spatial_post_merge_cannot_skip_intervening_title_block() -> None:- """验证二次组件合并不能越过同一水平流中的中间标题块。"""-- common = {- "angle": 0,- "_single_run_row_id": None,- "_lane_interval": (0.0, 100.0),- "_lane_is_span": False,- "_font_signatures": {("Body", 0)},- }- blocks = [- {- **common,- "type": "text",- "bbox": (0.0, 0.0, 25.0, 10.0),- "content": "short opener",- "_visual_row_ids": {0},- "_local_line_bboxes": [(0.0, 0.0, 25.0, 10.0)],- "_line_heights": [10.0],- },- {- **common,- "type": "paragraph_title",- "bbox": (0.0, 9.0, 45.0, 19.0),- "content": "intervening title",- "_visual_row_ids": {1},- "_local_line_bboxes": [(0.0, 9.0, 45.0, 19.0)],- "_line_heights": [10.0],- },- {- **common,- "type": "text",- "bbox": (0.0, 12.0, 100.0, 22.0),- "content": "wide body",- "_visual_row_ids": {2},- "_local_line_bboxes": [(0.0, 12.0, 100.0, 22.0)],- "_line_heights": [10.0],- },- ]-- merged = text_blocks._merge_spatial_text_components(blocks, (100.0, 50.0))-- assert [block["content"] for block in merged] == [- "short opener",- "intervening title",- "wide body",- ]---def test_exaggerated_bbox_short_tail_stays_with_full_width_previous_row() -> None:- """验证同左边界短尾行不会因异常字体框高度而从正文段落脱落。"""-- previous = _text_line(- "full width previous row",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- current = _text_line(- "short tail",- (0.0, 12.0, 25.0, 30.0),- 1,- effective_height=18.0,- font_signature=("Number", 0),- font_coverage=1.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- regular_gap=2.0,- gap_mad=0.5,- table_bboxes=[],- axis_lines=[],- )---def test_indented_reference_colon_keeps_safe_short_tail_with_abnormal_height() -> None:- """验证参考文献续行相对编号左缘缩进时,冒号后的异常高短尾仍保持同块。"""-- previous = _text_line(- "full continuation:",- (25.0, 0.0, 100.0, 10.0),- 0,- effective_height=9.0,- )- current = _text_line(- "short tall tail",- (25.0, 11.0, 50.0, 29.0),- 1,- effective_height=18.6,- )- next_entry = _text_line(- "[10] next entry",- (0.0, 24.0, 100.0, 34.0),- 2,- effective_height=10.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (previous, previous.bbox),- (current, current.bbox),- (next_entry, next_entry.bbox),- ],- )-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- regular_gap=1.0,- gap_mad=0.1,- table_bboxes=[],- axis_lines=[],- )- assert text_blocks._starts_structural_reference_entry(- (current, current.bbox),- (next_entry, next_entry.bbox),- )---def test_indented_list_row_can_return_to_lane_left_for_short_tail() -> None:- """验证列表首行轻度缩进时,回到栏左边的同字体短尾行仍可续接。"""-- body_font = ("Body", 0)- previous = _text_line(- "indented list row",- (15.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- )- current = _text_line(- "short tail",- (0.0, 10.0, 65.0, 20.0),- 1,- font_signature=body_font,- font_coverage=1.0,- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- regular_gap=0.0,- gap_mad=0.0,- table_bboxes=[],- axis_lines=[],- )---def test_outdented_reference_number_starts_new_structural_entry() -> None:- """验证通用参考文献编号仅在左突几何成立时切开上一条续行。"""-- previous = _text_line("previous continuation", (25.0, 0.0, 100.0, 10.0), 0)- current = _text_line("[23] next reference", (0.0, 10.0, 100.0, 20.0), 1)- aligned = _text_line("[23] inline marker", (25.0, 10.0, 100.0, 20.0), 2)-- assert text_blocks._starts_structural_reference_entry(- (previous, previous.bbox),- (current, current.bbox),- )- assert not text_blocks._starts_structural_reference_entry(- (previous, previous.bbox),- (aligned, aligned.bbox),- )---def test_spatial_post_merge_limits_tapered_tail_to_parallel_information_grid() -> None:- """验证略大间距的递减尾行只在并列信息网格中并回其左对齐主体。"""-- blocks = [- {- "type": "text",- "bbox": (10.0, 10.0, 90.0, 40.0),- "angle": 0,- "content": "left body",- "_visual_row_ids": {0},- "_local_line_bboxes": [(10.0, 30.0, 90.0, 40.0)],- "_line_heights": [10.0],- },- {- "type": "text",- "bbox": (110.0, 10.0, 190.0, 40.0),- "angle": 0,- "content": "right body",- "_visual_row_ids": {1},- "_local_line_bboxes": [(110.0, 30.0, 190.0, 40.0)],- "_line_heights": [10.0],- },- {- "type": "text",- "bbox": (10.0, 50.0, 60.0, 60.0),- "angle": 0,- "content": "left tail",- "_visual_row_ids": {2},- "_local_line_bboxes": [(10.0, 50.0, 60.0, 60.0)],- "_line_heights": [10.0],- },- ]-- merged = text_blocks._merge_spatial_text_components(- blocks,- (200.0, 100.0),- )-- assert [block["content"] for block in merged] == [- "left body left tail",- "right body",- ]-- isolated = text_blocks._merge_spatial_text_components(- [blocks[0], blocks[2]],- (200.0, 100.0),- )- assert [block["content"] for block in isolated] == [- "left body",- "left tail",- ]---def test_repeated_leading_emphasis_and_tail_gap_split_structured_text() -> None:- """验证重复行首强调只在前行留白充分时形成结构化正文边界。"""-- lines = [- _text_line(- "Purpose first section opener",- (0.0, 0.0, 100.0, 10.0),- 0,- leading_emphasis_width=12.0,- ),- _text_line("purpose tail.", (0.0, 10.0, 78.0, 20.0), 1),- _text_line(- "Methods second section opener",- (0.0, 20.0, 100.0, 30.0),- 2,- leading_emphasis_width=12.0,- ),- _text_line("methods tail.", (0.0, 30.0, 60.0, 40.0), 3),- _text_line(- "Results third section opener",- (0.0, 40.0, 100.0, 50.0),- 4,- leading_emphasis_width=12.0,- ),- _text_line("results tail.", (0.0, 50.0, 35.0, 60.0), 5),- _text_line(- "Conclusions fourth section opener",- (0.0, 60.0, 100.0, 70.0),- 6,- leading_emphasis_width=15.0,- ),- _text_line("conclusions tail.", (0.0, 70.0, 70.0, 80.0), 7),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))-- assert [block["content"] for block in blocks] == [- "Purpose first section opener purpose tail.",- "Methods second section opener methods tail.",- "Results third section opener results tail.",- "Conclusions fourth section opener conclusions tail.",- ]---def test_native_typography_caches_leading_emphasis_before_chars_are_cleared() -> None:- """验证字符释放前缓存短粗体前缀宽度,后续文本分块仍可读取。"""-- chars = []- for index, char in enumerate("Lead"):- chars.append(- {- "char": char,- "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),- "font": {"name": "LeadFont", "flags": 0, "weight": 600},- }- )- for index, char in enumerate("body", start=5):- chars.append(- {- "char": char,- "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),- "font": {"name": "BodyFont", "flags": 0, "weight": 400},- }- )- line = models._LineItem(- text="Lead body",- bbox=(0.0, 0.0, 45.0, 10.0),- angle=0,- source_index=0,- chars=chars,- )-- native_text._fill_native_typography(line, (100.0, 100.0))- pipeline._compact_prepared_lines([line], (100.0, 100.0))-- assert line.leading_emphasis_width == 20.0- assert not line.chars---def test_native_typography_caches_leading_font_family_run_without_weight_change() -> None:- """验证同字重的独立行首字体 run 仍缓存为视觉排版宽度。"""-- chars = []- for index, char in enumerate("Lead"):- chars.append(- {- "char": char,- "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),- "font": {"name": "LeadFont", "flags": 0, "weight": 400},- }- )- for index, char in enumerate("body", start=5):- chars.append(- {- "char": char,- "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),- "font": {"name": "BodyFont", "flags": 0, "weight": 400},- }- )- line = models._LineItem(- text="Lead body",- bbox=(0.0, 0.0, 45.0, 10.0),- angle=0,- source_index=0,- chars=chars,- )-- native_text._fill_native_typography(line, (100.0, 100.0))- pipeline._compact_prepared_lines([line], (100.0, 100.0))-- assert line.leading_emphasis_width is None- assert line.leading_typography_width == 20.0- assert not line.chars---def test_image_adjacent_centered_short_to_wide_rows_split_without_text_markers() -> None:- """验证图片下方短居中行到宽居中行按纯视觉关系形成独立块。"""-- first = _text_line("alpha", (35.0, 62.0, 65.0, 72.0), 0)- second = _text_line("beta", (10.0, 74.0, 90.0, 84.0), 1)-- blocks = text_blocks._build_text_blocks(- [first, second],- [],- (100.0, 100.0),- visual_bboxes=[(5.0, 10.0, 95.0, 60.0)],- )- control = text_blocks._build_text_blocks(- [first, second],- [],- (100.0, 100.0),- )-- assert [block["content"] for block in blocks] == ["alpha", "beta"]- assert [block["content"] for block in control] == ["alpha beta"]---def test_short_tail_and_leading_typography_run_split_structured_text() -> None:- """验证短尾之后的宽行仅在存在独立行首字体 run 时形成新块。"""-- previous = _text_line("tail", (0.0, 0.0, 35.0, 10.0), 0)- opener = _text_line(- "opener body",- (0.0, 12.0, 90.0, 22.0),- 1,- leading_typography_width=12.0,- )-- blocks = text_blocks._build_text_blocks(- [previous, opener],- [],- (100.0, 100.0),- )- control = text_blocks._build_text_blocks(- [previous, replace(opener, leading_typography_width=None)],- [],- (100.0, 100.0),- )-- assert [block["content"] for block in blocks] == ["tail", "opener body"]- assert [block["content"] for block in control] == ["tail opener body"]---def test_same_baseline_merge_preserves_paragraph_formula_context() -> None:- """验证公式回退上下文在同行碎片合并后不会丢失。"""-- fragments = [- _text_line(- "left",- (0.0, 0.0, 40.0, 10.0),- 0,- font_signature=("Math", 0),- font_coverage=0.5,- paragraph_formula_context=True,- ),- _text_line(- "right",- (40.1, 0.0, 80.0, 10.0),- 1,- font_signature=("Math", 0),- font_coverage=0.5,- ),- ]-- merged = line_merging._merge_same_baseline_text_lines(- fragments,- (100.0, 100.0),- [],- )-- assert len(merged) == 1- assert merged[0].paragraph_formula_context--[email protected]("row_count", [2, 3, 6])-def test_formula_style_text_rows_split_pairwise_without_count_gate(- row_count: int,-) -> None:- """验证两行起任意长度的独立公式样式文本均按相邻行拆分。"""-- rows = [- _text_line(- f"row {index}",- (20.0 - index, 14.0 * index, 80.0 + index, 14.0 * index + 10.0),- index,- font_signature=("Math", 0),- font_coverage=0.5,- paragraph_formula_context=True,- )- for index in range(row_count)- ]- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[(row, row.bbox) for row in rows],- )-- break_sources = text_blocks._formula_style_text_row_break_sources(lane)-- assert break_sources == set(range(row_count))--- "second_bbox",- [- (35.0, 11.0, 65.0, 21.0),- (20.0, 5.0, 80.0, 15.0),- ],- ids=["narrow-denominator", "overlapping-script-tier"],-)-def test_formula_style_text_rows_keep_connected_math_fragments(- second_bbox: tuple[float, float, float, float],-) -> None:- """验证窄分母和垂直重叠层级不会被拆成独立正文块。"""-- rows = [- _text_line(- "formula body",- (20.0, 0.0, 80.0, 10.0),- 0,- paragraph_formula_context=True,- ),- _text_line(- "math fragment",- second_bbox,- 1,- paragraph_formula_context=True,- ),- ]-- blocks = text_blocks._build_text_blocks(- rows,- [],- (100.0, 100.0),- )-- assert [block["content"] for block in blocks] == [- "formula body math fragment",- ]---def test_native_typography_separates_loose_height_from_canonical_em() -> None:- """验证异常 loose 字符高度不会覆盖 PDF 字号形成的 canonical 尺度。"""-- chars = [- {- "char": character,- "bbox": (float(index * 6), 0.0, float(index * 6 + 6), 24.0),- "font": {- "name": "ABCDEF+Body",- "flags": 0,- "weight": 400,- "size": 10.0,- },- "char_idx": index,- }- for index, character in enumerate("Body")- ]- line = models._LineItem(- text="Body",- bbox=(0.0, 0.0, 24.0, 24.0),- angle=0,- source_index=0,- chars=chars,- em_height=10.0,- style_scale_repaired=True,- )-- native_text._fill_native_typography(line, (100.0, 100.0))-- assert line.effective_height == 24.0- assert line.em_height == 10.0- assert line_layout._line_effective_height(line, line.bbox) == 10.0- assert line_layout._line_layout_height(line, line.bbox) == 24.0---def test_canonical_visual_resplit_separates_cross_column_coarse_row() -> None:- """验证 repaired/tight 字符间隙可把跨栏粗行重切成唯一视觉 run。"""-- positions = (0.0, 6.0, 12.0, 18.0, 62.0, 68.0, 74.0, 80.0)- chars = [- {- "char": character,- "bbox": (position, 10.0, position + 20.0, 20.0),- "font": {- "name": "ABCDEF+Body",- "flags": 0,- "weight": 400,- "size": 10.0,- },- "char_idx": index,- }- for index, (character, position) in enumerate(- zip("ABCDEFGH", positions, strict=True),- )- ]- visual_bboxes = {index: (position, 10.0, position + 5.0, 20.0) for index, position in enumerate(positions)}- line = models._LineItem(- text="ABCDEFGH",- bbox=(0.0, 10.0, 100.0, 20.0),- angle=0,- source_index=5,- chars=chars,- visual_row_id=3,- )-- output, resplits = native_text._resplit_native_visual_runs(- [line],- (100.0, 100.0),- visual_bboxes,- source_index_start=10,- )-- assert [item.text for item in output] == ["ABCD", "EFGH"]- assert [item.source_index for item in output] == [5, 10]- assert all(item.visual_row_id == 3 for item in output)- assert all(item.split_from_row for item in output)- assert resplits[5].source is line- assert resplits[5].members == tuple(output)---def test_two_leading_emphasis_rows_do_not_activate_structured_text_split() -> None:- """验证不足三个重复强调首行时不会把普通混排正文切碎。"""-- lines = [- _text_line(- "first emphasized opener",- (0.0, 0.0, 100.0, 10.0),- 0,- leading_emphasis_width=15.0,- ),- _text_line("first short tail", (0.0, 10.0, 60.0, 20.0), 1),- _text_line(- "second emphasized opener",- (0.0, 20.0, 100.0, 30.0),- 2,- leading_emphasis_width=15.0,- ),- _text_line("second short tail", (0.0, 30.0, 60.0, 40.0), 3),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))-- assert len(blocks) == 1---def test_leading_emphasis_count_does_not_cross_semantic_title_boundary() -> None:- """验证不同语义区段的强调首行数量不能合并触发结构化正文模式。"""-- lines = [- _text_line("first opener", (0.0, 0.0, 100.0, 10.0), 0, leading_emphasis_width=10.0),- _text_line("first tail", (0.0, 10.0, 60.0, 20.0), 1),- _text_line("second opener", (0.0, 20.0, 100.0, 30.0), 2, leading_emphasis_width=10.0),- _text_line("second tail", (0.0, 30.0, 60.0, 40.0), 3),- _text_line(- "semantic title",- (0.0, 50.0, 40.0, 60.0),- 4,- semantic_type="paragraph_title",- ),- _text_line("third opener", (0.0, 70.0, 100.0, 80.0), 5, leading_emphasis_width=10.0),- _text_line("third tail", (0.0, 80.0, 60.0, 90.0), 6),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))-- first_region = next(block for block in blocks if "first opener" in block["content"])- assert "second opener" in first_region["content"]---def test_page_footnote_visual_markers_attach_six_affiliation_entries() -> None:- """验证同行窄编号与右侧单位首行、续行分别组成独立脚注条目。"""-- lines = [- _text_line("contact name", (10.0, 0.0, 48.0, 10.0), 0, semantic_type="page_footnote"),- _text_line("contact email", (10.0, 10.0, 55.0, 20.0), 1, semantic_type="page_footnote"),- ]- source_index = 2- for marker in range(1, 7):- top = 20.0 + (marker - 1) * 20.0- visual_row_id = 100 + marker- lines.extend(- [- _text_line(- str(marker),- (0.0, top, 3.0, top + 8.0),- source_index,- visual_row_id=visual_row_id,- run_index=0,- split_from_row=True,- median_glyph_width=3.0,- semantic_type="page_footnote",- ),- _text_line(- f"affiliation {marker} first row",- (10.0, top, 90.0, top + 10.0),- source_index + 1,- visual_row_id=visual_row_id,- run_index=1,- split_from_row=True,- median_glyph_width=4.0,- semantic_type="page_footnote",- ),- _text_line(- f"affiliation {marker} continuation",- (10.0, top + 10.0, 75.0, top + 20.0),- source_index + 2,- visual_row_id=visual_row_id + 100,- median_glyph_width=4.0,- semantic_type="page_footnote",- ),- ]- )- source_index += 3-- blocks = text_blocks._build_text_blocks(- lines,- [],- (100.0, 160.0),- page_footnote_groups=[{line.source_index for line in lines}],- )-- assert [block["content"] for block in blocks[:2]] == [- "contact name",- "contact email",- ]- assert len(blocks[2:]) == 6- for marker, block in enumerate(blocks[2:], start=1):- assert block["content"].startswith(f"{marker} affiliation {marker} first row")- assert f"affiliation {marker} continuation" in block["content"]---def test_local_aligned_column_replaces_polluted_full_width_lane() -> None:- """验证跨栏上文不会使后续稳定单栏正文被首行缩进规则拆开。"""-- lines = [- _text_line("wide row one", (0.0, 0.0, 200.0, 10.0), 0),- _text_line("wide row two", (0.0, 10.0, 200.0, 20.0), 1),- _text_line("wide short tail", (0.0, 20.0, 150.0, 30.0), 2),- _text_line(- "Introduction",- (110.0, 40.0, 150.0, 50.0),- 3,- semantic_type="paragraph_title",- ),- _text_line("local first sentence.", (110.0, 55.0, 200.0, 65.0), 4),- _text_line("local second sentence", (110.0, 65.0, 200.0, 75.0), 5),- _text_line("local third sentence", (110.0, 75.0, 200.0, 85.0), 6),- _text_line("local final sentence.", (110.0, 85.0, 195.0, 95.0), 7),- ]-- blocks = text_blocks._build_text_blocks(lines, [], (200.0, 120.0))- introduction_body = next(block for block in blocks if "local first sentence" in block["content"])-- assert introduction_body["content"] == (- "local first sentence. local second sentence local third sentence local final sentence."- )- assert introduction_body["_lane_interval"] == (110.0, 200.0)---def test_typographic_gap_splits_caption_body_without_image_geometry() -> None:- """验证异常净空与行高层级变化可独立于图片位置形成段落硬边界。"""-- caption = _text_line(- "caption ends without punctuation",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- body = _text_line(- "body starts",- (0.0, 19.0, 100.0, 30.5),- 1,- effective_height=11.5,- font_signature=("Body", 0),- font_coverage=1.0,- )- lane = models._TextLane(left=0.0, right=100.0)-- assert not line_layout._should_connect_text_rows(- (caption, caption.bbox),- (body, body.bbox),- lane,- regular_gap=0.0,- gap_mad=0.0,- table_bboxes=[],- axis_lines=[],- )---def test_typographic_gap_requires_both_spacing_and_typography_evidence() -> None:- """验证单独字号变化或单独中等净空都不会触发新增段落屏障。"""-- base = _text_line("base", (0.0, 0.0, 100.0, 10.0), 0, effective_height=10.0)- larger_nearby = _text_line(- "larger nearby",- (0.0, 10.0, 100.0, 21.5),- 1,- effective_height=11.5,- )- same_size_spaced = _text_line(- "same size spaced",- (0.0, 18.0, 100.0, 28.0),- 2,- effective_height=10.0,- )- lane = models._TextLane(left=0.0, right=100.0)-- assert line_layout._should_connect_text_rows(- (base, base.bbox),- (larger_nearby, larger_nearby.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert line_layout._should_connect_text_rows(- (base, base.bbox),- (same_size_spaced, same_size_spaced.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_hyphenated_row_bypasses_typographic_gap_barrier() -> None:- """验证排版断词仍可在现有近距离上限内跨过字号和净空变化。"""-- previous = _text_line("hyphen-", (0.0, 0.0, 100.0, 10.0), 0, effective_height=10.0)- current = _text_line("ated", (0.0, 19.0, 100.0, 30.5), 1, effective_height=11.5)- lane = models._TextLane(left=0.0, right=100.0)-- assert line_layout._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_caption_post_merge_respects_typographic_gap_barrier() -> None:- """验证图片邻接后处理不能跨过已确认的图注正文排版边界。"""-- common = {- "type": "text",- "angle": 0,- "_single_run_row_id": None,- "_lane_interval": (0.0, 100.0),- "_lane_is_span": False,- "_font_signatures": {("Body", 0)},- }- caption = {- **common,- "bbox": (0.0, 50.0, 100.0, 60.0),- "content": "Fig. 1 caption",- "_visual_row_ids": {1},- "_local_line_bboxes": [(0.0, 50.0, 100.0, 60.0)],- "_line_heights": [10.0],- }- body = {- **common,- "bbox": (0.0, 69.0, 100.0, 80.5),- "content": "body starts",- "_visual_row_ids": {2},- "_local_line_bboxes": [(0.0, 69.0, 100.0, 80.5)],- "_line_heights": [11.5],- }-- merged = text_blocks._merge_image_caption_text_blocks(- [caption, body],- [(0.0, 10.0, 100.0, 50.0)],- )-- assert [block["content"] for block in merged] == [- "Fig. 1 caption",- "body starts",- ]---def test_repeated_compact_title_continuations_merge_across_font_switch() -> None:- """验证重复两行弱标题可与紧邻异字体续行合并并恢复为正文。"""-- blocks: list[dict[str, object]] = []- for offset, label in ((0.0, "first"), (45.0, "second")):- blocks.extend(- [- {- "type": "paragraph_title",- "bbox": (10.0, 10.0 + offset, 65.0, 30.0 + offset),- "angle": 0,- "content": f"{label} name {label} address",- "_visual_row_ids": {1, 2},- "_single_run_row_id": None,- "_local_line_bboxes": [- (10.0, 10.0 + offset, 50.0, 20.0 + offset),- (10.0, 20.0 + offset, 65.0, 30.0 + offset),- ],- "_line_heights": [10.0, 10.0],- "_font_signatures": {("Title", 0)},- "_lane_interval": (10.0, 100.0),- "_lane_is_span": False,- },- {- "type": "text",- "bbox": (10.0, 31.0 + offset, 80.0, 41.0 + offset),- "angle": 0,- "content": f"{label} contact",- "_visual_row_ids": {3},- "_single_run_row_id": None,- "_local_line_bboxes": [- (10.0, 31.0 + offset, 80.0, 41.0 + offset),- ],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (10.0, 100.0),- "_lane_is_span": False,- },- ]- )-- merged = text_blocks._merge_repeated_compact_title_continuations(- blocks,- (200.0, 200.0),- )-- assert [block["type"] for block in merged] == ["text", "text"]- assert [block["content"] for block in merged] == [- "first name first address first contact",- "second name second address second contact",- ]---def test_compact_title_continuation_requires_repetition_and_font_switch() -> None:- """验证单组结构或相同字体续行不会越过真正的标题边界。"""-- title = {- "type": "paragraph_title",- "bbox": (10.0, 10.0, 65.0, 30.0),- "angle": 0,- "content": "title",- "_visual_row_ids": {1, 2},- "_single_run_row_id": None,- "_local_line_bboxes": [- (10.0, 10.0, 50.0, 20.0),- (10.0, 20.0, 65.0, 30.0),- ],- "_line_heights": [10.0, 10.0],- "_font_signatures": {("Title", 0)},- "_lane_interval": (10.0, 100.0),- "_lane_is_span": False,- }- continuation = {- "type": "text",- "bbox": (10.0, 31.0, 80.0, 41.0),- "angle": 0,- "content": "body",- "_visual_row_ids": {3},- "_single_run_row_id": None,- "_local_line_bboxes": [(10.0, 31.0, 80.0, 41.0)],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (10.0, 100.0),- "_lane_is_span": False,- }-- unique = text_blocks._merge_repeated_compact_title_continuations(- [title, continuation],- (200.0, 200.0),- )- same_font = text_blocks._merge_repeated_compact_title_continuations(- [- title,- {**continuation, "_font_signatures": {("Title", 0)}},- {**title, "bbox": (10.0, 55.0, 65.0, 75.0)},- {- **continuation,- "bbox": (10.0, 76.0, 80.0, 86.0),- "_font_signatures": {("Title", 0)},- },- ],- (200.0, 200.0),- )-- assert [block["type"] for block in unique] == ["paragraph_title", "text"]- assert [block["type"] for block in same_font] == [- "paragraph_title",- "text",- "paragraph_title",- "text",- ]---def test_caption_neighbor_uses_union_of_aligned_image_row() -> None:- """验证三张并排图片会额外形成统一图注邻接使用的联合 bbox。"""-- grouped = text_blocks._caption_image_group_bboxes(- [- (10.0, 10.0, 35.0, 40.0),- (37.0, 10.0, 62.0, 40.0),- (64.0, 10.0, 90.0, 40.0),- ],- median_height=10.0,- )-- assert (10.0, 10.0, 90.0, 40.0) in grouped---def test_inline_math_fragments_merge_into_wide_split_text_row() -> None:- """验证宽正文行上下叠放的多个小数学块收敛为一个文本块。"""-- host = {- "type": "text",- "bbox": (10.0, 40.0, 90.0, 50.0),- "angle": 0,- "content": "body host",- "_visual_row_ids": {1},- "_single_run_row_id": 1,- "_local_line_bboxes": [(10.0, 40.0, 90.0, 50.0)],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- }- fragments = [- {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": content,- "_visual_row_ids": {index + 2},- "_single_run_row_id": None,- "_local_line_bboxes": [bbox],- "_line_heights": [bbox[3] - bbox[1]],- "_font_signatures": {("Math", 0)},- }- for index, (bbox, content) in enumerate(- (- ((30.0, 34.0, 40.0, 43.0), "numerator"),- ((30.0, 47.0, 40.0, 56.0), "denominator"),- ((60.0, 35.0, 70.0, 44.0), "power"),- )- )- ]-- merged = text_blocks._merge_inline_math_fragment_text_blocks(- [host, *fragments],- (200.0, 100.0),- )-- assert len(merged) == 1- assert merged[0]["bbox"] == (10.0, 34.0, 90.0, 56.0)- assert all(token in merged[0]["content"] for token in ("body host", "numerator", "denominator", "power"))- assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True---def test_residual_narrow_math_fragment_merges_into_unique_wide_host() -> None:- """验证单个窄数学碎片与宽正文行重叠时会收回唯一宿主。"""-- host = {- "type": "text",- "bbox": (10.0, 40.0, 90.0, 52.0),- "angle": 0,- "content": "body host",- "_local_line_bboxes": [(10.0, 40.0, 90.0, 52.0)],- "_line_heights": [12.0],- }- fragment = {- "type": "text",- "bbox": (50.0, 48.0, 54.0, 57.0),- "angle": 0,- "content": "gamma",- "_local_line_bboxes": [(50.0, 48.0, 54.0, 57.0)],- "_line_heights": [9.0],- }-- merged = text_blocks._merge_residual_narrow_math_text_blocks(- [host, fragment],- (200.0, 100.0),- )-- assert len(merged) == 1- assert merged[0]["bbox"] == (10.0, 40.0, 90.0, 57.0)- assert "body host" in merged[0]["content"]- assert "gamma" in merged[0]["content"]- assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True---def test_hostless_inline_math_fragments_keep_recovery_marker() -> None:- """验证无宽宿主的数学碎片合并后也保留内部恢复标记。"""-- fragments = [- {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": f"fragment {index}",- "_local_line_bboxes": [bbox],- "_line_heights": [10.0],- "_font_signatures": {("Body" if index < 2 else "Math", 0)},- }- for index, bbox in enumerate(- (- (20.0, 40.0, 60.0, 50.0),- (62.0, 40.0, 100.0, 50.0),- (20.0, 52.0, 55.0, 62.0),- (57.0, 52.0, 100.0, 62.0),- )- )- ]-- merged = text_blocks._merge_hostless_inline_math_fragment_blocks(- fragments,- (200.0, 100.0),- )-- assert len(merged) == 1- assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True---def _inline_math_paragraph_test_blocks(- marker_indices: tuple[int, ...] = (0, 2),-) -> list[dict[str, object]]:- """构造同一栏内连续的五个宽正文块,供数学段落闭合测试复用。"""-- bboxes = (- (20.0, 40.0, 172.0, 70.0),- (20.0, 74.0, 172.0, 94.0),- (20.0, 99.0, 172.0, 129.0),- (20.0, 122.0, 172.0, 145.0),- (20.0, 145.0, 172.0, 175.0),- )- blocks: list[dict[str, object]] = []- for index, bbox in enumerate(bboxes):- block: dict[str, object] = {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": f"paragraph part {index}",- "_local_line_bboxes": [bbox],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (20.0, 180.0),- "_lane_is_span": False,- }- if index in marker_indices:- block[text_blocks._INLINE_MATH_RECOVERY_MARKER] = True- blocks.append(block)- return blocks---def test_inline_math_paragraph_continuations_merge_five_wide_blocks() -> None:- """验证至少两个数学恢复块可带动同栏五段正文闭合为一个块。"""-- merged = text_blocks._merge_inline_math_paragraph_continuations(- _inline_math_paragraph_test_blocks(),- (300.0, 300.0),- )-- assert len(merged) == 1- assert merged[0]["bbox"] == (20.0, 40.0, 172.0, 175.0)- assert all(f"paragraph part {index}" in str(merged[0]["content"]) for index in range(5))- assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True---def test_inline_math_paragraph_does_not_merge_ordinary_paragraphs() -> None:- """验证缺少两个数学恢复锚点时不合并普通连续段落。"""-- merged = text_blocks._merge_inline_math_paragraph_continuations(- _inline_math_paragraph_test_blocks(marker_indices=(0,)),- (300.0, 300.0),- )-- assert len(merged) == 5--[email protected]("variant", ["different_lane", "large_gap", "font_conflict"])-def test_inline_math_paragraph_rejects_geometry_or_font_conflict(- variant: str,-) -> None:- """验证跨栏、过大间距或字体冲突会切断数学正文段落链。"""-- blocks = _inline_math_paragraph_test_blocks()- if variant == "different_lane":- for block in blocks[2:]:- left, top, right, bottom = block["bbox"]- shifted = (left + 170.0, top, right + 170.0, bottom)- block["bbox"] = shifted- block["_local_line_bboxes"] = [shifted]- block["_lane_interval"] = (190.0, 350.0)- elif variant == "large_gap":- for block in blocks[2:]:- left, top, right, bottom = block["bbox"]- shifted = (left, top + 20.0, right, bottom + 20.0)- block["bbox"] = shifted- block["_local_line_bboxes"] = [shifted]- else:- for block in blocks[2:]:- block["_font_signatures"] = {("Other", 0)}-- merged = text_blocks._merge_inline_math_paragraph_continuations(- blocks,- (400.0, 300.0),- )-- assert len(merged) == 5---def test_inline_math_paragraph_does_not_cross_footer_boundary() -> None:- """验证位于相邻正文块之间的 footer 会阻断数学段落闭合。"""-- blocks = _inline_math_paragraph_test_blocks()- footer_bbox = (20.0, 95.0, 172.0, 98.0)- footer = {- "type": "footer",- "bbox": footer_bbox,- "angle": 0,- "content": "footer",- "_local_line_bboxes": [footer_bbox],- "_line_heights": [3.0],- "_font_signatures": {("Body", 0)},- "_lane_interval": (20.0, 180.0),- "_lane_is_span": False,- }-- merged = text_blocks._merge_inline_math_paragraph_continuations(- [*blocks[:2], footer, *blocks[2:]],- (300.0, 300.0),- )-- assert len(merged) == 6- assert sum(block["type"] == "footer" for block in merged) == 1---def test_overlapping_wide_text_rows_merge_without_broad_page_line_merge() -> None:- """验证同左沿宽正文的重叠行可在块级合并,且不依赖全页行合并。"""-- first = {- "type": "text",- "bbox": (20.0, 40.0, 140.0, 52.0),- "angle": 0,- "content": "first row",- "_local_line_bboxes": [(20.0, 40.0, 140.0, 52.0)],- "_line_heights": [12.0],- "_font_signatures": {("Body", 0)},- }- second = {- "type": "text",- "bbox": (20.0, 42.0, 180.0, 65.0),- "angle": 0,- "content": "second row continuation",- "_local_line_bboxes": [- (100.0, 42.0, 180.0, 53.0),- (20.0, 54.0, 180.0, 65.0),- ],- "_line_heights": [11.0, 11.0],- "_font_signatures": {("Body", 0)},- }-- merged = text_blocks._merge_overlapping_same_line_text_blocks(- [first, second],- (300.0, 200.0),- )-- assert len(merged) == 1- assert merged[0]["bbox"] == (20.0, 40.0, 180.0, 65.0)- assert "first row" in merged[0]["content"]- assert "second row continuation" in merged[0]["content"]---def test_boundary_visual_row_merges_two_and_three_row_text_blocks() -> None:- """验证前块末行与后块首行拼接时可合并二行块和三行块。"""-- first = {- "type": "text",- "bbox": (20.0, 40.0, 280.0, 64.0),- "angle": 0,- "content": "first block ending",- "_local_line_bboxes": [- (20.0, 40.0, 280.0, 51.0),- (20.0, 52.0, 200.0, 64.0),- ],- "_line_heights": [11.0, 12.0],- "_font_signatures": {("Body", 0)},- }- second = {- "type": "text",- "bbox": (20.0, 54.0, 280.0, 90.0),- "angle": 0,- "content": "continued on the same visual row",- "_local_line_bboxes": [- (204.0, 54.0, 280.0, 64.0),- (20.0, 66.0, 280.0, 77.0),- (20.0, 79.0, 280.0, 90.0),- ],- "_line_heights": [10.0, 11.0, 11.0],- "_font_signatures": {("Body", 0)},- }-- merged = text_blocks._merge_overlapping_same_line_text_blocks(- [first, second],- (300.0, 200.0),- )-- assert len(merged) == 1- assert "first block ending" in merged[0]["content"]- assert "continued on the same visual row" in merged[0]["content"]--- ("boundary_left", "second_font"),- [(220.0, ("Body", 0)), (204.0, ("Other", 0))],-)-def test_boundary_visual_row_rejects_large_gap_or_font_conflict(- boundary_left: float,- second_font: tuple[str, int],-) -> None:- """验证边界行横向间隔过大或字体集合冲突时不合并正文块。"""-- first = {- "type": "text",- "bbox": (20.0, 40.0, 280.0, 64.0),- "angle": 0,- "content": "first",- "_local_line_bboxes": [- (20.0, 40.0, 280.0, 51.0),- (20.0, 52.0, 200.0, 64.0),- ],- "_line_heights": [11.0, 12.0],- "_font_signatures": {("Body", 0)},- }- second = {- "type": "text",- "bbox": (20.0, 54.0, 280.0, 90.0),- "angle": 0,- "content": "second",- "_local_line_bboxes": [- (boundary_left, 54.0, 280.0, 64.0),- (20.0, 66.0, 280.0, 77.0),- (20.0, 79.0, 280.0, 90.0),- ],- "_line_heights": [10.0, 11.0, 11.0],- "_font_signatures": {second_font},- }-- merged = text_blocks._merge_overlapping_same_line_text_blocks(- [first, second],- (300.0, 200.0),- )-- assert len(merged) == 2---def test_front_matter_grid_merges_each_author_column_independently() -> None:- """验证标题后的四列规则前置信息按列合并且不横向串列。"""-- title = {- "type": "doc_title",- "bbox": (200.0, 100.0, 800.0, 130.0),- "angle": 0,- "content": "document title",- "_visual_row_ids": {0},- "_single_run_row_id": None,- "_local_line_bboxes": [(200.0, 100.0, 800.0, 130.0)],- "_line_heights": [30.0],- "_font_signatures": {("Title", 0)},- }- author_parts = []- for column_index, left in enumerate((75.0, 325.0, 575.0, 825.0)):- for row_index, top in enumerate((150.0, 165.0, 180.0)):- bbox = (left, top, left + 100.0, top + 10.0)- author_parts.append(- {- "type": "text",- "bbox": bbox,- "angle": 0,- "content": f"author-{column_index}-row-{row_index}",- "_visual_row_ids": {10 + row_index},- "_single_run_row_id": None,- "_local_line_bboxes": [bbox],- "_line_heights": [10.0],- "_font_signatures": {("Body", 0)},- }- )-- merged = text_blocks._merge_front_matter_column_blocks(- [title, *author_parts],- (1000.0, 1000.0),- page_index=0,- )- merged_authors = [block for block in merged if block["type"] == "text"]-- assert len(merged_authors) == 4- for column_index, block in enumerate(merged_authors):- assert all(f"author-{column_index}-row-{row_index}" in block["content"] for row_index in range(3))diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.pydeleted file mode 100644index 3391ed23..00000000--- a/tests/unittest/test_flash_pdf_titles.py+++ /dev/null@@ -1,1519 +0,0 @@-from __future__ import annotations--import inspect--import pytest--from docvortex.analyzers.native.pdf import line_layout-from docvortex.analyzers.native.pdf import line_merging-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import text_blocks-from docvortex.analyzers.native.pdf import titles---from _flash_pdf_test_utils import (- _prepared_text_page,- _text_line,-)--[email protected]("heading_text", ["1. INTRODUCTION", "completely unrelated words"])-def test_paragraph_title_classification_is_independent_of_heading_content(heading_text: str) -> None:- """验证相同版式和字体的不同内容得到完全相同的段落标题类型。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 1)- lines = [- _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(heading_text, (0.0, 45.0, 40.0, 55.0), 2, font_signature=heading_font, font_coverage=1.0),- _text_line("body three", (0.0, 68.0, 100.0, 78.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 80.0, 100.0, 90.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body five", (0.0, 92.0, 100.0, 102.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type == "paragraph_title"---def test_heading_like_content_with_body_layout_remains_text() -> None:- """验证标题式字符串在正文几何、正文字体和常规行距下仍保持普通文本。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body {index}",- (0.0, 10.0 + 12.0 * index, 100.0, 20.0 + 12.0 * index),- index,- font_signature=body_font,- font_coverage=1.0,- )- for index in range(6)- ]- lines[2].text = "1. INTRODUCTION"-- titles._classify_page_titles(lines, (100.0, 120.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type is None---def test_explicit_section_number_rejects_century_and_decimal_sentence() -> None:- """验证通用章节编号补标标题,同时排除世纪年代和小数正文。"""-- body_font = ("Body", 0)- lines = [- _text_line("20 century body", (0.0, 10.0, 80.0, 20.0), 0, font_signature=body_font),- _text_line("ordinary body one", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font),- _text_line("2 Section heading", (0.0, 45.0, 55.0, 55.0), 2, font_signature=body_font),- _text_line("ordinary body two", (0.0, 62.0, 100.0, 72.0), 3, font_signature=body_font),- _text_line("ordinary body three", (0.0, 74.0, 100.0, 84.0), 4, font_signature=body_font),- _text_line("0.26 value, continues", (0.0, 96.0, 100.0, 106.0), 5, font_signature=body_font),- _text_line("ordinary body four", (0.0, 108.0, 100.0, 118.0), 6, font_signature=body_font),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._classify_explicit_section_titles(- lines,- (120.0, 150.0),- container_bboxes=[],- document_body_profile=profile,- )-- assert lines[0].semantic_type is None- assert lines[2].semantic_type == "paragraph_title"- assert lines[5].semantic_type is None---def test_document_regular_fonts_only_use_body_height_band() -> None:- """验证跨页重复的大字号标题字体不会进入全文常规正文字体集合。"""-- body_font = ("Body", 0)- heading_font = ("RepeatedHeading", 0)- pages = [- _prepared_text_page(- _text_line(- f"heading-{page_index}",- (10.0, 10.0, 90.0, 28.0),- 0,- effective_height=18.0,- font_signature=heading_font,- font_coverage=1.0,- ),- _text_line(- f"body-{page_index}",- (0.0, 40.0, 100.0, 50.0),- 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- )- for page_index in range(3)- ]-- profile = titles._infer_document_body_profile(pages)-- assert profile is not None- assert profile.body_height == pytest.approx(10.0)- assert profile.regular_fonts == frozenset({body_font})---def test_noninitial_document_title_requires_paragraph_title_candidate() -> None:- """验证非首页文档标题只能从已确认的段落标题候选升档。"""-- title_font = ("Title", 0)- body_font = ("Body", 0)- title_first = _text_line(- "Translated document title first",- (15.0, 20.0, 85.0, 38.0),- 0,- effective_height=18.0,- font_signature=title_font,- font_coverage=1.0,- )- title_second = _text_line(- "translated title second",- (20.0, 38.0, 80.0, 56.0),- 1,- effective_height=18.0,- font_signature=title_font,- font_coverage=1.0,- )- title_first.semantic_type = "paragraph_title"- title_second.semantic_type = "paragraph_title"- author = _text_line(- "Author One, Author Two",- (20.0, 65.0, 80.0, 75.0),- 2,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- affiliation = _text_line(- "University affiliation",- (25.0, 77.0, 75.0, 87.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- abstract = _text_line(- "wide abstract body",- (5.0, 96.0, 95.0, 106.0),- 4,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._promote_noninitial_document_title_band(- [title_first, title_second, author, affiliation, abstract],- (100.0, 150.0),- page_index=1,- container_bboxes=[],- document_body_profile=profile,- title_candidate_source_indices={0, 1},- )-- assert title_first.semantic_type == "doc_title"- assert title_second.semantic_type == "doc_title"- assert all(line.semantic_type is None for line in (author, affiliation, abstract))-- ordinary_large_line = _text_line(- "large centered non-title",- (15.0, 20.0, 85.0, 38.0),- 10,- effective_height=18.0,- font_signature=title_font,- font_coverage=1.0,- )- titles._promote_noninitial_document_title_band(- [ordinary_large_line],- (100.0, 150.0),- page_index=2,- container_bboxes=[],- document_body_profile=profile,- title_candidate_source_indices=set(),- )- assert ordinary_large_line.semantic_type is None---def test_noninitial_document_titles_support_multiple_articles_without_metadata() -> None:- """验证杂志中的多篇文章可在各自起始页仅凭稳定标题版式成为 doc_title。"""-- title_font = ("Title", 0)- body_font = ("Body", 0)- first_article_title = _text_line(- "First article title",- (15.0, 20.0, 85.0, 36.0),- 0,- effective_height=16.0,- font_signature=title_font,- font_coverage=1.0,- )- first_article_title_tail = _text_line(- "continued title",- (20.0, 37.0, 80.0, 53.0),- 1,- effective_height=16.0,- font_signature=title_font,- font_coverage=1.0,- )- second_article_title = _text_line(- "Second article title",- (18.0, 28.0, 82.0, 44.0),- 0,- effective_height=16.0,- font_signature=title_font,- font_coverage=1.0,- )- later_section = _text_line(- "Centered section heading",- (25.0, 85.0, 75.0, 98.0),- 2,- effective_height=13.0,- font_signature=title_font,- font_coverage=1.0,- )- first_article_title.semantic_type = "paragraph_title"- first_article_title_tail.semantic_type = "paragraph_title"- second_article_title.semantic_type = "paragraph_title"- later_section.semantic_type = "paragraph_title"- pages = [- _prepared_text_page(- _text_line(- "magazine cover",- (5.0, 20.0, 95.0, 30.0),- 0,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- page_size=(100.0, 150.0),- ),- _prepared_text_page(- first_article_title,- first_article_title_tail,- _text_line(- "first article body",- (5.0, 70.0, 95.0, 80.0),- 2,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- page_size=(100.0, 150.0),- ),- _prepared_text_page(- second_article_title,- _text_line(- "second article body",- (5.0, 55.0, 95.0, 65.0),- 1,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- ),- later_section,- page_size=(100.0, 150.0),- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._promote_noninitial_document_title_band(- pages[1].remaining_lines,- pages[1].page_size,- page_index=1,- container_bboxes=[],- document_body_profile=profile,- title_candidate_source_indices={0, 1},- )- titles._promote_noninitial_document_title_band(- pages[2].remaining_lines,- pages[2].page_size,- page_index=2,- container_bboxes=[],- document_body_profile=profile,- title_candidate_source_indices={0, 2},- )-- assert first_article_title.semantic_type == "doc_title"- assert first_article_title_tail.semantic_type == "doc_title"- assert second_article_title.semantic_type == "doc_title"- assert later_section.semantic_type == "paragraph_title"---def test_document_body_profile_prefers_width_support_over_footer_page_count() -> None:- """验证窄页脚覆盖更多页面时,累计行宽更大的正文高度仍优先。"""-- body_font = ("Body", 0)- footer_font = ("Footer", 0)- pages = []- for page_index in range(4):- lines = [- _text_line(- f"footer-{page_index}",- (0.0, 90.0, 10.0, 98.0),- 100,- effective_height=8.0,- font_signature=footer_font,- font_coverage=1.0,- )- ]- if page_index < 3:- lines.extend(- _text_line(- f"body-{page_index}-{row_index}",- (0.0, 10.0 + 12.0 * row_index, 100.0, 20.0 + 12.0 * row_index),- row_index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for row_index in range(4)- )- pages.append(_prepared_text_page(*lines))-- profile = titles._infer_document_body_profile(pages)-- assert profile is not None- assert profile.body_height == pytest.approx(10.0)- assert profile.regular_fonts == frozenset({body_font})---def test_body_height_section_titles_mark_only_repeated_short_anchors() -> None:- """验证同字号短章节锚点独立成标题,明细、联系方式和版权行保持正文。"""-- body_font = ("Body", 0)- lines = [- _text_line("first section", (0.0, 10.0, 20.0, 20.0), 0),- _text_line("wide body one", (0.0, 24.0, 100.0, 34.0), 1),- _text_line("wide body two", (0.0, 36.0, 100.0, 46.0), 2),- _text_line("wide body three", (0.0, 48.0, 100.0, 58.0), 3),- _text_line("second section", (0.0, 72.0, 20.0, 82.0), 4),- _text_line("compact row one", (0.0, 84.0, 60.0, 94.0), 5),- _text_line("compact row two", (0.0, 96.0, 60.0, 106.0), 6),- _text_line("compact row three", (0.0, 108.0, 60.0, 118.0), 7),- _text_line("boxed label", (0.0, 132.0, 20.0, 142.0), 8),- _text_line("boxed row one", (0.0, 144.0, 100.0, 154.0), 9),- _text_line("boxed row two", (0.0, 156.0, 100.0, 166.0), 10),- _text_line("boxed row three", (0.0, 168.0, 100.0, 178.0), 11),- _text_line("contact label", (0.0, 192.0, 20.0, 202.0), 12),- _text_line("small address", (0.0, 204.0, 60.0, 212.0), 13, effective_height=8.0),- _text_line("small phone", (0.0, 214.0, 60.0, 222.0), 14, effective_height=8.0),- _text_line("small email", (0.0, 224.0, 60.0, 232.0), 15, effective_height=8.0),- _text_line("copyright", (0.0, 250.0, 20.0, 260.0), 16),- ]- for line in lines:- line.font_signature = body_font- line.font_coverage = 1.0- line.dominant_font_weight = 250.0-- titles._classify_body_height_section_titles(- lines,- (100.0, 280.0),- container_bboxes=[(0.0, 128.0, 100.0, 180.0)],- document_body_profile=models._DocumentBodyProfile(- body_height=10.0,- body_weight=250.0,- regular_fonts=frozenset({body_font}),- ),- )-- assert [lines[index].semantic_type for index in (0, 4)] == [- "paragraph_title",- "paragraph_title",- ]- assert all(line.semantic_type is None for index, line in enumerate(lines) if index not in {0, 4})---def test_physical_title_gap_ignores_disjoint_column_and_keeps_overlapping_row() -> None:- """验证物理邻行只在水平投影相交时参与标题留白,避免另一栏正文压缩间距。"""-- target = _text_line("target", (0.0, 40.0, 40.0, 50.0), 0)- disjoint = _text_line("other column", (60.0, 39.0, 100.0, 49.0), 1)- overlapping = _text_line("wide row", (0.0, 25.0, 100.0, 35.0), 2)-- gaps = titles._build_physical_title_gap_map(- [(target, target.bbox), (disjoint, disjoint.bbox), (overlapping, overlapping.bbox)]- )-- assert gaps[target.source_index] == (5.0, None)---def test_grid_title_suppression_requires_two_distinct_parallel_bands() -> None:- """验证单个三栏短首行带不足以抑制标题,重复两带才形成信息网格证据。"""-- lanes = []- source_index = 0- for lane_index in range(3):- left = 110.0 * lane_index- first_opener = _text_line(- f"opener-{lane_index}-0",- (left, 10.0, left + 20.0, 20.0),- source_index,- )- source_index += 1- first_body = _text_line(- f"body-{lane_index}-0",- (left, 20.0, left + 80.0, 30.0),- source_index,- )- source_index += 1- lanes.append(- models._TextLane(- left=left,- right=left + 100.0,- lines=[- (first_opener, first_opener.bbox),- (first_body, first_body.bbox),- ],- )- )-- assert titles._find_repeated_grid_title_suppressions(lanes, 10.0) == set()-- second_band_sources = set()- for lane in lanes[:2]:- second_opener = _text_line(- "second opener",- (lane.left, 40.0, lane.left + 20.0, 50.0),- source_index,- )- second_band_sources.add(source_index)- source_index += 1- second_body = _text_line(- "second body",- (lane.left, 50.0, lane.left + 80.0, 60.0),- source_index,- )- source_index += 1- lane.lines.extend([(second_opener, second_opener.bbox), (second_body, second_body.bbox)])-- suppressions = titles._find_repeated_grid_title_suppressions(lanes, 10.0)-- assert second_band_sources <= suppressions- assert len(suppressions) == 5---def test_centered_smaller_paragraph_title_uses_layout_contrast_only() -> None:- """验证同字体的小字号居中标题可由栏宽和上下留白识别。"""-- body_font = ("Body", 0)- lines = [- _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "neutral label",- (30.0, 45.0, 70.0, 53.0),- 2,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("body three", (0.0, 66.0, 100.0, 76.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 78.0, 100.0, 88.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body five", (0.0, 90.0, 100.0, 100.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type == "paragraph_title"---def test_centered_smaller_paragraph_title_accepts_compact_text_section() -> None:- """验证小字号居中标题可由紧随其后的连续小字号正文区段支撑。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body {index}",- (0.0, 12.0 * index, 100.0, 12.0 * index + 10.0),- index,- font_signature=body_font,- font_coverage=1.0,- )- for index in range(5)- ]- lines.extend(- [- _text_line(- "neutral label",- (30.0, 70.0, 70.0, 78.0),- 5,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("compact row one", (0.0, 84.0, 100.0, 92.0), 6, effective_height=8.0),- _text_line("compact row two", (0.0, 94.0, 100.0, 102.0), 7, effective_height=8.0),- _text_line("compact row three", (0.0, 104.0, 100.0, 112.0), 8, effective_height=8.0),- ]- )-- titles._classify_page_titles(lines, (100.0, 140.0), page_index=1, container_bboxes=[])-- assert lines[5].semantic_type == "paragraph_title"--[email protected]("failure_mode", ["too_few", "narrow", "large_gap"])-def test_centered_smaller_paragraph_title_rejects_incomplete_compact_section(- failure_mode: str,-) -> None:- """验证不足三行、行宽不足或行距中断的小字号区段不能放宽标题。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body {index}",- (0.0, 12.0 * index, 100.0, 12.0 * index + 10.0),- index,- font_signature=body_font,- font_coverage=1.0,- )- for index in range(5)- ]- compact_rows = [- _text_line("compact row one", (0.0, 84.0, 100.0, 92.0), 6, effective_height=8.0),- _text_line("compact row two", (0.0, 94.0, 100.0, 102.0), 7, effective_height=8.0),- _text_line("compact row three", (0.0, 104.0, 100.0, 112.0), 8, effective_height=8.0),- ]- if failure_mode == "too_few":- compact_rows.pop()- elif failure_mode == "narrow":- compact_rows[-1].bbox = (0.0, 104.0, 40.0, 112.0)- else:- compact_rows[-1].bbox = (0.0, 114.0, 100.0, 122.0)- lines.append(- _text_line(- "neutral label",- (30.0, 70.0, 70.0, 78.0),- 5,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- )- )- lines.extend(compact_rows)-- titles._classify_page_titles(lines, (100.0, 140.0), page_index=1, container_bboxes=[])-- assert lines[5].semantic_type is None---def test_multiline_document_title_does_not_absorb_author_line() -> None:- """验证首页两行大字号标题合并为文档标题,较小作者行保持普通文本。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line(- "title line one",- (15.0, 20.0, 85.0, 34.4),- 0,- effective_height=14.4,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "title line two",- (10.0, 33.8, 90.0, 48.2),- 1,- effective_height=14.4,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "author names",- (20.0, 60.0, 80.0, 69.1),- 2,- effective_height=9.1,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line("body one", (0.0, 110.0, 100.0, 120.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 122.0, 100.0, 132.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body three", (0.0, 134.0, 100.0, 144.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(lines, (100.0, 200.0), page_index=0, container_bboxes=[])-- assert [line.semantic_type for line in lines[:3]] == ["doc_title", "doc_title", None]---def test_multiline_document_title_accepts_uncertain_mixed_dominant_font() -> None:- """验证混排标题主字体覆盖不稳定时仍可按字号、居中和字重合并。"""-- lines = [- _text_line(- "wide mixed title",- (5.0, 20.0, 95.0, 35.0),- 0,- effective_height=15.0,- font_signature=("MixedDominant", 0),- font_coverage=0.8,- dominant_font_weight=500.0,- ),- _text_line(- "wide title continuation",- (10.0, 36.0, 90.0, 50.0),- 1,- effective_height=14.0,- font_signature=("LocalTitle", 0),- font_coverage=1.0,- dominant_font_weight=500.0,- ),- _text_line(- "author",- (35.0, 60.0, 65.0, 69.0),- 2,- effective_height=9.0,- font_signature=("LocalTitle", 0),- font_coverage=1.0,- dominant_font_weight=500.0,- ),- _text_line("body one", (0.0, 110.0, 100.0, 120.0), 3),- _text_line("body two", (0.0, 122.0, 100.0, 132.0), 4),- _text_line("body three", (0.0, 134.0, 100.0, 144.0), 5),- ]-- titles._classify_page_titles(- lines,- (100.0, 200.0),- page_index=0,- container_bboxes=[],- )-- assert [line.semantic_type for line in lines[:3]] == ["doc_title", "doc_title", None]- blocks = text_blocks._build_text_blocks(lines, [], (100.0, 200.0))- title_blocks = [block for block in blocks if block["type"] == "doc_title"]- assert len(title_blocks) == 1- assert title_blocks[0]["content"] == "wide mixed title\nwide title continuation"---def test_compact_left_heading_accepts_one_body_height_following_gap() -> None:- """验证短标题与后继正文相隔约一行时仍可由局部样式过渡确认。"""-- body_font = ("Body", 0)- heading = _text_line(- "neutral heading",- (0.0, 45.0, 25.0, 56.0),- 3,- effective_height=11.0,- font_signature=("Heading", 0),- font_coverage=0.65,- )- lines = [- _text_line(- "body one",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body two",- (0.0, 12.0, 100.0, 22.0),- 1,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body three",- (0.0, 24.0, 100.0, 34.0),- 2,- font_signature=body_font,- font_coverage=1.0,- ),- heading,- _text_line(- "next body",- (0.0, 67.0, 100.0, 77.0),- 4,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "next body two",- (0.0, 79.0, 100.0, 89.0),- 5,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- titles._classify_page_titles(- lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )-- assert heading.semantic_type == "paragraph_title"---def test_same_font_body_tail_with_moderate_gap_is_not_title() -> None:- """验证同字体满行之后的短正文尾行不会因中等间距被升级为标题。"""-- body_font = ("Body", 0)- lines = [- _text_line("reference body", (0.0, 0.0, 100.0, 10.0), 0, effective_height=8.0),- _text_line("reference body two", (0.0, 10.0, 100.0, 20.0), 1, effective_height=8.0),- _text_line(- "local full body",- (0.0, 35.0, 100.0, 45.0),- 2,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "local body tail",- (0.0, 54.0, 60.0, 64.0),- 3,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("different section", (0.0, 80.0, 100.0, 90.0), 4),- _text_line("different continuation", (0.0, 92.0, 100.0, 102.0), 5),- ]-- titles._classify_page_titles(- lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )-- assert lines[3].semantic_type is None---def test_subset_font_visual_row_continues_into_short_body_tail() -> None:- """验证同一满行的拆分片段归一化子集字体后,短尾仍优先判为正文续行。"""-- first = _text_line(- "prefix",- (0.0, 0.0, 12.0, 10.0),- 0,- visual_row_id=10,- split_from_row=True,- font_signature=("SimSun", 0),- font_coverage=1.0,- )- second = _text_line(- "full row remainder",- (15.0, 0.0, 100.0, 10.0),- 1,- visual_row_id=10,- split_from_row=True,- font_signature=("ABCDEF+SimSun", 0),- font_coverage=1.0,- )- tail = _text_line(- "short tail",- (0.0, 12.0, 35.0, 22.0),- 2,- font_signature=("UVWXYZ+SimSun", 0),- font_coverage=1.0,- )- rows = [(line, line.bbox) for line in (first, second, tail)]- profile = models._LaneBodyProfile(- body_height=10.0,- body_font=("ABCDEF+SimSun", 0),- body_weight=400.0,- regular_gap=2.0,- style_support={},- )-- assert titles._continues_local_body_row(rows, 2, 100.0, profile)---def test_normal_body_font_needs_precise_centering_for_layout_title_fallback() -> None:- """验证普通正文样式只有精确居中且紧邻正文时才能使用版式标题兜底。"""-- body_font = ("Body", 0)- imprecise_lines = [- _text_line("body one", (0.0, 0.0, 100.0, 10.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 12.0, 100.0, 22.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line("imprecise label", (20.0, 35.0, 65.0, 45.0), 2, font_signature=body_font, font_coverage=1.0),- _text_line("body three", (0.0, 58.0, 100.0, 68.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 70.0, 100.0, 80.0), 4, font_signature=body_font, font_coverage=1.0),- ]- precise_lines = [- _text_line("body one", (0.0, 0.0, 100.0, 10.0), 10, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 12.0, 100.0, 22.0), 11, font_signature=body_font, font_coverage=1.0),- _text_line("precise label", (30.0, 35.0, 70.0, 45.0), 12, font_signature=body_font, font_coverage=1.0),- _text_line("body three", (0.0, 58.0, 100.0, 68.0), 13, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 70.0, 100.0, 80.0), 14, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(- imprecise_lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )- titles._classify_page_titles(- precise_lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )-- assert imprecise_lines[2].semantic_type is None- assert precise_lines[2].semantic_type == "paragraph_title"---def test_first_page_centered_body_style_metadata_does_not_use_title_fallback() -> None:- """验证首页上部普通字号居中元数据不会仅凭留白升级为段落标题。"""-- body_font = ("Body", 0)- lines = [- _text_line("metadata", (30.0, 20.0, 70.0, 30.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body one", (0.0, 43.0, 100.0, 53.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 55.0, 100.0, 65.0), 2, font_signature=body_font, font_coverage=1.0),- _text_line("body three", (0.0, 67.0, 100.0, 77.0), 3, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(- lines,- (100.0, 150.0),- page_index=0,- container_bboxes=[],- )-- assert lines[0].semantic_type is None---def test_first_page_centered_small_regular_metadata_requires_emphasis() -> None:- """验证首页正文区的小字号常规字体元数据不会仅凭居中和留白晋升。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "body above one",- (0.0, 10.0, 100.0, 20.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "body above two",- (0.0, 22.0, 100.0, 32.0),- 1,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "centered metadata",- (25.0, 48.0, 75.0, 55.0),- 2,- effective_height=7.0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "compact body one",- (0.0, 72.0, 100.0, 80.0),- 3,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "compact body two",- (0.0, 82.0, 100.0, 90.0),- 4,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "compact body three",- (0.0, 92.0, 100.0, 100.0),- 5,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._classify_page_titles(- lines,- (100.0, 140.0),- page_index=0,- container_bboxes=[],- document_body_profile=profile,- )-- assert lines[2].semantic_type is None---def test_first_page_hanging_title_rows_demote_to_text_geometry() -> None:- """验证近满栏缩进首行接栏左续行的标题组在首页降回正文。"""-- heading_font = ("Heading", 0)- first = _text_line(- "first row",- (10.0, 10.0, 100.0, 20.0),- 0,- font_signature=heading_font,- font_coverage=1.0,- semantic_type="paragraph_title",- )- second = _text_line(- "second row",- (0.0, 20.2, 55.0, 30.2),- 1,- font_signature=heading_font,- font_coverage=1.0,- semantic_type="paragraph_title",- )- lane = models._TextLane(- left=0.0,- right=100.0,- lines=[- (first, first.bbox),- (second, second.bbox),- ],- )- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({("Body", 0)}),- )-- titles._demote_hanging_multiline_text_titles(- [lane],- profile,- page_index=0,- )-- assert first.semantic_type is None- assert second.semantic_type is None- assert first.title_suppressed- assert second.title_suppressed---def test_inline_typography_reset_promotes_only_distinct_middle_row() -> None:- """验证短段尾、异字体短行和缩进正文的三行结构只提升中间行。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 0)- lines = [- _text_line(- "short tail",- (0.0, 0.0, 25.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "inline heading",- (0.0, 11.0, 45.0, 21.0),- 1,- font_signature=heading_font,- font_coverage=1.0,- ),- _text_line(- "indented body",- (18.0, 22.0, 100.0, 32.0),- 2,- font_signature=body_font,- font_coverage=1.0,- ),- ]- profile = models._DocumentBodyProfile(- body_height=10.0,- body_weight=400.0,- regular_fonts=frozenset({body_font}),- )-- titles._classify_inline_typography_reset_titles(- lines,- (100.0, 100.0),- container_bboxes=[],- document_body_profile=profile,- )- control = [- _text_line(- line.text,- line.bbox,- line.source_index,- font_signature=body_font,- font_coverage=1.0,- )- for line in lines- ]- titles._classify_inline_typography_reset_titles(- control,- (100.0, 100.0),- container_bboxes=[],- document_body_profile=profile,- )-- assert [line.semantic_type for line in lines] == [- None,- "paragraph_title",- None,- ]- assert all(line.semantic_type is None for line in control)---def test_cross_column_document_title_uses_thirteen_tenths_body_height_fallback() -> None:- """验证首页跨栏居中标题达到正文 1.30 倍时可命中,作者行保持正文类型。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line(- "wide title",- (20.0, 20.0, 180.0, 33.0),- 0,- effective_height=13.0,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "author row",- (60.0, 42.0, 140.0, 52.0),- 1,- effective_height=10.0,- font_signature=title_font,- font_coverage=1.0,- ),- ]- for row_index, top in enumerate((80.0, 92.0, 104.0, 116.0)):- lines.extend(- [- _text_line(- f"left body {row_index}",- (10.0, top, 90.0, top + 10.0),- 2 + row_index * 2,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- f"right body {row_index}",- (110.0, top, 190.0, top + 10.0),- 3 + row_index * 2,- font_signature=body_font,- font_coverage=1.0,- ),- ]- )-- titles._classify_page_titles(- lines,- (200.0, 200.0),- page_index=0,- container_bboxes=[],- )-- assert lines[0].semantic_type == "doc_title"- assert lines[1].semantic_type != "paragraph_title"---def test_complete_visual_row_promotes_number_and_demotes_inline_body() -> None:- """验证同字体编号整行晋升,标题字体与正文同排时整行降级并重新合并。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line("body one", (0.0, 5.0, 100.0, 15.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 17.0, 100.0, 27.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "2",- (0.0, 42.0, 8.0, 52.0),- 2,- visual_row_id=20,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "neutral heading",- (15.0, 42.0, 60.0, 52.0),- 3,- visual_row_id=20,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line("body three", (0.0, 65.0, 100.0, 75.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line(- "inline label",- (0.0, 82.0, 32.0, 92.0),- 5,- visual_row_id=30,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "inline body",- (34.0, 82.0, 100.0, 92.0),- 6,- visual_row_id=30,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("body four", (0.0, 94.0, 100.0, 104.0), 7, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(- lines,- (100.0, 140.0),- page_index=1,- container_bboxes=[],- )- merged = line_merging._merge_title_resolved_visual_rows(lines, (100.0, 140.0))-- numbered_title = next(line for line in merged if line.visual_row_id == 20)- inline_row = next(line for line in merged if line.visual_row_id == 30)- assert numbered_title.semantic_type == "paragraph_title"- assert numbered_title.text == "2 neutral heading"- assert inline_row.semantic_type is None- assert inline_row.text == "inline label inline body"---def test_low_coverage_mixed_weight_visual_row_demotes_inline_title() -> None:- """验证低字体覆盖率的同一视觉行仍按字重冲突识别为行内粗体正文。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "body one",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body two",- (0.0, 12.0, 100.0, 22.0),- 1,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body three",- (0.0, 24.0, 100.0, 34.0),- 2,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "inline label",- (0.0, 50.0, 35.0, 62.0),- 3,- visual_row_id=30,- split_from_row=True,- font_signature=("Heading", 0),- font_coverage=0.6,- dominant_font_weight=700.0,- ),- _text_line(- "inline body",- (37.0, 50.0, 100.0, 62.0),- 4,- visual_row_id=30,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=0.6,- dominant_font_weight=400.0,- ),- _text_line(- "body continuation",- (0.0, 64.0, 100.0, 74.0),- 5,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- ]-- titles._classify_page_titles(- lines,- (100.0, 100.0),- page_index=1,- container_bboxes=[],- )- merged = line_merging._merge_title_resolved_visual_rows(lines, (100.0, 100.0))-- inline_row = next(line for line in merged if line.visual_row_id == 30)- assert inline_row.semantic_type is None- assert inline_row.text == "inline label inline body"---def test_full_width_normal_height_inline_heading_merges_with_body_continuation() -> None:- """验证满栏正常字号粗体行降为正文,并只与其下方常规正文续接。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 1)- lines = [- _text_line("body one", (0.0, 0.0, 100.0, 10.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 12.0, 100.0, 22.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "inline heading",- (0.0, 40.0, 100.0, 50.0),- 2,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "continuation one",- (0.0, 52.0, 100.0, 62.0),- 3,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("continuation two", (0.0, 64.0, 100.0, 74.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("continuation three", (0.0, 76.0, 100.0, 86.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- titles._classify_page_titles(- lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )- blocks = text_blocks._build_text_blocks(lines, [], (100.0, 120.0))-- inline_block = next(block for block in blocks if block["content"].startswith("inline heading"))- assert lines[2].semantic_type is None- assert inline_block["type"] == "text"- assert "continuation one" in inline_block["content"]- assert "body two" not in inline_block["content"]---def test_dense_same_font_two_run_row_requires_complete_high_occupancy_geometry() -> None:- """验证双 run 正文仅在同字体、同基线、连续编号且占用充分时恢复。"""-- body_font = ("Body", 0)- dense_members = [- _text_line(- "left",- (0.0, 0.0, 48.0, 10.0),- 0,- visual_row_id=10,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "right",- (52.0, 0.0, 100.0, 10.0),- 1,- visual_row_id=10,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- sparse_members = [- _text_line(- "sparse left",- (0.0, 20.0, 30.0, 30.0),- 2,- visual_row_id=20,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "sparse right",- (70.0, 20.0, 100.0, 30.0),- 3,- visual_row_id=20,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- partial_formula_row = [- _text_line(- "formula body",- (0.0, 40.0, 48.0, 50.0),- 4,- visual_row_id=30,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "sidecar",- (52.0, 40.0, 100.0, 50.0),- 5,- visual_row_id=30,- run_index=2,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- different_font_members = [- dense_members[0],- _text_line(- "different",- (52.0, 0.0, 100.0, 10.0),- 6,- visual_row_id=10,- run_index=1,- split_from_row=True,- font_signature=("Math", 0),- font_coverage=1.0,- ),- ]-- assert line_merging._is_dense_same_font_two_run_row(dense_members, (100.0, 100.0))- assert not line_merging._is_dense_same_font_two_run_row(sparse_members, (100.0, 100.0))- assert not line_merging._is_dense_same_font_two_run_row(partial_formula_row, (100.0, 100.0))- assert not line_merging._is_dense_same_font_two_run_row(different_font_members, (100.0, 100.0))-- merged = line_merging._merge_title_resolved_visual_rows(- dense_members + sparse_members,- (100.0, 100.0),- )- assert [line.text for line in merged if line.visual_row_id == 10] == ["left right"]- assert len([line for line in merged if line.visual_row_id == 20]) == 2---def test_preserved_split_boundary_blocks_dense_and_title_row_restoration() -> None:- """验证空间分栏保护同时阻止密集正文恢复和段落标题同行恢复。"""-- body_font = ("Body", 0)- protected_members = [- _text_line(- "left",- (0.0, 0.0, 48.0, 10.0),- 0,- visual_row_id=10,- run_index=0,- split_from_row=True,- preserve_split_boundary=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "right",- (52.0, 0.0, 100.0, 10.0),- 1,- visual_row_id=10,- run_index=1,- split_from_row=True,- preserve_split_boundary=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]-- assert not line_merging._is_dense_same_font_two_run_row(- protected_members,- (100.0, 100.0),- )- assert not line_merging._can_restore_dense_split_visual_row(- protected_members,- (100.0, 100.0),- [],- {0: (0, 0), 1: (0, 0)},- )-- protected_titles = [- _text_line(- member.text,- member.bbox,- member.source_index,- visual_row_id=member.visual_row_id,- run_index=member.run_index,- split_from_row=True,- preserve_split_boundary=True,- font_signature=body_font,- font_coverage=1.0,- semantic_type="paragraph_title",- )- for member in protected_members- ]- merged = line_merging._merge_title_resolved_visual_rows(- protected_titles,- (100.0, 100.0),- )-- assert [line.text for line in merged] == ["left", "right"]---def test_paragraph_title_detector_does_not_read_line_text() -> None:- """守卫段落标题候选、打分和邻行扩展不读取文本内容。"""-- source = "\n".join(- inspect.getsource(function)- for function in (- titles._classify_page_titles,- titles._classify_inline_typography_reset_titles,- titles._infer_document_body_profile,- titles._classify_body_height_section_titles,- titles._body_height_section_followers,- titles._infer_document_title_profile,- titles._title_profile_seed_matches_cluster,- titles._title_profile_alignment,- titles._document_font_is_regular,- titles._build_physical_title_gap_map,- titles._find_repeated_grid_title_suppressions,- titles._find_container_visual_row_title_suppressions,- titles._infer_lane_body_profile,- titles._classify_document_title,- titles._document_title_fonts_compatible,- titles._document_title_uses_page_fallback,- titles._classify_paragraph_titles_in_lane,- titles._line_uses_document_regular_font,- titles._matching_document_title_prototype,- titles._line_inside_visual_container,- titles._visual_row_has_body_style_sibling,- titles._is_near_full_mixed_inline_row,- titles._continues_local_body_row,- titles._is_continuous_field_row,- titles._is_full_width_inline_heading,- titles._has_following_body_row,- titles._has_following_compact_text_section,- titles._unify_visual_row_title_types,- titles._protect_front_matter_title_types,- titles._infer_front_matter_boundary,- titles._normalized_title_gap,- titles._line_near_visual_container,- titles._is_wide_leading_title_continuation,- titles._demote_hanging_multiline_text_titles,- line_layout._title_fonts_compatible,- titles._expand_paragraph_title_neighbors,- )- )-- assert ".text" not in source---def test_cross_lane_title_expansion_accepts_only_wide_leading_line() -> None:- """验证较宽首行可并入下方窄标题锚点,反向的正文续行不会被扩成标题。"""-- heading_font = ("Heading", 0)- leading = _text_line(- "wide leading line",- (72.0, 20.0, 287.0, 30.0),- 0,- font_signature=heading_font,- font_coverage=1.0,- )- anchor = _text_line(- "narrow anchor",- (130.0, 30.6, 230.0, 40.6),- 1,- semantic_type="paragraph_title",- font_signature=heading_font,- font_coverage=1.0,- )- following = _text_line(- "wide following line",- (72.0, 41.2, 287.0, 51.2),- 2,- font_signature=heading_font,- font_coverage=1.0,- )-- titles._expand_cross_lane_paragraph_title_neighbors(- [(leading, leading.bbox), (anchor, anchor.bbox), (following, following.bbox)]- )-- assert leading.semantic_type == "paragraph_title"- assert following.semantic_type is Nonediff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.pydeleted file mode 100644index 69644549..00000000--- a/tests/unittest/test_flash_pdf_visual_annotations.py+++ /dev/null@@ -1,928 +0,0 @@-from __future__ import annotations--import pytest--from docvortex.analyzers.native.pdf import geometry-from docvortex.analyzers.native.pdf import pipeline-from docvortex.analyzers.native.pdf import text_blocks-from docvortex.analyzers.native.pdf import visual_annotations---_PAGE_SIZE = (200.0, 200.0)---def _text_block(- content: str,- bbox: tuple[float, float, float, float],- *,- block_type: str = "text",- row_id: int | None = None,- line_height: float = 10.0,- local_bbox: tuple[float, float, float, float] | None = None,- lane_interval: tuple[float, float] | None = None,- lane_is_span: bool = False,- font_signature: tuple[str, int] | None = ("TestFont", 400),-) -> dict[str, object]:- """构造带稳定行框、字体和栏带元数据的独立文本测试块。"""-- return {- "type": block_type,- "bbox": bbox,- "angle": 0,- "content": content,- "_line_heights": [line_height],- "_local_line_bboxes": [local_bbox or bbox],- "_font_signatures": {font_signature} if font_signature else set(),- "_visual_row_ids": {row_id} if row_id is not None else set(),- "_single_run_row_id": row_id,- "_lane_interval": lane_interval or (bbox[0], bbox[2]),- "_lane_is_span": lane_is_span,- }---def _visual_block(- bbox: tuple[float, float, float, float],- *,- block_type: str = "image",-) -> dict[str, object]:- """构造不包含内部文本的视觉主体测试块。"""-- return {- "type": block_type,- "bbox": bbox,- "angle": 0,- "content": "",- }---def _classify_with_text_block_merge(- blocks: list[dict[str, object]],-) -> list[list[dict[str, object]]]:- """通过 pipeline 使用的文本合并回调运行视觉注释分类。"""-- return visual_annotations._classify_and_bind_visual_annotations(- blocks,- _PAGE_SIZE,- merge_text_block_group=text_blocks._merge_internal_text_block_group,- )--- "content",- [- "Fig. 2. Overview",- "Figure A1: Overview",- "Tab. 2-1 Results",- "Table IV. Results",- "Alg. 1 Procedure",- "Algorithm 2: Procedure",- "Listing 3 Source code",- "Chart 4: Revenue",- "Scheme Ⅴ. Architecture",- "图20:系统结构",- "图表2-1 行业走势",- "表格三 实验结果",- "算法 A1:训练流程",- "程序清单2 示例",- ],-)-def test_strong_caption_markers_accept_numbered_titles(content: str) -> None:- """验证中英文强标题标记兼容常用编号写法。"""-- assert visual_annotations._is_strong_caption_text(content)--- "content",- [- "Figure 2 shows the result.",- "Table 1, 2 and 3 show the results.",- "Figure without a number",- "图2为系统结构。",- "表1展示实验结果。",- "图6和图7分别为输入与输出。",- "图 8(a)、8(b)分别为两个模型的结果。",- "普通正文中的 Figure 2",- ],-)-def test_strong_caption_markers_reject_body_references(content: str) -> None:- """验证正文引用、并列编号和无编号标签不会进入标题候选。"""-- assert not visual_annotations._is_strong_caption_text(content)---def test_stacked_bilingual_captions_share_visual_parent() -> None:- """验证编号相同、上下紧邻的中英文图题共同绑定一个图片。"""-- image = _visual_block((20.0, 20.0, 180.0, 120.0))- chinese = _text_block(- "图 1 系统结构",- (55.0, 125.0, 145.0, 135.0),- )- english = _text_block(- "Fig. 1 System architecture",- (50.0, 138.0, 150.0, 145.0),- line_height=7.0,- font_signature=("EnglishCaption", 400),- )- blocks = [image, chinese, english]-- regions = _classify_with_text_block_merge(blocks)-- assert chinese["type"] == english["type"] == "caption"- assert regions == [[image, chinese, english]]--- "content",- [- "Source: survey",- "Sources: survey",- "Source(s): survey",- "Data source: survey",- "Note: adjusted values",- "Note(s): adjusted values",- "资料来源:公司公告",- "数据来源:统计局",- "来源:作者整理",- "注:数值经过调整",- "备注:数值经过调整",- ],-)-def test_strong_footnote_markers_require_colon_and_body(content: str) -> None:- """验证来源与注释强规则要求冒号和实际正文。"""-- assert visual_annotations._is_strong_footnote_text(content)--- "content",- ["Note that the value changes.", "Source material is public.", "注释内容", "来源:"],-)-def test_strong_footnote_markers_reject_narrative_text(content: str) -> None:- """验证无冒号的叙述句和空标记不会进入脚注候选。"""-- assert not visual_annotations._is_strong_footnote_text(content)--- ("caption_bbox", "expected_order"),- [- ((40.0, 25.0, 80.0, 35.0), ("caption", "image")),- ((40.0, 85.0, 80.0, 95.0), ("image", "caption")),- ((5.0, 40.0, 35.0, 80.0), ("caption", "image")),- ((85.0, 40.0, 115.0, 80.0), ("image", "caption")),- ],-)-def test_caption_binds_on_all_four_sides(- caption_bbox: tuple[float, float, float, float],- expected_order: tuple[str, str],-) -> None:- """验证上下左右紧邻标题均能绑定,并按相对方向展开。"""-- caption = _text_block("Figure 1: Overview", caption_bbox)- image = _visual_block((40.0, 40.0, 80.0, 80.0))- blocks = [caption, image]-- regions = _classify_with_text_block_merge(blocks)-- assert caption["type"] == "caption"- assert len(regions) == 1- assert tuple(block["type"] for block in regions[0]) == expected_order---def test_rotated_caption_uses_parent_local_coordinates() -> None:- """验证九十度页面块会先转入共同局部坐标再判断上方标题。"""-- caption = _text_block("Figure 1: Rotated", (165.0, 40.0, 175.0, 80.0))- image = _visual_block((120.0, 40.0, 160.0, 80.0))- caption["angle"] = image["angle"] = 90-- regions = visual_annotations._classify_and_bind_visual_annotations(- [caption, image],- _PAGE_SIZE,- )-- assert caption["type"] == "caption"- assert regions == [[caption, image]]---def test_caption_rejects_more_than_one_line_height_penetration() -> None:- """验证边缘轻微浮入主体可接受,深入超过自身一行高则保持 text。"""-- image = _visual_block((40.0, 40.0, 80.0, 80.0))- accepted = _text_block("Figure 1: Accepted", (40.0, 72.0, 80.0, 82.0))- accepted_regions = visual_annotations._classify_and_bind_visual_annotations(- [image, accepted],- _PAGE_SIZE,- )-- rejected = _text_block("Figure 2: Rejected", (40.0, 69.0, 80.0, 79.0))- rejected_regions = visual_annotations._classify_and_bind_visual_annotations(- [image.copy(), rejected],- _PAGE_SIZE,- )-- assert accepted["type"] == "caption"- assert accepted_regions- assert rejected["type"] == "text"- assert rejected_regions == []---def test_footnote_accepts_six_line_gap_but_rejects_farther_text() -> None:- """验证视觉块下方脚注的六行高距离上限为闭区间。"""-- image = _visual_block((20.0, 20.0, 100.0, 50.0))- accepted = _text_block("Note: accepted", (20.0, 110.0, 100.0, 120.0))- accepted_blocks = [image, accepted]- accepted_regions = visual_annotations._classify_and_bind_visual_annotations(- accepted_blocks,- _PAGE_SIZE,- )-- rejected = _text_block("Note: rejected", (20.0, 110.1, 100.0, 120.1))- rejected_blocks = [image.copy(), rejected]- rejected_regions = visual_annotations._classify_and_bind_visual_annotations(- rejected_blocks,- _PAGE_SIZE,- )-- assert accepted["type"] == "footnote"- assert [block["type"] for block in accepted_regions[0]] == ["image", "footnote"]- assert rejected["type"] == "text"- assert rejected_regions == []---def test_existing_visual_footnote_binds_without_content_marker() -> None:- """验证已有横线小字 footnote 无需再次命中内容规则即可加入区域。"""-- image = _visual_block((20.0, 20.0, 100.0, 60.0))- footnote = _text_block(- "calculated by the authors",- (20.0, 70.0, 100.0, 80.0),- block_type="footnote",- )-- regions = visual_annotations._classify_and_bind_visual_annotations(- [image, footnote],- _PAGE_SIZE,- )-- assert [block["type"] for block in regions[0]] == ["image", "footnote"]---def test_preclassified_table_annotations_keep_local_order_and_do_not_expand() -> None:- """验证预分类 caption/table/footnote 稳定成组,完整表注不吸收后续正文。"""-- caption = _text_block(- "unmarked table title",- (20.0, 10.0, 120.0, 20.0),- block_type="caption",- )- table = _visual_block((20.0, 30.0, 180.0, 70.0), block_type="table")- footnote = _text_block(- "1 numeric table note",- (20.0, 80.0, 140.0, 90.0),- block_type="footnote",- lane_interval=(20.0, 160.0),- )- footnote["_table_annotation_complete"] = True- continuation = _text_block(- "indented body text",- (30.0, 95.0, 150.0, 105.0),- lane_interval=(20.0, 160.0),- )- blocks = [table, continuation, footnote, caption]-- regions = _classify_with_text_block_merge(blocks)-- assert len(blocks) == 4- assert regions == [[caption, table, footnote]]- assert continuation["type"] == "text"---def test_table_footnote_merges_multiple_hanging_indent_continuations() -> None:- """验证表注强标记会吸收多个同栏悬挂缩进续块并保留内部元数据。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- anchor = _text_block(- "注:(1)首项。",- (20.0, 70.0, 100.0, 80.0),- row_id=1,- lane_interval=(20.0, 160.0),- )- continuation1 = _text_block(- "(2)续项。",- (30.0, 85.0, 130.0, 95.0),- row_id=2,- lane_interval=(20.0, 160.0),- )- continuation2 = _text_block(- "(3)末项。",- (30.0, 100.0, 150.0, 110.0),- row_id=3,- lane_interval=(20.0, 160.0),- )- blocks = [table, anchor, continuation1, continuation2]-- regions = _classify_with_text_block_merge(blocks)-- assert len(blocks) == 2- merged = blocks[1]- assert merged["type"] == "footnote"- assert merged["content"] == "注:(1)首项。(2)续项。(3)末项。"- assert merged["bbox"] == (20.0, 70.0, 150.0, 110.0)- assert merged["_local_line_bboxes"] == [- (20.0, 70.0, 100.0, 80.0),- (30.0, 85.0, 130.0, 95.0),- (30.0, 100.0, 150.0, 110.0),- ]- assert merged["_line_heights"] == [10.0, 10.0, 10.0]- assert merged["_font_signatures"] == {("TestFont", 400)}- assert merged["_visual_row_ids"] == {1, 2, 3}- assert merged["_single_run_row_id"] is None- assert regions == [[table, merged]]--- ("gap", "should_merge"),- [(13.5, True), (13.6, False)],-)-def test_table_footnote_uses_pair_median_gap_limit(- gap: float,- should_merge: bool,-) -> None:- """验证 page 31 型净空按配对中位行高的一点五倍闭区间判定。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- anchor = _text_block(- "注:(1)首项。",- (20.0, 70.0, 100.0, 78.0),- line_height=8.0,- lane_interval=(20.0, 160.0),- )- continuation = _text_block(- "(2)续项。",- (30.0, 78.0 + gap, 130.0, 88.0 + gap),- line_height=10.0,- lane_interval=(20.0, 160.0),- )- blocks = [table, anchor, continuation]-- regions = _classify_with_text_block_merge(blocks)-- if should_merge:- assert len(blocks) == 2- assert blocks[1]["content"] == "注:(1)首项。(2)续项。"- assert regions == [[table, blocks[1]]]- else:- assert blocks == [table, anchor, continuation]- assert regions == [[table, anchor]]--- "candidate",- [- _text_block(- "(2)间距过大。",- (30.0, 95.1, 130.0, 105.1),- lane_interval=(20.0, 160.0),- ),- _text_block(- "(2)没有悬挂缩进。",- (20.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- ),- _text_block(- "(2)字体不同。",- (30.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- font_signature=("OtherFont", 400),- ),- _text_block(- "(2)行高不同。",- (30.0, 85.0, 130.0, 95.0),- line_height=13.4,- lane_interval=(20.0, 160.0),- ),- _text_block(- "(2)栏带不同。",- (30.0, 85.0, 130.0, 95.0),- lane_interval=(30.0, 170.0),- ),- _text_block(- "(2)跨栏属性不同。",- (30.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- lane_is_span=True,- ),- ],-)-def test_table_footnote_rejects_incompatible_continuation(- candidate: dict[str, object],-) -> None:- """验证间距、缩进、字体、行高或栏带突变均终止表注聚合。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- anchor = _text_block(- "注:(1)首项。",- (20.0, 70.0, 100.0, 80.0),- lane_interval=(20.0, 160.0),- )- blocks = [table, anchor, candidate]-- regions = _classify_with_text_block_merge(blocks)-- assert len(blocks) == 3- assert anchor["type"] == "footnote"- assert candidate["type"] == "text"- assert regions == [[table, anchor]]--[email protected]("barrier_type", ["paragraph_title", "image"])-def test_table_footnote_does_not_skip_semantic_or_visual_barrier(- barrier_type: str,-) -> None:- """验证语义块或视觉块横隔栏带时,不会越过它吸收后续文本。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- anchor = _text_block(- "注:(1)首项。",- (20.0, 70.0, 100.0, 80.0),- lane_interval=(20.0, 160.0),- )- barrier = (- _text_block(- "正文标题",- (20.0, 85.0, 130.0, 95.0),- block_type=barrier_type,- lane_interval=(20.0, 160.0),- )- if barrier_type != "image"- else _visual_block((20.0, 85.0, 160.0, 95.0))- )- continuation = _text_block(- "(2)不得吸收。",- (30.0, 100.0, 130.0, 110.0),- lane_interval=(20.0, 160.0),- )- blocks = [table, anchor, barrier, continuation]-- _classify_with_text_block_merge(blocks)-- assert len(blocks) == 4- assert anchor["type"] == "footnote"- assert continuation["type"] == "text"---def test_table_footnote_stops_before_second_strong_annotation() -> None:- """验证第二个强标记注释保持独立,不会成为前一个表注的续块。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- first = _text_block(- "注:(1)首项。",- (20.0, 70.0, 100.0, 80.0),- lane_interval=(20.0, 160.0),- )- second = _text_block(- "备注:另一条注释。",- (20.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- )- blocks = [table, first, second]-- regions = _classify_with_text_block_merge(blocks)-- assert [block["type"] for block in blocks] == ["table", "footnote", "footnote"]- assert regions == [[table, first, second]]---def test_table_footnote_continuation_uses_rotated_local_coordinates() -> None:- """验证九十度表注在共同局部坐标中按相同缩进规则完成合并。"""-- angle = 90- table_local = (20.0, 20.0, 180.0, 60.0)- anchor_local = (20.0, 70.0, 100.0, 80.0)- continuation_local = (30.0, 85.0, 150.0, 95.0)- table = _visual_block(- geometry._rotate_bbox_from_upright(table_local, _PAGE_SIZE, angle),- block_type="table",- )- anchor = _text_block(- "注:(1)首项。",- geometry._rotate_bbox_from_upright(anchor_local, _PAGE_SIZE, angle),- local_bbox=anchor_local,- lane_interval=(20.0, 160.0),- )- continuation = _text_block(- "(2)续项。",- geometry._rotate_bbox_from_upright(- continuation_local,- _PAGE_SIZE,- angle,- ),- local_bbox=continuation_local,- lane_interval=(20.0, 160.0),- )- table["angle"] = anchor["angle"] = continuation["angle"] = angle- blocks = [table, anchor, continuation]-- regions = _classify_with_text_block_merge(blocks)-- assert len(blocks) == 2- merged_local_bbox = visual_annotations._block_local_bbox(- blocks[1],- _PAGE_SIZE,- angle,- )- assert merged_local_bbox == pytest.approx((20.0, 70.0, 150.0, 95.0))- assert regions == [[table, blocks[1]]]--[email protected]("visual_type", ["image", "code"])-def test_non_table_or_existing_footnote_does_not_expand_continuations(- visual_type: str,-) -> None:- """验证图片、代码脚注和既有 footnote 不进入表格强标记聚合范围。"""-- image = _visual_block(- (20.0, 20.0, 180.0, 60.0),- block_type=visual_type,- )- image_note = _text_block(- "注:(1)图片注释。",- (20.0, 70.0, 100.0, 80.0),- lane_interval=(20.0, 160.0),- )- image_continuation = _text_block(- "(2)图片续块。",- (30.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- )- image_blocks = [image, image_note, image_continuation]-- _classify_with_text_block_merge(image_blocks)-- table = _visual_block((20.0, 110.0, 180.0, 140.0), block_type="table")- existing_note = _text_block(- "既有脚注",- (20.0, 150.0, 100.0, 160.0),- block_type="footnote",- lane_interval=(20.0, 160.0),- )- existing_continuation = _text_block(- "缩进正文",- (30.0, 165.0, 130.0, 175.0),- lane_interval=(20.0, 160.0),- )- table_blocks = [table, existing_note, existing_continuation]-- _classify_with_text_block_merge(table_blocks)-- assert len(image_blocks) == 3- assert image_note["type"] == "footnote"- assert image_continuation["type"] == "text"- assert len(table_blocks) == 3- assert existing_note["type"] == "footnote"- assert existing_continuation["type"] == "text"---def test_caption_does_not_expand_hanging_indent_text() -> None:- """验证表格 caption 即使后接悬挂缩进正文也不会触发表注聚合。"""-- table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")- caption = _text_block(- "表1:测试表格",- (20.0, 70.0, 100.0, 80.0),- lane_interval=(20.0, 160.0),- )- continuation = _text_block(- "缩进正文",- (30.0, 85.0, 130.0, 95.0),- lane_interval=(20.0, 160.0),- )- blocks = [table, caption, continuation]-- regions = _classify_with_text_block_merge(blocks)-- assert blocks == [table, caption, continuation]- assert caption["type"] == "caption"- assert continuation["type"] == "text"- assert regions == [[table, caption]]--[email protected]("visual_type", ["image", "table", "code"])-def test_cross_lane_caption_companion_uses_geometry_for_all_visual_parents(- visual_type: str,-) -> None:- """验证三类跨栏视觉父块均可仅凭空间补标另一栏标题。"""-- parent = _visual_block(- (20.0, 20.0, 180.0, 80.0),- block_type=visual_type,- )- left_caption = _text_block(- "Figure 1: Spatial anchor",- (20.0, 90.5, 90.0, 120.5),- lane_interval=(20.0, 90.0),- )- right_companion = _text_block(- "plain continuation without a caption marker",- (110.0, 90.0, 180.0, 110.0),- lane_interval=(110.0, 180.0),- )- body = _text_block(- "ordinary body paragraph",- (20.0, 135.0, 90.0, 165.0),- line_height=13.0,- lane_interval=(20.0, 90.0),- )- blocks = [parent, left_caption, body, right_companion]-- regions = _classify_with_text_block_merge(blocks)- ordered = pipeline._sort_blocks_with_visual_row_groups(- blocks,- _PAGE_SIZE,- visual_annotation_regions=regions,- )-- assert left_caption["type"] == right_companion["type"] == "caption"- assert regions == [[parent, left_caption, right_companion]]- assert ordered == [parent, left_caption, right_companion, body]---def test_cross_lane_caption_companion_above_parent_keeps_left_to_right_order() -> None:- """验证父块上方的双栏标题同样按左栏、右栏、主体展开。"""-- table = _visual_block(- (20.0, 80.0, 180.0, 130.0),- block_type="table",- )- left_caption = _text_block(- "Table 1: Spatial anchor",- (20.0, 60.0, 90.0, 70.0),- lane_interval=(20.0, 90.0),- )- right_companion = _text_block(- "plain continuation",- (110.0, 59.5, 180.0, 69.5),- lane_interval=(110.0, 180.0),- )- blocks = [table, right_companion, left_caption]-- regions = _classify_with_text_block_merge(blocks)-- assert left_caption["type"] == right_companion["type"] == "caption"- assert regions == [[left_caption, right_companion, table]]---def test_cross_lane_caption_companion_uses_rotated_local_coordinates() -> None:- """验证旋转页面在共同局部坐标中完成跨栏匹配和行内排序。"""-- angle = 90- parent_local = (20.0, 20.0, 180.0, 80.0)- left_local = (20.0, 90.5, 90.0, 110.5)- right_local = (110.0, 90.0, 180.0, 110.0)- parent = _visual_block(- geometry._rotate_bbox_from_upright(parent_local, _PAGE_SIZE, angle),- )- left_caption = _text_block(- "Figure 1: Rotated anchor",- geometry._rotate_bbox_from_upright(left_local, _PAGE_SIZE, angle),- local_bbox=left_local,- lane_interval=(20.0, 90.0),- )- right_companion = _text_block(- "plain rotated continuation",- geometry._rotate_bbox_from_upright(- right_local,- _PAGE_SIZE,- angle,- ),- local_bbox=right_local,- lane_interval=(110.0, 180.0),- )- parent["angle"] = left_caption["angle"] = right_companion["angle"] = angle- blocks = [parent, right_companion, left_caption]-- regions = _classify_with_text_block_merge(blocks)-- assert left_caption["type"] == right_companion["type"] == "caption"- assert regions == [[parent, left_caption, right_companion]]--- "case",- [- "no_anchor",- "same_lane",- "misaligned",- "line_height",- "font",- "missing_font",- "span_lane",- "narrow_parent",- "barrier",- "competing_parent",- ],-)-def test_cross_lane_caption_companion_rejects_unsafe_geometry(case: str) -> None:- """验证缺少任一关键空间或排版证据时不补标跨栏标题。"""-- parent = _visual_block((20.0, 20.0, 180.0, 80.0))- anchor = _text_block(- "ordinary text" if case == "no_anchor" else "Figure 1: Spatial anchor",- (20.0, 90.5, 90.0, 110.5),- lane_interval=(20.0, 90.0),- )- companion_bbox = (110.0, 94.0, 180.0, 114.0) if case == "misaligned" else (110.0, 90.0, 180.0, 110.0)- companion = _text_block(- "plain continuation",- companion_bbox,- line_height=12.0 if case == "line_height" else 10.0,- lane_interval=((20.0, 90.0) if case == "same_lane" else (110.0, 180.0)),- lane_is_span=case == "span_lane",- font_signature=(None if case == "missing_font" else ("OtherFont", 400) if case == "font" else ("TestFont", 400)),- )- extra_blocks: list[dict[str, object]] = []- if case == "narrow_parent":- parent["bbox"] = (20.0, 20.0, 90.0, 80.0)- elif case == "barrier":- extra_blocks.append(- _text_block(- "intervening body",- (110.0, 83.0, 180.0, 87.0),- lane_interval=(110.0, 180.0),- )- )- elif case == "competing_parent":- extra_blocks.append(_visual_block((110.0, 82.0, 180.0, 86.0)))- blocks = [parent, anchor, *extra_blocks, companion]-- _classify_with_text_block_merge(blocks)-- assert companion["type"] == "text"---def test_cross_lane_caption_companion_rejects_multiple_spatial_peers() -> None:- """验证一个锚点同时命中多个栏带时保持全部同伴为正文。"""-- parent = _visual_block((10.0, 20.0, 190.0, 80.0))- anchor = _text_block(- "Figure 1: Spatial anchor",- (10.0, 90.0, 60.0, 110.0),- lane_interval=(10.0, 60.0),- )- middle = _text_block(- "first possible continuation",- (75.0, 90.0, 125.0, 110.0),- lane_interval=(75.0, 125.0),- )- right = _text_block(- "second possible continuation",- (140.0, 90.0, 190.0, 110.0),- lane_interval=(140.0, 190.0),- )- blocks = [parent, anchor, middle, right]-- regions = _classify_with_text_block_merge(blocks)-- assert anchor["type"] == "caption"- assert middle["type"] == right["type"] == "text"- assert regions == [[parent, anchor]]---def test_cross_lane_caption_companion_rejects_multiple_caption_anchors() -> None:- """验证一个同伴被多个标题锚点认领时维持正文分类。"""-- parent = _visual_block((20.0, 20.0, 180.0, 80.0))- upper_anchor = _text_block(- "Figure 1: First spatial anchor",- (20.0, 90.0, 52.0, 110.0),- lane_interval=(20.0, 90.0),- )- lower_anchor = _text_block(- "Figure 2: Second spatial anchor",- (58.0, 90.0, 90.0, 110.0),- lane_interval=(20.0, 90.0),- )- companion = _text_block(- "plain shared continuation",- (110.0, 90.0, 180.0, 110.0),- lane_interval=(110.0, 180.0),- )- blocks = [parent, upper_anchor, lower_anchor, companion]-- regions = _classify_with_text_block_merge(blocks)-- assert upper_anchor["type"] == lower_anchor["type"] == "caption"- assert companion["type"] == "text"- assert regions == [[parent, upper_anchor, lower_anchor]]---def test_multi_panel_images_only_group_when_union_improves_coverage() -> None:- """验证跨面板标题绑定图片并集,而单图标题不会无故吞并相邻图片。"""-- caption = _text_block("Figure 1: Two panels", (10.0, 10.0, 90.0, 20.0))- left = _visual_block((10.0, 25.0, 45.0, 60.0))- right = _visual_block((50.0, 25.0, 90.0, 60.0))- blocks = [caption, left, right]-- regions = visual_annotations._classify_and_bind_visual_annotations(- blocks,- _PAGE_SIZE,- )-- assert len(regions) == 1- assert regions[0] == [caption, left, right]-- left_caption = _text_block("Figure 2: Left", (10.0, 10.0, 45.0, 20.0))- independent_blocks = [left_caption, left.copy(), right.copy()]- independent_regions = visual_annotations._classify_and_bind_visual_annotations(- independent_blocks,- _PAGE_SIZE,- )-- assert len(independent_regions) == 1- assert independent_regions[0] == [left_caption, independent_blocks[1]]---def test_nearest_parent_wins_and_intervening_body_blocks_cross_binding() -> None:- """验证竞争父块优先选择归一化边距更小者,正文阻挡远距绑定。"""-- upper = _visual_block((20.0, 10.0, 100.0, 40.0))- caption = _text_block("Figure 1: Upper", (20.0, 45.0, 100.0, 55.0))- lower = _visual_block((20.0, 80.0, 100.0, 110.0))- blocks = [upper, caption, lower]- regions = visual_annotations._classify_and_bind_visual_annotations(- blocks,- _PAGE_SIZE,- )-- assert regions == [[upper, caption]]-- body = _text_block("ordinary paragraph", (20.0, 55.0, 100.0, 65.0))- note = _text_block("Source: survey", (20.0, 75.0, 100.0, 85.0))- blocked = [upper.copy(), body, note]- blocked_regions = visual_annotations._classify_and_bind_visual_annotations(- blocked,- _PAGE_SIZE,- )-- assert note["type"] == "text"- assert blocked_regions == []---def test_visual_regions_prevent_cross_column_row_remerge() -> None:- """验证同一拆分视觉行的左右标题在区域化后不会先于两个主体一起输出。"""-- left_caption = _text_block(- "Chart 1: Left",- (10.0, 10.0, 80.0, 20.0),- row_id=7,- )- right_caption = _text_block(- "Chart 2: Right",- (110.0, 10.0, 180.0, 20.0),- row_id=7,- )- left_image = _visual_block((10.0, 25.0, 80.0, 70.0))- right_image = _visual_block((110.0, 25.0, 180.0, 70.0))- blocks = [left_caption, right_caption, left_image, right_image]- regions = visual_annotations._classify_and_bind_visual_annotations(- blocks,- _PAGE_SIZE,- )-- ordered = pipeline._sort_blocks_with_visual_row_groups(- blocks,- _PAGE_SIZE,- visual_annotation_regions=regions,- )-- assert ordered == [left_caption, left_image, right_caption, right_image]---def test_non_text_marginals_never_enter_visual_reclassification() -> None:- """验证 footer 与 page_footnote 即使内容像强规则也不会改为视觉脚注。"""-- image = _visual_block((20.0, 20.0, 100.0, 60.0))- footer = _text_block(- "Source: disclaimer",- (20.0, 70.0, 100.0, 80.0),- block_type="footer",- )- page_footnote = _text_block(- "Note: author affiliation",- (20.0, 85.0, 100.0, 95.0),- block_type="page_footnote",- )-- regions = visual_annotations._classify_and_bind_visual_annotations(- [image, footer, page_footnote],- _PAGE_SIZE,- )-- assert regions == []- assert footer["type"] == "footer"- assert page_footnote["type"] == "page_footnote"diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex 663a39ae..c08c3e1e 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -1,16 +1,12 @@from __future__ import annotations-from docvortex.export.middle import export_middle_jsonimport asynciofrom io import BytesIO-import subprocess-import sys-import tracemallocfrom pathlib import Path-from unittest.mock import patch-from zipfile import ZipFileimport pytest+from docvortex.analyzers.native.office.rtf.converter import extract_rtf_metadata+from docvortex.export.middle import export_middle_jsonfrom mineru.backend.analyze import aio_doc_analyze, doc_analyzefrom mineru.doclib.core import file_io@@ -18,27 +14,13 @@ from mineru.doclib.core.db import DatabaseManagerfrom mineru.doclib.core.fts import FTSManagerfrom mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestError-from docvortex.analyzers.native import RtfModel-from docvortex.analyzers.native.office.errors import LegacyOfficeMalformedError-from docvortex.analyzers.native.office.errors import LegacyOfficeResourceLimitError-from docvortex.analyzers.native.office.rtf import lexer as lexer_module-from docvortex.analyzers.native.office.rtf import parser as parser_module-from docvortex.analyzers.native.office.rtf.converter import extract_rtf_metadata-from docvortex.analyzers.native.office.rtf.lexer import RtfBinary-from docvortex.analyzers.native.office.rtf.lexer import RtfLexerfrom mineru.parser import parsefrom mineru.render import RenderMode, render_docx, render_html, render_markdown, render_structured_content-from mineru.types import BlockType-from _span_test_utils import inline, inline_text+_PROJECT_ROOT = Path(__file__).resolve().parents[2]-_PROJECT_ROOT = Path(__file__).resolve().parents[2]_SEMANTIC_RTF = _PROJECT_ROOT / "tests" / "fixtures" / "rtf" / "semantic.rtf"-_PNG_HEX = (- b"89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d24"- b"0000001549444154789c6394acb8f39f81818181094480300024350270cd4262d30000000049454e44ae426082"-)def _complex_rtf() -> bytes:@@ -46,230 +28,6 @@ def _complex_rtf() -> bytes:return _SEMANTIC_RTF.read_bytes()-def test_rtf_lexer_bin_payload_is_position_explicit() -> None:- """验证 bin 中的花括号和反斜杠不改变 lexer group 结构。"""- tokens = list(RtfLexer(rb"{\rtf1 before\bin5 }}{\x after}"))- binaries = [token for token in tokens if isinstance(token, RtfBinary)]-- assert [token.data for token in binaries] == [b"}}{\\x"]---def test_rtf_lexer_rejects_truncated_bin_payload() -> None:- """验证截断 bin 在游标失去可信边界前立即失败。"""- with pytest.raises(LegacyOfficeMalformedError, match="truncated"):- list(RtfLexer(rb"{\rtf1\bin9 ab}"))--- "control",- [- b"\\foo99999999999",- b"\\foo2147483648",- b"\\foo-2147483649",- b"\\bin99999999999 payload",- ],-)-def test_rtf_lexer_rejects_control_parameters_before_unbounded_int(control: bytes) -> None:- """验证超长或越界 control parameter 在整数转换和 bin 定位前失败。"""- with pytest.raises(LegacyOfficeResourceLimitError, match="control parameter"):- list(RtfLexer(b"{\\rtf1" + control + b"}"))---def test_rtf_lexer_accepts_signed_32_bit_control_parameter_boundaries() -> None:- """验证十位词法限制仍允许有符号 32 位参数边界。"""- tokens = list(RtfLexer(rb"{\rtf1\foo2147483647\bar-2147483648}"))- controls = [token for token in tokens if isinstance(token, lexer_module.RtfControlWord)]-- assert [(token.name, token.param) for token in controls[-2:]] == [- ("foo", 2_147_483_647),- ("bar", -2_147_483_648),- ]---def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:- """验证 per-font CP1251/CP932、多字节 hex 和 UTF-16 代理对恢复。"""- russian = b"".join(f"\\'{value:02x}".encode("ascii") for value in "Привет".encode("cp1251"))- japanese = b"".join(f"\\'{value:02x}".encode("ascii") for value in "こんにちは".encode("cp932"))- source = b"".join(- [- rb"{\rtf1\ansi{\fonttbl{\f0\fcharset204 Arial;}{\f1\fcharset128 MS Gothic;}}",- rb"\pard\f0 ",- russian,- rb" \f1 ",- japanese,- rb" \u-10179?\u-8704?\par}",- ]- )-- pages = RtfModel().predict(BytesIO(source))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("Привет こんにちは 😀")}]]---def test_rtf_metadata_decodes_consecutive_multibyte_hex_as_one_run() -> None:- """验证 metadata 定义组中的连续 GB18030 hex byte 按完整代码页序列解码。"""- encoded_title = b"".join(f"\\'{value:02x}".encode("ascii") for value in "中文".encode("gb18030"))- source = b"".join(- [- rb"{\rtf1\ansi\ansicpg936{\info{\title ",- encoded_title,- rb"}}Body\par}",- ]- )-- metadata = extract_rtf_metadata(BytesIO(source))- pages = RtfModel().predict(BytesIO(source))-- assert metadata["title"] == "中文"- assert pages == [[{"type": BlockType.TEXT, "content": inline("Body")}]]---def test_rtf_unicode_controls_buffer_adjacent_text_without_repeated_run_copy() -> None:- """验证逐字符 Unicode control 只在边界处物化文本 run。"""- count = 5_000- source = b"{\\rtf1\\ansi\\uc1 " + b"\\u20013?" * count + b"\\par}"-- with patch.object(parser_module, "replace", wraps=parser_module.replace) as replace_mock:- pages = RtfModel().predict(BytesIO(source))-- text_replacements = [- call- for call in replace_mock.call_args_list- if isinstance(call.args[0], parser_module.RtfTextRun) and "text" in call.kwargs- ]- assert pages == [[{"type": BlockType.TEXT, "content": inline("中" * count)}]]- assert text_replacements == []---def test_rtf_upr_prefers_unicode_branch_without_leaking_ansi_fallback() -> None:- """验证 Unicode-aware parser 在 upr 中只输出 ud 分支。"""- source = rb"{\rtf1\ansi Before {\upr{?}{\*\ud{\u20013?}}} After\par}"-- pages = RtfModel().predict(BytesIO(source))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("Before 中 After")}]]---def test_rtf_inherited_style_honors_explicit_formatting_resets() -> None:- """验证 derived stylesheet 的 b0/i0/ul0/strike0 覆盖基样式开启值。"""- source = (- rb"{\rtf1\ansi{\stylesheet{\s0\b\i\ul\strike Base;}{\s1\sbasedon0\b0\i0\ul0\strike0 Derived;}}\pard\s1 Reset text\par}"- )-- pages = RtfModel().predict(BytesIO(source))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("Reset text")}]]---def test_rtf_large_roman_list_start_falls_back_to_decimal() -> None:- """验证超出规范范围的 Roman 起始值直接回退十进制而不线性扩张。"""- source = b"".join(- [- rb"{\rtf1\ansi{\*\listtable{\list{\listlevel\levelnfc1\levelstartat2147483647}\listid7}}",- rb"{\*\listoverridetable{\listoverride\listid7\listoverridecount0\ls2}}",- rb"\pard\ls2\ilvl0 item\par}",- ]- )-- pages = RtfModel().predict(BytesIO(source))-- assert pages[0][0]["type"] == BlockType.LIST- assert pages[0][0]["content"][0]["list_label"] == "2147483647."---def test_rtf_model_recovers_unicode_styles_and_structures() -> None:- """验证完整 typed RTF 链路生成稳定单页 raw blocks。"""- stream = BytesIO(_complex_rtf())-- pages = RtfModel().predict(stream)-- assert not stream.closed- assert len(pages) == 1- blocks = pages[0]- assert [block["type"] for block in blocks].count(BlockType.TABLE) == 1- assert [block["type"] for block in blocks].count(BlockType.IMAGE) == 1- assert [block["type"] for block in blocks].count(BlockType.CODE) == 1- title = blocks[0]- assert title["type"] == BlockType.PARAGRAPH_TITLE- assert title["level"] == 2- assert title["anchor"] == "heading"- assert any(set(span.get("styles", [])) == {"bold", "italic"} for span in title["content"])- body = next(- block for block in blocks if block.get("type") == BlockType.TEXT and "Unicode" in inline_text(block.get("content"))- )- assert "中文" in inline_text(body["content"])- assert any("superscript" in span.get("styles", []) for span in body["content"])- link = next(- block for block in blocks if block.get("type") == BlockType.TEXT and "Jump heading" in inline_text(block.get("content"))- )- assert any(span.get("type") == "hyperlink" and span.get("url") == "#heading" for span in link["content"])- assert "javascript:" not in str(link["content"])- assert blocks[-3:] == [- {"type": BlockType.HEADER, "content": inline("Header text")},- {"type": BlockType.FOOTER, "content": inline("Footer text")},- {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] Foot body.")},- ]- code = next(block for block in blocks if block.get("type") == BlockType.CODE)- assert code["content"] == "first()\nsecond()"- table = next(block for block in blocks if block.get("type") == BlockType.TABLE)- assert 'colspan="2"' in table["content"]- assert "<th" in table["content"]---def test_rtf_page_controls_remain_inside_one_semantic_page() -> None:- """验证 page/column 只保留换行,sect 只结束段落。"""- pages = RtfModel().predict(BytesIO(rb"{\rtf1\ansi A\page B\column C\sect D\par}"))-- assert len(pages) == 1- assert pages[0] == [- {"type": BlockType.TEXT, "content": inline("A\nB\nC")},- {"type": BlockType.TEXT, "content": inline("D")},- ]---def test_rtf_nested_and_merged_tables_preserve_content() -> None:- """验证 nested table、cellx 投影及纵向 continuation 不丢可见文本。"""- source = rb"""{\rtf1\ansi-\trowd\clvmgf\cellx1000\cellx2000 A\cell B\cell\row-\trowd\clvmrg\cellx1000\cellx2000 \cell C\cell\row-\trowd\cellx1000\cellx2000-\pard\intbl\itap2 N1\nestcell N2\nestcell{\*\nesttableprops\trowd\cellx500\cellx1000\nestrow}-\pard\intbl outer\cell\row}"""-- pages = RtfModel().predict(BytesIO(source))-- tables = [block for block in pages[0] if block["type"] == BlockType.TABLE]- assert len(tables) == 1- html = tables[0]["content"]- assert 'rowspan="2"' in html- assert html.count("<table>") == 2- assert all(text in html for text in ("A", "B", "C", "N1", "N2", "outer"))---def test_rtf_math_picture_is_only_used_when_formula_conversion_fails() -> None:- """验证 Office Math 成功时去重预览,失败时保留首个安全 fallback 图片。"""- valid = b"".join(- [- rb"{\rtf1{\mmath{\*\moMath{\mr x}}{\mmathPict{\pict\pngblip ",- _PNG_HEX,- rb"}}}}",- ]- )- invalid = b"".join(- [- rb"{\rtf1{\mmath{\*\moMath{\munknown x}}{\mmathPict{\pict\pngblip ",- _PNG_HEX,- rb"}}}}",- ]- )-- valid_blocks = RtfModel().predict(BytesIO(valid))[0]- invalid_blocks = RtfModel().predict(BytesIO(invalid))[0]-- assert [block["type"] for block in valid_blocks] == [BlockType.EQUATION]- assert [block["type"] for block in invalid_blocks] == [BlockType.IMAGE]--def test_rtf_doc_analyze_and_renderers_share_strict_metadata() -> None:"""验证 RTF 同步/异步入口和四类 renderer 使用同一严格 Middle JSON。"""middle, model = doc_analyze(_complex_rtf(), effort="xhigh", parse_mode="ocr", file_suffix="rtf")@@ -415,210 +173,3 @@ def test_doclib_rejects_rtf_quality_tier_and_remote(assert exc_info.value.param == expected_paramasyncio.run(run())---def test_rtf_unknown_destination_and_unbalanced_tail_recover_visible_text() -> None:- """验证未知 ignorable destination 不泄漏,缺尾括号仍保留已恢复正文。"""- source = rb"{\rtf1\ansi{\*\unknown hidden}\pard visible\par"-- pages = RtfModel().predict(BytesIO(source))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("visible")}]]---def test_rtf_source_html_is_rendered_as_inert_text() -> None:- """验证源文档中的活动 HTML 外观不会进入 HTML renderer DOM。"""- middle, _ = doc_analyze(- rb"{\rtf1\ansi visible <script>alert(1)</script> and x < y\par}",- file_suffix="rtf",- )-- html = render_html(middle, standalone=False)- markdown = render_markdown(middle)-- assert "<script>" not in html- assert "<script>alert(1)</script>" in html- assert "<script>alert(1)</script>" in markdown---def test_rtf_literal_tag_protocol_remains_inert_text() -> None:- """验证普通 RTF 标签外观原文只生成 TextSpan,不能注入公式或链接。"""- source = (- rb"{\rtf1\ansi literal <eq>x</eq> and "- rb"<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>\par}"- )-- pages = RtfModel().predict(BytesIO(source))- middle, _ = doc_analyze(source, file_suffix="rtf")- markdown = render_markdown(middle)-- content = pages[0][0]["content"]- assert "<eq>x</eq>" in inline_text(content)- assert "<hyperlink>" in inline_text(content)- assert all(span.get("type") == "text" for span in content)- assert "](javascript:alert(1))" not in markdown---def test_rtf_footnote_literal_tag_protocol_remains_inert_text() -> None:- """验证 RTF 脚注标签外观原文只生成 TextSpan,不能注入公式或链接。"""- source = (- rb"{\rtf1\ansi Body{\footnote <eq>x</eq> and "- rb"<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>}\par}"- )-- middle, model = doc_analyze(source, file_suffix="rtf")- footnote = next(block for block in model.pages[0] if block.get("type") == BlockType.PAGE_FOOTNOTE)- markdown = render_markdown(middle)- docx = render_docx(middle)- with ZipFile(BytesIO(docx)) as package:- relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")-- assert "<eq>x</eq>" in inline_text(footnote["content"])- assert "<hyperlink>" in inline_text(footnote["content"])- assert all(span.get("type") == "text" for span in footnote["content"])- assert "](javascript:alert(1))" not in markdown- assert "javascript:alert(1)" not in relationships---def test_rtf_annotation_preserves_comment_as_page_footnote() -> None:- """验证 annotation 正文进入页脚注块且不会生成虚假的正文脚注引用。"""- source = rb"{\rtf1\ansi Before {\*\annotation Review comment} After\par}"-- pages = RtfModel().predict(BytesIO(source))-- assert pages[0][0]["type"] == BlockType.TEXT- assert inline_text(pages[0][0]["content"]).split() == ["Before", "After"]- assert "[1]" not in inline_text(pages[0][0]["content"])- assert pages[0][1] == {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] Review comment")}---def test_rtf_hidden_annotation_preserves_body_and_suppresses_metadata() -> None:- """验证隐藏批注可恢复正文,同时作者和标识元数据不会泄漏。"""- source = (- rb"{\rtf1\ansi Body {\v {\*\atnauthor Alice}{\*\atnid AB}\chatn"- rb"{\*\annotation Review <eq>x</eq> comment}} end\par}"- )-- pages = RtfModel().predict(BytesIO(source))-- footnote = next(block for block in pages[0] if block.get("type") == BlockType.PAGE_FOOTNOTE)- assert "Review <eq>x</eq> comment" in inline_text(footnote["content"])- assert "Alice" not in inline_text(footnote["content"])- assert "AB" not in inline_text(footnote["content"])- assert all(span.get("type") == "text" for span in footnote["content"])---def test_rtf_equation_only_paragraph_preserves_note_reference() -> None:- """验证纯公式段落仍保留脚注引用,不生成孤立脚注正文。"""- source = rb"{\rtf1\ansi\pard {\mmath{\*\moMath{\mr x}}}{\footnote Foot.}\par}"-- pages = RtfModel().predict(BytesIO(source))-- assert pages[0][0]["type"] == BlockType.TEXT- assert any(span.get("type") == "equation_inline" and span.get("content") == "x" for span in pages[0][0]["content"])- assert "[1]" in inline_text(pages[0][0]["content"])- assert pages[0][1] == {"type": BlockType.PAGE_FOOTNOTE, "content": inline("[1] Foot.")}---def test_rtf_object_keeps_safe_result_and_suppresses_objdata() -> None:- """验证对象载荷不执行不泄漏,但显式 result 文本仍可恢复。"""- pages = RtfModel().predict(BytesIO(rb"{\rtf1 before {\object{\*\objdata 41424344}{\result Visible object}} after\par}"))-- assert pages == [[{"type": BlockType.TEXT, "content": inline("before Visible object after")}]]---def test_rtf_malformed_vector_picture_is_locally_dropped() -> None:- """验证伪装 WMF 的 bin 字节不会生成占位图或破坏周围正文。"""- pages = RtfModel().predict(BytesIO(rb"{\rtf1 before {\pict\wmetafile8\bin5 abcde} after\par}"))-- assert pages == [- [- {"type": BlockType.TEXT, "content": inline("before")},- {"type": BlockType.TEXT, "content": inline("after")},- ]- ]---def test_rtf_valid_empty_and_invalid_header_have_distinct_results() -> None:- """合法空 RTF 返回空逻辑页,非 RTF 输入返回稳定 malformed 错误。"""- assert RtfModel().predict(BytesIO(rb"{\rtf1}")) == [[]]- with pytest.raises(LegacyOfficeMalformedError, match="not an RTF"):- RtfModel().predict(BytesIO(b"plain text"))---def test_rtf_resource_limits_are_fixed_and_non_configurable(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 token、group、input、asset、grid 和 nested-table 上限均硬失败。"""- monkeypatch.setattr(lexer_module, "MAX_RECORDS", 3)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_tokens"):- list(RtfLexer(rb"{\rtf1 text}"))-- monkeypatch.setattr(lexer_module, "MAX_RECORDS", 16_000_000)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_group_depth"):- list(RtfLexer(b"{" * 257 + b"}" * 257))-- monkeypatch.setattr(parser_module, "MAX_RTF_BYTES", 8)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_bytes"):- RtfModel().predict(BytesIO(rb"{\rtf1 too long}"))-- monkeypatch.setattr(parser_module, "MAX_RTF_BYTES", 128 * 1024 * 1024)- monkeypatch.setattr(parser_module, "MAX_ASSET_TOTAL_BYTES", 1)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):- RtfModel().predict(BytesIO(rb"{\rtf1{\pict\pngblip 89504e47}}"))-- monkeypatch.setattr(parser_module, "MAX_ASSET_TOTAL_BYTES", 128 * 1024 * 1024)- monkeypatch.setattr(parser_module, "MAX_GRID_SLOTS", 1)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):- RtfModel().predict(BytesIO(rb"{\rtf1\trowd\cellx1\cellx2 A\cell B\cell\row}"))-- monkeypatch.setattr(parser_module, "MAX_GRID_SLOTS", 4_000_000)- with pytest.raises(LegacyOfficeResourceLimitError, match="max_table_depth"):- RtfModel().predict(BytesIO(rb"{\rtf1\pard\intbl\itap5 nested\par}"))---def test_rtf_cell_definitions_enforce_budget_before_row_materialization(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 cellx 在定义列表增长阶段即执行 RTF 专用 cell 预算。"""- monkeypatch.setattr(parser_module, "MAX_RTF_TABLE_CELLS", 3)- source = rb"{\rtf1\trowd\cellx1\cellx2\cellx3\cellx4}"-- with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots=3"):- RtfModel().predict(BytesIO(source))---def test_rtf_prelude_nested_groups_do_not_materialize_overlapping_slices() -> None:- """验证 prelude 扫描深层 group 时峰值内存保持为输入规模常数倍。"""- payload_size = 256 * 1024- depth = 64- source = b"{\\rtf1" + b"{" * depth + b"x" * payload_size + b"}" * depth + b"}"-- tracemalloc.start()- try:- parser_module.parse_rtf_prelude(source)- _, peak_bytes = tracemalloc.get_traced_memory()- finally:- tracemalloc.stop()-- assert peak_bytes < len(source) * 4---def test_rtf_runtime_has_no_anydoc_dependency() -> None:- """验证依赖清单、源码导入和惰性模型加载均不包含 anydoc。"""- assert "firecrawl-anydoc" not in (_PROJECT_ROOT / "pyproject.toml").read_text(encoding="utf-8").lower()- assert all("import anydoc" not in path.read_text(encoding="utf-8") for path in (_PROJECT_ROOT / "mineru").rglob("*.py"))- script = "\n".join(- [- "import sys",- "from docvortex.analyzers.native import RtfModel",- "assert 'docvortex.analyzers.native.office.rtf.converter' not in sys.modules",- "pages = RtfModel().predict(__import__('io').BytesIO(b'{\\\\rtf1 ok}'))",- "assert pages == [[{'type': 'text', 'content': [{'type': 'text', 'content': 'ok'}]}]]",- "assert 'anydoc' not in sys.modules",- ]- )- completed = subprocess.run(- [sys.executable, "-c", script],- cwd=_PROJECT_ROOT,- capture_output=True,- text=True,- check=False,- )- assert completed.returncode == 0, completed.stderrdiff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.pydeleted file mode 100644index 2005190c..00000000--- a/tests/unittest/test_flash_shared_helpers.py+++ /dev/null@@ -1,200 +0,0 @@-from __future__ import annotations--import base64-from io import BytesIO-import struct-from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo--from PIL import Image-import pytest-from lxml import etree--from docvortex.analyzers.native._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES-from docvortex.analyzers.native._shared.hyperlink import sanitize_hyperlink_target-from docvortex.analyzers.native._shared.image import image_to_b64str-from docvortex.analyzers.native._shared.image import image_to_bytes-from docvortex.analyzers.native._shared.mathml import mathml_to_latex-from docvortex.analyzers.native.office.doc import records as doc_records-from docvortex.analyzers.native.office.legacy.binary import bounded_slice-from docvortex.analyzers.native.office.legacy.binary import get_f64-from docvortex.analyzers.native.office.legacy.binary import get_i16-from docvortex.analyzers.native.office.legacy.binary import get_u16-from docvortex.analyzers.native.office.legacy.binary import get_u32-from docvortex.analyzers.native.office.opc import relationship_source_base_dir-from docvortex.analyzers.native.office.opc import write_zip_package-from docvortex.analyzers.native.office.ppt import records as ppt_records-from docvortex.analyzers.native.office.rich_text import OfficeRichTextSegment-from docvortex.analyzers.native.office.rich_text import build_rich_text_from_segments-from docvortex.analyzers.native.office.xls import records as xls_records--- ("mode", "image_format", "expected_format"),- [- ("RGB", "JPEG", "JPEG"),- ("RGBA", "PNG", "PNG"),- ],-)-def test_shared_image_encoding_preserves_format_and_data_uri(- mode: str,- image_format: str,- expected_format: str,-) -> None:- """验证共享图片编码同时保留字节格式与 data URI 载荷。"""- image = Image.new(mode, (2, 3), (12, 34, 56, 78) if mode == "RGBA" else (12, 34, 56))-- image_bytes = image_to_bytes(image, image_format=image_format)- data_uri = image_to_b64str(image, image_format=image_format)- prefix, encoded = data_uri.split(",", 1)-- assert prefix == f"data:image/{image_format.lower()};base64"- assert base64.b64decode(encoded) == image_bytes- with Image.open(BytesIO(image_bytes)) as decoded:- assert decoded.format == expected_format- assert decoded.size == (2, 3)---def test_mathml_semantics_ignores_non_tex_alternate_annotations() -> None:- """验证 semantics 只转换主展示分支,不重复拼接非 TeX annotation。"""- math = etree.fromstring(- b'<math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mfrac><mi>x</mi><mn>2</mn></mfrac>'- b'<annotation-xml encoding="MathML-Content"><apply><divide/><ci>x</ci><cn>2</cn></apply></annotation-xml>'- b"</semantics></math>"- )-- assert mathml_to_latex(math) == r"\frac{x}{2}"--- ("token", "value", "expected"),- [- ("mi", "a_b", r"a\_b"),- ("mi", r"\name{x}", r"\backslash{}name\{x\}"),- ("mn", "12_3", r"12\_3"),- ("mi", "x^~", r"x\^{}\~{}"),- ("mi", "α", r"\alpha"),- ],-)-def test_mathml_literal_identifier_tokens_do_not_become_latex_syntax(token: str, value: str, expected: str) -> None:- """验证标识符和数字字面量转义 TeX 控制字符,同时保留显式希腊字母映射。"""- math = etree.fromstring(f'<math xmlns="http://www.w3.org/1998/Math/MathML"><{token}>{value}</{token}></math>'.encode())-- assert mathml_to_latex(math) == expected--[email protected]("extra_node", ["<!--producer note-->", "<?producer note?>"])-def test_mathml_annotation_scan_skips_non_element_nodes(extra_node: str) -> None:- """验证 TeX annotation 扫描跳过 XML comment 与处理指令。"""- math = etree.fromstring(- (- '<math xmlns="http://www.w3.org/1998/Math/MathML">'- f"{extra_node}"- '<semantics><mi>x</mi><annotation encoding="application/x-tex">x^2</annotation></semantics>'- "</math>"- ).encode()- )-- assert mathml_to_latex(math) == "x^2"--- ("target", "expected"),- [- ("https://example.com/path", "https://example.com/path"),- ("mailto:[email protected]", "mailto:[email protected]"),- ("#anchor", "#anchor"),- ("../relative/path", "../relative/path"),- ("javascript:alert(1)", None),- ("file:///tmp/local", None),- ("//example.com/path", None),- (r"C:\local\file", None),- ("https:///missing-host", None),- ("https://example.com/a\x01b", None),- ],-)-def test_shared_hyperlink_policy_rejects_active_and_local_targets(target: str, expected: str | None) -> None:- """验证共享策略统一处理外链、fragment、相对路径和危险目标。"""- assert (- sanitize_hyperlink_target(- target,- allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,- allow_relative=True,- allow_fragment=True,- )- == expected- )---def test_shared_hyperlink_spans_preserve_url_and_tag_literals() -> None:- """验证结构化链接保留 URL 与标签外观原文,危险目标降级为 TextSpan。"""- unsafe = build_rich_text_from_segments(- [OfficeRichTextSegment("<hyperlink>click</hyperlink>", hyperlink="javascript:alert(1)")]- )- safe = build_rich_text_from_segments(- [OfficeRichTextSegment("<b>click</b>", style="bold", hyperlink="https://example.com/?a=1&b=2")]- )-- assert unsafe == [{"type": "text", "content": "<hyperlink>click</hyperlink>"}]- assert safe == [- {- "type": "hyperlink",- "url": "https://example.com/?a=1&b=2",- "content": [{"type": "text", "content": "<b>click</b>", "styles": ["bold"]}],- }- ]---def test_legacy_binary_readers_preserve_bounds_and_values() -> None:- """验证旧版 Office 共用读取器只在完整边界内返回小端数值。"""- data = struct.pack("<HhId", 0xABCD, -123, 0x1234_5678, 1.25)-- assert get_u16(data, 0) == 0xABCD- assert get_i16(data, 2) == -123- assert get_u32(data, 4) == 0x1234_5678- assert get_f64(data, 8) == 1.25- assert get_u16(data, -1) is None- assert get_u32(data, len(data) - 3) is None- assert get_f64(data, len(data) - 7) is None- assert bounded_slice(data, 2, 4) == data[2:6]- assert bounded_slice(data, -1, 1) is None- assert bounded_slice(data, 0, -1) is None- assert bounded_slice(data, len(data), 1) is None---def test_format_record_modules_no_longer_export_duplicate_binary_readers() -> None:- """验证严格迁移后格式 records 模块不再暴露重复的读取函数。"""- for module in (doc_records, ppt_records, xls_records):- for name in ("get_u16", "get_i16", "get_u32", "get_f64", "bounded_slice"):- assert not hasattr(module, name)--- ("rels_filename", "expected"),- [- ("_rels/.rels", ""),- ("word/_rels/document.xml.rels", "word"),- ("ppt/slides/_rels/slide1.xml.rels", "ppt/slides"),- ("word/document.xml.rels", None),- ("word/_rels/document.xml", None),- ],-)-def test_opc_relationship_source_base_dir(rels_filename: str, expected: str | None) -> None:- """验证 OPC relationship 路径只接受根关系或规范 part 关系。"""- assert relationship_source_base_dir(rels_filename) == expected---def test_write_zip_package_preserves_member_data_and_metadata() -> None:- """验证共享写包器保留成员内容与 ZipInfo 元数据。"""- info = ZipInfo("word/document.xml", date_time=(2024, 1, 2, 3, 4, 6))- info.compress_type = ZIP_DEFLATED- info.external_attr = 0o640 << 16- payload = b"<document/>"-- package = write_zip_package([(info, payload)])-- with ZipFile(BytesIO(package)) as archive:- restored = archive.getinfo(info.filename)- assert archive.read(info.filename) == payload- assert restored.date_time == info.date_time- assert restored.compress_type == info.compress_type- assert restored.external_attr == info.external_attrdiff --git a/tests/unittest/test_flash_spreadsheet_projector.py b/tests/unittest/test_flash_spreadsheet_projector.pydeleted file mode 100644index 0cd2ef3f..00000000--- a/tests/unittest/test_flash_spreadsheet_projector.py+++ /dev/null@@ -1,269 +0,0 @@-from __future__ import annotations--from bs4 import BeautifulSoup-from openpyxl import Workbook-from openpyxl.cell.rich_text import CellRichText, TextBlock-from openpyxl.cell.text import InlineFont-from openpyxl.worksheet.worksheet import Worksheet-import pytest--from docvortex.analyzers.native.office.spreadsheet.html import render_spreadsheet_table-from docvortex.analyzers.native.office.spreadsheet.models import AnchoredBlock-from docvortex.analyzers.native.office.spreadsheet.models import ExcelCell-from docvortex.analyzers.native.office.spreadsheet.models import ExcelTable-from docvortex.analyzers.native.office.spreadsheet.models import SheetImage-from docvortex.analyzers.native.office.spreadsheet.projector import SpreadsheetProjector-from docvortex.analyzers.native.office.xls.xls_converter import _XlsPageBuilder-from docvortex.analyzers.native.office.xlsx import xlsx_converter as xlsx_converter_module-from docvortex.analyzers.native.office.xlsx.xlsx_converter import XlsxConverter-from mineru.types import BlockType--from _span_test_utils import inline---def _cell(- row: int,- col: int,- text: str,- *,- row_span: int = 1,- col_span: int = 1,- media: list[str] | None = None,- equations: list[str] | None = None,- text_is_html: bool = False,- source_row: int | None = None,- source_col: int | None = None,-) -> ExcelCell:- """构造具有完整默认值的共享单元格测试对象。"""- return ExcelCell(- row=row,- col=col,- text=text,- row_span=row_span,- col_span=col_span,- media=media or [],- equations=equations or [],- text_is_html=text_is_html,- source_row=source_row,- source_col=source_col,- )---def test_shared_html_renderer_preserves_escape_merge_media_and_equation_order() -> None:- """验证纯 renderer 保留转义、合并格以及文本媒体公式顺序。"""- table = ExcelTable(- anchor=(0, 0),- num_rows=2,- num_cols=2,- data=[- _cell(0, 0, "A&B"),- _cell(- 0,- 1,- "<strong>rich</strong>",- media=['<img src="data:image/png;base64,AA==" />'],- equations=["x+1"],- text_is_html=True,- ),- _cell(1, 0, "merged", col_span=2),- ],- )-- rendered = render_spreadsheet_table(table)- soup = BeautifulSoup(rendered, "html.parser")- cells = soup.find_all(["th", "td"])-- assert "A&B" in rendered- rich_html = str(cells[1])- assert rich_html.index("<strong>rich</strong>") < rich_html.index("<img") < rich_html.index("<eq>x+1</eq>")- assert cells[2]["colspan"] == "2"- assert len(soup.find_all("tr")) == 2--- ("media", "equations", "text_is_html"),- [- (["<img/>"], [], False),- ([], ["x"], False),- ([], [], True),- ],-)-def test_singleton_with_structured_content_remains_table(- media: list[str],- equations: list[str],- text_is_html: bool,-) -> None:- """验证带媒体、公式或 HTML 的单格不会错误降级为文本。"""- projector = SpreadsheetProjector()- plain = ExcelTable(anchor=(0, 0), num_rows=1, num_cols=1, data=[_cell(0, 0, "plain")])- structured = ExcelTable(- anchor=(0, 0),- num_rows=1,- num_cols=1,- data=[_cell(0, 0, "value", media=media, equations=equations, text_is_html=text_is_html)],- )-- assert projector._build_block_from_excel_table(plain)["type"] == BlockType.TEXT- assert projector._build_block_from_excel_table(structured)["type"] == BlockType.TABLE---def test_projector_materializes_safe_links_rich_text_media_and_equations() -> None:- """验证单元格 IR 在渲染前已完整持有链接、富文本、媒体和公式。"""- workbook = Workbook()- sheet = workbook.active- assert sheet is not None- sheet["A1"] = "link"- sheet["A1"].hyperlink = "https://example.test/path"- sheet["B1"] = CellRichText([TextBlock(InlineFont(b=True), "Bold"), " plain"])- projector = SpreadsheetProjector()- projector.workbook = workbook- projector.math_map = {(0, 1): ["x"]}- projector.table_image_map[(0, 1)].append("<img/>")-- link_cell = projector._build_excel_cell(sheet, 0, 0, 0, 0)- rich_cell = projector._build_excel_cell(sheet, 0, 1, 0, 1)-- assert link_cell.text == '<a href="https://example.test/path">link</a>'- assert link_cell.text_is_html is True- assert rich_cell.text == "<strong>Bold</strong> plain"- assert rich_cell.media == ["<img/>"]- assert rich_cell.equations == ["x"]---def test_gap_discovery_sparse_cells_and_merged_spans_are_stable() -> None:- """验证 gap 候选、稀疏扫描和合并跨度沿用当前算法。"""- workbook = Workbook()- sheet = workbook.active- assert sheet is not None- sheet["A1"] = "left"- sheet["C1"] = "right"- projector = SpreadsheetProjector()- projector.workbook = workbook-- gap_zero = projector._find_data_tables_with_gap_raw(sheet, 0)- gap_one = projector._find_data_tables_with_gap_raw(sheet, 1)-- assert len(gap_zero) == 2- assert [(table.num_rows, table.num_cols) for table in gap_one] == [(1, 3)]-- merged = workbook.create_sheet("Merged")- merged["A1"] = "merged"- merged.merge_cells("A1:B1")- merged_table = projector._find_data_tables_with_gap_raw(merged, 0)[0]- assert merged_table.data[0].col_span == 2-- sparse = workbook.create_sheet("Sparse")- sparse["A1"] = "first"- sparse.cell(row=1000, column=1000, value="last")- initial_cell_count = len(sparse._cells)- assert len(projector._find_data_tables_with_gap_raw(sparse, 0)) == 2- assert len(sparse._cells) == initial_cell_count---def test_semantic_subset_filter_keeps_only_maximal_table() -> None:- """验证候选过滤只删除语义坐标严格属于另一候选的表格。"""- projector = SpreadsheetProjector()- subset = ExcelTable(- anchor=(0, 0),- num_rows=1,- num_cols=1,- data=[_cell(0, 0, "a", source_row=0, source_col=0)],- )- superset = ExcelTable(- anchor=(0, 0),- num_rows=1,- num_cols=2,- data=[- _cell(0, 0, "a", source_row=0, source_col=0),- _cell(0, 1, "b", source_row=0, source_col=1),- ],- )-- assert projector._filter_semantic_subset_tables([subset, superset]) == [superset]---def test_hidden_sheet_titles_and_standalone_images_remain_separate() -> None:- """验证隐藏 sheet、非空页标题和未吸收图片继续遵守原边界。"""- workbook = Workbook()- first = workbook.active- assert first is not None- first.title = "First"- hidden = workbook.create_sheet("Hidden")- hidden.sheet_state = Worksheet.SHEETSTATE_HIDDEN- workbook.create_sheet("Second")- projector = SpreadsheetProjector()- projector.workbook = workbook-- assert [sheet.title for sheet in projector._iter_sheets_to_convert()] == ["First", "Second"]- sheet_pages = [("First", [{"type": BlockType.TEXT, "content": inline("a")}]), ("Empty", [])]- projector._prepend_sheet_titles(sheet_pages)- assert sheet_pages[0][1][0] == {- "type": BlockType.PARAGRAPH_TITLE,- "level": 2,- "content": inline("First"),- }- assert sheet_pages[1][1] == []-- projector.cur_page = []- projector.sheet_images = [- SheetImage(anchor=(0, 0), image_base64="used"),- SheetImage(anchor=(1, 0), latex="x"),- SheetImage(anchor=(2, 0), image_base64="free"),- ]- projector._find_images_in_sheet({(0, 0)})- assert projector.cur_page == [{"type": BlockType.IMAGE, "image_base64": "free"}]---class _OrderingProjector(SpreadsheetProjector):- """为稳定排序测试提供不依赖表格发现的确定性 artifacts。"""-- def _find_tables_in_sheet(- self,- sheet: Worksheet,- ) -> tuple[set[tuple[int, int]], list[AnchoredBlock]]:- """返回一个位置较后的表格 block。"""- return set(), [((1, 0), 0, {"type": BlockType.TABLE, "content": "table"})]-- def _find_charts_in_sheet(self, sheet: Worksheet) -> list[AnchoredBlock]:- """返回与公式同 anchor 但优先级较后的 chart。"""- return [((0, 1), 10, {"type": BlockType.CHART, "content": "chart"})]-- def _find_additional_visual_artifacts(- self,- used_cells: set[tuple[int, int]],- ) -> list[AnchoredBlock]:- """返回与 chart 同 anchor 但优先级更高的公式。"""- return [((0, 1), 5, {"type": BlockType.EQUATION, "content": "equation"})]-- def _find_images_in_sheet(self, used_cells: set[tuple[int, int]] | None = None) -> None:- """在几何排序完成后追加独立图片。"""- self.cur_page.append({"type": BlockType.IMAGE, "image_base64": "image"})---def test_sheet_projection_sorts_artifacts_before_standalone_images() -> None:- """验证排序键固定为 anchor、priority,独立图片最后输出。"""- workbook = Workbook()- sheet = workbook.active- assert sheet is not None- projector = _OrderingProjector()- projector.workbook = workbook-- projector._convert_sheet(sheet)-- assert [block["type"] for block in projector.cur_page] == [- BlockType.EQUATION,- BlockType.CHART,- BlockType.TABLE,- BlockType.IMAGE,- ]---def test_xls_and_xlsx_depend_only_on_shared_projector_contract() -> None:- """验证最终继承关系和旧 XLSX 私有表格模型均已严格迁移。"""- assert issubclass(_XlsPageBuilder, SpreadsheetProjector)- assert issubclass(XlsxConverter, SpreadsheetProjector)- assert XlsxConverter not in _XlsPageBuilder.__mro__- assert not hasattr(xlsx_converter_module, "DataRegion")- assert not hasattr(xlsx_converter_module, "ExcelCell")- assert not hasattr(xlsx_converter_module, "ExcelTable")- assert not hasattr(XlsxConverter, "excel_table_to_html")diff --git a/tests/unittest/test_guess_suffix_ole2.py b/tests/unittest/test_guess_suffix_ole2.pydeleted file mode 100644index 326b45b2..00000000--- a/tests/unittest/test_guess_suffix_ole2.py+++ /dev/null@@ -1,33 +0,0 @@-from __future__ import annotations--from docvortex.document.detection import (- _guess_ole2_suffix_by_bytes,- guess_suffix_by_bytes,-)--# 最小 OLE2 compound file header(512 bytes header + 不可读 stream 目录)-# 用于测试 magic bytes 检查;olefile 打开后会因结构不完整返回 None-_OLE2_HEADER_ONLY = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 512---def test_guess_ole2_suffix_returns_none_for_non_ole2_bytes() -> None:- assert _guess_ole2_suffix_by_bytes(b"%PDF-1.4 test") is None- assert _guess_ole2_suffix_by_bytes(b"plain text") is None---def test_guess_ole2_suffix_returns_none_for_ole2_without_known_streams() -> None:- """OLE2 magic 但无 WordDocument/Workbook/PowerPoint Document stream 时返回 None。"""- assert _guess_ole2_suffix_by_bytes(_OLE2_HEADER_ONLY) is None---def test_guess_suffix_by_bytes_falls_through_to_magika_for_unknown_ole2() -> None:- """OLE2 magic 但无已知 stream 时,交给 Magika 兜底(不返回 unknown_ole2)。"""- suffix = guess_suffix_by_bytes(_OLE2_HEADER_ONLY)- assert isinstance(suffix, str)---def test_guess_suffix_by_bytes_prefers_rtf_signature_over_csv_extension() -> None:- """RTF 强内容签名必须覆盖 CSV 的无签名扩展名兜底。"""- payload = b"\xef\xbb\xbf \r\n{\\RTF1\\ANSI body}"-- assert guess_suffix_by_bytes(payload, "disguised.csv") == "rtf"diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pydeleted file mode 100644index 2f981c9b..00000000--- a/tests/unittest/test_html_render.py+++ /dev/null@@ -1,988 +0,0 @@-from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inline--from copy import deepcopy-from importlib import resources--from bs4 import BeautifulSoup-import pytest--from mineru.render import RenderMode, render_html-from mineru.types import (- AlgorithmBodyBlock,- ChartAnnotationBlock,- ChartBlock,- ChartBodyBlock,- CodeAnnotationBlock,- CodeBlock,- CodeBodyBlock,- DocTitleBlock,- EquationBlock,- ImageBlock,- IndexBlock,- ListBlock,- MiddleJson,- PageAuxTextBlock,- PageBlock,- PageFootnoteBlock,- PageInfo,- ParagraphTitleBlock,- RefTextBlock,- TableBlock,- TableBodyBlock,- TextBlock,- TextSpan,-)--_PNG_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII="---def _middle(*pages: PageInfo) -> MiddleJson:- """构造无需 PDF bbox 的严格 Office MiddleJson。"""- return MiddleJson(- pages=list(pages),- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:- """按调用方顺序构造测试页面。"""- return PageInfo(page_idx=page_idx, blocks=list(blocks))---def _list(index: int, *items: str, sub_type: str | None = None) -> ListBlock:- """构造普通或参考文献列表。"""- child_class = RefTextBlock if sub_type == "ref_text" else TextBlock- return ListBlock(- type="list",- index=index,- sub_type=sub_type,- content=[child_class(type=sub_type or "text", content=_inline(item)) for item in items],- )---def _mermaid_fence(source: str, *, language: str = "mermaid") -> str:- """用标准三反引号构造 diagram fence,避免测试字符串散落围栏细节。"""- fence = chr(96) * 3- return f"{fence}{language}\n{source}\n{fence}"---def _flowchart(content: str, *, with_raster: bool = True) -> ImageBlock:- """构造带可选 raster 回退的 flowchart 图片块。"""- body: dict[str, object] = {- "type": "image_body",- "index": 0,- "content": content,- }- if with_raster:- body["image_base64"] = _PNG_URI- return ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "sub_type": "flowchart",- "content": [- body,- {"type": "image_caption", "index": 1, "content": _inline("Flowchart caption")},- ],- }- )---def test_public_contract_fragment_standalone_title_and_input_immutability() -> None:- """验证严格公共参数、双输出形态、标题回退和输入无副作用。"""- middle = _middle(- _page(- 0,- DocTitleBlock(- type="doc_title",- index=0,- level=1,- content=[- {"type": "text", "content": "Demo", "styles": ["bold"]},- {"type": "text", "content": " <unsafe>"},- ],- ),- TextBlock(type="text", index=1, content=_inline("body")),- )- )- original = deepcopy(middle)-- fragment = render_html(middle, standalone=False)- standalone = render_html(middle)-- assert fragment.startswith('<article class="docvortex-document docvortex-document--default" ')- assert 'data-docvortex-html-version="1" data-render-mode="default"' in fragment- assert fragment in standalone- assert '<html lang="und">' in standalone- assert "<title>Demo <unsafe></title>" in standalone- assert '<body class="docvortex-html-body">' in standalone- assert "<style>" in standalone- assert "mathjax@" not in standalone- assert "prismjs@" not in standalone- assert middle == original-- explicit = render_html(middle, document_title="A </title><script>x</script>")- assert "<title>A </title><script>x</script></title>" in explicit-- with pytest.raises(TypeError, match="MiddleJson"):- render_html({}) # type: ignore[arg-type]- with pytest.raises(TypeError, match="RenderMode"):- render_html(middle, mode="default") # type: ignore[arg-type]- with pytest.raises(TypeError, match="standalone"):- render_html(middle, standalone=1) # type: ignore[arg-type]---def test_default_and_full_modes_preserve_their_page_contracts() -> None:- """验证 DEFAULT 连续阅读与 FULL 空页、辅助块和页面分隔。"""- middle = _middle(- _page(- 0,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- TextBlock(type="text", index=1, content=_inline("inter-")),- ),- _page(5),- _page(- 9,- TextBlock(type="text", index=0, content=_inline("national"), continues_prev=True),- PageAuxTextBlock(type="footer", index=1, content=_inline("FOOTER")),- ),- )-- default = BeautifulSoup(render_html(middle, standalone=False), "html.parser")- full = BeautifulSoup(render_html(middle, mode=RenderMode.FULL, standalone=False), "html.parser")-- assert default.select_one(".docvortex-text").get_text() == "international"- assert default.select_one('[data-block-type="text"]')["data-page-idx"] == "0"- assert not default.select(".docvortex-page")- assert "HEADER" not in default.get_text()-- assert [section["data-page-idx"] for section in full.select(".docvortex-page")] == ["0", "5", "9"]- assert len(full.select(".docvortex-page-break")) == 2- assert [item.get_text() for item in full.select(".docvortex-text")] == ["inter-", "national"]- assert "HEADER" in full.get_text() and "FOOTER" in full.get_text()---def test_default_and_full_html_link_to_visible_page_footnote_anchor() -> None:- """验证默认与完整 HTML 都输出页面脚注目标及弱化样式类。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "See "},- {"type": "hyperlink", "url": "#note-one", "content": _inline("[1]")},- {"type": "text", "content": "."},- ],- ),- PageFootnoteBlock(- type="page_footnote",- index=1,- content=_inline("Footnote body."),- anchor="note-one",- ),- )- )-- default = BeautifulSoup(render_html(middle, standalone=False), "html.parser")- full = BeautifulSoup(render_html(middle, mode=RenderMode.FULL, standalone=False), "html.parser")-- assert default.select_one('a[href="#note-one"]') is not None- for output in (default, full):- target = output.select_one("#note-one.docvortex-page-footnote")- assert target is not None- assert target["data-block-type"] == "page_footnote"- assert target.get_text() == "Footnote body."- assert full.select_one('a[href="#note-one"]') is not None---def test_inline_html_escapes_plain_text_and_renders_styles_links_and_math() -> None:- """验证普通尖括号、富样式、安全链接及 MathJax carrier。"""- content = [- {"type": "text", "content": "p <0.05 <local_dir> "},- {"type": "text", "content": " styled ", "styles": ["bold", "italic", "underline"]},- {"type": "text", "content": " "},- {"type": "hyperlink", "url": "https://example.test/a b", "content": _inline("safe")},- {"type": "text", "content": " bad javascript:alert(1) "},- {"type": "equation_inline", "content": "x < y & z"},- ]- result = render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))))- soup = BeautifulSoup(result, "html.parser")-- paragraph = soup.select_one(".docvortex-text")- assert "p <0.05 <local_dir>" in paragraph.get_text()- assert paragraph.select_one("em strong u") is not None- assert paragraph.select_one(".docvortex-preserve-whitespace") is not None- assert paragraph.select_one('a[href="https://example.test/a%20b"]') is not None- assert "bad" in paragraph.get_text()- assert paragraph.select_one('a[href^="javascript:"]') is None- assert paragraph.select_one(".docvortex-math").get_text() == r"\(x < y & z\)"- assert "[email protected]/tex-chtml.js" in result- assert "loader: {load: ['ui/safe']}" in result- assert "ignoreHtmlClass: 'docvortex-document'" in result- assert "packages: {'[-]': ['require']}" in result---def test_plain_text_autolinks_mpe_style_urls_domains_and_email() -> None:- """验证显式 URL、www、裸域名、邮箱、括号和 CJK 句读按 MPE 风格转成链接。"""- content = (- "See https://example.com/a_(b), www.example.org/path?x=1, "- "example.net/docs。Email [email protected];"- "local http://127.0.0.1:8080/a. "- "pair https://one.example/ahttps://two.example/b"- )- soup = BeautifulSoup(- render_html(_middle(_page(0, TextBlock(type="text", index=0, content=_inline(content)))), standalone=False),- "html.parser",- )-- links = soup.select(".docvortex-text a")- assert [link["href"] for link in links] == [- "https://example.com/a_%28b%29",- "https://www.example.org/path?x=1",- "https://example.net/docs",- "mailto:[email protected]",- "http://127.0.0.1:8080/a",- "https://one.example/a",- "https://two.example/b",- ]- assert [link.get_text() for link in links] == [- "https://example.com/a_(b)",- "www.example.org/path?x=1",- "example.net/docs",- "[email protected]",- "http://127.0.0.1:8080/a",- "https://one.example/a",- "https://two.example/b",- ]- assert "docs。Email" in soup.select_one(".docvortex-text").get_text()--- "tld",- [- "ai",- "app",- "au",- "biz",- "br",- "ca",- "cloud",- "cn",- "com",- "de",- "dev",- "edu",- "eu",- "fr",- "gov",- "hk",- "in",- "info",- "io",- "jp",- "kr",- "net",- "nl",- "nz",- "online",- "org",- "ru",- "sg",- "shop",- "site",- "store",- "tech",- "tw",- "uk",- "xyz",- ],-)-def test_common_engineering_bare_domain_suffixes_linkify(tld: str) -> None:- """验证 B 工程常用集中的裸域名后缀全部保持可链接。"""- content = f"Project.Example.{tld}/docs?x=1#intro"- soup = BeautifulSoup(- render_html(_middle(_page(0, TextBlock(type="text", index=0, content=_inline(content)))), standalone=False),- "html.parser",- )-- link = soup.select_one(".docvortex-text a")- assert link["href"] == f"https://Project.Example.{tld}/docs?x=1#intro"- assert link.get_text() == content--- "content",- [- "machine.Aborted",- "HostID.lic",- "requirements.txt",- "600104.SH",- "000868.SZ",- "libcudart.so",- "TABLEFORMER.md",- "cs.CL",- "TSLA.US",- "A.Balakrishnan",- "R.Kohli",- ],-)-def test_non_common_bare_domain_suffixes_remain_plain_text(content: str) -> None:- """验证文件名、股票代码、作者姓名和非白名单后缀不再误生成链接。"""- soup = BeautifulSoup(- render_html(_middle(_page(0, TextBlock(type="text", index=0, content=_inline(content)))), standalone=False),- "html.parser",- )-- assert soup.select_one(".docvortex-text a") is None- assert soup.select_one(".docvortex-text").get_text() == content---def test_strong_link_syntax_bypasses_bare_domain_suffix_allowlist() -> None:- """验证显式 HTTP、www 和邮箱不受裸域名 B 白名单限制。"""- content = "https://example.ch www.example.ch [email protected] https://machine.Aborted"- soup = BeautifulSoup(- render_html(_middle(_page(0, TextBlock(type="text", index=0, content=_inline(content)))), standalone=False),- "html.parser",- )-- assert [link["href"] for link in soup.select(".docvortex-text a")] == [- "https://example.ch",- "https://www.example.ch",- "mailto:[email protected]",- "https://machine.Aborted",- ]---def test_autolink_excludes_existing_links_code_math_algorithm_and_raw_html() -> None:- """验证 linkify 不嵌套显式链接,也不进入危险协议、代码、公式、算法和 raw HTML。"""- text = TextBlock(- type="text",- index=0,- content=[- {- "type": "text",- "content": (- "ftp://bad.example.com /relative.example.com 1.2.3.4 "- "javascript:evil.example.com data:text/html,data.example.com [email protected] "- ),- },- {"type": "hyperlink", "url": "https://target.test", "content": _inline("example.com")},- {"type": "text", "content": " "},- {"type": "equation_inline", "content": "math.example.com"},- ],- )- code = CodeBlock(- type="code",- index=1,- sub_type="code",- guess_lang="txt",- content=[CodeBodyBlock(type="code_body", index=1, content="https://code.example.com")],- )- algorithm = CodeBlock(- type="code",- index=2,- sub_type="algorithm",- content=[AlgorithmBodyBlock(type="algorithm_body", index=2, content=_inline("visit algorithm.example.com"))],- )- raw_html = ChartBlock(- type="chart",- index=3,- content=[ChartBodyBlock(type="chart_body", index=3, content="<p>raw.example.com</p>")],- )- soup = BeautifulSoup(- render_html(_middle(_page(0, text, code, algorithm, raw_html)), standalone=False),- "html.parser",- )-- links = soup.select("a")- assert len(links) == 1- assert links[0]["href"] == "https://target.test"- assert links[0].get_text() == "example.com"- assert soup.select_one(".docvortex-math").get_text() == r"\(math.example.com\)"- assert soup.select_one(".docvortex-code").get_text() == "https://code.example.com"- assert soup.select_one(".docvortex-algorithm").get_text() == "visit algorithm.example.com"- assert soup.select_one(".docvortex-figure--chart p").get_text() == "raw.example.com"---def test_formula_body_closing_delimiters_are_neutralized_before_mathjax_scanning() -> None:- """验证公式体内的结束定界符改写为等价 TeX,不会提前闭合 carrier。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[{"type": "text", "content": "inline "}, {"type": "equation_inline", "content": r"x\)y"}],- ),- EquationBlock(type="equation", index=1, content=r"x\]y"),- )- )- soup = BeautifulSoup(render_html(middle, standalone=False), "html.parser")-- assert soup.select_one(".docvortex-math--inline").get_text() == r"\(x\mathclose{)}y\)"- assert soup.select_one(".docvortex-math--block").get_text().replace("\n", "") == r"\[x\mathclose{]}y\]"---def test_lists_cover_native_explicit_reference_nested_and_orphan_shapes() -> None:- """验证列表分类、非连续编号、显式 marker、参考文献和嵌套归属。"""- ordered = _list(0, "1. first", "3. third")- alpha = _list(1, "a. alpha", "b. beta")- explicit = _list(2, "(1) one", "[x] done", "plain")- mixed = _list(6, "1. one", "- two", "plain")- reference = _list(3, "[1] first", "Author A", sub_type="ref_text")- nested = ListBlock(- type="list",- index=4,- content=[- TextBlock(type="text", content=_inline("- parent")),- ListBlock(type="list", content=[TextBlock(type="text", content=_inline("- child"))]),- ],- )- orphan = ListBlock(- type="list",- index=5,- content=[ListBlock(type="list", content=[TextBlock(type="text", content=_inline("- orphan"))])],- )- markerless_owner = ListBlock(- type="list",- index=7,- content=[- TextBlock(type="text", content=_inline("1. visible")),- TextBlock(type="text", content=[]),- ListBlock(type="list", content=[TextBlock(type="text", content=_inline("- nested owner"))]),- ],- )- soup = BeautifulSoup(- render_html(- _middle(_page(0, ordered, alpha, explicit, reference, nested, orphan, mixed, markerless_owner)),- standalone=False,- ),- "html.parser",- )-- ordered_html = soup.select('[data-block-index="0"] ol')[0]- assert ordered_html.find_all("li", recursive=False)[1]["value"] == "3"- assert ordered_html.get_text(" ", strip=True) == "first third"- assert soup.select_one('[data-block-index="1"] ol')["type"] == "a"- assert [marker.get_text() for marker in soup.select('[data-block-index="2"] .docvortex-list-marker')] == [- "(1)",- "[x]",- "",- ]- assert "[1] first" in soup.select_one('[data-block-index="3"] li').get_text()- parent_item = soup.select_one('[data-block-index="4"] > .docvortex-list > li')- assert parent_item.find("ul", recursive=False) is not None- assert soup.select_one('[data-block-index="5"] .docvortex-list-item--orphan') is not None- assert [marker.get_text() for marker in soup.select('[data-block-index="6"] .docvortex-list-marker')] == [- "1.",- "-",- "",- ]- assert soup.select_one('[data-block-index="7"] .docvortex-list-item--markerless > ul') is not None---def test_index_uses_real_forward_anchor_and_omits_duplicate_ids() -> None:- """验证目录前向链接、页码尾清理、嵌套目录及重复 anchor 首项生效。"""- index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(type="paragraph_title", level=2, anchor="sec 1", content=_inline("Section\t3")),- IndexBlock(- type="index",- content=[- ParagraphTitleBlock(type="paragraph_title", level=3, anchor="missing", content=_inline("Missing\tiv"))- ],- ),- ],- )- first = ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="sec 1", content=_inline("Section"))- duplicate = ParagraphTitleBlock(type="paragraph_title", index=2, level=6, anchor="sec 1", content=_inline("Duplicate"))- soup = BeautifulSoup(render_html(_middle(_page(0, index, first, duplicate)), standalone=False), "html.parser")-- assert soup.select_one('.docvortex-index a[href="#sec-1"]').get_text() == "Section"- assert "3" not in soup.select_one(".docvortex-index").get_text()- assert soup.select_one(".docvortex-index li ul") is not None- assert soup.select_one(".docvortex-index li ul a") is None- assert len(soup.select('[id="sec-1"]')) == 1- assert soup.find("h6", attrs={"data-heading-level": "6"}).get_text() == "Duplicate"---def test_empty_title_does_not_create_a_broken_index_target_and_anchor_controls_are_normalized() -> None:- """验证空正文标题不成为链接目标,控制字符在 id/href 两侧一致归一化。"""- index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(type="paragraph_title", level=2, anchor="empty", content=_inline("Empty")),- ParagraphTitleBlock(type="paragraph_title", level=2, anchor="bad\x00id", content=_inline("Good")),- ParagraphTitleBlock(type="paragraph_title", level=2, anchor="bad\ufffdid", content=_inline("Collision")),- ],- )- empty = ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="empty", content=[])- good = ParagraphTitleBlock(type="paragraph_title", index=2, level=2, anchor="bad\x00id", content=_inline("Good"))- collision = ParagraphTitleBlock(- type="paragraph_title",- index=3,- level=2,- anchor="bad\ufffdid",- content=_inline("Collision"),- )- soup = BeautifulSoup(- render_html(_middle(_page(0, index, empty, good, collision)), standalone=False),- "html.parser",- )-- links = soup.select(".docvortex-index a")- assert len(links) == 2- assert links[0]["href"] == "#bad%EF%BF%BDid"- assert links[1]["href"] == "#bad%EF%BF%BDid-2"- assert soup.find(id="bad\ufffdid") is not None- assert soup.find(id="bad\ufffdid-2") is not None---def test_empty_index_leaf_owns_its_following_nested_index() -> None:- """验证空目录叶子的 nested ul 不会错误挂到更早的可见目录项。"""- index = IndexBlock(- type="index",- index=0,- content=[- TextBlock(type="text", content=_inline("visible")),- TextBlock(type="text", content=[]),- IndexBlock(type="index", content=[TextBlock(type="text", content=_inline("nested"))]),- ],- )- soup = BeautifulSoup(render_html(_middle(_page(0, index)), standalone=False), "html.parser")- top_items = soup.select(".docvortex-index > ul > li")-- assert len(top_items) == 2- assert top_items[0].find("ul", recursive=False) is None- assert top_items[1].find("ul", recursive=False).get_text(strip=True) == "nested"---def test_visual_child_order_image_details_and_asset_precedence() -> None:- """验证视觉说明顺序、图片路径优先级、URL 编码与识别内容 details。"""- image = ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "sub_type": "diagram",- "content": [- {"type": "image_caption", "content": _inline("before")},- {- "type": "image_body",- "index": 0,- "content": "description <eq>x</eq>",- "image_path": "images/a b.png",- "image_base64": _PNG_URI,- },- {"type": "image_footnote", "content": _inline("after")},- {"type": "image_caption", "content": _inline("again")},- ],- }- )- rendered = render_html(- _middle(_page(0, image)),- asset_base_url="https://cdn.example/doc",- standalone=False,- )- soup = BeautifulSoup(rendered, "html.parser")-- assert rendered.index("before") < rendered.index("images/a%20b.png") < rendered.index("after") < rendered.index("again")- assert soup.select_one("img")["src"] == "https://cdn.example/doc/images/a%20b.png"- assert "data:image" not in rendered- assert soup.select_one("details .docvortex-math") is not None- assert len(soup.select(".docvortex-caption")) == 2---def test_mermaid_flowchart_uses_live_canvas_raster_fallback_and_safe_config() -> None:- """验证受限 Mermaid 源生成 canvas,并保留 raster、源码和固定安全运行时。"""- source_text = '%% comment\ngraph LR\n A["<script>alert(1)</script>"] --> B'- middle = _middle(_page(0, _flowchart(_mermaid_fence(source_text))))- fragment = render_html(middle, standalone=False)- standalone = render_html(middle)- soup = BeautifulSoup(fragment, "html.parser")-- host = soup.select_one(".docvortex-flowchart")- assert host["data-mermaid-state"] == "pending"- assert "docvortex-flowchart--has-raster" in host["class"]- assert host.select_one('.docvortex-flowchart-canvas[role="img"]') is not None- assert host.select_one(".docvortex-flowchart-fallback")["src"].startswith("data:image/png")- details = host.find_next_sibling("details")- assert "open" not in details.attrs- assert details.select_one(".docvortex-flowchart-source code").get_text() == source_text- assert soup.find("script") is None- assert "mermaid@" not in fragment- assert "[email protected]/dist/mermaid.min.js" in standalone- assert "sha384-aBQXj4hK6Jm05i7aQAsUV3bLdSUrHX1BGYfMB0166TtWt/RRaw+h0Eelme9OCOvy" in standalone- assert "securityLevel: 'strict'" in standalone- assert "suppressErrorRendering: true" in standalone- assert "maxTextSize: 50000" in standalone and "maxEdges: 500" in standalone- assert "flowchart: {htmlLabels: false, useMaxWidth: true}" in standalone- assert "bindFunctions" not in standalone---def test_mermaid_flowchart_without_raster_opens_source_fallback() -> None:- """验证无 raster 的有效 flowchart 默认展开源码,等待或替代浏览器渲染。"""- soup = BeautifulSoup(- render_html(- _middle(_page(0, _flowchart(_mermaid_fence("flowchart TD\n A --> B"), with_raster=False))),- standalone=False,- ),- "html.parser",- )-- host = soup.select_one(".docvortex-flowchart")- assert "docvortex-flowchart--has-raster" not in host.get("class", [])- assert host.select_one("img") is None- assert "open" in host.find_next_sibling("details").attrs--- "content",- [- _mermaid_fence("sequenceDiagram\n A->>B: example.com"),- _mermaid_fence('%%{init: {"securityLevel": "loose"}}%%\ngraph LR\n A --> B'),- _mermaid_fence("---\ntheme: dark\n---\ngraph LR\n A --> B"),- _mermaid_fence("graph LR\n A --> B", language="python"),- _mermaid_fence(f"graph LR\n A[{'x' * 50_001}]"),- ],-)-def test_invalid_or_out_of_scope_mermaid_keeps_existing_image_path(content: str) -> None:- """验证非流程图、配置注入、错误 fence 和超限源码不触发 Mermaid 依赖。"""- rendered = render_html(_middle(_page(0, _flowchart(content))))- soup = BeautifulSoup(rendered, "html.parser")-- assert soup.select_one(".docvortex-flowchart") is None- assert soup.select_one(".docvortex-image") is not None- assert soup.select_one(".docvortex-details") is not None- assert soup.select_one(".docvortex-details a") is None- assert "mermaid@" not in rendered---def test_table_keeps_safe_html_and_spatial_or_image_fallbacks() -> None:- """验证原生表格、公式、危险属性清理、空间文本和不可用表格图片回退。"""- html_table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=(- '<table border="1"><tr><td rowspan="2" onclick="bad()">'- "<eq>x<y</eq><table><tr><td>N</td></tr></table></td></tr></table>"- ),- )- ],- )- spatial = TableBlock(- type="table",- index=1,- content=[TableBodyBlock(type="table_body", index=1, content="A < B\nC D")],- )- invalid = TableBlock(- type="table",- index=2,- content=[TableBodyBlock(type="table_body", index=2, content="<table></table>", image_base64=_PNG_URI)],- )- soup = BeautifulSoup(render_html(_middle(_page(0, html_table, spatial, invalid)), standalone=False), "html.parser")-- assert len(soup.select('[data-block-index="0"] table')) == 2- cell = soup.select_one('[data-block-index="0"] td')- assert cell["rowspan"] == "2"- assert "onclick" not in cell.attrs and "border" not in soup.select_one("table").attrs- assert cell.select_one(".docvortex-math") is not None- assert soup.select_one('[data-block-index="1"] .docvortex-table-text').get_text() == "A < B\nC D"- assert soup.select_one('[data-block-index="2"] img')["src"].startswith("data:image/png")---def test_table_preserves_standard_inline_style_tags() -> None:- """验证表格安全 HTML 保留 renderer 支持的标准行内样式标签。"""- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=(- "<table><tr><td><strong>bold</strong><em>italic</em><u>under</u>"- "<s>strike</s><sup>sup</sup><sub>sub</sub></td></tr></table>"- ),- )- ],- )-- soup = BeautifulSoup(render_html(_middle(_page(0, table)), standalone=False), "html.parser")- cell = soup.select_one("td")-- assert [cell.select_one(tag).get_text() for tag in ("strong", "em", "u", "s", "sup", "sub")] == [- "bold",- "italic",- "under",- "strike",- "sup",- "sub",- ]---def test_discarded_invalid_table_math_does_not_load_mathjax() -> None:- """验证无单元格表格回退图片后,已丢弃的 eq 不会误触发 MathJax。"""- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content="<table><eq>x</eq></table>",- image_base64=_PNG_URI,- )- ],- )- rendered = render_html(_middle(_page(0, table)))-- assert BeautifulSoup(rendered, "html.parser").select_one("article .docvortex-math") is None- assert "mathjax@" not in rendered- assert "data:image/png" in rendered---def test_chart_gfm_details_code_prism_and_algorithm_html() -> None:- """验证严格 chart GFM、图片 details、Prism Autoloader 和算法转义。"""- chart = ChartBlock(- type="chart",- index=0,- sub_type="line chart",- content=[- ChartAnnotationBlock(type="chart_caption", content=_inline("chart before")),- ChartBodyBlock(- type="chart_body",- index=0,- image_path="images/chart.png",- content="| A | B |\n| :--- | ---: |\n| 1 | 2 |",- ),- ],- )- code = CodeBlock(- type="code",- index=1,- sub_type="code",- guess_lang="shell",- content=[- CodeBodyBlock(type="code_body", index=1, content='echo "<x>"\n'),- CodeAnnotationBlock(type="code_footnote", content=_inline("code after")),- ],- )- algorithm = CodeBlock(- type="code",- index=2,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=2,- content=[- {"type": "text", "content": "if a < b:\n T"},- {"type": "text", "content": "bold", "styles": ["bold"]},- {"type": "text", "content": "italic", "styles": ["italic"]},- {"type": "text", "content": "strike", "styles": ["strikethrough"]},- {"type": "text", "content": "under", "styles": ["underline"]},- {"type": "text", "content": "dot", "styles": ["emphasis"]},- {"type": "text", "content": "q", "styles": ["subscript"]},- {"type": "text", "content": " = "},- {"type": "equation_inline", "content": "x"},- {"type": "equation_inline", "content": "y"},- ],- )- ],- )- result = render_html(_middle(_page(0, chart, code, algorithm)))- soup = BeautifulSoup(result, "html.parser")-- assert soup.select_one("details .docvortex-chart-table") is not None- assert soup.select_one("th.docvortex-align-left") is not None- assert soup.select_one("th.docvortex-align-right") is not None- assert soup.select_one("pre.language-bash code.language-bash").get_text() == 'echo "<x>"\n'- assert "[email protected]/components/prism-core.min.js" in result- assert "[email protected]/plugins/autoloader/prism-autoloader.min.js" in result- assert "Prism.highlightAllUnder(root)" in result- assert "sha384-zLRFO4dw" in result and "sha384-Uq05+JLk" in result- algorithm_html = soup.select_one(".docvortex-algorithm")- assert "if a < b:" in algorithm_html.get_text()- assert algorithm_html.select_one("strong").get_text() == "bold"- assert algorithm_html.select_one("em").get_text() == "italic"- assert algorithm_html.select_one("s").get_text() == "strike"- assert algorithm_html.select_one("u").get_text() == "under"- assert algorithm_html.select_one(".docvortex-text-emphasis").get_text() == "dot"- assert algorithm_html.select_one("sub").get_text() == "q"- assert len(algorithm_html.select(".docvortex-math")) == 2- assert r"\(x\) \(y\)" in algorithm_html.get_text()- assert "<br" not in str(algorithm_html)- assert "if a < b:\n " in str(algorithm_html)- assert "**bold**" not in str(algorithm_html)- assert "*italic*" not in str(algorithm_html)- assert "~~strike~~" not in str(algorithm_html)--[email protected]("guess_lang", ["python bad/../../x", "constructor", "prototype", "__proto__"])-def test_invalid_code_language_remains_visible_without_loading_prism(guess_lang: str) -> None:- """验证非法语言名不会进入 class 或 CDN 组件路径。"""- code = CodeBlock(- type="code",- index=0,- sub_type="code",- guess_lang=guess_lang,- content=[CodeBodyBlock(type="code_body", index=0, content="<script>x</script>")],- )- result = render_html(_middle(_page(0, code)))- soup = BeautifulSoup(result, "html.parser")-- assert soup.select_one("code").get_text() == "<script>x</script>"- assert not soup.select_one("code").get("class")- assert "prismjs@" not in result- assert "<script>x</script>" not in result---def test_empty_code_and_literal_class_text_do_not_load_external_runtimes() -> None:- """验证空代码和普通文本中的 class 字样不会误触发 Prism 或 MathJax。"""- middle = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline('class="docvortex-math fake" class="language-python"')),- CodeBlock(- type="code",- index=1,- sub_type="code",- guess_lang="python",- content=[CodeBodyBlock(type="code_body", index=1, content="")],- ),- )- )- rendered = render_html(middle)-- assert "mathjax@" not in rendered- assert "prismjs@" not in rendered- assert '<pre class="docvortex-code"><code></code></pre>' in rendered---def test_crlf_and_cr_are_normalized_to_visible_line_breaks() -> None:- """验证 CRLF 与 CR 统一为两个可见 HTML 换行。"""- rendered = render_html(- _middle(_page(0, TextBlock(type="text", index=0, content=_inline("one\r\ntwo\rthree")))),- standalone=False,- )- paragraph = BeautifulSoup(rendered, "html.parser").select_one(".docvortex-text")-- assert len(paragraph.find_all("br")) == 2- assert paragraph.get_text("|", strip=True) == "one|two|three"---def test_invalid_html_characters_are_replaced_and_output_remains_utf8_encodable() -> None:- """验证普通文本、代码、anchor 和富 HTML 中的控制字符与 surrogate 可见降级。"""- middle = _middle(- _page(- 0,- ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="a\ud800", content=_inline("T\x01")),- TextBlock.model_construct(- type="text",- index=1,- content=[TextSpan.model_construct(type="text", content="body\udfff", styles=[])],- ),- CodeBlock(- type="code",- index=2,- sub_type="code",- guess_lang="txt",- content=[CodeBodyBlock(type="code_body", index=2, content="code\ud800\x02")],- ),- ChartBlock(- type="chart",- index=3,- content=[ChartBodyBlock(type="chart_body", index=3, content="<p>chart\udfff\x03</p>")],- ),- TableBlock(- type="table",- index=4,- content=[TableBodyBlock(type="table_body", index=4, content="table\ud800\x04")],- ),- )- )- rendered = render_html(middle)-- rendered.encode("utf-8")- assert "\ud800" not in rendered and "\udfff" not in rendered- assert rendered.count("\ufffd") >= 6---def test_setext_heading_shape_is_not_misclassified_as_a_gfm_chart_table() -> None:- """验证缺少 pipe 的 Setext 标题形态按普通 chart 文本输出。"""- chart = ChartBlock(- type="chart",- index=0,- content=[ChartBodyBlock(type="chart_body", index=0, content="Title\n---\nbody")],- )- soup = BeautifulSoup(render_html(_middle(_page(0, chart)), standalone=False), "html.parser")-- assert soup.select_one(".docvortex-chart-table") is None- assert soup.select_one(".docvortex-figure--chart").get_text(" ", strip=True) == "Title --- body"--- ("slash_count", "expected"),- [(1, "|"), (2, "|"), (3, r"\|"), (4, r"\|"), (5, r"\\|")],-)-def test_chart_gfm_pipe_matches_markdown_it_backslash_decoding(slash_count: int, expected: str) -> None:- """验证任意相邻反斜杠都保护列内 pipe,并与 markdown-it 解码结果一致。"""- chart = ChartBlock(- type="chart",- index=0,- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="| Formula |\n| --- |\n| " + "\\" * slash_count + "| |",- )- ],- )- soup = BeautifulSoup(render_html(_middle(_page(0, chart)), standalone=False), "html.parser")-- assert soup.select_one(".docvortex-chart-table td").get_text() == expected---def test_mineru_styles_are_minified_scoped_and_inlined_byte_exact() -> None:- """验证独立样式产物体积、作用域及 standalone 的逐字内联契约。"""- root = resources.files("docvortex").joinpath("resources", "html")- source = root.joinpath("docvortex.css").read_text(encoding="utf-8")- minified = root.joinpath("docvortex.min.css").read_text(encoding="utf-8")- standalone = render_html(_middle())- style = BeautifulSoup(standalone, "html.parser").style-- assert len(minified.encode("utf-8")) <= 10 * 1024- assert "\n" not in minified and "/*" not in minified- assert ".docvortex-document" in source and ".docvortex-html-body" in source- assert style is not None and style.string == minified- assert f"<style>{minified}</style>" in standalone- assert not root.joinpath("crossnote").is_dir()---def test_empty_document_and_equation_image_do_not_load_external_scripts() -> None:- """验证空文档和纯公式图片不会无谓加载 MathJax 或 Prism。"""- empty = render_html(_middle())- image_equation = render_html(_middle(_page(0, EquationBlock(type="equation", index=0, content="", image_base64=_PNG_URI))))-- assert (- '<article class="docvortex-document docvortex-document--default" '- 'data-docvortex-html-version="1" data-render-mode="default">\n\n</article>'- ) in empty- assert "mathjax@" not in empty and "prismjs@" not in empty and "mermaid@" not in empty- assert "mathjax@" not in image_equation and "prismjs@" not in image_equation and "mermaid@" not in image_equation- assert "data:image/png" in image_equationdiff --git a/tests/unittest/test_html_security.py b/tests/unittest/test_html_security.pydeleted file mode 100644index 31852429..00000000--- a/tests/unittest/test_html_security.py+++ /dev/null@@ -1,427 +0,0 @@-from __future__ import annotations--import base64-from unittest.mock import Mock--import pytest-from bs4 import BeautifulSoup, Tag--from docvortex.render._internal.html.sanitizer import is_supported_html_markup-from docvortex.render._internal.html.sanitizer import sanitize_html_fragment-from docvortex.render._internal.html.sanitizer import sanitize_image_source-from docvortex.render._internal.html.sanitizer import sanitize_link_url-from docvortex.foundation import image_payload--_SAFE_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII="---def _generated_svg_data_uri(extra_markup: str = "") -> str:- """构造带 PNG fallback 的最小 MinerU 安全 SVG data URI。"""- svg = (- '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 1 1" '- 'data-metafile-render="wmf-emf">'- f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{_SAFE_PNG_BASE64}</metadata>'- '<path d="M 0 0 L 1 0 L 1 1 Z" fill="#000000"/>'- f"{extra_markup}</svg>"- ).encode()- return f"data:image/svg+xml;base64,{base64.b64encode(svg).decode('ascii')}"--- ("current", "obsolete"),- [- (b"data-metafile-render", b"data-mineru-generated"),- (b"metafile-render-raster-fallback", b"mineru-raster-fallback"),- (b"metafile-render-clip-1", b"mineru-clip-1"),- ],-)-def test_generated_svg_accepts_new_contract_and_rejects_obsolete_markers(current: bytes, obsolete: bytes) -> None:- """消费端只接受独立包的新 SVG 标识,不保留旧根属性、元数据或裁剪引用。"""- data_uri = _generated_svg_data_uri(- '<defs><clipPath id="metafile-render-clip-1"><path d="M 0 0 L 1 0 L 1 1 Z"/></clipPath></defs>'- '<g clip-path="url(#metafile-render-clip-1)"><path d="M 0 0 L 1 1"/></g>'- )- payload = base64.b64decode(data_uri.split(",", 1)[1])- fallback, width, height = image_payload.extract_generated_svg_fallback(payload)- assert fallback.startswith(b"\x89PNG")- assert (width, height) == (1, 1)- with pytest.raises(ValueError):- image_payload.extract_generated_svg_fallback(payload.replace(current, obsolete))--- "content",- [- "<table><tr><td>A</td></tr></table>",- "<eq>x</eq>",- "<script>alert(1)</script>",- '<img src="images/a.png">',- ],-)-def test_supported_html_markup_detects_renderable_and_active_tags(content: str) -> None:- """验证可渲染标签和需整体删除的活动标签会进入安全层。"""- assert is_supported_html_markup(content)--- "content",- [- "plain text",- "<local_dir> p <0.05 and x > 0",- "<custom-wrapper>visible</custom-wrapper>",- "literal <b> token",- "Use <img> tag",- "Example <script> tag",- "<table>not markup</table>",- ],-)-def test_supported_html_markup_keeps_ordinary_angle_brackets_as_text(content: str) -> None:- """验证未知尖括号文本不会被误判为 HTML。"""- assert not is_supported_html_markup(content)--- ("url", "expected"),- [- ("docs/page.html", "docs/page.html"),- ("/docs/page.html", "/docs/page.html"),- ("#section", "#section"),- ("?page=2", "?page=2"),- ("https://example.com/a b", "https://example.com/a%20b"),- ("http://example.com", "http://example.com"),- ("mailto:[email protected]", "mailto:[email protected]"),- ("tel:+8610000", "tel:+8610000"),- ],-)-def test_sanitize_link_url_allows_document_links(url: str, expected: str) -> None:- """验证文档内链接和明确允许的外部协议被保留。"""- assert sanitize_link_url(url) == expected--- "url",- [- "javascript:alert(1)",- "javascript:alert(1)",- "java\nscript:alert(1)",- "data:text/html,<script>alert(1)</script>",- "vbscript:msgbox(1)",- "file:///etc/passwd",- "blob:https://example.com/id",- "//evil.example/path",- "\\evil.example\\path",- "http:relative",- "https://",- "mailto:",- "https://example.com/\ud800",- "",- ],-)-def test_sanitize_link_url_rejects_dangerous_or_invalid_urls(url: str) -> None:- """验证可执行、本地文件、协议相对及无效 URL 被拒绝。"""- assert sanitize_link_url(url) is None---def test_sanitize_image_source_rewrites_only_safe_relative_sidecars() -> None:- """验证仅安全相对 sidecar 路径应用资源根地址。"""- base = "https://cdn.example/doc"-- assert sanitize_image_source("images/a b.png", asset_base_url=base) == ("https://cdn.example/doc/images/a%20b.png")- assert sanitize_image_source("/shared/a.png", asset_base_url=base) == "/shared/a.png"- assert sanitize_image_source("https://images.example/a.png", asset_base_url=base) == ("https://images.example/a.png")--- "source",- [- "../secret.png",- "images/../secret.png",- "images/%2e%2e/secret.png",- "images/%252e%252e/secret.png",- r"images\..\secret.png",- "file:///tmp/a.png",- "blob:https://example.com/id",- "//evil.example/a.png",- "javascript:alert(1)",- "data:text/html;base64,PHNjcmlwdD4=",- "data:image/svg+xml;base64,PHN2Zz4=",- "data:image/png;base64,AAAA",- "data:image/png;base64,not-base64!",- "#image",- "?image=1",- "",- ],-)-def test_sanitize_image_source_rejects_unsafe_sources(source: str) -> None:- """验证路径逃逸、活动内容和非栅格 data URI 被拒绝。"""- assert sanitize_image_source(source, asset_base_url="assets") is None--- "source",- [- "data:image/png;base64,iVBORw0KGgo=",- "data:image/jpeg;base64,/9j/",- "data:image/gif;base64,R0lGODlh",- "data:image/webp;base64,UklGRgAAAABXRUJQ",- ],-)-def test_sanitize_image_source_allows_strict_raster_data_uris(source: str) -> None:- """验证语法正确的常见栅格图 base64 data URI 被保留。"""- assert sanitize_image_source(source, asset_base_url="https://cdn.example/doc") == source--- "asset_base_url",- [- "javascript:alert(1)",- "data:text/html,boom",- "../escape",- "//evil.example/assets",- r"\evil.example\assets",- "https://cdn.example/%252e%252e/escape",- "https://cdn.example/assets?redirect=evil",- ],-)-def test_sanitize_image_source_rejects_malicious_asset_bases(asset_base_url: str) -> None:- """验证恶意资源根地址不会被拼接到安全 sidecar 路径。"""- assert sanitize_image_source("images/a.png", asset_base_url=asset_base_url) is None---def test_sanitize_html_fragment_keeps_structure_and_bounded_attributes() -> None:- """验证表格、列表、富文本与合法数值属性被保留。"""- markup = (- "<div><blockquote><p><b>B</b><strong>S</strong><i>I</i><em>E</em><u>U</u>"- "<s>D</s><sub>1</sub><sup>2</sup><code>C</code><br><span>T</span></p></blockquote>"- '<table><colgroup span="1000"><col span="0"></colgroup><thead><tr>'- '<th colspan="2" rowspan="1001">H</th></tr></thead><tbody><tr><td rowspan="1">A</td>'- "</tr></tbody><tfoot><tr><td>B</td></tr></tfoot></table>"- '<ol start="-1000000"><li value="+0002">two</li><li value="1000001">bad</li></ol>'- "<ul><li>bullet</li></ul></div>"- )-- soup = BeautifulSoup(sanitize_html_fragment(markup), "html.parser")-- assert soup.find("table") is not None- assert soup.find("blockquote") is not None- assert not soup.find("colgroup").has_attr("span")- assert not soup.find("col").has_attr("span")- assert soup.find("th")["colspan"] == "2"- assert not soup.find("th").has_attr("rowspan")- assert soup.find("td")["rowspan"] == "1"- assert soup.find("ol")["start"] == "-1000000"- assert soup.find_all("ol")[0].find_all("li")[0]["value"] == "2"- assert not soup.find_all("ol")[0].find_all("li")[1].has_attr("value")---def test_sanitize_html_fragment_strips_source_presentation_and_clobbering_attributes() -> None:- """验证来源样式、事件、DOM clobbering 和 data 属性全部删除。"""- markup = (- '<table id="location" name="cookie" class="evil" style="position:fixed" data-x="1">'- '<tr><td onclick="alert(1)"><span id="forms" class="x" style="color:red">safe</span></td></tr>'- '</table><a href="/docs" target="_blank" onclick="alert(1)" id="x">docs</a>'- '<img src="images/a.png" alt="preview" class="x" style="x" onerror="alert(1)" width="999">'- )-- rendered = sanitize_html_fragment(markup, asset_base_url="assets")- soup = BeautifulSoup(rendered, "html.parser")-- assert soup.find("a").attrs == {"href": "/docs"}- assert soup.find("img").attrs == {"alt": "preview", "src": "assets/images/a.png"}- for tag in soup.find_all(True):- assert not ({"class", "id", "name", "style"} & tag.attrs.keys())- assert not any(name.startswith("data-") or name.startswith("on") for name in tag.attrs)---def test_sanitize_html_fragment_removes_active_elements_with_contents() -> None:- """验证活动、表单和媒体标签连同内容删除。"""- paired_tags = [- "audio",- "button",- "canvas",- "form",- "iframe",- "math",- "noscript",- "object",- "script",- "select",- "style",- "svg",- "template",- "textarea",- "video",- ]- markup = "".join(f"<{tag}>payload-{tag}</{tag}>" for tag in paired_tags)- markup += '<embed src="x"><input value="payload-input"><p>safe</p>'-- rendered = sanitize_html_fragment(markup)-- assert rendered == "<p>safe</p>"---def test_sanitize_html_fragment_unwraps_unknown_safe_elements() -> None:- """验证未知非活动 wrapper 只去除标签,不丢失可见内容。"""- markup = '<custom-wrapper onclick="alert(1)">before<strong>safe</strong>after</custom-wrapper>'-- assert sanitize_html_fragment(markup) == "before<strong>safe</strong>after"---def test_sanitize_html_fragment_repairs_list_colgroup_and_image_content_models() -> None:- """验证孤立列表项、非法直接子项、colgroup span 与缺失 alt 被规范化。"""- markup = (- "<li>orphan</li><ol>text<div>block</div><li>ok</li></ol>"- "<span>before<li>phrasing orphan</li>after</span>"- '<table><colgroup span="2"><col></colgroup><tr><td><img src="images/a.png"></td></tr></table>'- )- soup = BeautifulSoup(sanitize_html_fragment(markup), "html.parser")-- orphan = soup.find("li", string="orphan")- assert orphan.parent.name == "ul"- phrasing_orphan = soup.find("li", string="phrasing orphan")- assert phrasing_orphan.parent.name == "ul"- assert phrasing_orphan.find_parent("span") is None- assert all(isinstance(child, Tag) and child.name == "li" for child in soup.find("ol").children)- assert not soup.find("colgroup").has_attr("span")- assert soup.find("img").attrs == {"alt": "", "src": "images/a.png"}---def test_unmarked_svg_data_uri_is_rejected() -> None:- """验证普通或伪装 SVG 仍无法绕过 MinerU 安全子集。"""- assert sanitize_image_source("data:image/svg+xml;base64,PHN2Zz4=") is None---def test_mineru_generated_svg_data_uri_is_allowed() -> None:- """验证带严格 PNG fallback 的 MinerU SVG 可用于 HTML 图片。"""- source = _generated_svg_data_uri()- assert sanitize_image_source(source) == source---def test_mineru_generated_svg_rejects_dtd_beyond_prefix_window(monkeypatch: pytest.MonkeyPatch) -> None:- """验证任意偏移和编码的 DTD 都不能绕过 HTML SVG 安全校验。"""- original_fromstring = image_payload.ElementTree.fromstring- parser_calls: list[object] = []-- def guarded_fromstring(payload: bytes, parser: object | None = None) -> object:- """断言 SVG 的首次 XML 解析已经使用拒绝 DTD 的 parser。"""- assert parser is not None- parser_calls.append(parser)- return original_fromstring(payload, parser=parser) # type: ignore[arg-type,return-value]-- monkeypatch.setattr(image_payload.ElementTree, "fromstring", guarded_fromstring)- safe_svg = base64.b64decode(_generated_svg_data_uri().split(",", 1)[1])- late_doctype = (- b" " * 4097- + b'<!DOCTYPE svg [<!ENTITY injected "expanded">]>'- + safe_svg.replace(b"</svg>", b'<text x="0" y="0" fill="#000">&injected;</text></svg>')- )- utf16_doctype = (- '<!DOCTYPE svg [<!ENTITY injected "expanded">]>'- + safe_svg.decode("utf-8").replace("</svg>", '<text x="0" y="0" fill="#000">&injected;</text></svg>')- ).encode("utf-16")-- for payload in (late_doctype, utf16_doctype):- source = f"data:image/svg+xml;base64,{base64.b64encode(payload).decode('ascii')}"- assert sanitize_image_source(source) is None- assert len(parser_calls) == 2---def test_svg_data_uri_rejects_encoded_oversize_before_xml_parse(monkeypatch: pytest.MonkeyPatch) -> None:- """验证明显超限的 SVG 在 base64 解码和 XML 解析前被拒绝。"""- xml_parser = Mock(side_effect=AssertionError("oversized SVG must not reach XML parsing"))- monkeypatch.setattr(image_payload, "MAX_GENERATED_SVG_BYTES", 1)- monkeypatch.setattr(image_payload.ElementTree, "fromstring", xml_parser)-- assert sanitize_image_source(_generated_svg_data_uri()) is None- xml_parser.assert_not_called()--- "extra_markup",- [- "<script>alert(1)</script>",- '<image width="1" height="1" href="https://evil.example/a.png"/>',- "<foreignObject><div>unsafe</div></foreignObject>",- ],-)-def test_mineru_svg_marker_does_not_bypass_active_content_checks(extra_markup: str) -> None:- """验证 MinerU marker 无法放行脚本、外链或 foreignObject。"""- assert sanitize_image_source(_generated_svg_data_uri(extra_markup)) is None---def test_sanitize_html_fragment_preserves_safe_equation_as_plain_text() -> None:- """验证 eq 保留为后续公式载体,其中的标签仅作纯文本处理。"""- markup = "<p>before <eq>x<y </script><b>z</b></eq> after</p>"-- rendered = sanitize_html_fragment(markup)- soup = BeautifulSoup(rendered, "html.parser")-- assert soup.find("eq") is not None- assert soup.find("eq").get_text() == "x<y </script>z"- assert "</script>" in rendered- assert soup.find("eq").find(True) is None---def test_sanitize_html_fragment_degrades_dangerous_links_and_images_visibly() -> None:- """验证危险链接留下 label,危险图片留下已转义的 alt。"""- markup = (- '<a href="javascript:alert(1)"><strong>label</strong></a>'- '<img src="data:image/svg+xml;base64,PHN2Zz4=" alt="<unsafe>">'- )-- rendered = sanitize_html_fragment(markup)-- assert rendered == "<strong>label</strong><unsafe>"- assert "javascript" not in rendered- assert "<img" not in rendered---def test_sanitize_html_fragment_handles_malformed_mutation_xss() -> None:- """验证畸形 SVG/MathML/脚本与属性组合不会绕过二次解析。"""- markup = (- '<svg><style><img src="x" onerror="alert(1)"></style></svg>'- '<math><mtext><img src="x" onerror="alert(2)"></mtext></math>'- '<table><tr><td><a href="java
script:alert(3)">link</a>'- '<img src="images/a.png" onerror="alert(4)"></td></tr></table>'- '<iframe srcdoc="<script>alert(5)</script>">frame</iframe>'- "<!-- <script>alert(6)</script> -->"- )-- rendered = sanitize_html_fragment(markup, asset_base_url="assets")- reparsed = BeautifulSoup(rendered, "html.parser")-- assert reparsed.get_text(strip=True) == "link"- assert reparsed.find("a") is None- assert reparsed.find("img")["src"] == "assets/images/a.png"- lowered = rendered.lower()- for forbidden in ("<script", "<style", "<svg", "<math", "<iframe", "onerror", "javascript"):- assert forbidden not in lowered---def test_sanitize_html_fragment_escapes_malicious_titles_and_alt_text() -> None:- """验证 title/alt 中的引号与标签只作属性或可见文本。"""- markup = (- '<a href="https://example.com" title="" onmouseover="alert(1)">safe</a>'- '<img src="javascript:alert(2)" alt="<img src=x onerror=alert(3)>">'- )-- rendered = sanitize_html_fragment(markup)- soup = BeautifulSoup(rendered, "html.parser")-- assert soup.find("a")["title"] == '" onmouseover="alert(1)'- assert not soup.find("a").has_attr("onmouseover")- assert soup.find("img") is None- assert soup.get_text().endswith("<img src=x onerror=alert(3)>")- assert "<img src=x onerror=alert(3)>" in rendered---def test_sanitize_html_fragment_rejects_invalid_argument_types() -> None:- """验证安全层不隐式接受非字符串输入。"""- with pytest.raises(TypeError, match="markup"):- sanitize_html_fragment(None) # type: ignore[arg-type]- with pytest.raises(TypeError, match="asset_base_url"):- sanitize_html_fragment("<p>x</p>", asset_base_url=None) # type: ignore[arg-type]- with pytest.raises(TypeError, match="url"):- sanitize_link_url(None) # type: ignore[arg-type]- with pytest.raises(TypeError, match="source"):- sanitize_image_source(None) # type: ignore[arg-type]diff --git a/tests/unittest/test_latex_render.py b/tests/unittest/test_latex_render.pydeleted file mode 100644index 53892ed0..00000000--- a/tests/unittest/test_latex_render.py+++ /dev/null@@ -1,468 +0,0 @@-from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata--from _span_test_utils import inline as _inline--from copy import deepcopy-from pathlib import Path-import os-import shutil-import subprocess--from PIL import Image-import pytest--from mineru.render import render_latex-from mineru.types import (- AlgorithmBodyBlock,- ChartAnnotationBlock,- ChartBlock,- ChartBodyBlock,- CodeAnnotationBlock,- CodeBlock,- CodeBodyBlock,- DocTitleBlock,- EquationBlock,- ImageAnnotationBlock,- ImageBlock,- ImageBodyBlock,- IndexBlock,- ListBlock,- MiddleJson,- PageAuxTextBlock,- PageBlock,- PageFootnoteBlock,- PageInfo,- ParagraphTitleBlock,- TableAnnotationBlock,- TableBlock,- TableBodyBlock,- TextBlock,-)--_TEX_LIVE_FILES = (- "ctexart.cls",- "geometry.sty",- "amsmath.sty",- "amssymb.sty",- "graphicx.sty",- "longtable.sty",- "array.sty",- "booktabs.sty",- "multirow.sty",- "enumitem.sty",- "xcolor.sty",- "ulem.sty",- "xeCJKfntef.sty",- "fvextra.sty",- "hyperref.sty",- "FandolSong-Regular.otf",- "FandolSong-Bold.otf",- "FandolHei-Regular.otf",- "FandolHei-Bold.otf",- "FandolKai-Regular.otf",- "FandolFang-Regular.otf",-)---def _middle(*pages: PageInfo) -> MiddleJson:- """构造无需源坐标布局的严格测试 MiddleJson。"""- return MiddleJson(- pages=list(pages),- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:- """按调用方顺序构造一页测试内容。"""- return PageInfo(page_idx=page_idx, blocks=list(blocks))---def test_latex_document_uses_tex_live_preamble_default_planner_and_escaping() -> None:- """验证固定 TeX Live 模板、续段合并、辅助块过滤、标题和普通文本转义。"""- middle = _middle(- _page(- 0,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- DocTitleBlock(type="doc_title", index=1, level=1, content=_inline("中文标题")),- TextBlock(type="text", index=2, content=_inline("first\ninter-"), anchor="body-target"),- ),- _page(- 3,- TextBlock(type="text", index=0, content=_inline("national 50% & x_y {#} \\path"), continues_prev=True),- PageFootnoteBlock(type="page_footnote", index=1, anchor="note", content=_inline("页面脚注")),- ),- )- original = deepcopy(middle)-- rendered = render_latex(middle, document_title="Title & Metadata")-- assert rendered.startswith("% !TeX program = xelatex\n")- assert r"\documentclass[UTF8,fontset=fandol,11pt]{ctexart}" in rendered- assert "unicode-math" not in rendered and r"\setCJKmainfont" not in rendered- assert r"\hypersetup{pdftitle={Title \& Metadata}}" in rendered- assert r"first\DocVortexLineBreak{}international 50\% \& x\_y \{\#\} \textbackslash{}path\par" in rendered- assert "HEADER" not in rendered- assert "页面脚注" in rendered and r"\footnotesize\color{DocVortexGray}" in rendered- assert r"\write18" not in rendered and "minted" not in rendered and "shellesc" not in rendered.casefold()- assert rendered.endswith("\\end{document}\n")- assert rendered == render_latex(middle, document_title="Title & Metadata")- assert middle == original---def test_latex_renders_inline_styles_formulas_links_and_safe_anchors() -> None:- """验证全部 InlineSpan 样式、原始公式、内外部链接及哈希 anchor。"""- title = ParagraphTitleBlock(- type="paragraph_title",- index=0,- level=2,- anchor="章节 1/#",- content=_inline("章节一"),- )- text = TextBlock(- type="text",- index=1,- content=[- {"type": "text", "content": "Styled", "styles": ["bold", "italic", "underline"]},- {"type": "text", "content": " dot", "styles": ["emphasis"]},- {"type": "text", "content": " strike", "styles": ["strikethrough"]},- {"type": "text", "content": "2", "styles": ["superscript"]},- {"type": "text", "content": "i", "styles": ["subscript"]},- {"type": "code_inline", "content": "a_b% c"},- {"type": "equation_inline", "content": r"x_1^2"},- {"type": "hyperlink", "url": "#章节 1/#", "content": _inline("jump")},- {"type": "hyperlink", "url": "https://example.com/a_b?q=1&x=2", "content": _inline("external")},- ],- )- equation = EquationBlock(type="equation", index=2, content=r"\frac{1}{1-x^2}\tag{7}")- aligned = EquationBlock(type="equation", index=3, content=r"\begin{align}a&=b\\c&=d\end{align}")-- rendered = render_latex(_middle(_page(0, title, text, equation, aligned)))-- assert r"\textbf{\textit{\uline{Styled}}}" in rendered- assert r"\CJKunderdot[format=\normalcolor]{ dot}" in rendered- assert r"\sout{ strike}" in rendered- assert r"\textsuperscript{2}" in rendered and r"\textsubscript{i}" in rendered- assert r"\texttt{a\_b\%\ \ c}" in rendered and r"\(x_1^2\)" in rendered- assert r"\hypertarget{docvortex-" in rendered and r"\hyperlink{docvortex-" in rendered- assert r"\href{https://example.com/a\_b?q=1\&x=2}{external}" in rendered- assert "\\begin{equation*}\n\\frac{1}{1-x^2}\\tag{7}\n\\end{equation*}" in rendered- assert rendered.count(r"\begin{align}") == 1 and r"\begin{equation*}\begin{align}" not in rendered---def test_latex_renders_native_lists_and_linked_index() -> None:- """验证有序、显式、嵌套列表和目录链接保持来源语义。"""- target = ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="target", content=_inline("Target"))- ordered = ListBlock(- type="list",- index=1,- sub_type="text",- content=[- TextBlock(type="text", content=_inline("2. Second")),- TextBlock(type="text", content=_inline("4. Fourth")),- ListBlock(type="list", sub_type="text", content=[TextBlock(type="text", content=_inline("- Nested"))]),- ],- )- explicit = ListBlock(- type="list",- index=2,- sub_type="text",- content=[- TextBlock(type="text", content=_inline("[A] Alpha")),- TextBlock(type="text", content=_inline("plain")),- ],- )- index = IndexBlock(- type="index",- index=3,- content=[ParagraphTitleBlock(type="paragraph_title", level=2, anchor="target", content=_inline("Target\t12"))],- )-- rendered = render_latex(_middle(_page(0, target, ordered, explicit, index)))-- assert r"\begin{enumerate}[leftmargin=*,nosep]" in rendered- assert r"\item[{2.}] Second" in rendered and r"\item[{4.}] Fourth" in rendered- assert r"\item Nested" in rendered- assert r"\begin{description}[style=nextline,leftmargin=3em,nosep]" in rendered- assert r"\item[{[A]}] Alpha" in rendered and r"\item[{}] plain" in rendered- assert "Target 12" not in rendered- assert r"\hyperlink{docvortex-" in rendered and "{Target}" in rendered---def test_latex_renders_visual_blocks_complex_tables_and_code_in_source_order() -> None:- """验证图片、复杂表格、图表、代码和视觉说明按子块来源顺序输出。"""- image = ImageBlock(- type="image",- index=0,- content=[- ImageAnnotationBlock(type="image_caption", content=_inline("Before image")),- ImageBodyBlock(type="image_body", index=0, content="Alt", image_path="images/a b.png"),- ImageAnnotationBlock(type="image_footnote", content=_inline("After image")),- ],- )- table_html = (- "<table><thead><tr><th rowspan='2'>H</th><th colspan='2'><b>Group</b></th></tr></thead>"- "<tbody><tr><td><eq>x^2</eq></td><td>before<table><tr><td>Nested</td></tr></table></td></tr></tbody></table>"- )- table = TableBlock(- type="table",- index=1,- content=[- TableBodyBlock(type="table_body", index=1, content=table_html),- TableAnnotationBlock(type="table_caption", content=_inline("Table caption")),- ],- )- chart = ChartBlock(- type="chart",- index=2,- content=[- ChartBodyBlock(- type="chart_body",- index=2,- content="<table><tr><td>Data</td></tr></table>",- image_path="images/chart.png",- ),- ChartAnnotationBlock(type="chart_footnote", content=_inline("Chart note")),- ],- )- code = CodeBlock(- type="code",- index=3,- sub_type="code",- guess_lang="python",- content=[- CodeBodyBlock(type="code_body", index=3, content="print('x_y%')\n\\end{DocVortexVerbatim1}"),- CodeAnnotationBlock(type="code_caption", content=_inline("Code caption")),- ],- )- algorithm = CodeBlock(- type="code",- index=4,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=4,- content=[{"type": "text", "content": "Step "}, {"type": "equation_inline", "content": "x^2"}],- )- ],- )-- rendered = render_latex(- _middle(_page(0, image, table, chart, code, algorithm)),- asset_base_path="document assets",- )-- assert rendered.index("Before image") < rendered.index(r"\detokenize{document assets/images/a b.png}")- assert rendered.index(r"\detokenize{document assets/images/a b.png}") < rendered.index("After image")- assert r"\begin{longtable}" in rendered and r"\multirow{2}" in rendered and r"\multicolumn{2}" in rendered- assert r"\cline{2-3}" in rendered- assert r"\begin{tabular}" in rendered and "Nested" in rendered and r"\(x^2\)" in rendered- assert r"\detokenize{document assets/images/chart.png}" in rendered and "Data" in rendered- assert "Table caption" in rendered and "Chart note" in rendered- assert r"\DefineVerbatimEnvironment{DocVortexVerbatim2}" in rendered- assert "print('x_y%')" in rendered and "Code caption" in rendered- assert r"{\small\ttfamily Step \(x^2\)\par}" in rendered---def test_latex_table_cell_preserves_interleaved_text_image_and_nested_table_order() -> None:- """验证单元格文字、图片与嵌套表格严格保持 HTML 来源顺序。"""-- table = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content=(- "<table><tr><td><b>before<img src='images/cell.png' alt='cell'>after</b>"- "<table><tr><td>nested</td></tr></table>tail</td></tr></table>"- ),- )- ],- )-- rendered = render_latex(- _middle(_page(0, table)),- asset_base_path="assets",- )-- before_index = rendered.index(r"\textbf{before}")- image_index = rendered.index(r"\detokenize{assets/images/cell.png}")- after_index = rendered.index(r"\textbf{after}")- nested_index = rendered.index("nested")- tail_index = rendered.index("tail")- assert before_index < image_index < after_index < nested_index < tail_index---def test_latex_image_and_table_fallbacks_remain_visible_without_io() -> None:- """验证远程、data URI、不支持格式和畸形表格均退化为可见内容。"""- remote = ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="Remote diagram",- image_url="https://example.com/a.png",- )- ],- )- unsupported = ImageBlock(- type="image",- index=1,- content=[ImageBodyBlock(type="image_body", index=1, content="SVG diagram", image_path="images/a.svg")],- )- malformed = TableBlock(- type="table",- index=2,- content=[TableBodyBlock(type="table_body", index=2, content="<table><tr><td rowspan='2'>A</td></tr></table>")],- )- spatial = TableBlock(- type="table",- index=3,- content=[TableBodyBlock(type="table_body", index=3, content="A B\n1 2")],- )- inline_chart = ChartBlock(- type="chart",- index=4,- content=[- ChartBodyBlock(- type="chart_body",- index=4,- content="",- image_base64="data:image/png;base64,AAAA",- )- ],- )- empty_formula = EquationBlock(type="equation", index=5, content="")- empty_table = TableBlock(- type="table",- index=6,- content=[TableBodyBlock(type="table_body", index=6, content="")],- )-- rendered = render_latex(- _middle(_page(0, remote, unsupported, malformed, spatial, inline_chart, empty_formula, empty_table))- )-- assert r"\href{https://example.com/a.png}" in rendered and "Remote diagram" in rendered- assert "SVG diagram" in rendered and "images/a.svg" not in rendered- assert "A" in rendered and rendered.count("table unavailable") == 1- assert "A B\n1 2" in rendered- assert rendered.count(r"\DefineVerbatimEnvironment") == 2- assert "image unavailable: chart" in rendered- assert "formula unavailable" in rendered and "table unavailable" in rendered---def test_latex_normalizes_windows_asset_prefix_without_system_font_or_io_dependencies() -> None:- """验证 Windows 路径前缀使用 XeLaTeX 跨平台可读的正斜杠。"""- image = ImageBlock(- type="image",- index=0,- content=[ImageBodyBlock(type="image_body", index=0, content="image", image_path="images/a.png")],- )-- rendered = render_latex(_middle(_page(0, image)), asset_base_path=r"C:\documents\output")-- assert r"\detokenize{C:/documents/output/images/a.png}" in rendered---def test_latex_public_entry_rejects_invalid_contract_values() -> None:- """验证专用入口拒绝旧字典、错误选项类型和控制字符路径。"""- middle = _middle(_page(0))-- with pytest.raises(TypeError, match="MiddleJson"):- render_latex(middle.to_dict()) # type: ignore[arg-type]- with pytest.raises(TypeError, match="asset_base_path"):- render_latex(middle, asset_base_path=1) # type: ignore[arg-type]- with pytest.raises(TypeError, match="document_title"):- render_latex(middle, document_title=1) # type: ignore[arg-type]- with pytest.raises(ValueError, match="control"):- render_latex(middle, asset_base_path="images\nunsafe")---def test_latex_compiles_with_default_tex_live_full(tmp_path: Path) -> None:- """在可用或强制要求的 TeX Live full 环境中真实编译代表文档。"""- required = os.environ.get("MINERU_REQUIRE_TEXLIVE") == "1"- latexmk = shutil.which("latexmk")- xelatex = shutil.which("xelatex")- kpsewhich = shutil.which("kpsewhich")- missing_tools = [- name for name, path in (("latexmk", latexmk), ("xelatex", xelatex), ("kpsewhich", kpsewhich)) if path is None- ]- if missing_tools:- message = f"TeX Live tools are unavailable: {', '.join(missing_tools)}"- pytest.fail(message) if required else pytest.skip(message)- assert latexmk is not None and xelatex is not None and kpsewhich is not None-- missing_files = [- filename- for filename in _TEX_LIVE_FILES- if subprocess.run([kpsewhich, filename], capture_output=True, text=True, check=False).returncode != 0- ]- if missing_files:- message = f"TeX Live scheme-full files are unavailable: {', '.join(missing_files)}"- pytest.fail(message) if required else pytest.skip(message)-- image_dir = tmp_path / "images"- image_dir.mkdir()- Image.new("RGB", (16, 8), (40, 80, 120)).save(image_dir / "sample image.png")- middle = _middle(- _page(- 0,- DocTitleBlock(type="doc_title", index=0, level=1, content=_inline("中文 TeX Live")),- TextBlock(- type="text",- index=1,- content=[- {"type": "text", "content": "正文 "},- {"type": "equation_inline", "content": r"x_1^2"},- ],- ),- EquationBlock(type="equation", index=2, content=r"\frac{a}{b}\tag{1}"),- ImageBlock(- type="image",- index=3,- content=[ImageBodyBlock(type="image_body", index=3, content="sample", image_path="images/sample image.png")],- ),- TableBlock(- type="table",- index=4,- content=[- TableBodyBlock(- type="table_body",- index=4,- content="<table><tr><th colspan='2'>Header</th></tr><tr><td>A</td><td><eq>x</eq></td></tr></table>",- )- ],- ),- CodeBlock(- type="code",- index=5,- sub_type="code",- guess_lang="python",- content=[CodeBodyBlock(type="code_body", index=5, content="print('TeX Live')")],- ),- )- )- tex_path = tmp_path / "main.tex"- tex_path.write_text(render_latex(middle), encoding="utf-8")-- result = subprocess.run(- [latexmk, "-xelatex", "-interaction=nonstopmode", "-halt-on-error", tex_path.name],- cwd=tmp_path,- capture_output=True,- text=True,- check=False,- timeout=120,- )-- assert result.returncode == 0, f"{result.stdout}\n{result.stderr}"- assert (tmp_path / "main.pdf").read_bytes().startswith(b"%PDF-")diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.pyindex 250ccbad..8caffd52 100644--- a/tests/unittest/test_markdown_render.py+++ b/tests/unittest/test_markdown_render.py@@ -1,35 +1,16 @@from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inline--from copy import deepcopy-from typing import Literalimport pytest+from docvortex.schema import Producerfrom mineru.config import Config-from mineru.render import RenderMode, render_markdown+from mineru.integrations.docvortex import build_metadata+from mineru.render import render_markdownfrom mineru.types import (- AlgorithmBodyBlock,- ChartBlock,- ChartBodyBlock,- CodeBlock,- CodeBodyBlock,EquationBlock,- ImageBlock,- ImageBodyBlock,- IndexBlock,- ListBlock,MiddleJson,- PageAuxTextBlock,PageBlock,- PageFootnoteBlock,PageInfo,- ParagraphTitleBlock,- RefTextBlock,- TableBlock,- TableBodyBlock,TextBlock,)@@ -50,606 +31,6 @@ def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:return PageInfo(page_idx=page_idx, blocks=list(blocks))-def _image(index: int, path: str = "images/a.png") -> ImageBlock:- """构造带 path 的图片父块。"""- return ImageBlock(- type="image",- index=index,- content=[ImageBodyBlock(type="image_body", index=index, content="", image_path=path)],- )---def _table(index: int, content: str, *, continues_prev: bool | None = None) -> TableBlock:- """构造无 bbox 的 Office 表格父块。"""- return TableBlock(- type="table",- index=index,- continues_prev=continues_prev,- content=[TableBodyBlock(type="table_body", index=index, content=content)],- )---def _pdf_table(- index: int,- content: str,- *,- continues_prev: bool | None = None,-) -> TableBlock:- """构造带归一化 bbox 的 PDF 表格父块。"""- bbox = (0.1, 0.1, 0.9, 0.9)- return TableBlock(- type="table",- index=index,- bbox=bbox,- continues_prev=continues_prev,- content=[TableBodyBlock(type="table_body", index=index, bbox=bbox, content=content)],- )---def _list(- index: int,- *items: str | list[dict[str, object]],- sub_type: Literal["text", "ref_text"] | None = None,- continues_prev: bool | None = None,-) -> ListBlock:- """构造带归一化 bbox 的列表父块,并按子类型生成文本叶子。"""- child_type = sub_type or "text"- child_class = RefTextBlock if child_type == "ref_text" else TextBlock- return ListBlock(- type="list",- index=index,- bbox=(0.1, 0.1, 0.9, 0.3),- sub_type=sub_type,- continues_prev=continues_prev,- content=[child_class(type=child_type, content=_inline(item) if isinstance(item, str) else item) for item in items],- )---def _ref_text(index: int, content: str, *, continues_prev: bool | None = None) -> RefTextBlock:- """构造可携带续段标记的顶层参考文献文本块。"""- return RefTextBlock(- type="ref_text",- index=index,- content=_inline(content),- continues_prev=continues_prev,- )---def test_render_modes_filter_merge_and_preserve_input() -> None:- """验证两种模式的过滤、页内/跨页合并、分页线及无副作用。"""- middle = _middle(- _page(- 0,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- TextBlock(type="text", index=1, content=_inline("Hello")),- _image(2),- TextBlock(type="text", index=3, content=_inline("world"), continues_prev=True),- PageAuxTextBlock(type="footer", index=4, content=_inline("FOOTER")),- ),- _page(- 1,- PageAuxTextBlock(type="page_number", index=0, content=_inline("2")),- TextBlock(type="text", index=1, content=_inline("again"), continues_prev=True),- PageFootnoteBlock(type="page_footnote", index=2, content=_inline("NOTE")),- ),- )- before = middle.to_json(skip_defaults=False)-- default = render_markdown(middle)- full = render_markdown(middle, mode=RenderMode.FULL)-- note = '<small><span class="docvortex-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'- assert default == f"Hello world again\n\n\n\n{note}"- assert full == "\n\n---\n\n".join(- [- "HEADER\n\nHello world\n\n\n\nFOOTER",- f"2\n\nagain\n\n{note}",- ]- )- assert middle.to_json(skip_defaults=False) == before---def test_page_footnote_is_styled_and_linkable_in_default_and_full_modes() -> None:- """验证默认与完整模式都输出非折叠的小字号页面脚注及 anchor。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "See "},- {"type": "hyperlink", "url": "#note-one", "content": _inline("[1]")},- {"type": "text", "content": "."},- ],- ),- PageFootnoteBlock(- type="page_footnote",- index=1,- content=_inline("Footnote body."),- anchor="note-one",- ),- )- )-- expected = (- 'See [\\[1\\]](#note-one).\n\n<small><span id="note-one" class="docvortex-page-footnote" '- 'data-block-type="page_footnote" style="color:#6b7280">Footnote body.</span></small>'- )- assert render_markdown(middle) == expected- assert render_markdown(middle, mode=RenderMode.FULL) == expected- assert "Page footnote:" not in expected---def test_page_footnote_does_not_interrupt_continued_text_rendering() -> None:- """验证页面脚注保持独立输出,但不会阻断前后正文续接。"""- middle = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("inter-")),- PageFootnoteBlock(type="page_footnote", index=1, content=_inline("NOTE")),- TextBlock(type="text", index=2, content=_inline("national"), continues_prev=True),- )- )-- assert render_markdown(middle) == (- 'international\n\n<small><span class="docvortex-page-footnote" '- 'data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'- )---def test_full_mode_preserves_empty_page_boundaries() -> None:- """验证 FULL 对空白页仍保留相邻页分割线。"""- middle = _middle(_page(0), _page(1, TextBlock(type="text", index=0, content=_inline("x"))), _page(2))-- assert render_markdown(middle, mode=RenderMode.FULL) == "\n\n---\n\nx\n\n---\n\n"- assert render_markdown(middle) == "x"---def test_text_continuation_handles_hyphen_and_cjk_boundaries() -> None:- """验证续写文本沿用西文断词与 CJK 直接连接规则。"""- western = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("inter-")),- TextBlock(type="text", index=1, content=_inline("national"), continues_prev=True),- )- )- cjk = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("中文")),- TextBlock(type="text", index=1, content=_inline("继续"), continues_prev=True),- )- )-- assert render_markdown(western) == "international"- assert render_markdown(cjk) == "中文继续"---def test_ref_text_continuation_skips_merge_transparent_blocks_by_mode() -> None:- """验证 ref_text 可跨页面脚注与辅助块查找,FULL 仍保留页界。"""- middle = _middle(- _page(- 0,- _ref_text(0, "inter-"),- PageFootnoteBlock(type="page_footnote", index=1, content=_inline("NOTE")),- ),- _page(- 1,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- _ref_text(1, "national", continues_prev=True),- _ref_text(2, "continuation", continues_prev=True),- ),- )- original = deepcopy(middle)-- note = '<small><span class="docvortex-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'- assert render_markdown(middle) == f"international continuation\n\n{note}"- assert render_markdown(middle, mode=RenderMode.FULL) == (f"inter-\n\n{note}\n\n---\n\nHEADER\n\nnational continuation")- assert middle == original---def test_ref_text_continuation_keeps_semantic_barrier() -> None:- """验证手工标记也不能让 ref_text 跨过正文等语义块。"""- middle = _middle(- _page(- 0,- _ref_text(0, "first"),- TextBlock(type="text", index=1, content=_inline("separator")),- _ref_text(2, "second", continues_prev=True),- )- )-- assert render_markdown(middle) == "first\n\nseparator\n\nsecond"---def test_ref_text_continuation_reuses_url_boundary_joining() -> None:- """验证 ref_text 续段复用正文的跨块 URL 连接规则。"""- middle = _middle(- _page(- 0,- _ref_text(0, "See https://doi.o"),- _ref_text(1, "rg/10.1016/example", continues_prev=True),- )- )-- assert render_markdown(middle) == "See https://doi.org/10.1016/example"---def test_list_continuation_merges_same_page_in_both_modes_without_mutating_input() -> None:- """验证同页同子类型列表在两种模式下拼接,且不污染原始 MiddleJson。"""- middle = _middle(- _page(- 0,- _list(0, "- first"),- _list(1, "- second", continues_prev=True),- ),- file_suffix="pdf",- )- original = deepcopy(middle)-- assert render_markdown(middle) == "- first\n- second"- assert render_markdown(middle, mode=RenderMode.FULL) == "- first\n- second"- assert middle == original---def test_list_continuation_merges_cross_page_chain_only_in_default_mode() -> None:- """验证跨页列表链仅在默认模式整体拼接,完整模式保留页界并合并页内续段。"""- middle = _middle(- _page(0, _list(0, "[1] first", sub_type="ref_text")),- _page(- 1,- _list(0, "[2] second", sub_type="ref_text", continues_prev=True),- _list(1, "[3] third", sub_type="ref_text", continues_prev=True),- ),- file_suffix="pdf",- )-- assert render_markdown(middle) == "[1] first\n[2] second\n[3] third"- assert render_markdown(middle, mode=RenderMode.FULL) == ("[1] first\n\n---\n\n[2] second\n[3] third")---def test_ref_list_continuation_skips_merge_transparent_blocks_without_mutating_input() -> None:- """验证默认模式跨页面脚注与辅助块合并参考文献,FULL 仍保留页界。"""- middle = _middle(- _page(- 0,- _list(0, "[1] first", sub_type="ref_text"),- PageFootnoteBlock(type="page_footnote", index=1, content=_inline("NOTE")),- ),- _page(- 1,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- PageAuxTextBlock(type="page_number", index=1, content=_inline("2")),- _list(2, "[2] second", sub_type="ref_text", continues_prev=True),- ),- )- original = deepcopy(middle)-- note = '<small><span class="docvortex-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'- assert render_markdown(middle) == f"[1] first\n[2] second\n\n{note}"- assert render_markdown(middle, mode=RenderMode.FULL) == (f"[1] first\n\n{note}\n\n---\n\nHEADER\n\n2\n\n[2] second")- assert middle == original---def test_ordinary_list_continuation_does_not_skip_page_footnote() -> None:- """验证页面脚注透明规则只作用于参考文献,普通列表仍要求物理相邻。"""- middle = _middle(- _page(- 0,- _list(0, "- first"),- PageFootnoteBlock(type="page_footnote", index=1, content=_inline("NOTE")),- ),- _page(- 1,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- _list(1, "- second", continues_prev=True),- ),- )-- assert render_markdown(middle) == (- '- first\n\n<small><span class="docvortex-page-footnote" data-block-type="page_footnote" '- 'style="color:#6b7280">NOTE</span></small>\n\n- second'- )---def test_list_continuation_keeps_semantic_barrier_and_matching_subtype() -> None:- """验证语义块仍会阻断列表续接,且子类型不一致时保持独立输出。"""- non_adjacent = _middle(- _page(- 0,- _list(0, "[1] first", sub_type="ref_text"),- TextBlock(type="text", index=1, bbox=(0.1, 0.4, 0.9, 0.5), content=_inline("separator")),- _list(2, "[2] second", sub_type="ref_text", continues_prev=True),- ),- file_suffix="pdf",- )- mismatched = _middle(- _page(- 0,- _list(0, "[1] first", sub_type="ref_text"),- _list(1, "- second", sub_type="text", continues_prev=True),- ),- file_suffix="pdf",- )-- assert render_markdown(non_adjacent) == "[1] first\n\nseparator\n\n[2] second"- assert render_markdown(mismatched) == "[1] first\n\n- second"--- ("item", "expected"),- [- ("[1] bracket", "[1] bracket"),- ("1. dot", "1. dot"),- ("(1) parenthesized", "(1) parenthesized"),- ("1) closing parenthesis", "1) closing parenthesis"),- ("1、cjk delimiter", "1、cjk delimiter"),- ("[1]full width", "[1]full width"),- ('<text style="bold">[1]</text> styled', "**[1]** styled"),- ],-)-def test_reference_list_keeps_supported_numeric_prefix_styles(item: str, expected: str) -> None:- """验证数字出现在前五个可见字符内时,单条参考文献保留原有编号。"""- content = (- [- {"type": "text", "content": "[1]", "styles": ["bold"]},- {"type": "text", "content": " styled"},- ]- if item.startswith("<text")- else _inline(item)- )- middle = _middle(_page(0, _list(0, content, sub_type="ref_text")), file_suffix="pdf")-- assert render_markdown(middle) == expected---def test_reference_list_uses_strict_numeric_prefix_majority() -> None:- """验证参考文献按全部直属非空条目的严格多数决定是否补无序标记。"""- numbered_majority = _middle(- _page(0, _list(0, "[1] first", "missing marker", "3) third", sub_type="ref_text")),- file_suffix="pdf",- )- unordered_majority = _middle(- _page(0, _list(0, "1470–1480 continuation", "Author A", "Author B", sub_type="ref_text")),- file_suffix="pdf",- )- tied = _middle(- _page(0, _list(0, "[1] first", "Author A", sub_type="ref_text")),- file_suffix="pdf",- )-- assert render_markdown(numbered_majority) == "[1] first\nmissing marker\n3) third"- expected_unordered = "- 1470–1480 continuation\n- Author A\n- Author B"- assert render_markdown(unordered_majority) == expected_unordered- assert render_markdown(unordered_majority, mode=RenderMode.FULL) == expected_unordered- assert render_markdown(tied) == "- [1] first\n- Author A"---def test_reference_list_bullets_mixed_children_without_duplication() -> None:- """验证混合直属类型共同参与统计,已有短横线不重复且多行正文正确缩进。"""- block = ListBlock(- type="list",- index=0,- bbox=(0.1, 0.1, 0.9, 0.3),- sub_type="ref_text",- content=[- TextBlock(type="text", content=_inline("- existing")),- RefTextBlock(type="ref_text", content=_inline("Author A\ncontinued")),- ],- )-- assert render_markdown(_middle(_page(0, block), file_suffix="pdf")) == ("- existing\n- Author A\n continued")---def test_nested_reference_list_decides_bullets_independently() -> None:- """验证嵌套参考文献依据自身子类型判定,外层普通列表行为保持不变。"""- nested = ListBlock(- type="list",- sub_type="ref_text",- content=[RefTextBlock(type="ref_text", content=_inline("Author A"))],- )- outer = ListBlock(- type="list",- index=0,- bbox=(0.1, 0.1, 0.9, 0.3),- sub_type="text",- content=[TextBlock(type="text", content=_inline("- outer")), nested],- )-- assert render_markdown(_middle(_page(0, outer), file_suffix="pdf")) == "- outer\n - Author A"---def test_text_continuation_joins_url_candidates_but_separates_independent_urls() -> None:- """验证 Markdown 续写连接跨块 URL,同时保留两条独立 URL 的分隔。"""- continued_url = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("See https://doi.o")),- TextBlock(type="text", index=1, content=_inline("rg/10.1016/example"), continues_prev=True),- )- )- independent_urls = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("https://example.test/first")),- TextBlock(type="text", index=1, content=_inline("https://example.test/second"), continues_prev=True),- )- )-- assert render_markdown(continued_url) == "See https://doi.org/10.1016/example"- assert render_markdown(independent_urls) == "https://example.test/first https://example.test/second"---def test_text_continuation_does_not_rewrite_formula_or_style_wrappers() -> None:- """验证续写边界不会越过末尾公式或破坏样式节点。"""- formula = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[{"type": "text", "content": "before "}, {"type": "equation_inline", "content": "x"}],- ),- TextBlock(type="text", index=1, content=_inline("after"), continues_prev=True),- )- )- styled = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("inter-", styles=["bold"])),- TextBlock(type="text", index=1, content=_inline("national"), continues_prev=True),- )- )-- assert render_markdown(formula) == "before $x$ after"- assert render_markdown(styled) == "**inter**national"---def test_render_rejects_legacy_inputs_and_string_mode() -> None:- """验证公共入口不兼容旧 dict/pages 输入或字符串模式。"""- middle = _middle(_page(0))-- with pytest.raises(TypeError, match="MiddleJson"):- render_markdown(middle.to_dict()) # type: ignore[arg-type]- with pytest.raises(TypeError, match="RenderMode"):- render_markdown(middle, mode="full") # type: ignore[arg-type]---def test_inline_rich_text_unknown_tags_and_visible_spaces() -> None:- """验证富文本、公式、链接、未知标签与可见空白。"""- content = [- {"type": "text", "content": "A "},- {"type": "text", "content": "B", "styles": ["bold"]},- {"type": "text", "content": " "},- {- "type": "hyperlink",- "url": "https://example.com/a b",- "content": [{"type": "text", "content": "link", "styles": ["underline"]}],- },- {"type": "text", "content": " "},- {"type": "equation_inline", "content": "x_1"},- {"type": "text", "content": " <local_dir> p <0.05 and x > 0 "},- {"type": "text", "content": "2", "styles": ["superscript"]},- {"type": "text", "content": " ", "styles": ["underline"]},- ]- middle = _middle(_page(0, TextBlock(type="text", index=0, content=content)))-- rendered = render_markdown(middle)-- assert "**B**" in rendered- assert '<a href="https://example.com/a b"><u>link</u></a>' in rendered- assert "$x_1$" in rendered- assert "<local_dir>" in rendered- assert "p <0.05 and x > 0" in rendered- assert "<sup>2</sup>" in rendered- assert rendered.endswith("<sup>2</sup>__")--- ("style", "expected"),- [- ("underline", "A___B"),- ("strikethrough", "A---B"),- ("underline,strikethrough", "A<s>___</s>B"),- ("bold,underline", "A<strong>___</strong>B"),- ],-)-def test_visible_style_ascii_spaces_use_dev_markers(style: str, expected: str) -> None:- """验证纯 ASCII 样式空格使用 dev 的下划线或短横线 marker。"""- content = [- {"type": "text", "content": "A"},- {"type": "text", "content": " ", "styles": style.split(",")},- {"type": "text", "content": "B"},- ]-- assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected--- ("style", "expected"),- [- ("underline", "<u>___广东__</u>"),- ("strikethrough", "~~---广东--~~"),- ("underline,strikethrough", "<s><u>___广东__</u></s>"),- ],-)-def test_visible_style_edge_spaces_use_dev_markers(style: str, expected: str) -> None:- """验证非空样式文本只替换首尾 ASCII 空格。"""- content = _inline(" 广东 ", styles=style.split(","))-- assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected--- ("style", "expected"),- [- ("underline", r"\___"),- ("strikethrough", r"\---"),- ],-)-def test_standalone_visible_space_markers_are_escaped(style: str, expected: str) -> None:- """验证整块 marker 会转义首字符,避免被当作 Markdown 分割线。"""- content = _inline(" ", styles=[style])-- assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected---def test_emphasis_only_spaces_keep_existing_html_behavior() -> None:- """验证 emphasis-only 空格不进入 underline/strikethrough marker 规则。"""- content = _inline(" ", styles=["emphasis"])-- rendered = render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content))))-- assert " " in rendered---def test_text_block_escapes_markdown_prefix_and_malformed_tag() -> None:- """验证普通 text 不会误变列表,损坏白名单标签按原文转义。"""- middle = _middle(- _page(- 0,- TextBlock(type="text", index=0, content=_inline("- plain")),- TextBlock(type="text", index=1, content=_inline('<text style="bold">broken')),- )- )-- assert render_markdown(middle) == '\\- plain\n\n<text style="bold">broken'---def test_title_and_index_render_anchor_links_without_heading_leaves() -> None:- """验证标题 anchor 与递归目录 title leaf 的链接输出。"""- index = IndexBlock(- type="index",- index=0,- content=[- ParagraphTitleBlock(- type="paragraph_title",- level=2,- anchor="toc-a",- content=_inline("1 Section\t12"),- ),- IndexBlock(- type="index",- content=[TextBlock(type="text", content=_inline("Plain"))],- ),- ],- )- title = ParagraphTitleBlock(- type="paragraph_title",- index=1,- level=6,- anchor="toc-a",- content=_inline("Section"),- )-- rendered = render_markdown(_middle(_page(0, index, title)))-- assert rendered.startswith("- [1 Section](#toc-a)\n - Plain")- assert '<a id="toc-a"></a>\n###### Section' in rendered--def test_equation_uses_content_then_image_fallback(monkeypatch: pytest.MonkeyPatch) -> None:"""验证行间公式定界符配置及空公式图片回退。"""configured = Config(@@ -675,266 +56,3 @@ def test_equation_uses_content_then_image_fallback(monkeypatch: pytest.MonkeyPat)assert render_markdown(middle) == "\\[\nx=1\n\\]\n\n\n\ninline \\(y\\)"--- "html_table",- [- "<table><tr><td rowspan='2'>A</td></tr><tr><td>B</td></tr></table>",- "<table><tr><td colspan='2'>A</td></tr></table>",- "<table><tr><td><table><tr><td>N</td></tr></table></td></tr></table>",- "<table><tr><td><img src='images/a.png'></td></tr></table>",- "<table><tr><td><ul><li>A</li></ul></td></tr></table>",- "<table><tr><td><p>A</p><p>B</p></td></tr></table>",- ],-)-def test_complex_html_tables_fall_back_to_html(html_table: str) -> None:- """验证不可无损转换的表格结构保持 HTML。"""- rendered = render_markdown(_middle(_page(0, _table(0, html_table))), asset_base_url="assets")-- assert rendered.startswith("<table")- assert "| --- |" not in rendered- if "<img" in html_table:- assert "assets/images/a.png" in rendered---def test_simple_html_table_converts_to_gfm_and_preserves_inline_formula() -> None:- """验证简单 HTML table 转 GFM,并保留单元格公式反斜杠。"""- content = "<table><tr><th>Name</th><th>Value</th></tr><tr><td>A|B</td><td><eq>\\frac{1}{2}</eq></td></tr></table>"-- assert render_markdown(_middle(_page(0, _table(0, content)))) == "\n".join(- [- "| Name | Value |",- "| --- | --- |",- r"| A\|B | $\frac{1}{2}$ |",- ]- )---def test_spatial_table_uses_dynamic_fence_and_empty_table_uses_image() -> None:- """验证空间投影文本保留空白,且空表回退图片。"""- spatial = _table(0, "A B\n```\n1 2")- empty = TableBlock(- type="table",- index=1,- content=[TableBodyBlock(type="table_body", index=1, content="", image_path="images/t.png")],- )-- rendered = render_markdown(_middle(_page(0, spatial, empty)))-- assert rendered.startswith("````\nA B\n```\n1 2\n````")- assert rendered.endswith("")---def test_cross_page_table_merges_only_in_default_mode() -> None:- """验证续表只在 DEFAULT 跨页合并,FULL 保持分页。"""- previous_html = "<table><tr><th>H</th></tr><tr><td>A</td></tr></table>"- current_html = "<table><tr><th>H</th></tr><tr><td>B</td></tr></table>"- middle = _middle(- _page(0, _pdf_table(0, previous_html)),- _page(1, _pdf_table(0, current_html, continues_prev=True)),- file_suffix="pdf",- )- original = deepcopy(middle)-- default = render_markdown(middle)- full = render_markdown(middle, mode=RenderMode.FULL)-- assert default == "\n".join(["| H |", "| --- |", "| A |", "| B |"])- assert full.count("| --- |") == 2- assert "\n\n---\n\n" in full- assert middle == original---def test_code_uses_language_and_dynamic_fence() -> None:- """验证普通代码使用 guess_lang 和足够长的 fenced block。"""- code = CodeBlock(- type="code",- index=0,- sub_type="code",- guess_lang="python",- content=[CodeBodyBlock(type="code_body", index=0, content="print('x')\n```")],- )- invalid_language = CodeBlock(- type="code",- index=1,- sub_type="code",- guess_lang="python bad",- content=[CodeBodyBlock(type="code_body", index=1, content="x")],- )-- rendered = render_markdown(_middle(_page(0, code, invalid_language)))-- assert rendered.startswith("````python\nprint('x')\n```\n````")- assert rendered.endswith("```txt\nx\n```")---def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> None:- """验证算法 raw HTML 使用 HTML 行内语法并保留缩进与相邻公式。"""- algorithm = CodeBlock(- type="code",- index=0,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=0,- content=[- {"type": "text", "content": "if a < b and c * d:\n "},- {"type": "text", "content": "bold", "styles": ["bold"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "italic", "styles": ["italic"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "strike", "styles": ["strikethrough"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "under", "styles": ["underline"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "dot", "styles": ["emphasis"]},- {"type": "text", "content": " "},- {"type": "text", "content": "q", "styles": ["subscript"]},- {"type": "text", "content": "2", "styles": ["superscript"]},- {"type": "text", "content": " "},- {"type": "code_inline", "content": "x * y"},- {"type": "text", "content": " "},- {- "type": "hyperlink",- "url": "https://example.com/a b",- "content": [{"type": "text", "content": "link", "styles": ["bold"]}],- },- {"type": "text", "content": " = "},- {"type": "equation_inline", "content": "a < b"},- {"type": "equation_inline", "content": "c > d"},- ],- )- ],- )-- rendered = render_markdown(_middle(_page(0, algorithm)))-- assert 'class="docvortex-algorithm"' in rendered- assert (- "if a < b and c * d:\n <strong>bold</strong> / <em>italic</em> / <s>strike</s> / "- '<u>under</u> / <span style="text-emphasis: dot; text-emphasis-position: under;">dot</span> '- '<sub>q</sub><sup>2</sup> <code>x * y</code> <a href="https://example.com/a b"><strong>link</strong></a> '- "= $a < b$ $c > d$"- ) in rendered- assert "**bold**" not in rendered- assert "*italic*" not in rendered- assert "~~strike~~" not in rendered- assert r"\*" not in rendered---def test_image_path_precedes_base64_and_visual_child_order_is_preserved() -> None:- """验证图片资源优先级、base URL 和视觉子块原始顺序。"""- image = ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "content": [- {"type": "image_caption", "content": _inline("before")},- {- "type": "image_body",- "index": 0,- "content": "description",- "image_path": "images/a b.png",- "image_base64": "data:image/png;base64,AAAA",- },- {"type": "image_footnote", "content": _inline("after")},- ],- }- )-- rendered = render_markdown(_middle(_page(0, image)), asset_base_url="https://cdn.example/doc")-- assert rendered.index("before") < rendered.index("https://cdn.example/doc/images/a%20b.png")- assert rendered.index("description") < rendered.index("after")- assert "data:image" not in rendered---def test_chart_without_image_outputs_existing_gfm_content() -> None:- """验证无图片图表直接输出已有 GFM 内容。"""- chart = ChartBlock(- type="chart",- index=0,- content=[ChartBodyBlock(type="chart_body", index=0, content="| A |\n| --- |\n| 1 |")],- )-- assert render_markdown(_middle(_page(0, chart))) == "| A |\n| --- |\n| 1 |"---def test_chart_without_image_converts_simple_html_table_to_gfm() -> None:- """验证无图片 chart 的简单 HTML table 直接转换为 GFM。"""- chart = ChartBlock(- type="chart",- index=0,- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",- )- ],- )-- assert render_markdown(_middle(_page(0, chart))) == "| A |\n| --- |\n| 1 |"---def test_chart_with_image_places_converted_gfm_in_details() -> None:- """验证有图片 chart 保留图片,并把简单表格 GFM 放入 details。"""- chart = ChartBlock(- type="chart",- index=0,- sub_type="line chart",- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",- image_path="images/chart.png",- )- ],- )-- rendered = render_markdown(_middle(_page(0, chart)))-- assert rendered.startswith("\n\n<details>")- assert "| A |\n| --- |\n| 1 |" in rendered- assert "<table>" not in rendered---def test_chart_complex_html_table_remains_html() -> None:- """验证 chart 的复杂 HTML table 不会被有损转换为 GFM。"""- chart = ChartBlock(- type="chart",- index=0,- content=[- ChartBodyBlock(- type="chart_body",- index=0,- content='<table><tr><td colspan="2">A</td></tr></table>',- )- ],- )-- rendered = render_markdown(_middle(_page(0, chart)))-- assert rendered.startswith("<table>")- assert 'colspan="2"' in rendered---def test_direct_base64_image_fallback() -> None:- """验证未外置图片时 Markdown 直接使用 data URI。"""- image = ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="",- image_base64="data:image/png;base64,AAAA",- )- ],- )-- assert render_markdown(_middle(_page(0, image))) == ""diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.pydeleted file mode 100644index 7cba1cdc..00000000--- a/tests/unittest/test_middle_json_block_models.py+++ /dev/null@@ -1,577 +0,0 @@-from __future__ import annotations-import json-from docvortex.codecs.json import load_middle-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inline--from copy import deepcopy-from typing import get_args--import pytest-from pydantic import ValidationError--import mineru.types as types_module-from docvortex.postprocess.pages import model_json_to_pages-from docvortex.content.inline import inline_plain_text-from docvortex.content.inline import normalize_inline_spans-from mineru.types import (- BLOCK_ADAPTER,- BLOCK_TYPES,- PAGE_BLOCK_TYPES,- RAW_FORMULA_NUMBER,- RAW_ONLY_BLOCK_TYPES,- BlockType,- BlockTypes,- ChartAnnotationBlock,- CodeAnnotationBlock,- CodeBlock,- ContinuableTextBlockBase,- EquationBlock,- ImageAnnotationBlock,- ListBlock,- MiddleJson,- ModelJson,- PageAuxTextBlock,- PageBlockTypes,- PageFootnoteBlock,- PageInfo,- RefTextBlock,- TableAnnotationBlock,- TextBlock,- TextSpan,- parse_block,- parse_inline_spans,-)---def _public_block_payloads() -> dict[str, dict[str, object]]:- """构造 29 个公开 discriminator 的最小合法载荷。"""- text_leaf = {"type": "text", "content": _inline("item")}- payloads: dict[str, dict[str, object]] = {- "aside_text": {"type": "aside_text", "content": _inline("aside")},- "doc_title": {"type": "doc_title", "content": _inline("title"), "level": 1},- "footer": {"type": "footer", "content": _inline("footer")},- "header": {"type": "header", "content": _inline("header")},- "index": {"type": "index", "content": [text_leaf]},- "equation": {"type": "equation", "content": "x=1"},- "list": {"type": "list", "content": [text_leaf]},- "page_footnote": {"type": "page_footnote", "content": _inline("note")},- "page_number": {"type": "page_number", "content": _inline("1")},- "paragraph_title": {"type": "paragraph_title", "content": _inline("section"), "level": 2},- "ref_text": {"type": "ref_text", "content": _inline("reference")},- "text": {"type": "text", "content": _inline("text")},- "image_body": {"type": "image_body", "content": ""},- "image_caption": {"type": "image_caption", "content": _inline("caption")},- "image_footnote": {"type": "image_footnote", "content": _inline("note")},- "table_body": {"type": "table_body", "content": "<table></table>"},- "table_caption": {"type": "table_caption", "content": _inline("caption")},- "table_footnote": {"type": "table_footnote", "content": _inline("note")},- "chart_body": {"type": "chart_body", "content": ""},- "chart_caption": {"type": "chart_caption", "content": _inline("caption")},- "chart_footnote": {"type": "chart_footnote", "content": _inline("note")},- "code_body": {"type": "code_body", "content": "print(1)"},- "algorithm_body": {"type": "algorithm_body", "content": _inline("algorithm")},- "code_caption": {"type": "code_caption", "content": _inline("caption")},- "code_footnote": {"type": "code_footnote", "content": _inline("note")},- }- payloads.update(- {- "image": {"type": "image", "content": [payloads["image_body"]]},- "table": {"type": "table", "content": [payloads["table_body"]]},- "chart": {"type": "chart", "content": [payloads["chart_body"]]},- "code": {- "type": "code",- "content": [payloads["code_body"]],- "sub_type": "code",- "guess_lang": "python",- },- }- )- return payloads---def test_all_29_public_discriminators_parse_to_concrete_models() -> None:- """验证公开类型集合与 discriminated union 完整一致。"""- payloads = _public_block_payloads()-- assert set(payloads) == BLOCK_TYPES- assert len(payloads) == 29- assert "equation" not in RAW_ONLY_BLOCK_TYPES- assert all(parse_block(payload).type == block_type for block_type, payload in payloads.items())- assert isinstance(parse_block(payloads["equation"]), EquationBlock)---def test_public_block_type_declarations_match_block_union() -> None:- """验证 BlockType、BlockTypes 和 BLOCK_TYPES 只公开 Block 联合的 discriminator。"""- class_values = {value for name, value in vars(BlockType).items() if name.isupper()}-- assert class_values == BLOCK_TYPES- assert set(get_args(BlockTypes)) == BLOCK_TYPES- assert set(get_args(PageBlockTypes)) == PAGE_BLOCK_TYPES---def test_shared_models_preserve_all_discriminator_values() -> None:- """验证同结构 discriminator 共用模型,但仍保留原始 type 语义。"""- assert isinstance(parse_block({"type": "header", "content": _inline("h")}), PageAuxTextBlock)- assert isinstance(parse_block({"type": "image_caption", "content": _inline("c")}), ImageAnnotationBlock)- assert isinstance(parse_block({"type": "table_footnote", "content": _inline("f")}), TableAnnotationBlock)- assert isinstance(parse_block({"type": "chart_caption", "content": _inline("c")}), ChartAnnotationBlock)- assert isinstance(parse_block({"type": "code_footnote", "content": _inline("f")}), CodeAnnotationBlock)---def test_inline_span_models_normalize_styles_and_merge_adjacent_text() -> None:- """验证 TextSpan 样式顺序去重、空白保真和相邻同样式合并。"""- spans = normalize_inline_spans(- [- {"type": "text", "content": "A", "styles": ["underline", "bold", "bold"]},- {"type": "text", "content": " \n", "styles": ["bold", "underline"]},- {"type": "text", "content": "B"},- ]- )-- assert spans == [- TextSpan(type="text", content="A \n", styles=["bold", "underline"]),- TextSpan(type="text", content="B"),- ]- assert inline_plain_text(spans) == "A \nB"- with pytest.raises(ValidationError, match="string_too_short"):- parse_inline_spans([{"type": "text", "content": ""}])- with pytest.raises(ValidationError, match="both superscript and subscript"):- parse_inline_spans([{"type": "text", "content": "x", "styles": ["superscript", "subscript"]}])---def test_inline_equation_code_and_hyperlink_are_strict_and_safe() -> None:- """验证非文字 Span 的空值、嵌套链接、危险 URL 和额外字段均被拒绝。"""- valid = parse_inline_spans(- [- {"type": "equation_inline", "content": "x<y"},- {"type": "code_inline", "content": "print(x)"},- {"type": "hyperlink", "url": "#target", "content": _inline("link")},- ]- )- assert inline_plain_text(valid) == "x<yprint(x)link"-- invalid_payloads = [- [{"type": "equation_inline", "content": " "}],- [{"type": "code_inline", "content": ""}],- [{"type": "hyperlink", "url": "", "content": _inline("link")}],- [{"type": "hyperlink", "url": "javascript:alert(1)", "content": _inline("link")}],- [{"type": "hyperlink", "url": "https://example.com", "content": []}],- [- {- "type": "hyperlink",- "url": "https://example.com",- "content": [{"type": "hyperlink", "url": "#nested", "content": _inline("nested")}],- }- ],- [{"type": "text", "content": "x", "unknown": True}],- ]- for payload in invalid_payloads:- with pytest.raises(ValidationError):- parse_inline_spans(payload)---def test_inline_text_preserves_markup_entities_and_unicode_verbatim() -> None:- """验证符号、实体外观、引号、Unicode 和完整标签字面量不被解释。"""- content = 'A&B / 1<2 / 3>2 / & / "quote" / 中文🙂 / <eq>x</eq> / <script>alert(1)</script>'- spans = parse_inline_spans(_inline(content))-- assert inline_plain_text(spans) == content- assert len(spans) == 1 and isinstance(spans[0], TextSpan)---def test_model_json_rejects_legacy_inline_string_with_page_and_block_location() -> None:- """验证 ModelJson 对旧字符串 content 给出页号和块号定位。"""- with pytest.raises(ValidationError, match=r"pages\[0\]\[0\].*type=text"):- ModelJson(- pages=[[{"type": BlockType.TEXT, "content": "legacy string"}]],- page_index_map=[],- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def test_page_footnote_uses_independent_model_and_exclusive_anchor() -> None:- """验证页面脚注使用独立模型,页面辅助块不再接受 anchor。"""- footnote = parse_block(- {- "type": "page_footnote",- "content": _inline("note"),- "anchor": "note-one",- }- )-- assert isinstance(footnote, PageFootnoteBlock)- assert footnote.anchor == "note-one"- assert footnote.to_dict()["anchor"] == "note-one"- for block_type in ("header", "footer", "page_number", "aside_text"):- with pytest.raises(ValidationError, match="Extra inputs are not permitted"):- parse_block({"type": block_type, "content": _inline("aux"), "anchor": "invalid"})---def test_title_levels_follow_global_hierarchy() -> None:- """验证文档标题固定为一级,段落标题严格限制在二至六级。"""- doc_title = parse_block({"type": "doc_title", "content": _inline("doc"), "level": 1})- paragraph_title = parse_block({"type": "paragraph_title", "content": _inline("section"), "level": 2})- deepest_title = parse_block({"type": "paragraph_title", "content": _inline("deep"), "level": 6})-- assert doc_title.to_dict()["level"] == 1- assert paragraph_title.to_dict()["level"] == 2- assert deepest_title.to_dict()["level"] == 6- for payload in (- {"type": "doc_title", "content": _inline("doc")},- {"type": "doc_title", "content": _inline("doc"), "level": 2},- {"type": "paragraph_title", "content": _inline("section")},- {"type": "paragraph_title", "content": _inline("section"), "level": 1},- {"type": "paragraph_title", "content": _inline("section"), "level": 7},- ):- with pytest.raises(ValidationError):- parse_block(payload)--[email protected]("block_type", ["equation", "image_body", "table_body", "chart_body"])-def test_image_payload_content_must_be_string(block_type: str) -> None:- """验证所有图片载荷块在严格 Middle JSON 中都拒绝 null content。"""- with pytest.raises(ValidationError):- parse_block({"type": block_type, "content": None})---def test_cell_merge_belongs_only_to_table_root() -> None:- """验证 cell_merge 只允许位于 table 根块。"""- table_payload = deepcopy(_public_block_payloads()["table"])- table_payload["cell_merge"] = [1, 0]-- table = parse_block(table_payload)-- assert table.cell_merge == [1, 0]- with pytest.raises(ValidationError):- parse_block({"type": "table_body", "content": "<table></table>", "cell_merge": [1, 0]})--[email protected]("raw_type", sorted(RAW_ONLY_BLOCK_TYPES))-def test_raw_only_types_are_rejected(raw_type: str) -> None:- """验证 Analyze 私有 raw type 不能越过公开对象边界。"""- assert raw_type in RAW_ONLY_BLOCK_TYPES- with pytest.raises(ValidationError):- parse_block({"type": raw_type, "content": "raw"})---def test_legacy_interline_equation_discriminator_is_rejected() -> None:- """验证旧 interline_equation 不提供兼容入口,严格对象只接受 equation。"""- with pytest.raises(ValidationError):- parse_block({"type": "interline_equation", "content": "x=1"})---def test_equation_schema_uses_only_canonical_discriminator() -> None:- """验证生成的 JSON Schema 只公开 equation 与 EquationBlock。"""- schema = BLOCK_ADAPTER.json_schema()- mapping = schema["discriminator"]["mapping"]- legacy_model_name = "Interline" + "EquationBlock"-- assert mapping["equation"] == "#/$defs/EquationBlock"- assert "interline_equation" not in mapping- assert "EquationBlock" in schema["$defs"]- assert legacy_model_name not in schema["$defs"]---def test_formula_number_is_rejected_by_middle_json_boundary_and_schema() -> None:- """验证 formula_number 仅属于 Analyze raw 阶段,不能进入公开 Block 或 Middle JSON。"""- schema = BLOCK_ADAPTER.json_schema()- mapping = schema["discriminator"]["mapping"]-- assert RAW_FORMULA_NUMBER in RAW_ONLY_BLOCK_TYPES- assert RAW_FORMULA_NUMBER not in mapping- assert "FormulaNumberBlock" not in schema["$defs"]- with pytest.raises(ValidationError):- parse_block({"type": RAW_FORMULA_NUMBER, "content": "(1)"})- with pytest.raises(ValidationError):- model_json_to_pages(- ModelJson(- pages=[[{"type": RAW_FORMULA_NUMBER, "bbox": [0.7, 0.3, 0.8, 0.4], "content": "(1)"}]],- page_index_map=[],- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )- )---def test_continuable_text_models_share_marker_and_keep_text_anchor_strict() -> None:- """验证 Text 独有 anchor、Text/RefText 续接字段及未知字段校验。"""- text = parse_block({"type": "text", "content": _inline("x"), "continues_prev": True})- anchored_text = parse_block({"type": "text", "content": _inline("x"), "anchor": "a"})- ref_text = parse_block({"type": "ref_text", "content": _inline("r"), "continues_prev": True})-- assert isinstance(text, ContinuableTextBlockBase)- assert isinstance(ref_text, RefTextBlock)- assert isinstance(ref_text, ContinuableTextBlockBase)- assert set(TextBlock.model_fields) == {*RefTextBlock.model_fields, "anchor"}- assert text.continues_prev is True- assert isinstance(anchored_text, TextBlock) and anchored_text.anchor == "a"- assert ref_text.continues_prev is True- with pytest.raises(ValidationError):- parse_block({"type": "ref_text", "content": _inline("r"), "anchor": "a"})- with pytest.raises(ValidationError):- parse_block({"type": "text", "content": _inline("x"), "unknown": 1})---def test_every_public_block_rejects_removed_merge_field() -> None:- """验证已废弃合并字段不会被任一公开 block 静默接收。"""- for payload in _public_block_payloads().values():- invalid_payload = deepcopy(payload)- invalid_payload["merge_prev"] = False- with pytest.raises(ValidationError):- parse_block(invalid_payload)---def test_removed_block_classes_are_not_exposed() -> None:- """验证未采用的旧 block 类没有重新进入公开对象体系。"""- legacy_equation_model_name = "Interline" + "EquationBlock"- removed_names = (- "TitleBlock",- "AsideTextBlock",- "HeaderBlock",- "FooterBlock",- "PageNumberBlock",- "ImageCaptionBlock",- "ImageFootnoteBlock",- "TableCaptionBlock",- "TableFootnoteBlock",- "ChartCaptionBlock",- "ChartFootnoteBlock",- "CodeCaptionBlock",- "CodeFootnoteBlock",- "HeaderImageBlock",- "FooterImageBlock",- legacy_equation_model_name,- "_DocElement",- "Span",- "Line",- "ContentItem",- "EMPTY_BBOX",- "_is_default_value",- "_origin_is_list",- "_list_arg",- )- for removed_name in removed_names:- assert not hasattr(types_module, removed_name)- assert not hasattr(types_module.BlockType, "INTERLINE_" + "EQUATION")--- "bbox",- [(-0.1, 0.1, 0.8, 0.8), (0.1, 0.1, 1.1, 0.8), (0.5, 0.1, 0.5, 0.8), (0.1, 0.8, 0.5, 0.2)],-)-def test_bbox_must_be_normalized_and_positive(bbox: tuple[float, ...]) -> None:- """验证 bbox 必须有限、归一化且具有正面积。"""- with pytest.raises(ValidationError):- parse_block({"type": "text", "content": _inline("x"), "bbox": bbox})---def test_recursive_list_and_index_round_trip() -> None:- """验证四层 List 与递归 Index 的顺序和具体类型可无损恢复。"""- list_payload: dict[str, object] = {"type": "text", "content": _inline("leaf")}- for _ in range(4):- list_payload = {"type": "list", "content": [{"type": "text", "content": _inline("item")}, list_payload]}- index_payload = {- "type": "index",- "content": [- {"type": "text", "content": _inline("one")},- {"type": "index", "content": [{"type": "text", "content": _inline("two")}]},- ],- }-- list_block = parse_block(list_payload)- index_block = parse_block(index_payload)-- assert isinstance(list_block, ListBlock)- assert isinstance(list_block.content[1], ListBlock)- assert [child.content[0].content for child in index_block.content if isinstance(child, TextBlock)] == ["one"]- assert parse_block(list_block.to_dict(skip_defaults=False)) == list_block- assert parse_block(index_block.to_dict(skip_defaults=False)) == index_block---def test_list_subtype_allows_mixed_direct_text_children() -> None:- """验证 List subtype 是子项类型的统计结果,不约束每个直接子项。"""- block = parse_block(- {- "type": "list",- "sub_type": "ref_text",- "content": [- {"type": "text", "content": _inline("x")},- {"type": "ref_text", "content": _inline("r1")},- {"type": "ref_text", "content": _inline("r2")},- {"type": "list", "sub_type": "text", "content": [{"type": "ref_text", "content": _inline("nested")}]},- ],- }- )- assert isinstance(block, ListBlock)- assert block.sub_type == BlockType.REF_TEXT- assert [child.type for child in block.content] == [- BlockType.TEXT,- BlockType.REF_TEXT,- BlockType.REF_TEXT,- BlockType.LIST,- ]- assert isinstance(block.content[3], ListBlock)- assert block.content[3].content[0].type == BlockType.REF_TEXT--[email protected]("visual_type", ["image", "table", "chart", "code"])-def test_visual_parent_requires_exactly_one_body(visual_type: str) -> None:- """验证视觉父块必须且只能包含一个对应 body。"""- payload = deepcopy(_public_block_payloads()[visual_type])- payload["content"] = []- with pytest.raises(ValidationError, match="exactly one"):- parse_block(payload)---def test_visual_parent_body_location_contract() -> None:- """验证视觉 parent/body 的 index 和同时存在的 bbox 必须一致。"""- with pytest.raises(ValidationError, match="index"):- parse_block(- {- "type": "image",- "index": 1,- "content": [{"type": "image_body", "index": 2, "content": ""}],- }- )- with pytest.raises(ValidationError, match="bbox"):- parse_block(- {- "type": "image",- "bbox": [0.1, 0.1, 0.9, 0.9],- "content": [{"type": "image_body", "bbox": [0.2, 0.2, 0.8, 0.8], "content": ""}],- }- )---def test_visual_parent_rejects_other_family_annotation() -> None:- """验证合并 annotation 模型后仍禁止视觉父块接收其他家族子块。"""- with pytest.raises(ValidationError):- parse_block(- {- "type": "image",- "content": [- {"type": "image_body", "content": ""},- {"type": "table_caption", "content": _inline("wrong")},- ],- }- )---def test_code_subtype_controls_guess_language() -> None:- """验证 code 必须有语言,而 algorithm 禁止语言字段。"""- with pytest.raises(ValidationError):- parse_block({"type": "code", "sub_type": "code", "content": [{"type": "code_body", "content": "x"}]})- with pytest.raises(ValidationError):- parse_block(- {- "type": "code",- "sub_type": "algorithm",- "guess_lang": "python",- "content": [{"type": "algorithm_body", "content": _inline("x")}],- }- )- assert isinstance(- parse_block(- {"type": "code", "sub_type": "algorithm", "content": [{"type": "algorithm_body", "content": _inline("x")}]}- ),- CodeBlock,- )---def test_page_info_requires_unique_strictly_increasing_top_indices() -> None:- """验证顶层 index 必填、唯一、严格递增,但允许缺号。"""- page = PageInfo(- page_idx=0,- blocks=[- TextBlock(type="text", index=2, content=_inline("a")),- TextBlock(type="text", index=8, content=_inline("b")),- ],- )- assert [block.index for block in page.blocks] == [2, 8]- with pytest.raises(ValidationError):- PageInfo(page_idx=0, blocks=[TextBlock(type="text", content=_inline("missing"))])- with pytest.raises(ValidationError):- PageInfo(- page_idx=0,- blocks=[- TextBlock(type="text", index=1, content=_inline("a")),- TextBlock(type="text", index=1, content=_inline("b")),- ],- )--[email protected]("block_type", ["image_body", "table_caption", "code_footnote"])-def test_page_info_rejects_visual_child_as_top_level(block_type: str) -> None:- """验证视觉 body/caption/footnote 只能出现在对应父块内部。"""- with pytest.raises(ValidationError):- PageInfo.model_validate(- {- "page_idx": 0,- "blocks": [{"type": block_type, "index": 0, "content": ""}],- }- )---def test_page_info_accepts_all_page_root_discriminators() -> None:- """验证 PAGE_BLOCK_TYPES 中的全部页面根类型都能进入 PageInfo。"""- payloads = _public_block_payloads()- for block_type in PAGE_BLOCK_TYPES:- payload = deepcopy(payloads[block_type])- payload["index"] = 0- content = payload.get("content")- if isinstance(content, list):- for child in content:- if isinstance(child, dict) and str(child.get("type", "")).endswith("_body"):- child["index"] = 0- page = PageInfo.model_validate({"page_idx": 0, "blocks": [payload]})- assert page.blocks[0].type == block_type--[email protected]("child_type", [BlockType.TEXT, BlockType.REF_TEXT])[email protected]("continues_prev", [True, None])-def test_nested_continues_prev_is_rejected_by_page_tree(child_type: str, continues_prev: bool | None) -> None:- """验证 continues_prev 只能出现在页面顶层 text/ref_text/list/table。"""- with pytest.raises(ValidationError, match="nested"):- PageInfo.model_validate(- {- "page_idx": 0,- "blocks": [- {- "type": "list",- "index": 0,- "content": [{"type": child_type, "content": _inline("x"), "continues_prev": continues_prev}],- }- ],- }- )---def test_middle_json_pdf_requires_top_level_bbox_and_round_trips() -> None:- """验证 PDF 顶层 bbox 约束及 MiddleJson JSON 往返。"""- with pytest.raises(ValidationError, match="requires bbox"):- MiddleJson(- pages=[PageInfo(page_idx=0, blocks=[TextBlock(type="text", index=0, content=_inline("x"))])],- is_full_document=True,- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )- middle_json = MiddleJson(- pages=[- PageInfo(- page_idx=0,- blocks=[TextBlock(type="text", index=0, bbox=(0.1, 0.1, 0.9, 0.9), content=_inline("x"))],- )- ],- is_full_document=True,- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )- restored = load_middle(json.loads(middle_json.to_json()))- assert restored == middle_jsondiff --git a/tests/unittest/test_middle_json_export.py b/tests/unittest/test_middle_json_export.pydeleted file mode 100644index 6cabd61e..00000000--- a/tests/unittest/test_middle_json_export.py+++ /dev/null@@ -1,359 +0,0 @@-from __future__ import annotations-import json-from docvortex.codecs.json import load_middle-from docvortex.export.middle import export_middle_json-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata--import base64-import os-from pathlib import Path--import pytest--from mineru.types import EquationBlock, MiddleJson, PageInfo, TableBlock, TableBodyBlock---def _data_uri(mime_subtype: str, payload: bytes) -> str:- """把测试图片字节编码为 data URI。"""- return f"data:image/{mime_subtype};base64,{base64.b64encode(payload).decode('ascii')}"---def _middle_json_with_table(body: TableBodyBlock) -> MiddleJson:- """构造只包含一个表格载体的最小 Office MiddleJson。"""- table = TableBlock(type="table", index=body.index, content=[body])- return MiddleJson(- pages=[PageInfo(page_idx=3, blocks=[table])],- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def test_full_serialization_round_trip_and_recursive_field_exclusion() -> None:- """验证完整 dump 保留图片,而递归排除不遗漏 visual 子块。"""- jpeg_uri = _data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9")- middle_json = _middle_json_with_table(- TableBodyBlock(type="table_body", index=0, content="<table></table>", image_base64=jpeg_uri)- )-- full_json = middle_json.to_json(indent=None)- excluded = middle_json.to_dict(exclude_block_fields={"image_base64"})-- assert jpeg_uri in full_json- assert load_middle(json.loads(full_json)) == middle_json- assert "image_base64" not in excluded["pages"][0]["blocks"][0]["content"][0]---def test_equation_export_uses_canonical_sidecar_name(tmp_path: Path) -> None:- """验证行间公式图片使用 equation discriminator 生成确定性 sidecar 名称。"""- jpeg_payload = b"\xff\xd8\xffequation\xff\xd9"- equation = EquationBlock(- type="equation",- index=6,- content="x+1",- image_base64=_data_uri("jpeg", jpeg_payload),- )- middle_json = MiddleJson(- pages=[PageInfo(page_idx=3, blocks=[equation])],- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )-- result = export_middle_json(middle_json, tmp_path)- exported_equation = result.middle_json.pages[0].blocks[0]-- assert [path.name for path in result.image_paths] == ["page_3_equation_6.jpg"]- assert (tmp_path / "images/page_3_equation_6.jpg").read_bytes() == jpeg_payload- assert exported_equation.image_path == "images/page_3_equation_6.jpg"- assert exported_equation.image_base64 is None- assert equation.image_base64 is not None---def test_export_writes_direct_and_multiple_html_images_without_mutating_source(tmp_path: Path) -> None:- """验证直接图片与 HTML 多图采用确定性命名,导出副本不污染原对象。"""- jpeg_payload = b"\xff\xd8\xffjpeg\xff\xd9"- gif_payload = b"GIF89agif"- png_payload = b"\x89PNG\r\n\x1a\npng"- jpeg_uri = _data_uri("jpeg", jpeg_payload)- gif_uri = _data_uri("gif", gif_payload)- png_uri = _data_uri("png", png_payload)- html = f'<table><img src="{gif_uri}"><img src="{png_uri}"></table>'- middle_json = _middle_json_with_table(TableBodyBlock(type="table_body", index=4, content=html, image_base64=jpeg_uri))-- result = export_middle_json(middle_json, tmp_path)- exported_json = result.json_path.read_text()- exported_body = result.middle_json.pages[0].blocks[0].content[0]-- assert {path.name for path in result.image_paths} == {- "page_3_table_body_4.jpg",- "page_3_table_body_4_1.gif",- "page_3_table_body_4_2.png",- }- assert (tmp_path / "images/page_3_table_body_4.jpg").read_bytes() == jpeg_payload- assert (tmp_path / "images/page_3_table_body_4_1.gif").read_bytes() == gif_payload- assert (tmp_path / "images/page_3_table_body_4_2.png").read_bytes() == png_payload- assert exported_body.image_path == "images/page_3_table_body_4.jpg"- assert exported_body.image_base64 is None- assert "images/page_3_table_body_4_1.gif" in exported_body.content- assert "images/page_3_table_body_4_2.png" in exported_body.content- assert "image_base64" not in exported_json- assert "data:image/" not in exported_json- assert middle_json.pages[0].blocks[0].content[0].image_base64 == jpeg_uri- assert "data:image/" in middle_json.pages[0].blocks[0].content[0].content---def test_export_supports_strict_svg_payload(tmp_path: Path) -> None:- """验证 PPTX 可能产出的 SVG data URI 可按 XML 根元素严格校验并外置。"""- svg_payload = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>'- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=2,- content="<table></table>",- image_base64=_data_uri("svg+xml", svg_payload),- )- )-- result = export_middle_json(middle_json, tmp_path)-- assert (tmp_path / "images/page_3_table_body_2.svg").read_bytes() == svg_payload- assert result.middle_json.pages[0].blocks[0].content[0].image_path.endswith(".svg")---def test_export_supports_direct_png_and_html_jpeg(tmp_path: Path) -> None:- """验证直接 PNG 与 Office 表格 HTML 内嵌 JPEG 都能按各自格式外置。"""- png_payload = b"\x89PNG\r\n\x1a\npng"- jpeg_payload = b"\xff\xd8\xffjpeg\xff\xd9"- jpeg_uri = _data_uri("jpeg", jpeg_payload)- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=5,- content=f'<table><img src="{jpeg_uri}"></table>',- image_base64=_data_uri("png", png_payload),- )- )-- result = export_middle_json(middle_json, tmp_path)-- assert (tmp_path / "images/page_3_table_body_5.png").read_bytes() == png_payload- assert (tmp_path / "images/page_3_table_body_5_1.jpg").read_bytes() == jpeg_payload- assert "images/page_3_table_body_5_1.jpg" in result.middle_json.pages[0].blocks[0].content[0].content--- "data_uri",- [- "data:image/jpeg;base64,not-base64!",- _data_uri("png", b"\xff\xd8\xffwrong-mime\xff\xd9"),- _data_uri("avif", b"unsupported-format"),- _data_uri("svg+xml", b"<html></html>"),- ],-)-def test_export_rejects_invalid_payload_before_writing(tmp_path: Path, data_uri: str) -> None:- """验证非法 base64、MIME 签名不符和不支持格式均不会产生半成品。"""- output_dir = tmp_path / "output"- middle_json = _middle_json_with_table(- TableBodyBlock(type="table_body", index=0, content="<table></table>", image_base64=data_uri)- )-- with pytest.raises(ValueError):- export_middle_json(middle_json, output_dir)-- assert not output_dir.exists()---def test_export_rejects_unparsed_inline_data_uri_before_writing(tmp_path: Path) -> None:- """验证不符合 base64 data URI 语法的 HTML 图片不会原样泄漏到导出 JSON。"""- output_dir = tmp_path / "output"- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content='<table><img src="data:image/jpeg,raw-payload"></table>',- )- )-- with pytest.raises(ValueError, match="inline image data URI"):- export_middle_json(middle_json, output_dir)-- assert not output_dir.exists()---def test_export_preflights_conflicts_and_supports_explicit_overwrite(tmp_path: Path) -> None:- """验证同名同内容可复用、不同内容默认报错且 overwrite 可替换。"""- first_payload = b"\xff\xd8\xfffirst\xff\xd9"- second_payload = b"\xff\xd8\xffsecond\xff\xd9"- first = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_base64=_data_uri("jpeg", first_payload),- )- )- second = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_base64=_data_uri("jpeg", second_payload),- )- )-- export_middle_json(first, tmp_path)- export_middle_json(first, tmp_path)- image_path = tmp_path / "images/page_3_table_body_0.jpg"- with pytest.raises(FileExistsError):- export_middle_json(second, tmp_path)- assert image_path.read_bytes() == first_payload-- export_middle_json(second, tmp_path, overwrite=True)- assert image_path.read_bytes() == second_payload---def test_export_conflicting_json_rolls_back_before_any_image_write(tmp_path: Path) -> None:- """验证 JSON 冲突在提交前被发现,不会先留下图片 sidecar。"""- (tmp_path / "middle_json.json").write_text("occupied")- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=9,- content="<table></table>",- image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),- )- )-- with pytest.raises(FileExistsError):- export_middle_json(middle_json, tmp_path)-- assert not (tmp_path / "images/page_3_table_body_9.jpg").exists()- assert (tmp_path / "middle_json.json").read_text() == "occupied"---def test_export_restores_existing_files_after_commit_failure(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证提交中途失败时会恢复已覆盖文件,并清理全部临时文件。"""- image_path = tmp_path / "images/page_3_table_body_0.jpg"- image_path.parent.mkdir()- image_path.write_bytes(b"old-image")- json_path = tmp_path / "middle_json.json"- json_path.write_bytes(b"old-json")- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_base64=_data_uri("jpeg", b"\xff\xd8\xffnew-image\xff\xd9"),- )- )- original_replace = os.replace- replace_count = 0-- def fail_second_replace(source: str | Path, target: str | Path) -> None:- """模拟第二个文件提交失败,以覆盖事务回滚分支。"""- nonlocal replace_count- replace_count += 1- if replace_count == 2:- raise OSError("simulated commit failure")- original_replace(source, target)-- monkeypatch.setattr("docvortex.export.middle.os.replace", fail_second_replace)-- with pytest.raises(OSError, match="simulated commit failure"):- export_middle_json(middle_json, tmp_path, overwrite=True)-- assert image_path.read_bytes() == b"old-image"- assert json_path.read_bytes() == b"old-json"- assert not list(tmp_path.rglob(".docvortex-export-*"))--[email protected]("json_name", ["../middle.json", "/tmp/middle.json", "..\\middle.json"])-def test_export_rejects_path_escape(tmp_path: Path, json_name: str) -> None:- """验证 JSON 输出名不能使用绝对路径或逃逸文档目录。"""- middle_json = _middle_json_with_table(TableBodyBlock(type="table_body", index=0, content="<table></table>"))- with pytest.raises(ValueError):- export_middle_json(middle_json, tmp_path, json_name=json_name)---def test_export_rejects_file_and_directory_path_collision(tmp_path: Path) -> None:- """验证 JSON 文件名不能占用图片 sidecar 所需的 images 目录。"""- output_dir = tmp_path / "output"- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),- )- )-- with pytest.raises(ValueError, match="required directory"):- export_middle_json(middle_json, output_dir, json_name="images")-- assert not output_dir.exists()---def test_export_rejects_symlink_output_directory(tmp_path: Path) -> None:- """验证导出根目录是符号链接时直接拒绝写入。"""- actual_dir = tmp_path / "actual"- actual_dir.mkdir()- link_dir = tmp_path / "link"- os.symlink(actual_dir, link_dir)- middle_json = _middle_json_with_table(TableBodyBlock(type="table_body", index=0, content="<table></table>"))-- with pytest.raises(ValueError, match="symlink"):- export_middle_json(middle_json, link_dir)-- assert list(actual_dir.iterdir()) == []---def test_export_rejects_symlink_sidecar_directory(tmp_path: Path) -> None:- """验证图片子目录是符号链接时不会跟随链接写到文档目录之外。"""- outside_dir = tmp_path / "outside"- outside_dir.mkdir()- output_dir = tmp_path / "output"- output_dir.mkdir()- os.symlink(outside_dir, output_dir / "images")- middle_json = _middle_json_with_table(- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),- )- )-- with pytest.raises(ValueError, match="symlink"):- export_middle_json(middle_json, output_dir)-- assert list(outside_dir.iterdir()) == []---def test_image_path_is_validated_during_deserialization() -> None:- """验证对象边界拒绝绝对路径、目录逃逸和 Windows 反斜杠路径。"""- for image_path in ("/tmp/image.jpg", "../image.jpg", "images\\image.jpg"):- with pytest.raises(ValueError):- TableBodyBlock(- type="table_body",- index=0,- content="<table></table>",- image_path=image_path,- )---def test_exported_json_is_a_pure_middle_json_object(tmp_path: Path) -> None:- """验证导出 JSON 可独立严格反序列化且不依赖导出结果包装对象。"""- middle_json = _middle_json_with_table(TableBodyBlock(type="table_body", index=0, content="<table></table>"))- result = export_middle_json(middle_json, tmp_path)-- payload = json.loads(result.json_path.read_text())- restored = load_middle(payload)-- assert restored == result.middle_jsondiff --git a/tests/unittest/test_middle_json_validator.py b/tests/unittest/test_middle_json_validator.pyindex daffa6e3..e289a03f 100644--- a/tests/unittest/test_middle_json_validator.py+++ b/tests/unittest/test_middle_json_validator.py@@ -1,536 +1,5 @@-from _span_test_utils import inline as _inline-from dataclasses import dataclass-from typing import Literal-from mineru.parser import MIDDLE_JSON_SCHEMA_VERSION-from mineru.types import (- BLOCK_TYPES,- BlockBase,- BlockType,- ImageAnnotationBlock,- ImageBlock,- ImageBodyBlock,- InlineContentBlock,- PageInfo,- ParagraphTitleBlock,- TextBlock,-)--IssueSeverity = Literal["error", "warning"]--KNOWN_BLOCK_TYPES = BLOCK_TYPES-STRING_CONTENT_BLOCK_TYPES = {- BlockType.EQUATION,- BlockType.TABLE_BODY,- BlockType.CODE_BODY,- BlockType.IMAGE_BODY,- BlockType.CHART_BODY,-}-VISUAL_PARENT_TYPES = {- BlockType.IMAGE,- BlockType.TABLE,- BlockType.CHART,- BlockType.CODE,-}-VISUAL_BODY_TYPE_BY_PARENT = {- BlockType.IMAGE: BlockType.IMAGE_BODY,- BlockType.TABLE: BlockType.TABLE_BODY,- BlockType.CHART: BlockType.CHART_BODY,- BlockType.CODE: BlockType.CODE_BODY,-}-CONTAINER_BLOCK_TYPES = {- BlockType.IMAGE,- BlockType.TABLE,- BlockType.CHART,- BlockType.CODE,- BlockType.LIST,- BlockType.INDEX,-}---@dataclass(frozen=True)-class ValidationIssue:- severity: IssueSeverity- code: str- path: str- message: str---def validate_pages(pages: list[PageInfo]) -> list[ValidationIssue]:- issues: list[ValidationIssue] = []- if not isinstance(pages, list):- return [- ValidationIssue(- severity="error",- code="pages_invalid",- path="pages",- message="pages must be a list.",- )- ]-- for page_index, page in enumerate(pages):- page_path = f"pages[{page_index}]"- if not isinstance(page, PageInfo):- issues.append(_invalid_type(page_path, "PageInfo"))- continue-- if not _has_field(page, "page_idx"):- issues.append(_missing(f"{page_path}.page_idx"))- elif not _is_int(page.page_idx):- issues.append(_invalid_type(f"{page_path}.page_idx", "int"))- elif page.page_idx < 0:- issues.append(_invalid_value(f"{page_path}.page_idx", "page_idx must be non-negative."))-- if not _has_field(page, "blocks"):- issues.append(_missing(f"{page_path}.blocks"))- continue- if not isinstance(page.blocks, list):- issues.append(_invalid_type(f"{page_path}.blocks", "list"))- continue-- _validate_block_list(page.blocks, f"{page_path}.blocks", issues)- return issues---def _validate_block_list(- blocks: list[object],- path: str,- issues: list[ValidationIssue],-) -> None:- seen_indexes: set[int] = set()- previous_index: int | None = None- for block_index, block in enumerate(blocks):- block_path = f"{path}[{block_index}]"- if not isinstance(block, BlockBase):- issues.append(_invalid_type(block_path, "BlockBase"))- continue-- if _has_field(block, "index") and block.index is not None and _is_int(block.index):- if block.index in seen_indexes:- issues.append(- ValidationIssue(- severity="error",- code="block_index_duplicate",- path=f"{block_path}.index",- message=f"block index {block.index} is duplicated within {path}.",- )- )- seen_indexes.add(block.index)- if previous_index is not None and block.index < previous_index:- issues.append(- ValidationIssue(- severity="warning",- code="block_index_out_of_order",- path=f"{block_path}.index",- message="block indexes should be sorted in ascending order.",- )- )- previous_index = block.index-- _validate_block(block, block_path, issues)---def _validate_block(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:- block_type = getattr(block, "type", None)- if not _has_field(block, "type"):- issues.append(_missing(f"{path}.type"))- elif not isinstance(block_type, str):- issues.append(_invalid_type(f"{path}.type", "str"))- elif block_type not in KNOWN_BLOCK_TYPES:- issues.append(- ValidationIssue(- severity="error",- code="block_type_unknown",- path=f"{path}.type",- message=f"unknown block type: {block_type}",- )- )- elif block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:- _validate_title_level(block, f"{path}.level", issues)-- if _has_field(block, "index") and block.index is not None and not _is_int(block.index):- issues.append(_invalid_type(f"{path}.index", "int"))- elif _has_field(block, "index") and block.index is not None and block.index < 0:- issues.append(_invalid_value(f"{path}.index", "block index must be non-negative."))-- if _has_field(block, "bbox") and block.bbox is not None:- _validate_bbox(block.bbox, f"{path}.bbox", issues)-- if isinstance(block, InlineContentBlock):- _validate_inline_content(block, f"{path}.content", issues)- elif block_type in STRING_CONTENT_BLOCK_TYPES:- _validate_string_content(block, f"{path}.content", issues)-- if block_type in VISUAL_PARENT_TYPES:- _validate_visual_block_children(block, f"{path}.content", issues)-- if block_type in CONTAINER_BLOCK_TYPES:- content = getattr(block, "content", None)- if isinstance(content, list):- _validate_block_list(content, f"{path}.content", issues)---def _validate_string_content(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:- content = getattr(block, "content", None)- block_type = getattr(block, "type", None)- if content is None:- issues.append(_missing(path))- return- if not isinstance(content, str):- issues.append(_invalid_type(path, "str"))- return- if not content and block_type == BlockType.CODE_BODY:- issues.append(- ValidationIssue(- severity="warning",- code="block_content_missing",- path=path,- message=f"{block_type} block should provide content.",- )- )---def _validate_inline_content(block: InlineContentBlock, path: str, issues: list[ValidationIssue]) -> None:- """验证行内内容是非空 Span 列表。"""- content = getattr(block, "content", None)- if not isinstance(content, list):- issues.append(_invalid_type(path, "list[InlineSpan]"))- return- if not content:- issues.append(- ValidationIssue(- severity="warning",- code="block_content_missing",- path=path,- message=f"{block.type} block should provide content.",- )- )---def _validate_visual_block_children(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:- """Validate visual parent block has exactly one body, and body index equals parent index."""- content = getattr(block, "content", None)- block_type = getattr(block, "type", None)- if not isinstance(content, list):- issues.append(_invalid_type(path, "list"))- return-- body_type = VISUAL_BODY_TYPE_BY_PARENT.get(block_type)- if body_type is None:- return-- bodies = [child for child in content if isinstance(child, BlockBase) and getattr(child, "type", None) == body_type]- if len(bodies) != 1:- issues.append(- ValidationIssue(- severity="error",- code="visual_block_body_count",- path=path,- message=f"{block_type} must contain exactly one {body_type}.",- )- )- return-- body = bodies[0]- if block.index is not None and body.index is not None and block.index != body.index:- issues.append(- ValidationIssue(- severity="error",- code="visual_block_body_index_mismatch",- path=f"{path}[body].index",- message=f"{block_type} body index must equal parent index.",- )- )---def _validate_bbox(- bbox: object,- path: str,- issues: list[ValidationIssue],-) -> None:- if not _is_bbox(bbox):- issues.append(- ValidationIssue(- severity="error",- code="bbox_invalid",- path=path,- message="bbox must contain four numeric coordinates.",- )- )- return-- x0, y0, x1, y1 = (float(v) for v in bbox)- if x1 <= x0 or y1 <= y0:- issues.append(- ValidationIssue(- severity="error",- code="bbox_invalid",- path=path,- message="bbox coordinates must satisfy x1 > x0 and y1 > y0.",- )- )- return- if not all(0.0 <= v <= 1.0 for v in (x0, y0, x1, y1)):- issues.append(- ValidationIssue(- severity="warning",- code="bbox_out_of_bounds",- path=path,- message="bbox values should be normalized to [0, 1].",- )- )---def _validate_title_level(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:- level = getattr(block, "level", None)- if level is None:- issues.append(- ValidationIssue(- severity="warning",- code="title_level_missing",- path=path,- message="title block should provide a positive integer level.",- )- )- return- if not _is_int(level) or level < 1:- issues.append(- ValidationIssue(- severity="error",- code="title_level_invalid",- path=path,- message="title level must be a positive integer.",- )- )---def _is_bbox(bbox: object) -> bool:- return (- isinstance(bbox, tuple | list)- and len(bbox) == 4- and all(isinstance(v, int | float) and not isinstance(v, bool) for v in bbox)- )---def _is_int(value: object) -> bool:- return isinstance(value, int) and not isinstance(value, bool)---def _has_field(obj: object, name: str) -> bool:- return hasattr(obj, name)---def _missing(path: str) -> ValidationIssue:- return ValidationIssue(- severity="error",- code="missing_required_field",- path=path,- message=f"{path} is required.",- )---def _invalid_type(path: str, expected: str) -> ValidationIssue:- return ValidationIssue(- severity="error",- code="invalid_type",- path=path,- message=f"{path} must be {expected}.",- )---def _invalid_value(path: str, message: str) -> ValidationIssue:- return ValidationIssue(- severity="error",- code="invalid_value",- path=path,- message=message,- )---def _issue_keys(issues):- return {(issue.severity, issue.code, issue.path) for issue in issues}---def _valid_page() -> PageInfo:- return PageInfo(- page_idx=0,- blocks=[- TextBlock(type=BlockType.TEXT, index=0, bbox=(0.1, 0.1, 0.2, 0.2), content=_inline("hello")),- ],- )def test_middle_json_schema_version_is_public_constant() -> None:assert MIDDLE_JSON_SCHEMA_VERSION == "2.0"---def test_validate_pages_accepts_valid_page_tree() -> None:- assert validate_pages([_valid_page()]) == []---def test_validate_pages_reports_missing_required_page_and_block_fields() -> None:- page = _valid_page()- page_no_idx = PageInfo.model_construct(blocks=page.blocks)- block_no_type = TextBlock.model_construct(index=0, content="hello", bbox=(0.1, 0.1, 0.2, 0.2))- page_no_type = PageInfo.model_construct(page_idx=0, blocks=[block_no_type])-- issues = validate_pages([page_no_idx, page_no_type])-- assert ("error", "missing_required_field", "pages[0].page_idx") in _issue_keys(issues)- assert ("error", "missing_required_field", "pages[1].blocks[0].type") in _issue_keys(issues)---def test_validate_pages_distinguishes_unknown_and_invalid_bbox() -> None:- """验证 bbox 坐标 x1 <= x0 或 y1 <= y0 时报 error。"""- invalid_bbox_block = TextBlock.model_construct(- type=BlockType.TEXT,- index=0,- content="hello",- bbox=(0.5, 0.1, 0.2, 0.2), # x1 < x0- )- page = PageInfo.model_construct(page_idx=0, blocks=[invalid_bbox_block])-- issues = validate_pages([page])-- assert ("error", "bbox_invalid", "pages[0].blocks[0].bbox") in _issue_keys(issues)---def test_validate_pages_reports_bbox_out_of_bounds() -> None:- """验证 bbox 值超出 [0, 1] 范围时报 warning。"""- out_of_bounds_block = TextBlock.model_construct(- type=BlockType.TEXT,- index=0,- content="hello",- bbox=(0.1, 0.1, 1.5, 0.2), # x1 > 1.0- )- page = PageInfo.model_construct(page_idx=0, blocks=[out_of_bounds_block])-- issues = validate_pages([page])-- assert ("warning", "bbox_out_of_bounds", "pages[0].blocks[0].bbox") in _issue_keys(issues)---def test_validate_pages_recurses_into_child_blocks() -> None:- """验证 visual parent block 的 content 子块也会被递归校验。"""- image_block = ImageBlock(- type=BlockType.IMAGE,- index=0,- bbox=(0.0, 0.0, 0.5, 0.5),- content=[- ImageBodyBlock(- type=BlockType.IMAGE_BODY,- index=0,- bbox=(0.0, 0.0, 0.5, 0.5),- content="",- ),- ],- )- page = PageInfo(page_idx=0, blocks=[image_block])-- issues = validate_pages([page])-- # image_body 允许空 content,不应产生 content 警告- assert ("warning", "block_content_missing", "pages[0].blocks[0].content[0].content") not in _issue_keys(issues)---def test_validate_pages_reports_wrong_node_types() -> None:- page = _valid_page()- page.blocks.append(object()) # type: ignore[arg-type]-- issues = validate_pages([object(), page]) # type: ignore[list-item]-- assert ("error", "invalid_type", "pages[0]") in _issue_keys(issues)- assert ("error", "invalid_type", "pages[1].blocks[1]") in _issue_keys(issues)---def test_validate_pages_reports_unknown_block_type_and_bad_title_level() -> None:- bad_type_block = TextBlock.model_construct(type="unknown_type", index=0, content="hello", bbox=(0.1, 0.1, 0.2, 0.2))- bad_level_block = ParagraphTitleBlock.model_construct(- type=BlockType.PARAGRAPH_TITLE,- index=1,- content="section",- bbox=(0.1, 0.1, 0.2, 0.2),- level=0,- )- page = PageInfo.model_construct(page_idx=0, blocks=[bad_type_block, bad_level_block])-- issues = validate_pages([page])-- assert ("error", "block_type_unknown", "pages[0].blocks[0].type") in _issue_keys(issues)- assert ("error", "title_level_invalid", "pages[0].blocks[1].level") in _issue_keys(issues)---def test_validate_pages_reports_block_index_order_and_duplicates() -> None:- """验证 block index 乱序和重复会被报告。-- PageInfo 顶层 index 在构造时已强制 unique+ascending,这里用 model_construct 绕过- Pydantic 校验来测试 validator 自身的检测能力。- """- page = PageInfo.model_construct(- page_idx=0,- blocks=[- TextBlock(type=BlockType.TEXT, index=2, bbox=(0.1, 0.1, 0.2, 0.2), content=_inline("a")),- TextBlock(type=BlockType.TEXT, index=1, bbox=(0.1, 0.1, 0.2, 0.2), content=_inline("b")),- TextBlock(type=BlockType.TEXT, index=1, bbox=(0.1, 0.1, 0.2, 0.2), content=_inline("c")),- ],- )-- issues = validate_pages([page])-- assert ("warning", "block_index_out_of_order", "pages[0].blocks[1].index") in _issue_keys(issues)- assert ("error", "block_index_duplicate", "pages[0].blocks[2].index") in _issue_keys(issues)---def test_validate_pages_reports_inline_content_contracts() -> None:- """验证 Span 内容 block 的空 content 会触发 warning。"""- empty_text = TextBlock.model_construct(type=BlockType.TEXT, index=0, content=[], bbox=(0.1, 0.1, 0.2, 0.2))- page = PageInfo(page_idx=0, blocks=[empty_text])-- issues = validate_pages([page])-- assert ("warning", "block_content_missing", "pages[0].blocks[0].content") in _issue_keys(issues)---def test_validate_pages_reports_visual_block_body_count_mismatch() -> None:- """验证视觉父块必须有且仅有一个 body。-- ImageBlock 构造时已强制 exactly-one-body,用 model_construct 绕过以测试 validator。- """- image_block = ImageBlock.model_construct(- type=BlockType.IMAGE,- index=0,- bbox=(0.0, 0.0, 0.5, 0.5),- content=[- ImageAnnotationBlock.model_construct(- type=BlockType.IMAGE_CAPTION,- index=1,- content=_inline("caption"),- bbox=(0.0, 0.0, 0.5, 0.5),- ),- ],- )- page = PageInfo.model_construct(page_idx=0, blocks=[image_block])-- issues = validate_pages([page])-- assert ("error", "visual_block_body_count", "pages[0].blocks[0].content") in _issue_keys(issues)---def test_validate_pages_reports_visual_block_body_index_mismatch() -> None:- """验证视觉父块 body index 必须等于 parent index。-- ImageBlock 构造时已强制 body index == parent index,用 model_construct 绕过以测试 validator。- """- image_block = ImageBlock.model_construct(- type=BlockType.IMAGE,- index=0,- bbox=(0.0, 0.0, 0.5, 0.5),- content=[- ImageBodyBlock.model_construct(type=BlockType.IMAGE_BODY, index=5, content="", bbox=(0.0, 0.0, 0.5, 0.5)),- ],- )- page = PageInfo.model_construct(page_idx=0, blocks=[image_block])-- issues = validate_pages([page])-- assert ("error", "visual_block_body_index_mismatch", "pages[0].blocks[0].content[body].index") in _issue_keys(issues)diff --git a/tests/unittest/test_model_json.py b/tests/unittest/test_model_json.pyindex c2f6fa01..19d0685a 100644--- a/tests/unittest/test_model_json.py+++ b/tests/unittest/test_model_json.py@@ -1,21 +1,26 @@from __future__ import annotations+import json-from docvortex.codecs.json import load_middle, load_model-from docvortex.schema import Producer-from mineru.integrations.docvortex import from_mineru_model, from_mineru_middle, to_mineru_model, to_mineru_middle-from mineru.integrations.docvortex import build_metadataimport pytest+from _span_test_utils import inline+from docvortex.codecs.json import load_middle, load_model+from docvortex.schema import Producerfrom pydantic import ValidationErrorfrom mineru import ModelJson as PublicModelJsonfrom mineru.backend.postprocess import documentfrom mineru.backend.postprocess.document import model_json_to_middle_jsonfrom mineru.config import LLMAidedConfig+from mineru.integrations.docvortex import (+ build_metadata,+ from_mineru_middle,+ from_mineru_model,+ to_mineru_middle,+ to_mineru_model,+)from mineru.types import MiddleJson, ModelJson-from _span_test_utils import inline-def _model_json(*,@@ -62,54 +67,6 @@ def test_model_json_is_public_and_serializes_exact_envelope() -> None:assert load_model(json.loads(model_json.to_json())) == model_json-def test_non_empty_page_index_map_represents_partial_input() -> None:- """验证非空页号映射表示显式抽页并与 raw pages 一一对应。"""- model_json = _model_json(pages=[[], []], page_index_map=[3, 5])-- assert model_json.page_index_map == [3, 5]- assert model_json.is_full_document is False- assert model_json.resolved_page_indices == [3, 5]---def test_empty_model_json_resolves_to_no_page_indices() -> None:- """验证空文档仍属于整本解析且不会产生虚构页号。"""- model_json = _model_json(pages=[])-- assert model_json.is_full_document is True- assert model_json.resolved_page_indices == []--- ("page_index_map", "message"),- [- ([0], "length mismatch"),- ([0, 0], "unique"),- ([1, 0], "increasing"),- ([0, -1], "non-negative"),- ],-)-def test_model_json_rejects_invalid_page_index_map(page_index_map: list[int], message: str) -> None:- """验证显式抽页映射不允许截断、重复、逆序或负数。"""- with pytest.raises(ValidationError, match=message):- _model_json(pages=[[], []], page_index_map=page_index_map)--- "pages",- ["[]", [{}], [[[]]]],-)-def test_model_json_rejects_invalid_page_structure(pages: object) -> None:- """验证 pages 必须保持页列表、块列表和块字典三层结构。"""- with pytest.raises(ValidationError):- ModelJson(- pages=pages,- page_index_map=[],- file_suffix="pdf",- producer=Producer(name="mineru", version="3.4.0"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="3.4.0"),- )--def test_model_json_requires_page_index_map_and_forbids_extra_fields() -> None:"""验证页映射不可省略且 ModelJson 顶层不接受未声明字段。"""payload = {diff --git a/tests/unittest/test_native_pdf_table.py b/tests/unittest/test_native_pdf_table.pydeleted file mode 100644index 04dcd0fe..00000000--- a/tests/unittest/test_native_pdf_table.py+++ /dev/null@@ -1,2179 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""验证 Native PDF 表格结构恢复的网格、文本和候选仲裁。"""--from __future__ import annotations--from collections.abc import Iterable-from io import BytesIO--import pytest-from reportlab.pdfgen.canvas import Canvas--from docvortex.analyzers.native.pdf.table_recovery import NativeTableCell-from docvortex.analyzers.native.pdf.table_recovery import NativeTableInput-from docvortex.analyzers.native.pdf.table_recovery import NativeTableRectangle-from docvortex.analyzers.native.pdf.table_recovery import NativeTableRule-from docvortex.analyzers.native.pdf.table_recovery import coerce_native_table_rectangles-from docvortex.analyzers.native.pdf.table_recovery import coerce_native_table_rules-from docvortex.analyzers.native.pdf.table_recovery import recover_native_pdf_table-from docvortex.analyzers.native.pdf.table_recovery.candidate import GridCellSpec-from docvortex.analyzers.native.pdf.table_recovery.candidate import build_candidate-from docvortex.analyzers.native.pdf.table_recovery.contracts import NativeTableCandidate-from docvortex.analyzers.native.pdf.table_recovery.contracts import NativeTableGlyph-from docvortex.analyzers.native.pdf.table_recovery.engine import _remove_undercounted_vector_candidates-from docvortex.analyzers.native.pdf.table_recovery.engine import _select_candidate-from docvortex.analyzers.native.pdf.table_recovery.engine import diagnose_native_pdf_table-from docvortex.analyzers.native.pdf.table_recovery.text import build_cell_text-from docvortex.analyzers.native.pdf.table_recovery.text import build_cell_text_parts-from docvortex.analyzers.native.pdf.table_recovery.text import build_native_table_text-from docvortex.analyzers.native.pdf.table_recovery.vector import MAX_PRIMITIVES_PER_TABLE-from docvortex.analyzers.native.pdf.table_recovery.vector import build_vector_candidates-from docvortex.document.pdf.document import PDFDocument---def _char_items(- entries: Iterable[tuple[str, tuple[float, float, float, float]]],-) -> tuple[dict[str, object], ...]:- """把文本框拆成带稳定 char_idx 的逐字符测试输入。"""-- rebuilt: list[dict[str, object]] = []- for text, bbox in entries:- left, top, right, bottom = bbox- char_width = (right - left) / max(1, len(text))- for offset, char in enumerate(text):- rebuilt.append(- {- "char": char,- "bbox": (- left + char_width * offset,- top,- left + char_width * (offset + 1),- bottom,- ),- "char_idx": len(rebuilt),- }- )- return tuple(rebuilt)---def _cell_glyph_rows(rows: list[str]) -> list[NativeTableGlyph]:- """把多条物理行构造成保留显式词间空格的 cell 字形。"""-- glyphs: list[NativeTableGlyph] = []- source_index = 0- for row_index, text in enumerate(rows):- x = 0.0- pending_space = False- for char in text:- if char.isspace():- pending_space = True- x += 2.0- continue- glyphs.append(- NativeTableGlyph(- glyph_id=len(glyphs),- source_index=source_index,- text=char,- bbox=(x, row_index * 12.0, x + 4.0, row_index * 12.0 + 8.0),- visual_row=row_index,- explicit_space_before=pending_space,- )- )- source_index += 1- pending_space = False- x += 4.0- return glyphs---def _grid_rules(- *,- width: float = 100.0,- height: float = 60.0,- internal_vertical: tuple[float, float] = (0.0, 60.0),- internal_horizontal: tuple[float, float] = (0.0, 100.0),-) -> tuple[NativeTableRule, ...]:- """构造二行二列表格边框,并允许裁剪内部横竖隔断。"""-- return (- NativeTableRule((0.0, 0.0, width, 1.0), 1.0, "horizontal"),- NativeTableRule(- (internal_horizontal[0], 29.5, internal_horizontal[1], 30.5),- 1.0,- "horizontal",- ),- NativeTableRule((0.0, height - 1.0, width, height), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, height), 1.0, "vertical"),- NativeTableRule(- (49.5, internal_vertical[0], 50.5, internal_vertical[1]),- 1.0,- "vertical",- ),- NativeTableRule((width - 1.0, 0.0, width, height), 1.0, "vertical"),- )---def _local_to_page_bbox(- bbox: tuple[float, float, float, float],- page_width: float,- page_height: float,- angle: int,-) -> tuple[float, float, float, float]:- """把正向局部测试框逆变换回页面坐标。"""-- x0, y0, x1, y1 = bbox- if angle == 90:- return page_width - y1, x0, page_width - y0, x1- if angle == 270:- return y0, page_height - x1, y1, page_height - x0- if angle == 180:- return page_width - x1, page_height - y1, page_width - x0, page_height - y0- return bbox---def _aligned_text_input(- rows: list[list[str | None]],- *,- angle: int = 0,- rules: tuple[NativeTableRule, ...] = (),- rectangles: tuple[NativeTableRectangle, ...] = (),-) -> NativeTableInput:- """构造标准旋转下的等距文本表格输入。"""-- page_width, page_height = 120.0, 90.0- local_width, local_height = (page_height, page_width) if angle in {90, 270} else (page_width, page_height)- col_count = max(len(row) for row in rows)- x_positions = [local_width * (0.10 + 0.75 * col / max(1, col_count - 1)) for col in range(col_count)]- y_positions = [local_height * (0.12 + 0.70 * row / max(1, len(rows) - 1)) for row in range(len(rows))]- entries = []- for row_index, row in enumerate(rows):- for col_index, text in enumerate(row):- if text is None:- continue- width = max(4.0, min(local_width * 0.20, len(text) * 4.0))- local_bbox = (- x_positions[col_index],- y_positions[row_index],- min(local_width - 1.0, x_positions[col_index] + width),- min(local_height - 1.0, y_positions[row_index] + 8.0),- )- entries.append(- (- text,- _local_to_page_bbox(- local_bbox,- page_width,- page_height,- angle,- ),- )- )- return NativeTableInput(- table_bbox=(0.0, 0.0, page_width, page_height),- page_size=(page_width, page_height),- angle=angle,- chars=_char_items(entries),- drawing_lines=rules,- rectangles=rectangles,- )---def _rotated_single_row_input(angle: int) -> NativeTableInput:- """构造四种标准旋转下的三列单物理行强线框。"""-- page_width, page_height = 120.0, 90.0- local_width, local_height = (page_height, page_width) if angle in {90, 270} else (page_width, page_height)- x_tracks = (0.0, local_width / 3.0, 2.0 * local_width / 3.0, local_width)- local_rule_bboxes = [- (0.0, 0.0, local_width, 1.0),- (0.0, local_height - 1.0, local_width, local_height),- *((x - 0.5, 0.0, x + 0.5, local_height) for x in x_tracks),- ]- page_rule_bboxes = [- _local_to_page_bbox(- bbox,- page_width,- page_height,- angle,- )- for bbox in local_rule_bboxes- ]- rules = tuple(- NativeTableRule(- bbox,- 1.0,- "horizontal" if bbox[2] - bbox[0] >= bbox[3] - bbox[1] else "vertical",- )- for bbox in page_rule_bboxes- )- entries = []- for col, text in enumerate(("A", "B", "C")):- local_bbox = (- x_tracks[col] + 5.0,- 10.0,- x_tracks[col] + 10.0,- 18.0,- )- entries.append(- (- text,- _local_to_page_bbox(- local_bbox,- page_width,- page_height,- angle,- ),- )- )- return NativeTableInput(- table_bbox=(0.0, 0.0, page_width, page_height),- page_size=(page_width, page_height),- angle=angle,- chars=_char_items(entries),- drawing_lines=rules,- )---def _rotated_single_column_input(angle: int) -> NativeTableInput:- """构造四种标准旋转下的二行单列强线框表单。"""-- page_width, page_height = 120.0, 90.0- local_width, local_height = (page_height, page_width) if angle in {90, 270} else (page_width, page_height)- y_tracks = (0.0, local_height / 2.0, local_height)- local_rule_bboxes = [- *((0.0, y - 0.5, local_width, y + 0.5) for y in y_tracks),- (0.0, 0.0, 1.0, local_height),- (local_width - 1.0, 0.0, local_width, local_height),- ]- page_rule_bboxes = [- _local_to_page_bbox(- bbox,- page_width,- page_height,- angle,- )- for bbox in local_rule_bboxes- ]- rules = tuple(- NativeTableRule(- bbox,- 1.0,- "horizontal" if bbox[2] - bbox[0] >= bbox[3] - bbox[1] else "vertical",- )- for bbox in page_rule_bboxes- )- chars: list[dict[str, object]] = []- for row, text in enumerate(("A&B", "Value A B")):- top = row * local_height / 2.0 + 10.0- for offset, char in enumerate(text):- chars.append(- {- "char": char,- "bbox": _local_to_page_bbox(- (- 8.0 + 4.0 * offset,- top,- 12.0 + 4.0 * offset,- top + 8.0,- ),- page_width,- page_height,- angle,- ),- "char_idx": len(chars),- }- )- return NativeTableInput(- table_bbox=(0.0, 0.0, page_width, page_height),- page_size=(page_width, page_height),- angle=angle,- chars=tuple(chars),- drawing_lines=rules,- )---def _rotated_sparse_hybrid_input(angle: int) -> NativeTableInput:- """构造四种标准旋转下仅有表头横线的三行三列表格。"""-- page_width, page_height = 120.0, 90.0- local_width, local_height = (page_height, page_width) if angle in {90, 270} else (page_width, page_height)- x_tracks = (0.0, local_width / 3.0, 2.0 * local_width / 3.0, local_width)- header_boundary = 0.30 * local_height- local_rule_bboxes = [- (0.0, 0.0, local_width, 1.0),- (0.0, header_boundary - 0.5, local_width, header_boundary + 0.5),- (0.0, local_height - 1.0, local_width, local_height),- *((track - 0.5, 0.0, track + 0.5, local_height) for track in x_tracks),- ]- rules = tuple(- NativeTableRule(- page_bbox,- 1.0,- "horizontal" if page_bbox[2] - page_bbox[0] >= page_bbox[3] - page_bbox[1] else "vertical",- )- for page_bbox in (- _local_to_page_bbox(- bbox,- page_width,- page_height,- angle,- )- for bbox in local_rule_bboxes- )- )- y_positions = (5.0, 0.42 * local_height, 0.70 * local_height)- entries = []- for row, values in enumerate((("H", "I", "J"), ("A", "1", "2"), ("B", "3", "4"))):- for col, value in enumerate(values):- local_bbox = (- x_tracks[col] + 5.0,- y_positions[row],- x_tracks[col] + 13.0,- y_positions[row] + 8.0,- )- entries.append(- (- value,- _local_to_page_bbox(- local_bbox,- page_width,- page_height,- angle,- ),- )- )- return NativeTableInput(- table_bbox=(0.0, 0.0, page_width, page_height),- page_size=(page_width, page_height),- angle=angle,- chars=_char_items(entries),- drawing_lines=rules,- )---def _candidate(- *,- source: str,- rows: int,- cols: int,- score: float,- issues: tuple[str, ...] = (),-) -> NativeTableCandidate:- """构造候选仲裁测试需要的最小内部对象。"""-- cells = tuple(- NativeTableCell(- row=row,- col=col,- rowspan=1,- colspan=1,- bbox=(float(col), float(row), float(col + 1), float(row + 1)),- content="",- )- for row in range(rows)- for col in range(cols)- )- return NativeTableCandidate(- source=source, # type: ignore[arg-type]- rows=rows,- cols=cols,- cells=cells,- score=score,- text_capture=1.0,- structure_support=1.0,- row_stability=1.0,- column_stability=1.0,- order_consistency=1.0,- issues=issues,- )---def _build_reportlab_table_pdf() -> bytes:- """生成带真实 PDF drawing 和文本层的二行二列表格 fixture。"""-- output = BytesIO()- canvas = Canvas(output, pagesize=(200, 200))- canvas.setLineWidth(1)- for y in (40, 100, 160):- canvas.line(20, y, 180, y)- for x in (20, 100, 180):- canvas.line(x, 40, x, 160)- canvas.drawString(35, 130, "A")- canvas.drawString(115, 130, "B")- canvas.drawString(35, 70, "C")- canvas.drawString(115, 70, "D")- canvas.showPage()- canvas.save()- return output.getvalue()---def test_vector_grid_recovers_cells_and_escapes_html() -> None:- """验证完整矢量网格生成稳定 HTML,并转义单元格文本。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("<&", (10.0, 10.0, 20.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "vector_grid"- assert result.html == ("<table><tbody><tr><td><&</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></tbody></table>")- assert sorted(index for cell in result.cells for index in cell.source_char_indices) == [0, 1, 2, 3, 4]---def test_vector_grid_splits_one_pdf_text_run_by_character_boundary() -> None:- """验证物理列边界可将同一 PDF 文本对象按字符安全落格。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("AB", (45.0, 10.0, 55.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert "<tr><td>A</td><td>B</td></tr>" in result.html---def test_text_candidate_rejects_token_split_across_cell_boundary() -> None:- """验证纯文本轨道不将一个原子 token 分割到两个逻辑单元格。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("AB", (45.0, 10.0, 55.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- )- text = build_native_table_text(table_input)- assert text is not None- specs = (- GridCellSpec(0, 0, 1, 1, (0.0, 0.0, 50.0, 30.0)),- GridCellSpec(0, 1, 1, 1, (50.0, 0.0, 100.0, 30.0)),- GridCellSpec(1, 0, 1, 1, (0.0, 30.0, 50.0, 60.0)),- GridCellSpec(1, 1, 1, 1, (50.0, 30.0, 100.0, 60.0)),- )- diagnostics: dict[str, object] = {}-- candidate = build_candidate(- source="text_grid",- rows=2,- cols=2,- specs=specs,- text=text,- structure_support=1.0,- row_stability=1.0,- column_stability=1.0,- require_atomic_tokens=True,- diagnostics=diagnostics,- )-- assert candidate is None- assert diagnostics["candidate_rejection_gate"] == "token_split"- assert diagnostics["token_split_count"] == 1---def test_vector_grid_accepts_open_outer_vertical_edges() -> None:- """验证横线端点可补齐缺失的左右外框而不伪造内部隔断。"""-- rules = (- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((49.5, 0.0, 50.5, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=rules,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "vector_grid"- assert (result.rows, result.cols) == (2, 2)---def test_single_long_rule_endpoint_does_not_create_global_column() -> None:- """验证单条长横线的内缩端点不能创建全局幽灵列。"""-- rules = list(_grid_rules())- rules[0] = NativeTableRule((10.0, 0.0, 100.0, 1.0), 1.0, "horizontal")- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=tuple(rules),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)---def test_sparse_hybrid_splits_dense_keyed_baselines_after_line_undercount() -> None:- """验证只有表头横线时按独立关键列把稠密正文基线恢复成多行。"""-- rules = (- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 60.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 60.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("H1", (8.0, 5.0, 16.0, 13.0)),- ("H2", (48.0, 5.0, 56.0, 13.0)),- ("H3", (88.0, 5.0, 96.0, 13.0)),- ("A", (8.0, 27.0, 12.0, 35.0)),- ("1", (48.0, 27.0, 52.0, 35.0)),- ("2", (88.0, 27.0, 92.0, 35.0)),- ("B", (8.0, 42.0, 12.0, 50.0)),- ("3", (48.0, 42.0, 52.0, 50.0)),- ("4", (88.0, 42.0, 92.0, 50.0)),- ]- ),- drawing_lines=rules,- )-- diagnostics = diagnose_native_pdf_table(table_input)-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "sparse_hybrid"- assert (result.rows, result.cols) == (3, 3)- assert "<tr><td>B</td><td>3</td><td>4</td></tr>" in result.html- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["first_rejection_gate"] == "physical_row_undercount"- assert line_attempt["physical_row_dense_baseline_pairs"] == [- {- "physical_row": 1,- "visual_rows": [1, 2],- "occupied_cols": [0, 1, 2],- }- ]--[email protected]("angle", [0, 90, 180, 270])-def test_sparse_hybrid_supports_standard_table_rotations(angle: int) -> None:- """验证竖线加视觉正文行的少线候选支持四种标准旋转。"""-- result = recover_native_pdf_table(_rotated_sparse_hybrid_input(angle))-- assert result is not None- assert result.source == "sparse_hybrid"- assert (result.rows, result.cols) == (3, 3)- assert "<tr><td>B</td><td>3</td><td>4</td></tr>" in result.html---def test_sparse_hybrid_recovers_two_level_header_spans() -> None:- """验证局部表头横线恢复左侧 rowspan 和分组标题 colspan。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 100.0),- page_size=(120.0, 100.0),- angle=0,- chars=_char_items(- [- ("Site", (8.0, 5.0, 24.0, 13.0)),- ("Metrics", (60.0, 5.0, 88.0, 13.0)),- ("Q1", (48.0, 25.0, 56.0, 33.0)),- ("Q2", (88.0, 25.0, 96.0, 33.0)),- ("A", (8.0, 55.0, 12.0, 63.0)),- ("1", (48.0, 55.0, 52.0, 63.0)),- ("2", (88.0, 55.0, 92.0, 63.0)),- ("B", (8.0, 78.0, 12.0, 86.0)),- ("3", (48.0, 78.0, 52.0, 86.0)),- ("4", (88.0, 78.0, 92.0, 86.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((30.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 99.0, 120.0, 100.0), 1.0, "horizontal"),- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "sparse_hybrid"- assert (result.rows, result.cols) == (4, 3)- assert '<td rowspan="2">Site</td><td colspan="2">Metrics</td>' in result.html- assert "<tr><td>Q1</td><td>Q2</td></tr>" in result.html---def test_sparse_hybrid_rejects_ambiguous_partial_header_separator() -> None:- """验证表头横线只覆盖部分叶子列时不猜测 rowspan/colspan。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 100.0),- page_size=(120.0, 100.0),- angle=0,- chars=_char_items(- [- ("Site", (8.0, 5.0, 24.0, 13.0)),- ("Metrics", (60.0, 5.0, 88.0, 13.0)),- ("Q1", (48.0, 25.0, 56.0, 33.0)),- ("Q2", (88.0, 25.0, 96.0, 33.0)),- ("A", (8.0, 55.0, 12.0, 63.0)),- ("1", (48.0, 55.0, 52.0, 63.0)),- ("2", (88.0, 55.0, 92.0, 63.0)),- ("B", (8.0, 78.0, 12.0, 86.0)),- ("3", (48.0, 78.0, 52.0, 86.0)),- ("4", (88.0, 78.0, 92.0, 86.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((40.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 99.0, 120.0, 100.0), 1.0, "horizontal"),- ),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- assert recover_native_pdf_table(table_input) is None- sparse_attempt = diagnostics["sparse_hybrid_attempts"][0]- assert sparse_attempt["first_rejection_gate"] == "header_topology"---def test_vector_grid_joins_small_collinear_gaps() -> None:- """验证内部竖线的小间隙会先连接,不会误判为 colspan。"""-- rules = tuple(rule for rule in _grid_rules() if not (rule.orientation == "vertical" and 49.0 <= rule.bbox[0] <= 51.0)) + (- NativeTableRule((49.5, 0.0, 50.5, 14.0), 1.0, "vertical"),- NativeTableRule((49.5, 16.0, 50.5, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=rules,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert "colspan" not in result.html---def test_line_grid_ignores_stroked_rectangle_duplicate_tracks() -> None:- """验证 drawing 与描边矩形重复边界不会混成幽灵行列。"""-- rectangles = tuple(- NativeTableRectangle(bbox, 5, False, True)- for bbox in (- (0.5, 0.5, 49.5, 29.5),- (50.5, 0.5, 99.5, 29.5),- (0.5, 30.5, 49.5, 59.5),- (50.5, 30.5, 99.5, 59.5),- )- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(),- rectangles=rectangles,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- assert "evidence=line_grid" in result.diagnostics---def test_rect_grid_requires_repeated_two_dimensional_lattice() -> None:- """验证四个重复单元格矩形可独立形成 rect_grid。"""-- rectangles = tuple(- NativeTableRectangle(bbox, 5, True, False)- for bbox in (- (0.0, 0.0, 50.0, 30.0),- (50.0, 0.0, 100.0, 30.0),- (0.0, 30.0, 50.0, 60.0),- (50.0, 30.0, 100.0, 60.0),- )- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- rectangles=rectangles,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- assert "evidence=rect_grid" in result.diagnostics---def test_vector_grid_collapses_narrow_empty_duplicate_track() -> None:- """验证窄空列会保留较强真实边界并删除重复竖轨。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=(- *_grid_rules(),- NativeTableRule((50.5, 0.0, 51.5, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- assert "colspan" not in result.html---def test_vector_grid_uses_aliases_for_offset_complementary_separators() -> None:- """验证表头正文错位的同一竖线折叠后仍按 alias 保持分隔。"""-- rules = tuple(rule for rule in _grid_rules() if not (rule.orientation == "vertical" and 49.0 <= rule.bbox[0] <= 51.0)) + (- NativeTableRule((48.5, 0.0, 49.5, 30.0), 1.0, "vertical"),- NativeTableRule((50.5, 30.0, 51.5, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=rules,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- assert "colspan" not in result.html- assert "alias_separator_recoveries=2" in result.diagnostics---def test_vector_grid_rejects_non_unique_alias_chain() -> None:- """验证连续窄轨的 alias 总跨度超限时主动放弃。"""-- rules = (- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((44.5, 0.0, 45.5, 60.0), 1.0, "vertical"),- NativeTableRule((48.5, 0.0, 49.5, 60.0), 1.0, "vertical"),- NativeTableRule((52.5, 0.0, 53.5, 60.0), 1.0, "vertical"),- NativeTableRule((99.0, 0.0, 100.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (70.0, 10.0, 75.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (70.0, 40.0, 75.0, 48.0)),- ]- ),- drawing_lines=rules,- )-- text = build_native_table_text(table_input)-- assert text is not None- assert build_vector_candidates(table_input, text) == []---def test_vector_grid_rejects_single_column_region_with_narrow_ghost_track() -> None:- """验证单列区域不能借一个窄空轨伪装成二列表格。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("Header", (20.0, 10.0, 44.0, 18.0)),- ("Value", (20.0, 40.0, 40.0, 48.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((4.5, 0.0, 5.5, 60.0), 1.0, "vertical"),- ),- )-- text = build_native_table_text(table_input)-- assert text is not None- assert build_vector_candidates(table_input, text) == []---def test_vector_grid_accepts_one_text_row_with_blank_physical_row() -> None:- """验证强物理二行网格即使只有一行原生文本也可保留空白数据行。"""-- rules = (- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 120.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 60.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 60.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 14.0, 18.0)),- ("B", (50.0, 10.0, 54.0, 18.0)),- ("C", (90.0, 10.0, 94.0, 18.0)),- ]- ),- drawing_lines=rules,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 3)- assert result.html.endswith("<tr><td></td><td></td><td></td></tr></tbody></table>")---def test_line_grid_accepts_multilevel_header_and_blank_template_row() -> None:- """验证强线框多层表头可保留全宽空白模板行。"""-- rules = (- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 39.5, 120.0, 40.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 40.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 40.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 5.0, 14.0, 13.0)),- ("B", (50.0, 5.0, 54.0, 13.0)),- ("C", (90.0, 5.0, 94.0, 13.0)),- ("D", (10.0, 25.0, 14.0, 33.0)),- ("E", (50.0, 25.0, 54.0, 33.0)),- ("F", (90.0, 25.0, 94.0, 33.0)),- ]- ),- drawing_lines=rules,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (3, 3)- assert result.confidence >= 0.95- assert result.html.endswith('<tr><td colspan="3"></td></tr></tbody></table>')- assert "physical_blank_rows=2" in result.diagnostics---def test_line_grid_accepts_blank_row_when_alias_recovery_is_elsewhere() -> None:- """验证其他物理行的 alias 恢复不会误伤独立封闭的空白行。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 5.0, 14.0, 13.0)),- ("B", (70.0, 5.0, 74.0, 13.0)),- ("C", (10.0, 25.0, 14.0, 33.0)),- ("D", (70.0, 25.0, 74.0, 33.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 39.5, 120.0, 40.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((48.5, 0.0, 49.5, 20.0), 1.0, "vertical"),- NativeTableRule((50.5, 20.0, 51.5, 40.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (3, 2)- assert result.html.endswith('<tr><td colspan="2"></td></tr></tbody></table>')- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["alias_affected_rows"] == [0, 1]- assert line_attempt["empty_rows"] == [2]---def test_line_grid_rejects_blank_row_touched_by_alias_recovery() -> None:- """验证空白行自身依赖 alias separator 时仍主动回退。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 5.0, 14.0, 13.0)),- ("B", (70.0, 5.0, 74.0, 13.0)),- ("C", (10.0, 25.0, 14.0, 33.0)),- ("D", (70.0, 25.0, 74.0, 33.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 39.5, 120.0, 40.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((48.5, 0.0, 49.5, 20.0), 1.0, "vertical"),- NativeTableRule((50.5, 20.0, 51.5, 40.0), 1.0, "vertical"),- NativeTableRule((48.5, 40.0, 49.5, 60.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)- assert result is None- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["first_rejection_gate"] == "empty_row"- assert 2 in line_attempt["alias_affected_rows"]---def test_line_grid_rejects_blank_row_without_bottom_boundary() -> None:- """验证缺少独立下边界的空白行不能借端点推断进入 HTML。"""-- base = (- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 39.5, 120.0, 40.5), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 40.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 40.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 5.0, 14.0, 13.0)),- ("B", (50.0, 5.0, 54.0, 13.0)),- ("C", (90.0, 5.0, 94.0, 13.0)),- ("D", (10.0, 25.0, 14.0, 33.0)),- ("E", (50.0, 25.0, 54.0, 33.0)),- ("F", (90.0, 25.0, 94.0, 33.0)),- ]- ),- drawing_lines=base,- )-- text = build_native_table_text(table_input)-- assert text is not None- assert build_vector_candidates(table_input, text) == []- diagnostics = diagnose_native_pdf_table(table_input)- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["first_rejection_gate"] == "empty_row"- assert line_attempt["empty_rows"] == [2]---def test_line_grid_rejects_too_narrow_blank_row() -> None:- """验证高度不足的空白物理行仍主动回退。"""-- rules = (- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 120.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 55.5, 120.0, 56.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 56.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 56.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 8.0, 14.0, 16.0)),- ("B", (50.0, 8.0, 54.0, 16.0)),- ("C", (90.0, 8.0, 94.0, 16.0)),- ("D", (10.0, 38.0, 14.0, 46.0)),- ("E", (50.0, 38.0, 54.0, 46.0)),- ("F", (90.0, 38.0, 94.0, 46.0)),- ]- ),- drawing_lines=rules,- )-- text = build_native_table_text(table_input)-- assert text is not None- assert build_vector_candidates(table_input, text) == []---def test_line_grid_prunes_inset_decorative_underlines() -> None:- """验证单元格内缩短下划线不会创建全表横轨。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("Left top", (5.0, 5.0, 45.0, 14.0)),- ("Right top", (65.0, 5.0, 110.0, 14.0)),- ("Left bottom", (5.0, 35.0, 50.0, 44.0)),- ("Right bottom", (65.0, 35.0, 115.0, 44.0)),- ]- ),- drawing_lines=(- *_grid_rules(width=120.0),- NativeTableRule((5.0, 17.5, 55.0, 18.5), 1.0, "horizontal"),- NativeTableRule((5.0, 23.5, 20.0, 24.5), 1.0, "horizontal"),- NativeTableRule((5.0, 47.5, 55.0, 48.5), 1.0, "horizontal"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["track_hypothesis"] == "supported"- assert len(line_attempt["removed_horizontal_tracks"]) == 3- assert len(line_attempt["track_hypotheses"]) == 2---def test_line_grid_keeps_partial_separator_spanning_complete_columns() -> None:- """验证跨完整列带的局部横线保留,同时删除单元格内短下划线。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 14.0, 18.0)),- ("B", (50.0, 10.0, 54.0, 18.0)),- ("C", (90.0, 10.0, 94.0, 18.0)),- ("D", (50.0, 40.0, 54.0, 48.0)),- ("E", (90.0, 40.0, 94.0, 48.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((40.0, 29.5, 120.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),- NativeTableRule((45.0, 22.5, 58.0, 23.5), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 60.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 60.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 3)- assert result.cells[0].rowspan == 2- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["track_hypothesis"] == "supported"- assert len(line_attempt["removed_horizontal_tracks"]) == 1--[email protected]("angle", [0, 90, 180, 270])-def test_single_column_line_grid_supports_standard_rotations(angle: int) -> None:- """验证强线框单列表单在四种标准方向下保留文本和转义。"""-- result = recover_native_pdf_table(_rotated_single_column_input(angle))-- assert result is not None- assert result.source == "vector_grid"- assert (result.rows, result.cols) == (2, 1)- assert result.html == ("<table><tbody><tr><td>A&B</td></tr><tr><td>Value A B</td></tr></tbody></table>")- assert "single_column_line_grid=true" in result.diagnostics--[email protected]("missing", ["right", "middle"])-def test_single_column_line_grid_requires_complete_physical_frame(- missing: str,-) -> None:- """验证缺少侧边或行分隔的单列区域不能进入 HTML。"""-- rules = [- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((99.0, 0.0, 100.0, 60.0), 1.0, "vertical"),- ]- if missing == "right":- rules.pop()- else:- rules.pop(1)- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("Header", (10.0, 10.0, 34.0, 18.0)),- ("Value", (10.0, 40.0, 30.0, 48.0)),- ]- ),- drawing_lines=tuple(rules),- )-- assert recover_native_pdf_table(table_input) is None---def test_line_grid_rejects_single_cell_frame() -> None:- """验证完整外框中的单个文本块不能作为一行一列表格采用。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 40.0),- page_size=(100.0, 40.0),- angle=0,- chars=_char_items([("Paragraph", (10.0, 10.0, 46.0, 18.0))]),- drawing_lines=(- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 39.0, 100.0, 40.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 40.0), 1.0, "vertical"),- NativeTableRule((99.0, 0.0, 100.0, 40.0), 1.0, "vertical"),- ),- )-- assert recover_native_pdf_table(table_input) is None---def test_line_grid_collapses_duplicate_outer_y_track_in_multirow_table() -> None:- """验证纵线端点与底部描边形成的重复外缘不会制造幽灵行。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 14.0, 18.0)),- ("B", (60.0, 10.0, 64.0, 18.0)),- ("C", (10.0, 40.0, 14.0, 48.0)),- ("D", (60.0, 40.0, 64.0, 48.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.5, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 59.0), 1.0, "vertical"),- NativeTableRule((49.5, 0.0, 50.5, 59.0), 1.0, "vertical"),- NativeTableRule((99.0, 0.0, 100.0, 59.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (2, 2)- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["outer_track_collapses"]["y"] == 1---def test_line_grid_preserves_independent_nearby_outer_boundaries() -> None:- """验证两条各自有强物理线的近邻外缘不会被重复轨规则折叠。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 14.0, 18.0)),- ("B", (60.0, 10.0, 64.0, 18.0)),- ("C", (10.0, 35.0, 14.0, 43.0)),- ("D", (60.0, 35.0, 64.0, 43.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 100.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 100.0, 30.5), 1.0, "horizontal"),- NativeTableRule((0.0, 53.5, 100.0, 54.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 100.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((49.5, 0.0, 50.5, 54.0), 1.0, "vertical"),- NativeTableRule((99.0, 0.0, 100.0, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["outer_track_collapses"]["y"] == 0- assert result is not None- assert result.source != "vector_grid"---def test_line_grid_does_not_fold_distinct_short_rule_into_outer_border() -> None:- """验证外缘附近存在独立短物理线时保留原有 rowspan 拓扑。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 400.0, 60.0),- page_size=(400.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 14.0, 18.0)),- ("B", (120.0, 10.0, 124.0, 18.0)),- ("C", (270.0, 10.0, 274.0, 18.0)),- ("D", (10.0, 40.0, 14.0, 48.0)),- ("E", (120.0, 40.0, 124.0, 48.0)),- ("F", (270.0, 40.0, 274.0, 48.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 400.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 29.5, 400.0, 30.5), 1.0, "horizontal"),- NativeTableRule((5.0, 53.5, 17.0, 54.5), 1.0, "horizontal"),- NativeTableRule((0.0, 59.0, 400.0, 60.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((99.5, 0.0, 100.5, 60.0), 1.0, "vertical"),- NativeTableRule((249.5, 0.0, 250.5, 60.0), 1.0, "vertical"),- NativeTableRule((399.0, 0.0, 400.0, 60.0), 1.0, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert result.source == "vector_grid"- assert (result.rows, result.cols) == (3, 3)- assert all(cell.rowspan == 2 for cell in result.cells if cell.row == 1)- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["outer_track_collapses"]["y"] == 0---def test_single_row_line_grid_recovers_clipped_outer_borders() -> None:- """验证 drawing halo 可恢复 bbox 外邻近边框且保留物理空列。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 2.0, 120.0, 58.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("C", (90.0, 38.0, 95.0, 46.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.5, 120.0, 1.0), 0.5, "horizontal"),- NativeTableRule((0.0, 59.0, 120.0, 59.5), 0.5, "horizontal"),- NativeTableRule((0.0, 1.0, 0.5, 59.0), 0.5, "vertical"),- NativeTableRule((39.75, 1.0, 40.25, 59.0), 0.5, "vertical"),- NativeTableRule((79.75, 1.0, 80.25, 59.0), 0.5, "vertical"),- NativeTableRule((119.5, 1.0, 120.0, 59.0), 0.5, "vertical"),- ),- )-- result = recover_native_pdf_table(table_input)- diagnostics = diagnose_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (1, 3)- assert result.html == ("<table><tbody><tr><td>A</td><td></td><td>C</td></tr></tbody></table>")- assert "single_row_line_grid=true" in result.diagnostics- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["evidence_halo"] > 0- assert line_attempt["single_row_evidence"]["verified"] is True---def test_single_row_line_grid_rejects_missing_outer_border() -> None:- """验证单物理行缺少任一横向外框时继续主动回退。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 60.0),- page_size=(120.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (50.0, 10.0, 55.0, 18.0)),- ("C", (90.0, 10.0, 95.0, 18.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),- NativeTableRule((39.5, 0.0, 40.5, 60.0), 1.0, "vertical"),- NativeTableRule((79.5, 0.0, 80.5, 60.0), 1.0, "vertical"),- NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),- ),- )-- assert recover_native_pdf_table(table_input) is None- diagnostics = diagnose_native_pdf_table(table_input)- assert diagnostics["first_rejection_gate"] == ("vector_single_row_physical_evidence")--[email protected]("angle", [0, 90, 180, 270])-def test_single_row_line_grid_supports_standard_rotations(angle: int) -> None:- """验证强线框单物理行在四种标准旋转下保持同一拓扑。"""-- result = recover_native_pdf_table(_rotated_single_row_input(angle))-- assert result is not None- assert (result.rows, result.cols) == (1, 3)- assert [cell.content for cell in result.cells] == ["A", "B", "C"]---def test_vector_cell_preserves_explicit_small_gap_space() -> None:- """验证 PDF 字符流显式空格在几何间距很小时仍不会丢失。"""-- chars = (- {"char": "A", "bbox": (10.0, 10.0, 14.0, 18.0), "char_idx": 0},- {"char": " ", "bbox": (14.0, 10.0, 14.5, 18.0), "char_idx": 1},- {"char": "B", "bbox": (14.5, 10.0, 18.5, 18.0), "char_idx": 2},- {"char": "X", "bbox": (60.0, 10.0, 64.0, 18.0), "char_idx": 3},- {"char": "C", "bbox": (10.0, 40.0, 14.0, 48.0), "char_idx": 4},- {"char": "D", "bbox": (60.0, 40.0, 64.0, 48.0), "char_idx": 5},- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=chars, # type: ignore[arg-type]- drawing_lines=_grid_rules(),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert "<td>A B</td>" in result.html---def test_reportlab_pdf_primitives_recover_expected_html() -> None:- """验证真实 ReportLab PDF 的字符与 drawing 可端到端恢复结构。"""-- with PDFDocument(_build_reportlab_table_pdf()) as document:- page = document[0]- result = recover_native_pdf_table(- NativeTableInput(- table_bbox=(20.0, 40.0, 180.0, 160.0),- page_size=page.size,- angle=0,- chars=tuple(page.get_chars()),- drawing_lines=coerce_native_table_rules(page.get_drawing_lines()),- rectangles=coerce_native_table_rectangles(page.get_path_infos()),- )- )-- assert result is not None- assert result.source == "vector_grid"- assert result.html == ("<table><tbody><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></tbody></table>")--- ("vertical_range", "horizontal_range", "expected_attribute"),- [- ((30.0, 60.0), (0.0, 100.0), 'colspan="2"'),- ((0.0, 60.0), (50.0, 100.0), 'rowspan="2"'),- ],-)-def test_vector_grid_recovers_rectangular_spans(- vertical_range: tuple[float, float],- horizontal_range: tuple[float, float],- expected_attribute: str,-) -> None:- """验证内部隔断缺失只生成矩形横向或纵向合并格。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(- internal_vertical=vertical_range,- internal_horizontal=horizontal_range,- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert expected_attribute in result.html---def test_vector_grid_rejects_non_rectangular_merge_component() -> None:- """验证横纵缺边形成 L 形连通域时拒绝矢量候选。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(- internal_vertical=(30.0, 60.0),- internal_horizontal=(50.0, 100.0),- ),- )- text = build_native_table_text(table_input)-- assert text is not None- assert build_vector_candidates(table_input, text) == []---def test_vector_cell_joins_latin_visual_lines_with_space() -> None:- """验证同一逻辑单元格中的 Latin 多行补空格但不写入 HTML 换行。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 6.0, 15.0, 12.0)),- ("B", (10.0, 18.0, 15.0, 24.0)),- ("X", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert "<td>A B</td>" in result.html- assert "<br>" not in result.html--- ("rows", "expected"),- [- (["Latin line", "continues"], "Latin line continues"),- (["中文", "继续"], "中文继续"),- (["标题 neural", "networks"], "标题 neural networks"),- (["Neural Networks:", "Unlocking"], "Neural Networks: Unlocking"),- (["RF-", "based"], "RF-based"),- (["https://example.test/path", "/next"], "https://example.test/path/next"),- (["https://example.test/one", "https://example.test/two"], "https://example.test/one https://example.test/two"),- (["40.5000", "00"], "40.500000"),- (["1.0mg/N", "m3"], "1.0mg/Nm3"),- (["RFC3986", "URL"], "RFC3986URL"),- (["Привет", "мир"], "Приветмир"),- ],-)-def test_cell_visual_line_join_is_language_aware(- rows: list[str],- expected: str,-) -> None:- """验证 Latin、CJK、URL、连字符、数字和紧凑标识符的边界策略。"""-- glyphs = _cell_glyph_rows(rows)-- assert build_cell_text(glyphs, 8.0) == expected---def test_cell_visual_line_separator_has_no_source_index() -> None:- """验证新增行间空格不伪造 PDF 字符来源索引。"""-- parts = build_cell_text_parts(_cell_glyph_rows(["Latin", "text"]), 8.0)-- assert (" ", None) in parts- assert "".join(text for text, _source_index in parts) == "Latin text"--[email protected]("angle", [0, 90, 180, 270])-def test_text_grid_supports_standard_table_rotations(angle: int) -> None:- """验证三列无线表在四个标准方向下恢复相同结构。"""-- result = recover_native_pdf_table(- _aligned_text_input(- [- ["A", "B", "C"],- ["1", "2", "3"],- ["4", "5", "6"],- ],- angle=angle,- )- )-- assert result is not None- assert result.source == "text_grid"- assert (result.rows, result.cols) == (3, 3)- assert "<tr><td>4</td><td>5</td><td>6</td></tr>" in result.html---def test_text_grid_preserves_empty_cells() -> None:- """验证缺少文本的叶子列保留空 td,且不会被推断为合并格。"""-- result = recover_native_pdf_table(- _aligned_text_input(- [- ["A", "B", "C"],- ["1", None, "3"],- ["4", "5", "6"],- ]- )- )-- assert result is not None- assert "<tr><td>1</td><td></td><td>3</td></tr>" in result.html- assert "rowspan" not in result.html- assert "colspan" not in result.html---def test_text_grid_groups_tight_subset_continuation_without_break() -> None:- """验证无线表紧邻且不引入新列的续行并入同一逻辑行且直接拼接。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 75.0),- page_size=(120.0, 75.0),- angle=0,- chars=_char_items(- [- ("A1", (8.0, 5.0, 16.0, 13.0)),- ("B1", (48.0, 5.0, 56.0, 13.0)),- ("C1", (88.0, 5.0, 96.0, 13.0)),- ("A2", (8.0, 14.0, 16.0, 22.0)),- ("1", (8.0, 36.0, 12.0, 44.0)),- ("2", (48.0, 36.0, 52.0, 44.0)),- ("3", (88.0, 36.0, 92.0, 44.0)),- ("4", (8.0, 60.0, 12.0, 68.0)),- ("5", (48.0, 60.0, 52.0, 68.0)),- ("6", (88.0, 60.0, 92.0, 68.0)),- ]- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (3, 3)- assert "<tr><td>A1A2</td><td>B1</td><td>C1</td></tr>" in result.html---def test_text_grid_rejects_tight_equal_dense_baselines() -> None:- """验证紧邻且占用列相同的稠密基线不被冒充续行合并。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 75.0),- page_size=(120.0, 75.0),- angle=0,- chars=_char_items(- [- ("A1", (8.0, 5.0, 16.0, 13.0)),- ("B1", (48.0, 5.0, 56.0, 13.0)),- ("C1", (88.0, 5.0, 96.0, 13.0)),- ("A2", (8.0, 14.0, 16.0, 22.0)),- ("B2", (48.0, 14.0, 56.0, 22.0)),- ("C2", (88.0, 14.0, 96.0, 22.0)),- ("A3", (8.0, 50.0, 16.0, 58.0)),- ("B3", (48.0, 50.0, 56.0, 58.0)),- ("C3", (88.0, 50.0, 96.0, 58.0)),- ]- ),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- assert recover_native_pdf_table(table_input) is None- text_attempt = next(attempt for attempt in diagnostics["text_attempts"] if attempt["source"] == "text_grid")- assert text_attempt["first_rejection_gate"] == "dense_row_ambiguity"- assert text_attempt["dense_row_ambiguities"] == [[0, 1]]---def test_text_grid_accepts_right_aligned_numeric_columns() -> None:- """验证数字宽度变化但右缘稳定时仍能恢复同一列结构。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 110.0, 70.0),- page_size=(110.0, 70.0),- angle=0,- chars=_char_items(- [- ("Name", (10.0, 5.0, 26.0, 13.0)),- ("Count", (40.0, 5.0, 60.0, 13.0)),- ("Rate", (84.0, 5.0, 100.0, 13.0)),- ("A", (10.0, 28.0, 14.0, 36.0)),- ("1", (56.0, 28.0, 60.0, 36.0)),- ("10", (92.0, 28.0, 100.0, 36.0)),- ("B", (10.0, 51.0, 14.0, 59.0)),- ("1000", (44.0, 51.0, 60.0, 59.0)),- ("2", (96.0, 51.0, 100.0, 59.0)),- ]- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert (result.rows, result.cols) == (3, 3)- assert "<tr><td>B</td><td>1000</td><td>2</td></tr>" in result.html---def test_text_grid_recovers_conservative_multicolumn_header() -> None:- """验证前导单项文本真实横跨叶子列时生成 colspan。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 70.0),- page_size=(100.0, 70.0),- angle=0,- chars=_char_items(- [- ("ABCDEFGHIJKLMNOPQR", (5.0, 5.0, 95.0, 13.0)),- ("A", (10.0, 30.0, 14.0, 38.0)),- ("B", (45.0, 30.0, 49.0, 38.0)),- ("C", (80.0, 30.0, 84.0, 38.0)),- ("1", (10.0, 52.0, 14.0, 60.0)),- ("2", (45.0, 52.0, 49.0, 60.0)),- ("3", (80.0, 52.0, 84.0, 60.0)),- ]- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert '<td colspan="3">ABCDEFGHIJKLMNOPQR</td>' in result.html---def test_text_grid_rejects_header_that_requires_rowspan() -> None:- """验证表头角落空缺且需要 rowspan 才能还原时不生成伪网格。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 90.0),- page_size=(120.0, 90.0),- angle=0,- chars=_char_items(- [- ("Metrics", (52.0, 5.0, 104.0, 13.0)),- ("Name", (8.0, 30.0, 24.0, 38.0)),- ("Q1", (48.0, 30.0, 56.0, 38.0)),- ("Q2", (88.0, 30.0, 96.0, 38.0)),- ("A", (8.0, 60.0, 12.0, 68.0)),- ("1", (48.0, 60.0, 52.0, 68.0)),- ("2", (88.0, 60.0, 92.0, 68.0)),- ]- ),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- assert recover_native_pdf_table(table_input) is None- text_attempt = next(attempt for attempt in diagnostics["text_attempts"] if attempt["source"] == "text_grid")- assert text_attempt["first_rejection_gate"] == "header_requires_rowspan"- assert text_attempt["header_representable"] is False---def test_key_value_candidate_handles_two_stable_columns() -> None:- """验证两列字段值表走独立 key-value 候选。"""-- result = recover_native_pdf_table(- _aligned_text_input(- [- ["Name", "Alice"],- ["Age", "30"],- ["City", "Paris"],- ]- )- )-- assert result is not None- assert result.source == "key_value"- assert "<td>Name</td><td>Alice</td>" in result.html---def test_text_grid_abstains_for_prose_without_repeated_columns() -> None:- """验证已知 bbox 内只有连续正文行时仍主动放弃结构化。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 70.0),- page_size=(120.0, 70.0),- angle=0,- chars=_char_items(- [- ("This is a complete sentence.", (5.0, 5.0, 110.0, 13.0)),- ("It continues as ordinary prose.", (5.0, 28.0, 112.0, 36.0)),- ("No stable columns are present.", (5.0, 51.0, 108.0, 59.0)),- ]- ),- )-- assert recover_native_pdf_table(table_input) is None--[email protected]("evidence", ["booktabs", "stripes"])-def test_sparse_candidate_uses_rules_or_row_stripes(evidence: str) -> None:- """验证三线规则和重复行底纹均可提升同拓扑少线候选。"""-- rules: tuple[NativeTableRule, ...] = ()- rectangles: tuple[NativeTableRectangle, ...] = ()- if evidence == "booktabs":- rules = (- NativeTableRule((0.0, 5.0, 120.0, 6.0), 1.0, "horizontal"),- NativeTableRule((0.0, 35.0, 120.0, 36.0), 1.0, "horizontal"),- NativeTableRule((0.0, 84.0, 120.0, 85.0), 1.0, "horizontal"),- )- else:- rectangles = (- NativeTableRectangle((0.0, 8.0, 120.0, 18.0), 5, True, False),- NativeTableRectangle((0.0, 38.0, 120.0, 48.0), 5, True, False),- NativeTableRectangle((0.0, 68.0, 120.0, 78.0), 5, True, False),- )- result = recover_native_pdf_table(- _aligned_text_input(- [- ["A", "B", "C"],- ["1", "2", "3"],- ["4", "5", "6"],- ],- rules=rules,- rectangles=rectangles,- )- )-- assert result is not None- assert result.source == ("sparse_hybrid" if evidence == "booktabs" else "sparse_grid")---def test_candidate_conflict_with_close_scores_abstains() -> None:- """验证近分异构候选无法建立明确优势时主动放弃。"""-- assert (- _select_candidate(- [- _candidate(source="vector_grid", rows=2, cols=2, score=0.94),- _candidate(source="text_grid", rows=3, cols=3, score=0.92),- ]- )- is None- )---def test_verified_line_grid_wins_conflicting_text_topology() -> None:- """验证无歧义 drawing 网格以独立物理证据胜出异构文本候选。"""-- line = _candidate(- source="vector_grid",- rows=2,- cols=4,- score=1.0,- issues=(- "evidence=line_grid",- "ambiguous_separator_ratio=0.0000",- ),- )- text = _candidate(source="text_grid", rows=3, cols=4, score=1.0)-- assert _select_candidate([line, text]) is line---def test_verified_line_and_rect_topology_conflict_abstains() -> None:- """验证两类独立物理证据拓扑不一致时不由 line-grid 抢占。"""-- line = _candidate(- source="vector_grid",- rows=2,- cols=2,- score=1.0,- issues=(- "evidence=line_grid",- "ambiguous_separator_ratio=0.0000",- ),- )- rect = _candidate(- source="vector_grid",- rows=3,- cols=2,- score=1.0,- issues=(- "evidence=rect_grid",- "ambiguous_separator_ratio=0.0000",- ),- )-- assert _select_candidate([line, rect]) is None---def test_text_candidate_removes_significantly_undercounted_vector() -> None:- """验证稳定文本候选显著多出行列时剔除欠分割矢量候选。"""-- vector = _candidate(source="vector_grid", rows=2, cols=2, score=0.96)- text = _candidate(source="text_grid", rows=3, cols=3, score=0.93)-- assert _remove_undercounted_vector_candidates([vector, text]) == [text]---def test_verified_line_grid_is_not_removed_by_text_undercount() -> None:- """验证无歧义强物理网格不会被多 baseline 文本候选误判欠分割。"""-- vector = _candidate(- source="vector_grid",- rows=2,- cols=2,- score=0.96,- issues=(- "evidence=line_grid",- "ambiguous_separator_ratio=0.0000",- ),- )- text = _candidate(source="text_grid", rows=4, cols=3, score=0.93)-- assert _remove_undercounted_vector_candidates([vector, text]) == [vector, text]---def test_primitive_limit_falls_back_before_candidate_generation() -> None:- """验证单表原语超过保护上限时直接主动放弃。"""-- base = _aligned_text_input(- [- ["A", "B", "C"],- ["1", "2", "3"],- ["4", "5", "6"],- ]- )- rules = tuple(NativeTableRule((0.0, 1.0, 120.0, 2.0), 1.0, "horizontal") for _ in range(MAX_PRIMITIVES_PER_TABLE + 1))- table_input = NativeTableInput(- table_bbox=base.table_bbox,- page_size=base.page_size,- angle=base.angle,- chars=base.chars,- drawing_lines=rules,- )-- assert recover_native_pdf_table(table_input) is None- diagnostics = diagnose_native_pdf_table(table_input)- assert diagnostics["first_rejection_gate"] == "primitive_limit"- assert diagnostics["generated_candidates"] == []---def test_diagnostics_records_tracks_components_and_adoption() -> None:- """验证调试入口记录轨道、分项可靠度和最终采用状态。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 100.0, 60.0),- page_size=(100.0, 60.0),- angle=0,- chars=_char_items(- [- ("A", (10.0, 10.0, 15.0, 18.0)),- ("B", (60.0, 10.0, 65.0, 18.0)),- ("C", (10.0, 40.0, 15.0, 48.0)),- ("D", (60.0, 40.0, 65.0, 48.0)),- ]- ),- drawing_lines=_grid_rules(),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- assert diagnostics["first_rejection_gate"] is None- assert diagnostics["adopted"]["tracks"] == {"x": 3, "y": 3}- assert diagnostics["adopted"]["score_components"]["text_capture"] == 1.0- assert diagnostics["counterfactual_best"]["source"] == "vector_grid"- line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")- assert line_attempt["first_rejection_gate"] is None- assert line_attempt["grid"] == {"rows": 2, "cols": 2}---def test_sparse_multiline_recovers_keyed_long_records() -> None:- """验证连续关键行和右列续行会合并为稳定长文本记录。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 145.0),- page_size=(120.0, 145.0),- angle=0,- chars=_char_items(- [- ("Name", (5.0, 5.0, 21.0, 13.0)),- ("Detail", (45.0, 5.0, 69.0, 13.0)),- ("Alpha", (5.0, 20.0, 25.0, 28.0)),- ("Title A", (45.0, 20.0, 73.0, 28.0)),- ("(A1)", (5.0, 30.0, 21.0, 38.0)),- ("body a1", (45.0, 30.0, 73.0, 38.0)),- ("body a2", (45.0, 40.0, 73.0, 48.0)),- ("body a3", (45.0, 50.0, 73.0, 58.0)),- ("Beta", (5.0, 65.0, 21.0, 73.0)),- ("Title B", (45.0, 65.0, 73.0, 73.0)),- ("(B1)", (5.0, 75.0, 21.0, 83.0)),- ("body b1", (45.0, 75.0, 73.0, 83.0)),- ("body b2", (45.0, 85.0, 73.0, 93.0)),- ("body b3", (45.0, 95.0, 73.0, 103.0)),- ("Gamma", (5.0, 110.0, 25.0, 118.0)),- ("Title C", (45.0, 110.0, 73.0, 118.0)),- ("(C1)", (5.0, 120.0, 21.0, 128.0)),- ("body c1", (45.0, 120.0, 73.0, 128.0)),- ("body c2", (45.0, 130.0, 73.0, 138.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 144.0, 120.0, 145.0), 1.0, "horizontal"),- ),- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "sparse_multiline"- assert (result.rows, result.cols) == (4, 2)- assert "<td>Alpha(A1)</td><td>Title A body a1 body a2 body a3</td>" in result.html---def test_sparse_multiline_recovers_filled_record_continuations() -> None:- """验证填充行带和关键列可恢复含续行的三列记录表。"""-- rectangles = tuple(- NativeTableRectangle((left, top, right, bottom), 5, True, False)- for top, bottom in ((20.0, 36.0), (62.0, 78.0))- for left, right in ((0.0, 30.0), (30.0, 60.0), (60.0, 120.0))- )- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 100.0),- page_size=(120.0, 100.0),- angle=0,- chars=_char_items(- [- ("Date", (5.0, 5.0, 21.0, 13.0)),- ("From", (35.0, 5.0, 51.0, 13.0)),- ("Title", (65.0, 5.0, 85.0, 13.0)),- ("D1", (5.0, 22.0, 13.0, 30.0)),- ("S1", (35.0, 22.0, 43.0, 30.0)),- ("A", (65.0, 22.0, 69.0, 30.0)),- ("A2", (65.0, 32.0, 73.0, 40.0)),- ("D2", (5.0, 47.0, 13.0, 55.0)),- ("S2", (35.0, 47.0, 43.0, 55.0)),- ("B", (65.0, 47.0, 69.0, 55.0)),- ("D3", (5.0, 67.0, 13.0, 75.0)),- ("S3", (35.0, 67.0, 43.0, 75.0)),- ("C", (65.0, 67.0, 69.0, 75.0)),- ("C2", (65.0, 79.0, 73.0, 87.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 99.0, 120.0, 100.0), 1.0, "horizontal"),- ),- rectangles=rectangles,- )-- result = recover_native_pdf_table(table_input)-- assert result is not None- assert result.source == "sparse_multiline"- assert (result.rows, result.cols) == (4, 3)- assert "<td>D1</td><td>S1</td><td>AA2</td>" in result.html---def test_sparse_multiline_merges_one_level_multiline_header() -> None:- """验证没有局部分隔线时多条表头基线只形成一层表头。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 120.0),- page_size=(120.0, 120.0),- angle=0,- chars=_char_items(- [- ("Item", (5.0, 5.0, 21.0, 13.0)),- ("Value", (45.0, 5.0, 65.0, 13.0)),- ("Result", (85.0, 5.0, 109.0, 13.0)),- ("unit", (45.0, 16.0, 61.0, 24.0)),- ("flag", (85.0, 16.0, 101.0, 24.0)),- ("kg", (45.0, 27.0, 53.0, 35.0)),- ("ok", (85.0, 27.0, 93.0, 35.0)),- ("A", (5.0, 50.0, 9.0, 58.0)),- ("1", (45.0, 50.0, 49.0, 58.0)),- ("Y", (85.0, 50.0, 89.0, 58.0)),- ("B", (5.0, 75.0, 9.0, 83.0)),- ("2", (45.0, 75.0, 49.0, 83.0)),- ("N", (85.0, 75.0, 89.0, 83.0)),- ("C", (5.0, 100.0, 9.0, 108.0)),- ("3", (45.0, 100.0, 49.0, 108.0)),- ("Y", (85.0, 100.0, 89.0, 108.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 39.5, 120.0, 40.5), 1.0, "horizontal"),- NativeTableRule((0.0, 119.0, 120.0, 120.0), 1.0, "horizontal"),- ),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- multiline_attempt = diagnostics["sparse_multiline_attempts"][0]- assert multiline_attempt["first_rejection_gate"] is None- assert multiline_attempt["grid"] == {"rows": 4, "cols": 3}- assert multiline_attempt["header_rows"] == 1---def test_sparse_multiline_rejects_ambiguous_body_rowspan() -> None:- """验证无线正文首列空缺后再次出现时不猜测正文 rowspan。"""-- table_input = NativeTableInput(- table_bbox=(0.0, 0.0, 120.0, 100.0),- page_size=(120.0, 100.0),- angle=0,- chars=_char_items(- [- ("Model", (5.0, 5.0, 25.0, 13.0)),- ("Param", (45.0, 5.0, 65.0, 13.0)),- ("Value", (85.0, 5.0, 105.0, 13.0)),- ("A", (5.0, 35.0, 9.0, 43.0)),- ("p1", (45.0, 35.0, 53.0, 43.0)),- ("1", (85.0, 35.0, 89.0, 43.0)),- ("p2", (45.0, 55.0, 53.0, 63.0)),- ("2", (85.0, 55.0, 89.0, 63.0)),- ("B", (5.0, 75.0, 9.0, 83.0)),- ("p3", (45.0, 75.0, 53.0, 83.0)),- ("3", (85.0, 75.0, 89.0, 83.0)),- ]- ),- drawing_lines=(- NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),- NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),- NativeTableRule((0.0, 99.0, 120.0, 100.0), 1.0, "horizontal"),- ),- )-- diagnostics = diagnose_native_pdf_table(table_input)-- multiline_attempt = diagnostics["sparse_multiline_attempts"][0]- assert multiline_attempt["first_rejection_gate"] == ("ambiguous_body_rowspan")diff --git a/tests/unittest/test_native_pdf_table_manifest.py b/tests/unittest/test_native_pdf_table_manifest.pydeleted file mode 100644index a1868e21..00000000--- a/tests/unittest/test_native_pdf_table_manifest.py+++ /dev/null@@ -1,213 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""验证仓库内 Native PDF Table 真实语料、隐私和结构发布门。"""--from __future__ import annotations--import hashlib-import importlib.util-import json-import subprocess-import sys-from pathlib import Path-from typing import Any--import pytest-from pypdf import PdfReader---_PROJECT_ROOT = Path(__file__).parents[2]-_FIXTURE_ROOT = Path(__file__).parent / "pdfs" / "native_pdf_tables"-_EVALUATOR = _PROJECT_ROOT / "tests" / "fixtures" / "evaluate_native_pdf_table_manifest.py"-_EXPECTED_PAGE_COUNTS = {- "annual_report_fundraising_projects_table.pdf": 2,- "annual_report_management_roles_table.pdf": 2,- "annual_report_research_projects_table.pdf": 2,- "conference_schedule_tables.pdf": 12,- "engineering_process_restrictions_table.pdf": 9,- "fund_asset_and_transaction_tables.pdf": 2,- "fund_manager_profile_table.pdf": 2,- "manufacturing_facilities_cross_page_table.pdf": 2,- "pollutant_discharge_tables.pdf": 89,- "procurement_contract_tables.pdf": 2,- "procurement_document_blank_page_tables.pdf": 4,- "quarterly_report_financial_tables.pdf": 2,-}-_SENSITIVE_PROBE_HASHES = (- (14, "f467375e9c732abd34da5916ef67d09601fe5a160fc07e34eae45b40b92a66fd"),- (12, "14627c288df62a412eca1a27ed52b6126bf2958b4be4a67694dd7d1144937f11"),- (10, "9b2e4ae1fe4b64def12ddb3e1096c542a47a8278c789d321641dbef69e9711cd"),- (18, "df3f9bd04eb98a918d39eb50ff84d22d16296aa39297e2b6c93bc27d5ebd301f"),- (2, "a03f26ca7f4771eecaf858e1dced39d5213c3423084bafdb62d1086c382ae906"),- (3, "99bc11448af2388b7cdba8f712eab541b868931286bce3162703de572b27d97f"),- (11, "ed0491aea67e74b66b983ee86ee32f067693f7603812b66127fd8e4be79ebbdc"),-)---def _load_evaluator_module() -> Any:- """按文件路径加载 Native Table evaluator,供内部调用次数单测使用。"""-- spec = importlib.util.spec_from_file_location(- "_native_pdf_table_manifest_evaluator",- _EVALUATOR,- )- assert spec is not None and spec.loader is not None- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---def _contains_sensitive_probe_hash(text: str) -> bool:- """使用不可逆摘要检查已知敏感片段,避免把原文写入仓库。"""-- for length, expected_digest in _SENSITIVE_PROBE_HASHES:- if any(- hashlib.sha256(text[start : start + length].encode()).hexdigest() == expected_digest- for start in range(max(0, len(text) - length + 1))- ):- return True- return False---def test_native_table_skip_performance_runs_recovery_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 pytest 功能模式只恢复一次,不执行预热或计时。"""-- evaluator = _load_evaluator_module()- recover_calls: list[object] = []-- def fake_recover(table_input: object) -> dict[str, int]:- """记录一次恢复并返回可识别结果。"""-- recover_calls.append(table_input)- return {"call": len(recover_calls)}-- monkeypatch.setattr(evaluator, "recover_native_pdf_table", fake_recover)- monkeypatch.setattr(evaluator, "_result_signature", lambda result: result)-- actual, duration = evaluator._recover_table_input(- object(),- measure_performance=False,- )-- assert actual == {"call": 1}- assert duration == 0.0- assert len(recover_calls) == 1---def test_native_table_performance_mode_warms_and_times_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证显式性能模式保留一次预热和一次正式计时恢复。"""-- evaluator = _load_evaluator_module()- recover_calls: list[object] = []- counter = iter((10.0, 12.5))-- def fake_recover(table_input: object) -> dict[str, int]:- """记录预热和正式恢复。"""-- recover_calls.append(table_input)- return {"call": len(recover_calls)}-- monkeypatch.setattr(evaluator, "recover_native_pdf_table", fake_recover)- monkeypatch.setattr(evaluator, "_result_signature", lambda result: result)- monkeypatch.setattr(evaluator.time, "perf_counter", lambda: next(counter))-- actual, duration = evaluator._recover_table_input(- object(),- measure_performance=True,- )-- assert actual == {"call": 2}- assert duration == 2.5- assert len(recover_calls) == 2---def test_native_table_diagnostics_are_lazy(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证候选诊断仅在显式请求或结果不匹配时执行。"""-- evaluator = _load_evaluator_module()- diagnose_calls: list[object] = []-- def fake_diagnose(table_input: object) -> dict[str, bool]:- """记录惰性诊断调用。"""-- diagnose_calls.append(table_input)- return {"diagnosed": True}-- monkeypatch.setattr(evaluator, "diagnose_native_pdf_table", fake_diagnose)- table_input = object()-- assert evaluator._maybe_diagnose_table_input(- table_input,- collect_diagnostics=False,- mismatch=False,- ) is None- assert evaluator._maybe_diagnose_table_input(- table_input,- collect_diagnostics=True,- mismatch=False,- ) == {"diagnosed": True}- assert evaluator._maybe_diagnose_table_input(- table_input,- collect_diagnostics=False,- mismatch=True,- ) == {"diagnosed": True}- assert diagnose_calls == [table_input, table_input]---def test_repository_native_table_manifest_matches_all_fixtures() -> None:- """验证仓库内 133 表真值及六个 Flash 精确目标全部匹配。"""-- completed = subprocess.run(- [- sys.executable,- str(_EVALUATOR),- "--skip-performance-gate",- ],- cwd=_PROJECT_ROOT,- check=False,- capture_output=True,- text=True,- )- assert completed.returncode == 0, completed.stdout + completed.stderr- payload = json.loads(completed.stdout)- assert payload["summary"] | {- "p95_milliseconds": 0.0,- } == {- "accuracy_scope": "targeted_only",- "tables": 133,- "html": 133,- "coverage": 1.0,- "target_tables": 41,- "target_html": 41,- "target_mismatches": 0,- "target_precision": 1.0,- "regression_mismatches": 0,- "flash_targets": 6,- "flash_target_html": 6,- "flash_target_mismatches": 0,- "p95_milliseconds": 0.0,- }---def test_repository_native_table_fixtures_are_sanitized() -> None:- """验证文件清单、页数、文档信息和污染物敏感字段均符合提交边界。"""-- fixture_paths = sorted(_FIXTURE_ROOT.glob("*.pdf"))- assert {path.name for path in fixture_paths} == set(_EXPECTED_PAGE_COUNTS)- for path in fixture_paths:- reader = PdfReader(path)- assert len(reader.pages) == _EXPECTED_PAGE_COUNTS[path.name]- assert not reader.metadata- assert reader.xmp_metadata is None- assert reader.trailer.get("/Info") is None- assert "/Metadata" not in reader.root_object- assert all("/Metadata" not in page for page in reader.pages)-- pollutant_reader = PdfReader(_FIXTURE_ROOT / "pollutant_discharge_tables.pdf")- visible_text = "".join("".join((page.extract_text() or "").split()) for page in pollutant_reader.pages)- assert not _contains_sensitive_probe_hash(visible_text)diff --git a/tests/unittest/test_native_pdf_table_pipeline.py b/tests/unittest/test_native_pdf_table_pipeline.pyindex 48e8801f..e2d9eb00 100644--- a/tests/unittest/test_native_pdf_table_pipeline.py+++ b/tests/unittest/test_native_pdf_table_pipeline.py@@ -10,20 +10,15 @@ from unittest.mock import MagicMockimport numpy as npimport pytest+from docvortex.document.pdf.document import PDFDocument, PDFPageTextGeometryfrom PIL import Imagefrom mineru.backend.analysis.pdf import formulas as pdf_formulasfrom mineru.backend.analysis.pdf import layout as pdf_layoutfrom mineru.backend.analysis.pdf import tables as pdf_tablesfrom mineru.backend.analysis.pdf import window as pdf_window-from docvortex.analyzers.native.pdf import models as flash_models-from docvortex.analyzers.native.pdf import tables as flash_tables-from docvortex.analyzers.native.pdf import table_materialization-from docvortex.document.pdf.document import PDFDocument-from docvortex.document.pdf.document import PDFPageTextGeometryfrom mineru.types import RAW_FORMULA_NUMBER, BlockType-_PROJECT_ROOT = Path(__file__).parents[2]@@ -43,50 +38,6 @@ def _build_native_pdf_page(*, width: float = 100.0, height: float = 100.0) -> Mareturn page-def test_flash_materialization_prefers_native_html_and_keeps_claims(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Flash 只替换表体 content,不改变候选认领语义。"""-- source = flash_models._PageSource(- page_size=(100.0, 100.0),- lines=[- flash_models._LineItem(- text="A B",- bbox=(10.0, 20.0, 80.0, 30.0),- angle=0,- source_index=7,- effective_height=10.0,- )- ],- chars=[],- drawing_lines=[],- )- candidate = flash_models._TableCandidate(- bbox=(0.0, 10.0, 90.0, 40.0),- local_bbox=(0.0, 10.0, 90.0, 40.0),- angle=0,- score=1.0,- core_bbox=(0.0, 10.0, 90.0, 40.0),- line_indices={7},- )- html = "<table><tbody><tr><td>A</td><td>B</td></tr></tbody></table>"- projection = MagicMock(return_value="fallback")- monkeypatch.setattr(table_materialization, "_recover_native_table_html", MagicMock(return_value=html))- monkeypatch.setattr(table_materialization, "project_pdf_table_text", projection)-- blocks, annotations, claimed = flash_tables._materialize_table_blocks(- source,- [candidate],- )-- assert annotations == []- assert claimed == {7}- assert blocks[0]["content"] == html- assert "cell_merge" not in blocks[0]- projection.assert_not_called()--def test_flash_ocr_projects_table_text(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/unittest/test_pdf_native_script_detection.py b/tests/unittest/test_pdf_native_script_detection.pyindex 2af98563..9678333d 100644--- a/tests/unittest/test_pdf_native_script_detection.py+++ b/tests/unittest/test_pdf_native_script_detection.py@@ -7,21 +7,17 @@ from dataclasses import dataclassfrom pathlib import Pathimport pytest-from docvortex.document.pdf.text.contracts import Bbox-from docvortex.document.pdf.text.contracts import Char+from docvortex.analyzers.native.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY+from docvortex.document.pdf.document import PDFDocument, get_lines_from_chars+from docvortex.document.pdf.text.contracts import Bbox, Charfrom mineru.backend.analysis.pdf.text import nativefrom mineru.backend.analysis.pdf.text.models import _AnalyzeSpan-from docvortex.document.pdf.document import PDFDocument-from docvortex.document.pdf.document import get_lines_from_chars-from docvortex.analyzers.native.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEYfrom mineru.types import BBox, ContentType-_PROJECT_ROOT = Path(__file__).resolve().parents[2]_DEMO_PDF_DIR = _PROJECT_ROOT / "demo" / "pdfs"_ZH_2_SOURCE = "中文论文2.pdf"-_FIXTURE_PDF_DIR = Path(__file__).resolve().parent / "pdfs"_PDF_CONTROL_CHARS = {"\r", "\n", "\x02", "\ufffe", "\uffff"}@@ -183,6 +179,21 @@ def _render_demo_line(source_name: str, page_index: int, probe: str) -> str:return _render_chars(_demo_chars(source_name, page_index, probe))+def _residual_script_case(source_name: str, probe: str = "") -> tuple[dict, list[_ScriptFixture]]:+ """读取残留 PDF 的原始字符快照,保持 Hybrid 输入与几何证据不变。"""+ payload = json.loads((_PROJECT_ROOT / "tests/fixtures/hybrid_pdf_script_inputs.json").read_text(encoding="utf-8"))+ case = next(case for case in payload["cases"] if Path(case["source"]).name == source_name and case["probe"] == probe)+ fragments = [+ _ScriptFixture(+ chars=[{**char, "bbox": Bbox(char["bbox"])} for char in fragment["chars"]],+ tight_bboxes={int(key): tuple(value) for key, value in fragment["tight_bboxes"].items()},+ origins={int(key): tuple(value) for key, value in fragment["origins"].items()},+ )+ for fragment in case["fragments"]+ ]+ return case, fragments++def _script_char(index: int,text: str,@@ -1004,11 +1015,7 @@ def test_synthetic_cjk_plain_text_does_not_gain_script_tags() -> None:"""验证合成项目符号、混合字体和文件名降部字符不会触发上下标误判。"""- matching_lines = _lines_chars_containing(- _FIXTURE_PDF_DIR / "native_cjk_layout_synthetic.pdf",- 2,- probe,- )+ _, matching_lines = _residual_script_case("native_cjk_layout_synthetic.pdf", probe)contents = [_render_chars(chars) for chars in matching_lines]font_names = {str((char.get("font") or {}).get("name", "")) for fixture in matching_lines for char in fixture.chars}@@ -1019,26 +1026,11 @@ def test_synthetic_cjk_plain_text_does_not_gain_script_tags(def test_rotated_powerpoint_page_keeps_all_plain_text_on_baseline() -> None:"""验证 PowerPoint 旋转页的紧字形框不会把普通升部和降部误判为上下标。"""- pdf_path = _FIXTURE_PDF_DIR / "metabolic_pathway_page_3.pdf"- with PDFDocument(str(pdf_path)) as document:- page = document[0]- page_rotation = page.rotation- geometry = page.get_chars_with_geometry()- lines = get_lines_from_chars(geometry.chars)-- rendered_lines = [- _render_chars(- _ScriptFixture(- chars=[char for span in line["spans"] for char in span.get("chars", [])],- tight_bboxes=geometry.tight_bboxes,- origins=geometry.origins,- )- )- for line in lines- ]+ case, fragments = _residual_script_case("metabolic_pathway_page_3.pdf")+ rendered_lines = [_render_chars(fragment) for fragment in fragments]- assert page_rotation == 90- assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for char in geometry.chars)+ assert case["page_rotation"] == 90+ assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for fragment in fragments for char in fragment.chars)assert len(rendered_lines) == 33assert rendered_lines[0] == "Energy Metabolism"assert all("<sup>" not in content and "<sub>" not in content for content in rendered_lines)diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.pydeleted file mode 100644index a060a9de..00000000--- a/tests/unittest/test_pdf_render.py+++ /dev/null@@ -1,547 +0,0 @@-from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata--from concurrent.futures import ThreadPoolExecutor-from copy import deepcopy-from io import BytesIO-from unittest.mock import MagicMock-import base64--from bs4 import BeautifulSoup-from PIL import Image-from pypdf import PdfReader-import pytest-from reportlab.graphics.shapes import Drawing-import ziamath--from _span_test_utils import inline as _inline-from mineru.render import render_pdf-from docvortex.render._internal.pdf import assets as pdf_assets-from docvortex.render._internal.pdf import formula as formula_module-from docvortex.render._internal.pdf.formula import FormulaRenderer-from docvortex.render._internal.pdf.formula import FormulaVector-from docvortex.render._internal.pdf.formula import PdfFormulaError-from docvortex.render._internal.pdf.table import _html_cell_spans-from mineru.types import (- AlgorithmBodyBlock,- ChartAnnotationBlock,- ChartBlock,- ChartBodyBlock,- CodeBlock,- CodeBodyBlock,- DocTitleBlock,- EquationBlock,- ImageBlock,- ImageBodyBlock,- IndexBlock,- ListBlock,- MiddleJson,- PageAuxTextBlock,- PageBlock,- PageFootnoteBlock,- PageInfo,- ParagraphTitleBlock,- TableBlock,- TextBlock,-)---def _middle(*pages: PageInfo) -> MiddleJson:- """构造无需源坐标布局的严格测试 MiddleJson。"""- return MiddleJson(- pages=list(pages),- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:- """按调用方顺序构造一页测试内容。"""- return PageInfo(page_idx=page_idx, blocks=list(blocks))---def _png_bytes(size: tuple[int, int] = (20, 10)) -> bytes:- """生成可由 Pillow、ReportLab 与 pypdf 测试读取的 PNG。"""- output = BytesIO()- Image.new("RGB", size, (30, 80, 130)).save(output, format="PNG")- return output.getvalue()---def _png_uri() -> str:- """返回有效 PNG data URI。"""- return f"data:image/png;base64,{base64.b64encode(_png_bytes()).decode('ascii')}"---def _reader(payload: bytes) -> PdfReader:- """从内存 bytes 打开 PDF 并先验证固定签名。"""- assert payload.startswith(b"%PDF-")- return PdfReader(BytesIO(payload))---def _page_text(reader: PdfReader, page_index: int) -> str:- """提取指定 PDF 页的可搜索文字。"""- return reader.pages[page_index].extract_text() or ""---def test_pdf_uses_default_planner_without_source_page_boundaries() -> None:- """验证固定默认 PDF 合并续段、隐藏辅助块、折叠空源页且输入不变。"""- middle = _middle(- _page(- 0,- PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),- TextBlock(type="text", index=1, content=_inline("inter-")),- ),- _page(5),- _page(- 9,- TextBlock(type="text", index=0, content=_inline("national"), continues_prev=True),- PageAuxTextBlock(type="footer", index=1, content=_inline("FOOTER")),- ),- )- original = deepcopy(middle)-- payload = render_pdf(middle, document_title="PDF Contract")- assert payload == render_pdf(middle, document_title="PDF Contract")- reader = _reader(payload)-- assert len(reader.pages) == 1- assert "international" in _page_text(reader, 0).replace("\n", "")- assert "HEADER" not in _page_text(reader, 0) and "FOOTER" not in _page_text(reader, 0)- assert reader.metadata.title == "PDF Contract"- assert reader.metadata.creation_date is not None and reader.metadata.creation_date.year == 2000- assert middle == original---def test_pdf_renders_inline_and_display_formulas_as_vector_paths_with_links() -> None:- """验证行内/行间公式矢量化、标签、中文混排及内外部链接。"""- middle = _middle(- _page(- 0,- ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="section-one", content=_inline("章节一")),- TextBlock(- type="text",- index=1,- content=[- {"type": "text", "content": "中文 Before "},- {"type": "equation_inline", "content": r"c=\pm\sqrt{a^2+b^2}"},- {"type": "text", "content": " after "},- {"type": "hyperlink", "url": "#section-one", "content": _inline("jump")},- {"type": "text", "content": " and "},- {"type": "hyperlink", "url": "https://example.com", "content": _inline("external")},- ],- ),- EquationBlock(type="equation", index=2, content=r"\frac{1}{1-x^2}\tag{7}"),- )- )-- reader = _reader(render_pdf(middle))- text = _page_text(reader, 0)- resources = reader.pages[0]["/Resources"]- xobjects = resources.get("/XObject", {})- image_xobjects = [value for value in xobjects.values() if value.get_object().get("/Subtype") == "/Image"]-- assert "章节一" in text and "中文 Before" in text and "after" in text- assert "jump" in text and "external" in text- assert not image_xobjects- assert len(reader.pages[0].get("/Annots", [])) >= 2- stream = reader.pages[0].get_contents().get_data()- assert b" m" in stream and (b" c" in stream or b" l" in stream)---def test_pdf_unicode_fallback_and_script_styles_avoid_black_squares() -> None:- """验证 Latin Extended、独立重音、希腊文和西里尔文使用确定性字体回退。"""- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "Jędrzej J˛edrzej λ Ж 中文 x"},- {"type": "text", "content": "2", "styles": ["superscript"]},- ],- ),- )- )-- reader = _reader(render_pdf(middle))- text = _page_text(reader, 0)- stream = reader.pages[0].get_contents().get_data()-- assert "Jędrzej J˛edrzej λ Ж 中文 x2" in text.replace("\n", "")- assert "■" not in text- assert b" Ts" in stream---def test_pdf_formula_failures_fall_back_to_visible_latex(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 ZiaMath 失败时行内与行间公式均保留可见 LaTeX。"""- original_render = FormulaRenderer.render-- def fail_bad_formula(- self: FormulaRenderer,- latex: str,- *,- inline: bool,- font_size: float,- color: str = "#1f2937",- ) -> object:- """仅让测试公式进入稳定回退,其余公式沿用真实实现。"""- if latex == "bad":- raise PdfFormulaError("synthetic formula failure")- return original_render(self, latex, inline=inline, font_size=font_size, color=color)-- monkeypatch.setattr(FormulaRenderer, "render", fail_bad_formula)- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[{"type": "text", "content": "inline "}, {"type": "equation_inline", "content": "bad"}],- ),- EquationBlock(type="equation", index=1, content="bad"),- )- )-- text = _page_text(_reader(render_pdf(middle)), 0)-- assert "$bad$" in text- assert "bad" in text--- "source,inline",- [- (r"\frac{1}{1-x^2}", False),- (r"\sqrt[3]{x+y}", True),- (r"\sum_{i=1}^{n} i^2", False),- (r"\int_0^\infty e^{-x}\,dx", False),- (r"\begin{bmatrix}a&b\\c&d\end{bmatrix}", False),- (r"\left(\frac{x}{y}\right)^2", True),- (r"\begin{aligned}a&=b+c\\d&=e\end{aligned}", False),- (r"\color{red}{x}+\boxed{y}", True),- ],-)-def test_ziamath_vector_corpus_covers_inline_and_display_constructs(source: str, inline: bool) -> None:- """验证分数、根式、积分、矩阵、aligned 与颜色均能生成有效矢量几何。"""- vector = FormulaRenderer().render(source, inline=inline, font_size=12)-- assert vector.width > 0 and vector.height > 0- assert vector.ascent >= 0 and vector.descent >= 0- assert vector.drawing.contents---def test_formula_cache_is_bounded_and_rejects_oversized_entries(monkeypatch: pytest.MonkeyPatch) -> None:- """验证超长公式在 ZiaMath 前失败,唯一项超过预算时不扩张缓存。"""- calls: list[str] = []-- def fake_render(latex: str, *, inline: bool, font_size: float, color: str) -> FormulaVector:- """返回固定矢量并记录实际转换次数。"""- calls.append(latex)- return FormulaVector(Drawing(1, 1), width=1, height=1, ascent=1, descent=0)-- monkeypatch.setattr(formula_module, "_render_ziamath_formula", fake_render)- renderer = FormulaRenderer()- oversized = "x" * (formula_module.MAX_FORMULA_CHARACTERS + 1)- with pytest.raises(PdfFormulaError, match="max_formula_characters"):- renderer.render(oversized, inline=True, font_size=10)- for index in range(formula_module.MAX_CACHED_FORMULAS + 3):- renderer.render(f"x_{index}", inline=True, font_size=10)-- assert oversized not in calls- assert len(renderer._cache) == formula_module.MAX_CACHED_FORMULAS # noqa: SLF001---def test_long_formulas_scale_or_wrap_without_hiding_surrounding_text() -> None:- """验证超宽行内与行间公式缩放后仍保留前后可搜索正文。"""- formula = "+".join(f"x_{index}^2" for index in range(45))- middle = _middle(- _page(- 0,- TextBlock(- type="text",- index=0,- content=[- {"type": "text", "content": "before long formula "},- {"type": "equation_inline", "content": formula},- {"type": "text", "content": " after long formula"},- ],- ),- EquationBlock(type="equation", index=1, content=formula + r"\tag{wide}"),- )- )-- reader = _reader(render_pdf(middle))- text = "\n".join(_page_text(reader, index) for index in range(len(reader.pages)))-- assert "before long formula" in text- assert "after long formula" in text---def test_pdf_uses_asset_resolver_and_replaces_missing_or_remote_images_with_placeholders() -> None:- """验证 sidecar 优先级、有效图片、损坏素材和远程 URL 的宽松占位策略。"""- requested: list[str] = []-- def resolve_asset(path: str) -> bytes:- """记录图片请求,并分别返回有效或损坏字节。"""- requested.append(path)- return _png_bytes() if path == "images/ok.png" else b"broken"-- middle = _middle(- _page(- 0,- ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="valid image",- image_path="images/ok.png",- image_base64=_png_uri(),- )- ],- ),- ImageBlock(- type="image",- index=1,- content=[- ImageBodyBlock(- type="image_body",- index=1,- content="external svg",- image_base64=(- "data:image/svg+xml;base64,"- + base64.b64encode(- b'<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>'- ).decode("ascii")- ),- )- ],- ),- ImageBlock(- type="image",- index=2,- content=[- ImageBodyBlock(- type="image_body",- index=2,- content="broken image",- image_path="images/broken.png",- )- ],- ),- ImageBlock(- type="image",- index=3,- content=[- ImageBodyBlock(- type="image_body",- index=3,- content="remote image",- image_url="https://example.com/image.png",- )- ],- ),- )- )-- reader = _reader(render_pdf(middle, asset_resolver=resolve_asset))- text = _page_text(reader, 0)-- assert requested == ["images/ok.png", "images/broken.png"]- assert text.count("image unavailable") == 3- assert "https://example.com/image.png" in text- assert "page_idx=0, block_index=2, block_type=image_body" in text---def test_pdf_oversized_image_uses_placeholder_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 PDF 超限 raster 在 load 前转为现有宽松 placeholder。"""- image = MagicMock()- image.__enter__.return_value = image- image.format = "PNG"- image.size = (4_001, 4_000)- image.load.side_effect = AssertionError("oversized image must not be decoded")- monkeypatch.setattr(pdf_assets.Image, "open", lambda _source: image)- middle = _middle(- _page(- 0,- ImageBlock(- type="image",- index=0,- content=[- ImageBodyBlock(- type="image_body",- index=0,- content="Oversized image",- image_path="images/oversized.png",- )- ],- ),- )- )-- reader = _reader(render_pdf(middle, asset_resolver=lambda _path: b"oversized"))-- assert "image unavailable" in _page_text(reader, 0)- image.load.assert_not_called()---def test_pdf_oversized_image_bytes_are_rejected_before_pillow(monkeypatch: pytest.MonkeyPatch) -> None:- """验证 PDF 在 Pillow 识别前拒绝超过固定字节预算的图片。"""- open_image = MagicMock(side_effect=AssertionError("oversized image must not reach Pillow"))- monkeypatch.setattr(pdf_assets, "MAX_IMAGE_PAYLOAD_BYTES", 8)- monkeypatch.setattr(pdf_assets.Image, "open", open_image)-- with pytest.raises(pdf_assets.PdfAssetError, match="Image payload exceeds its byte limit"):- pdf_assets.prepare_image_bytes(b"oversized")-- open_image.assert_not_called()---def test_pdf_table_parser_preserves_standard_inline_style_tags() -> None:- """验证 PDF 表格解析器把标准 HTML 标签恢复为结构化文字样式。"""- soup = BeautifulSoup(- "<td><strong>bold</strong><em>italic</em><u>under</u><s>strike</s><sup>sup</sup><sub>sub</sub></td>",- "html.parser",- )- cell = soup.td- assert cell is not None-- spans = _html_cell_spans(cell)-- assert [(span.content, list(getattr(span, "styles", []))) for span in spans] == [- ("bold", ["bold"]),- ("italic", ["italic"]),- ("under", ["underline"]),- ("strike", ["strikethrough"]),- ("sup", ["superscript"]),- ("sub", ["subscript"]),- ]---def test_pdf_renders_tables_lists_indices_code_algorithm_and_annotations() -> None:- """验证原生表格合并、嵌套表、目录、列表、代码算法与说明的组合输出。"""- table = TableBlock.model_validate(- {- "type": "table",- "index": 2,- "content": [- {- "type": "table_body",- "index": 2,- "content": (- "<table><thead><tr><th colspan='2'>Header</th></tr></thead>"- "<tbody><tr><td rowspan='2'>A<eq>x^2</eq></td><td>B</td></tr>"- "<tr><td><table><tr><td>Nested</td></tr></table></td></tr></tbody></table>"- ),- },- {"type": "table_caption", "content": _inline("Table caption")},- {"type": "table_footnote", "content": _inline("Table note")},- ],- }- )- index = IndexBlock(- type="index",- index=1,- content=[ParagraphTitleBlock(type="paragraph_title", level=2, anchor="target", content=_inline("Target\t9"))],- )- code = CodeBlock(- type="code",- index=3,- sub_type="code",- guess_lang="python",- content=[- CodeBodyBlock(type="code_body", index=3, content="print('中文')\nprint(2)"),- {"type": "code_caption", "content": _inline("Code caption")},- ],- )- algorithm = CodeBlock(- type="code",- index=4,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=4,- content=[{"type": "text", "content": "for "}, {"type": "equation_inline", "content": "n^2"}],- )- ],- )- chart = ChartBlock(- type="chart",- index=5,- sub_type="bar",- content=[- ChartBodyBlock(type="chart_body", index=5, content="<table><tr><th>Year</th></tr><tr><td>2026</td></tr></table>"),- ChartAnnotationBlock(type="chart_caption", content=_inline("Chart caption")),- ],- )- middle = _middle(- _page(- 0,- ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="target", content=_inline("Target")),- index,- table,- code,- algorithm,- chart,- ListBlock(type="list", index=6, content=[TextBlock(type="text", content=_inline("1. item"))]),- PageFootnoteBlock(type="page_footnote", index=7, anchor="note", content=_inline("Page note")),- )- )-- reader = _reader(render_pdf(middle))- text = "\n".join(_page_text(reader, index) for index in range(len(reader.pages)))-- for expected in (- "Target",- "Header",- "Nested",- "Table caption",- "Table note",- "print('中文')",- "Code caption",- "Year",- "2026",- "Chart caption",- "1. item",- "Page note",- ):- assert expected in text---def test_pdf_formula_configuration_is_restored_across_parallel_renders() -> None:- """验证并行 PDF 公式渲染不会泄漏 ZiaMath 的进程级 svg2 配置。"""- previous_svg2 = ziamath.config.svg2- middle = _middle(- _page(- 0,- DocTitleBlock(type="doc_title", index=0, level=1, content=_inline("Parallel")),- EquationBlock(type="equation", index=1, content=r"\sum_{i=1}^{n} i^2"),- )- )-- with ThreadPoolExecutor(max_workers=2) as executor:- outputs = list(executor.map(lambda _index: render_pdf(middle), range(4)))-- assert all(_reader(payload).pages for payload in outputs)- assert ziamath.config.svg2 is previous_svg2---def test_pdf_public_arguments_remain_strict() -> None:- """验证专用 PDF 门面拒绝旧 dict、已删除 mode 与错误参数类型。"""- middle = _middle(_page(0))-- with pytest.raises(TypeError, match="MiddleJson"):- render_pdf(middle.to_dict()) # type: ignore[arg-type]- with pytest.raises(TypeError, match="unexpected keyword argument 'mode'"):- render_pdf(middle, mode="full") # type: ignore[arg-type]- with pytest.raises(TypeError, match="asset_resolver"):- render_pdf(middle, asset_resolver="images") # type: ignore[arg-type]- with pytest.raises(TypeError, match="document_title"):- render_pdf(middle, document_title=1) # type: ignore[arg-type]diff --git a/tests/unittest/test_pdf_render_diagnostics.py b/tests/unittest/test_pdf_render_diagnostics.pydeleted file mode 100644index 3f3054fc..00000000--- a/tests/unittest/test_pdf_render_diagnostics.py+++ /dev/null@@ -1,201 +0,0 @@-from __future__ import annotations--from concurrent.futures import ALL_COMPLETED, Future, ProcessPoolExecutor-from typing import Any, cast--import pytest-from loguru import logger--from docvortex.document.pdf import images as pdf_image_tools---class _FakeProcess:- def __init__(self, pid: int | None, *, alive: bool, exit_code: int | None) -> None:- self.pid = pid- self.exitcode = exit_code- self._alive = alive-- def is_alive(self) -> bool:- return self._alive---class _FakeExecutor:- def __init__(self, processes: list[_FakeProcess]) -> None:- self._processes = {process.pid: process for process in processes}---def _capture_log_messages() -> tuple[list[str], int]:- messages: list[str] = []- handler_id = logger.add(lambda message: messages.append(str(message)), level="DEBUG", format="{message}")- return messages, handler_id---def test_pdf_render_worker_exits_after_parent_process(monkeypatch: pytest.MonkeyPatch) -> None:- events: list[object] = []-- class _ParentProcess:- def join(self) -> None:- events.append("parent.join")-- monkeypatch.setattr(pdf_image_tools.multiprocessing, "parent_process", _ParentProcess)- monkeypatch.setattr(pdf_image_tools.os, "_exit", lambda code: events.append(("exit", code)))-- pdf_image_tools._exit_pdf_render_worker_when_parent_exits()-- assert events == ["parent.join", ("exit", 1)]---def test_pdf_render_worker_without_multiprocessing_parent_does_not_exit(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(pdf_image_tools.multiprocessing, "parent_process", lambda: None)- monkeypatch.setattr(pdf_image_tools.os, "_exit", lambda code: pytest.fail(f"unexpected exit {code}"))-- pdf_image_tools._exit_pdf_render_worker_when_parent_exits()---def test_pdf_render_executor_installs_parent_exit_watcher(monkeypatch: pytest.MonkeyPatch) -> None:- """渲染 worker 同时安装父进程监控和固定字体,监控优先以覆盖初始化失败。"""- events: list[str] = []- monkeypatch.setattr(pdf_image_tools, "_install_pdf_render_parent_exit_watcher", lambda: events.append("watcher"))- monkeypatch.setattr(pdf_image_tools, "initialize_pdfium_runtime", lambda: events.append("fonts"))- executor = pdf_image_tools._create_pdf_render_executor(max_workers=1)- try:- assert executor._initializer is pdf_image_tools._initialize_pdf_render_worker- executor._initializer()- assert events == ["watcher", "fonts"]- finally:- executor.shutdown(wait=True, cancel_futures=True)---def test_pdf_render_parent_exit_watcher_is_daemon(monkeypatch: pytest.MonkeyPatch) -> None:- events: list[object] = []-- class _Thread:- def __init__(self, *, target: Any, name: str, daemon: bool) -> None:- events.append((target, name, daemon))-- def start(self) -> None:- events.append("start")-- monkeypatch.setattr(pdf_image_tools.threading, "Thread", _Thread)- pdf_image_tools._install_pdf_render_parent_exit_watcher()-- assert events == [- (- pdf_image_tools._exit_pdf_render_worker_when_parent_exits,- "docvortex-pdf-render-parent-exit-watcher",- True,- ),- "start",- ]---def test_pdf_render_future_states_cover_terminal_and_active_states() -> None:- pending: Future[Any] = Future()- running: Future[Any] = Future()- assert running.set_running_or_notify_cancel()- done: Future[Any] = Future()- done.set_result([])- cancelled: Future[Any] = Future()- assert cancelled.cancel()-- states = pdf_image_tools._get_pdf_render_future_states(- {- pending: (0, 0),- running: (1, 2),- done: (3, 3),- cancelled: (4, 5),- }- )-- assert states == [- {"pages": "1-1", "state": "pending"},- {"pages": "2-3", "state": "running"},- {"pages": "4-4", "state": "done"},- {"pages": "5-6", "state": "cancelled"},- ]---def test_pdf_render_worker_states_include_pid_liveness_and_exit_code() -> None:- executor = cast(- ProcessPoolExecutor,- _FakeExecutor(- [- _FakeProcess(42, alive=False, exit_code=1),- _FakeProcess(7, alive=True, exit_code=None),- ]- ),- )-- assert pdf_image_tools._get_pdf_render_worker_states(executor) == [- {"pid": 7, "alive": True, "exit_code": None},- {"pid": 42, "alive": False, "exit_code": 1},- ]---def test_pdf_render_worker_logs_start_and_completion(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(pdf_image_tools, "load_images_from_pdf_core", lambda *args: [{"scale": 1.0}])- messages, handler_id = _capture_log_messages()- try:- result = pdf_image_tools._load_images_from_pdf_worker(b"pdf", 200, 0, 0, pdf_image_tools.ImageType.PIL)- finally:- logger.remove(handler_id)-- assert result == [{"scale": 1.0}]- assert any("PDF render worker started:" in message and "pages=1-1" in message for message in messages)- assert any("PDF render worker completed:" in message and "images=1" in message for message in messages)---def test_pdf_render_worker_logs_exception(monkeypatch: pytest.MonkeyPatch) -> None:- def fail_render(*args: Any) -> list[dict[str, Any]]:- raise RuntimeError("render failed")-- monkeypatch.setattr(pdf_image_tools, "load_images_from_pdf_core", fail_render)- messages, handler_id = _capture_log_messages()- try:- with pytest.raises(RuntimeError, match="render failed"):- pdf_image_tools._load_images_from_pdf_worker(b"pdf", 200, 0, 0, pdf_image_tools.ImageType.PIL)- finally:- logger.remove(handler_id)-- assert any("PDF render worker failed:" in message and "pages=1-1" in message for message in messages)---def test_pdf_render_timeout_logs_future_and_worker_states(monkeypatch: pytest.MonkeyPatch) -> None:- executor = cast(- ProcessPoolExecutor,- _FakeExecutor([_FakeProcess(314, alive=False, exit_code=9)]),- )- future: Future[Any] = Future()- recycled: list[tuple[ProcessPoolExecutor | None, bool]] = []-- def fake_wait(- futures: list[Future[Any]],- timeout: int | None,- return_when: str,- ) -> tuple[set[Future[Any]], set[Future[Any]]]:- assert futures == [future]- assert timeout == 0- assert return_when == ALL_COMPLETED- return set(), {future}-- def fake_recycle(candidate: ProcessPoolExecutor | None, *, terminate_processes: bool) -> None:- recycled.append((candidate, terminate_processes))-- monkeypatch.setattr(pdf_image_tools, "_get_pdf_render_executor", lambda: executor)- monkeypatch.setattr(pdf_image_tools, "_submit_pdf_render_task", lambda *args, **kwargs: future)- monkeypatch.setattr(pdf_image_tools, "wait", fake_wait)- monkeypatch.setattr(pdf_image_tools, "_recycle_pdf_render_executor", fake_recycle)-- messages, handler_id = _capture_log_messages()- try:- with pytest.raises(TimeoutError, match="timeout after 0s"):- pdf_image_tools.load_images_from_pdf_bytes_range(b"pdf", start_page_id=0, end_page_id=0, timeout=0, threads=1)- finally:- logger.remove(handler_id)-- timeout_message = next(message for message in messages if "PDF image rendering timed out:" in message)- assert "'state': 'pending'" in timeout_message- assert "'pid': 314" in timeout_message- assert "'alive': False" in timeout_message- assert "'exit_code': 9" in timeout_message- assert recycled == [(executor, True)]diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.pyindex 2cac3c3b..3b99bba7 100644--- a/tests/unittest/test_pdf_text_styles.py+++ b/tests/unittest/test_pdf_text_styles.py@@ -1,76 +1,29 @@from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadataimport html-import math-from io import BytesIO-from types import SimpleNamespace-from collections.abc import Sequencefrom typing import Anyfrom unittest.mock import MagicMock-from zipfile import ZipFileimport pytest+from _span_test_utils import inline_text+from docvortex.analyzers.native.pdf.text_styles import (+ PDFTextLinkLine,+ PDFTextLinkRange,+ PDFTextScriptLine,+ PDFTextScriptRange,+ PDFTextStyleLine,+ PDFTextStyleRange,+)+from docvortex.document.pdf.document import PDFPageTextGeometryfrom mineru.backend.analysis.pdf.text import content as text_contentfrom mineru.backend.analysis.pdf.text import styles as text_style_enrichmentfrom mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpanfrom mineru.backend.analysis.pdf.text.native import txt_spans_extract-from docvortex.postprocess.pages import model_json_to_pages-from docvortex.analyzers.native import PdfModel-from docvortex.analyzers.native.pdf.inline import matching as inline_matching-from docvortex.analyzers.native.pdf import models-from docvortex.analyzers.native.pdf import native_text-from docvortex.analyzers.native.pdf import text_styles as flash_text_styles-from mineru.render import render_docx, render_html, render_markdownfrom mineru.types import (- RAW_CAPTION,- RAW_FOOTNOTE,BlockType,ContentType,- MiddleJson,- ModelJson,)-from docvortex.document.pdf.document import PDFDocument-from docvortex.document.pdf.document import PDFLinkAnnotation-from docvortex.document.pdf.document import PDFPageTextGeometry-from docvortex.analyzers.native.pdf.text_styles import PDF_FONT_FORCE_BOLD_FLAG-from docvortex.analyzers.native.pdf.text_styles import PDF_FONT_ITALIC_FLAG-from docvortex.analyzers.native.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY-from docvortex.analyzers.native.pdf.text_styles import PDFTextLinkLine-from docvortex.analyzers.native.pdf.text_styles import PDFTextLinkRange-from docvortex.analyzers.native.pdf.text_styles import PDFTextScriptLine-from docvortex.analyzers.native.pdf.text_styles import PDFTextScriptRange-from docvortex.analyzers.native.pdf.text_styles import PDFTextStyleLine-from docvortex.analyzers.native.pdf.text_styles import PDFTextStyleRange-from docvortex.analyzers.native.pdf.text_styles import apply_pdf_text_links as _apply_pdf_text_links-from docvortex.analyzers.native.pdf.text_styles import apply_pdf_text_styles as _apply_pdf_text_styles-from docvortex.analyzers.native.pdf.text_styles import detect_pdf_text_link_lines-from docvortex.analyzers.native.pdf.text_styles import detect_pdf_text_style_lines-from docvortex.analyzers.native.pdf.text_styles import materialize_pdf_inline_spans-from docvortex.analyzers.native.pdf.text_styles import _partition_resplit_text_evidence-from docvortex.analyzers.native.pdf.text_styles import _realign_repaired_text_evidence-from _span_test_utils import inline_text---def apply_pdf_text_links(- blocks: list[dict[str, Any]],- lines: Sequence[PDFTextLinkLine],- page_size: tuple[float, float],-) -> None:- """在测试中保留链接区间阶段,等待样式区间一并物化。"""- _apply_pdf_text_links(blocks, lines, page_size)---def apply_pdf_text_styles(- blocks: list[dict[str, Any]],- lines: Sequence[PDFTextStyleLine],- page_size: tuple[float, float],-) -> None:- """在测试中追加样式区间后执行生产环境的一次性 Span 物化。"""- _apply_pdf_text_styles(blocks, lines, page_size)- materialize_pdf_inline_spans(blocks)def _span_snapshot(content: Any) -> str:@@ -102,2129 +55,6 @@ def _span_snapshot(content: Any) -> str:return "".join(parts)-def _model_json(pages: list[list[dict[str, Any]]]) -> ModelJson:- """为 PDF 文本样式渲染测试构造最小严格 ModelJson。"""- return ModelJson(- pages=pages,- page_index_map=[],- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def _build_native_text_style_pdf() -> bytes:- """构造包含字体、删除线、下划线及其反例的单页原生 PDF。"""-- content = b"""0.8 w-BT /F1 12 Tf 50 250 Td (strike: alpha ) Tj (deleted) Tj ( omega) Tj ET-150.8 254 m 201.2 254 l S-BT /F1 12 Tf 50 210 Td (underline: alpha ) Tj (underlined) Tj ( omega) Tj ET-172.4 208 m 244.4 208 l S-BT /F1 12 Tf 50 170 Td (separator: alpha crossed omega) Tj ET-20 174 m 400 174 l S-BT /F1 12 Tf 50 130 Td (short: alpha ) Tj (x) Tj ( omega) Tj ET-143.6 134 m 150.8 134 l S-BT /F1 12 Tf 50 90 Td (filled: alpha ) Tj (filled strike) Tj ( omega) Tj ET-150.8 93.4 93.6 1.2 re f-BT /F2 12 Tf 50 50 Td (bold sample) Tj ET-BT /F3 12 Tf 50 30 Td (italic sample) Tj ET-BT /F4 12 Tf 50 10 Td (bold italic sample) Tj ET-"""- objects = [- b"<< /Type /Catalog /Pages 2 0 R >>",- b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",- b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 420 300] "- b"/Resources << /Font << /F1 4 0 R /F2 5 0 R /F3 6 0 R /F4 7 0 R >> >> "- b"/Contents 8 0 R >>",- b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",- b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",- b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique >>",- b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique >>",- b"<< /Length " + str(len(content)).encode("ascii") + b" >>\nstream\n" + content + b"endstream",- ]- payload = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")- offsets = [0]- for object_index, body in enumerate(objects, start=1):- offsets.append(len(payload))- payload.extend(f"{object_index} 0 obj\n".encode("ascii"))- payload.extend(body)- payload.extend(b"\nendobj\n")- xref_offset = len(payload)- payload.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii"))- payload.extend(b"0000000000 65535 f \n")- for offset in offsets[1:]:- payload.extend(f"{offset:010d} 00000 n \n".encode("ascii"))- payload.extend((f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n").encode("ascii"))- return bytes(payload)---def _text_line(- text: str,- *,- x: float = 10.0,- y: float = 10.0,- height: float = 10.0,- angle: int = 0,- source_index: int = 0,- font_name: str = "",- font_flags: int = 0,- font_weight: object = None,- rotation_degrees: float = 0.0,-) -> SimpleNamespace:- """构造带真实字符 bbox 的轻量视觉文本行。"""-- chars = []- cursor = x- for char_index, char in enumerate(text):- width = 3.0 if char.isspace() else 6.0- chars.append(- {- "char": char,- "bbox": (cursor, y, cursor + width, y + height),- "char_idx": char_index,- "rotation": math.radians(rotation_degrees),- "font": {- "name": font_name,- "flags": font_flags,- "weight": font_weight,- },- }- )- cursor += width- return SimpleNamespace(- text=text,- bbox=(x, y, cursor, y + height),- angle=angle,- source_index=source_index,- chars=chars,- )---def _drawing(- x0: float,- x1: float,- y: float,- *,- width: float = 1.0,- orientation: str = "horizontal",-) -> SimpleNamespace:- """构造文本装饰线检测使用的轻量 drawing。"""-- return SimpleNamespace(- bbox=(x0, y - width / 2, x1, y + width / 2),- width=width,- orientation=orientation,- )---def _char_span(line: SimpleNamespace, start: int, end: int) -> tuple[float, float]:- """返回指定字符区间的左右边缘。"""-- return line.chars[start]["bbox"][0], line.chars[end - 1]["bbox"][2]---def _link_evidence_line(- text: str,- target: str,- source_index: int,- *,- start: int = 0,- end: int | None = None,-) -> PDFTextLinkLine:- """构造跨行合并测试使用的轻量链接证据。"""-- resolved_end = len(text) if end is None else end- top = 10.0 + (source_index % 10) * 10.0- return PDFTextLinkLine(- bbox=(10.0, top, 90.0, top + 8.0),- text=text,- link_ranges=(PDFTextLinkRange(start, resolved_end, target),),- source_index=source_index,- )---def test_resplit_text_evidence_partitions_ranges_by_character_identity() -> None:- """验证重复字符、空白和连字不会让跨栏 evidence 按文本搜索错配。"""-- chars = [- {"char": char, "char_idx": char_idx}- for char_idx, char in enumerate(- ("A", "A", " ", "ff", "B", "B"),- start=10,- )- ]- source = models._LineItem(- text="AA ffBB",- bbox=(0.0, 10.0, 100.0, 20.0),- angle=0,- source_index=5,- chars=chars, # type: ignore[arg-type]- )- left = models._LineItem(- text="AA",- bbox=(0.0, 10.0, 20.0, 20.0),- angle=0,- source_index=5,- chars=chars[:3], # type: ignore[arg-type]- run_index=0,- )- right = models._LineItem(- text="ffBB",- bbox=(60.0, 10.0, 90.0, 20.0),- angle=0,- source_index=10,- chars=chars[3:], # type: ignore[arg-type]- run_index=1,- )- resplits = {- 5: native_text._NativeVisualResplit(- source=source,- members=(left, right),- )- }- style_line = PDFTextStyleLine(- bbox=source.bbox,- text="AAffBB",- style_ranges=(PDFTextStyleRange(1, 5, ("bold",)),),- source_index=5,- )- link_line = PDFTextLinkLine(- bbox=source.bbox,- text="AAffBB",- link_ranges=(PDFTextLinkRange(1, 4, "https://example.test/split"),),- source_index=5,- )-- style_lines, link_lines = _partition_resplit_text_evidence(- [style_line],- [link_line],- resplits,- )-- assert style_lines == [- PDFTextStyleLine(- bbox=left.bbox,- text="AA",- style_ranges=(PDFTextStyleRange(1, 2, ("bold",)),),- source_index=5,- ),- PDFTextStyleLine(- bbox=right.bbox,- text="ffBB",- style_ranges=(PDFTextStyleRange(0, 3, ("bold",)),),- source_index=10,- ),- ]- assert link_lines == [- PDFTextLinkLine(- bbox=left.bbox,- text="AA",- link_ranges=(PDFTextLinkRange(1, 2, "https://example.test/split"),),- source_index=5,- ),- PDFTextLinkLine(- bbox=right.bbox,- text="ffBB",- link_ranges=(PDFTextLinkRange(0, 2, "https://example.test/split"),),- source_index=10,- ),- ]---def test_resplit_text_evidence_preserves_identity_and_unsafe_mapping(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证无重切时保持原列表,映射不一致时保留粗行 evidence 并记录诊断。"""-- source = models._LineItem(- text="AB",- bbox=(0.0, 10.0, 100.0, 20.0),- angle=0,- source_index=5,- chars=[ # type: ignore[arg-type]- {"char": "A", "char_idx": 0},- {"char": "B", "char_idx": 1},- ],- )- member = models._LineItem(- text="AB",- bbox=(0.0, 10.0, 20.0, 20.0),- angle=0,- source_index=5,- chars=list(source.chars),- )- style_line = PDFTextStyleLine(source.bbox, "mismatch", (), 5)- link_line = PDFTextLinkLine(- source.bbox,- "mismatch",- (PDFTextLinkRange(0, 8, "https://example.test"),),- 5,- )- original_styles = [style_line]- original_links = [link_line]- warnings: list[str] = []- monkeypatch.setattr(- inline_matching,- "logger",- SimpleNamespace(warning=warnings.append),- )-- unchanged_styles, unchanged_links = _partition_resplit_text_evidence(- original_styles,- original_links,- {},- )- fallback_styles, fallback_links = _partition_resplit_text_evidence(- original_styles,- original_links,- {- 5: native_text._NativeVisualResplit(- source=source,- members=(member,),- )- },- )-- assert unchanged_styles is original_styles- assert unchanged_links is original_links- assert fallback_styles == original_styles- assert fallback_links == original_links- assert len(warnings) == 2- assert all("unsafe resplit mapping" in warning for warning in warnings)---def test_repaired_text_evidence_realigns_only_changed_unsplit_lines() -> None:- """验证 X/Y 修复后的普通行更新 bbox,未修复 evidence 保持对象身份和顺序。"""-- untouched_style = PDFTextStyleLine((10.0, 210.0, 50.0, 220.0), "plain", (), 0)- x_style = PDFTextStyleLine(- (0.0, 80.0, 200.0, 100.0),- "bold",- (PDFTextStyleRange(0, 4, ("bold",)),),- 1,- )- y_style = PDFTextStyleLine(- (20.0, 0.0, 60.0, 200.0),- "under",- (PDFTextStyleRange(0, 5, ("underline",)),),- 2,- )- untouched_link = PDFTextLinkLine(- (10.0, 210.0, 50.0, 220.0),- "plain",- (PDFTextLinkRange(0, 5, "https://example.test/plain"),),- 0,- )- x_link = PDFTextLinkLine(- x_style.bbox,- x_style.text,- (PDFTextLinkRange(0, 4, "https://example.test/x"),),- 1,- )- y_link = PDFTextLinkLine(- y_style.bbox,- y_style.text,- (PDFTextLinkRange(0, 5, "https://example.test/y"),),- 2,- )- style_lines = [untouched_style, x_style, y_style]- link_lines = [untouched_link, x_link, y_link]- repaired_bboxes = {- 0: untouched_style.bbox,- 1: (20.0, 80.0, 60.0, 100.0),- 2: (100.0, 80.0, 140.0, 100.0),- }-- aligned_styles, aligned_links = _realign_repaired_text_evidence(- style_lines,- link_lines,- repaired_bboxes,- {},- )-- assert aligned_styles[0] is untouched_style- assert aligned_links[0] is untouched_link- assert [line.source_index for line in aligned_styles] == [0, 1, 2]- assert [line.source_index for line in aligned_links] == [0, 1, 2]- assert [line.bbox for line in aligned_styles] == [untouched_style.bbox, repaired_bboxes[1], repaired_bboxes[2]]- assert [line.bbox for line in aligned_links] == [untouched_link.bbox, repaired_bboxes[1], repaired_bboxes[2]]- blocks = [- {"type": "text", "bbox": repaired_bboxes[1], "content": "bold"},- {"type": "text", "bbox": repaired_bboxes[2], "content": "under"},- ]- assert {- block_index: [line.source_index for line in lines]- for block_index, lines in flash_text_styles._assign_lines_to_blocks(- blocks,- aligned_styles[1:],- (200.0, 240.0),- ).items()- } == {0: [1], 1: [2]}- assert {- block_index: [line.source_index for line in lines]- for block_index, lines in flash_text_styles._assign_lines_to_blocks(- blocks,- aligned_links[1:],- (200.0, 240.0),- ).items()- } == {0: [1], 1: [2]}-- original_untouched_styles = [untouched_style]- original_untouched_links = [untouched_link]- unchanged_styles, unchanged_links = _realign_repaired_text_evidence(- original_untouched_styles,- original_untouched_links,- {0: untouched_style.bbox},- {},- )- assert unchanged_styles is original_untouched_styles- assert unchanged_links is original_untouched_links--[email protected]("angle", [0, 90, 180, 270])-def test_detect_and_apply_pdf_text_link_ranges_with_styles(angle: int) -> None:- """验证标准方向链接映射、内部空格、URL 转义、样式顺序和幂等性。"""-- line = _text_line("alpha beta", angle=angle)- annotation = PDFLinkAnnotation(- target="https://example.test/a?x=1&y=2",- bboxes=((line.bbox[0], line.bbox[1], line.bbox[2], line.bbox[3]),),- source_index=0,- )- link_lines = detect_pdf_text_link_lines([line], [annotation])-- assert link_lines == [- PDFTextLinkLine(- bbox=line.bbox,- text="alphabeta",- link_ranges=(- PDFTextLinkRange(- 0,- 9,- "https://example.test/a?x=1&y=2",- ),- ),- source_index=0,- )- ]-- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "alpha beta",- }- ]- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- apply_pdf_text_styles(- blocks,- [- PDFTextStyleLine(- bbox=line.bbox,- text="alphabeta",- style_ranges=(PDFTextStyleRange(5, 9, ("underline",)),),- source_index=0,- )- ],- (100.0, 100.0),- )- expected = "<hyperlink>alpha beta<url>https://example.test/a?x=1&y=2</url></hyperlink>"- assert _span_snapshot(blocks[0]["content"]) == expected-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- apply_pdf_text_styles(- blocks,- [- PDFTextStyleLine(- bbox=line.bbox,- text="alphabeta",- style_ranges=(PDFTextStyleRange(5, 9, ("underline",)),),- source_index=0,- )- ],- (100.0, 100.0),- )- assert _span_snapshot(blocks[0]["content"]) == expected---def test_pdf_underline_keeps_only_non_link_overlap() -> None:- """验证同一下划线跨越普通文本和链接时,仅保留链接外的真实下划线。"""-- line = _text_line("under hyperlink")- annotation = PDFLinkAnnotation(- target="https://example.test/partial",- bboxes=(- (- line.chars[6]["bbox"][0],- line.bbox[1],- line.chars[-1]["bbox"][2],- line.bbox[3],- ),- ),- source_index=0,- )- link_lines = detect_pdf_text_link_lines([line], [annotation])- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "under hyperlink",- }- ]- style_lines = [- PDFTextStyleLine(- bbox=line.bbox,- text="underhyperlink",- style_ranges=(PDFTextStyleRange(0, 14, ("underline",)),),- source_index=0,- )- ]-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- apply_pdf_text_styles(blocks, style_lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (- '<text style="underline">under</text> <hyperlink>hyperlink<url>https://example.test/partial</url></hyperlink>'- )---def test_detect_pdf_text_links_keeps_partial_ranges_and_drops_conflicts() -> None:- """验证局部字符链接可保留,而不同目标重叠字符按歧义丢弃。"""-- line = _text_line("alpha")- partial_bbox = (- line.chars[2]["bbox"][0],- line.bbox[1],- line.chars[3]["bbox"][2],- line.bbox[3],- )- partial = PDFLinkAnnotation(- target="https://partial.example.test",- bboxes=(partial_bbox,),- source_index=0,- )- partial_lines = detect_pdf_text_link_lines([line], [partial])- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "alpha",- }- ]- apply_pdf_text_links(blocks, partial_lines, (100.0, 100.0))- materialize_pdf_inline_spans(blocks)- assert _span_snapshot(blocks[0]["content"]) == ("al<hyperlink>ph<url>https://partial.example.test</url></hyperlink>a")-- conflict = PDFLinkAnnotation(- target="https://conflict.example.test",- bboxes=(partial_bbox,),- source_index=1,- )- assert detect_pdf_text_link_lines([line], [partial, conflict]) == []---def test_apply_pdf_text_links_splits_formula_gaps_and_maps_repeated_labels() -> None:- """验证链接不跨公式包装,并按物理行顺序定位重复标签。"""-- formula_blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": r"pre\(x\)post",- }- ]- apply_pdf_text_links(- formula_blocks,- [- PDFTextLinkLine(- bbox=(10.0, 10.0, 60.0, 20.0),- text="prexpost",- link_ranges=(PDFTextLinkRange(0, 8, "https://formula.example.test"),),- source_index=0,- )- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(formula_blocks)- assert _span_snapshot(formula_blocks[0]["content"]) == (- "<hyperlink>pre<url>https://formula.example.test</url></hyperlink>"- "<eq>x</eq>"- "<hyperlink>post<url>https://formula.example.test</url></hyperlink>"- )-- repeated_blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "link and link",- }- ]- apply_pdf_text_links(- repeated_blocks,- [- PDFTextLinkLine(- bbox=(10.0, 10.0, 35.0, 20.0),- text="link",- link_ranges=(PDFTextLinkRange(0, 4, "https://first.test"),),- source_index=0,- ),- PDFTextLinkLine(- bbox=(10.0, 30.0, 35.0, 40.0),- text="link",- link_ranges=(PDFTextLinkRange(0, 4, "https://second.test"),),- source_index=1,- ),- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(repeated_blocks)- assert _span_snapshot(repeated_blocks[0]["content"]) == (- "<hyperlink>link<url>https://first.test</url></hyperlink> and <hyperlink>link<url>https://second.test</url></hyperlink>"- )---def test_apply_pdf_text_links_merges_three_line_visible_url() -> None:- """验证三行同 href URL 合成一个标签,并吸收边界点号且不插入空格。"""-- target = "https://github.com/google-research/tapas/blob/master/TABLEFORMER.md"- blocks = [- {- "type": BlockType.PAGE_FOOTNOTE,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": f"1Code has been released at {target}",- }- ]- link_lines = [- _link_evidence_line(- "1Codehasbeenreleasedathttps://github.",- target,- 51,- start=22,- end=36,- ),- _link_evidence_line(- "com/google-research/tapas/blob/master/",- target,- 52,- ),- _link_evidence_line("TABLEFORMER.md", target, 53),- ]-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- materialize_pdf_inline_spans(blocks)-- expected = f"1Code has been released at <hyperlink>{target}<url>{target}</url></hyperlink>"- assert _span_snapshot(blocks[0]["content"]) == expected- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- assert _span_snapshot(blocks[0]["content"]) == expected--- (- "content",- "first_text",- "first_start",- "second_text",- "second_end",- "label",- ),- [- (- "Müller. 2020. Understanding tables with intermediate pre-training. In Findings",- "Müller.2020.Understandingtableswithinterme-",- len("Müller.2020."),- "diatepre-training.InFindings",- len("diatepre-training"),- "Understanding tables with intermediate pre-training",- ),- (- "Search-based neural structured learning for sequential question answering. In Proceedings",- "Search-basedneuralstructuredlearningforsequen-",- 0,- "tialquestionanswering.InProceedings",- len("tialquestionanswering"),- "Search-based neural structured learning for sequential question answering",- ),- (- "Yasemin Altun. 2019. Answering conversational questions",- "YaseminAltun.2019.An-",- len("YaseminAltun.2019."),- "sweringconversationalquestions",- len("sweringconversationalquestions"),- "Answering conversational questions",- ),- (- "Percy Liang. 2015. Compositional semantic parsing",- "PercyLiang.2015.Compo-",- len("PercyLiang.2015."),- "sitionalsemanticparsing",- len("sitionalsemanticparsing"),- "Compositional semantic parsing",- ),- ],-)-def test_apply_pdf_text_links_maps_dehyphenated_first_fragment(- content: str,- first_text: str,- first_start: int,- second_text: str,- second_end: int,- label: str,-) -> None:- """验证同 href 相邻行的首段断词符被回填删除后仍能完整映射。"""-- target = "https://doi.org/10.18653/v1/example"- blocks = [- {- "type": BlockType.REF_TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": content,- }- ]- apply_pdf_text_links(- blocks,- [- _link_evidence_line(- first_text,- target,- 80,- start=first_start,- ),- _link_evidence_line(- second_text,- target,- 81,- end=second_end,- ),- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- expected_link = f"<hyperlink>{label}<url>{target}</url></hyperlink>"- assert _span_snapshot(blocks[0]["content"]) == content.replace(label, expected_link)---def test_apply_pdf_text_links_maps_dehyphenated_middle_fragment() -> None:- """验证三行链接中间行的行末断词符不再阻断同 href 合并。"""-- target = "https://doi.org/10.18653/v1/N19-1423"- label = "BERT: Pre-training of deep bidirectional transformers for language understanding"- content = f"Kristina Toutanova. 2019. {label}. In Proceedings"- first_text = "KristinaToutanova.2019.BERT:Pre-trainingof"- blocks = [- {- "type": BlockType.REF_TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": content,- }- ]- link_lines = [- _link_evidence_line(- first_text,- target,- 90,- start=len("KristinaToutanova.2019."),- ),- _link_evidence_line(- "deepbidirectionaltransformersforlanguageunder-",- target,- 91,- ),- _link_evidence_line(- "standing.InProceedings",- target,- 92,- end=len("standing"),- ),- ]-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- materialize_pdf_inline_spans(blocks)-- expected = content.replace(- label,- f"<hyperlink>{label}<url>{target}</url></hyperlink>",- )- assert _span_snapshot(blocks[0]["content"]) == expected- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- assert _span_snapshot(blocks[0]["content"]) == expected--- ("content", "first_line", "second_line"),- [- (- "international",- _link_evidence_line("inter-", "https://same.test", 100),- _link_evidence_line("national", "https://same.test", 102),- ),- (- "international",- _link_evidence_line("inter-", "https://same.test", 100),- _link_evidence_line("national", "https://different.test", 101),- ),- (- "interxnational",- _link_evidence_line("inter-", "https://same.test", 100),- _link_evidence_line(- "xnational",- "https://same.test",- 101,- start=1,- ),- ),- (- "interxnational",- _link_evidence_line(- "interx-",- "https://same.test",- 100,- end=len("inter"),- ),- _link_evidence_line("national", "https://same.test", 101),- ),- ],-)-def test_apply_pdf_text_links_rejects_unsafe_dehyphenated_boundaries(- content: str,- first_line: PDFTextLinkLine,- second_line: PDFTextLinkLine,-) -> None:- """验证不同 href、非相邻行或非行首行尾链接不会启用断词投影。"""-- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": content,- }- ]-- apply_pdf_text_links(- blocks,- [first_line, second_line],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- assert f"<hyperlink>{content}<url>" not in _span_snapshot(blocks[0]["content"])---def test_apply_pdf_text_links_preserves_hyphen_before_uppercase_continuation() -> None:- """验证下一行以大写字母开头时保留可见连字符并正常合并链接。"""-- target = "https://same.test"- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "inter-National",- }- ]-- apply_pdf_text_links(- blocks,- [- _link_evidence_line("inter-", target, 110),- _link_evidence_line("National", target, 111),- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- assert _span_snapshot(blocks[0]["content"]) == (f"<hyperlink>inter-National<url>{target}</url></hyperlink>")---def test_apply_pdf_text_links_skips_ambiguous_dehyphenated_occurrence() -> None:- """验证断词候选在 block 中重复时不会把前后片段错误桥接。"""-- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "international international",- }- ]-- apply_pdf_text_links(- blocks,- [- _link_evidence_line("inter-", "https://same.test", 120),- _link_evidence_line("national", "https://same.test", 121),- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- assert "<hyperlink>international<url>" not in _span_snapshot(blocks[0]["content"])- assert _span_snapshot(blocks[0]["content"]).startswith("inter<hyperlink>national")- assert _span_snapshot(blocks[0]["content"]).endswith(" international")--- ("second_styles", "expected_label"),- [- (- ("bold",),- '<text style="bold">ETC: Encoding long and structured inputs in transformers</text>',- ),- (- ("underline",),- ('<text style="bold">ETC: Encoding long and structured inputs</text> in transformers'),- ),- ],-)-def test_apply_pdf_text_links_merges_title_and_preserves_non_underline_styles(- second_styles: tuple[str, ...],- expected_label: str,-) -> None:- """验证普通英文标签保留空格,并仅保留链接内非下划线样式。"""-- target = "https://doi.org/10.18653/v1/2020.emnlp-main.19"- first_text = "ETC:Encodinglongandstructuredinputs"- second_text = "intransformers"- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "ETC: Encoding long and structured inputs in transformers",- }- ]- link_lines = [- _link_evidence_line(first_text, target, 60),- _link_evidence_line(second_text, target, 61),- ]- style_lines = [- PDFTextStyleLine(- link_lines[0].bbox,- first_text,- (PDFTextStyleRange(0, len(first_text), ("bold",)),),- 60,- ),- PDFTextStyleLine(- link_lines[1].bbox,- second_text,- (PDFTextStyleRange(0, len(second_text), second_styles),),- 61,- ),- ]-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- apply_pdf_text_styles(blocks, style_lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (f"<hyperlink>{expected_label}<url>{target}</url></hyperlink>")--- ("content", "first_source", "second_source", "second_target"),- [- ("first unlinked second", 70, 71, "https://same.test"),- ("first<eq>x</eq>second", 70, 71, "https://same.test"),- ("first second", 70, 72, "https://same.test"),- ("first second", 70, 71, "https://different.test"),- ],-)-def test_apply_pdf_text_links_does_not_cross_invalid_merge_boundaries(- content: str,- first_source: int,- second_source: int,- second_target: str,-) -> None:- """验证无 href 正文、公式、非相邻行或不同目标都会阻断链接合并。"""-- first_target = "https://same.test"- blocks = [- {- "type": BlockType.TEXT,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": content,- }- ]- apply_pdf_text_links(- blocks,- [- _link_evidence_line("first", first_target, first_source),- _link_evidence_line("second", second_target, second_source),- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- assert _span_snapshot(blocks[0]["content"]).count("<hyperlink>") == 2--- ("block_type", "should_link"),- [- (BlockType.TEXT, True),- (BlockType.REF_TEXT, True),- (BlockType.DOC_TITLE, True),- (BlockType.PARAGRAPH_TITLE, True),- (BlockType.LIST, True),- (BlockType.INDEX, True),- (BlockType.HEADER, True),- (BlockType.FOOTER, True),- (BlockType.PAGE_NUMBER, True),- (BlockType.ASIDE_TEXT, True),- (BlockType.PAGE_FOOTNOTE, True),- (RAW_CAPTION, True),- (RAW_FOOTNOTE, True),- (BlockType.TABLE, False),- (BlockType.CODE, False),- (BlockType.EQUATION, False),- (BlockType.IMAGE, False),- ],-)-def test_apply_pdf_text_links_only_enriches_natural_language_blocks(- block_type: str,- should_link: bool,-) -> None:- """验证 PDF Link 只进入已批准的自然语言 block 类型。"""-- blocks = [- {- "type": block_type,- "bbox": (0.0, 0.0, 1.0, 1.0),- "content": "label",- }- ]- apply_pdf_text_links(- blocks,- [- PDFTextLinkLine(- bbox=(10.0, 10.0, 40.0, 20.0),- text="label",- link_ranges=(PDFTextLinkRange(0, 5, "https://target.test"),),- source_index=0,- )- ],- (100.0, 100.0),- )- materialize_pdf_inline_spans(blocks)-- expected = "<hyperlink>label<url>https://target.test</url></hyperlink>" if should_link else "label"- assert _span_snapshot(blocks[0]["content"]) == expected--- ("line_options", "expected_styles"),- [- ({"font_flags": PDF_FONT_FORCE_BOLD_FLAG}, ("bold",)),- ({"font_weight": 599}, None),- ({"font_weight": 600}, ("bold",)),- ({"font_weight": -1}, None),- ({"font_weight": "invalid"}, None),- ({"font_name": "ABCDEF+FrankRuhlHofshi-Bold"}, ("bold",)),- ({"font_name": "SourceSansPro-Semibold"}, ("bold",)),- ({"font_name": "Arial-Black"}, ("bold",)),- ({"font_name": "HiraginoSansGB-W6"}, ("bold",)),- ({"font_name": "HiraginoSansGB-W3"}, None),- (- {- "font_name": "LinuxLibertineGBI",- "font_flags": PDF_FONT_ITALIC_FLAG,- },- ("bold",),- ),- ({"font_name": "MyriadPro-SemiCn"}, None),- ({"font_flags": PDF_FONT_ITALIC_FLAG}, None),- ({"font_name": "TimesNewRomanPS-ItalicMT"}, None),- ({"font_name": "Helvetica-Oblique"}, None),- ({"rotation_degrees": 4.9}, None),- ({"rotation_degrees": 5.0}, None),- ({"rotation_degrees": 19.0}, None),- ({"rotation_degrees": 30.0}, None),- ({"rotation_degrees": 30.1}, None),- ],-)-def test_detects_font_styles_only_from_approved_direct_evidence(- line_options: dict[str, object],- expected_styles: tuple[str, ...] | None,-) -> None:- """验证 PDF 只从批准的直接证据生成粗体,所有斜体证据均被忽略。"""-- line = _text_line("styled", **line_options)-- detected = detect_pdf_text_style_lines([line], [])-- if expected_styles is None:- assert detected == []- else:- assert detected == [- PDFTextStyleLine(- line.bbox,- "styled",- (PDFTextStyleRange(0, 6, expected_styles),),- 0,- )- ]---def test_rotated_line_never_uses_local_rotation_as_italic_evidence() -> None:- """验证整行非标准方向即使字符角差落入区间也不会标为斜体。"""-- line = _text_line(- "watermark",- angle=340,- rotation_degrees=20.0,- )-- assert detect_pdf_text_style_lines([line], []) == []--- ("text", "expected_text"),- [- ("A", None),- ("中", None),- ("AB", "AB"),- ("fi", "fi"),- ],-)-def test_filters_pdf_bold_runs_shorter_than_two_comparable_characters(- text: str,- expected_text: str | None,-) -> None:- """验证单字符粗体被过滤,双字符和展开为双字符的 ligature 保留。"""-- line = _text_line(text, font_name="Helvetica-Bold")-- detected = detect_pdf_text_style_lines([line], [])-- if expected_text is None:- assert detected == []- else:- assert detected == [- PDFTextStyleLine(- line.bbox,- expected_text,- (PDFTextStyleRange(0, len(expected_text), ("bold",)),),- 0,- )- ]---def test_filters_isolated_leading_bold_list_marker_cluster() -> None:- """验证达到最小长度的行首项目符号簇仍不会污染普通正文。"""-- line = _text_line("•• body")- for char in line.chars[:2]:- char["font"] = {- "name": "Helvetica-Bold",- "flags": 0,- "weight": 400,- }-- assert detect_pdf_text_style_lines([line], []) == []---def test_filters_bold_bullet_but_keeps_later_bold_list_text() -> None:- """验证真实列表形态只移除行首粗体圆点,保留后续粗体正文。"""-- line = _text_line("• 无序列表项 1:bold 粗体文本")- bold_indices = {0}- bold_start = line.text.index("bold")- bold_indices.update(range(bold_start, len(line.text)))- for char_index in bold_indices:- line.chars[char_index]["font"] = {- "name": "Helvetica-Bold",- "flags": 0,- "weight": 400,- }-- detected = detect_pdf_text_style_lines([line], [])- bold_fragments = [- detected[0].text[style_range.start : style_range.end]- for style_range in detected[0].style_ranges- if "bold" in style_range.styles- ]-- assert bold_fragments == ["bold粗体文本"]---def test_keeps_list_marker_when_it_is_part_of_a_full_bold_run() -> None:- """验证项目符号与后续正文同属完整粗体 run 时不会被单独删除。"""-- line = _text_line("• bold", font_name="Helvetica-Bold")-- detected = detect_pdf_text_style_lines([line], [])-- assert detected[0].style_ranges == (PDFTextStyleRange(0, 5, ("bold",)),)---def test_combines_bold_and_strikethrough_styles_per_character() -> None:- """验证斜体字体保持普通文本,粗体与删除线仍按字符正确组合。"""-- line = _text_line("ABCDEF", height=5.0)- for char_index in (1, 2):- line.chars[char_index]["font"] = {- "name": "Helvetica-Bold",- "flags": 0,- "weight": 400,- }- line.chars[3]["font"] = {- "name": "Helvetica-Oblique",- "flags": 0,- "weight": 400,- }- for char_index in (4, 5):- line.chars[char_index]["font"] = {- "name": "Helvetica-BoldOblique",- "flags": 0,- "weight": 400,- }- x0, x1 = _char_span(line, 1, 6)-- detected = detect_pdf_text_style_lines(- [line],- [_drawing(x0, x1, 12.5)],- )-- assert detected[0].style_ranges == (- PDFTextStyleRange(1, 3, ("bold", "strikethrough")),- PDFTextStyleRange(3, 4, ("strikethrough",)),- PDFTextStyleRange(4, 6, ("bold", "strikethrough")),- )---def test_detects_long_strikethrough_and_preserves_internal_spaces() -> None:- """验证长删除线按字符范围生成单个紧凑样式区间。"""-- line = _text_line("alpha deleted text omega")- start = line.text.index("deleted")- end = start + len("deleted text")- x0, x1 = _char_span(line, start, end)-- detected = detect_pdf_text_style_lines(- [line],- [_drawing(x0, x1, 15.0)],- )-- assert len(detected) == 1- assert detected[0].text == "alphadeletedtextomega"- assert detected[0].text[detected[0].style_ranges[0].start : detected[0].style_ranges[0].end] == "deletedtext"--[email protected]("drawing_y", [18.0, 20.0, 22.0])-def test_detects_underline_inside_strict_bottom_band(drawing_y: float) -> None:- """验证主体字符下边界上下 0.20h 内的长横线产生下划线。"""-- line = _text_line("alpha underlined omega")- start = line.text.index("underlined")- end = start + len("underlined")- x0, x1 = _char_span(line, start, end)-- detected = detect_pdf_text_style_lines(- [line],- [_drawing(x0, x1, drawing_y)],- )-- assert detected[0].style_ranges == (PDFTextStyleRange(5, 15, ("underline",)),)--[email protected]("drawing_y", [17.99, 22.01])-def test_rejects_underline_outside_strict_bottom_band(- drawing_y: float,-) -> None:- """验证超过主体下边界 0.20h 的横线不产生下划线。"""-- line = _text_line("alpha underlined omega")- start = line.text.index("underlined")- end = start + len("underlined")- x0, x1 = _char_span(line, start, end)-- assert (- detect_pdf_text_style_lines(- [line],- [_drawing(x0, x1, drawing_y)],- )- == []- )---def test_combines_bold_underline_and_strikethrough_in_protocol_order() -> None:- """验证同一字符范围的粗体、下划线和删除线按固定顺序合并。"""-- line = _text_line("styled", font_name="Helvetica-Bold")- x0, x1 = _char_span(line, 0, len(line.text))-- detected = detect_pdf_text_style_lines(- [line],- [- _drawing(x0, x1, 15.0),- _drawing(x0, x1, 20.0),- ],- )-- assert detected[0].style_ranges == (- PDFTextStyleRange(- 0,- 6,- ("bold", "underline", "strikethrough"),- ),- )---def test_merges_repeated_underline_drawings() -> None:- """验证双线或重复共线 drawing 只生成一个下划线语义区间。"""-- line = _text_line("underlined")- x0, x1 = _char_span(line, 0, len(line.text))-- detected = detect_pdf_text_style_lines(- [line],- [- _drawing(x0, x1, 19.0),- _drawing(x0, x1, 20.0),- ],- )-- assert detected[0].style_ranges == (PDFTextStyleRange(0, 10, ("underline",)),)---def test_rejects_fraction_bar_with_tightly_contained_lower_run() -> None:- """验证横线下方紧邻且被覆盖的分母 run 会阻止下划线误判。"""-- numerator = _text_line("numerator", source_index=0)- denominator = _text_line(- "den",- x=28.0,- y=21.4,- height=8.0,- source_index=1,- )- x0, x1 = _char_span(numerator, 0, len(numerator.text))-- assert (- detect_pdf_text_style_lines(- [numerator, denominator],- [_drawing(x0, x1, 20.0)],- )- == []- )---def test_keeps_underline_when_following_text_is_outside_fraction_gap() -> None:- """验证普通下一行即使水平重叠也不会触发分数线排除。"""-- first = _text_line("underlined", source_index=0)- second = _text_line(- "next",- x=28.0,- y=22.1,- height=8.0,- source_index=1,- )- x0, x1 = _char_span(first, 0, len(first.text))-- detected = detect_pdf_text_style_lines(- [first, second],- [_drawing(x0, x1, 20.0)],- )-- ranges_by_source = {line.source_index: line.style_ranges for line in detected}- assert ranges_by_source[0] == (PDFTextStyleRange(0, 10, ("underline",)),)- assert ranges_by_source[1] == ()---def test_rejects_thick_short_and_column_rules() -> None:- """验证粗线、短线和贯穿整栏的分隔线均不产生文本样式。"""-- line = _text_line("alpha deleted omega")- start = line.text.index("deleted")- end = start + len("deleted")- x0, x1 = _char_span(line, start, end)- short_line = _text_line("alpha xy omega", y=30.0, source_index=1)- short_start = short_line.text.index("xy")- short_x0, short_x1 = _char_span(short_line, short_start, short_start + 2)-- detected = detect_pdf_text_style_lines(- [line, short_line],- [- _drawing(x0, x1, 15.0, width=2.1),- _drawing(short_x0, short_x1, 35.0),- _drawing(0.0, 200.0, 15.0),- ],- )-- assert all(not item.style_ranges for item in detected)--- ("drawing_length", "expected_styles"),- [- (17.99, ()),- (18.0, (PDFTextStyleRange(0, 3, ("strikethrough",)),)),- ],-)-def test_text_decoration_minimum_length_is_one_point_eight_heights(- drawing_length: float,- expected_styles: tuple[PDFTextStyleRange, ...],-) -> None:- """验证文本装饰线长度达到 1.8 倍中位字高时才允许生成样式。"""-- line = _text_line("abc")- detected = detect_pdf_text_style_lines(- [line],- [_drawing(line.bbox[0], line.bbox[0] + drawing_length, 15.0)],- )-- if expected_styles:- assert detected[0].style_ranges == expected_styles- else:- assert detected == []---def test_accepts_one_aligned_endpoint_and_merges_adjacent_drawings() -> None:- """验证尾部延长 drawing 可由左端点确认,邻接命中区间会合并。"""-- line = _text_line("alpha deleted text omega")- deleted_start = line.text.index("deleted")- deleted_end = deleted_start + len("deleted")- text_start = line.text.index("text")- text_end = text_start + len("text")- deleted_x0, deleted_x1 = _char_span(line, deleted_start, deleted_end)- text_x0, text_x1 = _char_span(line, text_start, text_end)-- detected = detect_pdf_text_style_lines(- [line],- [- _drawing(deleted_x0, deleted_x1 + 5.0, 15.0),- _drawing(text_x0, text_x1, 15.0),- ],- )-- assert len(detected[0].style_ranges) == 1- style_range = detected[0].style_ranges[0]- assert detected[0].text[style_range.start : style_range.end] == "deletedtext"---def test_keeps_two_disjoint_strikethrough_ranges() -> None:- """验证同一文本行内被普通字符隔开的两条删除线保持两个样式区间。"""-- line = _text_line("alpha deleted middle removed omega")- deleted_start = line.text.index("deleted")- removed_start = line.text.index("removed")- deleted_x0, deleted_x1 = _char_span(- line,- deleted_start,- deleted_start + len("deleted"),- )- removed_x0, removed_x1 = _char_span(- line,- removed_start,- removed_start + len("removed"),- )-- detected = detect_pdf_text_style_lines(- [line],- [- _drawing(deleted_x0, deleted_x1, 15.0),- _drawing(removed_x0, removed_x1, 15.0),- ],- )-- assert [detected[0].text[style_range.start : style_range.end] for style_range in detected[0].style_ranges] == [- "deleted",- "removed",- ]---def test_drawing_is_assigned_to_the_closest_overlapping_line() -> None:- """验证一条 drawing 同时接近两行时只归属中线距离更小的文本行。"""-- first = _text_line("deleted", y=10.0, source_index=0)- second = _text_line("deleted", y=11.0, source_index=1)- x0, x1 = _char_span(first, 0, len(first.text))-- detected = detect_pdf_text_style_lines(- [first, second],- [_drawing(x0, x1, 15.1)],- )-- ranges_by_source = {line.source_index: line.style_ranges for line in detected}- assert ranges_by_source[0] == (PDFTextStyleRange(0, 7, ("strikethrough",)),)- assert ranges_by_source[1] == ()---def test_rotated_text_is_not_a_style_candidate() -> None:- """验证首版忽略真正旋转的视觉文本。"""-- line = _text_line("rotated text", angle=90)-- assert (- detect_pdf_text_style_lines(- [line],- [_drawing(10.0, 80.0, 15.0)],- )- == []- )---def test_invalid_line_and_char_bboxes_are_ignored() -> None:- """验证退化 line 或 char bbox 不会进入删除线检测。"""-- invalid_line = SimpleNamespace(- bbox=(10.0, 10.0, 10.0, 20.0),- angle=0,- source_index=0,- chars=[{"char": "x", "bbox": (10.0, 10.0, 10.0, 20.0)}],- )-- assert (- detect_pdf_text_style_lines(- [invalid_line],- [_drawing(10.0, 40.0, 15.0)],- )- == []- )---def test_applies_style_to_plain_content_and_duplicate_second_line() -> None:- """验证物理行顺序可将重复文本的删除线写到第二次出现位置。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "deleted deleted",- }- ]- lines = [- PDFTextStyleLine((10.0, 10.0, 50.0, 20.0), "deleted", (), 0),- PDFTextStyleLine(- (10.0, 30.0, 50.0, 40.0),- "deleted",- (PDFTextStyleRange(0, 7, ("strikethrough",)),),- 1,- ),- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == 'deleted <text style="strikethrough">deleted</text>'---def test_applies_style_across_dehyphenated_line_boundary() -> None:- """验证行末断词符被正文回填删除后,两行粗体仍合并为完整区间。"""-- blocks = [- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "Abstract—Stereo matching was designed for sequences.",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "Abstract—Stereomatchingwasde-",- (PDFTextStyleRange(0, len("Abstract—Stereomatchingwasde-"), ("bold",)),),- 10,- ),- PDFTextStyleLine(- (10.0, 30.0, 90.0, 40.0),- "signedforsequences.",- (PDFTextStyleRange(0, len("signedforsequences."), ("bold",)),),- 11,- ),- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (- '<text style="bold">Abstract—Stereo matching was designed for sequences.</text>'- )--- ("content", "first_text", "second_text", "second_source_index", "expected"),- [- (- "inter-national",- "inter-",- "national",- 21,- '<text style="bold">inter-national</text>',- ),- (- "inter-National",- "inter-",- "National",- 21,- '<text style="bold">inter-National</text>',- ),- (- "international",- "inter-",- "national",- 22,- 'inter<text style="bold">national</text>',- ),- (- "international international",- "inter-",- "national",- 21,- 'inter<text style="bold">national</text> international',- ),- ],-)-def test_style_dehyphenation_preserves_safe_boundaries(- content: str,- first_text: str,- second_text: str,- second_source_index: int,- expected: str,-) -> None:- """验证保留连字符、大小写、非相邻行和重复候选均不会错误桥接。"""-- blocks = [- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": content,- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- first_text,- (PDFTextStyleRange(0, len(first_text), ("bold",)),),- 20,- ),- PDFTextStyleLine(- (10.0, 30.0, 90.0, 40.0),- second_text,- (PDFTextStyleRange(0, len(second_text), ("bold",)),),- second_source_index,- ),- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == expected---def test_same_visual_row_style_runs_follow_source_order_despite_bbox_jitter() -> None:- """验证同行 run 的细微顶边抖动不会把后方粗体片段提前映射。"""-- attention = _text_line(- "Attention",- x=10.0,- y=10.01,- source_index=0,- font_name="Helvetica-Bold",- )- bias = _text_line(- "Bias",- x=80.0,- y=10.01,- source_index=1,- font_name="Helvetica-Bold",- )- scaling = _text_line(- "Scaling. Unlike",- x=120.0,- y=10.0,- source_index=2,- )- for char in scaling.chars[: len("Scaling.")]:- char["font"] = {- "name": "Helvetica-Bold",- "flags": 0,- "weight": 400,- }-- style_lines = detect_pdf_text_style_lines(- [scaling, attention, bias],- [],- )- assert [line.source_index for line in style_lines] == [0, 1, 2]-- blocks = [- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "Attention Bias Scaling. Unlike",- }- ]- apply_pdf_text_styles(blocks, style_lines, (250.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == ('<text style="bold">Attention Bias Scaling.</text> Unlike')---def test_applies_style_inside_superscript_without_crossing_tags() -> None:- """验证删除线只包装 sup 内的文本叶子,不破坏原有上下标标签。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "value <sup>deleted</sup> tail",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "valuedeletedtail",- (PDFTextStyleRange(5, 12, ("strikethrough",)),),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == ('value <sup><text style="strikethrough">deleted</text></sup> tail')--- ("tag", "style"),- [- ("sup", "superscript"),- ("sub", "subscript"),- ],-)-def test_materializes_owned_script_markup(tag: str, style: str) -> None:- """验证 producer-owned 上标与下标标签都转换为结构化 TextSpan 样式。"""- block = {- "type": BlockType.TEXT,- "content": f"A<{tag}>2</{tag}>B",- PDF_NATIVE_SCRIPT_MARKUP_KEY: True,- }-- materialize_pdf_inline_spans([block])-- assert _span_snapshot(block["content"]) == f'A<text style="{style}">2</text>B'- assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in block---def test_materializes_owned_superscript_with_style_and_hyperlink() -> None:- """验证 producer-owned 上标会与删除线和链接语义共同物化。"""- target = "https://script.example.test"- blocks = [- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "value <sup>ref</sup> tail",- PDF_NATIVE_SCRIPT_MARKUP_KEY: True,- }- ]- link_lines = [- PDFTextLinkLine(- (10.0, 10.0, 90.0, 20.0),- "valuereftail",- (PDFTextLinkRange(5, 8, target),),- 0,- )- ]- style_lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "valuereftail",- (PDFTextStyleRange(5, 8, ("strikethrough",)),),- 0,- )- ]-- apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))- apply_pdf_text_styles(blocks, style_lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (- f'value <hyperlink><text style="strikethrough,superscript">ref</text><url>{target}</url></hyperlink> tail'- )- assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in blocks[0]--- "content",- [- "A<sup>B</sub>",- "A<sup><sub>B</sub></sup>",- "A<sup>B",- ],-)-def test_malformed_owned_script_markup_remains_literal(content: str) -> None:- """验证不平衡或嵌套的 producer-owned 标签按普通字面文本回退。"""- block = {- "type": BlockType.TEXT,- "content": content,- PDF_NATIVE_SCRIPT_MARKUP_KEY: True,- }-- materialize_pdf_inline_spans([block])-- assert inline_text(block["content"]) == content- assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in block---def test_filters_italic_before_merging_overlapping_style_ranges() -> None:- """验证过滤斜体后仍正确合并粗体、下划线与删除线区间。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 0.4],- "content": "abcdef",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "abcdef",- (- PDFTextStyleRange(0, 4, ("bold",)),- PDFTextStyleRange(2, 6, ("italic",)),- PDFTextStyleRange(1, 5, ("underline",)),- PDFTextStyleRange(3, 5, ("strikethrough",)),- ),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (- '<text style="bold">a</text>'- '<text style="bold,underline">bc</text>'- '<text style="bold,underline,strikethrough">d</text>'- '<text style="underline,strikethrough">e</text>f'- )---def test_preserves_internal_spaces_and_is_idempotent() -> None:- """验证字体样式保留内部空格,重复富化不会增加嵌套标签。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "bold text",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "boldtext",- (PDFTextStyleRange(0, 8, ("bold",)),),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))- first_result = _span_snapshot(blocks[0]["content"])- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert first_result == '<text style="bold">bold text</text>'- assert _span_snapshot(blocks[0]["content"]) == first_result---def test_underline_does_not_wrap_boundary_spaces() -> None:- """验证下划线只保留命中字符之间的内部空格,不扩散到边界空格。"""-- blocks = [- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": " under lined ",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "underlined",- (PDFTextStyleRange(0, 10, ("underline",)),),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == (' <text style="underline">under lined</text> ')--- "block_type",- [- BlockType.TEXT,- BlockType.REF_TEXT,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- BlockType.LIST,- BlockType.INDEX,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.ASIDE_TEXT,- BlockType.PAGE_FOOTNOTE,- RAW_CAPTION,- RAW_FOOTNOTE,- ],-)-def test_applies_style_specific_scope_to_natural_language_blocks(- block_type: str,-) -> None:- """验证粗体和下划线仅进入 text,删除线保持自然语言范围。"""-- blocks = [- {- "type": block_type,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "styled",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "styled",- (- PDFTextStyleRange(- 0,- 6,- ("bold", "italic", "underline", "strikethrough"),- ),- ),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- expected_styles = "bold,underline,strikethrough" if block_type == BlockType.TEXT else "strikethrough"- assert _span_snapshot(blocks[0]["content"]) == (f'<text style="{expected_styles}">styled</text>')--- "block_type",- [- BlockType.TABLE,- BlockType.CODE,- BlockType.EQUATION,- BlockType.IMAGE,- ],-)-def test_does_not_apply_styles_to_visual_or_code_blocks(block_type: str) -> None:- """验证表格、代码、公式和图片 block 不进入 PDF 文本样式富化。"""-- blocks = [- {- "type": block_type,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "styled",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "styled",- (- PDFTextStyleRange(- 0,- 6,- ("bold", "italic", "underline", "strikethrough"),- ),- ),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == "styled"---def test_tag_shaped_pdf_text_is_not_interpreted_as_inline_semantics() -> None:- """验证 PDF 标签外观原文始终保留为 TextSpan,不会重建旧行内协议。"""-- first_literal = "A<sup>B</sup><eq>C</eq><hyperlink><text>D</text><url>u</url></hyperlink>"- second_literal = '<b>A</b><i>B</i><u>C</u><s>D</s><text style="underline">E</text>'- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 0.4],- "content": first_literal,- },- {- "type": "text",- "bbox": [0.0, 0.6, 1.0, 1.0],- "content": second_literal,- },- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "ABCD",- (- PDFTextStyleRange(0, 1, ("bold",)),- PDFTextStyleRange(1, 2, ("italic",)),- PDFTextStyleRange(2, 3, ("bold",)),- PDFTextStyleRange(3, 4, ("bold", "italic", "underline")),- ),- 0,- ),- PDFTextStyleLine(- (10.0, 70.0, 90.0, 80.0),- "ABCDE",- (- PDFTextStyleRange(0, 1, ("bold",)),- PDFTextStyleRange(1, 2, ("italic",)),- PDFTextStyleRange(2, 3, ("underline",)),- PDFTextStyleRange(3, 4, ("strikethrough",)),- PDFTextStyleRange(4, 5, ("underline",)),- ),- 1,- ),- ]-- apply_pdf_text_styles(blocks, lines[:1], (100.0, 100.0))- apply_pdf_text_styles(blocks[1:], lines[1:], (100.0, 100.0))- first_results = [_span_snapshot(block["content"]) for block in blocks]- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert inline_text(blocks[0]["content"]) == first_literal- assert inline_text(blocks[1]["content"]) == second_literal- assert all(span.get("type") == "text" for block in blocks for span in block["content"])- assert [_span_snapshot(block["content"]) for block in blocks] == first_results---def test_formula_style_does_not_fall_back_to_same_plain_character() -> None:- """验证公式内字体样式不会误映射到同一 block 的同名普通字符。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": r"A\(C\)C",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "ACC",- (PDFTextStyleRange(1, 2, ("bold",)),),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == "A<eq>C</eq>C"---def test_unique_long_style_range_survives_omitted_list_marker() -> None:- """验证 layout 省略行首项目符号时,较长唯一字体片段仍能安全对齐。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "无序列表项1:bold 粗体文本",- }- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "•无序列表项1:bold粗体文本",- (- PDFTextStyleRange(0, 1, ("bold",)),- PDFTextStyleRange(8, 16, ("bold",)),- ),- 0,- )- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == ('无序列表项1:<text style="bold">bold 粗体文本</text>')---def test_never_styles_equations_or_excluded_blocks() -> None:- """验证公式内容与 table block 不会被 PDF 删除线富化。"""-- blocks = [- {- "type": "text",- "bbox": [0.0, 0.0, 1.0, 0.5],- "content": r"before \(deleted\) after",- },- {- "type": "table",- "bbox": [0.0, 0.5, 1.0, 1.0],- "content": "deleted",- },- ]- lines = [- PDFTextStyleLine(- (10.0, 10.0, 90.0, 20.0),- "beforedeletedafter",- (PDFTextStyleRange(6, 13, ("strikethrough",)),),- 0,- ),- PDFTextStyleLine(- (10.0, 60.0, 90.0, 70.0),- "deleted",- (PDFTextStyleRange(0, 7, ("strikethrough",)),),- 1,- ),- ]-- apply_pdf_text_styles(blocks, lines, (100.0, 100.0))-- assert _span_snapshot(blocks[0]["content"]) == "before <eq>deleted</eq> after"- assert _span_snapshot(blocks[1]["content"]) == "deleted"---def test_flash_native_pdf_styles_reach_model_middle_and_renderers() -> None:- """验证真实 PDF 字体和 drawing 样式贯穿 model、MiddleJson 与 renderer。"""-- document = PDFDocument(_build_native_text_style_pdf())- try:- model_list = PdfModel().predict(document)- finally:- document.close()- model_contents = [_span_snapshot(block.get("content")) for page in model_list for block in page]- joined_model_content = "\n".join(model_contents)- assert '<text style="strikethrough">deleted</text>' in joined_model_content- assert '<text style="strikethrough">filled strike</text>' in joined_model_content- assert '<text style="underline">underlined</text>' in joined_model_content- assert '<text style="strikethrough">underlined</text>' not in joined_model_content- assert '<text style="strikethrough">x</text>' not in joined_model_content- assert '<text style="strikethrough">separator' not in joined_model_content- assert '<text style="bold">bold sample</text>' in joined_model_content- assert "italic sample" in joined_model_content- assert '<text style="italic">' not in joined_model_content- assert '<text style="bold">bold italic sample</text>' in joined_model_content-- middle = MiddleJson(- pages=model_json_to_pages(_model_json(model_list)),- is_full_document=True,- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )- markdown = render_markdown(middle)- html = render_html(middle, standalone=False)- document_xml = ZipFile(BytesIO(render_docx(middle))).read("word/document.xml").decode("utf-8")-- assert "~~deleted~~" in markdown- assert "<u>underlined</u>" in markdown- assert "**bold sample**" in markdown- assert "*italic sample*" not in markdown- assert "**bold italic sample**" in markdown- assert "<s>deleted</s>" in html- assert "<u>underlined</u>" in html- assert "<strong>bold sample</strong>" in html- assert "<em>italic sample</em>" not in html- assert "<strong>bold italic sample</strong>" in html- assert "<w:strike" in document_xml- assert "<w:u" in document_xml- assert "<w:b" in document_xml- assert "<w:i/>" not in document_xml- assert '<w:i w:val="1"' not in document_xml--def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/unittest/test_postprocess_page_blocks.py b/tests/unittest/test_postprocess_page_blocks.pydeleted file mode 100644index 378d451d..00000000--- a/tests/unittest/test_postprocess_page_blocks.py+++ /dev/null@@ -1,132 +0,0 @@-from __future__ import annotations--from docvortex.postprocess.lists import fix_pdf_list_blocks-from docvortex.postprocess.page_blocks import process_page_blocks-from mineru.types import BlockType--from _span_test_utils import inline as _inline---def test_page_blocks_keep_canonical_equation_type_and_clean_content() -> None:- """验证单页后处理清理行间公式内容时不改写 equation 类型。"""- equation = {- "type": BlockType.EQUATION,- "content": r"\[x+1\]",- }-- blocks = process_page_blocks([equation], use_bbox=False)-- assert blocks == [- {- "type": BlockType.EQUATION,- "content": "x+1",- "index": 0,- }- ]---def test_fix_pdf_list_blocks_supports_unit_bbox_without_rewrite() -> None:- """验证归一化列表框可与像素文本框计算包含关系且不回写 bbox。"""- list_bbox = [0.0, 0.0, 1.0, 1.0]- text_bbox = [100, 100, 200, 200]- list_block = {- "type": BlockType.LIST,- "bbox": list_bbox,- "content": "",- }- text_block = {- "type": BlockType.TEXT,- "bbox": text_bbox,- "content": _inline("list item"),- }-- list_blocks, text_blocks, ref_text_blocks = fix_pdf_list_blocks(- [list_block],- [text_block],- [],- )-- assert list_blocks == [list_block]- assert text_blocks == []- assert ref_text_blocks == []- assert list_block["content"] == [text_block]- assert list_block["sub_type"] == BlockType.TEXT- assert list_bbox == [0.0, 0.0, 1.0, 1.0]- assert text_bbox == [100, 100, 200, 200]---def test_page_blocks_group_bbox_dict_visual_blocks() -> None:- """验证单页后处理可将带 bbox 的 dict 视觉块完成分组。"""- blocks = process_page_blocks(- [- {- "type": BlockType.IMAGE_CAPTION,- "bbox": [0.0, 0.0, 80.0, 10.0],- "content": _inline("Figure 1"),- },- {- "type": BlockType.IMAGE,- "bbox": [0.0, 15.0, 80.0, 60.0],- "image_base64": "data:image/jpeg;base64,image",- },- ]- )-- image_blocks = [block for block in blocks if block["type"] == BlockType.IMAGE]- assert len(image_blocks) == 1- image_block = image_blocks[0]- assert isinstance(image_block, dict)- assert [block["type"] for block in image_block["content"]] == [- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_BODY,- ]---def test_page_blocks_group_no_bbox_office_caption_by_prefix() -> None:- """验证单页后处理使用 Office 前缀规则分组无 bbox 视觉块。"""- blocks = process_page_blocks(- [- {- "type": BlockType.IMAGE,- "image_base64": "data:image/jpeg;base64,image",- },- {- "type": BlockType.TEXT,- "content": _inline("Figure 1"),- },- ]- )-- assert not [block for block in blocks if block["type"] == BlockType.TEXT]- image_blocks = [block for block in blocks if block["type"] == BlockType.IMAGE]- assert len(image_blocks) == 1- image_block = image_blocks[0]- assert [block["type"] for block in image_block["content"]] == [- BlockType.IMAGE_BODY,- BlockType.IMAGE_CAPTION,- ]---def test_page_blocks_group_no_bbox_chart_and_code_captions() -> None:- """验证无 bbox 的 chart/code caption 映射及 code subtype 保留。"""- blocks = process_page_blocks(- [- {"type": BlockType.CHART_CAPTION, "content": _inline("Chart 1")},- {"type": BlockType.CHART, "content": "<div>chart</div>"},- {"type": BlockType.CODE_CAPTION, "content": _inline("Algorithm 1")},- {"type": BlockType.CODE, "content": "print('ok')"},- ]- )-- chart_block = next(block for block in blocks if block["type"] == BlockType.CHART)- assert [block["type"] for block in chart_block["content"]] == [- BlockType.CHART_CAPTION,- BlockType.CHART_BODY,- ]- code_block = next(block for block in blocks if block["type"] == BlockType.CODE)- assert code_block["sub_type"] == "code"- assert code_block["guess_lang"]- assert [block["type"] for block in code_block["content"]] == [- BlockType.CODE_CAPTION,- BlockType.CODE_BODY,- ]diff --git a/tests/unittest/test_postprocess_pages.py b/tests/unittest/test_postprocess_pages.pydeleted file mode 100644index e21c939a..00000000--- a/tests/unittest/test_postprocess_pages.py+++ /dev/null@@ -1,560 +0,0 @@-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from copy import deepcopy-from typing import Any--from docvortex.postprocess import pages as pages_module-from docvortex.postprocess.lists import fix_office_list_blocks-from docvortex.postprocess.pages import model_json_to_pages-from mineru.types import (- ChartBlock,- DocTitleBlock,- EquationBlock,- ImageBlock,- ListBlock,- ModelJson,- PageInfo,- ParagraphTitleBlock,- RefTextBlock,- TableBlock,- TextBlock,-)-from _span_test_utils import equation, hyperlink, inline as _inline, inline_text---_RAW_INLINE_TYPES = {- "text",- "ref_text",- "doc_title",- "paragraph_title",- "header",- "footer",- "page_number",- "aside_text",- "page_footnote",- "list",- "index",- "caption",- "footnote",- "image_caption",- "image_footnote",- "table_caption",- "table_footnote",- "chart_caption",- "chart_footnote",- "code_caption",- "code_footnote",-}---def _spanize_blocks(blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:- """把本文件关注后处理逻辑的简写文字夹具转换为 Schema 2.0 Span。"""- for block in blocks:- block_type = str(block.get("type"))- content = block.get("content")- if block_type in _RAW_INLINE_TYPES and isinstance(content, str):- block["content"] = _inline(content) if content else []- elif block_type in {"list", "index"} and isinstance(content, list):- _spanize_blocks([child for child in content if isinstance(child, dict)])- return blocks---def _model_json(- pages: list[list[dict[str, Any]]],- *,- page_index_map: list[int] | None = None,-) -> ModelJson:- """为 PageInfo 后处理测试构造最小严格 ModelJson。"""- return ModelJson(- pages=[_spanize_blocks(deepcopy(page)) for page in pages],- page_index_map=page_index_map or [],- file_suffix="pdf",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )---def test_model_json_to_pages_replaces_raw_model_list_entrypoint() -> None:- """验证严格 ModelJson 是唯一文档级 PageInfo 转换入口。"""- assert callable(pages_module.model_json_to_pages)- assert not hasattr(pages_module, "model_list_to_pages")---def test_model_json_to_pages_keeps_equation_type_without_mutating_input() -> None:- """验证 equation 经单页后处理和严格对象化后保持类型、内容与图片载荷。"""- model_list = [- [- {- "type": "equation",- "bbox": [0.1, 0.2, 0.9, 0.4],- "content": r"\[x+1\]",- "image_base64": "data:image/jpeg;base64,/9j/2Q==",- }- ]- ]- original = deepcopy(model_list)-- page = model_json_to_pages(_model_json(model_list))[0]-- assert model_list == original- assert isinstance(page.blocks[0], EquationBlock)- assert page.blocks[0].type == "equation"- assert page.blocks[0].content == "x+1"- assert page.blocks[0].image_base64 == "data:image/jpeg;base64,/9j/2Q=="---def test_model_json_to_pages_returns_typed_pdf_tree_without_mutating_input() -> None:- """验证 PDF raw dict 只在副本上分组,并返回具体 PageInfo/Block 对象。"""- model_list = [- [- {"type": "image_caption", "bbox": [0.1, 0.05, 0.9, 0.1], "content": "Figure 1"},- {- "type": "image",- "bbox": [0.1, 0.12, 0.9, 0.45],- "content": None,- "image_base64": "data:image/jpeg;base64,/9j/2Q==",- },- {"type": "list", "bbox": [0.1, 0.5, 0.9, 0.8], "content": ""},- {"type": "text", "bbox": [0.15, 0.55, 0.85, 0.65], "content": "item"},- ]- ]- original = deepcopy(model_list)-- pages = model_json_to_pages(_model_json(model_list, page_index_map=[7]))-- assert model_list == original- assert isinstance(pages[0], PageInfo)- assert pages[0].page_idx == 7- assert isinstance(pages[0].blocks[0], ImageBlock)- assert [child.type for child in pages[0].blocks[0].content] == [- "image_caption",- "image_body",- ]- assert isinstance(pages[0].blocks[1], ListBlock)- assert isinstance(pages[0].blocks[1].content[0], TextBlock)---def test_model_json_to_pages_preserves_recursive_office_list_and_index() -> None:- """验证 Office list/index 任意深度递归对象化,并清理未匹配目录 anchor。"""- model_list = [- [- {- "type": "list",- "attribute": "ordered",- "ilevel": 0,- "start": 1,- "content": [- {"type": "text", "content": "first"},- {- "type": "list",- "attribute": "unordered",- "ilevel": 1,- "content": [- {"type": "text", "content": "child"},- {"type": "list", "content": [{"type": "text", "content": "deep"}]},- ],- },- ],- },- {- "type": "index",- "content": [- {- "type": "index",- "content": [{"type": "text", "content": "section", "anchor": "a1"}],- }- ],- },- ]- ]-- page = model_json_to_pages(_model_json(model_list))[0]- list_block = page.blocks[0]- index_block = page.blocks[1]-- assert isinstance(list_block, ListBlock)- assert inline_text(list_block.content[0].content) == "1. first"- assert isinstance(list_block.content[1], ListBlock)- assert inline_text(list_block.content[1].content[0].content) == "- child"- assert isinstance(list_block.content[1].content[1], ListBlock)- assert inline_text(index_block.content[0].content[0].content) == "section"- assert "anchor" not in index_block.content[0].content[0].model_fields_set---def test_fix_office_list_blocks_uses_local_ordered_markers_at_each_depth() -> None:- """验证多级 Office 有序列表按当前层独立编号,并保留富文本与各层起始值。"""- rich_content = [*_inline("root", styles=["bold"]), equation("x"), hyperlink("https://example.com", "link")]- list_block = {- "type": "list",- "attribute": "ordered",- "ilevel": 0,- "start": 3,- "content": [- {"type": "text", "content": rich_content},- {- "type": "list",- "attribute": "unordered",- "ilevel": 1,- "content": [- {"type": "text", "content": "bullet before"},- {- "type": "list",- "attribute": "ordered",- "ilevel": 2,- "start": 1,- "content": [- {"type": "text", "content": "level two first"},- {"type": "text", "content": "level two second"},- {- "type": "list",- "attribute": "ordered",- "ilevel": 3,- "start": 0,- "content": [- {"type": "text", "content": "zero"},- {"type": "text", "content": "one"},- ],- },- {"type": "text", "content": "level two third"},- {- "type": "list",- "attribute": "ordered",- "ilevel": 3,- "start": 5,- "content": [- {"type": "text", "content": "five"},- {"type": "text", "content": "six"},- ],- },- {"type": "text", "content": "level two fourth"},- ],- },- {"type": "text", "content": "bullet after"},- ],- },- {"type": "text", "content": "root after nested"},- ],- }- invalid_start_list = {- "type": "list",- "attribute": "ordered",- "ilevel": 0,- "start": "invalid",- "content": [{"type": "text", "content": "fallback"}],- }-- _spanize_blocks([list_block, invalid_start_list])- result = fix_office_list_blocks([list_block, invalid_start_list])-- assert result == [list_block, invalid_start_list]- assert inline_text(list_block["content"][0]["content"]) == "3. rootxlink"- assert inline_text(list_block["content"][2]["content"]) == "4. root after nested"- unordered = list_block["content"][1]- assert inline_text(unordered["content"][0]["content"]) == "- bullet before"- assert inline_text(unordered["content"][2]["content"]) == "- bullet after"- level_two = unordered["content"][1]- assert [inline_text(level_two["content"][index]["content"]) for index in (0, 1, 3, 5)] == [- "1. level two first",- "2. level two second",- "3. level two third",- "4. level two fourth",- ]- zero_start = level_two["content"][2]- assert [inline_text(child["content"]) for child in zero_start["content"]] == ["0. zero", "1. one"]- five_start = level_two["content"][4]- assert [inline_text(child["content"]) for child in five_start["content"]] == ["5. five", "6. six"]- assert inline_text(invalid_start_list["content"][0]["content"]) == "1. fallback"-- pending_lists = list(result)- while pending_lists:- current = pending_lists.pop()- assert {"attribute", "ilevel", "start"}.isdisjoint(current)- pending_lists.extend(- child for child in current.get("content", []) if isinstance(child, dict) and child.get("type") == "list"- )---def test_model_json_to_pages_maps_index_anchor_to_document_title_type_and_level() -> None:- """验证 Office 目录叶子按跨页目标 anchor 继承真实标题类型与层级。"""- model_list = [- [- {- "type": "index",- "content": [- {"type": "text", "content": "Document", "anchor": "doc-anchor"},- {- "type": "index",- "content": [- {"type": "text", "content": "Section", "anchor": "section-anchor"},- {"type": "text", "content": "Missing", "anchor": "missing-anchor"},- ],- },- ],- },- ],- [- {"type": "doc_title", "content": "Document title", "level": 1, "anchor": "doc-anchor"},- {- "type": "paragraph_title",- "content": "Section title",- "level": 3,- "anchor": "section-anchor",- },- ],- ]-- pages = model_json_to_pages(_model_json(model_list))- index = pages[0].blocks[0]- doc_leaf = index.content[0]- section_leaf = index.content[1].content[0]- missing_leaf = index.content[1].content[1]-- assert isinstance(doc_leaf, DocTitleBlock)- assert doc_leaf.level == 1- assert doc_leaf.anchor == "doc-anchor"- assert inline_text(doc_leaf.content) == "Document"- assert isinstance(section_leaf, ParagraphTitleBlock)- assert section_leaf.level == 3- assert section_leaf.anchor == "section-anchor"- assert inline_text(section_leaf.content) == "Section"- assert isinstance(missing_leaf, TextBlock)- assert "anchor" not in missing_leaf.model_fields_set---def test_model_json_to_pages_uses_first_title_for_duplicate_anchor() -> None:- """验证重复 anchor 按文档顺序使用首个标题目标。"""- model_list = [- [- {"type": "paragraph_title", "content": "First", "level": 2, "anchor": "same"},- {"type": "paragraph_title", "content": "Second", "level": 4, "anchor": "same"},- {- "type": "index",- "content": [{"type": "text", "content": "Entry", "anchor": "same"}],- },- ]- ]-- page = model_json_to_pages(_model_json(model_list))[0]- index = page.blocks[2]-- assert isinstance(index.content[0], ParagraphTitleBlock)- assert index.content[0].level == 2---def test_office_paragraph_numbering_is_document_wide_and_copy_only() -> None:- """验证 Office 标题跨页编号、显式编号同步和 raw 元数据保留。"""- model_list = [- [- {"type": "paragraph_title", "content": "<b>A</b>", "level": 1, "is_numbered_style": True},- {"type": "paragraph_title", "content": "B", "level": 3, "is_numbered_style": True},- ],- [- {"type": "paragraph_title", "content": "1.4 Explicit", "level": 3, "is_numbered_style": False},- {"type": "paragraph_title", "content": "C", "level": 3, "is_numbered_style": True},- {"type": "paragraph_title", "content": "No level", "is_numbered_style": True},- ],- ]- original = deepcopy(model_list)-- pages = model_json_to_pages(_model_json(model_list))- titles = [block for page in pages for block in page.blocks]-- assert all(isinstance(block, ParagraphTitleBlock) for block in titles)- assert [inline_text(block.content) for block in titles] == [- "1 <b>A</b>",- "1.1 B",- "1.4 Explicit",- "1.5 C",- "2 No level",- ]- assert [title.level for title in titles] == [2, 3, 3, 3, 2]- assert model_list == original---def test_office_paragraph_numbering_clears_deeper_levels() -> None:- """验证标题返回浅层时会清理旧深层计数,后续重新从一开始编号。"""- model_list = [- [- {"type": "paragraph_title", "content": "A", "level": 2, "is_numbered_style": True},- {"type": "paragraph_title", "content": "B", "level": 3, "is_numbered_style": True},- {"type": "paragraph_title", "content": "C", "level": 4, "is_numbered_style": True},- {"type": "paragraph_title", "content": "D", "level": 3, "is_numbered_style": True},- {"type": "paragraph_title", "content": "E", "level": 4, "is_numbered_style": True},- {"type": "paragraph_title", "content": "F", "level": 2, "is_numbered_style": True},- {"type": "paragraph_title", "content": "G", "level": 3, "is_numbered_style": True},- ]- ]-- titles = model_json_to_pages(_model_json(model_list))[0].blocks-- assert [inline_text(title.content) for title in titles] == [- "1 A",- "1.1 B",- "1.1.1 C",- "1.2 D",- "1.2.1 E",- "2 F",- "2.1 G",- ]---def test_visual_body_drops_empty_parent_subtype() -> None:- """验证 raw visual 的空 subtype 只用于父块判断,不会泄漏到严格 body 模型。"""- page = model_json_to_pages(_model_json([[{"type": "image", "content": None, "sub_type": None}]]))[0]-- assert isinstance(page.blocks[0], ImageBlock)- assert page.blocks[0].sub_type is None- assert page.blocks[0].content[0].type == "image_body"- assert page.blocks[0].content[0].content == ""---def test_chart_none_content_is_normalized_to_empty_string() -> None:- """验证 raw chart 的 null content 在严格对象化前规范为空字符串。"""- page = model_json_to_pages(_model_json([[{"type": "chart", "content": None}]]))[0]-- assert isinstance(page.blocks[0], ChartBlock)- assert page.blocks[0].content[0].type == "chart_body"- assert page.blocks[0].content[0].content == ""---def test_raw_title_levels_are_normalized_to_global_hierarchy() -> None:- """验证 raw 标题在严格对象化前归一为全局一至六级层级。"""- page = model_json_to_pages(- _model_json(- [- [- {"type": "doc_title", "content": "Document"},- {"type": "paragraph_title", "content": "Section", "level": 1},- {"type": "paragraph_title", "content": "Deep", "level": 9},- ]- ]- )- )[0]-- assert [block.level for block in page.blocks] == [1, 2, 6]---def test_pdf_raw_paragraph_title_level_is_clamped_to_six() -> None:- """验证带 bbox 的 PDF raw 深层标题在严格对象化前归一为六级。"""- page = model_json_to_pages(- _model_json([[{"type": "paragraph_title", "content": "Deep", "level": 9, "bbox": [0.1, 0.1, 0.9, 0.2]}]])- )[0]-- assert isinstance(page.blocks[0], ParagraphTitleBlock)- assert page.blocks[0].level == 6---def test_office_title_level_is_clamped_before_numbering_and_index_mapping() -> None:- """验证 Office 深层标题在编号和目录映射前归一为六级。"""- model_list = [- [- {- "type": "paragraph_title",- "content": "Deep",- "level": 9,- "anchor": "deep-anchor",- "is_numbered_style": True,- },- {- "type": "index",- "content": [{"type": "text", "content": "Deep entry", "anchor": "deep-anchor"}],- },- ]- ]-- page = model_json_to_pages(_model_json(model_list))[0]- title = page.blocks[0]- index = page.blocks[1]-- assert isinstance(title, ParagraphTitleBlock)- assert title.level == 6- assert inline_text(title.content) == "1.1.1.1.1 Deep"- assert isinstance(index.content[0], ParagraphTitleBlock)- assert index.content[0].level == 6---def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:- """验证 raw 段落延续在对象化前完成,公开 TextBlock 不保留临时 lines。"""- model_list = [- [- {- "type": "text",- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": "previous continuation",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],- },- {- "type": "text",- "bbox": [0.1, 0.25, 0.9, 0.45],- "content": "current continuation",- "lines": [{"bbox": [0.1, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],- },- ]- ]-- page = model_json_to_pages(_model_json(model_list))[0]-- assert all(isinstance(block, TextBlock) for block in page.blocks)- assert page.blocks[0].continues_prev is None- assert page.blocks[1].continues_prev is True- assert all("lines" not in type(block).model_fields for block in page.blocks)---def test_pdf_ref_text_continuation_is_typed_and_line_metadata_is_removed() -> None:- """验证 ref_text 续段标记越过 raw 边界,严格对象不保留临时 lines。"""- model_list = [- [- {- "type": "ref_text",- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": "previous continuation",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],- },- {- "type": "ref_text",- "bbox": [0.1, 0.25, 0.9, 0.45],- "content": "current continuation",- "lines": [{"bbox": [0.2, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],- },- ]- ]-- page = model_json_to_pages(_model_json(model_list))[0]-- assert all(isinstance(block, RefTextBlock) for block in page.blocks)- assert page.blocks[0].continues_prev is None- assert page.blocks[1].continues_prev is True- assert all("lines" not in type(block).model_fields for block in page.blocks)---def test_pdf_detection_scans_past_empty_first_page() -> None:- """验证整份文档 bbox 判定不会把 PDF 空白首页误认为 Office。"""- pages = model_json_to_pages(- _model_json(- [- [],- [{"type": "text", "bbox": [0.1, 0.1, 0.9, 0.3], "content": "later", "lines": []}],- ]- )- )-- assert pages[0].blocks == []- assert isinstance(pages[1].blocks[0], TextBlock)---def test_cross_page_table_continuation_remains_raw_postprocess() -> None:- """验证连续页表格仍在对象化前写入 continues_prev。"""- html_a = "<table><tr><td>A</td><td>B</td></tr></table>"- html_b = "<table><tr><td>C</td><td>D</td></tr></table>"- pages = model_json_to_pages(- _model_json(- [- [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_a}],- [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_b}],- ]- )- )-- assert isinstance(pages[0].blocks[0], TableBlock)- assert pages[0].blocks[0].continues_prev is None- assert pages[1].blocks[0].continues_prev is Truediff --git a/tests/unittest/test_postprocess_paragraphs.py b/tests/unittest/test_postprocess_paragraphs.pydeleted file mode 100644index 43bf32e9..00000000--- a/tests/unittest/test_postprocess_paragraphs.py+++ /dev/null@@ -1,1095 +0,0 @@-"""跨页段落延续规则的聚焦回归测试。"""--from copy import deepcopy--import pytest--from docvortex.postprocess.paragraphs import can_auto_merge_ref_text_blocks-from docvortex.postprocess.paragraphs import can_auto_merge_text_blocks-from docvortex.postprocess.paragraphs import merge_para_text_blocks-from mineru.types import BlockType--from _span_test_utils import inline as _inline, inline_text---def _text_block(- index: int,- content: str,- bbox: list[float],- line_bboxes: list[list[float]],- *,- block_type: str = BlockType.TEXT,-) -> dict:- """构造使用归一化 block/line bbox 的 dict text/ref_text block。"""- return {- "index": index,- "type": block_type,- "bbox": list(bbox),- "content": _inline(content),- "lines": [{"bbox": list(line_bbox)} for line_bbox in line_bboxes],- }---def _list_block(- index: int,- content: str,- *,- sub_type: str = BlockType.REF_TEXT,-) -> dict:- """构造带直属文本子项和临时行框的 dict list block。"""- child_type = BlockType.REF_TEXT if sub_type == BlockType.REF_TEXT else BlockType.TEXT- return {- "index": index,- "type": BlockType.LIST,- "sub_type": sub_type,- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": [- {- "type": child_type,- "content": _inline(content),- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- }- ],- }---def _horizontal_pair() -> tuple[dict, dict]:- """构造一组满足横排段落延续规则的前后 text block。"""- previous_block = _text_block(- 0,- "previous continuation",- [0.1, 0.1, 0.9, 0.3],- [[0.1, 0.1, 0.9, 0.15], [0.1, 0.2, 0.9, 0.25]],- )- current_block = _text_block(- 1,- "current continuation",- [0.1, 0.25, 0.9, 0.45],- [[0.1, 0.25, 0.9, 0.3], [0.1, 0.35, 0.9, 0.4]],- )- return previous_block, current_block---def _ref_text_horizontal_pair() -> tuple[dict, dict]:- """构造首行缩进但其余规则满足续接条件的 ref_text 块对。"""- previous_block, current_block = _horizontal_pair()- previous_block["type"] = BlockType.REF_TEXT- current_block["type"] = BlockType.REF_TEXT- current_block["lines"][0]["bbox"][0] = 0.2- return previous_block, current_block---def _horizontal_multiline_block(- index: int,- content: str,- *,- left: float,- right: float,- top: float,- line_count: int = 5,- line_height: float = 0.04,- first_indent: float = 0.0,-) -> dict:- """构造可控制首行缩进的横排多行正文块。"""- line_bboxes = [- [- left + (first_indent if line_index == 0 else 0.0),- top + line_index * line_height,- right,- top + (line_index + 1) * line_height,- ]- for line_index in range(line_count)- ]- return _text_block(- index,- content,- [min(line[0] for line in line_bboxes), top, right, top + line_count * line_height],- line_bboxes,- )---def _horizontal_single_line_block(- index: int,- content: str,- *,- left: float,- right: float,- top: float,- line_height: float = 0.04,-) -> dict:- """构造需要使用后续行补足虚拟宽度的横排单行块。"""- return _text_block(- index,- content,- [left, top, right, top + line_height],- [[left, top, right, top + line_height]],- )---def _vertical_multicolumn_block(- index: int,- content: str,- *,- right: float,- top: float,- bottom: float,- column_count: int = 5,- column_width: float = 0.04,- column_gap: float = 0.02,- first_top_indent: float = 0.0,-) -> dict:- """构造从右向左排列且可控制首列上边界的竖排多列正文块。"""- column_bboxes = [- [- right - column_width - column_index * (column_width + column_gap),- top + (first_top_indent if column_index == 0 else 0.0),- right - column_index * (column_width + column_gap),- bottom,- ]- for column_index in range(column_count)- ]- return _text_block(- index,- content,- [min(column[0] for column in column_bboxes), top, right, bottom],- column_bboxes,- )---def _vertical_single_column_block(- index: int,- content: str,- *,- left: float,- right: float,- top: float,- bottom: float,-) -> dict:- """构造需要使用后续列补足虚拟高度的竖排单列块。"""- return _text_block(- index,- content,- [left, top, right, bottom],- [[left, top, right, bottom]],- )---def _vertical_pair() -> tuple[dict, dict]:- """构造一组满足竖排段落延续规则的前后 text block。"""- previous_block = _text_block(- 0,- "previous vertical",- [0.65, 0.1, 0.9, 0.9],- [[0.82, 0.1, 0.87, 0.9], [0.72, 0.1, 0.77, 0.9]],- )- current_block = _text_block(- 1,- "current vertical",- [0.5, 0.1, 0.75, 0.9],- [[0.62, 0.1, 0.67, 0.9], [0.52, 0.1, 0.57, 0.9]],- )- return previous_block, current_block---def test_merge_para_text_blocks_marks_reverse_chain_without_moving_content() -> None:- """验证倒序处理会给连续链的后续块加标记,但不搬运正文或改写 bbox。"""- first_block, second_block = _horizontal_pair()- third_block = _text_block(- 2,- "third continuation",- [0.1, 0.4, 0.9, 0.6],- [[0.1, 0.4, 0.9, 0.45], [0.1, 0.5, 0.9, 0.55]],- )- pages = [{"page_idx": 0, "blocks": [first_block, second_block, third_block]}]- original_contents = [block["content"] for block in pages[0]["blocks"]]- original_bboxes = deepcopy([block["bbox"] for block in pages[0]["blocks"]])-- merge_para_text_blocks(pages)-- assert "continues_prev" not in first_block- assert second_block["continues_prev"] is True- assert third_block["continues_prev"] is True- assert [block["content"] for block in pages[0]["blocks"]] == original_contents- assert [block["bbox"] for block in pages[0]["blocks"]] == original_bboxes- assert all("lines" not in block for block in pages[0]["blocks"])-- first_result = deepcopy(pages)- merge_para_text_blocks(pages)- assert pages == first_result--- ("page_indices", "expected_continuation"),- [- ((0, 1), True),- ((0, 2), False),- ((2, 1), False),- ],-)-def test_merge_para_text_blocks_requires_consecutive_cross_page_indices(- page_indices: tuple[int, int],- expected_continuation: bool,-) -> None:- """验证跨页 text 仅允许从前一连续页延续。"""- previous_block, current_block = _horizontal_pair()- pages = [- {"page_idx": page_indices[0], "blocks": [previous_block]},- {"page_idx": page_indices[1], "blocks": [current_block]},- ]-- merge_para_text_blocks(pages)-- assert current_block.get("continues_prev", False) is expected_continuation--- ("middle_type", "expected_continuation"),- [- (BlockType.IMAGE, True),- (BlockType.CODE, True),- (BlockType.HEADER, True),- (BlockType.FOOTER, True),- (BlockType.PAGE_NUMBER, True),- (BlockType.PAGE_FOOTNOTE, True),- (BlockType.ASIDE_TEXT, True),- (BlockType.DOC_TITLE, False),- (BlockType.LIST, False),- (BlockType.REF_TEXT, False),- ],-)-def test_merge_para_text_blocks_respects_transparent_and_barrier_types(- middle_type: str,- expected_continuation: bool,-) -> None:- """验证视觉根块和页面装饰块可跨过,其他语义块会阻断 text 查找。"""- previous_block, current_block = _horizontal_pair()- middle_block = {- "index": 1,- "type": middle_type,- "bbox": [0.1, 0.22, 0.9, 0.24],- "content": "middle",- }- current_block["index"] = 2- pages = [{"page_idx": 0, "blocks": [previous_block, middle_block, current_block]}]-- merge_para_text_blocks(pages)-- assert current_block.get("continues_prev", False) is expected_continuation---def test_merge_para_text_blocks_ignores_cross_page_decorations() -> None:- """验证跨页正文会跳过前页尾部和后页头部的全部页面装饰块。"""- previous_block, current_block = _horizontal_pair()- current_block["index"] = 3- pages = [- {- "page_idx": 0,- "blocks": [- previous_block,- {"index": 1, "type": BlockType.FOOTER, "content": "footer"},- {"index": 2, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},- ],- },- {- "page_idx": 1,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "2"},- {"index": 2, "type": BlockType.ASIDE_TEXT, "content": "aside"},- current_block,- ],- },- ]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True- assert inline_text(previous_block["content"]) == "previous continuation"- assert inline_text(current_block["content"]) == "current continuation"- assert "lines" not in previous_block- assert "lines" not in current_block--- "barrier_type",- [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.EQUATION, BlockType.LIST],-)-def test_merge_para_text_blocks_keeps_cross_page_semantic_barriers(barrier_type: str) -> None:- """验证页面装饰块透明后,标题、公式和列表仍会阻断跨页正文连接。"""- previous_block, current_block = _horizontal_pair()- current_block["index"] = 2- pages = [- {- "page_idx": 0,- "blocks": [- previous_block,- {"index": 1, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},- ],- },- {- "page_idx": 1,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- {"index": 1, "type": barrier_type, "content": "barrier"},- current_block,- ],- },- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block---def test_merge_para_text_blocks_uses_following_lines_for_horizontal_single_line_width() -> None:- """验证横排单行会忽略缩进首行并使用其余四行补足虚拟栏宽。"""- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.1,- right=0.45,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(1, "tail.", left=0.55, right=0.67, top=0.1)- following_block = _horizontal_multiline_block(- 2,- "following paragraph.",- left=0.55,- right=0.9,- top=0.2,- first_indent=0.08,- )- pages = [{"page_idx": 0, "blocks": [previous_block, current_block, following_block]}]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True---def test_merge_para_text_blocks_uses_next_page_lines_for_horizontal_single_line_width() -> None:- """验证横排跨页单行使用当前页后续五行补足宽度而不依赖栏位数量。"""- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.55,- right=0.9,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.1, right=0.22, top=0.1)- following_block = _horizontal_multiline_block(- 1,- "following paragraph.",- left=0.1,- right=0.45,- top=0.2,- )- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block, following_block]},- ]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True---def test_merge_para_text_blocks_uses_following_columns_for_vertical_single_column_height() -> None:- """验证竖排单列会忽略上边界缩进首列并使用其余四列补足虚拟栏高。"""- previous_block = _vertical_multicolumn_block(- 0,- "未完",- right=0.9,- top=0.1,- bottom=0.9,- column_count=4,- )- current_block = _vertical_single_column_block(- 0,- "续。",- left=0.85,- right=0.9,- top=0.1,- bottom=0.3,- )- following_block = _vertical_multicolumn_block(- 1,- "後續正文。",- right=0.83,- top=0.1,- bottom=0.9,- first_top_indent=0.08,- )- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block, following_block]},- ]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True--[email protected]("is_vertical", [False, True])-def test_merge_para_text_blocks_requires_three_aligned_lookahead_lines(is_vertical: bool) -> None:- """验证横排或竖排后续同轴行列不足三条时不会构造虚拟尺寸。"""- if is_vertical:- previous_block = _vertical_multicolumn_block(- 0,- "未完",- right=0.9,- top=0.1,- bottom=0.9,- column_count=4,- )- current_block = _vertical_single_column_block(- 0,- "續。",- left=0.85,- right=0.9,- top=0.1,- bottom=0.3,- )- following_block = _vertical_multicolumn_block(- 1,- "短參考。",- right=0.83,- top=0.1,- bottom=0.9,- column_count=2,- )- else:- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.1,- right=0.45,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)- following_block = _horizontal_multiline_block(- 1,- "short reference.",- left=0.55,- right=0.9,- top=0.2,- line_count=2,- )- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block, following_block]},- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block--[email protected]("is_vertical", [False, True])-def test_merge_para_text_blocks_stops_single_line_lookahead_at_semantic_barrier(is_vertical: bool) -> None:- """验证标题屏障会阻止横排或竖排单行读取更后的参考行列。"""- if is_vertical:- previous_block = _vertical_multicolumn_block(- 0,- "未完",- right=0.9,- top=0.1,- bottom=0.9,- column_count=4,- )- current_block = _vertical_single_column_block(- 0,- "續。",- left=0.85,- right=0.9,- top=0.1,- bottom=0.3,- )- following_block = _vertical_multicolumn_block(- 2,- "後續正文。",- right=0.83,- top=0.1,- bottom=0.9,- )- else:- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.1,- right=0.45,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)- following_block = _horizontal_multiline_block(- 2,- "following paragraph.",- left=0.55,- right=0.9,- top=0.2,- )- barrier = {"index": 1, "type": BlockType.PARAGRAPH_TITLE, "content": "barrier"}- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block, barrier, following_block]},- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block--[email protected]("is_vertical", [False, True])-def test_merge_para_text_blocks_rejects_unaligned_following_geometry(is_vertical: bool) -> None:- """验证后续五行或列的轴起点与当前单行不对齐时不会补足虚拟尺寸。"""- if is_vertical:- previous_block = _vertical_multicolumn_block(- 0,- "未完",- right=0.9,- top=0.1,- bottom=0.9,- column_count=4,- )- current_block = _vertical_single_column_block(- 0,- "續。",- left=0.85,- right=0.9,- top=0.1,- bottom=0.3,- )- following_block = _vertical_multicolumn_block(- 1,- "錯位正文。",- right=0.83,- top=0.25,- bottom=0.9,- )- else:- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.1,- right=0.45,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)- following_block = _horizontal_multiline_block(- 1,- "misaligned paragraph.",- left=0.7,- right=0.95,- top=0.2,- )- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block, following_block]},- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block--[email protected]("is_vertical", [False, True])-def test_merge_para_text_blocks_does_not_look_beyond_current_page(is_vertical: bool) -> None:- """验证当前页没有参考行列时不会读取再下一页的五行或列。"""- if is_vertical:- previous_block = _vertical_multicolumn_block(- 0,- "未完",- right=0.9,- top=0.1,- bottom=0.9,- column_count=4,- )- current_block = _vertical_single_column_block(- 0,- "續。",- left=0.85,- right=0.9,- top=0.1,- bottom=0.3,- )- later_block = _vertical_multicolumn_block(- 0,- "更後正文。",- right=0.83,- top=0.1,- bottom=0.9,- )- else:- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.1,- right=0.45,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)- later_block = _horizontal_multiline_block(- 0,- "later paragraph.",- left=0.55,- right=0.9,- top=0.2,- )- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {"page_idx": 1, "blocks": [current_block]},- {"page_idx": 2, "blocks": [later_block]},- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block---def test_can_auto_merge_horizontal_text_blocks_rejects_paragraph_boundaries() -> None:- """验证横排规则会拒绝终止标点、特殊段首以及不满足几何条件的候选。"""- previous_block, current_block = _horizontal_pair()- assert can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- previous_block["content"] = _inline("finished.")- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- previous_block["content"] = "<hyperlink>finished.<url>https://example.test/no-period</url></hyperlink>"- assert not can_auto_merge_text_blocks(current_block, previous_block)-- for current_content in ("1 numbered", "Uppercase"):- previous_block, current_block = _horizontal_pair()- current_block["content"] = current_content- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- current_block["content"] = "<hyperlink>Uppercase<url>https://example.test/lowercase</url></hyperlink>"- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- current_block["lines"][0]["bbox"][0] = 0.2- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- previous_block["lines"][-1]["bbox"][2] = 0.7- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- for line in current_block["lines"]:- line["bbox"][2] = 0.4- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- previous_block["lines"] = previous_block["lines"][:1]- current_block["lines"] = current_block["lines"][:1]- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _horizontal_pair()- current_block["bbox"][1] = 0.31- assert not can_auto_merge_text_blocks(current_block, previous_block)---def test_merge_para_text_blocks_supports_vertical_but_rejects_mixed_orientation() -> None:- """验证竖排块可以连续,而横竖方向不一致时不会误标记。"""- previous_vertical, current_vertical = _vertical_pair()- vertical_pages = [{"page_idx": 0, "blocks": [previous_vertical, current_vertical]}]-- merge_para_text_blocks(vertical_pages)-- assert current_vertical["continues_prev"] is True-- previous_vertical, _ = _vertical_pair()- _, current_horizontal = _horizontal_pair()- mixed_pages = [{"page_idx": 0, "blocks": [previous_vertical, current_horizontal]}]-- merge_para_text_blocks(mixed_pages)-- assert "continues_prev" not in current_horizontal---def test_ref_text_rule_relaxes_leading_edge_and_initial_character() -> None:- """验证 ref_text 放宽当前起始边界以及数字或大写字符开头限制。"""- previous_block, current_block = _ref_text_horizontal_pair()- assert can_auto_merge_ref_text_blocks(current_block, previous_block)- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- previous_block["content"] = "finished."- assert not can_auto_merge_ref_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- current_block["content"] = _inline("Uppercase")- assert can_auto_merge_ref_text_blocks(current_block, previous_block)- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- current_block["content"] = _inline("1470–1480, Beijing, China.")- assert can_auto_merge_ref_text_blocks(current_block, previous_block)- assert not can_auto_merge_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- previous_block["lines"][-1]["bbox"][2] = 0.7- assert not can_auto_merge_ref_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- for line in current_block["lines"]:- line["bbox"][2] = 0.4- assert not can_auto_merge_ref_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- previous_block["lines"] = previous_block["lines"][:1]- current_block["lines"] = current_block["lines"][:1]- assert not can_auto_merge_ref_text_blocks(current_block, previous_block)-- previous_block, current_block = _ref_text_horizontal_pair()- current_block["bbox"][1] = 0.31- assert not can_auto_merge_ref_text_blocks(current_block, previous_block)-- previous_vertical, current_vertical = _vertical_pair()- previous_vertical["type"] = BlockType.REF_TEXT- current_vertical["type"] = BlockType.REF_TEXT- current_vertical["lines"][0]["bbox"][1] = 0.2- assert can_auto_merge_ref_text_blocks(current_vertical, previous_vertical)- assert not can_auto_merge_text_blocks(current_vertical, previous_vertical)---def test_merge_para_text_blocks_marks_indented_ref_text_without_moving_content() -> None:- """验证页内 ref_text 只在后块写标记,并保留内容与 bbox。"""- previous_block, current_block = _ref_text_horizontal_pair()- pages = [{"page_idx": 0, "blocks": [previous_block, current_block]}]- original_contents = [previous_block["content"], current_block["content"]]- original_bboxes = deepcopy([previous_block["bbox"], current_block["bbox"]])-- merge_para_text_blocks(pages)-- assert "continues_prev" not in previous_block- assert current_block["continues_prev"] is True- assert [previous_block["content"], current_block["content"]] == original_contents- assert [previous_block["bbox"], current_block["bbox"]] == original_bboxes- assert "lines" not in previous_block- assert "lines" not in current_block-- first_result = deepcopy(pages)- merge_para_text_blocks(pages)- assert pages == first_result---def test_merge_para_text_blocks_marks_numeric_reference_page_range() -> None:- """验证数字页码范围开头的 ref_text 可以续接前一条未结束参考文献。"""- previous_block, current_block = _ref_text_horizontal_pair()- previous_block["content"] = _inline("Proceedings of the conference, pages")- current_block["content"] = _inline("1470–1480, Beijing, China.")- pages = [{"page_idx": 0, "blocks": [previous_block, current_block]}]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True--- ("page_indices", "expected_continuation"),- [((0, 1), True), ((0, 2), False), ((2, 1), False)],-)-def test_merge_para_text_blocks_requires_consecutive_ref_text_pages(- page_indices: tuple[int, int],- expected_continuation: bool,-) -> None:- """验证 ref_text 仅允许从同一阅读链的前一连续页续接。"""- previous_block, current_block = _ref_text_horizontal_pair()- pages = [- {"page_idx": page_indices[0], "blocks": [previous_block]},- {"page_idx": page_indices[1], "blocks": [current_block]},- ]-- merge_para_text_blocks(pages)-- assert current_block.get("continues_prev", False) is expected_continuation---def test_merge_para_text_blocks_skips_page_auxiliary_blocks_between_ref_text() -> None:- """验证跨页 ref_text 会跳过全部页面辅助块查找前序 ref_text。"""- previous_block, current_block = _ref_text_horizontal_pair()- current_block["index"] = 3- pages = [- {- "page_idx": 8,- "blocks": [- previous_block,- {"index": 1, "type": BlockType.FOOTER, "content": "footer"},- {"index": 2, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},- ],- },- {- "page_idx": 9,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "9"},- {"index": 2, "type": BlockType.ASIDE_TEXT, "content": "aside"},- current_block,- ],- },- ]-- merge_para_text_blocks(pages)-- assert current_block["continues_prev"] is True--- "barrier_type",- [BlockType.TEXT, BlockType.PARAGRAPH_TITLE, BlockType.IMAGE, BlockType.TABLE, BlockType.LIST],-)-def test_merge_para_text_blocks_keeps_semantic_barriers_between_ref_text(barrier_type: str) -> None:- """验证 ref_text 不能跨越页面辅助类型之外的语义块。"""- previous_block, current_block = _ref_text_horizontal_pair()- current_block["index"] = 2- barrier = {- "index": 1,- "type": barrier_type,- "content": [] if barrier_type == BlockType.LIST else "barrier",- }- pages = [{"page_idx": 0, "blocks": [previous_block, barrier, current_block]}]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_block--- ("following_type", "expected_continuation"),- [(BlockType.REF_TEXT, True), (BlockType.TEXT, False)],-)-def test_ref_text_single_line_lookahead_uses_only_same_type(- following_type: str,- expected_continuation: bool,-) -> None:- """验证 ref_text 单行只使用当前页后续 ref_text 补足虚拟栏宽。"""- previous_block = _horizontal_multiline_block(- 0,- "unfinished",- left=0.55,- right=0.9,- top=0.5,- line_count=4,- )- current_block = _horizontal_single_line_block(0, "tail.", left=0.1, right=0.22, top=0.1)- following_block = _horizontal_multiline_block(- 2,- "following reference.",- left=0.1,- right=0.45,- top=0.2,- )- previous_block["type"] = BlockType.REF_TEXT- current_block["type"] = BlockType.REF_TEXT- following_block["type"] = following_type- pages = [- {"page_idx": 0, "blocks": [previous_block]},- {- "page_idx": 1,- "blocks": [- current_block,- {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "2"},- following_block,- ],- },- ]-- merge_para_text_blocks(pages)-- assert current_block.get("continues_prev", False) is expected_continuation---def test_ref_list_and_ref_text_store_independent_continuation_markers() -> None:- """验证 xhigh 风格结果中的 ref list 与顶层 ref_text 分别保存续接标记。"""- previous_list = _list_block(0, "ref one")- current_list = _list_block(1, "ref two")- previous_ref_text, current_ref_text = _ref_text_horizontal_pair()- previous_ref_text["index"] = 2- current_ref_text["index"] = 3- pages = [- {- "page_idx": 0,- "blocks": [- previous_list,- {"index": 1, "type": BlockType.PAGE_FOOTNOTE, "content": "note"},- ],- },- {- "page_idx": 1,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- current_list,- previous_ref_text,- current_ref_text,- ],- },- ]-- merge_para_text_blocks(pages)-- assert current_list["continues_prev"] is True- assert current_ref_text["continues_prev"] is True- assert "continues_prev" not in previous_list- assert "continues_prev" not in previous_ref_text---def test_merge_para_text_blocks_marks_adjacent_ref_lists_without_moving_items() -> None:- """验证连续页的相邻参考文献 list 只增加标记,不搬运列表子项。"""- previous_list = {- "index": 0,- "type": BlockType.LIST,- "sub_type": BlockType.REF_TEXT,- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": [{"type": BlockType.REF_TEXT, "content": "ref one", "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}]}],- }- current_list = {- "index": 0,- "type": BlockType.LIST,- "sub_type": BlockType.REF_TEXT,- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": [{"type": BlockType.REF_TEXT, "content": "ref two", "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}]}],- }- pages = [- {"page_idx": 4, "blocks": [previous_list]},- {"page_idx": 5, "blocks": [current_list]},- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in previous_list- assert current_list["continues_prev"] is True- assert [child["content"] for child in previous_list["content"]] == ["ref one"]- assert [child["content"] for child in current_list["content"]] == ["ref two"]- assert "lines" not in previous_list["content"][0]- assert "lines" not in current_list["content"][0]-- previous_list, current_list = deepcopy(previous_list), deepcopy(current_list)- current_list.pop("continues_prev", None)- gap_pages = [- {"page_idx": 4, "blocks": [previous_list]},- {"page_idx": 6, "blocks": [current_list]},- ]- merge_para_text_blocks(gap_pages)- assert "continues_prev" not in current_list-- previous_list = _list_block(0, "ref one")- current_list = _list_block(0, "ordinary item", sub_type=BlockType.TEXT)- merge_para_text_blocks(- [- {"page_idx": 4, "blocks": [previous_list]},- {"page_idx": 5, "blocks": [current_list]},- ]- )- assert "continues_prev" not in current_list---def test_merge_para_text_blocks_skips_page_auxiliary_blocks_between_ref_lists() -> None:- """验证跨页参考文献会跳过前后页的全部页面辅助块建立延续关系。"""- previous_list = _list_block(0, "ref one")- current_list = _list_block(3, "ref two")- pages = [- {- "page_idx": 8,- "blocks": [- previous_list,- {"index": 1, "type": BlockType.FOOTER, "content": "footer"},- {"index": 2, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},- ],- },- {- "page_idx": 9,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "9"},- {"index": 2, "type": BlockType.ASIDE_TEXT, "content": "aside"},- current_list,- ],- },- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in previous_list- assert current_list["continues_prev"] is True- assert inline_text(previous_list["content"][0]["content"]) == "ref one"- assert inline_text(current_list["content"][0]["content"]) == "ref two"- assert "lines" not in previous_list["content"][0]- assert "lines" not in current_list["content"][0]--- "barrier_type",- [BlockType.TEXT, BlockType.PARAGRAPH_TITLE, BlockType.IMAGE, BlockType.TABLE, BlockType.LIST],-)-def test_merge_para_text_blocks_keeps_semantic_barriers_between_ref_lists(barrier_type: str) -> None:- """验证页面辅助块透明后,其他语义块仍会阻断参考文献列表延续。"""- previous_list = _list_block(0, "ref one")- current_list = _list_block(2, "ref two")- barrier = {- "index": 1,- "type": barrier_type,- "content": [] if barrier_type == BlockType.LIST else "barrier",- }- pages = [- {- "page_idx": 8,- "blocks": [- previous_list,- {"index": 1, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},- ],- },- {- "page_idx": 9,- "blocks": [- {"index": 0, "type": BlockType.HEADER, "content": "header"},- barrier,- current_list,- ],- },- ]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in current_list---def test_merge_para_text_blocks_cleans_nested_lines_and_invalid_stale_markers() -> None:- """验证非法 text 不合并,同时递归清理临时行框和过期标记。"""- nested_child = {- "type": BlockType.IMAGE_CAPTION,- "content": "caption",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- "continues_prev": True,- }- visual_block = {- "index": 0,- "type": BlockType.IMAGE,- "bbox": [0.1, 0.1, 0.9, 0.5],- "content": [nested_child],- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.5]}],- }- invalid_text = {- "index": 1,- "type": BlockType.TEXT,- "bbox": [0.1, 0.5, 0.9, 0.7],- "content": "invalid lines",- "lines": [{"bbox": [0.1, 0.5, 0.9]}],- "continues_prev": True,- }- pages = [{"page_idx": 0, "blocks": [visual_block, invalid_text]}]-- merge_para_text_blocks(pages)-- assert "continues_prev" not in nested_child- assert "continues_prev" not in invalid_text- assert "lines" not in visual_block- assert "lines" not in nested_child- assert "lines" not in invalid_textdiff --git a/tests/unittest/test_postprocess_visual.py b/tests/unittest/test_postprocess_visual.pydeleted file mode 100644index 4e43f508..00000000--- a/tests/unittest/test_postprocess_visual.py+++ /dev/null@@ -1,393 +0,0 @@-"""视觉块后处理规则的聚焦回归测试。"""--from __future__ import annotations--from docvortex.postprocess.visual import VISUAL_MAIN_TYPES-from docvortex.postprocess.visual import _bbox_for_calculation-from docvortex.postprocess.visual import fallback_inline_caption_fragments-from docvortex.postprocess.visual import fallback_leading_table_continuation_captions-from docvortex.postprocess.visual import fallback_no_bbox_caption_fragments-from docvortex.postprocess.visual import find_best_visual_parent-from docvortex.postprocess.visual import is_block_outside_visual_gap-from docvortex.postprocess.visual import regroup_visual_blocks-from mineru.types import RAW_CAPTION, RAW_FOOTNOTE-from mineru.types import BlockType---def _line_metadata(count: int) -> list[dict[str, list[float]]]:- """构造仅包含 bbox 的 dict 行级元数据。"""- return [{"bbox": [0.0, float(index), 1.0, float(index + 1)]} for index in range(count)]---def test_bbox_for_calculation_scales_only_all_unit_range_coordinates() -> None:- """验证仅四个坐标均不大于一时生成放大后的计算副本。"""- normalized_bbox = (0.123, 0.221, 0.445, 0.556)-- assert _bbox_for_calculation(normalized_bbox) == (123.0, 221.0, 445.0, 556.0)- assert normalized_bbox == (0.123, 0.221, 0.445, 0.556)- assert _bbox_for_calculation((123, 221, 445, 556)) == (123, 221, 445, 556)- assert _bbox_for_calculation((0.123, 0.221, 0.445, 1.0)) == (123.0, 221.0, 445.0, 1000.0)- assert _bbox_for_calculation((0.123, 0.221, 0.445, 1.001)) == (0.123, 0.221, 0.445, 1.001)---def test_normalized_dict_bbox_matches_scaled_caption_geometry_without_rewrite() -> None:- """验证 dict 归一化框与千倍坐标使用相同标题几何且不回写 bbox。"""- companion = {- "index": 1,- "type": BlockType.TEXT,- "bbox": [0.02, 0.125, 0.1, 0.145],- "content": "unrelated text",- "lines": _line_metadata(1),- }- normalized_blocks = [- {- "index": 0,- "type": RAW_CAPTION,- "bbox": [0.7, 0.1, 0.95, 0.12],- "content": "Table 1",- "lines": _line_metadata(1),- },- companion,- {- "index": 2,- "type": BlockType.TABLE_BODY,- "bbox": [0.7, 0.15, 0.95, 0.8],- "content": "",- },- ]- original_bboxes = [list(block["bbox"]) for block in normalized_blocks]- scaled_blocks = [- {- **block,- "bbox": [value * 1000 for value in block["bbox"]],- }- for block in normalized_blocks- ]-- fallback_inline_caption_fragments(normalized_blocks, VISUAL_MAIN_TYPES)- fallback_inline_caption_fragments(scaled_blocks, VISUAL_MAIN_TYPES)-- assert companion["type"] == BlockType.TEXT- assert scaled_blocks[1]["type"] == BlockType.TEXT- assert [block["bbox"] for block in normalized_blocks] == original_bboxes---def test_normalized_dict_bbox_matches_scaled_visual_parent_without_rewrite() -> None:- """验证 raw dict 归一化框与千倍坐标选择同一视觉父块且保留原框。"""- previous_table = {"index": 0, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.1, 0.4, 0.4]}- caption = {"index": 1, "type": RAW_CAPTION, "bbox": [0.1, 0.42, 0.4, 0.44]}- following_table = {"index": 2, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.8, 0.4, 0.95]}- normalized_blocks = [previous_table, caption, following_table]- original_bboxes = [list(block["bbox"]) for block in normalized_blocks]- scaled_blocks = [{**block, "bbox": [value * 1000 for value in block["bbox"]]} for block in normalized_blocks]-- normalized_parent = find_best_visual_parent(- caption,- [previous_table, following_table],- normalized_blocks,- {block["index"]: position for position, block in enumerate(normalized_blocks)},- )- scaled_parent = find_best_visual_parent(- scaled_blocks[1],- [scaled_blocks[0], scaled_blocks[2]],- scaled_blocks,- {block["index"]: position for position, block in enumerate(scaled_blocks)},- )-- assert normalized_parent is previous_table- assert scaled_parent is scaled_blocks[0]- assert [block["bbox"] for block in normalized_blocks] == original_bboxes---def test_normalized_dict_bbox_matches_scaled_visual_gap_geometry() -> None:- """验证归一化框在视觉间隔、相交和重叠判断中与千倍坐标一致。"""- child = {"index": 0, "type": RAW_CAPTION, "bbox": [0.1, 0.1, 0.4, 0.2]}- inside_gap = {"index": 1, "type": BlockType.TEXT, "bbox": [0.8, 0.3, 0.9, 0.4]}- outside_gap = {"index": 2, "type": BlockType.TEXT, "bbox": [0.8, 0.8, 0.9, 0.9]}- main = {"index": 3, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.6, 0.4, 0.7]}- normalized_blocks = [child, inside_gap, outside_gap, main]- scaled_blocks = [{**block, "bbox": [value * 1000 for value in block["bbox"]]} for block in normalized_blocks]-- assert is_block_outside_visual_gap(inside_gap, child, main) is False- assert is_block_outside_visual_gap(outside_gap, child, main) is True- assert is_block_outside_visual_gap(scaled_blocks[1], scaled_blocks[0], scaled_blocks[3]) is False- assert is_block_outside_visual_gap(scaled_blocks[2], scaled_blocks[0], scaled_blocks[3]) is True---def test_dict_inline_caption_fragment_uses_common_fields() -> None:- """验证 dict 同行标题片段可原地改成通用 caption。"""- companion = {- "index": 1,- "type": BlockType.TEXT,- "bbox": [40.0, 0.0, 80.0, 10.0],- "content": "continued caption",- "lines": _line_metadata(1),- }- blocks = [- {- "index": 0,- "type": RAW_CAPTION,- "bbox": [0.0, 0.0, 40.0, 10.0],- "content": "Table 1",- "lines": _line_metadata(1),- },- companion,- {- "index": 2,- "type": BlockType.TABLE_BODY,- "bbox": [0.0, 15.0, 80.0, 60.0],- "content": "",- },- ]-- fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)-- assert companion["type"] == RAW_CAPTION---def test_dict_stacked_caption_fragment_uses_line_metadata() -> None:- """验证堆叠标题片段根据 dict 的临时 lines 区分单行和多行。"""- single_line = {- "index": 1,- "type": BlockType.TEXT,- "bbox": [0.0, 12.0, 80.0, 22.0],- "content": "single line",- "lines": _line_metadata(1),- }- blocks = [- {- "index": 0,- "type": RAW_CAPTION,- "bbox": [0.0, 0.0, 80.0, 10.0],- "content": "Table 1",- "lines": _line_metadata(1),- },- single_line,- {- "index": 2,- "type": BlockType.TABLE_BODY,- "bbox": [0.0, 25.0, 80.0, 60.0],- "content": "",- },- ]-- fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)-- assert single_line["type"] == RAW_CAPTION- single_line["type"] = BlockType.TEXT- single_line["lines"] = _line_metadata(2)-- fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)-- assert single_line["type"] == BlockType.TEXT---def test_dict_leading_table_continuation_reads_top_level_content() -> None:- """验证 dict 页首续表使用顶层 content 和临时 lines 完成判断。"""- continuation = {- "index": 0,- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 80.0, 10.0],- "content": "Table 1 (continued)",- "lines": _line_metadata(1),- }- blocks = [- continuation,- {- "index": 1,- "type": BlockType.TABLE_BODY,- "bbox": [0.0, 15.0, 80.0, 60.0],- "content": "",- },- ]-- fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)-- assert continuation["type"] == RAW_CAPTION---def test_regroup_visual_blocks_supports_bbox_dicts() -> None:- """验证带 bbox 的 dict 可沿用现有视觉关系规则生成 dict 两层块。"""- caption = {- "index": 0,- "type": RAW_CAPTION,- "bbox": [0.0, 0.0, 80.0, 10.0],- "content": "Figure 1",- "lines": [{"bbox": [0.0, 0.0, 80.0, 10.0]}],- }- body = {- "index": 1,- "type": BlockType.IMAGE_BODY,- "bbox": [0.0, 15.0, 80.0, 60.0],- "content": "",- }- footnote = {- "index": 2,- "type": RAW_FOOTNOTE,- "bbox": [0.0, 65.0, 80.0, 75.0],- "content": "source",- "lines": [{"bbox": [0.0, 65.0, 80.0, 75.0]}],- }-- grouped_blocks, unmatched_blocks = regroup_visual_blocks([caption, body, footnote])-- assert unmatched_blocks == []- assert len(grouped_blocks[BlockType.IMAGE]) == 1- image_block = grouped_blocks[BlockType.IMAGE][0]- assert isinstance(image_block, dict)- assert image_block["type"] == BlockType.IMAGE- assert image_block["bbox"] == body["bbox"]- assert [block["type"] for block in image_block["content"]] == [- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_BODY,- BlockType.IMAGE_FOOTNOTE,- ]- image_caption, _, image_footnote = image_block["content"]- assert "lines" not in image_caption- assert "lines" not in image_footnote- assert "lines" in caption- assert "lines" in footnote- assert caption["type"] == RAW_CAPTION- assert footnote["type"] == RAW_FOOTNOTE---def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:- """验证 dict 根节点保留 code subtype、视觉 subtype 与表格合并信息。"""- blocks = [- {- "index": 0,- "type": BlockType.CODE_BODY,- "content": "print('ok')",- "sub_type": "code",- },- {- "index": 1,- "type": BlockType.IMAGE_BODY,- "content": "",- "sub_type": "seal",- },- {- "index": 2,- "type": BlockType.TABLE_BODY,- "content": "<table></table>",- "angle": 0,- "score": 0.0,- "cell_merge": [1, 0],- },- ]-- grouped_blocks, _ = regroup_visual_blocks(blocks, use_bbox=False)-- code_block = grouped_blocks[BlockType.CODE][0]- image_block = grouped_blocks[BlockType.IMAGE][0]- table_block = grouped_blocks[BlockType.TABLE][0]- assert code_block["sub_type"] == "code"- assert "sub_type" not in code_block["content"][0]- assert image_block["sub_type"] == "seal"- assert "sub_type" not in image_block["content"][0]- assert "sub_type" not in table_block- assert "sub_type" not in table_block["content"][0]- assert table_block["content"][0]["angle"] == 0- assert table_block["content"][0]["score"] == 0.0- assert table_block["cell_merge"] == [1, 0]- assert "cell_merge" not in table_block["content"][0]---def test_regroup_visual_blocks_lifts_cell_merge_to_table() -> None:- """验证 raw dict 表体的 cell_merge 上浮到 table 根块。"""- table_body = {- "index": 0,- "type": BlockType.TABLE_BODY,- "bbox": [0.0, 0.0, 80.0, 60.0],- "content": "<table></table>",- "cell_merge": [1, 0],- }-- grouped_blocks, unmatched_blocks = regroup_visual_blocks([table_body])-- assert unmatched_blocks == []- table_block = grouped_blocks[BlockType.TABLE][0]- assert table_block["cell_merge"] == [1, 0]- assert len(table_block["content"]) == 1- assert "cell_merge" not in table_block["content"][0]---def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:- """验证无 bbox 等距匹配优先选择 caption 前方的视觉主体。"""- image_body = {"index": 0, "type": BlockType.IMAGE_BODY, "content": ""}- caption = {"index": 1, "type": RAW_CAPTION, "content": "Figure 1"}- table_body = {"index": 2, "type": BlockType.TABLE_BODY, "content": ""}-- grouped_blocks, unmatched_blocks = regroup_visual_blocks(- [image_body, caption, table_body],- use_bbox=False,- )-- assert unmatched_blocks == []- assert "bbox" not in grouped_blocks[BlockType.IMAGE][0]- assert [block["type"] for block in grouped_blocks[BlockType.IMAGE][0]["content"]] == [- BlockType.IMAGE_BODY,- BlockType.IMAGE_CAPTION,- ]- assert [block["type"] for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]---def test_regroup_visual_blocks_supports_code_footnote() -> None:- """验证具体 code_footnote 可直接归入 code,且不会残留为额外顶层块。"""- code_body = {- "index": 0,- "type": BlockType.CODE_BODY,- "content": "print('ok')",- "sub_type": "code",- }- code_footnote = {- "index": 1,- "type": BlockType.CODE_FOOTNOTE,- "content": "runtime note",- }-- grouped_blocks, unmatched_blocks = regroup_visual_blocks(- [code_body, code_footnote],- use_bbox=False,- )-- assert unmatched_blocks == []- assert [child["type"] for child in grouped_blocks[BlockType.CODE][0]["content"]] == [- BlockType.CODE_BODY,- BlockType.CODE_FOOTNOTE,- ]---def test_regroup_visual_blocks_without_bbox_keeps_text_as_barrier() -> None:- """验证无 bbox 模式不会跨过普通文本关联 caption。"""- caption = {"index": 0, "type": RAW_CAPTION, "content": "Table 1"}- text = {"index": 1, "type": BlockType.TEXT, "content": "paragraph"}- table_body = {"index": 2, "type": BlockType.TABLE_BODY, "content": ""}-- grouped_blocks, unmatched_blocks = regroup_visual_blocks(- [caption, text, table_body],- use_bbox=False,- )-- assert unmatched_blocks == [caption]- assert [block["type"] for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]---def test_no_bbox_caption_fallback_uses_office_prefixes() -> None:- """验证无 bbox 的 table/image/chart 后置文本按 Office 前缀提升。"""- cases = [- (BlockType.TABLE_BODY, "Table 1", RAW_CAPTION),- (BlockType.IMAGE_BODY, "图 1", RAW_CAPTION),- (BlockType.CHART_BODY, "Chart 1", RAW_CAPTION),- (BlockType.IMAGE_BODY, "ordinary text", BlockType.TEXT),- ]-- for main_type, content, expected_type in cases:- blocks = [- {"index": 0, "type": main_type, "content": ""},- {"index": 1, "type": BlockType.TEXT, "content": content},- ]-- fallback_no_bbox_caption_fragments(blocks, VISUAL_MAIN_TYPES)-- assert blocks[1]["type"] == expected_typediff --git a/tests/unittest/test_render_api.py b/tests/unittest/test_render_api.pyindex ad9cca1c..b99f604d 100644--- a/tests/unittest/test_render_api.py+++ b/tests/unittest/test_render_api.py@@ -1,18 +1,18 @@from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inlinefrom copy import deepcopyfrom datetime import datetime, timezone-from io import BytesIOfrom inspect import signature+from io import BytesIO+import pytest+from _span_test_utils import inline as _inline+from docvortex.schema import Producerfrom docx import Documentfrom PIL import Image-import pytestimport mineru.render as render_module+from mineru.integrations.docvortex import build_metadatafrom mineru.render import (ContentListRenderOptions,ContentListV2RenderOptions,diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.pydeleted file mode 100644index 0348a7b8..00000000--- a/tests/unittest/test_render_html_table.py+++ /dev/null@@ -1,129 +0,0 @@-import markdown-from bs4 import BeautifulSoup--from mineru.config import LatexDelimitersConfig-from docvortex.render._internal.markdown.table import format_embedded_html-from docvortex.render._internal.markdown.table import render_html_table---DELIMITERS = LatexDelimitersConfig()---def test_render_html_table_uses_first_row_when_th_is_absent() -> None:- """验证普通 td 首行可作为 GFM 表头。"""- html = "<table><tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr></table>"-- assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(- ["| A | B |", "| --- | --- |", "| 1 | 2 |"]- )---def test_render_html_table_preserves_supported_inline_markup() -> None:- """验证简单单元格保留链接、强调、代码、换行和上下标。"""- html = (- "<table><tr><th>Item</th><th>Note</th></tr>"- "<tr><td><code>x|y</code></td>"- '<td><a href="https://example.com">docs</a><br><strong>ready</strong><sup>2</sup></td></tr>'- "</table>"- )-- assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(- [- "| Item | Note |",- "| --- | --- |",- r"| `x\|y` | [docs](https://example.com)<br>**ready**<sup>2</sup> |",- ]- )---def test_render_html_table_uses_markdown_only_for_simple_style_sets() -> None:- """验证标准 HTML 标签按有效样式集合选择 Markdown 或完整 HTML wrapper。"""- html = (- "<table><tr><td><strong>bold</strong></td><td><em>italic</em></td>"- "<td><s>strike</s></td><td><em><strong>both</strong></em></td>"- "<td><strong><u>complex</u></strong></td>"- "<td><s><strong>mixed</strong></s></td>"- "<td><sup><strong>script</strong></sup></td></tr></table>"- )-- assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(- [- (- "| **bold** | *italic* | ~~strike~~ | ***both*** | "- "<strong><u>complex</u></strong> | <s><strong>mixed</strong></s> | "- "<strong><sup>script</sup></strong> |"- ),- "| --- | --- | --- | --- | --- | --- | --- |",- ]- )---def test_render_html_table_escapes_angle_brackets_from_text_nodes() -> None:- """验证实体解码后的文本尖括号不会重新变成可执行 Markdown HTML。"""- html = (- "<table><tr><th>Name</th><th>Value</th></tr>"- "<tr><td>unsafe</td><td><script>alert(1)</script></td></tr></table>"- )-- rendered = render_html_table(html, asset_base_url="", delimiters=DELIMITERS)-- assert rendered == "\n".join(- [- "| Name | Value |",- "| --- | --- |",- "| unsafe | <script>alert(1)</script> |",- ]- )- parsed = BeautifulSoup(markdown.markdown(rendered, extensions=["tables"]), "html.parser")- assert parsed.find("script") is None- assert parsed.find_all("td")[1].get_text() == "<script>alert(1)</script>"---def test_render_html_table_escapes_formula_pipes_without_changing_latex() -> None:- """验证 GFM 源码转义公式竖线,Markdown 解析后恢复原始 LaTeX。"""- formulas = [- r"\left|x\right|",- r"\|x\|",- r"\begin{array}{c|c}x\end{array}",- ]- rows = "".join(- f"<tr><td>F{index}</td><td><eq>{formula}</eq></td><td>ok</td></tr>" for index, formula in enumerate(formulas, start=1)- )- html = f"<table><tr><th>Name</th><th>Formula</th><th>Note</th></tr>{rows}</table>"-- rendered = render_html_table(html, asset_base_url="", delimiters=DELIMITERS)- assert rendered is not None- parsed = BeautifulSoup(markdown.markdown(rendered, extensions=["tables"]), "html.parser")- parsed_rows = parsed.find_all("tr")-- assert [len(row.find_all(["th", "td"], recursive=False)) for row in parsed_rows] == [3, 3, 3, 3]- assert [row.find_all("td", recursive=False)[1].get_text() for row in parsed_rows[1:]] == [- f"${formula}$" for formula in formulas- ]---def test_render_html_table_falls_back_for_span_attribute_even_when_value_is_one() -> None:- """验证只要显式出现 rowspan/colspan 就按复杂 HTML 输出。"""- html = '<table><tr><td colspan="1">A</td></tr></table>'-- assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == html---def test_format_embedded_html_rewrites_relative_images_and_equations() -> None:- """验证复杂 HTML 的相对图片和行内公式统一改写。"""- html = '<table><tr><td><img src="images/a.png"><eq>x<y</eq></td></tr></table>'-- formatted = format_embedded_html(html, asset_base_url="https://cdn.example/doc", delimiters=DELIMITERS)-- assert 'src="https://cdn.example/doc/images/a.png"' in formatted- assert "$x<y$" in formatted---def test_format_embedded_html_keeps_absolute_and_data_images() -> None:- """验证已经可访问的绝对图片来源不会重复添加 base URL。"""- html = '<table><tr><td><img src="https://example.com/a.png"><img src="data:image/png;base64,AAAA"></td></tr></table>'-- formatted = format_embedded_html(html, asset_base_url="https://cdn.example/doc", delimiters=DELIMITERS)-- assert "https://cdn.example/doc/https://" not in formatted- assert 'src="data:image/png;base64,AAAA"' in formatteddiff --git a/tests/unittest/test_render_image_renderer.py b/tests/unittest/test_render_image_renderer.pydeleted file mode 100644index 9f175b1e..00000000--- a/tests/unittest/test_render_image_renderer.py+++ /dev/null@@ -1,206 +0,0 @@-from __future__ import annotations-from _span_test_utils import inline as _inline--from unittest.mock import Mock--import pytest--from mineru.config import LatexDelimitersConfig, config-from mineru.render import ImageRenderer-from docvortex.render._internal.markdown.blocks import render_single_block-from mineru.types import (- BlockBase,- BlockType,- ChartBlock,- ChartBodyBlock,- EquationBlock,- ImageAnnotationBlock,- ImageBlock,- ImageBodyBlock,- TableBlock,- TableBodyBlock,-)---def _delimiters() -> LatexDelimitersConfig:- return config.render.latex_delimiters---def _image_block() -> ImageBlock:- body = ImageBodyBlock(- type=BlockType.IMAGE_BODY,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content="",- image_path="internal/hash.jpg",- )- caption = ImageAnnotationBlock(- type=BlockType.IMAGE_CAPTION,- index=0,- bbox=(0.0, 0.0, 0.1, 0.01),- content=_inline("Figure caption"),- )- return ImageBlock(- type=BlockType.IMAGE,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=[body, caption],- )---def test_pipeline_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:- block = _image_block()- renderer_mock = Mock(return_value="")- image_renderer: ImageRenderer = renderer_mock-- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=image_renderer,- )-- assert "" in rendered- assert "Figure caption" in rendered- assert "internal/hash.jpg" not in rendered- renderer_mock.assert_called_once_with(block)---def test_office_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:- block = _image_block()-- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=lambda _block: "![Image block]()",- )-- assert "![Image block]()" in rendered- assert "Figure caption" in rendered- assert "internal/hash.jpg" not in rendered--[email protected]("block_type", [BlockType.TABLE, BlockType.CHART])-def test_pipeline_markdown_uses_custom_renderer_for_image_only_visual_blocks(- block_type: BlockType,-) -> None:- if block_type == BlockType.TABLE:- block: BlockBase = TableBlock(- type=BlockType.TABLE,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=[- TableBodyBlock(- type=BlockType.TABLE_BODY,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content="",- image_path="internal/hash.jpg",- )- ],- )- else:- block = ChartBlock(- type=BlockType.CHART,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=[- ChartBodyBlock(- type=BlockType.CHART_BODY,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content="",- image_path="internal/hash.jpg",- )- ],- )-- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=lambda _block: "",- )-- assert rendered == ""---def test_pipeline_markdown_uses_custom_renderer_for_image_only_formula() -> None:- block = EquationBlock(- type=BlockType.EQUATION,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content="",- image_path="internal/hash.jpg",- )-- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=lambda _block: "",- )-- assert rendered == ""---def test_custom_renderer_removes_internal_images_from_structured_table_html() -> None:- internal_path = "internal/cell-image.png"- html = f'<table><tr><td>Text<img src="{internal_path}"></td></tr></table>'- block = TableBlock(- type=BlockType.TABLE,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=[- TableBodyBlock(- type=BlockType.TABLE_BODY,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=html,- )- ],- )-- image_renderer = Mock(return_value="")- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=image_renderer,- )-- assert "Text" in rendered- assert internal_path not in rendered- assert "<img" not in rendered- assert block.content[0].content == html- image_renderer.assert_not_called()---def test_custom_renderer_handles_table_html_containing_only_images() -> None:- internal_path = "internal/cell-image.png"- block = TableBlock(- type=BlockType.TABLE,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=[- TableBodyBlock(- type=BlockType.TABLE_BODY,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content=f'<table><tr><td><img src="{internal_path}"></td></tr></table>',- )- ],- )- image_renderer = Mock(return_value="")-- rendered = render_single_block(- block,- delimiters=_delimiters(),- asset_base_url="",- image_renderer=image_renderer,- )-- assert rendered == ""- assert internal_path not in rendered- image_renderer.assert_called_once_with(block)diff --git a/tests/unittest/test_render_list_index_utils.py b/tests/unittest/test_render_list_index_utils.pydeleted file mode 100644index 5b989ef8..00000000--- a/tests/unittest/test_render_list_index_utils.py+++ /dev/null@@ -1,173 +0,0 @@-from __future__ import annotations-from _span_test_utils import inline as _inline--import pytest--from docvortex.content.inline import inline_plain_text-from docvortex.render._internal.common.index import looks_like_index_page_token-from docvortex.render._internal.common.index import strip_index_page_tail-from docvortex.render._internal.common.list_items import has_markdown_unordered_marker-from docvortex.render._internal.common.list_items import parse_list_item_marker-from docvortex.render._internal.common.list_items import reference_list_needs_bullets-from mineru.types import ListBlock, RefTextBlock, TextBlock--- ("content", "marker", "body", "kind", "value", "ordered_style"),- [- ("- item", "-", "item", "unordered", None, None),- ("* item", "*", "item", "unordered", None, None),- ("+ item", "+", "item", "unordered", None, None),- ("12. item", "12.", "item", "ordered", 12, "decimal"),- ("a. item", "a.", "item", "ordered", 1, "lower-alpha"),- ("A. item", "A.", "item", "ordered", 1, "upper-alpha"),- ("i. item", "i.", "item", "ordered", 1, "lower-roman"),- ("I. item", "I.", "item", "ordered", 1, "upper-roman"),- ("iv. item", "iv.", "item", "ordered", 4, "lower-roman"),- ("XII. item", "XII.", "item", "ordered", 12, "upper-roman"),- ("12) item", "12)", "item", "explicit", None, None),- ("(12) item", "(12)", "item", "explicit", None, None),- ("(12. item", "(12.", "item", "explicit", None, None),- ("a) item", "a)", "item", "explicit", None, None),- ("[12] item", "[12]", "item", "explicit", None, None),- ("[x] done", "[x]", "done", "explicit", None, None),- ("[ ] pending", "[ ]", "pending", "explicit", None, None),- ("plain item", None, "plain item", "none", None, None),- ("-without-space", None, "-without-space", "none", None, None),- ],-)-def test_parse_list_item_marker_classifies_supported_styles(- content: str,- marker: str | None,- body: str,- kind: str,- value: int | None,- ordered_style: str | None,-) -> None:- """验证共享 parser 区分原生列表与需要显式 marker 的编号风格。"""- item = parse_list_item_marker(_inline(content))-- assert item.marker == marker- assert inline_plain_text(item.body) == body- assert item.kind == kind- assert item.value == value- assert item.ordered_style == ordered_style--[email protected]("content", [" 2. item", "\t- item", "- \ncontinued", " plain item"])-def test_parse_list_item_marker_preserves_reconstructable_whitespace(content: str) -> None:- """验证 parser 单独保存前导与分隔空白,并可无损重建原内容。"""- item = parse_list_item_marker(_inline(content))- reconstructed = item.leading- if item.marker is not None:- reconstructed += item.marker + item.separator- reconstructed += inline_plain_text(item.body)-- assert reconstructed == content---def test_single_roman_letters_use_stable_roman_precedence() -> None:- """验证与字母编号同形的罗马字符固定优先解释为罗马数字。"""- assert parse_list_item_marker(_inline("v. item")).ordered_style == "lower-roman"- assert parse_list_item_marker(_inline("v. item")).value == 5- assert parse_list_item_marker(_inline("c. item")).ordered_style == "lower-roman"- assert parse_list_item_marker(_inline("c. item")).value == 100- assert parse_list_item_marker(_inline("z. item")).ordered_style == "lower-alpha"- assert parse_list_item_marker(_inline("z. item")).value == 26--- "content",- [- f"{'9' * 5000}. item",- "1000001. item",- "01. item",- "001. item",- "IIII. item",- f"{'M' * 5000}. item",- ],-)-def test_unbounded_or_invalid_ordered_markers_degrade_to_explicit(content: str) -> None:- """验证超长、超界或非规范编号不会触发大整数异常,并原样保留 marker。"""- item = parse_list_item_marker(_inline(content))-- assert item.kind == "explicit"- assert item.marker is not None- assert item.value is None- assert item.ordered_style is None---def test_markdown_existing_bullet_detection_remains_hyphen_only() -> None:- """验证参考文献补 bullet 只避开既有短横线,保持 Markdown 历史输出。"""- assert has_markdown_unordered_marker(_inline(" - existing"))- assert not has_markdown_unordered_marker(_inline("* existing"))- assert not has_markdown_unordered_marker(_inline("+ existing"))- assert not has_markdown_unordered_marker(_inline("-without-space"))- assert not has_markdown_unordered_marker(_inline("-\ncontinued"))---def _reference_list(*children: TextBlock | RefTextBlock | ListBlock) -> ListBlock:- """构造用于严格多数判定的参考文献列表。"""- return ListBlock(type="list", sub_type="ref_text", content=list(children))---def test_reference_list_bullet_rule_uses_visible_direct_item_strict_majority() -> None:- """验证富文本可见数字、空项和嵌套列表遵守既有严格多数规则。"""- nested = _reference_list(RefTextBlock(type="ref_text", content=_inline("Author nested")))- numbered_majority = _reference_list(- RefTextBlock(- type="ref_text",- content=[- {"type": "text", "content": "[1]", "styles": ["bold"]},- {"type": "text", "content": " first"},- ],- ),- RefTextBlock(type="ref_text", content=_inline("missing marker")),- TextBlock(type="text", content=_inline("3) third")),- RefTextBlock(type="ref_text", content=[]),- nested,- )- tied = _reference_list(- RefTextBlock(type="ref_text", content=_inline("[1] first")),- RefTextBlock(type="ref_text", content=_inline("Author A")),- )-- assert not reference_list_needs_bullets(numbered_majority)- assert reference_list_needs_bullets(tied)- assert not reference_list_needs_bullets(ListBlock(type="list", sub_type="text", content=tied.content))--- ("content", "expected"),- [- ("Title", "Title"),- ("Title\t12", "Title"),- ('Title\t<text style="bold">IV</text>', "Title"),- ("Part\tSection\tA", "Part Section"),- ("Title\tAppendix", "Title Appendix"),- ("Title\tA2", "Title A2"),- ],-)-def test_strip_index_page_tail_uses_visible_tail_token(content: str, expected: str) -> None:- """验证目录仅删除可信的末尾页码,并把保留 tab 转为空格。"""- spans = (- [- {"type": "text", "content": "Title\t"},- {"type": "text", "content": "IV", "styles": ["bold"]},- ]- if "<text" in content- else _inline(content)- )- assert inline_plain_text(strip_index_page_tail(spans)) == expected--[email protected]("content", ["1", "12", "iv", "XII", "a", "Z"])-def test_index_page_token_accepts_supported_forms(content: str) -> None:- """验证数字、罗马数字与单字母可作为目录页码 token。"""- assert looks_like_index_page_token(content)--[email protected]("content", ["", "AB", "A2", "appendix", "1234567890123"])-def test_index_page_token_rejects_ambiguous_forms(content: str) -> None:- """验证空值、长值和普通词不会被误删为目录页码。"""- assert not looks_like_index_page_token(content)diff --git a/tests/unittest/test_structured_content_render.py b/tests/unittest/test_structured_content_render.pyindex cb64b5c9..2b7a69d5 100644--- a/tests/unittest/test_structured_content_render.py+++ b/tests/unittest/test_structured_content_render.py@@ -1,33 +1,26 @@from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata-from _span_test_utils import inline as _inlineimport jsonfrom copy import deepcopyimport pytest+from _span_test_utils import inline as _inline+from docvortex.schema import Producerfrom mineru.config import Config+from mineru.integrations.docvortex import build_metadatafrom mineru.render import render_markdown, render_structured_contentfrom mineru.types import (- AlgorithmBodyBlock,ChartAnnotationBlock,ChartBlock,ChartBodyBlock,- CodeBlock,EquationBlock,- ImageBlock,- IndexBlock,- ListBlock,MiddleJson,PageAuxTextBlock,PageBlock,PageFootnoteBlock,PageInfo,ParagraphTitleBlock,- TableBlock,- TableBodyBlock,TextBlock,)@@ -130,240 +123,6 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation(assert middle == original-def test_structured_content_flattens_recursive_list_index_and_code_metadata() -> None:- """验证递归容器和代码 body 上浮为 Markdown,渲染元数据不进入输出。"""- nested = ListBlock(- type="list",- content=[TextBlock(type="text", content=_inline("- inner"))],- )- list_block = ListBlock(- type="list",- index=0,- sub_type="text",- content=[TextBlock(type="text", content=_inline("- outer")), nested],- )- index_block = IndexBlock(- type="index",- index=1,- content=[- ParagraphTitleBlock(- type="paragraph_title",- level=2,- anchor="section-b",- content=_inline("Section\t12"),- )- ],- )- code = CodeBlock.model_validate(- {- "type": "code",- "index": 2,- "sub_type": "code",- "guess_lang": "python",- "content": [- {- "type": "code_caption",- "index": 4,- "bbox": [0.1, 0.1, 0.5, 0.2],- "content": _inline("Example", styles=["bold"]),- },- {"type": "code_body", "index": 2, "content": "print('x')\n```"},- {- "type": "code_footnote",- "index": 5,- "bbox": [0.1, 0.8, 0.5, 0.9],- "content": [- {"type": "text", "content": "note "},- {"type": "equation_inline", "content": "x"},- ],- },- ],- }- )-- blocks = render_structured_content(_middle(_page(0, list_block, index_block, code)))["pages"][0]["blocks"]-- assert blocks[0]["content"] == "- outer\n - inner"- assert blocks[1]["content"] == "- [Section](#section-b)"- assert blocks[2]["content"] == "````python\nprint('x')\n```\n````"- assert blocks[2]["captions"] == [{"bbox": [0.1, 0.1, 0.5, 0.2], "content": "**Example**"}]- assert blocks[2]["footnotes"] == [{"bbox": [0.1, 0.8, 0.5, 0.9], "content": "note $x$"}]- assert "guess_lang" not in blocks[2]- _assert_output_field_contract(blocks)---def test_structured_content_renders_algorithm_as_markdown_like_content() -> None:- """验证算法 content 使用简单 Markdown 样式并为复杂样式降级到 HTML。"""- algorithm = CodeBlock(- type="code",- index=0,- sub_type="algorithm",- content=[- AlgorithmBodyBlock(- type="algorithm_body",- index=0,- content=[- {"type": "text", "content": "if x:\n "},- {"type": "text", "content": "bold", "styles": ["bold"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "italic", "styles": ["italic"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "strike", "styles": ["strikethrough"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "under", "styles": ["underline"]},- {"type": "text", "content": " / "},- {"type": "text", "content": "dot", "styles": ["emphasis"]},- {"type": "text", "content": " "},- {"type": "text", "content": "q", "styles": ["subscript"]},- {"type": "text", "content": "2", "styles": ["superscript"]},- {"type": "text", "content": " = "},- {"type": "equation_inline", "content": "x"},- {"type": "equation_inline", "content": "y"},- ],- )- ],- )-- output = render_structured_content(_middle(_page(0, algorithm)))["pages"][0]["blocks"][0]-- assert output["content"] == (- "if x:\n **bold** / *italic* / ~~strike~~ / <u>under</u> / "- '<span style="text-emphasis: dot; text-emphasis-position: under;">dot</span> '- "<sub>q</sub><sup>2</sup> = $x$ $y$"- )- assert "mineru-algorithm" not in output["content"]- _assert_output_field_contract(output)---def test_structured_content_sorts_visual_annotations_and_selects_image_source() -> None:- """验证视觉说明稳定排序、空项保留及图片 path 优先规则。"""- image = ImageBlock.model_validate(- {- "type": "image",- "index": 0,- "sub_type": "diagram",- "content": [- {"type": "image_caption", "content": _inline("missing index")},- {- "type": "image_body",- "index": 0,- "content": "description",- "image_path": "images/a b.png",- "image_base64": "data:image/png;base64,AAAA",- },- {- "type": "image_caption",- "index": 5,- "bbox": [0.1, 0.5, 0.4, 0.6],- "content": [],- },- {- "type": "image_caption",- "index": 3,- "bbox": [0.1, 0.2, 0.4, 0.3],- "content": _inline("early", styles=["bold"]),- },- {- "type": "image_footnote",- "index": 4,- "bbox": [0.1, 0.7, 0.4, 0.8],- "content": _inline("after"),- },- ],- }- )-- result = render_structured_content(- _middle(_page(0, image)),- asset_base_url="https://cdn.example/doc",- )["pages"][0]["blocks"][0]-- assert result["content"] == "description"- assert result["image_source"] == "https://cdn.example/doc/images/a%20b.png"- assert result["captions"] == [- {"bbox": [0.1, 0.2, 0.4, 0.3], "content": "**early**"},- {"bbox": [0.1, 0.5, 0.4, 0.6], "content": ""},- {"content": "missing index"},- ]- assert result["footnotes"] == [{"bbox": [0.1, 0.7, 0.4, 0.8], "content": "after"}]- assert "- _assert_output_field_contract(result)---def test_structured_content_keeps_table_image_source_and_cross_page_metadata() -> None:- """验证表格 body 上浮后仍保留图片来源、续表字段且不执行跨页合并。"""- first = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",- image_path="images/table.png",- )- ],- )- second = TableBlock.model_validate(- {- "type": "table",- "index": 0,- "continues_prev": True,- "cell_merge": [1],- "content": [- {- "type": "table_body",- "index": 0,- "content": "<table><tr><th>A</th></tr><tr><td>2</td></tr></table>",- },- {- "type": "table_caption",- "index": 2,- "bbox": [0.1, 0.1, 0.9, 0.2],- "content": _inline("Table 2"),- },- {- "type": "table_footnote",- "index": 3,- "bbox": [0.1, 0.8, 0.9, 0.9],- "content": _inline("note"),- },- ],- }- )- image_only = TableBlock(- type="table",- index=0,- content=[- TableBodyBlock(- type="table_body",- index=0,- content="",- image_path="images/image-only-table.png",- )- ],- )-- result = render_structured_content(_middle(_page(0, first), _page(1, second), _page(2, image_only)))- first_output = result["pages"][0]["blocks"][0]- second_output = result["pages"][1]["blocks"][0]- image_only_output = result["pages"][2]["blocks"][0]-- assert first_output["content"] == "| A |\n| --- |\n| 1 |"- assert first_output["image_source"] == "images/table.png"- assert first_output["captions"] == []- assert first_output["footnotes"] == []- assert second_output["content"] == "| A |\n| --- |\n| 2 |"- assert second_output["continues_prev"] is True- assert second_output["cell_merge"] == [1]- assert second_output["captions"] == [{"bbox": [0.1, 0.1, 0.9, 0.2], "content": "Table 2"}]- assert second_output["footnotes"] == [{"bbox": [0.1, 0.8, 0.9, 0.9], "content": "note"}]- assert image_only_output["content"] == ""- assert image_only_output["image_source"] == "images/image-only-table.png"--def test_structured_content_keeps_chart_content_separate_from_base64_source(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -473,11 +232,3 @@ def test_structured_content_renders_equation_as_raw_latex_with_single_image_sourassert "data:image/png;base64,DDDD" not in serializedassert "\\[" not in serialized and "\\]" not in serialized_assert_output_field_contract(blocks)---def test_structured_content_rejects_legacy_dict_input() -> None:- """验证公共入口只接受严格 MiddleJson。"""- middle = _middle(_page(0))-- with pytest.raises(TypeError, match="MiddleJson"):- render_structured_content(middle.to_dict()) # type: ignore[arg-type]diff --git a/tests/unittest/test_table_merge.py b/tests/unittest/test_table_merge.pydeleted file mode 100644index 1158339b..00000000--- a/tests/unittest/test_table_merge.py+++ /dev/null@@ -1,392 +0,0 @@-from __future__ import annotations--from copy import deepcopy-from typing import Any--import pytest-from bs4 import BeautifulSoup--from mineru.backend.postprocess.table_merge import merge_table, merge_table_content-from mineru.types import BlockType---DEFAULT_HTML = "<table><tr><td>A</td><td>B</td></tr></table>"---def _table_body(- html: str = DEFAULT_HTML,- *,- index: int = 0,- bbox: list[float] | None = None,-) -> dict[str, Any]:- """构造归一化 bbox 的 table body 测试块。"""- body: dict[str, Any] = {- "type": BlockType.TABLE_BODY,- "index": index,- "bbox": deepcopy(bbox or [0.1, 0.1, 0.9, 0.9]),- "content": html,- }- return body---def _caption(- text: str,- *,- index: int = 0,- bbox: list[float] | None = None,-) -> dict[str, Any]:- """构造 table caption 测试块。"""- return {- "type": BlockType.TABLE_CAPTION,- "index": index,- "bbox": deepcopy(bbox or [0.1, 0.05, 0.9, 0.08]),- "content": text,- }---def _footnote(text: str, *, index: int = 1) -> dict[str, Any]:- """构造 table footnote 测试块。"""- return {- "type": BlockType.TABLE_FOOTNOTE,- "index": index,- "bbox": [0.1, 0.91, 0.9, 0.95],- "content": text,- }---def _table(- index: int,- html: str = DEFAULT_HTML,- *,- bbox: list[float] | None = None,- children: list[dict[str, Any]] | None = None,- cell_merge: list[int] | None = None,-) -> dict[str, Any]:- """构造两层 dict table 测试块。"""- table_bbox = deepcopy(bbox or [0.1, 0.1, 0.9, 0.9])- body = _table_body(- html,- index=index,- bbox=table_bbox,- )- table = {- "type": BlockType.TABLE,- "index": index,- "bbox": table_bbox,- "content": children if children is not None else [body],- }- if cell_merge is not None:- table["cell_merge"] = cell_merge- return table---def _page(page_idx: int, blocks: list[dict[str, Any]]) -> dict[str, Any]:- """构造 ModelJson 后处理阶段使用的 raw 页面。"""- return {"page_idx": page_idx, "blocks": blocks}---def _noise(block_type: str) -> dict[str, Any]:- """构造页边界可忽略的噪声块。"""- return {- "type": block_type,- "index": 99,- "bbox": [0.1, 0.01, 0.9, 0.03],- "content": "noise",- }---def _merged_soup(table: dict[str, Any]) -> BeautifulSoup:- """读取合并结果中的 table body HTML。"""- body = next(child for child in table["content"] if child["type"] == BlockType.TABLE_BODY)- return BeautifulSoup(body["content"], "html.parser")---def _row_texts(table: dict[str, Any]) -> list[list[str]]:- """提取合并 HTML 的逐行单元格文本。"""- return [[cell.get_text() for cell in row.find_all(["td", "th"])] for row in _merged_soup(table).find_all("tr")]---def test_merge_table_marks_reverse_multi_page_chain_and_cleans_stale_markers() -> None:- """验证多页链倒序识别,并清理根块及子块的过期标记。"""- tables = [_table(index) for index in range(3)]- tables[0]["continues_prev"] = True- tables[0]["content"][0]["continues_prev"] = True- pages = [_page(index, [table]) for index, table in enumerate(tables)]-- merge_table(pages)-- assert "continues_prev" not in tables[0]- assert "continues_prev" not in tables[0]["content"][0]- assert tables[1]["continues_prev"] is True- assert tables[2]["continues_prev"] is True-- merge_table(pages)- assert tables[1]["continues_prev"] is True- assert tables[2]["continues_prev"] is True--[email protected]("page_indices", [(0, 2), (2, 1)])-def test_merge_table_requires_consecutive_increasing_page_indices(- page_indices: tuple[int, int],-) -> None:- """验证跳页和逆序 page_idx 都不会建立跨页关系。"""- previous_table = _table(0)- current_table = _table(1)-- merge_table(- [- _page(page_indices[0], [previous_table]),- _page(page_indices[1], [current_table]),- ]- )-- assert "continues_prev" not in current_table--- "block_type",- [- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.ASIDE_TEXT,- ],-)-def test_merge_table_skips_boundary_noise(block_type: str) -> None:- """验证指定页眉页脚类块不会阻断边界 table 扫描。"""- previous_table = _table(0)- current_table = _table(1)- pages = [- _page(0, [previous_table, _noise(block_type)]),- _page(1, [_noise(block_type), current_table]),- ]-- merge_table(pages)-- assert current_table["continues_prev"] is True--[email protected]("barrier_side", ["previous", "current"])-def test_merge_table_is_blocked_by_boundary_semantic_block(barrier_side: str) -> None:- """验证普通正文位于页边界时会阻断 table 关系。"""- previous_table = _table(0)- current_table = _table(1)- text = _noise(BlockType.TEXT)- previous_blocks = [previous_table, text] if barrier_side == "previous" else [previous_table]- current_blocks = [text, current_table] if barrier_side == "current" else [current_table]-- merge_table([_page(0, previous_blocks), _page(1, current_blocks)])-- assert "continues_prev" not in current_table--- ("previous_footnotes", "current_caption", "expected"),- [- (0, None, True),- (0, "Table 1", False),- (0, "Table 1 (continued)", True),- (1, None, False),- (1, "Table 1 (continued)", True),- (2, "Table 1 (continued)", False),- ],-)-def test_merge_table_applies_caption_and_footnote_rules(- previous_footnotes: int,- current_caption: str | None,- expected: bool,-) -> None:- """验证续表 caption 与前表 footnote 的组合规则。"""- previous_children = [_table_body()]- previous_children.extend(_footnote(f"old-{index}", index=index + 1) for index in range(previous_footnotes))- current_children = [_table_body(index=1)]- if current_caption is not None:- current_children.insert(0, _caption(current_caption))- previous_table = _table(0, children=previous_children)- current_table = _table(1, children=current_children)-- merge_table([_page(0, [previous_table]), _page(1, [current_table])])-- assert current_table.get("continues_prev", False) is expected---def test_post_table_non_continuation_caption_does_not_block_merge() -> None:- """验证 table body 下方的非续表 caption 不参与阻断判断。"""- current_children = [- _table_body(index=1, bbox=[0.1, 0.1, 0.9, 0.7]),- _caption("Next section", index=2, bbox=[0.1, 0.75, 0.9, 0.8]),- ]- current_table = _table(1, children=current_children)-- merge_table([_page(0, [_table(0)]), _page(1, [current_table])])-- assert current_table["continues_prev"] is True---def test_merge_table_enforces_strict_ten_percent_width_threshold() -> None:- """验证宽度差恰好百分之十时拒绝,小于阈值时接受。"""- previous_table = _table(0, bbox=[0.1, 0.1, 0.9, 0.9])- exact_threshold = _table(1, bbox=[0.06, 0.1, 0.94, 0.9])- pages = [_page(0, [previous_table]), _page(1, [exact_threshold])]-- merge_table(pages)- assert "continues_prev" not in exact_threshold-- exact_threshold["bbox"] = [0.08, 0.1, 0.92, 0.9]- exact_threshold["content"][0]["bbox"] = [0.08, 0.1, 0.92, 0.9]- merge_table(pages)- assert exact_threshold["continues_prev"] is True---def test_merge_table_uses_boundary_row_metrics_when_total_columns_differ() -> None:- """验证总列数不同后按边界行 effective/actual/渲染段数回退判断。"""- matching_previous = _table(- 0,- "<table><tr><td colspan='3'>H</td></tr><tr><td>A</td><td>B</td></tr></table>",- )- matching_current = _table(1, "<table><tr><td>C</td><td>D</td></tr></table>")- merge_table([_page(0, [matching_previous]), _page(1, [matching_current])])- assert matching_current["continues_prev"] is True-- mismatching_previous = _table(- 0,- "<table><tr><td colspan='4'>H</td></tr><tr><td colspan='2'>A</td><td>B</td></tr></table>",- )- mismatching_current = _table(1, "<table><tr><td colspan='2'>C</td></tr></table>")- merge_table([_page(0, [mismatching_previous]), _page(1, [mismatching_current])])- assert "continues_prev" not in mismatching_current--- "current_table",- [- _table(1, bbox=[10.0, 10.0, 90.0, 90.0]),- {"type": BlockType.TABLE, "index": 1, "bbox": [0.1, 0.1, 0.9, 0.9], "content": []},- _table(1, "<table></table>"),- _table(1, "<table><tr><td colspan='bad'>X</td></tr></table>"),- ],-)-def test_merge_table_safely_skips_invalid_bbox_body_or_html(current_table: dict[str, Any]) -> None:- """验证非法 bbox、table body 和 HTML 均安全降级。"""- current_table = deepcopy(current_table)- merge_table([_page(0, [_table(0)]), _page(1, [current_table])])- assert "continues_prev" not in current_table---def test_merge_table_only_changes_markers_and_preserves_normalized_bboxes() -> None:- """验证千分位计算不会回写 bbox,检测也不修改任何表格内容。"""- previous_table = _table(0)- current_table = _table(1)- pages = [_page(0, [previous_table]), _page(1, [current_table])]- original_pages = deepcopy(pages)-- merge_table(pages)-- assert current_table.pop("continues_prev") is True- assert pages == original_pages---def test_merge_table_content_removes_repeated_rowspan_header_and_appends_data() -> None:- """验证重复表头按 rowspan 覆盖范围删除,并追加当前数据行。"""- previous_html = (- "<table><tr><th rowspan='2'>H1</th><th>H2</th></tr><tr><th>H3</th></tr><tr><td>A</td><td>B</td></tr></table>"- )- current_html = "<table><tr><th rowspan='2'>H1</th><th>H2</th></tr><tr><th>H3</th></tr><tr><td>C</td><td>D</td></tr></table>"-- merged = merge_table_content(_table(0, previous_html), _table(1, current_html))-- assert merged is not None- assert _row_texts(merged) == [["H1", "H2"], ["H3"], ["A", "B"], ["C", "D"]]---def test_merge_table_content_repairs_colspan_on_narrower_current_rows() -> None:- """验证较窄的当前页数据行会补齐末单元格 colspan。"""- previous = _table(0, "<table><tr><td>A</td><td colspan='2'>B</td></tr></table>")- current = _table(1, "<table><tr><td>C</td><td>D</td></tr></table>")-- merged = merge_table_content(previous, current)-- assert merged is not None- appended_cells = _merged_soup(merged).find_all("tr")[-1].find_all(["td", "th"])- assert [cell.get_text() for cell in appended_cells] == ["C", "D"]- assert appended_cells[-1]["colspan"] == "2"---def test_merge_table_content_clips_overlapped_blank_rowspan_placeholder() -> None:- """验证当前页重复空白 rowspan 占位会按上页剩余跨度裁剪。"""- previous = _table(0, "<table><tr><td rowspan='2'>A</td><td>X</td></tr></table>")- current = _table(- 1,- "<table><tr><td rowspan='2'></td><td>Y</td></tr><tr><td>Z</td></tr></table>",- )-- merged = merge_table_content(previous, current)-- assert merged is not None- assert _row_texts(merged) == [["A", "X"], ["Y"], ["", "Z"]]- moved_blank_cell = _merged_soup(merged).find_all("tr")[-1].find_all(["td", "th"])[0]- assert "rowspan" not in moved_blank_cell.attrs---def test_merge_table_content_replaces_footnote_and_preserves_previous_payloads() -> None:- """验证纯合并保留前表载荷、忽略当前 caption,并替换 footnote。"""- previous_body = _table_body(- "<table><tr><th>H</th></tr><tr><td>A</td></tr></table>",- index=5,- )- previous_body["image_base64"] = "previous-image"- previous = _table(- 5,- children=[_caption("Original caption", index=4), previous_body, _footnote("old", index=6)],- )- previous["image_base64"] = "outer-image"- current = _table(- 8,- children=[- _caption("Table 1 (continued)", index=7),- _table_body("<table><tr><th>H</th></tr><tr><td>B</td></tr></table>", index=8),- {**_footnote("new", index=9), "_cross_page": True},- ],- )- previous_original = deepcopy(previous)- current_original = deepcopy(current)-- merged = merge_table_content(previous, current)-- assert merged is not None- assert previous == previous_original- assert current == current_original- assert merged["index"] == previous["index"]- assert merged["bbox"] == previous["bbox"]- assert merged["image_base64"] == "outer-image"- merged_body = next(child for child in merged["content"] if child["type"] == BlockType.TABLE_BODY)- assert merged_body["image_base64"] == "previous-image"- assert _row_texts(merged) == [["H"], ["A"], ["B"]]- captions = [child["content"] for child in merged["content"] if child["type"] == BlockType.TABLE_CAPTION]- footnotes = [child for child in merged["content"] if child["type"] == BlockType.TABLE_FOOTNOTE]- assert captions == ["Original caption"]- assert [footnote["content"] for footnote in footnotes] == ["new"]- assert "_cross_page" not in footnotes[0]--- ("previous", "current"),- [- (_table(0, "<table></table>"), _table(1)),- (_table(0), _table(1, "<table><tr><td colspan='bad'>X</td></tr></table>")),- (_table(0), {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.9], "content": []}),- (_table(0), _table(1, bbox=[0.0, 0.0, 100.0, 100.0])),- ],-)-def test_merge_table_content_returns_none_for_invalid_input(- previous: dict[str, Any],- current: dict[str, Any],-) -> None:- """验证纯内容操作遇到非法 HTML、主体或 bbox 时返回空。"""- previous_original = deepcopy(previous)- current_original = deepcopy(current)-- assert merge_table_content(previous, current) is None- assert previous == previous_original- assert current == current_originaldiff --git a/tests/unittest/test_table_merge_cell_merge.py b/tests/unittest/test_table_merge_cell_merge.pydeleted file mode 100644index 13c8badd..00000000--- a/tests/unittest/test_table_merge_cell_merge.py+++ /dev/null@@ -1,93 +0,0 @@-from __future__ import annotations--from copy import deepcopy-from typing import Any--from bs4 import BeautifulSoup--from mineru.backend.postprocess.table_merge import merge_table_content-from mineru.types import BlockType---def _build_table_block(index: int, html: str, cell_merge: list[int] | None = None) -> dict[str, Any]:- """构造纯内容合并测试使用的两层 dict 表格块。"""- body: dict[str, Any] = {- "index": index,- "type": BlockType.TABLE_BODY,- "bbox": [0.1, 0.1, 0.9, 0.9],- "content": html,- }- table = {- "index": index,- "type": BlockType.TABLE,- "bbox": [0.1, 0.1, 0.9, 0.9],- "content": [body],- }- if cell_merge is not None:- table["cell_merge"] = cell_merge- return table---def _row_texts(table: dict[str, Any]) -> list[list[str]]:- """提取合并后 table body 的逐行单元格文本。"""- body = table["content"][0]- soup = BeautifulSoup(body["content"], "html.parser")- return [[cell.get_text() for cell in row.find_all(["td", "th"])] for row in soup.find_all("tr")]---def test_merge_table_content_applies_partial_cell_merge_from_table() -> None:- """验证部分视觉列续接后保留当前首行并清空已迁移单元格。"""- previous_table = _build_table_block(- 0,- "<table><tr><td>A</td><td>X</td></tr></table>",- )- current_table = _build_table_block(- 1,- "<table><tr><td>B</td><td>Y</td></tr></table>",- [1, 0],- )- previous_original = deepcopy(previous_table)- current_original = deepcopy(current_table)-- merged = merge_table_content(previous_table, current_table)-- assert merged is not None- assert _row_texts(merged) == [["AB", "X"], ["", "Y"]]- assert previous_table == previous_original- assert current_table == current_original---def test_merge_table_content_applies_full_cell_merge_and_removes_consumed_row() -> None:- """验证全部视觉列续接后删除已消费行,并继续追加后续数据行。"""- previous_table = _build_table_block(- 0,- "<table><tr><td>A</td><td>X</td></tr></table>",- )- current_table = _build_table_block(- 1,- "<table><tr><td>B</td><td>Y</td></tr><tr><td>C</td><td>Z</td></tr></table>",- [1, 1],- )-- merged = merge_table_content(previous_table, current_table)-- assert merged is not None- assert _row_texts(merged) == [["AB", "XY"], ["C", "Z"]]---def test_merge_table_content_supports_fully_consumed_only_current_row() -> None:- """验证当前表仅有一行且被 cell_merge 全部消费时仍返回合并结果。"""- previous_table = _build_table_block(- 0,- "<table><tr><td>A</td><td>X</td></tr></table>",- )- current_table = _build_table_block(- 1,- "<table><tr><td>B</td><td>Y</td></tr></table>",- [1, 1],- )-- merged = merge_table_content(previous_table, current_table)-- assert merged is not None- assert _row_texts(merged) == [["AB", "XY"]]diff --git a/tests/unittest/test_text_block_anchor.py b/tests/unittest/test_text_block_anchor.pyindex 6bc55e84..d81fe41d 100644--- a/tests/unittest/test_text_block_anchor.py+++ b/tests/unittest/test_text_block_anchor.py@@ -1,30 +1,14 @@from __future__ import annotations-from docvortex.schema import Producer-from mineru.integrations.docvortex import build_metadata--from datetime import datetime, timezone-from io import BytesIO-from zipfile import ZipFile-from bs4 import BeautifulSoup-from lxml import etree-from pydantic import ValidationError-from pypdf import PdfReader-import pytest+from docvortex.schema import Producer-from mineru.backend.analyze import doc_analyze+from mineru.integrations.docvortex import build_metadatafrom mineru.render import (render_content_list,render_content_list_v2,- render_docx,- render_epub,- render_html,- render_markdown,- render_pdf,render_structured_content,)-from docvortex.render._internal.common.planner import build_render_plan-from mineru.types import IndexBlock, MiddleJson, PageInfo, RefTextBlock, TextBlock+from mineru.types import IndexBlock, MiddleJson, PageInfo, TextBlockdef _inline(text: str) -> list[dict[str, str]]:@@ -58,126 +42,6 @@ def _middle_with_text_anchor() -> MiddleJson:)-def _zip_text(payload: bytes, name: str) -> str:- """读取 ZIP 容器中的 UTF-8 XML 文本。"""- with ZipFile(BytesIO(payload)) as archive:- return archive.read(name).decode("utf-8")---def test_text_anchor_is_strict_and_blocks_continuation_merge() -> None:- """验证 TextBlock 接受 anchor,而带目标的续段不会被规划器吸收。"""- anchored = TextBlock(type="text", anchor="target", content=_inline("continued"), continues_prev=True)- middle = MiddleJson(- pages=[- PageInfo(page_idx=0, blocks=[TextBlock(type="text", index=0, content=_inline("first"))]),- PageInfo(page_idx=1, blocks=[anchored.model_copy(update={"index": 0})]),- ],- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )-- planned = build_render_plan(middle)- assert planned[1][0].removed is False- assert TextBlock.model_validate(anchored.model_dump()).anchor == "target"- with pytest.raises(ValidationError):- RefTextBlock.model_validate({"type": "ref_text", "anchor": "target", "content": _inline("ref")})---def test_duplicate_and_empty_text_anchors_emit_only_the_first_visible_target() -> None:- """验证重复正文 anchor 仅首项生效,空正文不会产生悬空目标。"""- middle = MiddleJson(- pages=[- PageInfo(- page_idx=0,- blocks=[- TextBlock(type="text", index=0, anchor="same", content=_inline("First")),- TextBlock(type="text", index=1, anchor="same", content=_inline("Second")),- TextBlock(type="text", index=2, anchor="empty", content=[]),- ],- )- ],- is_full_document=True,- file_suffix="docx",- producer=Producer(name="mineru", version="test"),- extensions=build_metadata(effort="flash", parse_mode="txt", mineru_version="test"),- )-- assert render_markdown(middle).count('<a id="same"></a>') == 1- rendered_html = BeautifulSoup(render_html(middle), "html.parser")- assert len(rendered_html.select('[id="same"]')) == 1- assert rendered_html.select_one('[id="empty"]') is None---def test_text_anchor_markdown_html_and_html_wire_roundtrip() -> None:- """验证 Markdown、HTML 目标与 canonical HTML v1 往返保持 TextBlock anchor。"""- middle = _middle_with_text_anchor()-- markdown = render_markdown(middle)- assert "[Body target](#body%20target)" in markdown- assert '<a id="body target"></a>\nBody paragraph' in markdown-- rendered_html = render_html(middle)- soup = BeautifulSoup(rendered_html, "html.parser")- target_wrapper = soup.select_one('.docvortex-block[data-block-type="text"][data-anchor="body target"]')- assert target_wrapper is not None- assert target_wrapper.find("p")["id"] == "body-target"- assert soup.select_one('[data-block-type="index"] a')["href"] == "#body-target"-- decoded, _ = doc_analyze(rendered_html.encode("utf-8"), effort="flash", parse_mode="auto", file_suffix="html")- decoded_target = next(- block- for page in decoded.pages- for block in page.blocks- if isinstance(block, TextBlock) and block.anchor == "body target"- )- decoded_index = next(block for page in decoded.pages for block in page.blocks if isinstance(block, IndexBlock))- assert decoded_target.anchor == "body target"- assert isinstance(decoded_index.content[0], TextBlock)- assert decoded_index.content[0].anchor == "body target"-- missing = MiddleJson.model_validate(- {- **middle.model_dump(mode="python", exclude={"pages"}),- "pages": [- {- "page_idx": 0,- "blocks": [- {- "type": "index",- "index": 0,- "content": [{"type": "text", "anchor": "missing", "content": _inline("Missing\t1")}],- }- ],- }- ],- }- )- assert "#missing" not in render_markdown(missing)- assert BeautifulSoup(render_html(missing), "html.parser").select_one('[data-block-type="index"] a') is None---def test_text_anchor_docx_pdf_and_epub_targets() -> None:- """验证 DOCX bookmark、PDF 内链和 EPUB XHTML 目标均指向 TextBlock。"""- middle = _middle_with_text_anchor()-- document_xml = _zip_text(render_docx(middle), "word/document.xml")- assert 'w:bookmarkStart w:id="0" w:name="body_target"' in document_xml- assert 'w:hyperlink w:anchor="body_target"' in document_xml-- pdf_reader = PdfReader(BytesIO(render_pdf(middle)))- annotations = [annotation.get_object() for page in pdf_reader.pages for annotation in (page.get("/Annots") or [])]- assert any("/Dest" in annotation for annotation in annotations)-- epub = render_epub(middle, modified_at=datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc))- content = etree.fromstring(_zip_text(epub, "EPUB/text/content.xhtml").encode("utf-8"))- namespaces = {"xhtml": "http://www.w3.org/1999/xhtml"}- assert content.xpath("//xhtml:p[@id='body-target']/text()", namespaces=namespaces) == ["Body paragraph"]- navigation = etree.fromstring(_zip_text(epub, "EPUB/nav.xhtml").encode("utf-8"))- assert "text/content.xhtml#body-target" in navigation.xpath("//xhtml:a/@href", namespaces=namespaces)--def test_text_anchor_structured_and_content_list_metadata() -> None:"""验证结构化输出只保留 anchor 元数据,不向正文内容注入目标标签。"""middle = _middle_with_text_anchor()diff --git a/tests/unittest/test_text_utils.py b/tests/unittest/test_text_utils.pydeleted file mode 100644index a2ded572..00000000--- a/tests/unittest/test_text_utils.py+++ /dev/null@@ -1,139 +0,0 @@-import pytest--from docvortex.foundation.text import merge_text_line_contents-from docvortex.foundation.text import resolve_text_line_boundary--- ("previous_content", "next_content", "block_language", "expected"),- [- pytest.param(- "See https://example.test/current-research",- "/image-processing/",- "en",- "See https://example.test/current-research/image-processing/",- id="url-path-continuation",- ),- pytest.param(- "Download from ftp://example.test/archive",- "?format=zip",- "en",- "Download from ftp://example.test/archive?format=zip",- id="url-query-continuation",- ),- pytest.param(- "Visit www.example.test/docs",- "#install",- "en",- "Visit www.example.test/docs#install",- id="url-fragment-continuation",- ),- pytest.param(- "Use https://example.test/search?key=one",- "&page=2",- "en",- "Use https://example.test/search?key=one&page=2",- id="url-query-parameter-continuation",- ),- pytest.param(- "Use https://example.test/search?key",- "=value",- "en",- "Use https://example.test/search?key=value",- id="url-query-value-continuation",- ),- pytest.param("input", "/ output", "en", "input / output", id="ordinary-slash-text"),- pytest.param(- "https://blog.example.test/first",- "https://blog.example.test/second",- "en",- "https://blog.example.test/first https://blog.example.test/second",- id="independent-urls",- ),- pytest.param(- "DOI https",- "://doi.org/10.37921/example",- "en",- "DOI https://doi.org/10.37921/example",- id="url-scheme-continuation",- ),- pytest.param(- "See https://doi.o",- "rg/10.3322/example",- "en",- "See https://doi.org/10.3322/example",- id="url-host-continuation",- ),- pytest.param(- "See https://doi.org/10.101",- "6/example",- "en",- "See https://doi.org/10.1016/example",- id="url-numeric-path-continuation",- ),- pytest.param(- "See https://doi.org/10.1038/example-019",- "-0178-8",- "en",- "See https://doi.org/10.1038/example-019-0178-8",- id="url-hyphen-continuation",- ),- pytest.param(- "Download from https://download.docker.com/linux/",- "ubuntu/dists/",- "en",- "Download from https://download.docker.com/linux/ubuntu/dists/",- id="url-alpha-path-continuation",- ),- pytest.param("inter-", "national", "en", "international", id="western-hyphen"),- pytest.param("first line", "second line", "en", "first line second line", id="western-space"),- pytest.param("中文", "继续", "zh", "中文继续", id="cjk-direct-join"),- ],-)-def test_resolve_text_line_boundary_keeps_conservative_joining_rules(- previous_content: str,- next_content: str,- block_language: str,- expected: str,-) -> None:- """验证 URL、普通西文、断词和 CJK 的物理行边界规则互不干扰。"""- processed_previous, separator = resolve_text_line_boundary(- previous_content,- block_language=block_language,- next_content=next_content,- )-- assert f"{processed_previous}{separator}{next_content}" == expected---def test_merge_text_line_contents_keeps_accumulated_url_context() -> None:- """验证三行 URL 使用完整累计前缀,而普通标题和独立 URL 保留自然空格。"""-- assert merge_text_line_contents(- [- "Code at https://github.",- "com/google-research/tapas/blob/master/",- "TABLEFORMER.md",- ],- block_language="en",- ) == ("Code at https://github.com/google-research/tapas/blob/master/TABLEFORMER.md")- assert (- merge_text_line_contents(- [- "ETC: Encoding long and structured inputs",- "in transformers",- ],- block_language="en",- )- == "ETC: Encoding long and structured inputs in transformers"- )- assert (- merge_text_line_contents(- [- "https://example.test/first",- "https://example.test/second",- ],- block_language="en",- )- == "https://example.test/first https://example.test/second"- )