fix(contract): 纯图片扫描 PDF 坐标高亮与 OCR 复核

This commit is contained in:
sophie committed 2026-07-29 08:56:13 +08:00
1 parent ca312ea751
commit ce1fd59f61
21 files changed
+1665 -54

No files matched your search

@@ -1,6 +1,9 @@
"""
backend/app/services/knowledge_cleaning/edkb_adapter.py
文件用途:edkb_system 轻量适配层
用途:把 edkb_system 的清洗产物适配为业务服务可直接使用的文件路径和统计信息。
依赖:edkb_system.controller、文件系统临时目录和导出产物约定。
逻辑:复制源文件到隔离目录执行清洗,再把 Markdown、分块和原始布局等必要产物持久化到目标目录。
"""
from __future__ import annotations
@@ -60,6 +63,15 @@ def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
return candidates[0]
def _find_generated_raw_layout(output_root: Path) -> Path | None:
"""定位包含 OCR Block 元数据的原始布局产物,供下游复用检测框。"""
candidates = [path for path in output_root.rglob('01_raw_layout.json') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _count_jsonl_lines(path: Path) -> int:
count = 0
with path.open(encoding='utf-8', errors='ignore') as handle:
@@ -178,6 +190,12 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
raw_layout_source = _find_generated_raw_layout(output_dir)
raw_layout_path = None
if raw_layout_source:
raw_layout_target = target_dir / '01_raw_layout.json'
shutil.copy2(raw_layout_source, raw_layout_target)
raw_layout_path = str(raw_layout_target)
return {
'mode': 'edkb_system',
@@ -186,4 +204,5 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
'word_count': len(content.split()),
'chunks_file_path': chunks_file_path,
'chunks_count': chunks_count,
'raw_layout_path': raw_layout_path,
}
@@ -4,7 +4,7 @@ backend/app/services/procurement_contract/pdf_annotation.py
用途:把合同审核发现锚定到原 PDF 页码/坐标,并生成带标准高亮批注的合同副本。
依赖:pypdfium2 提取逐字坐标;pypdf 写入 Highlight annotation。
逻辑:审核结果合并后调用 enrich_result_with_pdf_anchors → 条款写入 evidence_anchor;
下载时文本型 PDF 复用坐标绘制高亮,扫描 PDF 按 OCR 分页正文定位原页并添加批注意见。
下载时文本型 PDF 复用字符坐标,纯图片 PDF 复用持久化 OCR 行框绘制高亮,最后才降级页级批注。
"""
from __future__ import annotations
@@ -56,6 +56,19 @@ def _candidate_texts(item: dict[str, Any]) -> list[str]:
candidates.append(fragment[:MAX_ANCHOR_CHARS])
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
return candidates
# OCR 可能只错一个值,完整句无法命中时仍可用稳定字段名定位同一行。
stable_values = [item.get("new_text")]
if str(item.get("change_type") or "") == "modify":
stable_values.append(item.get("old_text"))
for raw in stable_values:
text = re.sub(r"^\s*\d+(?:[.、.])?\s*", "", str(raw or "")).strip()
label = re.split(r"[::]", text, maxsplit=1)[0].strip(" ,。;;::")
compact = _compact_text(label)
if 4 <= len(compact) <= 30 and compact not in seen:
seen.add(compact)
candidates.append(label)
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
break
return candidates
@@ -124,6 +137,96 @@ def locate_ocr_evidence_page(clean_text: str, item: dict[str, Any]) -> dict[str,
return best
def _ocr_layout_pages(ocr_layout: dict[str, Any] | None) -> list[dict[str, Any]]:
"""校验并返回 OCR 坐标产物中的页面列表。"""
if not isinstance(ocr_layout, dict):
return []
pages = ocr_layout.get("pages")
return [page for page in pages if isinstance(page, dict)] if isinstance(pages, list) else []
def _layout_match(
page: dict[str, Any],
candidate: str,
) -> tuple[list[dict[str, Any]], float] | None:
"""在单页 OCR 行序列中匹配候选文本,并返回覆盖该文本的行框。"""
lines = [line for line in page.get("lines") or [] if isinstance(line, dict)]
compact_chars: list[str] = []
char_line_indexes: list[int] = []
for line_index, line in enumerate(lines):
for char in _compact_text(line.get("text")):
compact_chars.append(char)
char_line_indexes.append(line_index)
page_key = "".join(compact_chars)
candidate_key = _compact_text(candidate)
if len(candidate_key) < 4 or len(page_key) < len(candidate_key):
return None
window_size = min(len(candidate_key), 80)
candidate_window = candidate_key[:window_size]
best_start = page_key.find(candidate_window)
best_score = 1.0 if best_start >= 0 else 0.0
if best_start < 0 and window_size >= MIN_FUZZY_ANCHOR_CHARS:
step = max(1, window_size // 12)
for start in range(0, len(page_key) - window_size + 1, step):
score = difflib.SequenceMatcher(
a=candidate_window,
b=page_key[start : start + window_size],
autojunk=False,
).ratio()
if score > best_score:
best_start = start
best_score = score
if best_start < 0 or best_score < MIN_FUZZY_SCORE:
return None
end = min(best_start + window_size, len(char_line_indexes))
matched_indexes = sorted(set(char_line_indexes[best_start:end]))
matched_lines = [lines[index] for index in matched_indexes if lines[index].get("polygon")]
if not matched_lines:
return None
return matched_lines, best_score
def locate_ocr_layout_evidence(
ocr_layout: dict[str, Any] | None,
item: dict[str, Any],
) -> dict[str, Any] | None:
"""
在纯图片 PDF 的持久化 OCR 行框中定位证据。
Returns:
命中时返回页码、归一化多边形和置信度;坐标转换延迟到写 PDF 批注阶段完成。
"""
candidates = _candidate_texts(item)
if not candidates:
return None
best: dict[str, Any] | None = None
for page in _ocr_layout_pages(ocr_layout):
page_no = int(page.get("page_no") or 0)
if page_no <= 0:
continue
for candidate in candidates:
matched = _layout_match(page, candidate)
if not matched:
continue
lines, score = matched
anchor = {
"page_no": page_no,
"rects": [],
"ocr_polygons": [line["polygon"] for line in lines],
"matched_text": "\n".join(str(line.get("text") or "") for line in lines),
"source_text": candidate,
"confidence": round(score, 3),
"method": "ocr_bbox_exact" if score == 1.0 else "ocr_bbox_fuzzy",
}
if score == 1.0:
return anchor
if best is None or score > float(best.get("confidence") or 0):
best = anchor
return best
def _merge_char_rects(rects: list[tuple[float, float, float, float]]) -> list[list[float]]:
"""把同一文本行的逐字坐标合并成适合高亮显示的矩形。"""
if not rects:
@@ -261,6 +364,7 @@ def enrich_result_with_pdf_anchors(
*,
filename: str,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
给审核结果逐项写入 PDF 证据锚点和定位统计;失败不会中断审核主流程。
@@ -282,10 +386,15 @@ def enrich_result_with_pdf_anchors(
anchored = 0
attempted = 0
for item in clauses:
if not isinstance(item, dict) or item.get("risk_level") == "ok":
if not isinstance(item, dict):
continue
is_compare_change = str(item.get("change_type") or "") in {"insert", "delete", "modify"}
if item.get("risk_level") == "ok" and not is_compare_change:
continue
attempted += 1
anchor = locate_pdf_evidence(pdf_bytes, item)
if anchor is None:
anchor = locate_ocr_layout_evidence(ocr_layout, item)
if anchor:
item["evidence_anchor"] = anchor
item["anchor_status"] = "anchored"
@@ -315,6 +424,7 @@ def build_annotated_pdf_bytes(
clauses: list[dict[str, Any]],
*,
clean_text: str = "",
ocr_layout: dict[str, Any] | None = None,
) -> bytes:
"""
按 evidence_anchor 在原 PDF 副本上写入可打印的标准高亮批注。
@@ -337,6 +447,8 @@ def build_annotated_pdf_bytes(
annotation_count = 0
for item in clauses:
anchor = item.get("evidence_anchor") if isinstance(item, dict) else None
if not isinstance(anchor, dict) and isinstance(item, dict):
anchor = locate_ocr_layout_evidence(ocr_layout, item)
if not isinstance(anchor, dict) and isinstance(item, dict):
anchor = locate_ocr_evidence_page(clean_text, item)
if not isinstance(anchor, dict):
@@ -345,6 +457,26 @@ def build_annotated_pdf_bytes(
if page_index < 0 or page_index >= len(writer.pages):
continue
rects = anchor.get("rects") or []
if not rects and anchor.get("ocr_polygons"):
page = writer.pages[page_index]
width = float(page.mediabox.width)
height = float(page.mediabox.height)
page_left = float(page.mediabox.left)
page_bottom = float(page.mediabox.bottom)
for polygon in anchor.get("ocr_polygons") or []:
if not isinstance(polygon, list) or len(polygon) < 4:
continue
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
except (TypeError, ValueError, IndexError):
continue
rects.append([
page_left + min(xs) * width,
page_bottom + (1.0 - max(ys)) * height,
page_left + max(xs) * width,
page_bottom + (1.0 - min(ys)) * height,
])
for raw_rect in rects:
if not isinstance(raw_rect, list) or len(raw_rect) != 4:
continue
@@ -27,6 +27,10 @@ from app.services.procurement_contract import analyze, artifact_archive
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
OCR_LAYOUT_ARTIFACT = "ocr_layout.json"
_OCR_RENDER_SCALE = 1.25
def _extract_pdf_page_texts(pdf_path: Path) -> list[str]:
"""
Extract searchable text per PDF page while preserving the source pagination.
@@ -67,6 +71,99 @@ def _ocr_marker_page_texts(raw_text: str) -> list[str]:
return pages
def _ocr_layout_from_edkb(raw_layout_path: Path | None) -> list[dict[str, Any]]:
"""从 edkb 原始布局中提取 PDF 整页 OCR 行框,避免重复执行 OCR。"""
if not raw_layout_path or not raw_layout_path.is_file():
return []
try:
blocks = json.loads(raw_layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return []
pages: dict[int, list[dict[str, Any]]] = {}
for block in blocks if isinstance(blocks, list) else []:
if not isinstance(block, dict) or block.get("type") != "ocr_text":
continue
meta = block.get("meta") if isinstance(block.get("meta"), dict) else {}
if not meta.get("page_image") or not isinstance(meta.get("ocr_lines"), list):
continue
page_no = int(block.get("page") or 0)
if page_no <= 0:
continue
lines = [item for item in meta["ocr_lines"] if isinstance(item, dict) and item.get("polygon")]
if lines:
pages.setdefault(page_no, []).extend(lines)
return [{"page_no": page_no, "lines": pages[page_no]} for page_no in sorted(pages)]
def _ocr_layout_from_pdf(pdf_path: Path) -> list[dict[str, Any]]:
"""
为无文本层 PDF 生成行级 OCR 坐标;RapidOCR 不可用或单页失败时安全返回其余页面。
坐标保存为左上角原点的归一化多边形,下载标注时再按实际 PDF 页面尺寸换算。
"""
try:
import numpy as np
import pypdfium2 as pdfium
from edkb_system.skills.ocr import recognize_image_lines
except Exception:
return []
try:
document = pdfium.PdfDocument(str(pdf_path))
except Exception:
return []
pages: list[dict[str, Any]] = []
try:
for page_index in range(len(document)):
page = document[page_index]
try:
text_page = page.get_textpage()
try:
if (text_page.get_text_range() or "").strip():
continue
finally:
text_page.close()
bitmap = page.render(scale=_OCR_RENDER_SCALE)
image = np.asarray(bitmap.to_pil().convert("RGB"))
lines = recognize_image_lines(image, pdf_page_image=True)
if lines:
pages.append({"page_no": page_index + 1, "lines": lines})
except Exception:
continue
finally:
page.close()
finally:
document.close()
return pages
def _persist_pdf_ocr_layout(
source_path: Path,
target_dir: Path,
*,
raw_layout_path: Path | None = None,
) -> dict[str, Any] | None:
"""复用或生成纯图片 PDF 行坐标,并保存为合同审查可归档产物。"""
if source_path.suffix.lower() != ".pdf":
return None
pages = _ocr_layout_from_edkb(raw_layout_path)
source = "edkb"
if not pages:
pages = _ocr_layout_from_pdf(source_path)
source = "rapidocr_fallback"
if not pages:
return None
payload = {"version": 1, "coordinate_space": "normalized_top_left", "pages": pages}
artifact_path = target_dir / OCR_LAYOUT_ARTIFACT
artifact_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
return {
"source": source,
"page_count": len(pages),
"line_count": sum(len(page.get("lines") or []) for page in pages),
}
def _extract_page_texts(source_path: Path, target_dir: Path, raw_text: str) -> tuple[list[str], str | None]:
"""
Produce physical-page text for PDF and Word files without inventing page boundaries.
@@ -242,6 +339,7 @@ def clean_review_asset(
mode = "edkb_system"
warning: str | None = None
mineru_meta: dict[str, Any] = {}
raw_layout_path: Path | None = None
# [STEP 1] PDF 优先交给 MinerU 恢复版面、表格与阅读顺序;未配置或服务异常时保持旧链路可用。
if source_path.suffix.lower() == ".pdf" and current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL"):
try:
@@ -256,6 +354,8 @@ def clean_review_asset(
cleaned_path = Path(str(clean_result.get("cleaned_file_path") or ""))
raw_text = cleaned_path.read_text(encoding="utf-8", errors="ignore") if cleaned_path.is_file() else ""
mode = str(clean_result.get("mode") or mode)
raw_layout_value = str(clean_result.get("raw_layout_path") or "").strip()
raw_layout_path = Path(raw_layout_value) if raw_layout_value else None
except Exception as exc: # noqa: BLE001 - local extractor is the intended degradation path
warning = f"{warning}; {exc}".strip("; ")[:500]
mode = "local_fallback"
@@ -277,6 +377,9 @@ def clean_review_asset(
clauses_path.write_text(json.dumps(clauses, ensure_ascii=False, indent=2), encoding="utf-8")
quality = analyze.extraction_quality(clean_text)
page_texts, page_warning = _extract_page_texts(source_path, target_dir, raw_text)
ocr_layout = _persist_pdf_ocr_layout(source_path, target_dir, raw_layout_path=raw_layout_path)
if ocr_layout:
ocr_layout["artifact"] = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
return {
"clean_text": clean_text,
"clauses": clauses,
@@ -292,6 +395,7 @@ def clean_review_asset(
"document_artifact": f"cleaned/{normalized_role}/document.md",
"clauses_artifact": f"cleaned/{normalized_role}/clauses.json",
"mineru": mineru_meta or None,
"ocr_layout": ocr_layout,
},
}
@@ -344,3 +448,21 @@ def read_review_clean_text(review_no: str, *, role: str = "contract") -> str:
if not document_path.is_file():
return ""
return document_path.read_text(encoding="utf-8", errors="ignore")
def read_review_ocr_layout(review_no: str, *, role: str = "contract") -> dict[str, Any]:
"""读取或从 MinIO 恢复纯图片 PDF 的行级 OCR 坐标产物。"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
relative_path = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
layout_path = _review_root(review_no) / relative_path
if not layout_path.is_file():
artifact_archive.restore_review_artifact(review_no, relative_path)
if not layout_path.is_file():
return {}
try:
payload = json.loads(layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return payload if isinstance(payload, dict) else {}
@@ -2,7 +2,7 @@
backend/app/services/procurement_contract/review_service.py
用途:创建、异步执行、查询与导出采购合同审查记录。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation/visual_ocr_validation。
逻辑:Chat/Admin API 创建 queued 审查 → Worker 清洗 → 改稿 Diff/五灯或单份五问 →
(仅 solo 可选)LLM 增强 → 页锚落库。比对模式默认不做 Dify 全面扫描。
"""
@@ -31,6 +31,7 @@ from app.services.procurement_contract import (
preprocessing,
rule_service,
template_service,
visual_ocr_validation,
)
DEFAULT_CONTRACT_TYPE = "general_procurement"
@@ -307,7 +308,8 @@ def read_review_annotated_contract_bytes(
"""
生成并读取带审核高亮批注的合同 PDF。
核心逻辑:文本型 PDF 使用 evidence_anchor 写入 Highlight;扫描 PDF 使用已保存 OCR 分页正文定位页面并写入批注意见。
核心逻辑:文本型 PDF 使用 evidence_anchor 写入 Highlight;纯图片 PDF 优先使用已保存 OCR 行框,
无行框时再按 OCR 分页正文定位页面并写入批注意见。
原始 FileAsset 永不修改。没有任何可定位证据时仍返回原合同副本,避免下载入口报错。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
@@ -322,6 +324,7 @@ def read_review_annotated_contract_bytes(
read_asset_bytes(asset),
clauses,
clean_text=preprocessing.read_review_clean_text(row.review_no),
ocr_layout=preprocessing.read_review_ocr_layout(row.review_no),
)
stem = filename.rsplit(".", 1)[0]
return f"{stem}_{row.review_no}_annotated.pdf", data, "application/pdf"
@@ -477,8 +480,8 @@ def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str
"""
在后台 Worker 中执行一份采购合同的完整审核。
核心逻辑:[STEP 1] 复用知识库清洗器;[STEP 2] 合同结构化;[STEP 3] Diff 与整份红线;
[STEP 4] Dify 全面法律扫描;[STEP 5] 后端重算、持久化和报告生成。
核心逻辑:[STEP 1] 复用知识库清洗器;[STEP 2] 合同结构化;[STEP 3] Diff 与双边视觉 OCR 复核;
[STEP 4] 单份审核可选 Dify 法律扫描;[STEP 5] 后端重算、持久化和报告生成。
Args:
review_no: 已创建的审查编号。
@@ -623,6 +626,45 @@ def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str
)
# [STEP 1] Uploaded original remains the baseline; Admin contributes only reusable region rules.
result = analyze.analyze_compare(original_text, returned_text, rules=rules)
# [STEP 2] 混合提取产生的地点类差异再做双边同源 OCR;只有视觉结果一致才移除。
try:
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
result,
review_no=row.review_no,
original_filename=template_asset.original_filename or row.template_name or "template.pdf",
original_pdf_bytes=read_asset_bytes(template_asset),
original_extraction_meta=template_meta,
original_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="template"),
returned_filename=contract_asset.original_filename or row.contract_file_name,
returned_pdf_bytes=read_asset_bytes(contract_asset),
returned_extraction_meta=dict(contract_doc["extraction_meta"]),
returned_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="contract"),
)
except Exception as exc: # noqa: BLE001 - OCR复核失败时必须保留原始差异并继续审核
current_app.logger.warning(
"[contract-review] visual OCR validation failed review_no=%s err=%s",
row.review_no,
exc,
)
validation_summary = (
result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
)
comparison_quality = (
validation_summary.get("comparison_quality")
if isinstance(validation_summary.get("comparison_quality"), dict)
else {}
)
comparison_quality["visual_ocr_rechecks"] = {
"status": "failed",
"mixed_extraction": None,
"checked": 0,
"ignored": 0,
"kept": 0,
"reason": str(exc)[:500],
"items": [],
}
validation_summary["comparison_quality"] = comparison_quality
result["summary_json"] = validation_summary
region_summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
region_summary["comparison_scope"] = comparison_scope
region_summary["metadata_comparison"] = metadata_comparison
@@ -665,6 +707,7 @@ def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str
result,
filename=contract_asset.original_filename or row.contract_file_name,
pdf_bytes=read_asset_bytes(contract_asset),
ocr_layout=preprocessing.read_review_ocr_layout(row.review_no),
)
except Exception as exc: # noqa: BLE001 - evidence anchoring is a non-blocking report enhancement
current_app.logger.warning(
@@ -0,0 +1,726 @@
"""
backend/app/services/procurement_contract/visual_ocr_validation.py
用途:对“原生文本 vs 扫描 OCR”产生的地点字段及设备清单疑似差异执行双边同源 OCR 复核。
依赖:pypdfium2 页面渲染、RapidOCR 行识别、pdf_annotation 页面证据定位。
逻辑:review_service 完成确定性 Diff 后调用本模块;地点字段按行复核,设备清单按视觉坐标
重建表头与数据行;双方同源 OCR 业务值一致时移除噪声差异,并保留结构化诊断与日志。
"""
from __future__ import annotations
import logging
import re
import unicodedata
from typing import Any
from app.services.procurement_contract import pdf_annotation
_LOGGER = logging.getLogger(__name__)
_OCR_RENDER_SCALE = 1.25
_MAX_DIAGNOSTIC_ITEMS = 50
_EQUIPMENT_TABLE_HEADER_TERMS = ("序号", "设备名称", "品牌", "型号", "数量", "单价", "总价")
_EQUIPMENT_TABLE_END_TERMS = ("合计", "备注", "总计")
_EQUIPMENT_DIFF_HINTS = (
"设备名称",
"品牌",
"型号",
"数量",
"单价",
"总价",
"合计",
"总计",
"交易条件",
"清单信息",
)
_LOCATION_FIELD_LABELS = frozenset({
"设备使用地",
"设备安装地",
"交货地点",
"交付地点",
"安装地点",
"使用地点",
})
def _compact_text(value: Any) -> str:
"""统一全半角并只保留中英文和数字,供 OCR 字段行稳定比较。"""
normalized = unicodedata.normalize("NFKC", str(value or ""))
return re.sub(r"[^\u4e00-\u9fffA-Za-z0-9]+", "", normalized)
def _field_label(value: Any) -> str:
"""从差异文本中提取冒号前的稳定字段名,并移除条款编号。"""
text = str(value or "").strip().splitlines()[0] if str(value or "").strip() else ""
text = re.sub(r"^\s*(?:第[一二三四五六七八九十百千万\d]+条|[一二三四五六七八九十百千万\d]+[.、.))])\s*", "", text)
return re.split(r"[::]", text, maxsplit=1)[0].strip(" ,,。;;::")
def _eligible_location_field(item: dict[str, Any]) -> str | None:
"""仅允许双方字段名一致的地点类 modify 项进入自动复核。"""
if str(item.get("change_type") or "") != "modify":
return None
old_text = str(item.get("old_text") or "").strip()
new_text = str(item.get("new_text") or "").strip()
if not old_text or not new_text:
return None
old_label = _field_label(old_text)
new_label = _field_label(new_text)
if old_label != new_label or old_label not in _LOCATION_FIELD_LABELS:
return None
return old_label
def _pdf_text_profile(pdf_bytes: bytes) -> dict[str, int] | None:
"""
检查 PDF 是否含可搜索文字层,用于确认双方是否属于混合提取模式。
Args:
pdf_bytes: 完整 PDF 字节。
Returns:
page_count/native_text_pages;PDF 无法打开时返回 None。
"""
try:
import pypdfium2 as pdfium
document = pdfium.PdfDocument(pdf_bytes)
except Exception:
return None
native_text_pages = 0
try:
for page_index in range(len(document)):
page = document[page_index]
try:
text_page = page.get_textpage()
try:
if (text_page.get_text_range() or "").strip():
native_text_pages += 1
finally:
text_page.close()
finally:
page.close()
return {"page_count": len(document), "native_text_pages": native_text_pages}
finally:
document.close()
def _evidence_item(text: str) -> dict[str, Any]:
"""把单侧字段文本包装成 pdf_annotation 可识别的定位项。"""
return {"change_type": "modify", "old_text": text, "new_text": text}
def _locate_page(
*,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None,
text: str,
scanned_side: bool,
) -> int | None:
"""按页面类型定位字段:扫描侧优先 OCR 行框,文本侧优先 PDF 字符坐标。"""
item = _evidence_item(text)
anchor = (
pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
if scanned_side
else pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
)
if anchor is None and not scanned_side:
anchor = pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
page_no = int((anchor or {}).get("page_no") or 0)
return page_no if page_no > 0 else None
def _ocr_pdf_pages(pdf_bytes: bytes, page_numbers: set[int]) -> dict[int, list[dict[str, Any]]]:
"""
用相同渲染比例和 RapidOCR 参数强制识别指定 PDF 页面。
Args:
pdf_bytes: 完整 PDF 字节,不修改原文件。
page_numbers: 1-based 页面集合;只渲染已由证据定位命中的页面。
Returns:
page_no 到 OCR 行记录的映射;单页失败时保留其他页面结果。
"""
if not page_numbers:
return {}
import numpy as np
import pypdfium2 as pdfium
from edkb_system.skills.ocr import recognize_image_lines
document = pdfium.PdfDocument(pdf_bytes)
output: dict[int, list[dict[str, Any]]] = {}
try:
for page_no in sorted(page_numbers):
if page_no <= 0 or page_no > len(document):
continue
page = document[page_no - 1]
try:
bitmap = page.render(scale=_OCR_RENDER_SCALE)
image = np.asarray(bitmap.to_pil().convert("RGB"))
output[page_no] = recognize_image_lines(
image,
pdf_page_image=True,
retain_short_tokens=True,
)
except Exception as exc: # noqa: BLE001 - one OCR page must not block the contract review
_LOGGER.warning("[contract-review] visual OCR page failed page_no=%s err=%s", page_no, exc)
finally:
page.close()
finally:
document.close()
return output
def _matching_field_line(lines: list[dict[str, Any]], field_label: str) -> str:
"""从 OCR 阅读顺序中选出包含稳定字段名的单行或相邻行窗口。"""
label_key = _compact_text(field_label)
texts = [str(line.get("text") or "").strip() for line in lines if isinstance(line, dict)]
for window_size in (1, 2, 3):
for start in range(0, max(0, len(texts) - window_size + 1)):
candidate = "".join(texts[start : start + window_size])
if label_key and label_key in _compact_text(candidate):
return candidate[:500]
return ""
def _line_bounds(line: dict[str, Any]) -> tuple[float, float, float, float] | None:
"""读取 OCR 行像素框;旧版行记录没有 pixel_polygon 时回退到归一化框。"""
raw_polygon = line.get("pixel_polygon") or line.get("polygon")
if not isinstance(raw_polygon, list):
return None
points: list[tuple[float, float]] = []
for point in raw_polygon:
if not isinstance(point, (list, tuple)) or len(point) < 2:
continue
try:
points.append((float(point[0]), float(point[1])))
except (TypeError, ValueError):
continue
if len(points) < 4:
return None
xs = [point[0] for point in points]
ys = [point[1] for point in points]
return min(xs), min(ys), max(xs), max(ys)
def _line_center(line: dict[str, Any]) -> tuple[float, float] | None:
"""返回 OCR 行框中心点,用于按视觉行和列组织设备表。"""
bounds = _line_bounds(line)
if bounds is None:
return None
left, top, right, bottom = bounds
return (left + right) / 2.0, (top + bottom) / 2.0
def _group_visual_rows(lines: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""根据行框纵向重叠将 OCR 片段聚成视觉行,再按横坐标排序。"""
positioned = [line for line in lines if isinstance(line, dict) and _line_bounds(line)]
positioned.sort(key=lambda line: (_line_center(line) or (0.0, 0.0))[1])
rows: list[dict[str, Any]] = []
for line in positioned:
bounds = _line_bounds(line)
if bounds is None:
continue
_, top, _, bottom = bounds
center_y = (top + bottom) / 2.0
height = max(0.001, bottom - top)
matched: dict[str, Any] | None = None
for row in reversed(rows[-3:]):
tolerance = max(float(row["height"]), height) * 0.7
if abs(center_y - float(row["center_y"])) <= tolerance:
matched = row
break
if matched is None:
rows.append({"center_y": center_y, "height": height, "lines": [line]})
else:
matched_lines = matched["lines"]
matched_lines.append(line)
matched["center_y"] = sum((_line_center(item) or (0.0, 0.0))[1] for item in matched_lines) / len(
matched_lines
)
matched["height"] = max(float(matched["height"]), height)
output: list[list[dict[str, Any]]] = []
for row in rows:
output.append(sorted(row["lines"], key=lambda line: (_line_center(line) or (0.0, 0.0))[0]))
return output
def _table_header_row(rows: list[list[dict[str, Any]]]) -> tuple[int, list[dict[str, Any]]] | None:
"""定位同时包含至少五个标准列名的设备清单表头。"""
best: tuple[int, list[dict[str, Any]], int] | None = None
for row_index, row in enumerate(rows):
text = "".join(str(line.get("text") or "") for line in row)
hits = sum(1 for term in _EQUIPMENT_TABLE_HEADER_TERMS if term in text)
if hits >= 5 and (best is None or hits > best[2]):
best = row_index, row, hits
return (best[0], best[1]) if best else None
def _header_columns(header_row: list[dict[str, Any]]) -> list[tuple[str, float]]:
"""把表头 OCR 片段映射为标准字段及其横向中心,兼容一个片段含多个列名。"""
columns: list[tuple[str, float]] = []
for line in header_row:
text = str(line.get("text") or "")
bounds = _line_bounds(line)
if bounds is None:
continue
left, _, right, _ = bounds
matched_terms = [term for term in _EQUIPMENT_TABLE_HEADER_TERMS if term in text]
if not matched_terms:
continue
width = max(0.001, right - left)
for term in matched_terms:
position = text.find(term)
ratio = (position + len(term) / 2.0) / max(1, len(text))
columns.append((term, left + width * ratio))
deduplicated: dict[str, float] = {}
for term, center_x in columns:
deduplicated.setdefault(term, center_x)
return sorted(deduplicated.items(), key=lambda item: item[1])
def _column_boundaries(columns: list[tuple[str, float]]) -> list[tuple[str, float, float]]:
"""根据相邻表头中心中点生成每列左右边界。"""
boundaries: list[tuple[str, float, float]] = []
for index, (term, center_x) in enumerate(columns):
left = float("-inf") if index == 0 else (columns[index - 1][1] + center_x) / 2.0
right = float("inf") if index == len(columns) - 1 else (center_x + columns[index + 1][1]) / 2.0
boundaries.append((term, left, right))
return boundaries
def _equipment_table_rows(lines: list[dict[str, Any]]) -> dict[str, Any] | None:
"""
从整页 OCR 行框中重建设备清单业务行,空品牌列不会引起后续字段左移。
Returns:
包含 rows/key/page_text 的表格;找不到标准表头或业务行时返回 None。
"""
visual_rows = _group_visual_rows(lines)
located_header = _table_header_row(visual_rows)
if located_header is None:
return None
header_index, header_row = located_header
columns = _header_columns(header_row)
required_columns = {"设备名称", "型号", "数量", "单价", "总价"}
if not required_columns.issubset({term for term, _ in columns}):
return None
boundaries = _column_boundaries(columns)
table_rows: list[dict[str, str]] = []
for row in visual_rows[header_index + 1:]:
row_text = "".join(str(line.get("text") or "") for line in row)
if any(term in row_text for term in _EQUIPMENT_TABLE_END_TERMS):
if table_rows:
break
continue
values = {term: "" for term, _ in columns}
for line in row:
center = _line_center(line)
if center is None:
continue
center_x, _ = center
for term, left, right in boundaries:
if left <= center_x < right:
values[term] += str(line.get("text") or "").strip()
break
if not values.get("设备名称"):
continue
if not any(values.get(term) for term in ("型号", "数量", "单价", "总价")):
continue
table_rows.append(values)
if not table_rows:
return None
comparable_fields = ("设备名称", "品牌", "型号", "数量", "单价", "总价")
normalized_rows = [
{field: _compact_text(row.get(field)) for field in comparable_fields}
for row in table_rows
]
key = "||".join("|".join(row[field] for field in comparable_fields) for row in normalized_rows)
return {"rows": table_rows, "normalized_rows": normalized_rows, "key": key}
def _looks_like_equipment_table_diff(item: dict[str, Any]) -> bool:
"""判断差异项是否可能来自设备清单列错位,避免表格复核影响普通条款。"""
if str(item.get("change_class") or "") != "commercial":
return False
blob = "\n".join(
str(item.get(field) or "")
for field in ("title", "old_text", "new_text")
)
if any(term in blob for term in _EQUIPMENT_DIFF_HINTS[:7]):
return True
has_model = bool(re.search(r"(?=[A-Za-z0-9-]{5,})(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)", blob))
has_amount = bool(re.search(r"\d[\d,.]{2,}", blob))
return has_model and has_amount
def _is_empty_commercial_companion(item: dict[str, Any]) -> bool:
"""识别同一表格错位产生的无原文商业占位项;有任何对照文本时都必须保留。"""
if str(item.get("change_class") or "") != "commercial":
return False
if str(item.get("old_text") or "").strip() or str(item.get("new_text") or "").strip():
return False
detail = str(item.get("detail") or "")
return any(term in detail for term in ("交易条件", "清单信息"))
def _table_candidate_pages(
*,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None,
scanned_side: bool,
) -> set[int]:
"""用标准表头定位设备清单页;定位失败时只回退第一页,不扫描整份合同。"""
item = _evidence_item("序号 设备名称 品牌 型号 数量 单价 总价")
anchor = (
pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
if scanned_side
else pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
)
page_no = int((anchor or {}).get("page_no") or 0)
return {page_no} if page_no > 0 else {1}
def _write_diagnostics(
result: dict[str, Any],
*,
status: str,
mixed_extraction: bool,
checked: int,
ignored: int,
kept: int,
items: list[dict[str, Any]],
reason: str | None = None,
) -> None:
"""把复核统计写入 comparison_quality,确保结果归档后仍可追溯。"""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
quality = summary.get("comparison_quality") if isinstance(summary.get("comparison_quality"), dict) else {}
quality["visual_ocr_rechecks"] = {
"status": status,
"mixed_extraction": mixed_extraction,
"checked": checked,
"ignored": ignored,
"kept": kept,
"reason": reason,
"items": items[:_MAX_DIAGNOSTIC_ITEMS],
}
if ignored:
quality["ignored_ocr_noise"] = int(quality.get("ignored_ocr_noise") or 0) + ignored
summary["comparison_quality"] = quality
result["summary_json"] = summary
def _refresh_focus_lights(result: dict[str, Any]) -> None:
"""差异被移除后同步五盏灯的改动计数,避免摘要仍显示已变化。"""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
lights = summary.get("focus_lights") if isinstance(summary.get("focus_lights"), list) else []
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
risk_rank = {"ok": 0, "low": 1, "medium": 2, "high": 3}
for light in lights:
if not isinstance(light, dict):
continue
category = str(light.get("key") or "")
changes = [
item
for item in clauses
if isinstance(item, dict)
and str(item.get("clause_category") or "") == category
and str(item.get("change_type") or "") in {"insert", "delete", "modify"}
]
if changes:
light["change_count"] = len(changes)
light["risk_level"] = max(
(str(item.get("risk_level") or "ok") for item in changes),
key=lambda level: risk_rank.get(level, 0),
)
light["status"] = "changed"
elif light.get("status") == "changed":
light.update({"status": "unchanged", "risk_level": "ok", "change_count": 0})
summary["focus_lights"] = lights
result["summary_json"] = summary
def _log_diagnostic(review_no: str, diagnostic: dict[str, Any]) -> None:
"""输出单项双边视觉 OCR 复核日志,包含定位失败和保留分支。"""
_LOGGER.info(
"[contract-review] visual OCR recheck review_no=%s type=%s field=%s original_mode=%s "
"returned_mode=%s original_page=%s returned_page=%s old=%r new=%r original_ocr=%r "
"returned_ocr=%r decision=%s reason=%s",
review_no,
diagnostic.get("validation_type"),
diagnostic.get("field_label"),
diagnostic["original_extraction_mode"],
diagnostic["returned_extraction_mode"],
diagnostic["original_page_no"],
diagnostic["returned_page_no"],
diagnostic["old_text"],
diagnostic["new_text"],
diagnostic.get("original_visual_ocr"),
diagnostic.get("returned_visual_ocr"),
diagnostic["decision"],
diagnostic["reason"],
)
def suppress_mixed_extraction_ocr_noise(
result: dict[str, Any],
*,
review_no: str,
original_filename: str,
original_pdf_bytes: bytes,
original_extraction_meta: dict[str, Any] | None,
original_ocr_layout: dict[str, Any] | None,
returned_filename: str,
returned_pdf_bytes: bytes,
returned_extraction_meta: dict[str, Any] | None,
returned_ocr_layout: dict[str, Any] | None,
) -> dict[str, Any]:
"""
移除混合提取模式中经双边同源 OCR 证明一致的地点字段和设备清单噪声差异。
核心逻辑:[STEP 1] 确认一侧为文本 PDF、一侧为扫描 PDF;[STEP 2] 地点字段按稳定标签
定位命中页;[STEP 3] 设备清单按标准表头定位并用坐标重建列;[STEP 4] 双边视觉业务值
完全一致才移除关联差异。设备数量、金额、型号真实变化会使表格键不同并保留差异。
Args:
result: analyze_compare 生成的审核结果,函数原位更新并返回。
review_no: 审查编号,写入结构化日志。
original_filename: 我方原合同文件名,仅 PDF 执行。
original_pdf_bytes: 我方原合同 PDF 字节。
original_extraction_meta: 我方原合同提取元数据。
original_ocr_layout: 我方原合同持久化 OCR 行框。
returned_filename: 供应商回传合同文件名,仅 PDF 执行。
returned_pdf_bytes: 供应商回传合同 PDF 字节。
returned_extraction_meta: 回传合同提取元数据。
returned_ocr_layout: 回传合同持久化 OCR 行框。
Returns:
已更新 clauses_json 和 comparison_quality 诊断的同一结果字典。
"""
if not original_filename.lower().endswith(".pdf") or not returned_filename.lower().endswith(".pdf"):
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="non_pdf_input",
)
return result
# [STEP 1] 直接检查 PDF 文字层,避免把 MinerU/edkb 的提供商名称误当成提取方式。
original_profile = _pdf_text_profile(original_pdf_bytes)
returned_profile = _pdf_text_profile(returned_pdf_bytes)
if original_profile is None or returned_profile is None:
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="pdf_profile_unavailable",
)
return result
original_scanned = original_profile["native_text_pages"] == 0
returned_scanned = returned_profile["native_text_pages"] == 0
mixed_extraction = original_scanned != returned_scanned
if not mixed_extraction:
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="same_extraction_type",
)
return result
# [STEP 2] 先完成地点项页面定位,并识别是否存在设备清单列错位候选项。
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
pending_locations: list[dict[str, Any]] = []
diagnostic_items: list[dict[str, Any]] = []
candidate_item_ids: set[int] = set()
original_pages: set[int] = set()
returned_pages: set[int] = set()
for item in clauses:
if not isinstance(item, dict):
continue
field_label = _eligible_location_field(item)
if not field_label:
continue
candidate_item_ids.add(id(item))
original_page = _locate_page(
pdf_bytes=original_pdf_bytes,
ocr_layout=original_ocr_layout,
text=str(item.get("old_text") or ""),
scanned_side=original_scanned,
)
returned_page = _locate_page(
pdf_bytes=returned_pdf_bytes,
ocr_layout=returned_ocr_layout,
text=str(item.get("new_text") or ""),
scanned_side=returned_scanned,
)
diagnostic = {
"clause_no": item.get("clause_no"),
"title": str(item.get("title") or "")[:200],
"validation_type": "location_field",
"field_label": field_label,
"original_extraction_mode": str((original_extraction_meta or {}).get("mode") or ""),
"returned_extraction_mode": str((returned_extraction_meta or {}).get("mode") or ""),
"original_page_no": original_page,
"returned_page_no": returned_page,
"old_text": str(item.get("old_text") or "")[:500],
"new_text": str(item.get("new_text") or "")[:500],
}
diagnostic_items.append(diagnostic)
if not original_page or not returned_page:
diagnostic.update({"decision": "kept", "reason": "page_not_located"})
_log_diagnostic(review_no, diagnostic)
continue
pending_locations.append({
"item": item,
"field_label": field_label,
"original_page": original_page,
"returned_page": returned_page,
"diagnostic": diagnostic,
})
original_pages.add(original_page)
returned_pages.add(returned_page)
equipment_items = [item for item in clauses if isinstance(item, dict) and _looks_like_equipment_table_diff(item)]
if equipment_items:
candidate_item_ids.update(id(item) for item in equipment_items)
candidate_item_ids.update(id(item) for item in clauses if _is_empty_commercial_companion(item))
original_pages.update(
_table_candidate_pages(
pdf_bytes=original_pdf_bytes,
ocr_layout=original_ocr_layout,
scanned_side=original_scanned,
)
)
returned_pages.update(
_table_candidate_pages(
pdf_bytes=returned_pdf_bytes,
ocr_layout=returned_ocr_layout,
scanned_side=returned_scanned,
)
)
if not diagnostic_items and not equipment_items:
_write_diagnostics(
result,
status="complete",
mixed_extraction=True,
checked=0,
ignored=0,
kept=0,
items=[],
reason="no_eligible_visual_recheck",
)
return result
original_page_ocr = _ocr_pdf_pages(original_pdf_bytes, original_pages) if original_pages else {}
returned_page_ocr = _ocr_pdf_pages(returned_pdf_bytes, returned_pages) if returned_pages else {}
ignored_item_ids: set[int] = set()
# [STEP 3] 地点字段只有双方命中行完全一致时,才把原差异判为 OCR 噪声。
for candidate in pending_locations:
original_visual = _matching_field_line(
original_page_ocr.get(candidate["original_page"], []),
candidate["field_label"],
)
returned_visual = _matching_field_line(
returned_page_ocr.get(candidate["returned_page"], []),
candidate["field_label"],
)
diagnostic = candidate["diagnostic"]
diagnostic["original_visual_ocr"] = original_visual
diagnostic["returned_visual_ocr"] = returned_visual
if original_visual and returned_visual and _compact_text(original_visual) == _compact_text(returned_visual):
diagnostic.update({"decision": "ignored", "reason": "same_visual_ocr"})
ignored_item_ids.add(id(candidate["item"]))
else:
reason = "field_line_not_recognized" if not original_visual or not returned_visual else "visual_ocr_differs"
diagnostic.update({"decision": "kept", "reason": reason})
_log_diagnostic(review_no, diagnostic)
# [STEP 4] 设备表按视觉列重建;空品牌列保留为空,型号/金额不会因线性文本错位而丢失。
if equipment_items:
original_tables = [
(page_no, table)
for page_no in sorted(original_pages)
for table in [_equipment_table_rows(original_page_ocr.get(page_no, []))]
if table
]
returned_tables = [
(page_no, table)
for page_no in sorted(returned_pages)
for table in [_equipment_table_rows(returned_page_ocr.get(page_no, []))]
if table
]
table_match: tuple[int, dict[str, Any], int, dict[str, Any]] | None = None
for original_page, original_table in original_tables:
for returned_page, returned_table in returned_tables:
if original_table["key"] and original_table["key"] == returned_table["key"]:
table_match = original_page, original_table, returned_page, returned_table
break
if table_match:
break
table_diagnostic = {
"clause_no": None,
"title": "设备清单视觉复核",
"validation_type": "equipment_table",
"field_label": "设备清单",
"original_extraction_mode": str((original_extraction_meta or {}).get("mode") or ""),
"returned_extraction_mode": str((returned_extraction_meta or {}).get("mode") or ""),
"original_page_no": table_match[0] if table_match else (original_tables[0][0] if original_tables else None),
"returned_page_no": table_match[2] if table_match else (returned_tables[0][0] if returned_tables else None),
"old_text": "\n".join(str(item.get("old_text") or "") for item in equipment_items)[:500],
"new_text": "\n".join(str(item.get("new_text") or "") for item in equipment_items)[:500],
"original_visual_ocr": (table_match[1]["rows"] if table_match else original_tables[0][1]["rows"])
if original_tables
else None,
"returned_visual_ocr": (table_match[3]["rows"] if table_match else returned_tables[0][1]["rows"])
if returned_tables
else None,
}
diagnostic_items.append(table_diagnostic)
if table_match:
table_diagnostic.update({"decision": "ignored", "reason": "same_visual_equipment_table"})
ignored_item_ids.update(id(item) for item in equipment_items)
ignored_item_ids.update(id(item) for item in clauses if _is_empty_commercial_companion(item))
else:
reason = (
"equipment_table_not_recognized"
if not original_tables or not returned_tables
else "visual_table_differs"
)
table_diagnostic.update({"decision": "kept", "reason": reason})
_log_diagnostic(review_no, table_diagnostic)
if ignored_item_ids:
result["clauses_json"] = [item for item in clauses if id(item) not in ignored_item_ids]
_refresh_focus_lights(result)
ignored = len(ignored_item_ids)
kept = len(candidate_item_ids - ignored_item_ids)
_write_diagnostics(
result,
status="complete",
mixed_extraction=True,
checked=len(pending_locations) + (1 if equipment_items else 0),
ignored=ignored,
kept=kept,
items=diagnostic_items,
)
return result
+109 -23
View File
@@ -1,3 +1,12 @@
"""
edkb_system/skills/ocr.py
用途:识别文档图片中的文字,并为 PDF 整页 OCR 保留可复用的行级坐标与原始像素尺寸。
依赖:RapidOCR、Pillow、NumPy、edkb_system.contracts。
逻辑:图片预处理后执行检测与识别;正文继续写入 ocr_text Block,PDF 整页结果额外保存
归一化多边形,供采购合同等下游在原 PDF 上恢复精确高亮坐标。
"""
from __future__ import annotations
import base64
@@ -55,12 +64,9 @@ def _get_ocr_engine():
return _RAPID_OCR_ENGINE
def _prepare_image_for_ocr(image_obj, block: Block):
meta = getattr(block, "meta", {}) or {}
if not (
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
):
def _prepare_image_for_ocr(image_obj, *, pdf_page_image: bool):
"""限制 PDF 整页图尺寸,兼顾 OCR 速度、内存占用和坐标精度。"""
if not pdf_page_image:
return image_obj
try:
@@ -87,13 +93,89 @@ def _prepare_image_for_ocr(image_obj, block: Block):
return image_obj
def _ocr_call_kwargs(block: Block) -> dict:
meta = getattr(block, "meta", {}) or {}
if meta.get("page_image") and str(meta.get("page_image_source") or "").lower() == "pdf":
def _ocr_call_kwargs(*, pdf_page_image: bool) -> dict:
"""PDF 整页图强制启用文本检测,确保 RapidOCR 返回行框。"""
if pdf_page_image:
return {"use_det": True, "use_cls": False, "use_rec": True}
return {}
def _normalized_polygon(raw_box, *, width: int, height: int) -> list[list[float]]:
"""把 RapidOCR 像素坐标转换为左上角原点的 0..1 归一化多边形。"""
if width <= 0 or height <= 0 or raw_box is None:
return []
points: list[list[float]] = []
try:
raw_points = list(raw_box)
except TypeError:
return []
for raw_point in raw_points:
try:
if len(raw_point) < 2:
continue
x = min(1.0, max(0.0, float(raw_point[0]) / float(width)))
y = min(1.0, max(0.0, float(raw_point[1]) / float(height)))
except (TypeError, ValueError, IndexError):
continue
points.append([round(x, 6), round(y, 6)])
return points if len(points) >= 4 else []
def recognize_image_lines(
image_obj,
*,
min_confidence: float = 0.3,
pdf_page_image: bool = False,
retain_short_tokens: bool = False,
) -> list[dict]:
"""
识别一张图片并返回文本、置信度和可持久化的行级坐标。
Args:
image_obj: NumPy RGB/BGR 图片;调用方不得传文件路径。
min_confidence: 最低识别置信度,低于阈值的行不会输出。
pdf_page_image: True 表示图片覆盖完整 PDF 页面,坐标可以映射回原 PDF。
retain_short_tokens: True 时保留单个数字等短文本,供表格数量/序号列重建;普通正文默认过滤。
Returns:
按 RapidOCR 阅读顺序排列的行记录;polygon 使用左上角原点的归一化坐标,
pixel_polygon 保留 OCR 输入图像像素坐标,供即时表格行列重建使用。
"""
prepared = _prepare_image_for_ocr(image_obj, pdf_page_image=pdf_page_image)
if prepared is None or not hasattr(prepared, "shape") or len(prepared.shape) < 2:
return []
height = int(prepared.shape[0])
width = int(prepared.shape[1])
engine = _get_ocr_engine()
result, _ = engine(prepared, **_ocr_call_kwargs(pdf_page_image=pdf_page_image))
lines: list[dict] = []
for item in result or []:
if len(item) < 3:
continue
text = str(item[1]).strip()
confidence = float(item[2])
keep_short_token = retain_short_tokens and bool(re.fullmatch(r"[A-Za-z0-9]+", text))
if not text or confidence < min_confidence or (not keep_short_token and not _is_meaningful_ocr_line(text)):
continue
line = {"text": text, "confidence": round(confidence, 6)}
if pdf_page_image:
polygon = _normalized_polygon(item[0], width=width, height=height)
if polygon:
line["polygon"] = polygon
try:
pixel_polygon = [
[round(float(point[0]), 3), round(float(point[1]), 3)]
for point in list(item[0])
if len(point) >= 2
]
except (TypeError, ValueError, IndexError):
pixel_polygon = []
if len(pixel_polygon) >= 4:
line["pixel_polygon"] = pixel_polygon
lines.append(line)
return lines
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
@@ -113,8 +195,6 @@ def run(
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is not None:
image_obj = _prepare_image_for_ocr(image_obj, b)
if image_obj is None:
out.append(
Block(
@@ -128,20 +208,25 @@ def run(
continue
try:
result, _ = engine(image_obj, **_ocr_call_kwargs(b))
lines = []
for it in result or []:
if len(it) < 3:
continue
txt = str(it[1]).strip()
conf = float(it[2])
if txt and conf >= min_confidence and _is_meaningful_ocr_line(txt):
lines.append(txt)
if lines:
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
context.ocr_characters += sum(len(x) for x in lines)
meta = getattr(b, "meta", {}) or {}
pdf_page_image = bool(
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
)
line_records = recognize_image_lines(
image_obj,
min_confidence=min_confidence,
pdf_page_image=pdf_page_image,
)
line_texts = [str(item["text"]) for item in line_records]
if line_texts:
text = "OCR_TEXT:\n" + "\n".join(f"- {value}" for value in line_texts)
context.ocr_characters += sum(len(value) for value in line_texts)
else:
text = "OCR_TEXT: <empty>"
output_meta = {"source_image_id": b.id}
if pdf_page_image:
output_meta.update({"page_image": True, "ocr_lines": line_records})
out.append(
Block(
id=f"ocr-{b.id}",
@@ -149,6 +234,7 @@ def run(
type="ocr_text",
text=text,
bbox=b.bbox,
meta=output_meta,
)
)
except Exception as exc:
@@ -3,7 +3,7 @@ tests/services/procurement_contract/test_pdf_annotation.py
用途:验证采购合同 PDF 证据锚定、坐标字段和高亮批注输出。
依赖:procurement_contract.pdf_annotation、pypdfium2、pypdf。
逻辑:覆盖文本型 PDF 精确高亮,以及扫描 PDF 按 OCR 分页正文添加页级批注意见。
逻辑:覆盖文本型 PDF 精确高亮、纯图片 PDF OCR 行框高亮,以及无坐标时的页级批注降级。
"""
from __future__ import annotations
@@ -108,6 +108,108 @@ def test_annotate_scanned_pdf_from_ocr_page_text():
assert len(reader.pages[1].get("/Annots", [])) >= 1
def test_annotate_image_only_pdf_from_persisted_ocr_line_boxes():
"""纯图片 PDF 应把归一化 OCR 行框转换成 PDF 坐标并写入矩形高亮。"""
writer = PdfWriter()
writer.add_blank_page(width=600, height=800)
buffer = io.BytesIO()
writer.write(buffer)
item = {
"title": "设备使用地变更",
"change_type": "modify",
"risk_level": "ok",
"detail": "设备使用地发生变化。",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二厂。",
}
ocr_layout = {
"version": 1,
"coordinate_space": "normalized_top_left",
"pages": [
{
"page_no": 1,
"lines": [
{
"text": "3.设备使用地:一厂。",
"confidence": 0.98,
"polygon": [[0.1, 0.2], [0.5, 0.2], [0.5, 0.24], [0.1, 0.24]],
}
],
}
],
}
anchor = pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
assert anchor is not None
assert anchor["page_no"] == 1
assert anchor["method"] == "ocr_bbox_exact"
assert anchor["ocr_polygons"]
annotated = pdf_annotation.build_annotated_pdf_bytes(
buffer.getvalue(),
[item],
ocr_layout=ocr_layout,
)
reader = PdfReader(io.BytesIO(annotated))
annotations = reader.pages[0].get("/Annots", [])
assert len(annotations) == 1
# 关键断言:写入的是矩形 Highlight,而不是只能指示页码的 Text 批注。
assert annotations[0].get_object().get("/Subtype") == "/Highlight"
def test_ocr_line_box_anchor_falls_back_to_stable_field_label():
"""OCR 把一厂错成二厂时,完整句不一致仍应通过稳定字段名定位同一行。"""
item = {
"title": "设备使用地变更",
"change_type": "modify",
"risk_level": "ok",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二厂。",
}
layout = {
"pages": [
{
"page_no": 2,
"lines": [
{
"text": "3.设备使用地:一厂。",
"polygon": [[0.1, 0.3], [0.4, 0.3], [0.4, 0.34], [0.1, 0.34]],
}
],
}
]
}
anchor = pdf_annotation.locate_ocr_layout_evidence(layout, item)
assert anchor is not None
assert anchor["page_no"] == 2
assert "设备使用地" in anchor["matched_text"]
def test_enrich_anchors_compare_change_even_when_risk_is_ok(monkeypatch):
"""未发现风险的已确认比对改动仍属于标注对象,不能因 risk_level=ok 被跳过。"""
expected_anchor = {"page_no": 1, "rects": [[1, 2, 3, 4]], "method": "exact"}
monkeypatch.setattr(pdf_annotation, "locate_pdf_evidence", lambda *_args, **_kwargs: expected_anchor)
result = {
"summary_json": {},
"clauses_json": [
{
"change_type": "modify",
"risk_level": "ok",
"new_text": "设备使用地:二厂",
}
],
}
enriched = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename="contract.pdf",
pdf_bytes=b"test",
)
assert enriched["clauses_json"][0]["evidence_anchor"] == expected_anchor
assert enriched["summary_json"]["evidence_anchoring"]["anchored"] == 1
def test_annotate_returns_original_pdf_when_no_finding_can_be_anchored():
"""没有可定位证据时下载仍应成功,返回未加批注的合同副本。"""
pdf_bytes = _sample_pdf_bytes()
@@ -1,9 +1,9 @@
"""
backend/tests/services/procurement_contract/test_preprocessing.py
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取与故障回退前提。
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取、OCR 坐标产物与故障回退前提。
依赖:procurement_contract.preprocessing、Flask 最小应用上下文。
逻辑:模拟测试环境 MinerU 的 `/file_parse` 返回,确保 PDF 解析产物可审计且不依赖服务端文件名。
逻辑:模拟测试环境 MinerU 和 edkb 产物,确保 PDF 解析结果与纯图片行坐标可审计、可归档。
"""
from io import BytesIO
@@ -144,3 +144,37 @@ def test_extract_page_texts_uses_mineru_logical_page_when_pdf_has_no_text_layer(
# The logical page is only an anchor fallback; physical attachment page counts remain unavailable.
assert pages == ["兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司"]
assert warning == "PDF native page text unavailable; used MinerU logical page for body boundaries"
def test_ocr_layout_from_edkb_keeps_pdf_page_line_polygons(tmp_path):
"""edkb 已识别的 PDF 整页行框应直接复用,避免合同预处理重复 OCR。"""
raw_layout = tmp_path / "01_raw_layout.json"
raw_layout.write_text(
"""
[
{
"id": "ocr-pdf-page-2",
"page": 2,
"type": "ocr_text",
"text": "OCR_TEXT: 设备使用地:一厂",
"bbox": [0, 0, 1000, 1000],
"meta": {
"page_image": true,
"ocr_lines": [
{
"text": "设备使用地:一厂",
"confidence": 0.98,
"polygon": [[0.1, 0.2], [0.4, 0.2], [0.4, 0.24], [0.1, 0.24]]
}
]
}
}
]
""",
encoding="utf-8",
)
pages = preprocessing._ocr_layout_from_edkb(raw_layout)
assert pages[0]["page_no"] == 2
assert pages[0]["lines"][0]["text"] == "设备使用地:一厂"
assert pages[0]["lines"][0]["polygon"][0] == [0.1, 0.2]
@@ -0,0 +1,307 @@
"""
backend/tests/services/procurement_contract/test_visual_ocr_validation.py
用途:验证混合提取合同的双边同源 OCR 复核只移除地点字段和视觉设备表噪声差异。
依赖:visual_ocr_validation;页面定位和 OCR 在单元测试中替换为确定性结果。
逻辑:构造 compare 差异 → 模拟文字层/扫描件及页面 OCR → 断言移除、保留和诊断分支。
"""
from app.services.procurement_contract import analyze, visual_ocr_validation
def _compare_result(item: dict) -> dict:
"""构造包含一个差异项的最小 compare 结果,便于验证复核后的统计。"""
return {
"summary_json": {
"mode": "compare",
"comparison_quality": {"ignored_ocr_noise": 2},
"focus_lights": [
{
"key": "delivery",
"label": "交期",
"status": "changed",
"risk_level": "medium",
"change_count": 1,
}
],
},
"clauses_json": [item],
}
def _location_modify() -> dict:
"""返回本次真实问题对应的设备使用地 OCR 差异。"""
return {
"clause_no": "1",
"title": "设备使用地变更",
"clause_category": "commercial",
"change_type": "modify",
"risk_level": "ok",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二。",
}
def _run(monkeypatch, result: dict, *, original_ocr: str, returned_ocr: str) -> dict:
"""固定为文字原合同与扫描回传合同,并注入双方命中页 OCR 行。"""
profiles = iter([
{"page_count": 3, "native_text_pages": 3},
{"page_count": 3, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: 2)
page_results = iter([
{2: [{"text": original_ocr}]},
{2: [{"text": returned_ocr}]},
])
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda _data, _pages: next(page_results),
)
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
result,
review_no="CR-TEST",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "edkb_system"},
returned_ocr_layout={"pages": []},
)
def _ocr_line(text: str, left: float, top: float, right: float, bottom: float) -> dict:
"""构造带像素框的 OCR 行,模拟 RapidOCR 表格检测结果。"""
return {
"text": text,
"pixel_polygon": [[left, top], [right, top], [right, bottom], [left, bottom]],
}
def _equipment_page_lines(*, model: str = "BC-MD601", quantity: str = "2") -> list[dict]:
"""构造含空品牌列的标准设备表,验证后续列不会左移。"""
return [
_ocr_line("序号", 100, 100, 150, 125),
_ocr_line("设备名称", 220, 100, 330, 125),
_ocr_line("品牌", 400, 100, 455, 125),
_ocr_line("型号", 525, 100, 580, 125),
_ocr_line("数量", 670, 100, 725, 125),
_ocr_line("单价", 805, 100, 860, 125),
_ocr_line("总价", 945, 100, 1000, 125),
_ocr_line("1", 115, 150, 130, 175),
_ocr_line("半自动拉铆钉机", 205, 150, 350, 175),
_ocr_line(model, 500, 150, 610, 175),
_ocr_line(quantity, 690, 150, 705, 175),
_ocr_line("18,600", 790, 150, 875, 175),
_ocr_line("37,200", 930, 150, 1015, 175),
_ocr_line("合计", 430, 200, 485, 225),
]
def _equipment_result() -> dict:
"""构造截图中的型号漏列修改项及其无文本新增伴随项。"""
modify = {
"clause_no": "1",
"title": "合同内容变更",
"change_type": "modify",
"change_class": "commercial",
"risk_level": "ok",
"old_text": "1|半自动拉铆钉机|BC-MD601|2|18,600|37,200",
"new_text": "1|半自动拉铆钉机|2|18,600|37,200",
}
insert = {
"clause_no": "2",
"title": "合同内容变更",
"change_type": "insert",
"change_class": "commercial",
"risk_level": "ok",
"old_text": "",
"new_text": "",
"detail": "供应商回传合同新增了交易条件或清单信息,请以变更对照为准。",
}
result = _compare_result(modify)
result["clauses_json"].append(insert)
return result
def _run_equipment(monkeypatch, *, original_lines: list[dict], returned_lines: list[dict]) -> dict:
"""注入双方第一页设备表 OCR,执行混合提取视觉复核。"""
profiles = iter([
{"page_count": 5, "native_text_pages": 5},
{"page_count": 6, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_table_candidate_pages", lambda **_kwargs: {1})
page_results = iter([{1: original_lines}, {1: returned_lines}])
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda _data, _pages: next(page_results),
)
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
_equipment_result(),
review_no="CR-TABLE",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "mineru"},
returned_ocr_layout={},
)
def test_same_visual_ocr_removes_location_noise_and_records_diagnostic(monkeypatch):
"""双方视觉 OCR 同为“二”时应移除文本层“一厂 vs 二”的伪差异。"""
result = _run(
monkeypatch,
_compare_result(_location_modify()),
original_ocr="3.设备使用地:二。",
returned_ocr="3.设备使用地:二。",
)
result = analyze.rebuild_result(result)
assert result["clauses_json"] == [] # 关键断言:只移除经双边视觉证明一致的差异。
assert result["summary_json"]["total_changes"] == 0
assert result["total_change_count"] == 0
quality = result["summary_json"]["comparison_quality"]
assert quality["ignored_ocr_noise"] == 3
assert quality["visual_ocr_rechecks"]["ignored"] == 1
assert quality["visual_ocr_rechecks"]["items"][0]["decision"] == "ignored"
assert result["summary_json"]["focus_lights"][0]["status"] == "unchanged"
def test_different_visual_ocr_keeps_location_difference(monkeypatch):
"""双方视觉 OCR 不一致时必须保留差异,避免复核扩大为内容忽略器。"""
result = _run(
monkeypatch,
_compare_result(_location_modify()),
original_ocr="3.设备使用地:一厂。",
returned_ocr="3.设备使用地:二厂。",
)
assert result["clauses_json"] == [_location_modify()]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 0
assert diagnostic["kept"] == 1
assert diagnostic["items"][0]["reason"] == "visual_ocr_differs"
def test_numeric_field_is_never_auto_ignored(monkeypatch):
"""金额等关键数值字段即使双边 OCR 相同,也不得进入地点字段白名单。"""
item = {
"change_type": "modify",
"old_text": "合同总价:10000元",
"new_text": "合同总价:20000元",
"risk_level": "high",
}
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="合同总价:20000元",
returned_ocr="合同总价:20000元",
)
assert result["clauses_json"] == [item]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["checked"] == 0
assert diagnostic["reason"] == "no_eligible_visual_recheck"
def test_insert_and_delete_are_never_auto_ignored(monkeypatch):
"""单侧新增/删除缺少双边对应字段,不执行同源 OCR 自动忽略。"""
item = _location_modify()
item["change_type"] = "insert"
item["old_text"] = ""
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="设备使用地:二厂",
returned_ocr="设备使用地:二厂",
)
assert result["clauses_json"] == [item]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["checked"] == 0
def test_page_location_failure_keeps_difference_without_running_ocr(monkeypatch):
"""任一侧页码定位失败时保留差异并给出 page_not_located 诊断。"""
profiles = iter([
{"page_count": 3, "native_text_pages": 3},
{"page_count": 3, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: None)
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("OCR must not run")),
)
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
_compare_result(_location_modify()),
review_no="CR-TEST",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "edkb_system"},
returned_ocr_layout={},
)
assert len(result["clauses_json"]) == 1
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["kept"] == 1
assert diagnostic["items"][0]["reason"] == "page_not_located"
def test_same_visual_equipment_table_removes_modify_and_empty_insert(monkeypatch):
"""双方视觉设备表一致时,型号漏列修改及同表空新增项应一起移除。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(),
returned_lines=_equipment_page_lines(),
)
result = analyze.rebuild_result(result)
assert result["clauses_json"] == [] # 关键断言:表格线性化产生的两个伪差异同时消失。
assert result["summary_json"]["total_changes"] == 0
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 2
assert diagnostic["kept"] == 0
assert diagnostic["items"][0]["validation_type"] == "equipment_table"
assert diagnostic["items"][0]["reason"] == "same_visual_equipment_table"
def test_visual_equipment_table_keeps_real_model_change(monkeypatch):
"""型号真实变化会使设备表键不同,修改和新增项均保留。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(model="BC-MD601"),
returned_lines=_equipment_page_lines(model="BC-MD602"),
)
assert len(result["clauses_json"]) == 2
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 0
assert diagnostic["items"][0]["reason"] == "visual_table_differs"
def test_visual_equipment_table_keeps_real_quantity_change(monkeypatch):
"""数量真实变化不得被空品牌列容错吞掉。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(quantity="2"),
returned_lines=_equipment_page_lines(quantity="3"),
)
assert len(result["clauses_json"]) == 2
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["items"][0]["reason"] == "visual_table_differs"
+2
View File
@@ -6,6 +6,8 @@
- 合同比对固定上传两份文件:我方原合同与卖方回传合同;不得选择或自动回退库内默认模板。单份审核仍只上传一份待审卖方合同。
- 模板比对须区分“已确认实质修改”和“受 OCR/表格抽取影响待确认”,空格、换行、标点、编号及高相似 OCR 噪声不得直接计为合同修改。
- 原合同有文字层、回传合同为扫描件时,对已产生的地点类修改须按需执行双边同源 OCR 复核;双方视觉字段行一致才可忽略,金额、日期、比例、数量、型号及单侧增删不得自动忽略。
- 设备清单不得直接按 PDF 线性文本顺序判定差异;双方视觉表格的设备名称、品牌、型号、数量、单价和总价一致时,应忽略空单元格或列错位产生的修改/新增伪差异。
- 日期、金额、比例和期限中存在圈号、错字或不确定 OCR 字形时,只能进入待确认;待确认项不得计入高中低风险统计。
- OCR 待确认只保留会影响采购决策的关键事实,并按付款、交期、验收、质保、违约和管辖等业务主题聚合;合同抬头、普通错别字及非关键版面噪声不得逐条要求采购确认。
- 同一条款类别下的不同事实变化必须分别保留,例如预付款比例、出货款比例和付款期限不得合并为一项。
@@ -192,13 +192,13 @@ backend/data/procurement_contract/CR-.../
- 文本质量门禁:记录模板与合同的 `score/level/suspicious_ratio`;明确数字和权利义务变化继续输出,OCR 可疑数字、列表编号、表格错位及高相似字形噪声转入 `comparison_quality.needs_confirmation`,不计入 `total_changes`。
- 条款对齐使用 OCR 容错键,避免圈号、常见数字字形和列表编号导致后续条款整体错位;合同抬头、普通错字及非关键版面噪声计入 `ignored_ocr_noise`,不逐条展示。
- 待确认只保留关键数字或权利义务不明确的片段,并按付款、交付、验收、质保、违约与责任、争议解决等业务主题聚合;`comparison_quality.confirmation_fragments` 保留底层受影响片段数,`needs_confirmation` 表示页面需人工确认的主题数。
- 页码、`page-image-N` 和粘连分页噪声从审核正文剥离;原始 OCR 分页文本保存为 `ocr_document.md`,继续供扫描 PDF 批注定位使用。
- 页码、`page-image-N` 和粘连分页噪声从审核正文剥离;原始 OCR 分页文本保存为 `ocr_document.md`。纯图片 PDF 同时把 RapidOCR 行级检测框保存为 `ocr_layout.json`,坐标采用左上角原点的 0..1 归一化多边形,避免绑定渲染分辨率。
- 关键数字支持圈号、常见 OCR 字形、中文数字和“千分之五”等归一。无法可靠恢复时输出 `needs_review`,不计入高中低风险。
- 条款分类按父级标题、当前标题、正文关键词依次加权;同一业务类别下的不同事实 Diff 全部保留,仅完全相同证据去重。
- 整份红线:比对模式也执行单份审核规则,补足非差异段落中的实质缺项。
- 规则支持 `keyword_missing` 与 `keyword_present`,用于公司明确红线和确定性兜底,不承担全面法律语义审核。
- 采购重点策略:在配置规则之外确定性检查付款是否绑定交付/验收/发票、交期是否可计算、质保期限、买方所在地管辖,以及卖方逾期交付是否达到每日合同总价 `5‰`。
- PDF 证据锚定:优先使用合同侧 `new_text` 或原文 `evidence`,通过 PDFium 精确/模糊搜索获得页码与逐字坐标;扫描 PDF 无文本层时按清洗 Markdown 的 OCR 分页标记定位页码。下载时文本型 PDF 写入风险高亮,扫描 PDF 在对应原页写入批注意见;缺失型风险没有可引用原文时保持 `unanchored`。
- PDF 证据锚定:优先使用合同侧 `new_text` 或原文 `evidence`,通过 PDFium 精确/模糊搜索获得页码与逐字坐标;纯图片 PDF 使用 `ocr_layout.json` 的行文本和多边形做精确/模糊匹配,OCR 值误识别时可回退稳定字段名定位同一行。下载时将归一化坐标换算为 PDF 坐标并写入 Highlight,只有缺少行框时才按 OCR 分页写入页级批注;缺失型风险没有可引用原文时保持 `unanchored`。
- 结果展示分类:`insert/delete/modify` 仅进入合同改动项;`missing/rule_scan/policy_scan/llm_scan` 进入独立风险项;`ocr_uncertain` 或 `validation_status=needs_review` 进入待确认项。三类互斥,待确认项不计入改动数和高中低风险统计。
- Dify 对确定性发现可返回 `confirm/reject/uncertain`;只有原文直接反证和 `confidence >= 0.8` 同时满足时,`reject` 才能撤销误报。
@@ -50,6 +50,8 @@
| R-ANA-02 | 单份:红线规则 + 五问硬规则(付款前置、交期、质保、买方管辖、逾期违约金 ≥ 日 5‰) |
| R-ANA-03 | 正文抽取当事人:供应商(乙方/卖方等)、业务合同编号 |
| R-ANA-04 | 清洗复用知识库能力,待审合同不进入企业正式 Dataset |
| R-ANA-05 | 原生文字 PDF 与扫描 PDF 的地点类修改按需执行双边同源 OCR 复核;只有字段行一致才忽略 |
| R-ANA-06 | 设备清单按视觉坐标重建行列;业务字段一致时忽略空列/阅读顺序产生的修改和新增伪差异 |
### 2.2 非本期范围(Out of Scope)
@@ -176,6 +178,8 @@
- 输入:我方原合同全文 + 卖方回传全文。
- 空格、换行、标点、编号及高相似 OCR 噪声 **不得** 计为合同改动。
- 一侧为原生文字 PDF、另一侧为扫描 PDF 时,只对地点类 `modify` 疑似差异复核双方命中页;同源 OCR 字段行一致才可忽略,金额、日期、比例、数量、型号及 `insert/delete` 必须保留原判断。
- 设备清单出现表格差异时,须按视觉坐标比较设备名称、品牌、型号、数量、单价和总价;空品牌列不得导致型号及后续列左移,业务字段完全一致时可移除同一表格产生的修改和无对照新增项。
- 日期/金额/比例/期限出现圈号、错字或不确定 OCR 字形 → 仅可进待确认(实现上比对主列表可不展示待确认)。
- 同一条款类别下不同事实变化须分别保留(如预付款比例与付款期限不可合并为一项)。
- 比对路径以 Diff + 五盏灯关注为主;**不**强制跑与单份完全相同的整份红线扫缺。
@@ -444,6 +444,23 @@ PDF 保留原始分页;Word 和旧 `.doc` 通过现有 LibreOffice 能力转 P
计入 `comparison_quality.ignored_ocr_noise`,不写入 `clauses_json`。两侧修改及可识别的金额、
期限、型号、功率和数量仍按正常差异处理。
当两份 PDF 一侧有原生文字层、另一侧为纯图片扫描件时,Worker 对已产生的地点类 `modify`
疑似差异执行双边同源 OCR 复核。首期白名单仅包含设备使用地、设备安装地、交货/交付地点、
安装/使用地点:先用原生字符坐标或持久化 OCR 行框定位双方页面,再按相同 1.25 倍渲染比例
和 RapidOCR 参数只识别命中页。双方字段行归一化后完全一致才移除该项,并累计
`comparison_quality.ignored_ocr_noise`;金额、日期、比例、数量、型号及 `insert/delete` 均不
自动忽略。页面定位或 OCR 失败时保留原差异,不阻断审核。
每次复核写入 `comparison_quality.visual_ocr_rechecks`,包含提取模式、双方页码、原始差异、
双边视觉 OCR 文本、判定与原因;后端同时按 `review_no` 输出 `visual OCR recheck` 结构化日志,
用于排查“原生文字正确、扫描 OCR 错误”或“双边 OCR 同错”的案例。
设备清单表格也使用同一视觉复核链路。系统通过“序号/设备名称/品牌/型号/数量/单价/总价”
表头定位双方页面,按 OCR 像素框的纵向重叠聚合数据行,再以表头横坐标中点划分列。空品牌
单元格保持为空,不允许型号、数量和金额左移。双方视觉业务行完全一致时,可同时移除线性
文本错位产生的 `modify` 和无对照文本的商业 `insert` 伴随项;任一型号、数量、单价或总价
不同则保留原差异。该复核只渲染设备表命中页,找不到表头时最多回退双方第一页。
双合同对比按字符变化位置附近的业务对象重新分类,避免同句背景词抢占类别(例如“质保款”
句中的“6 个月→12 个月质保期”归入 warranty,而非 payment)。对比结果的标题、说明和下载
报告由确定性 Diff 生成;Admin 风险规则只提供风险等级参考,不覆盖标题,也不输出建议和
+3 -1
View File
@@ -118,7 +118,7 @@
| 条款层级分类与 Diff 保真 | 已实现增强版 | 子条款继承父级业务类别,标题优先于正文偶发词;同类别不同事实修改分别保留,仅对完全相同证据去重 |
| 双合同差异专用报告 | 已实现 | 按实际变化位置分类,逐项输出我方原文、回传内容及新增/删除/修改类型;风险规则仅提供等级参考,不覆盖差异标题或生成沟通话术 |
| LLM 证据化纠错 | 已实现 | 模型可对确定性项返回 confirm/reject/uncertain;仅真实原文证据且置信度不低于 0.8 时允许撤销误报 |
| PDF 原文证据锚定与标注副本 | 已实现 | 文本型 PDF 保存页码、坐标并高亮;扫描 PDF 按 OCR 分页正文在对应原页添加批注意见;Chat 成功审核的 PDF 始终展示下载入口,未定位项不伪造文字坐标 |
| PDF 原文证据锚定与标注副本 | 已实现增强版 | 文本型 PDF 使用文字层坐标高亮;纯图片扫描 PDF 保存 RapidOCR 行级归一化坐标并恢复矩形高亮,无坐标时才按 OCR 分页添加批注意见;比对改动不因风险等级为 `ok` 跳过锚定;Chat 成功审核的 PDF 始终展示下载入口 |
| 合同审查结果分区展示 | 已实现 | 顶部统计改动项与高中低风险;正文互斥拆分合同改动项、独立风险项、待确认项;风险原文与修改建议分列展示 |
| Chat 双模式 composer + 结果卡 | 已实现 | 合同比对固定上传“我方原合同 + 卖方回传合同”;单份审核上传一份待审合同;进行中展示七步进度轨道并高亮当前阶段;结果卡展示风险统计与条款对照,OCR 待确认按关键业务主题聚合,报告默认 docx |
| 合同当事人字段抽取 | 已实现 | 从对方合同正文识别乙方/卖方 → 供应商、合同编号 → `contract_no`,写入审查记录与下载报告 |
@@ -560,6 +560,8 @@
- [x] 抬头区域排除且不展示、正文限定比对、签章排除
- [x] 附件仅提示页数变化且不计入差异/风险统计
- [x] 锚点或分页失败时全文比对安全回退提示
- [x] 原生文字 PDF 与扫描 PDF 的地点类差异双边同源 OCR 复核、诊断日志与安全保留策略
- [x] 设备清单按 OCR 坐标重建行列,过滤空列/阅读顺序导致的修改与新增伪差异
# HXOPS 与产品内平级服务统一认证(2026-07-27)
+3 -1
View File
@@ -20,7 +20,7 @@ Chat 合同比对的基准固定为用户本次上传的“我方原合同”,
Dify 对已有确定性发现可返回 `confirm/reject/uncertain`。`reject` 必须引用存在于合同正文的直接反证,且置信度不低于 `0.8`;否则后端保持原确定性等级。该协议用于纠正规则误报,不允许无证据降级。
PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 `pypdf` 在原文件副本中写入标准 Highlight annotation;扫描 PDF 无文本层时,依据清洗 Markdown 的 `page-image-N` OCR 分页定位原页并添加 Text annotation,不伪造文字矩形。生成过程不修改原 FileAsset,锚定失败不阻断审核任务。
PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 `pypdf` 在原文件副本中写入标准 Highlight annotation。纯图片扫描 PDF 在首次提取时保存 RapidOCR 行级归一化多边形至 `ocr_layout.json`,标注时按实际 PDF 页面尺寸换算坐标并写入 Highlight;坐标产物随审核目录归档到 MinIO,下载时可按需恢复。仅在没有可用行框时才依据 `page-image-N` OCR 分页添加 Text annotation。生成过程不修改原 FileAsset,锚定失败不阻断审核任务。
## 1. 架构目标
@@ -1135,6 +1135,8 @@ Dify
- 两份上传文件均识别成功后,仅将 `body` 传入既有 `analyze_compare`;`metadata/signature/attachments` 分别进入字段对照、排除区和页数汇总。
- `summary_json` 扩展 `comparison_scope`、`metadata_comparison`、`attachment_comparison`;`clauses_json` 与 Chat 发起接口保持兼容。
- 区域处理为 fail-safe:任何一侧正文锚点或可靠分页缺失时,使用旧全文比对结果并记录回退原因。
- 混合提取 PDF 对地点类 `modify` 差异执行按需双边视觉 OCR:双方命中页用相同渲染比例和 RapidOCR 参数复核,字段行一致时作为 OCR 噪声移除;关键数值、型号和单侧增删不自动忽略。复核诊断写入 `comparison_quality.visual_ocr_rechecks`,定位或识别失败保持原差异。
- 设备清单视觉复核按 OCR 像素框重建表头、数据行和列边界,空单元格不会触发后续列左移;双方设备名称、品牌、型号、数量、单价、总价完全一致时过滤表格线性化产生的修改/空新增伪差异,任一业务字段不一致时保持原结果。
# HXOPS 产品内平级服务统一认证技术补充(2026-07-27)
+7 -2
View File
@@ -13,7 +13,7 @@ import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
const router = useRouter();
const { locale } = useI18n();
const { locale, t } = useI18n();
const { themePreference, initTheme, setThemePreference } = useTheme();
const {
messageDialogVisible,
@@ -62,11 +62,16 @@ watch(themePreference, (newTheme) => {
updateThemePreference(newTheme);
});
/**
* 处理接口返回未登录状态,提示用户重新登录并清理失效的本地登录信息。
* 核心逻辑:忽略可选的 SSO 应用目录请求;其余未授权请求统一展示易懂提示,再执行登出。
* @param event - 包含请求地址和状态码的全局未授权事件。
*/
const onUnauthorized = (event: Event) => {
const url = String((event as CustomEvent<{ url?: string }>).detail?.url || '');
// 外部应用目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return;
showMessageDialog('error', '认证已过期或无效,请重新登录');
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
logoutAuth();
};
@@ -1,7 +1,7 @@
/**
* features/chat/components/ChatInputBar.vue
* 聊天输入栏:文本框、附件、语音、知识库与采购合同双文件输入控件。
* 逻辑:采购合同审查隐藏企业知识库;模板比对明确上传我方原合同和卖方回传合同,单份审核仅上传待审合同。
* 逻辑:附件卡片和快捷操作显示在文字输入区上方;采购合同审查隐藏企业知识库,模板比对明确上传双方合同。
*/
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -374,20 +374,6 @@ watch(
<X class="h-3.5 w-3.5" />
</button>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : isMaintenanceAgent ? $t('maintenance.chat.inputPlaceholder') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-2.5 py-1.5 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 40px; max-height: 220px;"
:disabled="isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
@keydown.enter.prevent="emit('send')"
/>
<input
:ref="bindShippingPickerRef"
type="file"
@@ -539,6 +525,20 @@ watch(
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : isMaintenanceAgent ? $t('maintenance.chat.inputPlaceholder') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-2.5 py-1.5 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 40px; max-height: 220px;"
:disabled="isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
@keydown.enter.prevent="emit('send')"
/>
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
<div class="flex items-center gap-3">
<button
+2
View File
@@ -18,6 +18,8 @@
"passwordRequired": "Password cannot be empty",
"passwordRequiredHint": "Please enter your password",
"loginRequired": "Please login first",
"sessionExpired": "Sign-in expired",
"sessionExpiredHint": "Please sign in again to continue.",
"requestFailed": "Login request failed",
"forgotPassword": "Forgot Password?",
"newPassword": "New Password",
+2
View File
@@ -18,6 +18,8 @@
"passwordRequired": "รหัสผ่านต้องไม่ว่าง",
"passwordRequiredHint": "กรุณากรอกรหัสผ่าน",
"loginRequired": "กรุณาเข้าสู่ระบบก่อนเริ่มการสนทนา",
"sessionExpired": "การเข้าสู่ระบบหมดอายุแล้ว",
"sessionExpiredHint": "กรุณาเข้าสู่ระบบอีกครั้งเพื่อใช้งานต่อ",
"requestFailed": "คำขอเข้าสู่ระบบล้มเหลว",
"forgotPassword": "ลืมรหัสผ่าน?",
"rememberMe": "จดจำฉัน",
+2
View File
@@ -18,6 +18,8 @@
"passwordRequired": "密码不能为空",
"passwordRequiredHint": "请输入密码",
"loginRequired": "请先登录",
"sessionExpired": "登录已失效",
"sessionExpiredHint": "请重新登录后继续使用。",
"requestFailed": "登录请求失败",
"forgotPassword": "忘记密码?",
"newPassword": "新密码",
+2
View File
@@ -18,6 +18,8 @@
"passwordRequired": "密碼不能為空",
"passwordRequiredHint": "請輸入密碼",
"loginRequired": "請先登錄後再進入對話",
"sessionExpired": "登入已失效",
"sessionExpiredHint": "請重新登入後繼續使用。",
"requestFailed": "登錄請求失敗",
"forgotPassword": "忘記密碼?",
"rememberMe": "記住我",