""" backend/app/services/procurement_contract/pdf_annotation.py 用途:把合同审核发现锚定到原 PDF 页码/坐标,并生成带标准高亮批注的合同副本。 依赖:pypdfium2 提取逐字坐标;pypdf 写入 Highlight annotation。 逻辑:审核结果合并后调用 enrich_result_with_pdf_anchors → 条款写入 evidence_anchor; 下载时文本型 PDF 复用字符坐标,纯图片 PDF 复用持久化 OCR 行框绘制高亮,最后才降级页级批注。 """ from __future__ import annotations import difflib import io import re import unicodedata from typing import Any MAX_ANCHOR_CANDIDATES = 6 MAX_ANCHOR_CHARS = 180 MIN_FUZZY_ANCHOR_CHARS = 10 MIN_FUZZY_SCORE = 0.82 PAGE_IMAGE_MARKER_RE = re.compile(r"!\[page-image-(\d+)\]", re.IGNORECASE) def _compact_text(value: Any) -> str: """归一化空白和全半角,保留字符顺序供 PDF 搜索。""" text = unicodedata.normalize("NFKC", str(value or "")) return re.sub(r"\s+", "", text).strip() def _candidate_texts(item: dict[str, Any]) -> list[str]: """ 按证据可靠性生成 PDF 锚定候选文本。 比对模式优先合同侧 new_text;单份审核优先 evidence。建议、原因和谈判话术不是合同原文, 禁止作为锚点候选,避免把模型生成内容标进 PDF。 """ raw_values = [item.get("new_text"), item.get("evidence")] candidates: list[str] = [] seen: set[str] = set() for raw in raw_values: text = re.sub(r"\s+", " ", str(raw or "")).strip() if not text: continue fragments = [ part.strip(" ,,。;;::()()[]【】") for part in re.split(r"\n+|(?<=[。!?;;])", text) if part.strip() ] for fragment in sorted(fragments or [text], key=len, reverse=True): compact = _compact_text(fragment) if len(compact) < 4 or compact in seen: continue seen.add(compact) 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 def _ocr_pages(clean_text: str) -> list[tuple[int, str]]: """按清洗 Markdown 的 page-image 标记拆分 OCR 扫描件页文本。""" matches = list(PAGE_IMAGE_MARKER_RE.finditer(str(clean_text or ""))) pages: list[tuple[int, str]] = [] for index, match in enumerate(matches): start = match.end() end = matches[index + 1].start() if index + 1 < len(matches) else len(clean_text) pages.append((int(match.group(1)), clean_text[start:end])) return pages def locate_ocr_evidence_page(clean_text: str, item: dict[str, Any]) -> dict[str, Any] | None: """ 扫描 PDF 无文本坐标时,用 OCR 分页正文可靠定位证据所在页。 Returns: 命中时返回 page_no/source_text/confidence/method,不生成伪造矩形坐标。 """ pages = _ocr_pages(clean_text) candidates = _candidate_texts(item) if not pages or not candidates: return None best: dict[str, Any] | None = None for page_no, page_text in pages: page_key = _compact_text(page_text) if not page_key: continue for candidate in candidates: candidate_key = _compact_text(candidate) if len(candidate_key) < 4: continue if candidate_key in page_key: return { "page_no": page_no, "rects": [], "matched_text": candidate, "source_text": candidate, "confidence": 1.0, "method": "ocr_page", } window_size = min(len(candidate_key), 80) if window_size < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < window_size: continue candidate_window = candidate_key[:window_size] step = max(1, window_size // 12) score = max( difflib.SequenceMatcher( a=candidate_window, b=page_key[start : start + window_size], autojunk=False, ).ratio() for start in range(0, len(page_key) - window_size + 1, step) ) if score >= MIN_FUZZY_SCORE and (best is None or score > best["confidence"]): best = { "page_no": page_no, "rects": [], "matched_text": candidate, "source_text": candidate, "confidence": round(score, 3), "method": "ocr_page", } 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: return [] ordered = sorted(rects, key=lambda rect: (-rect[3], rect[0])) lines: list[list[float]] = [] for left, bottom, right, top in ordered: if not lines: lines.append([left, bottom, right, top]) continue current = lines[-1] vertical_overlap = min(current[3], top) - max(current[1], bottom) min_height = max(1.0, min(current[3] - current[1], top - bottom)) if vertical_overlap / min_height >= 0.45: current[0] = min(current[0], left) current[1] = min(current[1], bottom) current[2] = max(current[2], right) current[3] = max(current[3], top) else: lines.append([left, bottom, right, top]) return [[round(value, 2) for value in rect] for rect in lines] def _exact_anchor(textpage: Any, candidate: str) -> dict[str, Any] | None: """使用 PDFium 原生搜索返回首个精确文本命中的坐标。""" query = re.sub(r"\s+", "", candidate) if len(query) < 4: return None searcher = textpage.search(query, match_case=False) occurrence = searcher.get_next() if not occurrence: return None index, count = occurrence rects = [textpage.get_charbox(char_index) for char_index in range(index, index + count)] return { "char_index": int(index), "char_count": int(count), "rects": _merge_char_rects(rects), "matched_text": textpage.get_text_range(index, count), "confidence": 1.0, "method": "exact", } def _fuzzy_anchor(page_text: str, textpage: Any, candidate: str) -> dict[str, Any] | None: """精确搜索失败时,在去空白页文本上做受限滑窗匹配并映射回原字符坐标。""" compact_page_chars: list[str] = [] compact_to_raw: list[int] = [] for raw_index, char in enumerate(page_text): normalized = _compact_text(char) if not normalized: continue compact_page_chars.append(normalized) compact_to_raw.append(raw_index) page_key = "".join(compact_page_chars) candidate_key = _compact_text(candidate) if len(candidate_key) < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < len(candidate_key): return None window_size = min(len(candidate_key), 80) candidate_window = candidate_key[:window_size] best_score = 0.0 best_start = -1 exact_start = page_key.find(candidate_window) if exact_start >= 0: best_score = 1.0 best_start = exact_start step = max(1, window_size // 12) for start in range(0, len(page_key) - window_size + 1, step): if best_score == 1.0: break window = page_key[start : start + window_size] score = difflib.SequenceMatcher(a=candidate_window, b=window, autojunk=False).ratio() if score > best_score: best_score = score best_start = start if best_start < 0 or best_score < MIN_FUZZY_SCORE: return None raw_start = compact_to_raw[best_start] raw_end_index = min(best_start + window_size - 1, len(compact_to_raw) - 1) raw_end = compact_to_raw[raw_end_index] count = max(1, raw_end - raw_start + 1) rects = [textpage.get_charbox(char_index) for char_index in range(raw_start, raw_start + count)] return { "char_index": int(raw_start), "char_count": int(count), "rects": _merge_char_rects(rects), "matched_text": textpage.get_text_range(raw_start, count), "confidence": round(best_score, 3), "method": "fuzzy", } def locate_pdf_evidence(pdf_bytes: bytes, item: dict[str, Any]) -> dict[str, Any] | None: """ 在 PDF 中定位一个审核发现的合同原文证据。 Args: pdf_bytes: 原合同 PDF 字节。 item: 审核发现项,仅使用 new_text/evidence 字段。 Returns: 成功时返回 page_no、rects、matched_text、confidence;无法可靠定位时返回 None。 """ import pypdfium2 as pdfium candidates = _candidate_texts(item) if not candidates: return None document = pdfium.PdfDocument(pdf_bytes) try: best: dict[str, Any] | None = None for page_index in range(len(document)): page = document[page_index] textpage = page.get_textpage() page_text = textpage.get_text_range() for candidate in candidates: located = _exact_anchor(textpage, candidate) if located is None: located = _fuzzy_anchor(page_text, textpage, candidate) if located is None: continue located["page_no"] = page_index + 1 located["source_text"] = candidate if located["method"] == "exact": return located if best is None or located["confidence"] > best["confidence"]: best = located return best finally: document.close() def enrich_result_with_pdf_anchors( result: dict[str, Any], *, filename: str, pdf_bytes: bytes, ocr_layout: dict[str, Any] | None = None, ) -> dict[str, Any]: """ 给审核结果逐项写入 PDF 证据锚点和定位统计;失败不会中断审核主流程。 Args: result: 已完成规则和 LLM 合并的审核结果。 filename: 原合同文件名;非 PDF 时直接标记 unsupported。 pdf_bytes: 原合同字节。 Returns: 原 result 的更新版本。 """ clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else [] summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {} if not str(filename or "").lower().endswith(".pdf"): summary["evidence_anchoring"] = {"status": "unsupported", "anchored": 0, "unanchored": len(clauses)} result["summary_json"] = summary return result anchored = 0 attempted = 0 for item in clauses: 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" anchored += 1 else: item["anchor_status"] = "unanchored" summary["evidence_anchoring"] = { "status": "complete", "anchored": anchored, "unanchored": max(0, attempted - anchored), } result["summary_json"] = summary return result def _annotation_color(risk_level: str) -> str: """映射风险等级到 PDF 高亮颜色。""" if risk_level == "high": return "ff6b6b" if risk_level == "medium": return "ffb84d" return "ffe066" def build_annotated_pdf_bytes( pdf_bytes: bytes, clauses: list[dict[str, Any]], *, clean_text: str = "", ocr_layout: dict[str, Any] | None = None, ) -> bytes: """ 按 evidence_anchor 在原 PDF 副本上写入可打印的标准高亮批注。 Args: pdf_bytes: 原合同 PDF 字节。 clauses: 审核发现列表;优先使用 evidence_anchor,扫描件可回退 OCR 页码定位。 clean_text: 包含 page-image 标记的清洗正文,仅用于扫描 PDF 页级批注。 Returns: 带高亮批注的 PDF 字节;没有可定位发现时返回原合同副本。 """ from pypdf import PdfReader, PdfWriter from pypdf.annotations import Highlight, Text from pypdf.generic import ArrayObject, FloatObject, NameObject, TextStringObject reader = PdfReader(io.BytesIO(pdf_bytes)) writer = PdfWriter() writer.clone_document_from_reader(reader) 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): continue page_index = int(anchor.get("page_no") or 0) - 1 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 left, bottom, right, top = [float(value) for value in raw_rect] quad_points = ArrayObject( [ FloatObject(left), FloatObject(top), FloatObject(right), FloatObject(top), FloatObject(left), FloatObject(bottom), FloatObject(right), FloatObject(bottom), ] ) annotation = Highlight( rect=(left, bottom, right, top), quad_points=quad_points, highlight_color=_annotation_color(str(item.get("risk_level") or "low")), printing=True, ) annotation[NameObject("/Contents")] = TextStringObject( f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}" ) writer.add_annotation(page_number=page_index, annotation=annotation) annotation_count += 1 if not rects: page = writer.pages[page_index] top = float(page.mediabox.top) note = Text( rect=(18, max(18, top - 42), 38, max(38, top - 22)), text=f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}", open=False, ) writer.add_annotation(page_number=page_index, annotation=note) annotation_count += 1 output = io.BytesIO() writer.write(output) return output.getvalue()