420 lines
12 KiB
Python
420 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
from edkb_system.config import RouterConfig
|
|
from edkb_system.contracts import Context, DocumentProfile
|
|
|
|
|
|
_DOC_KIND_STRATEGY = {
|
|
"flow_procedure": {
|
|
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
|
"disable": set(),
|
|
},
|
|
"policy_text": {
|
|
"enable": set(),
|
|
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
|
},
|
|
"tabular_record": {
|
|
"enable": set(),
|
|
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
|
},
|
|
"mixed": {
|
|
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
|
"disable": set(),
|
|
},
|
|
}
|
|
|
|
|
|
def _keyword_score(name: str, keywords: dict[str, float]) -> float:
|
|
score = 0.0
|
|
for k, w in keywords.items():
|
|
if k in name:
|
|
score += w
|
|
return score
|
|
|
|
|
|
def _score_text_keywords(text: str, keywords: dict[str, float]) -> float:
|
|
score = 0.0
|
|
for k, w in keywords.items():
|
|
if k in text:
|
|
score += w
|
|
return score
|
|
|
|
|
|
def _has_flow_evidence(stem: str, content: dict) -> bool:
|
|
name = stem.lower()
|
|
strong_name_hit = any(
|
|
k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"]
|
|
)
|
|
flow_hits = int(content.get("flow_hits", 0) or 0)
|
|
shape_hits = int(content.get("shape_hits", 0) or 0)
|
|
if flow_hits >= 6:
|
|
return True
|
|
if flow_hits >= 3 and shape_hits >= 1:
|
|
return True
|
|
return strong_name_hit
|
|
|
|
|
|
def _probe_docx_xml(path: Path) -> dict:
|
|
signals = {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
try:
|
|
with zipfile.ZipFile(path) as zf:
|
|
xml_parts = [
|
|
n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml")
|
|
]
|
|
xml_blob = ""
|
|
for n in xml_parts[:12]:
|
|
try:
|
|
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
|
|
except Exception:
|
|
continue
|
|
except Exception:
|
|
return signals
|
|
|
|
if not xml_blob:
|
|
return signals
|
|
|
|
text = xml_blob.lower()
|
|
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
|
|
signals["table_hits"] = text.count("<w:tbl")
|
|
signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata")
|
|
signals["shape_hits"] = (
|
|
text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp")
|
|
)
|
|
flow_kw = {
|
|
"流程": 0.3,
|
|
"流程图": 0.4,
|
|
"判定": 0.25,
|
|
"检验": 0.2,
|
|
"作业": 0.15,
|
|
}
|
|
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
|
|
return signals
|
|
|
|
|
|
def _probe_pdf(path: Path) -> dict:
|
|
signals = {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
try:
|
|
blob = path.read_bytes()[: 2 * 1024 * 1024]
|
|
except Exception:
|
|
return signals
|
|
|
|
text = blob.decode("latin-1", errors="ignore")
|
|
signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image")
|
|
text_ops = text.count(" BT") + text.count(" ET")
|
|
signals["has_text"] = text_ops >= 10
|
|
return signals
|
|
|
|
|
|
def _probe_pptx(path: Path) -> dict:
|
|
signals = {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
try:
|
|
with zipfile.ZipFile(path) as zf:
|
|
xml_parts = [
|
|
n
|
|
for n in zf.namelist()
|
|
if n.startswith("ppt/slides/") and n.endswith(".xml")
|
|
]
|
|
xml_blob = ""
|
|
for n in xml_parts[:20]:
|
|
try:
|
|
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
|
|
except Exception:
|
|
continue
|
|
except Exception:
|
|
return signals
|
|
|
|
if not xml_blob:
|
|
return signals
|
|
text = xml_blob.lower()
|
|
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
|
|
signals["table_hits"] = text.count("<a:tbl")
|
|
signals["image_hits"] = text.count("<a:blip")
|
|
signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp")
|
|
flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25}
|
|
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
|
|
return signals
|
|
|
|
|
|
def _probe_content(file_path: Path, ext: str) -> dict:
|
|
if ext == ".docx":
|
|
return _probe_docx_xml(file_path)
|
|
if ext == ".doc":
|
|
cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx"
|
|
if cache_docx.exists():
|
|
return _probe_docx_xml(cache_docx)
|
|
return {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
if ext == ".pdf":
|
|
return _probe_pdf(file_path)
|
|
if ext == ".pptx":
|
|
return _probe_pptx(file_path)
|
|
if ext == ".ppt":
|
|
cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx"
|
|
if cache_pptx.exists():
|
|
return _probe_pptx(cache_pptx)
|
|
return {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
if ext in {".xls", ".xlsx", ".csv"}:
|
|
return {
|
|
"has_text": True,
|
|
"table_hits": 8,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
return {
|
|
"has_text": False,
|
|
"table_hits": 0,
|
|
"flow_hits": 0,
|
|
"image_hits": 0,
|
|
"shape_hits": 0,
|
|
}
|
|
|
|
|
|
def _build_pipeline(
|
|
ext: str,
|
|
doc_kind: str,
|
|
scan_likelihood: float,
|
|
cfg: RouterConfig,
|
|
) -> list[str]:
|
|
strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"])
|
|
enable = set(strategy["enable"])
|
|
disable = set(strategy["disable"])
|
|
|
|
pipeline: list[str] = []
|
|
if ext in {".doc", ".docx"}:
|
|
pipeline.append("edkb-loader-docx")
|
|
if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable:
|
|
pipeline.append("edkb-doc-to-pdf")
|
|
elif ext == ".pdf":
|
|
pipeline.append("edkb-loader-pdf")
|
|
elif ext in {".ppt", ".pptx"}:
|
|
pipeline.append("edkb-loader-pptx")
|
|
elif ext in {".xls", ".xlsx"}:
|
|
pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"])
|
|
elif ext == ".csv":
|
|
pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"])
|
|
|
|
if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}:
|
|
if scan_likelihood >= cfg.scan_likelihood_threshold:
|
|
pipeline.append("edkb-ocr")
|
|
if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable:
|
|
pipeline.append("edkb-flow-reconstruct")
|
|
|
|
pipeline.extend(
|
|
[
|
|
"edkb-clean",
|
|
"edkb-chunk",
|
|
"edkb-quality-gate",
|
|
"edkb-export",
|
|
"edkb-postcheck",
|
|
]
|
|
)
|
|
return pipeline
|
|
|
|
|
|
def _decide_doc_kind(
|
|
stem: str, ext: str, content: dict
|
|
) -> tuple[str, float, float, float, list[str]]:
|
|
s = stem.lower()
|
|
reasons: list[str] = []
|
|
|
|
flow_pos = {
|
|
"流程图": 0.5,
|
|
"作业流程": 0.45,
|
|
"流程": 0.25,
|
|
"检验": 0.25,
|
|
"作业标准": 0.35,
|
|
"sop": 0.35,
|
|
"判定": 0.2,
|
|
"oqc": 0.2,
|
|
"iqc": 0.2,
|
|
}
|
|
flow_neg = {
|
|
"管理办法": 0.35,
|
|
"制度": 0.3,
|
|
"守则": 0.3,
|
|
"规定": 0.25,
|
|
"手册": 0.2,
|
|
}
|
|
table_pos = {
|
|
"台账": 0.45,
|
|
"清单": 0.35,
|
|
"记录": 0.25,
|
|
"表单": 0.4,
|
|
"excel": 0.4,
|
|
}
|
|
|
|
flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg)
|
|
table_raw = 0.15 + _keyword_score(s, table_pos)
|
|
|
|
if ext in {".xls", ".xlsx", ".csv"}:
|
|
table_raw += 0.55
|
|
if ext == ".pdf":
|
|
flow_raw += 0.05
|
|
if ext in {".ppt", ".pptx"}:
|
|
flow_raw += 0.1
|
|
|
|
flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0))
|
|
flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0))
|
|
table_raw += min(0.55, 0.08 * content.get("table_hits", 0))
|
|
if content.get("image_hits", 0) >= 2 and ext in {
|
|
".doc",
|
|
".docx",
|
|
".pdf",
|
|
".ppt",
|
|
".pptx",
|
|
}:
|
|
flow_raw += 0.05
|
|
|
|
flow_likelihood = max(0.05, min(0.95, flow_raw))
|
|
table_likelihood = max(0.05, min(0.95, table_raw))
|
|
text_density = 0.55
|
|
flow_evidence = _has_flow_evidence(stem, content)
|
|
|
|
if not flow_evidence:
|
|
flow_likelihood = min(flow_likelihood, 0.59)
|
|
if content.get("table_hits", 0) >= 1:
|
|
table_likelihood = max(table_likelihood, 0.65)
|
|
|
|
if (
|
|
flow_evidence
|
|
and flow_likelihood >= 0.65
|
|
and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1)
|
|
):
|
|
doc_kind = "mixed"
|
|
reasons.append("content indicates mixed flow+table document")
|
|
elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence):
|
|
doc_kind = "tabular_record"
|
|
reasons.append("content indicates table-like document")
|
|
elif not flow_evidence and (
|
|
table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1
|
|
):
|
|
doc_kind = "tabular_record"
|
|
reasons.append("content indicates text+table document without flow")
|
|
elif flow_evidence and flow_likelihood >= 0.65:
|
|
doc_kind = "flow_procedure"
|
|
reasons.append("content indicates flow/procedure document")
|
|
elif flow_likelihood <= 0.35 or not flow_evidence:
|
|
doc_kind = "policy_text"
|
|
reasons.append("content indicates policy/management text")
|
|
else:
|
|
doc_kind = "mixed"
|
|
reasons.append("content indicates mixed document")
|
|
|
|
return doc_kind, flow_likelihood, table_likelihood, text_density, reasons
|
|
|
|
|
|
def _derive_content_modes(
|
|
ext: str,
|
|
stem: str,
|
|
content: dict,
|
|
flow_likelihood: float,
|
|
table_likelihood: float,
|
|
) -> list[str]:
|
|
modes: set[str] = set()
|
|
if content.get("has_text") or ext in {
|
|
".doc",
|
|
".docx",
|
|
".pdf",
|
|
".ppt",
|
|
".pptx",
|
|
".xls",
|
|
".xlsx",
|
|
".csv",
|
|
}:
|
|
modes.add("text")
|
|
if content.get("image_hits", 0) > 0:
|
|
modes.add("image")
|
|
if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1:
|
|
modes.add("table")
|
|
if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6:
|
|
modes.add("flow")
|
|
return sorted(modes)
|
|
|
|
|
|
def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile:
|
|
file_path = Path(input_data["file_path"])
|
|
ext = file_path.suffix.lower()
|
|
file_type = ext.lstrip(".")
|
|
|
|
size = file_path.stat().st_size if file_path.exists() else 0
|
|
has_tables = ext in {".xls", ".xlsx", ".csv"}
|
|
content_signals = _probe_content(file_path, ext)
|
|
doc_kind, flow_likelihood, table_likelihood, text_density, reasons = (
|
|
_decide_doc_kind(file_path.stem, ext, content_signals)
|
|
)
|
|
content_modes = _derive_content_modes(
|
|
ext, file_path.stem, content_signals, flow_likelihood, table_likelihood
|
|
)
|
|
|
|
scan_likelihood = 0.2
|
|
if ext == ".pdf" and size > 3 * 1024 * 1024:
|
|
scan_likelihood = 0.65
|
|
|
|
has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"}
|
|
|
|
pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg)
|
|
|
|
context.file_type = file_type
|
|
context.extras["intake"] = {
|
|
"doc_kind": doc_kind,
|
|
"content_modes": content_modes,
|
|
"route_reasons": reasons,
|
|
"strategy": {
|
|
"enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())),
|
|
"disable": sorted(
|
|
_DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set())
|
|
),
|
|
},
|
|
"content_signals": content_signals,
|
|
"flow_likelihood": round(flow_likelihood, 3),
|
|
"table_likelihood": round(table_likelihood, 3),
|
|
"scan_likelihood": round(scan_likelihood, 3),
|
|
"pipeline": pipeline,
|
|
}
|
|
|
|
return DocumentProfile(
|
|
file_type=file_type,
|
|
text_density=text_density,
|
|
has_images=has_images,
|
|
has_tables=has_tables,
|
|
flow_likelihood=flow_likelihood,
|
|
scan_likelihood=scan_likelihood,
|
|
table_likelihood=table_likelihood,
|
|
language_hint="zh",
|
|
recommended_pipeline=pipeline,
|
|
)
|