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
feat: implement semantic fingerprinting and geometry summary for Flash PDF review
myhlolid9b0c46e4cbf
diff --git a/scripts/render_flash_script_review.py b/scripts/render_flash_script_review.pydeleted file mode 100644index 54d612ec..00000000--- a/scripts/render_flash_script_review.py+++ /dev/null@@ -1,555 +0,0 @@-from __future__ import annotations--import hashlib-import json-import math-import os-import re-import shutil-import tempfile-import unicodedata-from collections import Counter, defaultdict, deque-from pathlib import Path-from typing import Any--from bs4 import BeautifulSoup-from PIL import Image, ImageDraw, ImageFont--from mineru.model.flash.pdf.document import PDFDocument-from mineru.model.flash.pdf.pipeline import _analyze_native_document-from mineru.model.flash.pdf.text_styles import PDFTextScriptLine---PROJECT_ROOT = Path(__file__).resolve().parents[1]-OUTPUT_DIR = PROJECT_ROOT / "output/pdf/flash_script_review"-PDF_PATHS = sorted((PROJECT_ROOT / "demo/pdfs").glob("*.pdf")) + [- Path("/Users/myhloli/pdf/NPU_开发环境部署_参考指南.pdf"),-]-RENDER_DPI = 200-CONTEXT_CHARS = 40-CONTACT_COLUMNS = 3-CONTACT_ROWS = 5---def _sha256(path: Path) -> str:- """计算源 PDF 摘要,供候选 ID 和审阅追踪使用。"""- digest = hashlib.sha256()- with path.open("rb") as input_file:- for chunk in iter(lambda: input_file.read(1024 * 1024), b""):- digest.update(chunk)- return digest.hexdigest()---def _normalized_text(value: str) -> str:- """生成适合 sidecar 与最终 TextSpan 对齐的稳定文本键。"""- normalized = unicodedata.normalize("NFKC", value)- normalized = "".join(char for char in normalized if char.isprintable())- return re.sub(r"\s+", "", normalized)---def _safe_stem(path: Path) -> str:- """生成适合作为产物目录的稳定文件名。"""- value = re.sub(r"[^\w.-]+", "_", path.stem, flags=re.UNICODE).strip("_.")- return value[:64] or "document"---def _load_font(size: int) -> ImageFont.ImageFont:- """优先加载支持中英文标签的系统字体。"""- for font_path in (- Path("/System/Library/Fonts/STHeiti Medium.ttc"),- Path("/System/Library/Fonts/Supplemental/Arial.ttf"),- ):- if font_path.exists():- return ImageFont.truetype(str(font_path), size=size)- return ImageFont.load_default(size=size)---def _page_bbox_from_normalized(- bbox: Any,- page_size: tuple[float, float],-) -> tuple[float, float, float, float] | None:- """把最终 Flash block bbox 转回页面 point。"""- if not isinstance(bbox, list) or len(bbox) != 4:- return None- try:- values = tuple(float(value) for value in bbox)- except (TypeError, ValueError):- return None- if values[2] <= values[0] or values[3] <= values[1]:- return None- return (- values[0] * page_size[0],- values[1] * page_size[1],- values[2] * page_size[0],- values[3] * page_size[1],- )---def _script_candidates(- diagnostic: dict[str, Any],-) -> tuple[dict[tuple[int | None, str, str], deque[dict[str, Any]]], list[dict[str, Any]]]:- """把检测及最终投影 sidecar 转成按 block、角色和文本消费的候选队列。"""- detected = []- detected_by_key: dict[tuple[int, int, int, str, str], deque[dict[str, Any]]] = defaultdict(deque)- lines = sorted(- diagnostic["lines"],- key=lambda item: (item["source_index"], item["bbox"][1], item["bbox"][0]),- )- line_position = {item["source_index"]: index for index, item in enumerate(lines)}- for script_line in diagnostic["script_lines"]:- if not isinstance(script_line, PDFTextScriptLine):- continue- position = line_position.get(script_line.source_index)- current = lines[position]["text"] if position is not None else script_line.text- previous = lines[position - 1]["text"] if position is not None and position > 0 else ""- following = lines[position + 1]["text"] if position is not None and position + 1 < len(lines) else ""- for script_range in script_line.script_ranges:- text = script_line.text[script_range.start : script_range.end]- candidate = {- "source_index": script_line.source_index,- "range_start": script_range.start,- "range_end": script_range.end,- "role": script_range.style,- "text": text,- "bbox": list(script_range.bbox),- "angle": script_line.angle,- "formula_region": script_range.formula_region,- "stable_body_count": script_range.stable_body_count,- "previous_line": previous,- "current_line": current,- "next_line": following,- }- detected.append(candidate)- detected_by_key[- (- script_line.source_index,- script_range.start,- script_range.end,- script_range.style,- text,- )- ].append(candidate)-- queues: dict[tuple[int | None, str, str], deque[dict[str, Any]]] = defaultdict(deque)- materialized = diagnostic.get("materialized_ranges")- if isinstance(materialized, list):- candidates = []- for mapped in sorted(- materialized,- key=lambda item: (- int(item.get("block_index", -1)),- int(item.get("raw_start", -1)),- int(item.get("source_index", -1)),- int(item.get("range_start", -1)),- ),- ):- identity = (- int(mapped["source_index"]),- int(mapped["range_start"]),- int(mapped["range_end"]),- str(mapped["role"]),- str(mapped["text"]),- )- candidate = dict(detected_by_key[identity].popleft()) if detected_by_key[identity] else dict(mapped)- candidate.update(mapped)- candidate["bbox"] = list(candidate["bbox"])- candidates.append(candidate)- queues[- (- int(mapped["block_index"]),- str(mapped["role"]),- _normalized_text(str(mapped["text"])),- )- ].append(candidate)- return queues, candidates-- for candidate in detected:- queues[(None, str(candidate["role"]), _normalized_text(str(candidate["text"])))].append(candidate)- return queues, detected---def _final_script_runs(- blocks: list[dict[str, Any]],- page_size: tuple[float, float],-) -> list[dict[str, Any]]:- """收集最终真正物化的 Flash 上下标 TextSpan。"""- runs = []- for block_index, block in enumerate(blocks):- block_type = str(block.get("type") or "")- block_bbox = _page_bbox_from_normalized(block.get("bbox"), page_size)- block_content = block.get("content")- if block_type == "table" and isinstance(block_content, str) and block_content.lstrip().lower().startswith("<table"):- soup = BeautifulSoup(block_content, "html.parser")- for row_index, row in enumerate(soup.find_all("tr")):- for cell_index, cell in enumerate(row.find_all(["td", "th"], recursive=False)):- for tag in cell.find_all(["sup", "sub"]):- text = tag.get_text()- if not _normalized_text(text):- continue- runs.append(- {- "block_index": block_index,- "block_type": block_type,- "block_bbox": list(block_bbox) if block_bbox is not None else None,- "role": "superscript" if tag.name == "sup" else "subscript",- "text": text,- "cell_row": row_index,- "cell_col": cell_index,- "cell_text": cell.get_text(),- }- )-- def walk(value: Any) -> None:- """递归遍历 block 的 InlineSpan。"""- if isinstance(value, dict):- content = value.get("content")- styles = value.get("styles")- if value.get("type") == "text" and isinstance(content, str) and isinstance(styles, list):- for role in ("superscript", "subscript"):- if role in styles and _normalized_text(content):- runs.append(- {- "block_index": block_index,- "block_type": block_type,- "block_bbox": list(block_bbox) if block_bbox is not None else None,- "role": role,- "text": content,- }- )- if isinstance(content, (dict, list)):- walk(content)- elif isinstance(value, list):- for child in value:- walk(child)-- walk(block_content)- return runs---def _candidate_id(- source_sha256: str,- page_number: int,- candidate: dict[str, Any],-) -> str:- """用源文件、页、来源区间和角色构造稳定候选 ID。"""- payload = "|".join(- (- source_sha256,- str(page_number),- str(candidate.get("source_index", -1)),- str(candidate.get("range_start", -1)),- str(candidate.get("range_end", -1)),- str(candidate["role"]),- str(candidate["text"]),- )- )- return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]---def _clip_context(value: str, styled_text: str) -> str:- """围绕样式文本保留约 40 字符上下文。"""- compact = re.sub(r"\s+", " ", value).strip()- position = compact.find(styled_text)- if position < 0:- return compact[: 2 * CONTEXT_CHARS + len(styled_text)]- start = max(0, position - CONTEXT_CHARS)- end = min(len(compact), position + len(styled_text) + CONTEXT_CHARS)- return compact[start:end]---def _render_crop(- page_image: Image.Image,- scale: float,- bbox: tuple[float, float, float, float],- record: dict[str, Any],- output_path: Path,-) -> None:- """裁剪上下标周围源页,并用角色颜色标出 tight bbox。"""- x0, y0, x1, y1 = bbox- line_height = max(1.0, y1 - y0)- padding_x = max(96.0, 10.0 * line_height)- padding_y = max(18.0, 1.75 * line_height)- crop_box = (- max(0, round((x0 - padding_x) * scale)),- max(0, round((y0 - padding_y) * scale)),- min(page_image.width, round((x1 + padding_x) * scale)),- min(page_image.height, round((y1 + padding_y) * scale)),- )- crop = page_image.crop(crop_box).convert("RGB")- label_height = 42- canvas = Image.new("RGB", (crop.width, crop.height + label_height), "white")- canvas.paste(crop, (0, label_height))- draw = ImageDraw.Draw(canvas)- color = (220, 40, 40) if record["role"] == "superscript" else (30, 90, 220)- draw.rectangle(- (- round(x0 * scale) - crop_box[0],- round(y0 * scale) - crop_box[1] + label_height,- round(x1 * scale) - crop_box[0],- round(y1 * scale) - crop_box[1] + label_height,- ),- outline=color,- width=4,- )- label = f"{record['id']} p{record['page']} {record['role']} {record['text']}"- draw.text((8, 8), label, fill=color, font=_load_font(20))- output_path.parent.mkdir(parents=True, exist_ok=True)- canvas.save(output_path)---def _build_contact_sheets(- records: list[dict[str, Any]],- staging: Path,- *,- directory: str = "contact_sheets",-) -> list[str]:- """按文档把候选 crop 组合成多张联系表。"""- contact_paths = []- page_size = (520, 250)- per_sheet = CONTACT_COLUMNS * CONTACT_ROWS- grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)- for record in records:- grouped[record["file"]].append(record)- for document_name, document_records in sorted(grouped.items()):- for sheet_index in range(math.ceil(len(document_records) / per_sheet)):- subset = document_records[sheet_index * per_sheet : (sheet_index + 1) * per_sheet]- canvas = Image.new(- "RGB",- (CONTACT_COLUMNS * page_size[0], CONTACT_ROWS * page_size[1]),- "white",- )- for index, record in enumerate(subset):- with Image.open(staging / record["crop"]) as source_crop:- crop = source_crop.convert("RGB")- crop.thumbnail((page_size[0] - 12, page_size[1] - 12))- x = (index % CONTACT_COLUMNS) * page_size[0] + 6- y = (index // CONTACT_COLUMNS) * page_size[1] + 6- canvas.paste(crop, (x, y))- relative = Path(directory) / (f"{_safe_stem(Path(document_name))}_{sheet_index + 1:02d}.png")- output = staging / relative- output.parent.mkdir(parents=True, exist_ok=True)- canvas.save(output)- contact_paths.append(relative.as_posix())- return contact_paths---def _write_review_markdown(records: list[dict[str, Any]], staging: Path) -> Path:- """生成按文件和页码分组、带勾选框和 crop 的人工审阅 Markdown。"""- lines = [- "# Flash 上下标人工审阅",- "",- f"候选总数:{len(records)}",- "",- "- 红框:superscript",- "- 蓝框:subscript",- "",- ]- grouped: dict[tuple[str, int], list[dict[str, Any]]] = defaultdict(list)- for record in records:- grouped[(record["file"], record["page"])].append(record)- for (file_name, page_number), page_records in sorted(grouped.items()):- lines.extend([f"## {file_name} - p{page_number}", ""])- for record in page_records:- context = _clip_context(record["current_line"], record["text"])- lines.extend(- [- f"- [ ] `{record['id']}` **{record['role']}** `{record['text']}`",- f" - block: `{record['block_type']}`; angle: `{record['angle']}`; "- f"cell: `{record.get('cell_row')},{record.get('cell_col')}`; "- f"formula_region: `{record['formula_region']}`; stable_body_count: `{record['stable_body_count']}`",- f" - previous: {record['previous_line']}",- f" - context: {context}",- f" - next: {record['next_line']}",- f" - ![{record['id']}]({record['crop']})",- "",- ]- )- output = staging / "review.md"- output.write_text("\n".join(lines), encoding="utf-8")- return output---def _promote(staging: Path) -> None:- """把已验证 staging 目录原子提升为最终审阅目录。"""- OUTPUT_DIR.parent.mkdir(parents=True, exist_ok=True)- backup = OUTPUT_DIR.with_name(f"{OUTPUT_DIR.name}.previous")- if backup.exists():- shutil.rmtree(backup)- if OUTPUT_DIR.exists():- OUTPUT_DIR.rename(backup)- try:- os.replace(staging, OUTPUT_DIR)- except Exception:- if backup.exists() and not OUTPUT_DIR.exists():- backup.rename(OUTPUT_DIR)- raise- if backup.exists():- shutil.rmtree(backup)---def main() -> None:- """扫描全部 Flash PDF,生成可追踪的上下标人工审阅产物。"""- OUTPUT_DIR.parent.mkdir(parents=True, exist_ok=True)- staging = Path(- tempfile.mkdtemp(- prefix="flash_script_review_",- dir=OUTPUT_DIR.parent,- )- )- records = []- documents = []- try:- for document_index, pdf_path in enumerate(PDF_PATHS, start=1):- source_sha256 = _sha256(pdf_path)- diagnostics: list[dict[str, Any]] = []- print(f"解析 {document_index}/{len(PDF_PATHS)} {pdf_path.name}", flush=True)- with PDFDocument(str(pdf_path)) as document:- pages = _analyze_native_document(- document,- script_diagnostics=diagnostics,- )- page_images: dict[int, tuple[Image.Image, float]] = {}- document_count = 0- for page_index, blocks in enumerate(pages):- diagnostic = diagnostics[page_index]- queues, _candidates = _script_candidates(diagnostic)- final_runs = _final_script_runs(blocks, diagnostic["page_size"])- for final_index, final_run in enumerate(final_runs):- key = (- final_run["block_index"],- final_run["role"],- _normalized_text(final_run["text"]),- )- fallback_key = (- None,- final_run["role"],- _normalized_text(final_run["text"]),- )- candidate = (- queues[key].popleft()- if queues[key]- else queues[fallback_key].popleft()- if queues[fallback_key]- else {- "source_index": -1,- "range_start": final_index,- "range_end": final_index + 1,- "role": final_run["role"],- "text": final_run["text"],- "bbox": final_run["block_bbox"],- "angle": 0,- "formula_region": False,- "stable_body_count": 0,- "previous_line": "",- "current_line": final_run.get("cell_text", final_run["text"]),- "next_line": "",- }- )- bbox = candidate.get("bbox") or final_run["block_bbox"]- if not isinstance(bbox, list) or len(bbox) != 4:- raise AssertionError((pdf_path, page_index, final_run))- record_id = _candidate_id(- source_sha256,- page_index + 1,- candidate,- )- relative_crop = Path("crops") / _safe_stem(pdf_path) / f"{record_id}.png"- record = {- "id": record_id,- "file": pdf_path.name,- "source_path": str(pdf_path),- "source_sha256": source_sha256,- "page": page_index + 1,- "block_type": final_run["block_type"],- "role": final_run["role"],- "text": final_run["text"],- "bbox": [float(value) for value in bbox],- "angle": int(candidate.get("angle", 0)),- "source_index": int(candidate.get("source_index", -1)),- "range_start": int(candidate.get("range_start", -1)),- "range_end": int(candidate.get("range_end", -1)),- "formula_region": bool(candidate.get("formula_region", False)),- "stable_body_count": int(candidate.get("stable_body_count", 0)),- "previous_line": str(candidate.get("previous_line", "")),- "current_line": str(candidate.get("current_line", final_run["text"])),- "next_line": str(candidate.get("next_line", "")),- "cell_row": final_run.get("cell_row"),- "cell_col": final_run.get("cell_col"),- "cell_text": final_run.get("cell_text"),- "crop": relative_crop.as_posix(),- }- if page_index not in page_images:- rendered = document.render_page(- page_index,- scale=RENDER_DPI / 72,- )- page_images[page_index] = (- rendered.pil_image,- rendered.scale,- )- image, scale = page_images[page_index]- _render_crop(- image,- scale,- tuple(record["bbox"]),- record,- staging / relative_crop,- )- records.append(record)- document_count += 1- documents.append(- {- "file": pdf_path.name,- "source_path": str(pdf_path),- "source_sha256": source_sha256,- "page_count": document.page_count,- "candidate_count": document_count,- }- )- contact_sheets = _build_contact_sheets(records, staging)- table_contact_sheets = _build_contact_sheets(- [record for record in records if record["block_type"] == "table"],- staging,- directory="table_contact_sheets",- )- review_path = _write_review_markdown(records, staging)- manifest = {- "source_count": len(PDF_PATHS),- "page_count": sum(document["page_count"] for document in documents),- "candidate_count": len(records),- "role_counts": dict(Counter(record["role"] for record in records)),- "formula_region_count": sum(record["formula_region"] for record in records),- "documents": documents,- "contact_sheets": contact_sheets,- "table_contact_sheets": table_contact_sheets,- "records": records,- }- manifest_path = staging / "manifest.json"- manifest_path.write_text(- json.dumps(manifest, ensure_ascii=False, indent=2),- encoding="utf-8",- )- crop_count = len(list((staging / "crops").rglob("*.png")))- checkbox_count = review_path.read_text(encoding="utf-8").count("- [ ]")- if not (- len(records) == crop_count == checkbox_count- and sum(document["candidate_count"] for document in documents) == len(records)- ):- raise AssertionError(- {- "records": len(records),- "crops": crop_count,- "checkboxes": checkbox_count,- }- )- _promote(staging)- print(OUTPUT_DIR / "manifest.json")- print(OUTPUT_DIR / "review.md")- except Exception:- if staging.exists():- shutil.rmtree(staging)- raise---if __name__ == "__main__":- main()diff --git a/scripts/review_flash_layout_geometry.py b/scripts/review_flash_layout_geometry.pydeleted file mode 100644index f23a7d28..00000000--- a/scripts/review_flash_layout_geometry.py+++ /dev/null@@ -1,519 +0,0 @@-"""生成 Flash 双几何全量回测、金标比对和逐页人工审阅产物。"""--from __future__ import annotations--import argparse-import hashlib-import json-import os-import sys-import time-from pathlib import Path-from typing import Any--import pypdfium2 as pdfium-from PIL import Image, ImageDraw, ImageFont---SOURCE_ROOT = Path(__file__).resolve().parents[1]-DEFAULT_OUTPUT = SOURCE_ROOT / "output" / "pdf" / "flash_layout_geometry_review"-TRACKED_GOLD_MANIFEST = SOURCE_ROOT / "tests" / "fixtures" / "flash_layout_geometry_manifest.json"-_PDF_FIXTURE_XOR_KEY = b"MinerU flash layout fixture"-_IGNORED_FINGERPRINT_KEYS = {- "bbox",- "lines",- "image_path",- "image_url",- "img_path",- "_layout_tree",-}-_TYPE_COLORS = {- "doc_title": (214, 39, 40),- "paragraph_title": (255, 127, 14),- "text": (31, 119, 180),- "header": (148, 103, 189),- "footer": (140, 86, 75),- "page_number": (227, 119, 194),- "caption": (44, 160, 44),- "footnote": (188, 189, 34),- "page_footnote": (23, 190, 207),- "table": (17, 127, 122),- "image": (127, 127, 127),- "equation": (188, 80, 144),- "code": (57, 59, 121),-}---def _sha256_bytes(value: bytes) -> str:- """返回字节内容的稳定 SHA256。"""-- return hashlib.sha256(value).hexdigest()---def read_pdf_fixture(path: Path) -> bytes:- """读取普通 PDF,或在内存中解密以 .xor 结尾的测试样本。"""-- payload = path.read_bytes()- if path.suffix != ".xor":- return payload- key_length = len(_PDF_FIXTURE_XOR_KEY)- return bytes(value ^ _PDF_FIXTURE_XOR_KEY[index % key_length] for index, value in enumerate(payload))---def _corpus_paths(manifest: dict[str, Any], source_root: Path) -> list[Path]:- """按版本化 manifest 返回仓库相对路径语料。"""-- paths = []- for document in manifest.get("documents", []):- path = Path(str(document["path"]))- if path.is_absolute() or ".." in path.parts:- raise ValueError(f"manifest path must be repository-relative: {path}")- resolved = source_root / path- if not resolved.exists():- raise FileNotFoundError(resolved)- expected_sha = str(document.get("sha256") or "")- if expected_sha and _sha256_bytes(resolved.read_bytes()) != expected_sha:- raise ValueError(f"manifest sha256 mismatch: {path}")- paths.append(resolved)- return paths---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 _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 _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 _block_id(pdf_sha: str, page_index: int, block_index: int, block: dict[str, Any]) -> str:- """生成与输出 bbox 无关的稳定人工金标 block ID。"""-- text_hash = _sha256_bytes(_visible_text(block.get("content")).encode("utf-8", errors="replace"))- raw = f"{pdf_sha}:{page_index}:{block_index}:{block.get('type')}:{text_hash}"- return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:20]---def _load_font(size: int) -> ImageFont.ImageFont:- """加载可显示中英文 block 标签的系统字体。"""-- for path in (- Path("/System/Library/Fonts/STHeiti Medium.ttc"),- Path("/System/Library/Fonts/Supplemental/Arial.ttf"),- ):- if path.exists():- return ImageFont.truetype(str(path), size=size)- return ImageFont.load_default(size=size)---def _render_overlays(- pdf_bytes: bytes,- pages: list[list[dict[str, Any]]],- geometry: dict[str, Any],- output_dir: Path,-) -> list[Path]:- """渲染 block 与 loose/tight/origin/canonical 四层逐页 overlay。"""-- output_dir.mkdir(parents=True, exist_ok=True)- font = _load_font(13)- rendered: list[Path] = []- document = pdfium.PdfDocument(pdf_bytes)- try:- for page_index, blocks in enumerate(pages):- page = document[page_index]- image = page.render(scale=1.25).to_pil().convert("RGB")- draw = ImageDraw.Draw(image)- page_width, page_height = [float(value) for value in page.get_size()]-- def absolute_rectangle(bbox: list[float] | tuple[float, ...]) -> tuple[int, int, int, int]:- """把页面 point bbox 映射为当前渲染像素框。"""-- x0, y0, x1, y1 = [float(item) for item in bbox]- return (- int(x0 / page_width * image.width),- int(y0 / page_height * image.height),- int(x1 / page_width * image.width),- int(y1 / page_height * image.height),- )-- for char in geometry.get("char_repairs", []):- if int(char["page_index"]) != page_index:- continue- draw.rectangle(absolute_rectangle(char["source_bbox"]), outline=(220, 40, 40), width=1)- draw.rectangle(absolute_rectangle(char["tight_bbox"]), outline=(40, 90, 220), width=1)- draw.rectangle(absolute_rectangle(char["layout_bbox"]), outline=(30, 170, 70), width=1)- ox = int(float(char["origin"][0]) / page_width * image.width)- oy = int(float(char["origin"][1]) / page_height * image.height)- draw.ellipse((ox - 2, oy - 2, ox + 2, oy + 2), fill=(255, 180, 0))- for line in geometry.get("line_repairs", []):- if int(line["page_index"]) != page_index:- continue- draw.rectangle(absolute_rectangle(line["source_bbox"]), outline=(220, 40, 40), width=1)- draw.rectangle(absolute_rectangle(line["layout_bbox"]), outline=(20, 180, 60), width=3)- for block_index, block in enumerate(blocks):- bbox = block.get("bbox")- if not isinstance(bbox, list) or len(bbox) != 4:- continue- block_type = str(block.get("type") or "unknown")- color = _TYPE_COLORS.get(block_type, (0, 0, 0))- x0, y0, x1, y1 = [float(item) for item in bbox]- rectangle = (- int(x0 * image.width),- int(y0 * image.height),- int(x1 * image.width),- int(y1 * image.height),- )- draw.rectangle(rectangle, outline=color, width=2)- draw.text((rectangle[0] + 2, max(0, rectangle[1] - 15)), f"{block_index}:{block_type}", fill=color, font=font)- output_path = output_dir / f"page_{page_index + 1:03d}.png"- image.save(output_path)- rendered.append(output_path)- page.close()- finally:- document.close()- return rendered---def _write_annotated_pdf(images: list[Path], output_path: Path) -> None:- """把逐页几何 overlay 保存成稳定的多页审阅 PDF。"""-- members = [Image.open(path).convert("RGB") for path in images]- if not members:- return- try:- # 页面以 1.25x 渲染;90 DPI 可还原原始 72pt 页面尺寸。- members[0].save(output_path, "PDF", save_all=True, append_images=members[1:], resolution=90.0)- finally:- for member in members:- member.close()---def _build_contact_sheets(images: list[Path], output_dir: Path) -> list[Path]:- """把逐页 overlay 按八页一张组合成可快速巡检的联系表。"""-- output_dir.mkdir(parents=True, exist_ok=True)- output: list[Path] = []- for sheet_index, start in enumerate(range(0, len(images), 8), start=1):- members = [Image.open(path).convert("RGB") for path in images[start : start + 8]]- try:- thumb_width = 420- thumbnails = []- for member in members:- height = max(1, round(member.height * thumb_width / member.width))- thumbnails.append(member.resize((thumb_width, height)))- row_heights = [max(image.height for image in thumbnails[row : row + 2]) for row in range(0, len(thumbnails), 2)]- canvas = Image.new("RGB", (thumb_width * 2, sum(row_heights)), "white")- y = 0- for row_index, row_start in enumerate(range(0, len(thumbnails), 2)):- for column, image in enumerate(thumbnails[row_start : row_start + 2]):- canvas.paste(image, (column * thumb_width, y))- y += row_heights[row_index]- path = output_dir / f"pages_{start + 1:03d}_{min(len(images), start + 8):03d}.png"- canvas.save(path)- output.append(path)- finally:- for member in members:- member.close()- return output---def _run_document(- path: Path,- *,- render: bool,- output_dir: Path,-) -> dict[str, Any]:- """解析一份语料并返回耗时、overlay 和金标页面信息。"""-- from mineru.model.flash.pdf.document import PDFDocument- from mineru.model.flash.pdf.pipeline import _analyze_native_document-- stored_bytes = path.read_bytes()- pdf_bytes = read_pdf_fixture(path)- pdf_sha = _sha256_bytes(stored_bytes)- geometry_diagnostics: list[dict[str, Any]] = []- started = time.perf_counter()- with PDFDocument(pdf_bytes) as document:- mode = document.classify()- pages = _analyze_native_document(document, geometry_diagnostics=geometry_diagnostics)- elapsed = time.perf_counter() - started- geometry = geometry_diagnostics[0] if geometry_diagnostics else {}- fingerprints = [_page_fingerprint(page) for page in pages]- bbox_fingerprints = [_page_bbox_fingerprint(page) for page in pages]-- output_dir.mkdir(parents=True, exist_ok=True)- (output_dir / "geometry.json").write_text(- json.dumps(geometry, ensure_ascii=False, indent=2),- encoding="utf-8",- )- (output_dir / "model_list.json").write_text(- json.dumps(pages, ensure_ascii=False, indent=2),- encoding="utf-8",- )- if render:- page_images = _render_overlays(pdf_bytes, pages, geometry, output_dir / "pages")- _build_contact_sheets(page_images, output_dir / "contact_sheets")- _write_annotated_pdf(page_images, output_dir / "annotated.pdf")- block_images = _render_overlays(pdf_bytes, pages, {}, output_dir / "block_pages")- _build_contact_sheets(block_images, output_dir / "block_contact_sheets")- _write_annotated_pdf(block_images, output_dir / "block_layout.pdf")-- return {- "file": path.name,- "path": str(path),- "sha256": pdf_sha,- "pages": len(pages),- "parse_mode": mode,- "page_fingerprints": fingerprints,- "bbox_fingerprints": bbox_fingerprints,- "elapsed_seconds": elapsed,- "geometry_summary": {- "repaired_chars": len(geometry.get("char_repairs", [])),- "repaired_lines": sum(line.get("state") != "healthy" for line in geometry.get("line_repairs", [])),- "split_y_candidates": sum(bool(line.get("split_y_candidate")) for line in geometry.get("line_repairs", [])),- "strong_x_runs": sum(bool(run.get("strong_x_bad")) for run in geometry.get("run_diagnostics", [])),- "sibling_x_runs": sum(bool(run.get("sibling_x_bad")) for run in geometry.get("run_diagnostics", [])),- },- "gold_pages": [- {- "page_index": page_index,- "fingerprint": fingerprints[page_index],- "bbox_fingerprint": bbox_fingerprints[page_index],- "approved": False,- "blocks": [- {- "id": _block_id(pdf_sha, page_index, block_index, block),- "type": str(block.get("type") or ""),- "text_sha256": _sha256_bytes(_visible_text(block.get("content")).encode("utf-8", errors="replace")),- }- for block_index, block in enumerate(page)- ],- }- for page_index, page in enumerate(pages)- ],- }---def _parse_args() -> argparse.Namespace:- """解析全量回测输出、筛选和渲染开关。"""-- default_source_root = Path(os.environ.get("MINERU_SOURCE_ROOT", SOURCE_ROOT)).resolve()- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--source-root", type=Path, default=default_source_root)- parser.add_argument("--manifest", type=Path)- parser.add_argument("--output", type=Path)- parser.add_argument("--no-render", action="store_true")- parser.add_argument("--include", action="append", default=[], help="仅运行指定 PDF 文件名,可重复传入")- parser.add_argument(- "--role",- action="append",- choices=("normal", "abnormal", "ocr_control"),- default=[],- help="仅运行 manifest 中指定角色,可重复传入",- )- parser.add_argument("--approve", action="store_true", help="把已人工审阅的全部页面标成 approved")- return parser.parse_args()---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 main() -> int:- """执行版本化 Flash 语料并写出几何、金标和视觉审阅产物。"""-- args = _parse_args()- source_root = args.source_root.resolve()- tracked_manifest_path = (args.manifest or source_root / "tests" / "fixtures" / TRACKED_GOLD_MANIFEST.name).resolve()- tracked_gold = json.loads(tracked_manifest_path.read_text(encoding="utf-8"))- output_dir = (args.output or source_root / "output" / "pdf" / DEFAULT_OUTPUT.name).resolve()- documents = []- role_by_name = {- Path(str(document["path"])).name: str(document.get("role") or "") for document in tracked_gold.get("documents", [])- }- corpus_paths = [- path- for path in _corpus_paths(tracked_gold, source_root)- if (not args.include or path.name in set(args.include))- and (not args.role or role_by_name.get(path.name) in set(args.role))- ]- if not corpus_paths:- include_filter = ",".join(args.include) if args.include else "<all>"- role_filter = ",".join(args.role) if args.role else "<all>"- print(- f"No review documents matched selection: include={include_filter}, role={role_filter}",- file=sys.stderr,- )- return 2- if str(source_root) not in sys.path:- sys.path.insert(0, str(source_root))- output_dir.mkdir(parents=True, exist_ok=True)- for index, path in enumerate(corpus_paths, start=1):- print(f"[{index}/{len(corpus_paths)}] {path.name}", flush=True)- document = _run_document(- path,- render=not args.no_render,- output_dir=output_dir / path.stem,- )- if args.approve:- for page in document["gold_pages"]:- page["approved"] = True- documents.append(document)-- gold_mismatches: list[dict[str, Any]] = []- geometry_mismatches: list[dict[str, Any]] = []- tracked_by_file = {Path(str(document["path"])).name: document for document in tracked_gold.get("documents", [])}- for document in documents:- expected = tracked_by_file.get(document["file"])- if expected is None or expected.get("sha256") != document["sha256"]:- gold_mismatches.append({"file": document["file"], "reason": "source_missing_or_sha_mismatch"})- continue- geometry_mismatch = _geometry_summary_mismatch(- document["file"],- expected,- document,- )- if geometry_mismatch is not None:- geometry_mismatches.append(geometry_mismatch)- expected_pages = expected.get("pages", [])- if not expected_pages:- continue- if len(expected_pages) != len(document["page_fingerprints"]):- gold_mismatches.append({"file": document["file"], "reason": "page_count_mismatch"})- continue- semantic_pages = [- page_index- for page_index, (expected_page, actual_fingerprint) in enumerate(- zip(expected_pages, document["page_fingerprints"], strict=True)- )- if expected_page.get("fingerprint") != actual_fingerprint- ]- bbox_pages = [- page_index- for page_index, (expected_page, actual_fingerprint) in enumerate(- zip(expected_pages, document["bbox_fingerprints"], strict=True)- )- if expected_page.get("bbox_fingerprint") != actual_fingerprint- ]- if semantic_pages:- gold_mismatches.append(- {"file": document["file"], "reason": "semantic_fingerprint_mismatch", "pages": semantic_pages}- )- if bbox_pages:- gold_mismatches.append({"file": document["file"], "reason": "bbox_fingerprint_mismatch", "pages": bbox_pages})-- manifest = {- "source_root": str(source_root),- "source_count": len(documents),- "page_count": sum(document["pages"] for document in documents),- "txt_page_count": sum(document["pages"] for document in documents if document["parse_mode"] == "txt"),- "geometry_mismatches": geometry_mismatches,- "gold_mismatches": gold_mismatches,- "documents": [{key: value for key, value in document.items() if key != "gold_pages"} for document in documents],- }- gold = {- "contract": "Flash semantic labels, grouping, and bboxes match the approved corpus",- "baseline_git_sha": tracked_gold.get("baseline_git_sha"),- "source_count": len(documents),- "page_count": manifest["page_count"],- "all_approved": all(page["approved"] for document in documents for page in document["gold_pages"]),- "documents": [- {- "file": document["file"],- "sha256": document["sha256"],- "pages": document["gold_pages"],- }- for document in documents- ],- }- (output_dir / "manifest.json").write_text(- json.dumps(manifest, ensure_ascii=False, indent=2),- encoding="utf-8",- )- (output_dir / "flash_layout_gold_manifest.json").write_text(- json.dumps(gold, ensure_ascii=False, indent=2),- encoding="utf-8",- )- review_lines = [- "# Flash layout geometry review",- "",- f"- Documents: {manifest['source_count']}",- f"- Pages: {manifest['page_count']}",- f"- TXT pages: {manifest['txt_page_count']}",- f"- Geometry summary mismatches: {len(geometry_mismatches)}",- f"- Gold mismatches: {len(gold_mismatches)}",- f"- All pages approved: {gold['all_approved']}",- "",- ]- for document in documents:- review_lines.append(- f"- {document['file']}: {document['pages']} pages, {document['parse_mode']}, "- f"elapsed={document['elapsed_seconds']:.3f}s"- )- (output_dir / "review.md").write_text("\n".join(review_lines) + "\n", encoding="utf-8")- return 1 if geometry_mismatches or gold_mismatches else 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/tests/unittest/_flash_pdf_test_utils.py b/tests/unittest/_flash_pdf_test_utils.pyindex 1de01564..38500216 100644--- a/tests/unittest/_flash_pdf_test_utils.py+++ b/tests/unittest/_flash_pdf_test_utils.py@@ -1,11 +1,103 @@from __future__ import annotations+import hashlib+import json+from typing import Anyfrom mineru.model.flash.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],diff --git a/tests/unittest/test_flash_pdf_semantics.py b/tests/unittest/test_flash_pdf_semantics.pyindex 1d674384..897c0c73 100644--- a/tests/unittest/test_flash_pdf_semantics.py+++ b/tests/unittest/test_flash_pdf_semantics.py@@ -2,10 +2,7 @@ from __future__ import annotationsimport hashlibimport json-import osimport re-import subprocess-import sysimport unicodedatafrom collections import Counterfrom functools import lru_cache@@ -14,7 +11,7 @@ from typing import Anyfrom mineru.model.flash.pdf.document import PDFDocumentfrom mineru.model.flash.pdf.pipeline import _analyze_native_document-from scripts.review_flash_layout_geometry import (+from _flash_pdf_test_utils import (_geometry_summary_mismatch,_page_bbox_fingerprint,_page_fingerprint,@@ -430,109 +427,3 @@ def test_flash_layout_geometry_summary_comparison_is_strict() -> None:"repaired_lines": 1,},}---def test_review_script_import_has_no_source_root_side_effect(tmp_path: Path) -> None:- """验证 import 审阅 helper 不读取 source-root 环境或修改全局模块搜索路径。"""-- fake_root = tmp_path / "stale-checkout"- env = os.environ.copy()- env["MINERU_SOURCE_ROOT"] = str(fake_root)- probe = subprocess.run(- [- sys.executable,- "-c",- (- "import json, sys; before=list(sys.path); "- "import scripts.review_flash_layout_geometry as review; "- "print(json.dumps({'same_path': before == sys.path, "- "'source_root': str(review.SOURCE_ROOT), "- "'mineru_loaded': 'mineru' in sys.modules}))"- ),- ],- cwd=_PROJECT_ROOT,- env=env,- check=True,- capture_output=True,- text=True,- )- payload = json.loads(probe.stdout)-- assert payload == {- "same_path": True,- "source_root": str(_PROJECT_ROOT),- "mineru_loaded": False,- }---def test_review_script_rejects_empty_explicit_selection(tmp_path: Path) -> None:- """验证拼错 include 时审阅脚本返回 2 且不生成零文档成功产物。"""-- output_dir = tmp_path / "review"- result = subprocess.run(- [- sys.executable,- str(_PROJECT_ROOT / "scripts" / "review_flash_layout_geometry.py"),- "--no-render",- "--include",- "definitely-missing.pdf",- "--output",- str(output_dir),- ],- cwd=_PROJECT_ROOT,- check=False,- capture_output=True,- text=True,- )-- assert result.returncode == 2- assert "No review documents matched selection" in result.stderr- assert not output_dir.exists()---def test_review_script_rejects_empty_manifest_and_role_selection(tmp_path: Path) -> None:- """验证空 manifest 与无匹配角色均明确失败,不写审阅结果。"""-- tracked = json.loads(_GEOMETRY_MANIFEST_PATH.read_text(encoding="utf-8"))- cases = [- ({"schema_version": 1, "documents": []}, []),- (- {- "schema_version": 1,- "documents": [- {- **tracked["documents"][0],- "role": "normal",- }- ],- },- ["--role", "abnormal"],- ),- ]- for case_index, (manifest, filters) in enumerate(cases):- manifest_path = tmp_path / f"manifest-{case_index}.json"- output_dir = tmp_path / f"review-{case_index}"- manifest_path.write_text(- json.dumps(manifest),- encoding="utf-8",- )- result = subprocess.run(- [- sys.executable,- str(_PROJECT_ROOT / "scripts" / "review_flash_layout_geometry.py"),- "--no-render",- "--manifest",- str(manifest_path),- "--output",- str(output_dir),- *filters,- ],- cwd=_PROJECT_ROOT,- check=False,- capture_output=True,- text=True,- )-- assert result.returncode == 2- assert "No review documents matched selection" in result.stderr- assert not output_dir.exists()