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

@@ -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