fix(contract): 纯图片扫描 PDF 坐标高亮与 OCR 复核
This commit is contained in:
1 parent
ca312ea751
commit
ce1fd59f61
21 files changed
+1665
-54
No files matched your search
@@ -27,6 +27,10 @@ from app.services.procurement_contract import analyze, artifact_archive
|
||||
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
|
||||
|
||||
|
||||
OCR_LAYOUT_ARTIFACT = "ocr_layout.json"
|
||||
_OCR_RENDER_SCALE = 1.25
|
||||
|
||||
|
||||
def _extract_pdf_page_texts(pdf_path: Path) -> list[str]:
|
||||
"""
|
||||
Extract searchable text per PDF page while preserving the source pagination.
|
||||
@@ -67,6 +71,99 @@ def _ocr_marker_page_texts(raw_text: str) -> list[str]:
|
||||
return pages
|
||||
|
||||
|
||||
def _ocr_layout_from_edkb(raw_layout_path: Path | None) -> list[dict[str, Any]]:
|
||||
"""从 edkb 原始布局中提取 PDF 整页 OCR 行框,避免重复执行 OCR。"""
|
||||
if not raw_layout_path or not raw_layout_path.is_file():
|
||||
return []
|
||||
try:
|
||||
blocks = json.loads(raw_layout_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
pages: dict[int, list[dict[str, Any]]] = {}
|
||||
for block in blocks if isinstance(blocks, list) else []:
|
||||
if not isinstance(block, dict) or block.get("type") != "ocr_text":
|
||||
continue
|
||||
meta = block.get("meta") if isinstance(block.get("meta"), dict) else {}
|
||||
if not meta.get("page_image") or not isinstance(meta.get("ocr_lines"), list):
|
||||
continue
|
||||
page_no = int(block.get("page") or 0)
|
||||
if page_no <= 0:
|
||||
continue
|
||||
lines = [item for item in meta["ocr_lines"] if isinstance(item, dict) and item.get("polygon")]
|
||||
if lines:
|
||||
pages.setdefault(page_no, []).extend(lines)
|
||||
return [{"page_no": page_no, "lines": pages[page_no]} for page_no in sorted(pages)]
|
||||
|
||||
|
||||
def _ocr_layout_from_pdf(pdf_path: Path) -> list[dict[str, Any]]:
|
||||
"""
|
||||
为无文本层 PDF 生成行级 OCR 坐标;RapidOCR 不可用或单页失败时安全返回其余页面。
|
||||
|
||||
坐标保存为左上角原点的归一化多边形,下载标注时再按实际 PDF 页面尺寸换算。
|
||||
"""
|
||||
try:
|
||||
import numpy as np
|
||||
import pypdfium2 as pdfium
|
||||
|
||||
from edkb_system.skills.ocr import recognize_image_lines
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
try:
|
||||
document = pdfium.PdfDocument(str(pdf_path))
|
||||
except Exception:
|
||||
return []
|
||||
pages: list[dict[str, Any]] = []
|
||||
try:
|
||||
for page_index in range(len(document)):
|
||||
page = document[page_index]
|
||||
try:
|
||||
text_page = page.get_textpage()
|
||||
try:
|
||||
if (text_page.get_text_range() or "").strip():
|
||||
continue
|
||||
finally:
|
||||
text_page.close()
|
||||
bitmap = page.render(scale=_OCR_RENDER_SCALE)
|
||||
image = np.asarray(bitmap.to_pil().convert("RGB"))
|
||||
lines = recognize_image_lines(image, pdf_page_image=True)
|
||||
if lines:
|
||||
pages.append({"page_no": page_index + 1, "lines": lines})
|
||||
except Exception:
|
||||
continue
|
||||
finally:
|
||||
page.close()
|
||||
finally:
|
||||
document.close()
|
||||
return pages
|
||||
|
||||
|
||||
def _persist_pdf_ocr_layout(
|
||||
source_path: Path,
|
||||
target_dir: Path,
|
||||
*,
|
||||
raw_layout_path: Path | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""复用或生成纯图片 PDF 行坐标,并保存为合同审查可归档产物。"""
|
||||
if source_path.suffix.lower() != ".pdf":
|
||||
return None
|
||||
pages = _ocr_layout_from_edkb(raw_layout_path)
|
||||
source = "edkb"
|
||||
if not pages:
|
||||
pages = _ocr_layout_from_pdf(source_path)
|
||||
source = "rapidocr_fallback"
|
||||
if not pages:
|
||||
return None
|
||||
payload = {"version": 1, "coordinate_space": "normalized_top_left", "pages": pages}
|
||||
artifact_path = target_dir / OCR_LAYOUT_ARTIFACT
|
||||
artifact_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return {
|
||||
"source": source,
|
||||
"page_count": len(pages),
|
||||
"line_count": sum(len(page.get("lines") or []) for page in 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.
|
||||
@@ -242,6 +339,7 @@ def clean_review_asset(
|
||||
mode = "edkb_system"
|
||||
warning: str | None = None
|
||||
mineru_meta: dict[str, Any] = {}
|
||||
raw_layout_path: Path | None = None
|
||||
# [STEP 1] PDF 优先交给 MinerU 恢复版面、表格与阅读顺序;未配置或服务异常时保持旧链路可用。
|
||||
if source_path.suffix.lower() == ".pdf" and current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL"):
|
||||
try:
|
||||
@@ -256,6 +354,8 @@ def clean_review_asset(
|
||||
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)
|
||||
raw_layout_value = str(clean_result.get("raw_layout_path") or "").strip()
|
||||
raw_layout_path = Path(raw_layout_value) if raw_layout_value else None
|
||||
except Exception as exc: # noqa: BLE001 - local extractor is the intended degradation path
|
||||
warning = f"{warning}; {exc}".strip("; ")[:500]
|
||||
mode = "local_fallback"
|
||||
@@ -277,6 +377,9 @@ def clean_review_asset(
|
||||
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)
|
||||
ocr_layout = _persist_pdf_ocr_layout(source_path, target_dir, raw_layout_path=raw_layout_path)
|
||||
if ocr_layout:
|
||||
ocr_layout["artifact"] = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
|
||||
return {
|
||||
"clean_text": clean_text,
|
||||
"clauses": clauses,
|
||||
@@ -292,6 +395,7 @@ def clean_review_asset(
|
||||
"document_artifact": f"cleaned/{normalized_role}/document.md",
|
||||
"clauses_artifact": f"cleaned/{normalized_role}/clauses.json",
|
||||
"mineru": mineru_meta or None,
|
||||
"ocr_layout": ocr_layout,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -344,3 +448,21 @@ def read_review_clean_text(review_no: str, *, role: str = "contract") -> str:
|
||||
if not document_path.is_file():
|
||||
return ""
|
||||
return document_path.read_text(encoding="utf-8", errors="ignore")
|
||||
|
||||
|
||||
def read_review_ocr_layout(review_no: str, *, role: str = "contract") -> dict[str, Any]:
|
||||
"""读取或从 MinIO 恢复纯图片 PDF 的行级 OCR 坐标产物。"""
|
||||
normalized_role = str(role or "").strip().lower()
|
||||
if normalized_role not in {"contract", "template"}:
|
||||
raise ValidationError("role must be contract or template")
|
||||
relative_path = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
|
||||
layout_path = _review_root(review_no) / relative_path
|
||||
if not layout_path.is_file():
|
||||
artifact_archive.restore_review_artifact(review_no, relative_path)
|
||||
if not layout_path.is_file():
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(layout_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
Reference in new issue
Block a user