Files

353 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
edkb_system/skills/common.py
用途:edkb 清洗链路的通用工具(哈希、OCR 载荷整理、blocks→markdown)。
依赖:edkb_system.contracts.Block。
逻辑:controller / export / loader 等技能复用;手册类图文保留策略也集中在此判定。
"""
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import asdict
from pathlib import Path
from typing import Any
from edkb_system.contracts import Block
# 机械设计手册等图文密集文档:清洗时需保留图片并写入 OCR「图中文字」供问答检索。
_FIGURE_RICH_HANDBOOK_KEYWORDS = (
"手册",
"圖冊",
"图册",
"图集",
"圖集",
"机械设计",
"機械設計",
"handbook",
"design manual",
)
def is_figure_rich_handbook(name: str) -> bool:
"""
判断文件名是否像「图文密集手册/设计手册」。
核心逻辑:文件名命中手册/图册/机械设计等关键词时返回 True,供 loader/controller
放宽嵌图保留、跳过 policy_text 丢图、并强制 OCR。
Args:
name: 文件名或 stem(可含扩展名)。
Returns:
True 表示应按图文手册策略处理。
"""
text = str(name or "").strip()
if not text:
return False
lowered = text.lower()
for keyword in _FIGURE_RICH_HANDBOOK_KEYWORDS:
if keyword.isascii():
if keyword in lowered:
return True
elif keyword in text:
return True
return False
def hash_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def hash_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _page_image_structured_lines(payload: str) -> list[str]:
tokens = [x.strip() for x in payload.split(";") if x.strip()]
if not tokens:
return []
cert_context_hits = 0
cert_context_pat = re.compile(
r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|"
r"检测报告|測試報告|材质证明|物性表",
re.IGNORECASE,
)
for tok in tokens:
if cert_context_pat.search(tok):
cert_context_hits += 1
if cert_context_hits < 2:
return []
def _find(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
if rx.search(tok):
return tok
return ""
def _find_match(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
m = rx.search(tok)
if m:
return m.group(0)
return ""
def _find_after(anchor_pat: str, value_pat: str = r".+") -> str:
anchor_rx = re.compile(anchor_pat, re.IGNORECASE)
value_rx = re.compile(value_pat, re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not anchor_rx.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if value_rx.search(cand) and not anchor_rx.search(cand):
return cand
return ""
def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
seen: set[str] = set()
for key, value in values:
v = value.strip()
if not v:
continue
marker = f"{key}:{v.lower()}"
if marker in seen:
continue
seen.add(marker)
out.append((key, v))
return out
certificate_no = ""
cert_anchor = re.compile(
r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE
)
cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not cert_anchor.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if re.search(r"fax|tel|date", cand, re.IGNORECASE):
continue
if cert_value.fullmatch(cand):
certificate_no = cand
break
if certificate_no:
break
if not certificate_no:
certificate_no = _find_match(
r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b"
) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b")
issue_date = _find(
r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}"
)
spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+")
product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find(
r"HDG[-A-Z0-9 ]*COIL"
)
customer = _find(r"CORPORATION|COMPANY|STEEL")
order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find(
r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*"
)
weight = ""
for idx, tok in enumerate(tokens):
if tok.lower() == "kg" and idx > 0:
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1])
weight = (m.group(0) if m else tokens[idx - 1]) + " kg"
break
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE)
if m:
weight = m.group(0)
break
tensile: list[tuple[str, str]] = []
for idx, tok in enumerate(tokens):
if tok in {"降伏", "抗拉", "硬度"}:
for cand in tokens[idx + 1 : idx + 4]:
if re.fullmatch(r"\d+(?:\.\d+)?", cand):
tensile.append((tok, cand))
break
fields = _uniq(
[
("证书编号", certificate_no),
("日期", issue_date),
("客户", customer),
("产品", product),
("规格", spec),
("订单/追踪号", order_no),
("重量", weight),
]
)
if not fields and not tensile:
return []
lines = ["## 识别整理版", ""]
for key, value in fields:
lines.append(f"- {key}:{value}")
if tensile:
if fields:
lines.append("")
lines.append("### 关键数值")
lines.append("")
lines.append("| 项目 | 数值 |")
lines.append("| --- | --- |")
for key, value in _uniq(tensile):
lines.append(f"| {key} | {value} |")
lines.extend(["", "## 原始识别结果", ""])
return lines
def blocks_to_plain_markdown(
blocks: list[Block], *, keep_figure_ocr: bool = False
) -> str:
"""
将 block 列表转为纯文本 markdown(含可选图片与「图中文字」OCR)。
核心逻辑:按页排序输出 heading/paragraph/image;PDF 整页图在正文较多时默认抑制,
但 keep_figure_ocr=True(手册类)时始终保留 OCR 文案供问答检索。
Args:
blocks: 清洗后的内容块。
keep_figure_ocr: 为 True 时不因页内正文较多而丢弃 PDF 页图 OCR。
Returns:
markdown 字符串(末尾带换行)。
"""
def _is_meaningful_ocr_segment(text: str) -> bool:
token = re.sub(r"\s+", "", text or "")
if not token or re.fullmatch(r"[\W_]+", token):
return False
cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token))
alnum_count = len(re.findall(r"[A-Za-z0-9]", token))
if cjk_count >= 2:
return True
if cjk_count >= 1 and len(token) >= 2:
return True
if alnum_count >= 5:
return True
return len(token) >= 4
def _is_rich_ocr_payload(payload: str) -> bool:
token = re.sub(r"\s+", "", payload or "")
cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token))
alnum_count = len(re.findall(r"[A-Za-z0-9]", token))
return cjk_count >= 6 or alnum_count >= 12 or len(token) >= 20
def _ocr_payload(txt: str) -> str:
payload = txt
if payload.startswith("OCR_TEXT:"):
payload = payload[len("OCR_TEXT:") :].strip()
if not payload or payload == "<empty>":
return ""
payload = re.sub(r"(?m)^\s*-\s*", "", payload)
segments = [
x.strip()
for x in payload.splitlines()
if x.strip() and _is_meaningful_ocr_segment(x.strip())
]
return ";".join(segments)
ocr_by_image: dict[str, str] = {}
for b in blocks:
if b.type != "ocr_text" or not b.id.startswith("ocr-"):
continue
payload = _ocr_payload((b.text or "").strip())
if payload:
ocr_by_image[b.id[len("ocr-") :]] = payload
page_text_chars: dict[int, int] = {}
page_body_chars: dict[int, int] = {}
for b in blocks:
if b.type in {"ocr_text", "image"}:
continue
txt = (b.text or "").strip()
if not txt:
continue
page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt)
if b.type != "heading":
page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt)
lines: list[str] = []
image_idx = 0
for b in sorted(
[x for x in blocks if x.type != "ocr_text"],
key=lambda x: (x.page, x.cy(), x.cx()),
):
txt = (b.text or "").strip()
if not txt and b.type != "image":
continue
if b.type == "heading":
lines.append(f"## {txt}")
elif b.type == "image":
data_uri = b.meta.get("data_uri") if b.meta else None
is_pdf_page_image = bool(
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") == "pdf"
)
if is_pdf_page_image:
ocr_text = ocr_by_image.get(b.id)
# [STEP] 手册类保留页图 OCR;普通 PDF 仍避免与正文重复的整页图噪声
suppress_pdf_page_image = (
not keep_figure_ocr
and (
page_body_chars.get(b.page, 0) >= 80
or page_text_chars.get(b.page, 0) >= 120
)
and not _is_rich_ocr_payload(ocr_text or "")
)
if not suppress_pdf_page_image:
lines.append(f"![page-image-{b.page}]")
if ocr_text and not suppress_pdf_page_image:
lines.append(f"图中文字:{ocr_text}")
elif data_uri:
image_idx += 1
if b.meta and b.meta.get("page_image"):
lines.append(f"![page-image-{b.page}]({data_uri})")
else:
lines.append(f"![image-{image_idx}]({data_uri})")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
suppress_pptx_ocr = (
not keep_figure_ocr
and bool(b.meta and b.meta.get("page_image_source") == "pptx")
and (
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
)
if b.meta and b.meta.get("page_image"):
lines.extend(_page_image_structured_lines(ocr_text))
if not suppress_pptx_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append("![image]")
ocr_text = ocr_by_image.get(b.id)
if ocr_text and keep_figure_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append(txt)
return "\n\n".join(lines).strip() + "\n"
def dump_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
def block_to_dict(block: Block) -> dict[str, Any]:
return asdict(block)