Merge branch 'env' into dev

This commit is contained in:
sophie committed 2026-07-27 14:50:18 +08:00
commit d79def5519
90 files changed
+16729 -1344

No files matched your search

@@ -116,3 +116,17 @@ agent_types:
lock_input_when_running:
type: boolean
default: true
procurement_contract_review:
label: 采购合同审查
conversation_mode_default: task_chat
runtime_provider_default: dify
models:
- ContractTemplate
- ContractReview
required_fields: []
default_capabilities:
file_upload: true
forced_capabilities:
file_upload: true
human_confirm: false
handler_config_schema: {}
+98
View File
@@ -1166,6 +1166,104 @@ class DifyService:
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
def run_chatflow_once(
*,
agent,
query: str,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 120),
) -> dict[str, Any]:
"""
以单次、无持久会话方式调用 Dify Chatflow 并收集最终回答。
核心逻辑:复用 Chatflow 的 `/v1/chat-messages` 和 SSE 协议,但不写 chat_logs、
不传 conversation_id;适用于合同审核等后台结构化任务,返回 message_end 的 answer。
Args:
agent: 含 Dify API Key 的 Chatflow Agent。
query: 传给 Chatflow 的一次性任务提示。
inputs: Dify Start 节点声明的变量。
user: Dify 用户标识,不应使用真实业务用户 ID。
timeout: `(connect_seconds, read_seconds)`。
Returns:
包含 `answer`、`conversation_id`、`message_id` 的字典。
Raises:
RuntimeError: Dify 返回错误事件或未产出最终回答。
requests.RequestException: HTTP 连接、超时或状态码错误。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"query": str(query or "").strip(),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[chatflow-once] start agent_id=%s url=%s query_len=%s",
getattr(agent, "id", None),
url,
len(payload["query"]),
)
answer_parts: list[str] = []
final_data: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as response:
if not response.ok and current_app:
current_app.logger.error(
"[chatflow-once] bad response status=%s url=%s body=%s",
response.status_code,
url,
response.text[:2000],
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
if not decoded.startswith("data: "):
continue
try:
data = json.loads(decoded[6:])
except json.JSONDecodeError:
continue
event = str(data.get("event") or "")
if event == "error":
raise RuntimeError(str(data.get("message") or data))
if event == "message" and data.get("answer"):
answer_parts.append(str(data["answer"]))
if event in {"message_end", "workflow_finished"}:
final_data = data
workflow_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if event == "workflow_finished" and workflow_data.get("status") == "failed":
# Chatflow also emits workflow events; expose the canvas-node error to the review task.
error_text = str(workflow_data.get("error") or "Dify Chatflow workflow failed")
raise RuntimeError(error_text)
final_answer = str(data.get("answer") or "").strip()
if final_answer:
answer_parts = [final_answer]
if event == "message_end":
break
answer = "".join(answer_parts).strip()
if not answer:
raise RuntimeError("Dify Chatflow returned no final answer")
return {
"answer": answer,
"conversation_id": final_data.get("conversation_id"),
"message_id": final_data.get("message_id") or final_data.get("id"),
"event": final_data.get("event") or "message_end",
}
@staticmethod
def _log_chat(
user_id,
@@ -0,0 +1,7 @@
"""
backend/app/services/procurement_contract/__init__.py
用途:采购合同审查域服务包入口。
依赖:template_service、review_service。
逻辑:API / Tool 层从此包导入业务函数。
"""
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
"""
backend/app/services/procurement_contract/artifact_archive.py
用途:将采购合同审核的本地运行产物归档至私有 MinIO,并在本地缓存缺失时按需恢复。
依赖:Flask current_app、minio、procurement_contract.preprocessing 的审查目录约定。
逻辑:审核完成后先上传所有文件,再上传 manifest;manifest 成功后本地目录可安全清理,
后续标注合同或 OCR 页码定位通过 manifest 从 MinIO 恢复所需文件。
"""
from __future__ import annotations
import hashlib
import io
import json
import logging
import mimetypes
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from minio import Minio
_LOGGER = logging.getLogger(__name__)
_MANIFEST_NAME = "_manifest.json"
def _archive_enabled() -> bool:
"""读取归档开关,关闭时调用方保持本地缓存行为。"""
return bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_ENABLED", True))
def _archive_bucket() -> str:
"""获取合同专用私有桶名,拒绝空配置避免误写默认桶。"""
bucket = str(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET") or "").strip()
if not bucket:
raise RuntimeError("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET is required")
return bucket
def _archive_client() -> Minio:
"""构造 MinIO 客户端;合同归档不设置 public-read policy。"""
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
if not endpoint:
raise RuntimeError("MINIO_ENDPOINT is required")
return Minio(
endpoint,
access_key=str(current_app.config.get("MINIO_ACCESS_KEY") or ""),
secret_key=str(current_app.config.get("MINIO_SECRET_KEY") or ""),
secure=bool(current_app.config.get("MINIO_SECURE", False)),
)
def _review_root(review_no: str) -> Path:
"""将审查编号限制在存储根目录内,和预处理阶段保持同一目录规则。"""
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve()
candidate = (root / str(review_no or "").strip()).resolve()
if candidate.parent != root:
raise RuntimeError("invalid review_no")
return candidate
def _object_key(review_no: str, relative_path: Path) -> str:
"""生成稳定对象键,保留审查目录内的相对层级。"""
return f"reviews/{review_no}/{relative_path.as_posix()}"
def _ensure_bucket(client: Minio, bucket: str) -> None:
"""确保私有合同桶存在;禁止继承公开资料桶策略。"""
if not client.bucket_exists(bucket):
client.make_bucket(bucket)
def _file_entry(path: Path, *, root: Path) -> dict[str, Any]:
"""生成可校验的归档清单条目,供恢复时限定允许路径。"""
data = path.read_bytes()
relative = path.relative_to(root)
return {
"path": relative.as_posix(),
"size": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
}
def archive_review_artifacts(review_no: str) -> dict[str, Any]:
"""
上传一份审核的所有本地产物,并最后写入 manifest 作为完整归档提交标记。
Args:
review_no: 已完成审核编号。
Returns:
归档状态、bucket、对象前缀和文件数量;开关关闭时返回 disabled。
Raises:
RuntimeError: 本地目录不存在或 MinIO 上传失败;调用方必须保留本地目录。
"""
if not _archive_enabled():
return {"status": "disabled"}
root = _review_root(review_no)
if not root.is_dir():
raise RuntimeError(f"review artifact directory not found: {review_no}")
files = sorted(
(path for path in root.rglob("*") if path.is_file() and path.name != _MANIFEST_NAME),
key=lambda path: path.relative_to(root).as_posix(),
)
if not files:
raise RuntimeError(f"review artifact directory is empty: {review_no}")
client = _archive_client()
bucket = _archive_bucket()
_ensure_bucket(client, bucket)
entries: list[dict[str, Any]] = []
for path in files:
entry = _file_entry(path, root=root)
data = path.read_bytes()
client.put_object(
bucket,
_object_key(review_no, Path(entry["path"])),
io.BytesIO(data),
len(data),
content_type=entry["content_type"],
)
entries.append(entry)
manifest = {
"review_no": review_no,
"archived_at": datetime.now(timezone.utc).isoformat(),
"files": entries,
}
manifest_data = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")
client.put_object(
bucket,
_object_key(review_no, Path(_MANIFEST_NAME)),
io.BytesIO(manifest_data),
len(manifest_data),
content_type="application/json",
)
return {
"status": "archived",
"bucket": bucket,
"prefix": f"reviews/{review_no}/",
"manifest_key": _object_key(review_no, Path(_MANIFEST_NAME)),
"file_count": len(entries),
}
def restore_review_artifact(review_no: str, relative_path: str) -> Path | None:
"""
本地缓存缺失时,从已提交 manifest 的私有归档恢复单个文件。
Args:
review_no: 审查编号。
relative_path: 审查目录下的相对文件路径,不允许绝对路径或父级跳转。
Returns:
已存在或恢复后的本地路径;归档关闭或 manifest 未包含该文件时返回 None。
"""
root = _review_root(review_no)
relative = Path(relative_path)
target = (root / relative).resolve()
if target.parent != root and root not in target.parents:
raise RuntimeError("invalid artifact relative path")
if target.is_file():
return target
if not _archive_enabled():
return None
client = _archive_client()
bucket = _archive_bucket()
try:
response = client.get_object(bucket, _object_key(review_no, Path(_MANIFEST_NAME)))
try:
manifest = json.loads(response.read().decode("utf-8"))
finally:
response.close()
response.release_conn()
allowed = {str(item.get("path")): item for item in manifest.get("files") or [] if isinstance(item, dict)}
entry = allowed.get(relative.as_posix())
if not entry:
return None
response = client.get_object(bucket, _object_key(review_no, relative))
try:
data = response.read()
finally:
response.close()
response.release_conn()
except Exception as exc:
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
if hashlib.sha256(data).hexdigest() != str(entry.get("sha256") or ""):
_LOGGER.warning("[contract-review] artifact checksum mismatch review_no=%s path=%s", review_no, relative)
return None
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
return target
def cleanup_local_review_artifacts(review_no: str) -> bool:
"""仅在归档成功后删除本地运行缓存;由环境开关控制,删除失败不影响归档结果。"""
if not bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL", True)):
return False
root = _review_root(review_no)
if not root.is_dir():
return False
shutil.rmtree(root)
return True
@@ -0,0 +1,388 @@
"""
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",
}
@@ -0,0 +1,512 @@
"""
backend/app/services/procurement_contract/llm_enhancer.py
Purpose: Dify Chatflow/Workflow-based comprehensive legal review for cleaned procurement contracts.
Dependencies: Config, DifyService, Agent model.
Flow: review_service passes cleaned text, structured clauses and deterministic findings; Dify Chatflow or Workflow enhances existing findings
and independently returns new legal risks, then this module validates and merges them without lowering deterministic risk.
"""
from __future__ import annotations
import json
import re
from typing import Any
from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
MAX_FINDINGS = 20
MAX_TEXT_CHARS = 900
VALID_RISK_LEVELS = {"high", "medium", "low", "ok"}
RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
def is_enabled() -> bool:
"""Return whether procurement-contract LLM enhancement is enabled by configuration."""
return bool(getattr(Config, "PROCUREMENT_CONTRACT_LLM_ENABLED", False))
def enhance_review_result(
result: dict[str, Any],
*,
review_no: str,
review_mode: str,
contract_type: str | None,
template_name: str | None = None,
clean_text: str = "",
structured_clauses: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
Ask Dify to enhance deterministic findings and independently scan the cleaned contract.
AI trigger timing: call after HXOPS has cleaned and structured the contract and completed Diff/rule checks.
The LLM must return JSON only; it may add risks and may challenge deterministic findings only with verified evidence.
Args:
result: HXOPS deterministic review result.
review_no/review_mode/contract_type/template_name: Review context passed to Dify.
clean_text: Cleaned contract Markdown text; never pass a server-local path.
structured_clauses: Full ordered clause list generated by HXOPS.
Returns:
Result with enhanced existing findings, validated new_items and Dify audit metadata.
"""
if not is_enabled():
return result
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
clean_text = str(clean_text or "").strip()
structured_clauses = structured_clauses or []
if not clean_text or not structured_clauses:
return _with_llm_meta(result, enabled=True, status="skipped", message="cleaned contract is unavailable")
agent = _resolve_agent()
if not agent:
return _with_llm_meta(result, enabled=True, status="skipped", message="LLM agent is not configured")
findings = _build_findings_payload(clauses)
max_text_chars = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS", 120000) or 120000), 10000)
max_clauses = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES", 160) or 160), 20)
sent_text = clean_text[:max_text_chars]
sent_clauses = structured_clauses[:max_clauses]
input_truncated = len(clean_text) > len(sent_text) or len(structured_clauses) > len(sent_clauses)
inputs = {
"review_no": review_no,
"review_mode": review_mode,
"contract_type": contract_type or "general_procurement",
"template_name": template_name or "",
"findings_json": json.dumps(findings, ensure_ascii=False),
"clauses_json": json.dumps(sent_clauses, ensure_ascii=False),
"clean_text": sent_text,
"scan_enabled": "true",
"scan_scope": "bounded_contract" if input_truncated else "full_contract",
"instruction": _review_instruction(),
}
try:
timeout = (
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS", 5) or 5),
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS", 120) or 120),
)
provider = _review_provider(agent)
if provider == "chatflow":
response = DifyService.run_chatflow_once(
agent=agent,
query=_chatflow_review_query(),
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output({"answer": response.get("answer")})
workflow_run_id = str(response.get("message_id") or "") or None
else:
response = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output(response)
workflow_run_id = _workflow_run_id(response)
except Exception as exc: # noqa: BLE001 - enhancement must not fail deterministic review
if current_app:
current_app.logger.warning("[contract-llm] enhance failed review_no=%s err=%s", review_no, exc)
return _with_llm_meta(result, enabled=True, status="failed", message=str(exc)[:500])
if not enhancements and not new_items:
return _with_llm_meta(result, enabled=True, status="empty", message="LLM returned no usable review items")
merged = _merge_review_output(
result,
enhancements,
new_items,
clean_text=clean_text,
structured_clauses=structured_clauses,
)
summary = merged.get("summary_json") if isinstance(merged.get("summary_json"), dict) else {}
summary["llm_input"] = {
"text_characters": len(clean_text),
"sent_text_characters": len(sent_text),
"clause_count": len(structured_clauses),
"sent_clause_count": len(sent_clauses),
"truncated": input_truncated,
}
merged["summary_json"] = summary
return _with_llm_meta(
merged,
enabled=True,
status="success",
message="Dify comprehensive review applied",
provider=provider,
workflow_run_id=workflow_run_id,
)
def _resolve_agent() -> Agent | None:
"""Resolve the configured Dify Chatflow or Workflow agent used for contract review."""
agent_id = int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_AGENT_ID", 0) or 0)
if agent_id:
row = db.session.get(Agent, agent_id)
if row and row.is_active and row.dify_api_key:
return row
app_id = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID", "") or "").strip()
if app_id:
row = db.session.query(Agent).filter(Agent.dify_app_id == app_id, Agent.is_active.is_(True)).first()
if row and row.dify_api_key:
return row
api_key = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY", "") or "").strip()
if api_key:
return Agent(
id=0,
name="Procurement Contract LLM Enhancer",
dify_api_key=api_key,
api_base_url=str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_BASE", "") or "").strip() or Config.DIFY_API_BASE,
dify_app_type="workflow",
)
return None
def _review_provider(agent: Agent) -> str:
"""Return the configured Dify provider; env override supports reusing a Chatflow during rollout."""
configured = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "agent") or "agent").strip().lower()
if configured in {"chatflow", "workflow"}:
return configured
app_type = str(getattr(agent, "dify_app_type", "") or "").strip().lower()
return "chatflow" if app_type == "chatflow" else "workflow"
def _chatflow_review_query() -> str:
"""
提供给 Chatflow 的一次性任务提示;正式合同内容均通过 Start inputs 传入。
Chatflow 可以沿用普通会话应用,但必须在画布中识别该指令并只输出 JSON,
否则后端会把非 JSON 回答标为无可用审核项。
"""
return "执行合同全面审核任务。请严格根据 Start 输入变量返回 instruction 要求的 JSON,不要输出解释性文字。"
def _build_findings_payload(clauses: list[Any]) -> list[dict[str, Any]]:
"""Build compact findings for LLM consumption without sending the whole contract."""
findings: list[dict[str, Any]] = []
for idx, raw in enumerate(clauses[:MAX_FINDINGS], start=1):
if not isinstance(raw, dict):
continue
findings.append(
{
"id": str(raw.get("clause_no") or idx),
"title": str(raw.get("title") or raw.get("clause_category") or f"finding-{idx}")[:120],
"change_type": str(raw.get("change_type") or ""),
"rule_risk_level": str(raw.get("risk_level") or ""),
"category": str(raw.get("clause_category") or ""),
"rule_detail": _clip(raw.get("detail")),
"rule_risk_hint": _clip(raw.get("risk_hint")),
"rule_suggestion": _clip(raw.get("suggestion")),
"template_excerpt": _clip(raw.get("old_text"), 450),
"contract_excerpt": _clip(raw.get("new_text"), 450),
}
)
return findings
def _review_instruction() -> str:
"""Build the versioned instruction consumed by the Chatflow review branch's LLM node."""
# [PROMPT_UPDATE] 2026-07-21: 增加带原文证据和置信度门槛的 confirm/reject/uncertain 纠错协议。
return (
"你是企业采购方合同审核助手。输入包含 clean_text、clauses_json、findings_json。"
"必须逐条覆盖 clauses_json,并结合全文检查付款、交付、验收、质保、违约赔偿、免责、"
"责任上限、知识产权、保密数据、解除续期、不可抗力、争议解决以及跨条款冲突。"
"items 用于增强 findings_json 已有项;new_items 用于返回后端未发现的新风险。"
"每个 new_item 必须引用真实 clause_id/clause_no,并给出合同原文 evidence;禁止编造法条编号。"
"返回严格 JSON:{\"items\":[{\"id\":\"1\",\"decision\":\"confirm|reject|uncertain\",\"evidence\":\"合同原文\",\"professional_reason\":\"...\","
"\"professional_suggestion\":\"...\",\"negotiation_text\":\"...\","
"\"model_risk_level\":\"high|medium|low|ok\",\"confidence\":0.0}],"
"\"new_items\":[{\"id\":\"llm-1\",\"clause_id\":\"clause-0001\","
"\"clause_no\":\"第八条\",\"title\":\"...\",\"clause_category\":\"liability\","
"\"risk_level\":\"high|medium|low\",\"professional_reason\":\"...\","
"\"business_impact\":\"...\",\"professional_suggestion\":\"...\","
"\"negotiation_text\":\"...\",\"evidence\":\"合同原文\",\"confidence\":0.0}]}."
"已有项若规则结论正确返回 confirm;若原文明确证明规则误报可返回 reject;OCR 无法确认返回 uncertain。"
"reject 必须引用能直接反驳规则结论的真实合同原文,且 confidence 不低于0.8;confidence 必须为 0 到 1。"
)
def _clip(value: Any, limit: int = MAX_TEXT_CHARS) -> str:
"""Normalize and clip text sent to or returned from the LLM."""
text = re.sub(r"\s+", " ", str(value or "")).strip()
if len(text) <= limit:
return text
return text[:limit] + "..."
def _extract_review_output(
workflow_result: dict[str, Any] | None,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
"""Parse Dify outputs into existing-finding enhancements and independent new risks."""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = data.get("outputs") if isinstance(data.get("outputs"), dict) else {}
direct_output = None
if outputs.get("items") is not None or outputs.get("new_items") is not None:
direct_output = {
"items": _parse_json_candidate(outputs.get("items")) or outputs.get("items") or [],
"new_items": _parse_json_candidate(outputs.get("new_items")) or outputs.get("new_items") or [],
}
candidates = [
direct_output,
outputs.get("items"),
outputs.get("enhancements"),
outputs.get("result"),
outputs.get("text"),
outputs.get("output"),
data.get("answer"),
]
parsed: Any = None
for candidate in candidates:
parsed = _parse_json_candidate(candidate)
if parsed:
break
raw_new_items: list[Any] = []
if isinstance(parsed, dict):
raw_items = parsed.get("items") or parsed.get("enhancements") or []
raw_new_items = parsed.get("new_items") or parsed.get("newItems") or []
elif isinstance(parsed, list):
raw_items = parsed
else:
raw_items = []
out: dict[str, dict[str, Any]] = {}
for item in raw_items:
if not isinstance(item, dict):
continue
item_id = str(item.get("id") or item.get("clause_no") or "").strip()
if not item_id:
continue
confidence = _normalize_confidence(item.get("confidence"))
level = str(item.get("model_risk_level") or item.get("risk_level") or "").strip().lower()
if level not in VALID_RISK_LEVELS:
level = ""
decision = str(item.get("decision") or "confirm").strip().lower()
if decision not in {"confirm", "reject", "uncertain"}:
decision = "confirm"
out[item_id] = {
"llm_reason": _clip(item.get("professional_reason") or item.get("reason") or item.get("detail")),
"llm_suggestion": _clip(item.get("professional_suggestion") or item.get("suggestion")),
"llm_negotiation_text": _clip(item.get("negotiation_text")),
"llm_model_risk_level": level,
"llm_confidence": confidence,
"llm_decision": decision,
"llm_evidence": _clip(item.get("evidence"), 1200),
}
new_items = [item for item in raw_new_items if isinstance(item, dict)]
return out, new_items
def _parse_json_candidate(value: Any) -> Any:
"""Parse a Dify output value that may already be JSON or may be JSON text."""
if isinstance(value, (dict, list)):
return value
if not isinstance(value, str) or not value.strip():
return None
text = value.strip()
try:
return json.loads(text)
except json.JSONDecodeError:
pass
match = re.search(r"```(?:json)?\s*(.*?)```", text, flags=re.S)
if match:
try:
return json.loads(match.group(1).strip())
except json.JSONDecodeError:
return None
start = min([i for i in [text.find("{"), text.find("[")] if i >= 0], default=-1)
end = max(text.rfind("}"), text.rfind("]"))
if start >= 0 and end > start:
try:
return json.loads(text[start : end + 1])
except json.JSONDecodeError:
return None
return None
def _normalize_confidence(value: Any) -> float | None:
"""Normalize confidence to 0..1."""
try:
num = float(value)
except (TypeError, ValueError):
return None
if num > 1:
num = num / 100
return max(0.0, min(1.0, round(num, 2)))
def _normalize_evidence(value: Any) -> str:
"""归一化证据文本,供原文包含校验和结果展示。"""
return re.sub(r"\s+", "", str(value or "")).strip()
def _merge_review_output(
result: dict[str, Any],
enhancements: dict[str, dict[str, Any]],
new_items: list[dict[str, Any]],
*,
clean_text: str,
structured_clauses: list[dict[str, Any]],
) -> dict[str, Any]:
"""
合并 Dify 对已有发现的增强及其独立发现,并执行证据、去重和风险等级治理。
Args:
result: HXOPS 确定性结果。
enhancements: finding id 对应的解释增强。
new_items: Dify 独立发现的候选风险。
clean_text/structured_clauses: 用于验证 clause_id 与 evidence 是否真实存在。
Returns:
合并后的结果;证据不足项保留但标记 needs_review,便于采购人员识别不确定结论。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
for idx, clause in enumerate(clauses, start=1):
if not isinstance(clause, dict):
continue
item_id = str(clause.get("clause_no") or idx)
extra = enhancements.get(item_id)
if not extra:
continue
clause["llm_enabled"] = True
clause.update({k: v for k, v in extra.items() if v not in ("", None)})
if extra.get("llm_reason"):
clause["detail"] = extra["llm_reason"]
if extra.get("llm_suggestion"):
clause["suggestion"] = extra["llm_suggestion"]
if extra.get("llm_negotiation_text"):
clause["negotiation_text"] = extra["llm_negotiation_text"]
deterministic_level = str(clause.get("risk_level") or "ok").lower()
model_level = str(extra.get("llm_model_risk_level") or "").lower()
decision = str(extra.get("llm_decision") or "confirm")
evidence = str(extra.get("llm_evidence") or "").strip()
evidence_valid = bool(_normalize_evidence(evidence) and _normalize_evidence(evidence) in _normalize_evidence(clean_text))
confidence = extra.get("llm_confidence")
if decision == "reject" and evidence_valid and isinstance(confidence, float) and confidence >= 0.8:
clause["risk_level"] = "ok"
clause["change_type"] = "pass"
clause["validation_status"] = "confirmed"
clause["evidence"] = evidence
clause["detail"] = extra.get("llm_reason") or "原文证据表明该确定性风险未命中。"
elif decision == "uncertain":
clause["validation_status"] = "needs_review"
if evidence_valid:
clause["evidence"] = evidence
elif RISK_RANK.get(model_level, -1) > RISK_RANK.get(deterministic_level, 0):
clause["risk_level"] = model_level
clause_map = {
str(item.get("clause_id") or ""): item
for item in structured_clauses
if isinstance(item, dict) and item.get("clause_id")
}
clause_no_map = {
str(item.get("clause_no") or "").strip(): item
for item in structured_clauses
if isinstance(item, dict) and str(item.get("clause_no") or "").strip()
}
normalized_contract = _normalize_evidence(clean_text)
fingerprints = {
_normalize_evidence(
f"{item.get('clause_no') or ''}|{item.get('title') or ''}|{item.get('detail') or ''}"
)[:240]
for item in clauses
if isinstance(item, dict)
}
accepted = 0
needs_review = 0
for idx, raw in enumerate(new_items, start=1):
clause_id = str(raw.get("clause_id") or "").strip()
requested_clause_no = str(raw.get("clause_no") or "").strip()
linked_clause = clause_map.get(clause_id) or clause_no_map.get(requested_clause_no)
evidence = _clip(raw.get("evidence"), 1200)
evidence_key = _normalize_evidence(evidence)
evidence_valid = bool(evidence_key and evidence_key in normalized_contract)
clause_valid = bool(linked_clause)
title = _clip(raw.get("title") or "AI 新发现风险", 120)
reason = _clip(raw.get("professional_reason") or raw.get("legal_reason") or raw.get("reason"))
fingerprint = _normalize_evidence(
f"{raw.get('clause_no') or (linked_clause or {}).get('clause_no') or ''}|{title}|{reason}"
)[:240]
if not fingerprint or fingerprint in fingerprints:
continue
level = str(raw.get("risk_level") or raw.get("model_risk_level") or "medium").lower()
if level not in {"high", "medium", "low"}:
level = "medium"
confidence = _normalize_confidence(raw.get("confidence"))
validation_status = "confirmed" if clause_valid and evidence_valid else "needs_review"
item = {
"clause_no": str(
requested_clause_no or (linked_clause or {}).get("clause_no") or f"AI-{idx}"
),
"clause_id": clause_id or None,
"title": title,
"clause_category": str(
raw.get("clause_category") or raw.get("category") or (linked_clause or {}).get("category") or "other"
),
"change_type": "llm_scan",
"risk_level": level,
"detail": reason or "大模型识别到潜在合同风险。",
"risk_hint": reason,
"business_impact": _clip(raw.get("business_impact")),
"suggestion": _clip(raw.get("professional_suggestion") or raw.get("suggestion")),
"negotiation_text": _clip(raw.get("negotiation_text")),
"evidence": evidence,
"source": "llm",
"llm_enabled": True,
"llm_confidence": confidence,
"llm_reason": reason,
"llm_model_risk_level": level,
"validation_status": validation_status,
}
clauses.append(item)
fingerprints.add(fingerprint)
accepted += 1
if validation_status == "needs_review":
needs_review += 1
result["clauses_json"] = clauses
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_new_findings"] = {"accepted": accepted, "needs_review": needs_review}
result["summary_json"] = summary
return result
def _with_llm_meta(
result: dict[str, Any],
*,
enabled: bool,
status: str,
message: str,
provider: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""Attach LLM enhancement metadata to summary_json."""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": enabled,
"status": status,
"message": message,
"provider": provider,
"workflow_run_id": workflow_run_id,
}
result["summary_json"] = summary
return result
def _workflow_run_id(workflow_result: dict[str, Any] | None) -> str | None:
"""Read Dify workflow run id from gateway metadata."""
if not isinstance(workflow_result, dict):
return None
value = workflow_result.get("workflow_run_id") or workflow_result.get("id")
return str(value) if value else None
@@ -0,0 +1,381 @@
"""
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
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 _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,
) -> 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) or item.get("risk_level") == "ok":
continue
attempted += 1
anchor = locate_pdf_evidence(pdf_bytes, 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 = "",
) -> 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_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 []
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()
@@ -0,0 +1,346 @@
"""
backend/app/services/procurement_contract/preprocessing.py
用途:复用知识库 edkb_system 清洗能力,为单次合同审核生成 Markdown 和结构化条款产物。
依赖:knowledge_cleaning.edkb_adapter、file_assets、procurement_contract.analyze。
逻辑:合同 Worker 读取 FileAsset 字节 → 写入审查专属目录 → 清洗为 Markdown → 合同去噪与条款切分;
不创建 KbDocument,也不把一次性合同同步到企业正式 Dataset。
"""
from __future__ import annotations
import json
import mimetypes
import re
import shutil
from pathlib import Path
from typing import Any
import requests
from flask import current_app
from app.core.errors import ValidationError
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
from app.services.procurement_contract import analyze, artifact_archive
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
def _extract_pdf_page_texts(pdf_path: Path) -> list[str]:
"""
Extract searchable text per PDF page while preserving the source pagination.
Args:
pdf_path: Existing PDF path produced by upload or LibreOffice conversion.
Returns:
One string per physical page; blank strings are retained so page counts remain exact.
"""
import pypdfium2 as pdfium
document = pdfium.PdfDocument(str(pdf_path))
try:
pages: list[str] = []
for page_index in range(len(document)):
page = document[page_index]
text_page = page.get_textpage()
try:
pages.append(text_page.get_text_range() or "")
finally:
text_page.close()
page.close()
return pages
finally:
document.close()
def _ocr_marker_page_texts(raw_text: str) -> list[str]:
"""Recover page-aligned OCR text from existing `page-image-N` markers for scanned PDFs."""
matches = list(re.finditer(r"!\[page-image-(\d+)\]", raw_text or "", flags=re.I))
if not matches:
return []
pages: list[str] = []
for index, match in enumerate(matches):
end = matches[index + 1].start() if index + 1 < len(matches) else len(raw_text)
pages.append(raw_text[match.end() : end].strip())
return 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.
Word files are converted to PDF through the existing LibreOffice utility. If conversion or PDF
parsing fails, callers receive no pages and comparison-region logic safely falls back to full diff.
When MinerU supplies readable full-document OCR but a PDF has no native text layer, use one logical
page for body-boundary recognition. Logical pagination deliberately does not claim physical page counts.
"""
suffix = source_path.suffix.lower()
pdf_path = source_path
warning: str | None = None
if suffix in {".doc", ".docx"}:
soffice = find_soffice()
if not soffice:
return [], "LibreOffice is unavailable; comparison regions were not applied"
page_dir = target_dir / "page_source"
page_dir.mkdir(parents=True, exist_ok=True)
completed = convert_with_soffice(
soffice,
convert_to="pdf",
source_path=source_path,
out_dir=page_dir,
)
pdf_path = page_dir / f"{source_path.stem}.pdf"
if completed.returncode != 0 or not pdf_path.is_file():
shutil.rmtree(page_dir, ignore_errors=True)
return [], "LibreOffice conversion failed; comparison regions were not applied"
elif suffix != ".pdf":
return [], "File format has no reliable pagination; comparison regions were not applied"
try:
pages = _extract_pdf_page_texts(pdf_path)
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages and len(marker_pages) >= len(pages):
pages = marker_pages
elif not any(page.strip() for page in pages) and raw_text.strip():
# MinerU's current response exposes only md_content. Keep its readable OCR available for
# body anchors instead of rejecting the region config solely because the source PDF lacks text.
pages = [raw_text]
warning = "PDF native page text unavailable; used MinerU logical page for body boundaries"
return [analyze.clean_contract_text(page) for page in pages], warning
except Exception as exc: # noqa: BLE001 - page extraction is optional and has an explicit fallback
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages:
return [analyze.clean_contract_text(page) for page in marker_pages], str(exc)[:500]
return [], str(exc)[:500]
def _mineru_parse_pdf(source_path: Path, target_dir: Path) -> tuple[str, dict[str, Any]]:
"""
调用部署在内网的 MinerU API 解析 PDF,并保存完整返回供合同审核审计追溯。
核心逻辑:以同步 `/file_parse` 接口上传单份 PDF,读取对应文件的 `md_content`;MinerU
服务地址为空、接口失败或未返回 Markdown 时抛出异常,调用方再回退现有清洗器。
Args:
source_path: 审查目录内的 PDF 文件。
target_dir: 当前合同角色的清洗产物目录。
Returns:
MinerU Markdown 正文和不含绝对路径的解析元数据。
Raises:
RuntimeError: MinerU 未配置、请求失败或响应缺少当前文件的 Markdown。
"""
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
raise RuntimeError("MinerU API is not configured")
connect_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS") or 5), 1)
read_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS") or 300), 30)
backend = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_BACKEND") or "pipeline").strip() or "pipeline"
parse_method = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD") or "auto").strip() or "auto"
content_type = mimetypes.guess_type(source_path.name)[0] or "application/pdf"
payload = {
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
}
try:
with source_path.open("rb") as handle:
response = requests.post(
f"{api_url}/file_parse",
data=payload,
files=[("files", (source_path.name, handle, content_type))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (OSError, ValueError, requests.RequestException) as exc:
raise RuntimeError(f"MinerU parse failed: {exc}") from exc
if str(result.get("status") or "").lower() != "completed":
detail = str(result.get("error") or result.get("status") or "unknown status")
raise RuntimeError(f"MinerU parse did not complete: {detail}")
results = result.get("results")
if not isinstance(results, dict) or not results:
raise RuntimeError("MinerU response has no file results")
# API 以去扩展名文件名为 key;单文件请求直接取唯一结果,避免依赖服务端命名规则。
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
markdown = str((parsed or {}).get("md_content") or "").strip()
if not markdown:
raise RuntimeError("MinerU response has no md_content")
(target_dir / "mineru_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2),
encoding="utf-8",
)
(target_dir / "mineru_document.md").write_text(markdown, encoding="utf-8")
return markdown, {
"provider": "mineru",
"backend": str(result.get("backend") or backend),
"version": str(result.get("version") or ""),
"parse_method": parse_method,
"result_artifact": "mineru_result.json",
}
def _review_root(review_no: str) -> Path:
"""解析并创建审查专属存储目录,拒绝把审查编号解释为路径。"""
safe_no = re.sub(r"[^A-Za-z0-9_-]+", "_", str(review_no or "").strip())[:80]
if not safe_no:
raise ValidationError("review_no is required")
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve() / safe_no
root.mkdir(parents=True, exist_ok=True)
return root
def _safe_source_name(filename: str, role: str) -> str:
"""生成保留扩展名的本地文件名,避免原文件名穿越审查目录。"""
suffix = Path(str(filename or "")).suffix.lower()[:16]
return f"{role}{suffix or '.bin'}"
def clean_review_asset(
*,
review_no: str,
role: str,
asset: FileAsset,
) -> dict[str, Any]:
"""
清洗一份合同或模板并产出合同审核结构。
核心逻辑:优先使用知识库 edkb_system 生成 Markdown;失败时回退到合同域本地抽取器,
随后执行合同专用去噪和条款切分,并保存 `document.md` / `clauses.json`。
Args:
review_no: 合同审查编号,只用于隔离产物目录。
role: 仅允许 contract 或 template。
asset: 已校验可读的 FileAsset ORM 对象。
Returns:
包含 clean_text、clauses 和不暴露绝对路径的 extraction_meta。
Raises:
ValidationError: 文件无法产生可审核正文。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
review_root = _review_root(review_no)
source_dir = review_root / "source"
target_dir = review_root / "cleaned" / normalized_role
source_dir.mkdir(parents=True, exist_ok=True)
target_dir.mkdir(parents=True, exist_ok=True)
data = read_asset_bytes(asset)
source_path = source_dir / _safe_source_name(asset.original_filename, normalized_role)
source_path.write_bytes(data)
mode = "edkb_system"
warning: str | None = None
mineru_meta: dict[str, Any] = {}
# [STEP 1] PDF 优先交给 MinerU 恢复版面、表格与阅读顺序;未配置或服务异常时保持旧链路可用。
if source_path.suffix.lower() == ".pdf" and current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL"):
try:
raw_text, mineru_meta = _mineru_parse_pdf(source_path, target_dir)
mode = "mineru"
except Exception as exc: # noqa: BLE001 - MinerU is an optional parser with explicit fallback
warning = str(exc)[:500]
if mode != "mineru":
try:
clean_result = build_clean_result(source_path, target_dir)
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)
except Exception as exc: # noqa: BLE001 - local extractor is the intended degradation path
warning = f"{warning}; {exc}".strip("; ")[:500]
mode = "local_fallback"
raw_text = analyze.extract_text_from_bytes(asset.original_filename, data)
# 保留清洗器原始分页/OCR文本供扫描 PDF 批注定位;审核正文会继续移除页码和图片标记。
(target_dir / "ocr_document.md").write_text(raw_text, encoding="utf-8")
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError("合同正文无法解析,请上传 Word 或可检索文本的 PDF")
clauses = analyze.structure_contract_clauses(clean_text)
if not clauses:
raise ValidationError("合同正文未识别到可审核条款")
document_path = target_dir / "document.md"
clauses_path = target_dir / "clauses.json"
document_path.write_text(clean_text, encoding="utf-8")
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)
return {
"clean_text": clean_text,
"clauses": clauses,
"page_texts": page_texts,
"page_count": len(page_texts),
"extraction_meta": {
"role": normalized_role,
"mode": mode,
"character_count": len(clean_text),
"clause_count": len(clauses),
"quality": quality,
"warning": warning or page_warning or quality.get("warning"),
"document_artifact": f"cleaned/{normalized_role}/document.md",
"clauses_artifact": f"cleaned/{normalized_role}/clauses.json",
"mineru": mineru_meta or None,
},
}
def persist_review_result_artifact(review_no: str, result: dict[str, Any]) -> None:
"""
保存最终结构化结果副本,供问题排查和审计回溯。
Args:
review_no: 合同审查编号。
result: 已完成后端校验和合并的结果字典。
"""
result_dir = _review_root(review_no) / "result"
result_dir.mkdir(parents=True, exist_ok=True)
(result_dir / "merged_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2, default=str),
encoding="utf-8",
)
def read_review_clean_text(review_no: str, *, role: str = "contract") -> str:
"""
读取审查任务已保存的清洗正文,供扫描 PDF 下载时按 OCR 分页补充批注定位。
Args:
review_no: 合同审查编号。
role: 仅允许 contract 或 template;下载标注合同默认读取 contract。
Returns:
清洗后的 Markdown 正文;产物不存在时返回空字符串。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
role_root = _review_root(review_no) / "cleaned" / normalized_role
ocr_document_path = role_root / "ocr_document.md"
if not ocr_document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/ocr_document.md",
)
if ocr_document_path.is_file():
return ocr_document_path.read_text(encoding="utf-8", errors="ignore")
document_path = role_root / "document.md"
if not document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/document.md",
)
if not document_path.is_file():
return ""
return document_path.read_text(encoding="utf-8", errors="ignore")
@@ -0,0 +1,795 @@
"""
backend/app/services/procurement_contract/review_service.py
用途:创建、异步执行、查询与导出采购合同审查记录。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation。
逻辑:Chat/Admin API 创建 queued 审查 → Worker 清洗 → 改稿 Diff/五灯或单份五问 →
(仅 solo 可选)LLM 增强 → 页锚落库。比对模式默认不做 Dify 全面扫描。
"""
from __future__ import annotations
import secrets
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import or_
from app import db
from app.core.config.settings import Config
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, FileAsset, Job, User
from app.services.file_assets.service import mark_asset_referenced, read_asset_bytes
from app.services.procurement_contract import (
analyze,
artifact_archive,
comparison_regions,
llm_enhancer,
pdf_annotation,
preprocessing,
rule_service,
template_service,
)
DEFAULT_CONTRACT_TYPE = "general_procurement"
def _gen_review_no() -> str:
"""Generate review number like CR-YYYYMMDD-AB12."""
day = datetime.utcnow().strftime("%Y%m%d")
return f"CR-{day}-{secrets.token_hex(2).upper()}"
def serialize_review(row: ContractReview, *, include_detail: bool = False) -> dict[str, Any]:
"""Convert a review ORM row into API response data."""
user = db.session.get(User, row.user_id) if row.user_id else None
data: dict[str, Any] = {
"id": row.id,
"review_no": row.review_no,
"review_mode": row.review_mode,
"status": row.status,
"contract_file_name": row.contract_file_name,
"supplier_name": row.supplier_name,
"contract_no": row.contract_no,
"contract_type": row.contract_type,
"template_id": row.template_id,
"template_source": row.template_source,
"template_name": row.template_name,
"total_change_count": row.total_change_count,
"high_risk_count": row.high_risk_count,
"medium_risk_count": row.medium_risk_count,
"low_risk_count": row.low_risk_count,
"user_id": row.user_id,
"user_name": (user.real_name or user.username) if user else None,
"error_message": row.error_message,
"started_at": utc_iso(row.started_at),
"finished_at": utc_iso(row.finished_at),
"created_at": utc_iso(row.created_at),
}
processing = row.summary_json.get("processing") if isinstance(row.summary_json, dict) else None
if isinstance(processing, dict):
data["progress"] = int(processing.get("progress") or 0)
data["processing_stage"] = processing.get("stage")
data["processing_message"] = processing.get("message")
else:
data["progress"] = 100 if row.status in {"success", "failed"} else 0
data["processing_stage"] = row.status
data["processing_message"] = None
if include_detail:
data["summary_json"] = row.summary_json
data["clauses_json"] = row.clauses_json
data["report_text"] = row.report_text
data["contract_asset_id"] = row.contract_asset_id
data["template_asset_id"] = row.template_asset_id
data["agent_id"] = row.agent_id
data["chat_log_id"] = row.chat_log_id
return data
def _parse_date(value: str | None, *, end_of_day: bool = False) -> datetime | None:
"""Parse YYYY-MM-DD or ISO datetime filter values."""
raw = str(value or "").strip()
if not raw:
return None
try:
if len(raw) == 10:
dt = datetime.strptime(raw, "%Y-%m-%d")
return dt + timedelta(days=1) if end_of_day else dt
return datetime.fromisoformat(raw.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError as exc:
raise ValidationError("invalid date filter") from exc
def list_reviews(
*,
review_mode: str | None = None,
template_source: str | None = None,
status: str | None = None,
keyword: str | None = None,
user_id: int | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
risk_level: str | None = None,
date_from: str | None = None,
date_to: str | None = None,
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
"""List review history with filters used by admin and chat pages."""
q = db.session.query(ContractReview)
if review_mode:
q = q.filter(ContractReview.review_mode == review_mode)
if template_source:
q = q.filter(ContractReview.template_source == template_source)
if status:
q = q.filter(ContractReview.status == status)
if user_id is not None:
q = q.filter(ContractReview.user_id == user_id)
if contract_type:
q = q.filter(ContractReview.contract_type == contract_type)
if supplier_name:
q = q.filter(ContractReview.supplier_name.ilike(f"%{supplier_name.strip()}%"))
if risk_level == "high":
q = q.filter(ContractReview.high_risk_count > 0)
elif risk_level == "medium":
q = q.filter(ContractReview.high_risk_count == 0, ContractReview.medium_risk_count > 0)
elif risk_level == "low":
q = q.filter(
ContractReview.high_risk_count == 0,
ContractReview.medium_risk_count == 0,
ContractReview.low_risk_count > 0,
)
start = _parse_date(date_from)
end = _parse_date(date_to, end_of_day=True)
if start:
q = q.filter(ContractReview.created_at >= start)
if end:
q = q.filter(ContractReview.created_at < end)
if keyword:
like = f"%{keyword.strip()}%"
q = q.filter(
or_(
ContractReview.review_no.ilike(like),
ContractReview.contract_file_name.ilike(like),
ContractReview.template_name.ilike(like),
ContractReview.supplier_name.ilike(like),
ContractReview.contract_no.ilike(like),
)
)
total = q.count()
rows = (
q.order_by(ContractReview.created_at.desc())
.offset(max(0, int(offset or 0)))
.limit(min(max(int(limit or 100), 1), 200))
.all()
)
return {"total": total, "items": [serialize_review(r) for r in rows]}
def _load_review_row(*, review_id: int | None = None, review_no: str | None = None) -> ContractReview:
"""Load a review row by id or review_no."""
row = None
if review_id is not None:
row = db.session.get(ContractReview, review_id)
elif review_no:
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
raise NotFoundError("review not found")
return row
def get_review(review_id: int | None = None, review_no: str | None = None) -> dict[str, Any]:
"""Get review details by id or review_no."""
return serialize_review(_load_review_row(review_id=review_id, review_no=review_no), include_detail=True)
def get_review_for_owner(*, review_no: str, user_id: int) -> dict[str, Any]:
"""
Get a user's review, recovering a stale background job before serializing it.
A browser reload must not leave a card permanently at its last persisted progress when the
contract worker has exited mid-task. Only an already-stale running job is recovered here;
normal task claiming remains the worker's responsibility.
"""
row = _load_review_row(review_no=review_no)
if row.user_id != user_id:
raise ForbiddenError("not your review")
_recover_stale_review_if_needed(row)
db.session.refresh(row)
return serialize_review(row, include_detail=True)
def _recover_stale_review_if_needed(row: ContractReview) -> None:
"""Recover timed-out contract jobs when a user polls a still-running review card."""
if row.status != "running" or not row.started_at:
return
timeout_seconds = max(int(getattr(Config, "PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600) or 600), 60)
if row.started_at >= datetime.utcnow() - timedelta(seconds=timeout_seconds):
return
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=timeout_seconds,
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
def read_review_report_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""
读取纯文本审查报告字节。
核心逻辑:正文前拼接审查编号、业务合同编号与供应商(乙方/卖方)。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
body = row.report_text or ""
if not body and isinstance(row.summary_json, dict):
body = str(row.summary_json.get("headline") or "")
header = "\n".join(
[
f"审查编号:{row.review_no}",
f"待审合同:{row.contract_file_name}",
f"合同编号:{row.contract_no or '-'}",
f"供应商(乙方/卖方):{row.supplier_name or '-'}",
"",
body,
]
)
return f"{row.review_no}_report.txt", header.encode("utf-8")
def read_review_report_docx_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes, str]:
"""
Create a docx report when python-docx is available.
Returns filename, bytes and mimetype; falls back to plain text without failing export.
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
try:
import io
from docx import Document
doc = Document()
doc.add_heading("合同差异对比报告" if row.review_mode == "compare" else "采购合同风险审核报告", level=1)
doc.add_paragraph(f"审查编号:{row.review_no}")
doc.add_paragraph(f"待审合同:{row.contract_file_name}")
doc.add_paragraph(f"合同编号:{row.contract_no or '-'}")
doc.add_paragraph(f"供应商(乙方/卖方):{row.supplier_name or '-'}")
doc.add_paragraph(f"审查模式:{row.review_mode}")
if row.review_mode == "compare":
doc.add_paragraph(
f"差异统计:共 {row.total_change_count} 项;风险参考:高 {row.high_risk_count} / "
f"中 {row.medium_risk_count} / 低 {row.low_risk_count}"
)
else:
doc.add_paragraph(f"风险统计:高 {row.high_risk_count} / 中 {row.medium_risk_count} / 低 {row.low_risk_count}")
doc.add_paragraph("说明:本报告为采购风险提示,不作为法律意见。")
doc.add_paragraph(row.report_text or "")
buffer = io.BytesIO()
doc.save(buffer)
return (
f"{row.review_no}_report.docx",
buffer.getvalue(),
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
)
except Exception:
name, data = read_review_report_bytes(review_id=review_id, review_no=review_no)
return name, data, "text/plain; charset=utf-8"
def read_review_contract_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read original contract bytes for a review."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
return asset.original_filename or row.contract_file_name or "contract.bin", read_asset_bytes(asset)
def read_review_template_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read the comparison baseline file used for a review (legacy field name: template)."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.template_asset_id) if row.template_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("comparison baseline file not found")
return asset.original_filename or "original-contract.bin", read_asset_bytes(asset)
def read_review_annotated_contract_bytes(
*,
review_id: int | None = None,
review_no: str | None = None,
) -> tuple[str, bytes, str]:
"""
生成并读取带审核高亮批注的合同 PDF。
核心逻辑:文本型 PDF 使用 evidence_anchor 写入 Highlight;扫描 PDF 使用已保存 OCR 分页正文定位页面并写入批注意见。
原始 FileAsset 永不修改。没有任何可定位证据时仍返回原合同副本,避免下载入口报错。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
filename = asset.original_filename or row.contract_file_name or "contract.pdf"
if not filename.lower().endswith(".pdf"):
raise ValidationError("annotated contract is only available for PDF files")
clauses = row.clauses_json if isinstance(row.clauses_json, list) else []
data = pdf_annotation.build_annotated_pdf_bytes(
read_asset_bytes(asset),
clauses,
clean_text=preprocessing.read_review_clean_text(row.review_no),
)
stem = filename.rsplit(".", 1)[0]
return f"{stem}_{row.review_no}_annotated.pdf", data, "application/pdf"
def start_review(
*,
user_id: int,
review_mode: str,
contract_asset_id: int | None = None,
contract_asset_no: str | None = None,
original_contract_asset_id: int | None = None,
original_contract_asset_no: str | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
agent_id: int | None = None,
chat_log_id: int | None = None,
) -> dict[str, Any]:
"""
创建采购合同审核记录并投递异步任务。
核心逻辑:比对模式校验我方原合同和卖方回传合同,单份模式仅校验待审合同;随后同事务写入 queued 审查与通用 Job。
文件清洗、Dify 调用和报告生成均由 Worker 执行,避免 Web 请求超时。
"""
mode = (review_mode or "").strip()
if mode not in ("compare", "solo"):
raise ValidationError("review_mode must be compare or solo")
if mode == "compare" and not (original_contract_asset_id or original_contract_asset_no):
raise ValidationError("original_contract_asset_no is required for compare mode")
contract_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=contract_asset_id,
asset_no=contract_asset_no,
label="contract",
)
normalized_contract_type = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
template_source = "none"
template_name = None
template_asset_id = None
template_id = None
if mode == "compare":
original_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=original_contract_asset_id,
asset_no=original_contract_asset_no,
label="original contract",
)
template_source = "user_upload"
template_asset_id = original_asset.id
template_name = original_asset.original_filename
row = ContractReview(
review_no=_gen_review_no(),
agent_id=agent_id,
user_id=user_id,
chat_log_id=chat_log_id,
review_mode=mode,
status="queued",
contract_asset_id=contract_asset.id,
contract_file_name=contract_asset.original_filename,
supplier_name=(supplier_name or "").strip() or None,
contract_type=normalized_contract_type,
template_id=template_id,
template_source=template_source,
template_asset_id=template_asset_id,
template_name=template_name,
total_change_count=0,
high_risk_count=0,
medium_risk_count=0,
low_risk_count=0,
summary_json={
"mode": mode,
"processing": {"stage": "queued", "progress": 0, "message": "等待后台审核"},
"review_note": "本结果为采购风险提示,不作为法律意见。",
},
)
db.session.add(row)
db.session.flush()
mark_asset_referenced(contract_asset)
if template_source == "user_upload" and template_asset_id:
original_asset = db.session.get(FileAsset, template_asset_id)
if original_asset:
mark_asset_referenced(original_asset)
from app.jobs import enqueue
from app.jobs.types import JobType
enqueue(
JobType.PROCUREMENT_CONTRACT_REVIEW,
{"review_no": row.review_no},
domain="procurement_contract",
business_ref=row.review_no,
created_by_id=user_id,
max_attempts=2,
message="等待合同清洗与审核",
commit=False,
)
db.session.commit()
return serialize_review(row, include_detail=True)
def _resolve_asset_for_user(*, user_id: int, asset_id: int | None, asset_no: str | None, label: str) -> FileAsset:
"""Resolve an uploaded file asset and enforce ownership for asset_no path."""
asset: FileAsset | None = None
if asset_id:
asset = db.session.get(FileAsset, asset_id)
elif asset_no:
from app.services.file_assets.service import get_asset_for_user
asset = get_asset_for_user(asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError(f"{label} file asset not found")
if asset.upload_status != "ready":
raise ValidationError(f"{label} file asset is not ready")
return asset
def _set_processing(
row: ContractReview,
*,
stage: str,
progress: int,
message: str,
job_id: int | None = None,
) -> None:
"""
同步更新业务审核记录和通用 Job 的阶段进度。
Args:
row: 当前 ContractReview。
stage/progress/message: 前端轮询展示的稳定阶段协议。
job_id: 可选通用 Job 主键;Worker 调用时同时更新队列监控信息。
"""
summary = dict(row.summary_json or {})
summary["processing"] = {
"stage": stage,
"progress": max(0, min(100, int(progress))),
"message": message,
}
row.summary_json = summary
row.status = "running" if stage not in {"success", "failed"} else stage
if job_id:
job = db.session.get(Job, int(job_id))
if job:
job.progress = max(0, min(100, int(progress)))
job.message = message[:500]
db.session.commit()
def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str, Any]:
"""
在后台 Worker 中执行一份采购合同的完整审核。
核心逻辑:[STEP 1] 复用知识库清洗器;[STEP 2] 合同结构化;[STEP 3] Diff 与整份红线;
[STEP 4] Dify 全面法律扫描;[STEP 5] 后端重算、持久化和报告生成。
Args:
review_no: 已创建的审查编号。
job_id: 通用 Job 主键,用于同步进度。
Returns:
已落库的完整审核详情。
"""
row = _load_review_row(review_no=review_no)
row.started_at = row.started_at or datetime.utcnow()
row.finished_at = None
row.error_message = None
_set_processing(row, stage="extracting", progress=10, message="正在提取并清洗合同", job_id=job_id)
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="contract",
asset=contract_asset,
)
contract_text = str(contract_doc["clean_text"])
contract_clauses = list(contract_doc["clauses"])
party = analyze.extract_party_fields(contract_text)
if not row.supplier_name and party.get("supplier_name"):
row.supplier_name = str(party["supplier_name"])
if party.get("contract_no"):
row.contract_no = str(party["contract_no"])
_set_processing(row, stage="structuring", progress=30, message="正在识别合同条款结构", job_id=job_id)
rules = rule_service.get_enabled_rules(row.contract_type)
template_meta: dict[str, Any] | None = None
_set_processing(
row,
stage="deterministic_review",
progress=45,
message="正在执行模板比对与公司红线检查",
job_id=job_id,
)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
template_asset = db.session.get(FileAsset, row.template_asset_id)
if not template_asset:
raise ValidationError("original contract asset missing")
template_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="template",
asset=template_asset,
)
template_meta = dict(template_doc["extraction_meta"])
# [STEP 1] 比对模式只做改稿红线 + 五灯,不再叠加整份 solo 扫描(避免噪声淹没采购)。
original_text = str(template_doc["clean_text"])
returned_text = contract_text
comparison_scope: dict[str, Any] = {
"status": "fallback",
"template_id": None,
"template_name": None,
"warning": "No enabled default template comparison-region config was available",
}
metadata_comparison: dict[str, Any] = {}
attachment_comparison: dict[str, Any] = {"status": "unavailable"}
default_template = template_service.get_default_enabled_template()
if default_template and isinstance(default_template.comparison_region_config, dict):
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "Comparison-region anchors could not be recognized in both uploaded files",
})
try:
region_config = comparison_regions.validate_comparison_region_config(
default_template.comparison_region_config
)
original_diagnostic = comparison_regions.diagnose_partition(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_diagnostic = comparison_regions.diagnose_partition(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
comparison_scope["diagnostics"] = {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
}
original_partition = comparison_regions.partition_document(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_partition = comparison_regions.partition_document(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
if original_partition and returned_partition:
original_text = original_partition.body
returned_text = returned_partition.body
metadata_comparison = comparison_regions.build_metadata_comparison(
original_partition.metadata,
returned_partition.metadata,
)
attachment_comparison = comparison_regions.build_attachment_comparison(
original_partition.attachment_pages,
returned_partition.attachment_pages,
)
comparison_scope = {
"status": "applied",
"template_id": default_template.id,
"template_name": default_template.name,
"body_start_found": True,
"body_end_found": True,
"signature_excluded": True,
"attachment_policy": region_config["attachment_policy"],
"diagnostics": {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
},
"warning": None,
}
except ValidationError as exc:
comparison_scope["warning"] = exc.message
elif default_template:
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "The enabled default template has no comparison-region config",
})
if comparison_scope["status"] == "fallback":
current_app.logger.warning(
"[contract-review] comparison region fallback review_no=%s template_id=%s "
"warning=%s diagnostics=%s",
row.review_no,
comparison_scope.get("template_id"),
comparison_scope.get("warning"),
comparison_scope.get("diagnostics"),
)
# [STEP 1] Uploaded original remains the baseline; Admin contributes only reusable region rules.
result = analyze.analyze_compare(original_text, returned_text, rules=rules)
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
region_summary["attachment_comparison"] = attachment_comparison
result["summary_json"] = region_summary
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["extraction"] = {
"contract": contract_doc["extraction_meta"],
"template": template_meta,
}
summary["structured_clause_count"] = len(contract_clauses)
result["summary_json"] = summary
# [STEP 2] 比对模式关闭 Dify 全面审核;仅单份卖方合同可选 LLM 解释增强。
if row.review_mode == "solo":
_set_processing(row, stage="llm_reviewing", progress=60, message="正在补充 AI 风险说明", job_id=job_id)
result = llm_enhancer.enhance_review_result(
result,
review_no=row.review_no,
review_mode=row.review_mode,
contract_type=row.contract_type,
template_name=row.template_name,
clean_text=contract_text,
structured_clauses=contract_clauses,
)
else:
_set_processing(row, stage="validating", progress=70, message="正在整理比对结果", job_id=job_id)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": False,
"status": "skipped",
"message": "compare mode uses redline + focus lights only",
}
result["summary_json"] = summary
_set_processing(row, stage="validating", progress=88, message="正在校验并合并审核结果", job_id=job_id)
try:
result = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename=contract_asset.original_filename or row.contract_file_name,
pdf_bytes=read_asset_bytes(contract_asset),
)
except Exception as exc: # noqa: BLE001 - evidence anchoring is a non-blocking report enhancement
current_app.logger.warning(
"[contract-review] evidence anchoring failed review_no=%s err=%s",
row.review_no,
exc,
)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["evidence_anchoring"] = {"status": "failed", "anchored": 0, "unanchored": 0}
result["summary_json"] = summary
result = analyze.rebuild_result(result)
summary = result["summary_json"]
summary["processing"] = {"stage": "success", "progress": 100, "message": "审核完成"}
result["summary_json"] = summary
row.status = "success"
row.total_change_count = int(result.get("total_change_count") or 0)
row.high_risk_count = int(result.get("high_risk_count") or 0)
row.medium_risk_count = int(result.get("medium_risk_count") or 0)
row.low_risk_count = int(result.get("low_risk_count") or 0)
row.summary_json = result["summary_json"]
row.clauses_json = result["clauses_json"]
row.report_text = result["report_text"]
row.error_message = None
row.finished_at = datetime.utcnow()
db.session.commit()
try:
preprocessing.persist_review_result_artifact(row.review_no, result)
except Exception as exc: # noqa: BLE001 - audit copy failure must not invalidate persisted review
current_app.logger.warning("[contract-review] result artifact failed review_no=%s err=%s", row.review_no, exc)
try:
archive_meta = artifact_archive.archive_review_artifacts(row.review_no)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = archive_meta
row.summary_json = summary
db.session.commit()
if archive_meta.get("status") == "archived":
artifact_archive.cleanup_local_review_artifacts(row.review_no)
except Exception as exc: # noqa: BLE001 - MinIO archiving must not turn a completed review into failure
current_app.logger.warning("[contract-review] artifact archive failed review_no=%s err=%s", row.review_no, exc)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = {"status": "failed", "message": str(exc)[:500]}
row.summary_json = summary
db.session.commit()
return serialize_review(row, include_detail=True)
def mark_review_failed(*, review_no: str, error: str) -> None:
"""在后台任务最终失败时将审核记录收口为 failed,避免前端永久轮询。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核失败"}
row.summary_json = summary
row.status = "failed"
row.error_message = str(error or "contract review failed")[:2000]
row.finished_at = datetime.utcnow()
db.session.commit()
def mark_review_retrying(*, review_no: str, error: str) -> None:
"""普通执行异常仍可重试时将业务审核状态恢复为 queued。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "queued", "progress": 0, "message": "审核失败,等待后台重试"}
row.summary_json = summary
row.status = "queued"
row.error_message = str(error or "contract review retrying")[:2000]
row.finished_at = None
db.session.commit()
def sync_review_after_job_recovery(job: Job) -> None:
"""
通用队列回收超时合同任务时同步业务审核状态。
核心逻辑:任务仍可重试时把进度重置为 queued;重试耗尽时收口 failed。
本函数由 recover_stale_jobs 在同一事务内调用,不自行 commit。
Args:
job: 已被队列更新为 queued 或 failed 的通用 Job。
"""
review_no = str(job.business_ref or (job.payload_json or {}).get("review_no") or "").strip()
if not review_no:
return
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
return
summary = dict(row.summary_json or {})
if job.status == "queued":
summary["processing"] = {"stage": "queued", "progress": 0, "message": "任务超时,等待后台重试"}
row.status = "queued"
row.finished_at = None
elif job.status == "failed":
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核任务执行超时"}
row.status = "failed"
row.error_message = str(job.error_message or "合同审核任务执行超时")[:2000]
row.finished_at = datetime.utcnow()
row.summary_json = summary
def _run_analysis(row: ContractReview) -> dict[str, Any]:
"""
兼容旧测试和内部调用的同步确定性分析入口。
核心逻辑:提取文本 → 解析供应商/合同编号 → Diff 或红线规则 → 把当事人字段写入报告头。
"""
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_bytes = read_asset_bytes(contract_asset)
contract_text = analyze.extract_text_from_bytes(contract_asset.original_filename, contract_bytes)
party = analyze.extract_party_fields(contract_text)
rules = rule_service.get_enabled_rules(row.contract_type)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
tpl_asset = db.session.get(FileAsset, row.template_asset_id)
if not tpl_asset:
raise ValidationError("original contract asset missing")
tpl_bytes = read_asset_bytes(tpl_asset)
tpl_text = analyze.extract_text_from_bytes(tpl_asset.original_filename, tpl_bytes)
result = analyze.analyze_compare(tpl_text, contract_text, rules=rules)
result["extracted_supplier_name"] = party.get("supplier_name")
result["extracted_contract_no"] = party.get("contract_no")
return result
@@ -0,0 +1,289 @@
"""
backend/app/services/procurement_contract/rule_service.py
Purpose: Manage procurement contract risk rules used by compare and solo review.
Dependencies: ContractRiskRule model, SQLAlchemy session, unified AppError classes.
Flow: Admin CRUD persists configurable red-line rules; review_service loads enabled rules for analysis.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from uuid import uuid4
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractRiskRule
DEFAULT_CONTRACT_TYPE = "general_procurement"
VALID_RISK_LEVELS = {"high", "medium", "low"}
VALID_STATUS = {"enabled", "disabled"}
VALID_TRIGGER_TYPES = {"keyword_missing", "keyword_present"}
# Keep categories stable because they drive result grouping, de-duplication and policy replacement.
VALID_CLAUSE_CATEGORIES = {
"payment",
"delivery",
"acceptance",
"warranty",
"liability",
"jurisdiction",
"dispute",
"ip",
"other",
}
BUILTIN_RULE_CODES = {
"payment_acceptance_required",
"acceptance_process_required",
"liability_required",
"jurisdiction_required",
"warranty_required",
}
def serialize_rule(row: ContractRiskRule) -> dict[str, Any]:
"""Convert a risk rule ORM row into API response data."""
return {
"id": row.id,
"code": row.code,
"rule_kind": "builtin" if row.code in BUILTIN_RULE_CODES else "custom",
"contract_type": row.contract_type,
"clause_category": row.clause_category,
"title": row.title,
"keywords": row.keywords or [],
"trigger_type": row.trigger_type,
"risk_level": row.risk_level,
"risk_hint": row.risk_hint,
"suggestion": row.suggestion,
"negotiation_text": row.negotiation_text,
"status": row.status,
"sort_order": row.sort_order,
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def _normalize_keywords(raw: Any) -> list[str]:
"""Normalize JSON/list/string keywords into a unique non-empty string list."""
if isinstance(raw, str):
items = [p.strip() for p in raw.replace(",", ",").split(",")]
elif isinstance(raw, list):
items = [str(p).strip() for p in raw]
else:
items = []
seen: set[str] = set()
result: list[str] = []
for item in items:
if item and item not in seen:
seen.add(item)
result.append(item)
return result
def _validate_clause_category(category: str) -> str:
"""
Validate and normalize a rule category used by the contract analyzer.
Args:
category: Stable category code selected in the admin form; free-form labels are not supported.
Returns:
A validated category code.
Raises:
ValidationError: If the category cannot participate in result grouping safely.
"""
normalized = category.strip().lower()
if normalized not in VALID_CLAUSE_CATEGORIES:
raise ValidationError("invalid clause_category")
return normalized
def _generate_custom_rule_code(category: str) -> str:
"""
Generate an opaque code for a custom keyword rule.
The code is an internal identifier only. Generating it server-side prevents administrators from
accidentally using a built-in code that carries compound business logic.
Args:
category: Validated clause category used to make the generated code traceable.
Returns:
Globally unique custom rule code.
"""
return f"custom_{category}_{uuid4().hex[:12]}"
def list_rules(
*,
contract_type: str | None = None,
status: str | None = None,
clause_category: str | None = None,
) -> list[dict[str, Any]]:
"""List risk rules with optional filters."""
q = db.session.query(ContractRiskRule)
if contract_type:
q = q.filter(ContractRiskRule.contract_type == contract_type)
if status:
q = q.filter(ContractRiskRule.status == status)
if clause_category:
q = q.filter(ContractRiskRule.clause_category == clause_category)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def get_enabled_rules(contract_type: str | None = None) -> list[dict[str, Any]]:
"""
Load enabled rules for analysis.
Rules for the requested contract type are used first; general procurement rules are included as fallback.
"""
normalized = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
q = db.session.query(ContractRiskRule).filter(ContractRiskRule.status == "enabled")
if normalized != DEFAULT_CONTRACT_TYPE:
q = q.filter(ContractRiskRule.contract_type.in_([normalized, DEFAULT_CONTRACT_TYPE]))
else:
q = q.filter(ContractRiskRule.contract_type == DEFAULT_CONTRACT_TYPE)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def create_rule(*, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Create a custom keyword-based contract risk rule.
Built-in codes are reserved for compound procurement checks. Custom rules receive an internal
generated code so their keywords cannot accidentally change a built-in rule's semantics.
Args:
user_id: Administrator creating the rule.
data: Rule display fields, category, keywords and trigger configuration; code is optional.
Returns:
Serialized newly created rule.
Raises:
ValidationError: If category, keywords or enum fields are invalid, or a built-in code is supplied.
"""
code = str(data.get("code") or "").strip()
title = str(data.get("title") or "").strip()
category = _validate_clause_category(str(data.get("clause_category") or ""))
risk_level = str(data.get("risk_level") or "").strip()
risk_hint = str(data.get("risk_hint") or "").strip()
suggestion = str(data.get("suggestion") or "").strip()
keywords = _normalize_keywords(data.get("keywords"))
trigger_type = str(data.get("trigger_type") or "keyword_missing").strip()
status = str(data.get("status") or "enabled").strip()
if not title:
raise ValidationError("title is required")
if not keywords:
raise ValidationError("keywords are required")
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
if status not in VALID_STATUS:
raise ValidationError("invalid status")
if code:
if code in BUILTIN_RULE_CODES:
raise ValidationError("built-in rule code is reserved")
raise ValidationError("custom rule code is generated by server")
code = _generate_custom_rule_code(category)
exists = db.session.query(ContractRiskRule).filter(ContractRiskRule.code == code).first()
if exists:
raise ValidationError("rule code already exists")
row = ContractRiskRule(
code=code,
contract_type=str(data.get("contract_type") or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE,
clause_category=category,
title=title,
keywords=keywords,
trigger_type=trigger_type,
risk_level=risk_level,
risk_hint=risk_hint,
suggestion=suggestion,
negotiation_text=(str(data.get("negotiation_text") or "").strip() or None),
status=status,
sort_order=int(data.get("sort_order") or 100),
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
db.session.commit()
return serialize_rule(row)
def update_rule(rule_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Update an existing risk rule without changing its detection semantics.
Built-in rules may keep editable display and risk guidance fields, but their category, keywords and
trigger remain fixed because those fields are coupled to compound analyzer logic.
Args:
rule_id: Existing rule primary key.
user_id: Administrator making the change.
data: Partial editable rule payload.
Returns:
Serialized updated rule.
Raises:
NotFoundError: If the rule does not exist.
ValidationError: If enum values are invalid or a built-in detection definition is changed.
"""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
if row.code in BUILTIN_RULE_CODES:
if "clause_category" in data and _validate_clause_category(str(data.get("clause_category") or "")) != row.clause_category:
raise ValidationError("built-in rule definition is read-only")
if "keywords" in data and _normalize_keywords(data.get("keywords")) != list(row.keywords or []):
raise ValidationError("built-in rule definition is read-only")
if "trigger_type" in data and str(data.get("trigger_type") or "").strip() != row.trigger_type:
raise ValidationError("built-in rule definition is read-only")
for key in ("contract_type", "clause_category", "title", "risk_hint", "suggestion", "negotiation_text"):
if key in data:
value = str(data.get(key) or "").strip()
if key != "negotiation_text" and not value:
raise ValidationError(f"{key} is required")
if key == "clause_category":
value = _validate_clause_category(value)
setattr(row, key, value or None)
if "keywords" in data:
keywords = _normalize_keywords(data.get("keywords"))
if not keywords:
raise ValidationError("keywords are required")
row.keywords = keywords
if "trigger_type" in data:
trigger_type = str(data.get("trigger_type") or "").strip()
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
row.trigger_type = trigger_type
if "risk_level" in data:
risk_level = str(data.get("risk_level") or "").strip()
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
row.risk_level = risk_level
if "status" in data:
status = str(data.get("status") or "").strip()
if status not in VALID_STATUS:
raise ValidationError("invalid status")
row.status = status
if "sort_order" in data:
row.sort_order = int(data.get("sort_order") or 100)
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_rule(row)
def delete_rule(rule_id: int) -> dict[str, Any]:
"""Delete a risk rule."""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
db.session.delete(row)
db.session.commit()
return {"deleted": True, "id": rule_id}
@@ -0,0 +1,293 @@
"""
backend/app/services/procurement_contract/template_service.py
用途:采购合同标准模板库 CRUD、设默认、列表。
依赖:models.ContractTemplate、file_assets、db、errors。
逻辑:Admin API 调用;Chat 下拉读 enabled 列表。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, ContractTemplate, FileAsset, User
from app.services.file_assets.service import (
get_asset_for_user,
mark_asset_referenced,
read_asset_bytes,
release_asset_reference,
)
from app.services.procurement_contract import analyze
from app.services.procurement_contract.comparison_regions import (
preview_anchor_recognition,
validate_comparison_region_config,
)
def serialize_template(row: ContractTemplate) -> dict[str, Any]:
"""ORM → API dict。"""
return {
"id": row.id,
"name": row.name,
"version": row.version,
"file_name": row.file_name,
"file_asset_id": row.file_asset_id,
"contract_type": row.contract_type,
"applicable_scope": row.applicable_scope,
"change_note": row.change_note,
"comparison_region_config": row.comparison_region_config,
"status": row.status,
"is_default": bool(row.is_default),
"remark": row.remark,
"created_by": row.created_by,
"updated_by": row.updated_by,
"updated_by_name": _user_name(row.updated_by),
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def list_templates(*, status: str | None = None) -> list[dict[str, Any]]:
"""列出模板;可按 status 过滤。"""
q = db.session.query(ContractTemplate)
if status:
q = q.filter(ContractTemplate.status == status)
rows = q.order_by(ContractTemplate.is_default.desc(), ContractTemplate.updated_at.desc()).all()
return [serialize_template(r) for r in rows]
def _user_name(user_id: int | None) -> str | None:
"""Resolve a user's display name for template metadata."""
if not user_id:
return None
user = db.session.get(User, user_id)
if not user:
return None
return user.real_name or user.username
def list_enabled_for_chat() -> list[dict[str, Any]]:
"""会话下拉:仅启用中的模板。"""
return list_templates(status="enabled")
def get_default_enabled_template() -> ContractTemplate | None:
"""Return the single enabled default template whose config controls compare-region partitioning."""
return (
db.session.query(ContractTemplate)
.filter(
ContractTemplate.status == "enabled",
ContractTemplate.is_default.is_(True),
)
.order_by(ContractTemplate.updated_at.desc())
.first()
)
def create_template(
*,
user_id: int,
name: str,
version: str,
file_asset_id: int | None = None,
file_asset_no: str | None = None,
remark: str | None = None,
is_default: bool = False,
status: str = "enabled",
contract_type: str = "general_procurement",
applicable_scope: str | None = None,
change_note: str | None = None,
comparison_region_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
创建模板并可选设为默认。
Raises:
ValidationError: 参数非法或资产不可用。
"""
name = (name or "").strip()
version = (version or "").strip()
if not name or not version:
raise ValidationError("name and version are required")
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
asset: FileAsset | None = None
if file_asset_id:
asset = db.session.get(FileAsset, file_asset_id)
elif file_asset_no:
asset = get_asset_for_user(file_asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError("file asset not found")
exists = (
db.session.query(ContractTemplate)
.filter(ContractTemplate.name == name, ContractTemplate.version == version)
.first()
)
if exists:
raise ValidationError("template name+version already exists")
if is_default and status == "enabled":
_clear_defaults()
row = ContractTemplate(
name=name,
version=version,
file_asset_id=asset.id,
file_name=asset.original_filename,
contract_type=(contract_type or "general_procurement").strip() or "general_procurement",
applicable_scope=(applicable_scope or "").strip() or None,
change_note=(change_note or "").strip() or None,
comparison_region_config=(
validate_comparison_region_config(comparison_region_config)
if comparison_region_config is not None
else None
),
status=status,
is_default=bool(is_default and status == "enabled"),
remark=(remark or "").strip() or None,
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
mark_asset_referenced(asset)
db.session.commit()
return serialize_template(row)
def update_template(template_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""更新模板元数据 / 启停 / 设默认。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if "name" in data and data["name"] is not None:
row.name = str(data["name"]).strip() or row.name
if "version" in data and data["version"] is not None:
row.version = str(data["version"]).strip() or row.version
if "remark" in data:
row.remark = (str(data["remark"]).strip() or None) if data["remark"] is not None else None
if "contract_type" in data and data["contract_type"] is not None:
row.contract_type = str(data["contract_type"]).strip() or row.contract_type
if "applicable_scope" in data:
row.applicable_scope = (str(data["applicable_scope"]).strip() or None) if data["applicable_scope"] is not None else None
if "change_note" in data:
row.change_note = (str(data["change_note"]).strip() or None) if data["change_note"] is not None else None
if "comparison_region_config" in data:
row.comparison_region_config = (
validate_comparison_region_config(data["comparison_region_config"])
if data["comparison_region_config"] is not None
else None
)
if "status" in data and data["status"] is not None:
status = str(data["status"])
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
if status == "disabled" and row.is_default:
raise ValidationError("cannot disable default template; set another default first")
row.status = status
if data.get("is_default") is True:
if row.status != "enabled":
raise ValidationError("only enabled template can be default")
_clear_defaults()
row.is_default = True
elif data.get("is_default") is False:
row.is_default = False
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_template(row)
def delete_template(template_id: int) -> dict[str, Any]:
"""
Delete a non-default template that is not referenced by review history.
Historical reviews retain their template relationship for audit and file download,
so referenced templates must be disabled rather than deleted.
Raises:
NotFoundError: The template does not exist.
ValidationError: The template is currently the default template.
ConflictError: One or more review history records reference the template.
"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if row.is_default:
raise ValidationError("cannot delete default template")
review_count = (
db.session.query(ContractReview.id)
.filter(ContractReview.template_id == template_id)
.count()
)
if review_count:
raise ConflictError(
code="PROCUREMENT_CONTRACT.TEMPLATE_REFERENCED",
message="模板已被审查历史引用,无法删除;请停用该模板",
details={"template_id": template_id, "review_count": review_count},
)
asset = db.session.get(FileAsset, row.file_asset_id) if row.file_asset_id else None
db.session.delete(row)
if asset:
release_asset_reference(asset)
db.session.commit()
return {"deleted": True, "id": template_id}
def get_template_or_404(template_id: int) -> ContractTemplate:
"""取模板实体。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
return row
def read_template_bytes(template: ContractTemplate) -> tuple[str, bytes]:
"""读取模板文件字节。"""
if not template.file_asset_id:
raise ValidationError("template has no file")
asset = db.session.get(FileAsset, template.file_asset_id)
if not asset:
raise NotFoundError("template file not found")
return asset.original_filename, read_asset_bytes(asset)
def preview_comparison_regions(template_id: int, config: Any) -> dict[str, Any]:
"""
Preview configured anchors against the stored Admin template without changing review baselines.
Args:
template_id: Admin template primary key.
config: Unsaved comparison-region config from the edit dialog.
Returns:
Recognition status for body, signature, and attachment anchors.
"""
template = get_template_or_404(template_id)
normalized = validate_comparison_region_config(config)
filename, data = read_template_bytes(template)
raw_text = analyze.extract_text_from_bytes(filename, data)
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError(
"template text cannot be extracted for comparison-region preview",
code="PROCUREMENT_CONTRACT.COMPARISON_REGION_PREVIEW_FAILED",
)
result = preview_anchor_recognition(clean_text, normalized)
result["template_id"] = template.id
result["template_name"] = template.name
return result
def _clear_defaults() -> None:
"""清除所有默认标记。"""
db.session.query(ContractTemplate).filter(ContractTemplate.is_default.is_(True)).update(
{"is_default": False},
synchronize_session=False,
)