347 lines
15 KiB
Python
347 lines
15 KiB
Python
"""
|
||
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")
|