389 lines
16 KiB
Python
389 lines
16 KiB
Python
"""
|
||
backend/app/services/procurement_contract/comparison_regions.py
|
||
|
||
Purpose: Validate template comparison-region rules and split uploaded contracts into metadata,
|
||
body, signature, and attachment scopes.
|
||
Dependencies: Standard-library regex/dataclasses only; review_service invokes this before analyze_compare.
|
||
Flow: Admin saves validated JSON; compare reviews partition both user-uploaded files and pass only body text
|
||
to the existing diff engine while returning metadata and attachment summaries separately.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
import re
|
||
from dataclasses import dataclass
|
||
from typing import Any
|
||
|
||
from app.core.errors import ValidationError
|
||
|
||
ALLOWED_METADATA_FIELDS = {"title", "version", "contract_no", "buyer", "seller"}
|
||
ALLOWED_ATTACHMENT_POLICIES = {"page_count_only"}
|
||
CONFIG_ARRAY_FIELDS = (
|
||
"metadata_fields",
|
||
"body_start_anchors",
|
||
"body_end_anchors",
|
||
"signature_terms",
|
||
"attachment_start_anchors",
|
||
)
|
||
|
||
DEFAULT_COMPARISON_REGION_CONFIG: dict[str, Any] = {
|
||
"metadata_fields": ["contract_no", "buyer", "seller", "version"],
|
||
"body_start_anchors": ["兹因甲方向乙方购买设备"],
|
||
"body_end_anchors": ["本合同一式两份", "以下无正文", "本页以下无正文"],
|
||
"signature_terms": ["甲方", "乙方", "盖章", "签署日期", "合同专用章"],
|
||
"attachment_start_anchors": ["附件", "性能需求表", "技术协议", "设备配置清单"],
|
||
"attachment_policy": "page_count_only",
|
||
}
|
||
|
||
_FIELD_PATTERNS = {
|
||
"version": re.compile(r"(?:版本|版次)\s*[::]\s*([^\n;;]{1,40})", re.I),
|
||
"contract_no": re.compile(r"(?:合同(?:编号|号)|编号)\s*[::]\s*([^\n;;]{2,128})", re.I),
|
||
"buyer": re.compile(r"(?:买方|甲方)\s*[::]\s*([^\n;;((]{2,128})", re.I),
|
||
"seller": re.compile(r"(?:卖方|乙方|供应商)\s*[::]\s*([^\n;;((]{2,128})", re.I),
|
||
}
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class RegionPartition:
|
||
"""Recognized comparison scopes for one uploaded contract."""
|
||
|
||
metadata: dict[str, str | None]
|
||
body: str
|
||
signature: str
|
||
attachment_pages: int
|
||
body_start_anchor: str
|
||
body_end_anchor: str
|
||
attachment_anchor: str | None
|
||
signature_terms_found: list[str]
|
||
|
||
|
||
def default_comparison_region_config() -> dict[str, Any]:
|
||
"""Return an isolated V4 default config so callers cannot mutate the shared constant."""
|
||
return copy.deepcopy(DEFAULT_COMPARISON_REGION_CONFIG)
|
||
|
||
|
||
def validate_comparison_region_config(value: Any) -> dict[str, Any]:
|
||
"""
|
||
Validate and normalize a comparison-region JSON object received from Admin.
|
||
|
||
Args:
|
||
value: Dict containing known array fields and attachment_policy.
|
||
|
||
Returns:
|
||
Normalized JSON-safe config with trimmed, deduplicated string arrays.
|
||
|
||
Raises:
|
||
ValidationError: The shape, anchors, metadata field, or policy is unsupported.
|
||
"""
|
||
if not isinstance(value, dict):
|
||
raise ValidationError(
|
||
"comparison_region_config must be an object",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
)
|
||
normalized: dict[str, Any] = {}
|
||
for field in CONFIG_ARRAY_FIELDS:
|
||
raw_items = value.get(field)
|
||
if not isinstance(raw_items, list) or not raw_items:
|
||
raise ValidationError(
|
||
f"{field} must be a non-empty array",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
details={"field": field},
|
||
)
|
||
if len(raw_items) > 20:
|
||
raise ValidationError(
|
||
f"{field} supports at most 20 items",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
details={"field": field},
|
||
)
|
||
items: list[str] = []
|
||
for raw_item in raw_items:
|
||
item = str(raw_item).strip() if isinstance(raw_item, str) else ""
|
||
if not item or len(item) > 120:
|
||
raise ValidationError(
|
||
f"{field} contains an invalid item",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
details={"field": field},
|
||
)
|
||
if item not in items:
|
||
items.append(item)
|
||
normalized[field] = items
|
||
|
||
unknown_fields = set(normalized["metadata_fields"]) - ALLOWED_METADATA_FIELDS
|
||
if unknown_fields:
|
||
raise ValidationError(
|
||
"metadata_fields contains unsupported fields",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
details={"field": "metadata_fields", "unknown": sorted(unknown_fields)},
|
||
)
|
||
policy = str(value.get("attachment_policy") or "").strip()
|
||
if policy not in ALLOWED_ATTACHMENT_POLICIES:
|
||
raise ValidationError(
|
||
"unsupported attachment_policy",
|
||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||
details={"field": "attachment_policy", "value": policy},
|
||
)
|
||
normalized["attachment_policy"] = policy
|
||
return normalized
|
||
|
||
|
||
def _compact_with_positions(text: str) -> tuple[str, list[int]]:
|
||
"""Build punctuation-insensitive text plus source indexes for robust OCR anchor matching."""
|
||
compact: list[str] = []
|
||
positions: list[int] = []
|
||
for index, char in enumerate(text or ""):
|
||
if not char.isalnum():
|
||
continue
|
||
compact.append(char.lower())
|
||
positions.append(index)
|
||
return "".join(compact), positions
|
||
|
||
|
||
def _find_anchor(text: str, anchors: list[str], *, start: int = 0) -> tuple[int, int, str] | None:
|
||
"""Locate the earliest configured anchor while tolerating OCR whitespace and punctuation noise."""
|
||
compact_text, positions = _compact_with_positions(text)
|
||
if not compact_text or not positions:
|
||
return None
|
||
compact_start = next((i for i, source_index in enumerate(positions) if source_index >= start), len(positions))
|
||
matches: list[tuple[int, int, str]] = []
|
||
for anchor in anchors:
|
||
compact_anchor, _ = _compact_with_positions(anchor)
|
||
if not compact_anchor:
|
||
continue
|
||
compact_index = compact_text.find(compact_anchor, compact_start)
|
||
if compact_index < 0:
|
||
continue
|
||
source_start = positions[compact_index]
|
||
source_end = positions[min(compact_index + len(compact_anchor) - 1, len(positions) - 1)] + 1
|
||
matches.append((source_start, source_end, anchor))
|
||
return min(matches, key=lambda item: item[0]) if matches else None
|
||
|
||
|
||
def _body_end_index(text: str, match: tuple[int, int, str]) -> int:
|
||
"""Keep the last substantive clause but exclude explicit no-body markers and following signatures."""
|
||
start, end, anchor = match
|
||
if "无正文" in anchor:
|
||
return start
|
||
tail = text[end : end + 300]
|
||
sentence_end = re.search(r"[。;;\n]", tail)
|
||
return end + sentence_end.end() if sentence_end else end
|
||
|
||
|
||
def _extract_metadata(header_text: str, fields: list[str]) -> dict[str, str | None]:
|
||
"""Extract configured header fields from text preceding the body start anchor."""
|
||
metadata: dict[str, str | None] = {}
|
||
for field in fields:
|
||
if field == "title":
|
||
title = next(
|
||
(line.strip() for line in header_text.splitlines() if "合同" in line and len(line.strip()) <= 80),
|
||
None,
|
||
)
|
||
metadata[field] = title
|
||
continue
|
||
pattern = _FIELD_PATTERNS.get(field)
|
||
match = pattern.search(header_text) if pattern else None
|
||
metadata[field] = re.sub(r"\s+", "", match.group(1)).strip("::;;。 ")[:128] if match else None
|
||
return metadata
|
||
|
||
|
||
def _page_index_for_anchor(page_texts: list[str], anchors: list[str]) -> int | None:
|
||
"""Return the page containing a configured body anchor."""
|
||
for page_index, page_text in enumerate(page_texts):
|
||
if _find_anchor(page_text, anchors):
|
||
return page_index
|
||
return None
|
||
|
||
|
||
def _attachment_boundary(
|
||
page_texts: list[str],
|
||
anchors: list[str],
|
||
*,
|
||
minimum_page_index: int,
|
||
) -> tuple[int, str] | None:
|
||
"""Find an attachment heading near the start of a page after the body/signature boundary."""
|
||
for page_index in range(max(0, minimum_page_index), len(page_texts)):
|
||
page_text = page_texts[page_index]
|
||
compact_page, _ = _compact_with_positions(page_text)
|
||
for anchor in anchors:
|
||
match = _find_anchor(page_text, [anchor])
|
||
if not match:
|
||
continue
|
||
compact_prefix, _ = _compact_with_positions(page_text[: match[0]])
|
||
# Generic "attachment" wording frequently appears inside body clauses; only accept page headings.
|
||
prefix_limit = 45 if anchor in {"附件", "附录"} else 140
|
||
if len(compact_prefix) <= prefix_limit and len(compact_page) > len(anchor):
|
||
return page_index, anchor
|
||
return None
|
||
|
||
|
||
def diagnose_partition(
|
||
text: str,
|
||
page_texts: list[str],
|
||
config: dict[str, Any],
|
||
) -> dict[str, Any]:
|
||
"""
|
||
Report why one uploaded contract can or cannot use comparison-region partitioning.
|
||
|
||
Args:
|
||
text: Cleaned full-document text used by the deterministic comparison.
|
||
page_texts: Extracted text for each physical page, including blank pages.
|
||
config: Already validated comparison-region config.
|
||
|
||
Returns:
|
||
JSON-safe recognition facts for audit records and Worker warning logs. It does not expose
|
||
contract text, only anchor/section availability and the resulting fallback reason.
|
||
"""
|
||
start_match = _find_anchor(text, config["body_start_anchors"])
|
||
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1] if start_match else 0)
|
||
body_end = _body_end_index(text, end_match) if end_match else None
|
||
signature_text = text[body_end:] if body_end is not None else ""
|
||
signature_terms_found = [
|
||
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
|
||
]
|
||
page_text_available = bool(page_texts and any(page.strip() for page in page_texts))
|
||
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"]) if page_text_available else None
|
||
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"]) if page_text_available else None
|
||
attachment = (
|
||
_attachment_boundary(
|
||
page_texts,
|
||
config["attachment_start_anchors"],
|
||
minimum_page_index=body_end_page,
|
||
)
|
||
if body_end_page is not None
|
||
else None
|
||
)
|
||
if not text.strip():
|
||
fallback_reason = "clean_text_unavailable"
|
||
elif not page_text_available:
|
||
fallback_reason = "page_text_unavailable"
|
||
elif not start_match:
|
||
fallback_reason = "body_start_anchor_missing"
|
||
elif not end_match or body_end is None or body_end <= start_match[0]:
|
||
fallback_reason = "body_end_anchor_missing"
|
||
elif body_start_page is None or body_end_page is None or body_end_page < body_start_page:
|
||
fallback_reason = "anchor_page_unavailable"
|
||
elif not signature_terms_found:
|
||
fallback_reason = "signature_term_missing"
|
||
else:
|
||
fallback_reason = None
|
||
return {
|
||
"page_text_available": page_text_available,
|
||
"page_count": len(page_texts),
|
||
"body_start_anchor": start_match[2] if start_match else None,
|
||
"body_end_anchor": end_match[2] if end_match else None,
|
||
"body_start_page": body_start_page + 1 if body_start_page is not None else None,
|
||
"body_end_page": body_end_page + 1 if body_end_page is not None else None,
|
||
"signature_terms_found": signature_terms_found,
|
||
"attachment_anchor": attachment[1] if attachment else None,
|
||
"attachment_page": attachment[0] + 1 if attachment else None,
|
||
"fallback_reason": fallback_reason,
|
||
}
|
||
|
||
|
||
def partition_document(
|
||
text: str,
|
||
page_texts: list[str],
|
||
config: dict[str, Any],
|
||
) -> RegionPartition | None:
|
||
"""
|
||
Partition one contract; return None unless required body anchors and reliable pages are available.
|
||
|
||
Args:
|
||
text: Existing cleaned contract text used by analyze_compare.
|
||
page_texts: Text extracted page-by-page from the original PDF or converted Word PDF.
|
||
config: Already validated comparison-region config.
|
||
|
||
Returns:
|
||
RegionPartition when safe to apply, otherwise None to force legacy full-document comparison.
|
||
"""
|
||
if not text.strip() or not page_texts or not any(page.strip() for page in page_texts):
|
||
return None
|
||
start_match = _find_anchor(text, config["body_start_anchors"])
|
||
if not start_match:
|
||
return None
|
||
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1])
|
||
if not end_match:
|
||
return None
|
||
body_end = _body_end_index(text, end_match)
|
||
if body_end <= start_match[0]:
|
||
return None
|
||
|
||
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"])
|
||
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"])
|
||
if body_start_page is None or body_end_page is None or body_end_page < body_start_page:
|
||
return None
|
||
attachment = _attachment_boundary(
|
||
page_texts,
|
||
config["attachment_start_anchors"],
|
||
minimum_page_index=body_end_page,
|
||
)
|
||
attachment_page = attachment[0] if attachment else len(page_texts)
|
||
attachment_pages = max(0, len(page_texts) - attachment_page)
|
||
signature_text = text[body_end:]
|
||
signature_terms_found = [
|
||
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
|
||
]
|
||
if not signature_terms_found:
|
||
return None
|
||
return RegionPartition(
|
||
metadata=_extract_metadata(text[: start_match[0]], config["metadata_fields"]),
|
||
body=text[start_match[0] : body_end].strip(),
|
||
signature=signature_text.strip(),
|
||
attachment_pages=attachment_pages,
|
||
body_start_anchor=start_match[2],
|
||
body_end_anchor=end_match[2],
|
||
attachment_anchor=attachment[1] if attachment else None,
|
||
signature_terms_found=signature_terms_found,
|
||
)
|
||
|
||
|
||
def build_metadata_comparison(
|
||
original: dict[str, str | None],
|
||
returned: dict[str, str | None],
|
||
) -> dict[str, dict[str, str | None]]:
|
||
"""Build stable field-by-field statuses without adding metadata changes to clause counts."""
|
||
result: dict[str, dict[str, str | None]] = {}
|
||
for field in original.keys() | returned.keys():
|
||
before = original.get(field)
|
||
after = returned.get(field)
|
||
if before == after:
|
||
status = "unchanged"
|
||
elif not before and after:
|
||
status = "filled"
|
||
elif before and not after:
|
||
status = "removed"
|
||
else:
|
||
status = "changed"
|
||
result[field] = {"original": before, "returned": after, "status": status}
|
||
return result
|
||
|
||
|
||
def build_attachment_comparison(original_pages: int, returned_pages: int) -> dict[str, Any]:
|
||
"""Summarize attachment page deltas without exposing attachment content."""
|
||
added = max(0, returned_pages - original_pages)
|
||
removed = max(0, original_pages - returned_pages)
|
||
status = "added" if added else "removed" if removed else "unchanged"
|
||
return {
|
||
"status": status,
|
||
"original_pages": original_pages,
|
||
"returned_pages": returned_pages,
|
||
"added_pages": added,
|
||
"removed_pages": removed,
|
||
}
|
||
|
||
|
||
def preview_anchor_recognition(text: str, config: dict[str, Any]) -> dict[str, Any]:
|
||
"""Preview which configured anchors can be recognized in an Admin template file."""
|
||
start = _find_anchor(text, config["body_start_anchors"])
|
||
end = _find_anchor(text, config["body_end_anchors"], start=start[1] if start else 0)
|
||
attachment = _find_anchor(text, config["attachment_start_anchors"], start=end[1] if end else 0)
|
||
signature_terms = [term for term in config["signature_terms"] if _find_anchor(text, [term])]
|
||
return {
|
||
"status": "recognized" if start and end else "incomplete",
|
||
"body_start_anchor": start[2] if start else None,
|
||
"body_end_anchor": end[2] if end else None,
|
||
"signature_terms_found": signature_terms,
|
||
"attachment_anchor": attachment[2] if attachment else None,
|
||
"warning": None if start and end else "Body start or end anchor was not recognized",
|
||
}
|