fix(contract): 纯图片扫描 PDF 坐标高亮与 OCR 复核
This commit is contained in:
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
|
||||
Reference in new issue
Block a user