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 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]) -> str: 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 == "": 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) suppress_pdf_page_image = ( 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 = 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]") 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)