This commit is contained in:
新新 committed 2026-04-27 17:03:56 +08:00
commit fe636432d0
154 files changed
+30381

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Enterprise KB Skill System orchestrator package."""
+167
View File
@@ -0,0 +1,167 @@
from __future__ import annotations
import json
from pathlib import Path
import typer
from edkb_system.config import SystemConfig
from edkb_system.contracts import Context
from edkb_system.controller import build_knowledge
from edkb_system.skills import (
flow_reconstruct,
loader_excel,
loader_pdf,
table_linearize,
)
app = typer.Typer(help="Enterprise KB multi-skill orchestrator")
def _write_failed_files_report(out_dir: Path, failed: list[dict]) -> tuple[Path, Path]:
txt_path = out_dir / "_failed_files.txt"
json_path = out_dir / "_failed_files.json"
if not failed:
for p in [txt_path, json_path]:
if p.exists():
p.unlink()
return txt_path, json_path
out_dir.mkdir(parents=True, exist_ok=True)
lines: list[str] = []
payload: list[dict] = []
for idx, item in enumerate(failed, start=1):
file_name = str(item.get("file") or "unknown").strip() or "unknown"
reason = str(item.get("error") or "unknown error")
elapsed_ms = int(item.get("elapsed_ms") or 0)
elapsed_s = f"{elapsed_ms / 1000:.3f}s"
is_timeout = "timed out" in reason.lower()
payload.append(
{
"index": idx,
"file": file_name,
"reason": reason,
"elapsed_ms": elapsed_ms,
"timed_out": is_timeout,
}
)
lines.extend(
[
f"[{idx}] {file_name}",
f"reason: {reason}",
f"elapsed: {elapsed_s}",
f"timed_out: {'true' if is_timeout else 'false'}",
"",
]
)
txt_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
json_path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
return txt_path, json_path
@app.command("build")
def build_cmd(
input_path: str = typer.Argument(..., metavar="PATH"),
out: str = typer.Option(..., "--out"),
config: str | None = typer.Option(None, "--config"),
skip: list[str] | None = typer.Option(
None,
"--skip",
help="Skip files by glob pattern (match name or relative path, repeatable)",
),
resume: bool = typer.Option(
False,
"--resume/--no-resume",
help="Skip files whose target markdown already exists",
),
prune_stale: bool = typer.Option(
False,
"--prune-stale/--keep-stale",
help="Remove stale markdown/intermediate leftovers in output before build",
),
) -> None:
cfg = SystemConfig.load(config)
root = Path(__file__).resolve().parents[2]
temp_dir = root / "work" / "cache"
in_path = Path(input_path)
if not in_path.exists():
typer.echo(f"Input path not found: {in_path}")
typer.echo("Create the folder and put documents in it, e.g. work/input")
raise typer.Exit(code=2)
results = build_knowledge(
in_path,
Path(out),
cfg,
temp_dir,
skip_patterns=skip or [],
resume=resume,
prune_stale_output=prune_stale,
)
ok = [r for r in results if r.get("status") == "success"]
failed = [r for r in results if r.get("status") == "failed"]
skipped = [r for r in results if r.get("status") == "skipped"]
typer.echo(
"Completed files: "
f"{len(results)} (success={len(ok)}, failed={len(failed)}, skipped={len(skipped)})"
)
if failed:
txt_path, json_path = _write_failed_files_report(Path(out), failed)
for r in failed:
file_name = str(r.get("file", "")).strip() or "unknown"
reason = str(r.get("error") or "unknown error")
typer.echo(f"- Failed: {file_name}")
typer.echo(f" - reason: {reason}")
typer.echo(f"- Failed list: {txt_path}")
typer.echo(f"- Failed json: {json_path}")
else:
_write_failed_files_report(Path(out), [])
typer.echo(f"- Output dir: {Path(out)}")
@app.command("inspect-flow")
def inspect_flow_cmd(
file: str = typer.Argument(..., metavar="FILE"),
out: str = typer.Option(..., "--out"),
) -> None:
ctx = Context(file_type="pdf")
blocks = loader_pdf.run({"file_path": file}, ctx)
data = flow_reconstruct.run(blocks, ctx)
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "inspect_flow.md").write_text(
"\n\n".join(data.get("flow_markdowns", [])), encoding="utf-8"
)
(out_dir / "inspect_flow_debug.json").write_text(
json.dumps(data.get("debug", []), ensure_ascii=False, indent=2),
encoding="utf-8",
)
typer.echo("inspect-flow done")
@app.command("inspect-excel")
def inspect_excel_cmd(
file: str = typer.Argument(..., metavar="FILE"),
out: str = typer.Option(..., "--out"),
) -> None:
ctx = Context(file_type="xlsx")
tables = loader_excel.run({"file_path": file, "work_dir": str(Path(out))}, ctx)
md = table_linearize.run(tables, ctx)
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "inspect_excel.md").write_text(md, encoding="utf-8")
(out_dir / "inspect_excel_schema.json").write_text(
json.dumps(
[{"sheet": t.get("sheet"), "headers": t.get("headers")} for t in tables],
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
typer.echo("inspect-excel done")
if __name__ == "__main__":
app()
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
import json
from pathlib import Path
from pydantic import BaseModel, Field
class RouterConfig(BaseModel):
scan_likelihood_threshold: float = 0.6
flow_likelihood_threshold: float = 0.5
table_likelihood_threshold: float = 0.5
class OCRConfig(BaseModel):
enable: bool = True
engine: str = "rapidocr"
min_confidence: float = 0.3
class ChunkConfig(BaseModel):
enable: bool = True
max_chars: int = 1200
overlap_chars: int = 150
add_heading_path_prefix: bool = True
class CleanConfig(BaseModel):
dedup_min_repeats: int = 3
merge_short_line_chars: int = 15
class SystemConfig(BaseModel):
router: RouterConfig = Field(default_factory=RouterConfig)
ocr: OCRConfig = Field(default_factory=OCRConfig)
chunk: ChunkConfig = Field(default_factory=ChunkConfig)
clean: CleanConfig = Field(default_factory=CleanConfig)
@classmethod
def load(cls, path: str | None) -> "SystemConfig":
if not path:
return cls()
p = Path(path)
raw = p.read_text(encoding="utf-8")
if p.suffix.lower() in {".yaml", ".yml"}:
import yaml
data = yaml.safe_load(raw) or {}
elif p.suffix.lower() == ".json":
data = json.loads(raw)
else:
raise ValueError("config only supports yaml/yml/json")
return cls.model_validate(data)
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Block:
id: str
page: int
type: str
text: str
bbox: tuple[float, float, float, float]
meta: dict[str, Any] = field(default_factory=dict)
def cx(self) -> float:
return (self.bbox[0] + self.bbox[2]) / 2.0
def cy(self) -> float:
return (self.bbox[1] + self.bbox[3]) / 2.0
@dataclass
class Chunk:
id: str
heading_path: str
text: str
index: int
source: str
@dataclass
class Context:
file_type: str = ""
pages: int = 0
images: int = 0
ocr_characters: int = 0
flows_detected: int = 0
warnings: list[str] = field(default_factory=list)
confidence: float = 1.0
extras: dict[str, Any] = field(default_factory=dict)
@dataclass
class DocumentProfile:
file_type: str
text_density: float
has_images: bool
has_tables: bool
flow_likelihood: float
scan_likelihood: float
table_likelihood: float
language_hint: str
recommended_pipeline: list[str]
+893
View File
@@ -0,0 +1,893 @@
from __future__ import annotations
import json
import fnmatch
import multiprocessing as mp
import os
import re
import shutil
import time
import traceback
from pathlib import Path
from edkb_system.config import SystemConfig
from edkb_system.contracts import Context
from edkb_system.discovery import discover
from edkb_system.skills import (
chunk,
clean,
doc_to_pdf,
export,
flow_reconstruct,
intake_router,
loader_csv,
loader_docx,
loader_excel,
loader_pdf,
loader_pptx,
ocr,
postcheck,
quality_gate,
table_linearize,
)
from edkb_system.skills.common import blocks_to_plain_markdown
from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids
_STEP_ALIAS = {
"edkb-intake-router": "route",
"edkb-loader-docx": "docx",
"edkb-doc-to-pdf": "doc2pdf",
"edkb-loader-pdf": "pdf",
"edkb-loader-pptx": "pptx",
"edkb-loader-excel": "excel",
"edkb-loader-csv": "csv",
"edkb-ocr": "ocr",
"edkb-flow-reconstruct": "flow",
"edkb-table-linearize": "table",
"edkb-clean": "clean",
"edkb-chunk": "chunk",
"edkb-quality-gate": "qgate",
"edkb-export": "export",
"edkb-postcheck": "check",
}
def _step_alias(step: str) -> str:
return _STEP_ALIAS.get(step, step.replace("edkb-", ""))
def _extract_doc_header_from_flow(flow_mds: list[str]) -> str | None:
if not flow_mds:
return None
for line in "\n".join(flow_mds).splitlines():
if "文件编号" not in line or "文件级别" not in line or "版本" not in line:
continue
s = " ".join(line.split())
m = re.search(r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", s)
if m:
return f"文件编号 {m.group(1)} 文件级别 {m.group(2)} 版本 {m.group(3)}"
return None
def _inject_doc_header_from_flow(text: str, flow_mds: list[str]) -> str:
if "文件编号" in text:
return text
meta = _extract_doc_header_from_flow(flow_mds)
if not meta:
return text
if text.startswith("制定部门"):
i = text.find("\n")
if i >= 0:
return text[: i + 1] + meta + "\n" + text[i + 1 :]
return meta + "\n" + text
def _inject_source_title_if_missing(text: str, source_stem: str) -> str:
if not source_stem:
return text
preview = "\n".join(text.splitlines()[:20])
norm_preview = re.sub(r"\s+", "", preview)
norm_source = re.sub(r"\s+", "", source_stem)
if norm_source in norm_preview:
return text
return source_stem + "\n" + text
def _promote_title_above_meta(text: str) -> str:
lines = text.splitlines()
if len(lines) < 2:
return text
first_idx = next((i for i, x in enumerate(lines) if x.strip()), None)
if first_idx is None:
return text
second_idx = next(
(i for i in range(first_idx + 1, len(lines)) if lines[i].strip()), None
)
if second_idx is None:
return text
first = lines[first_idx].strip()
second = lines[second_idx].strip()
if "文件编号" not in first:
return text
if (
re.match(r"^[一二三四五六七八九十]+、", second)
or second.startswith("制定部门")
or second.startswith("文件修订履历")
or "文件编号" in second
):
return text
if len(second) > 80:
return text
lines[first_idx], lines[second_idx] = lines[second_idx], lines[first_idx]
return "\n".join(lines)
def _promote_dept_header_near_top(text: str) -> str:
lines = text.splitlines()
pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+")
idx = next(
(i for i, ln in enumerate(lines) if pat.search(" ".join(ln.split()))), None
)
if idx is None or idx <= 4:
return text
line = lines.pop(idx)
insert_at = 1
for i, ln in enumerate(lines[:6]):
if ln.strip().startswith("文件编号"):
insert_at = i + 1
break
lines.insert(insert_at, line)
return "\n".join(lines)
def _ocr_payload_map(blocks: list) -> dict[str, str]:
out: dict[str, str] = {}
for b in blocks:
if getattr(b, "type", "") != "ocr_text" or not str(
getattr(b, "id", "")
).startswith("ocr-"):
continue
txt = (getattr(b, "text", "") or "").strip()
if txt.startswith("OCR_TEXT:"):
txt = txt[len("OCR_TEXT:") :].strip()
txt = re.sub(r"(?m)^\s*-\s*", "", txt)
txt = " ".join(x.strip() for x in txt.splitlines() if x.strip())
if txt and txt != "<empty>":
out[str(b.id)[len("ocr-") :]] = txt
return out
def _has_non_flow_image_content(blocks: list) -> bool:
img_ids = [str(b.id) for b in blocks if getattr(b, "type", "") == "image"]
if not img_ids:
return False
ocr_map = _ocr_payload_map(blocks)
info_kw = re.compile(r"分数值|频繁程度|严重性|LEC|评分基准|风险积分|事故发生")
flow_kw = re.compile(r"备料|取样|资料确认|品质检验|判定|产品出货|NG|OK|不合格品")
for iid in img_ids:
payload = ocr_map.get(iid, "")
if not payload:
continue
if info_kw.search(payload):
return True
if len(payload) >= 80 and len(flow_kw.findall(payload)) <= 2:
return True
return False
def _derive_source_category(file_path: Path, input_path: Path) -> str:
if input_path.is_dir():
try:
rel = file_path.relative_to(input_path)
if len(rel.parts) >= 2:
return rel.parts[0]
return input_path.name or "uncategorized"
except Exception:
return file_path.parent.name or "uncategorized"
return input_path.parent.name or "uncategorized"
def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
if input_path.is_dir():
try:
rel = file_path.relative_to(input_path)
except Exception:
rel = Path(file_path.name)
if len(rel.parts) == 1:
root_name = input_path.name
if root_name and root_name.lower() not in {"input", "work"}:
rel = Path(root_name) / rel
else:
parent_name = file_path.parent.name
if parent_name and parent_name.lower() not in {"input", "work"}:
rel = Path(parent_name) / file_path.name
else:
rel = Path(file_path.name)
return rel.with_suffix(".md")
def _normalize_path_for_match(p: Path | str) -> str:
return str(p).replace("\\", "/")
def _file_timeout_sec() -> int | None:
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
try:
value = int(raw)
except ValueError:
value = 0
return value if value > 0 else None
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
if input_path.is_file():
candidates = [input_path]
elif input_path.exists():
candidates = [p for p in input_path.rglob("*") if p.is_file()]
else:
return []
removed: list[Path] = []
for file in candidates:
name = file.name
if not (name.startswith("~$") or name.startswith("~WRL")):
continue
try:
file.unlink()
except Exception:
continue
removed.append(file)
return removed
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
if not patterns:
return None
lowered_candidates = [c.lower() for c in candidates if c]
for pat in patterns:
norm_pat = _normalize_path_for_match(pat).strip().lower()
if not norm_pat:
continue
for cand in lowered_candidates:
if fnmatch.fnmatch(cand, norm_pat):
return pat
return None
def _prune_stale_markdowns(output_dir: Path, expected: set[Path]) -> None:
keep_names = {"INDEX.md", "POSTCHECK_ISSUES.md"}
expected_resolved = {p.resolve() for p in expected}
for md in output_dir.rglob("*.md"):
if md.name in keep_names:
continue
try:
resolved = md.resolve()
except Exception:
resolved = md
if resolved in expected_resolved:
continue
try:
md.unlink()
except Exception:
continue
def _run_one_worker(payload: dict, queue: mp.Queue) -> None:
try:
cfg = SystemConfig.model_validate(payload["config"])
res = _run_one(
Path(payload["file_path"]),
Path(payload["out_root"]),
Path(payload["temp_dir"]),
cfg,
source_root=Path(payload["source_root"])
if payload.get("source_root")
else None,
source_category=payload.get("source_category"),
final_md_path=(
Path(payload["final_md_path"]) if payload.get("final_md_path") else None
),
progress_label=payload.get("progress_label"),
)
queue.put({"ok": True, "result": res})
except Exception as exc:
queue.put({"ok": False, "error": str(exc), "detail": traceback.format_exc()})
def _run_one_with_timeout(
file_path: Path,
out_root: Path,
temp_dir: Path,
cfg: SystemConfig,
source_root: Path | None = None,
source_category: str | None = None,
final_md_path: Path | None = None,
progress_label: str | None = None,
) -> dict:
timeout = _file_timeout_sec()
if not timeout:
return _run_one(
file_path,
out_root,
temp_dir,
cfg,
source_root=source_root,
source_category=source_category,
final_md_path=final_md_path,
progress_label=progress_label,
)
ctx = mp.get_context("spawn")
queue: mp.Queue = ctx.Queue()
before_pids = _list_winword_pids()
payload = {
"file_path": str(file_path),
"out_root": str(out_root),
"temp_dir": str(temp_dir),
"config": cfg.model_dump(),
"source_root": str(source_root) if source_root else None,
"source_category": source_category,
"final_md_path": str(final_md_path) if final_md_path else None,
"progress_label": progress_label,
}
proc = ctx.Process(target=_run_one_worker, args=(payload, queue))
proc.start()
proc.join(timeout)
if proc.is_alive():
proc.terminate()
proc.join(5)
after_pids = _list_winword_pids()
_kill_winword_pids(after_pids - before_pids)
raise TimeoutError(
f"file processing timed out after {timeout}s: {file_path.name}"
)
if queue.empty():
if proc.exitcode not in {0, None}:
raise RuntimeError(
f"file worker exited unexpectedly (code={proc.exitcode}): {file_path.name}"
)
raise RuntimeError(f"file worker returned no result: {file_path.name}")
message = queue.get()
if message.get("ok"):
return message["result"]
detail = str(message.get("detail") or "")
raise RuntimeError(str(message.get("error") or detail or "unknown worker error"))
marker_files = {
"01_raw_layout.json",
"02_flow_procedure.md",
"03_clean.md",
"04_chunks.jsonl",
"report.md",
"trace_pipeline.json",
"postcheck.json",
}
for d in list(output_dir.iterdir()):
if not d.is_dir():
continue
try:
names = {p.name for p in d.iterdir()}
except Exception:
continue
if names & marker_files:
shutil.rmtree(d, ignore_errors=True)
for d in sorted(output_dir.rglob("*"), key=lambda x: len(x.parts), reverse=True):
if not d.is_dir():
continue
try:
if d == output_dir:
continue
next(d.iterdir())
except StopIteration:
try:
d.rmdir()
except Exception:
pass
except Exception:
continue
def _run_one(
file_path: Path,
out_root: Path,
temp_dir: Path,
cfg: SystemConfig,
source_root: Path | None = None,
source_category: str | None = None,
final_md_path: Path | None = None,
progress_label: str | None = None,
) -> dict:
ctx = Context()
trace_steps: list[str] = []
timings_ms: dict[str, int] = {}
def _mark(step: str, started: float) -> None:
timings_ms[step] = int((time.perf_counter() - started) * 1000)
def _announce(stage: str) -> None:
if not progress_label:
return
print(f"{progress_label} stage: {stage}", flush=True)
out_dir = out_root / file_path.stem
out_dir.mkdir(parents=True, exist_ok=True)
for stale in [
out_dir / "inspect_flow_debug.json",
out_dir / "trace_pipeline.json",
out_dir / "postcheck.json",
]:
if stale.exists():
stale.unlink()
t0 = time.perf_counter()
profile = intake_router.run({"file_path": str(file_path)}, ctx, cfg.router)
_mark("edkb-intake-router", t0)
trace_steps.append("edkb-intake-router")
blocks = []
tables = None
text = ""
flow_mds: list[str] = []
if profile.file_type in {"doc", "docx"}:
_announce("doc/docx parse")
t0 = time.perf_counter()
docx_blocks = loader_docx.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-docx", t0)
trace_steps.append("edkb-loader-docx")
table_blocks = sum(1 for b in docx_blocks if b.type == "table")
prefer_docx = table_blocks > 0
docx_images = [b for b in docx_blocks if b.type == "image"]
docx_non_images = [b for b in docx_blocks if b.type != "image"]
pdf_blocks = None
if "edkb-doc-to-pdf" in profile.recommended_pipeline and (
(profile.file_type == "doc" and not prefer_docx) or not docx_blocks
):
_announce("doc to pdf")
t0 = time.perf_counter()
conv = doc_to_pdf.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-doc-to-pdf", t0)
trace_steps.append("edkb-doc-to-pdf")
pdf_path = conv.get("pdf_path")
if pdf_path:
_announce("pdf load")
t0 = time.perf_counter()
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
blocks = pdf_blocks
else:
blocks = docx_blocks
else:
blocks = docx_blocks
if (
profile.file_type == "doc"
and "edkb-doc-to-pdf" in profile.recommended_pipeline
and (not prefer_docx or not docx_blocks)
):
if pdf_blocks is None:
_announce("doc to pdf")
t0 = time.perf_counter()
conv = doc_to_pdf.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-doc-to-pdf", t0)
trace_steps.append("edkb-doc-to-pdf")
pdf_path = conv.get("pdf_path")
if pdf_path:
_announce("pdf load")
t0 = time.perf_counter()
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
if pdf_blocks is not None:
pdf_images = [b for b in pdf_blocks if b.type == "image"]
if pdf_images and len(pdf_images) > len(docx_images):
blocks = docx_non_images + pdf_images
ctx.warnings.append(
f"doc image source switched to pdf: {len(docx_images)} -> {len(pdf_images)}"
)
elif not blocks:
blocks = pdf_blocks
elif profile.file_type == "pdf":
_announce("pdf load")
t0 = time.perf_counter()
blocks = loader_pdf.run({"file_path": str(file_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
elif profile.file_type in {"ppt", "pptx"}:
_announce("ppt/pptx load")
t0 = time.perf_counter()
blocks = loader_pptx.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-pptx", t0)
trace_steps.append("edkb-loader-pptx")
elif profile.file_type in {"xls", "xlsx"}:
_announce("excel load")
t0 = time.perf_counter()
tables = loader_excel.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-excel", t0)
trace_steps.append("edkb-loader-excel")
elif profile.file_type == "csv":
t0 = time.perf_counter()
tables = loader_csv.run({"file_path": str(file_path)}, ctx)
_mark("edkb-loader-csv", t0)
trace_steps.append("edkb-loader-csv")
else:
ctx.warnings.append(f"unsupported file type: {profile.file_type}")
if blocks:
ctx.images = sum(1 for b in blocks if b.type == "image")
should_ocr = cfg.ocr.enable and (
"edkb-ocr" in profile.recommended_pipeline
or any(b.type == "image" for b in blocks)
)
if profile.file_type in {"ppt", "pptx"}:
should_ocr = False
if should_ocr:
_announce("ocr")
t0 = time.perf_counter()
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
_mark("edkb-ocr", t0)
trace_steps.append("edkb-ocr")
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
policy_text = doc_kind == "policy_text"
has_non_flow_info = _has_non_flow_image_content(blocks)
has_page_image_mode = bool(ctx.extras.get("pdf_page_image_mode_pages"))
has_figure_anchor = any(
(b.text or "")
and re.search(
r"^\s*\d+(?:\.\d+){1,3}\s*[^\n]{0,40}(?:示意图|图示)\s*$",
b.text,
)
for b in blocks
if b.type in {"heading", "paragraph"}
)
suppress_images = False
if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor:
if policy_text and not has_non_flow_info and not has_page_image_mode:
suppress_images = True
elif (
doc_kind == "flow_procedure"
and not has_non_flow_info
and not has_page_image_mode
):
suppress_images = True
if suppress_images:
blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}]
trace_steps.append("edkb-image-suppress(no_figure_anchor)")
flow_info = {}
if "edkb-flow-reconstruct" in profile.recommended_pipeline:
_announce("flow reconstruct")
t0 = time.perf_counter()
flow_info = flow_reconstruct.run(blocks, ctx)
_mark("edkb-flow-reconstruct", t0)
trace_steps.append("edkb-flow-reconstruct")
flow_mds = flow_info.get("flow_markdowns", [])
if flow_info.get("debug"):
(out_dir / "inspect_flow_debug.json").write_text(
json.dumps(flow_info["debug"], ensure_ascii=False, indent=2),
encoding="utf-8",
)
text = blocks_to_plain_markdown(blocks)
text = _inject_doc_header_from_flow(text, flow_mds)
elif tables is not None:
_announce("table linearize")
t0 = time.perf_counter()
text = table_linearize.run(tables, ctx)
_mark("edkb-table-linearize", t0)
trace_steps.append("edkb-table-linearize")
_announce("clean")
t0 = time.perf_counter()
clean_md = clean.run(
text, ctx, cfg.clean.dedup_min_repeats, cfg.clean.merge_short_line_chars
)
_mark("edkb-clean", t0)
clean_md = _inject_source_title_if_missing(clean_md, file_path.stem)
clean_md = _promote_title_above_meta(clean_md)
meta = _extract_doc_header_from_flow(flow_mds)
has_meta_line = bool(
re.search(r"文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S+", clean_md)
or ("| 文件编号 |" in clean_md and "| 文件级别 |" in clean_md)
)
if meta and not has_meta_line:
if clean_md.startswith("制定部门"):
i = clean_md.find("\n")
if i >= 0:
clean_md = clean_md[: i + 1] + meta + "\n" + clean_md[i + 1 :]
else:
clean_md = clean_md + "\n" + meta + "\n"
else:
clean_md = meta + "\n" + clean_md
clean_md = _promote_title_above_meta(clean_md)
clean_md = _promote_dept_header_near_top(clean_md)
trace_steps.append("edkb-clean")
chunks = []
if cfg.chunk.enable:
_announce("chunk")
t0 = time.perf_counter()
chunks = chunk.run(
{"source": file_path.name, "text": clean_md},
ctx,
max_chars=cfg.chunk.max_chars,
overlap_chars=cfg.chunk.overlap_chars,
add_heading_path_prefix=cfg.chunk.add_heading_path_prefix,
)
_mark("edkb-chunk", t0)
trace_steps.append("edkb-chunk")
t0 = time.perf_counter()
chunks = quality_gate.run(chunks, ctx)
_mark("edkb-quality-gate", t0)
trace_steps.append("edkb-quality-gate")
else:
ctx.warnings.append(
"chunk disabled by config: skip edkb-chunk/edkb-quality-gate"
)
trace_steps.append("edkb-chunk(skipped)")
trace_steps.append("edkb-quality-gate(skipped)")
source_rel_path = file_path.name
if source_root is not None:
try:
source_rel_path = str(file_path.relative_to(source_root))
except Exception:
source_rel_path = file_path.name
target_md_path = final_md_path
if target_md_path is None:
target_md_path = out_root / f"{file_path.stem}.md"
_announce("export")
t0 = time.perf_counter()
export.run(
{
"out_dir": str(out_dir),
"source_file": file_path.name,
"source_rel_path": source_rel_path,
"source_category": source_category or "",
"flat_md_path": str(target_md_path),
"clean_md": clean_md,
"chunks": chunks,
"blocks": blocks,
"flow_markdowns": flow_mds,
},
ctx,
)
_mark("edkb-export", t0)
trace_steps.append("edkb-export")
exported_clean_md = clean_md
exported_clean_path = out_dir / "03_clean.md"
if exported_clean_path.exists():
try:
exported_clean_md = exported_clean_path.read_text(encoding="utf-8")
except Exception:
exported_clean_md = clean_md
_announce("postcheck")
t0 = time.perf_counter()
check = postcheck.run({"out_dir": str(out_dir), "clean_md": exported_clean_md}, ctx)
_mark("edkb-postcheck", t0)
(out_dir / "postcheck.json").write_text(
json.dumps(check, ensure_ascii=False, indent=2), encoding="utf-8"
)
if check.get("status") != "pass":
failed = ", ".join(check.get("failed_required", []))
ctx.warnings.append(f"postcheck failed: {failed}")
if check.get("issue_count", 0) > 0:
issue_codes: list[str] = []
for it in check.get("issues", [])[:3]:
code = str(it.get("code", "")).strip()
if code and code not in issue_codes:
issue_codes.append(code)
if issue_codes:
ctx.warnings.append(
f"postcheck issues: {check.get('issue_count', 0)} ({', '.join(issue_codes)})"
)
else:
ctx.warnings.append(f"postcheck issues: {check.get('issue_count', 0)}")
trace_steps.append("edkb-postcheck")
(out_dir / "trace_pipeline.json").write_text(
json.dumps(
{
"file": file_path.name,
"recommended_pipeline": profile.recommended_pipeline,
"executed_steps": trace_steps,
"timings_ms": timings_ms,
"intake": ctx.extras.get("intake", {}),
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
return {
"file": file_path.name,
"out_dir": str(out_dir),
"warnings": ctx.warnings,
"timings_ms": timings_ms,
}
def build_knowledge(
input_path: Path,
output_dir: Path,
config: SystemConfig,
temp_dir: Path,
skip_patterns: list[str] | None = None,
resume: bool = False,
prune_stale_output: bool = False,
) -> list[dict]:
removed_temp_files = _cleanup_input_temp_files(input_path)
if removed_temp_files:
for removed in removed_temp_files:
print(f"cleanup-temp: {removed}", flush=True)
files = discover(input_path)
output_dir.mkdir(parents=True, exist_ok=True)
temp_dir.mkdir(parents=True, exist_ok=True)
patterns = [p for p in (skip_patterns or []) if str(p).strip()]
for stale in [output_dir / "INDEX.md", output_dir / "POSTCHECK_ISSUES.md"]:
if stale.exists():
stale.unlink()
for lock_md in output_dir.glob("~$*.md"):
if lock_md.is_file():
lock_md.unlink()
if prune_stale_output:
expected_paths = {
(output_dir / _derive_output_rel_md(file, input_path)).resolve()
for file in files
}
_prune_stale_markdowns(output_dir, expected_paths)
source_root = input_path if input_path.is_dir() else input_path.parent
results: list[dict] = []
total = len(files)
for idx, file in enumerate(files, start=1):
flat_out = output_dir / f"{file.stem}.md"
mirror_out = output_dir / _derive_output_rel_md(file, input_path)
source_rel_path = file.name
try:
source_rel_path = _normalize_path_for_match(file.relative_to(source_root))
except Exception:
source_rel_path = _normalize_path_for_match(file)
matched_pattern = _matches_pattern(
[
_normalize_path_for_match(file),
source_rel_path,
file.name,
],
patterns,
)
if matched_pattern:
print(
f"[{idx}/{total}] skipped(pattern): {source_rel_path} ({matched_pattern})",
flush=True,
)
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [],
"status": "skipped",
"skip_reason": f"pattern:{matched_pattern}",
"elapsed_ms": 0,
}
)
continue
if resume and mirror_out.exists() and mirror_out.stat().st_size > 0:
print(f"[{idx}/{total}] skipped(resume): {source_rel_path}", flush=True)
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [],
"status": "skipped",
"skip_reason": "resume-existing-output",
"elapsed_ms": 0,
}
)
continue
print(f"[{idx}/{total}] processing: {file.name}", flush=True)
if flat_out.exists():
flat_out.unlink()
if mirror_out != flat_out and mirror_out.exists():
mirror_out.unlink()
started = time.perf_counter()
try:
source_category = _derive_source_category(file, input_path)
res = _run_one_with_timeout(
file,
output_dir,
temp_dir,
config,
source_root=source_root,
source_category=source_category,
final_md_path=mirror_out,
progress_label=f"[{idx}/{total}] {file.name}",
)
elapsed_ms = int((time.perf_counter() - started) * 1000)
res["status"] = "success"
res["elapsed_ms"] = elapsed_ms
results.append(res)
print(
f"[{idx}/{total}] success: {file.name} ({elapsed_ms / 1000:.3f}s)",
flush=True,
)
timings = res.get("timings_ms", {}) or {}
if timings:
top = sorted(timings.items(), key=lambda x: x[1], reverse=True)[:3]
top_text = ", ".join(
f"{_step_alias(k)}={v / 1000:.3f}s" for k, v in top
)
print(f"[{idx}/{total}] time: {top_text}", flush=True)
out_dir_str = str(res.get("out_dir", "")).strip()
doc_artifact_dir = Path(out_dir_str) if out_dir_str else None
if (
doc_artifact_dir is not None
and doc_artifact_dir.exists()
and doc_artifact_dir.parent == output_dir
):
shutil.rmtree(doc_artifact_dir)
except Exception as exc:
elapsed_ms = int((time.perf_counter() - started) * 1000)
detail = traceback.format_exc()
doc_artifact_dir = output_dir / file.stem
if doc_artifact_dir.exists():
shutil.rmtree(doc_artifact_dir)
if flat_out.exists():
flat_out.unlink()
if mirror_out.exists() and mirror_out != flat_out:
mirror_out.unlink()
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [str(exc)],
"status": "failed",
"elapsed_ms": elapsed_ms,
"error": str(exc),
"error_detail": detail,
}
)
print(
f"[{idx}/{total}] failed: {file.name} ({elapsed_ms / 1000:.3f}s)",
flush=True,
)
print(f"[{idx}/{total}] reason: {exc}", flush=True)
print(detail.rstrip(), flush=True)
return results
+22
View File
@@ -0,0 +1,22 @@
from __future__ import annotations
from pathlib import Path
SUPPORTED_EXTS = {".doc", ".docx", ".pdf", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"}
def discover(path: Path) -> list[Path]:
if path.is_file():
if path.name.startswith("~$"):
return []
return [path] if path.suffix.lower() in SUPPORTED_EXTS else []
if not path.exists():
raise FileNotFoundError(path)
files = [
p
for p in path.rglob("*")
if p.is_file()
and not p.name.startswith("~$")
and p.suffix.lower() in SUPPORTED_EXTS
]
return sorted(files, key=lambda x: str(x))
+1
View File
@@ -0,0 +1 @@
"""Atomic skills for enterprise KB pipeline."""
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import hashlib
import re
from edkb_system.contracts import Chunk, Context
HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$")
def _chunk_id(source: str, heading: str, index: int, text: str) -> str:
raw = f"{source}|{heading}|{index}|{text}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def run(
input_data: dict,
context: Context,
max_chars: int = 1200,
overlap_chars: int = 150,
add_heading_path_prefix: bool = True,
) -> list[Chunk]:
source = input_data["source"]
md = input_data["text"]
lines = md.splitlines()
stack: list[str] = []
sections: list[tuple[str, str]] = []
buf: list[str] = []
def heading() -> str:
return " > ".join(stack) if stack else "ROOT"
for ln in lines:
m = HEAD_RE.match(ln.strip())
if m:
if buf:
sections.append((heading(), "\n".join(buf).strip()))
buf = []
level = len(m.group(1))
text = m.group(2).strip()
while len(stack) >= level:
stack.pop()
stack.append(text)
else:
buf.append(ln)
if buf:
sections.append((heading(), "\n".join(buf).strip()))
out: list[Chunk] = []
idx = 0
for hp, body in sections:
paras = [p.strip() for p in body.split("\n\n") if p.strip()]
acc = ""
for p in paras:
cand = (acc + "\n\n" + p).strip() if acc else p
if len(cand) <= max_chars:
acc = cand
continue
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
overlap = txt[-overlap_chars:] if overlap_chars > 0 else ""
acc = (overlap + "\n\n" + p).strip()
else:
acc = p[:max_chars]
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
return out
File diff suppressed because it is too large. Load diff
+244
View File
@@ -0,0 +1,244 @@
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 _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)
payload = ";".join(x.strip() for x in payload.splitlines() if x.strip())
return payload
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
if 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")
and b.meta.get("page_image_source") != "pptx"
):
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)
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from edkb_system.contracts import Context
from edkb_system.skills.word_bridge import convert_with_word
def _find_soffice() -> str | None:
candidates = [
os.environ.get("EDKB_SOFFICE"),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
for c in candidates:
if not c:
continue
if c == "soffice":
return c
if Path(c).exists():
return c
return None
def _convert_with_word(path: Path, out_dir: Path) -> Path:
output = out_dir / f"{path.stem}.pdf"
return convert_with_word(path.resolve(), output.resolve(), 17)
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
output = out_dir / f"{path.stem}.pdf"
cmd = [
soffice,
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip() or "no stderr"
raise RuntimeError(
f"soffice conversion failed (code={proc.returncode}): {stderr}"
)
if not output.exists():
raise RuntimeError(f"soffice conversion produced no output: {output}")
return output
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
out_dir = work_dir / "flow_pdf"
out_dir.mkdir(parents=True, exist_ok=True)
errors: list[str] = []
if os.name == "nt":
try:
pdf = _convert_with_word(file_path, out_dir)
return {"pdf_path": str(pdf), "converter": "word"}
except Exception as exc:
errors.append(f"word: {exc}")
soffice = _find_soffice()
if soffice:
try:
pdf = _convert_with_soffice(file_path, out_dir, soffice)
return {"pdf_path": str(pdf), "converter": "soffice"}
except Exception as exc:
errors.append(f"soffice: {exc}")
else:
errors.append("soffice: not found")
context.warnings.append(
"doc->pdf conversion unavailable; fallback to docx text parser"
)
context.warnings.append("doc->pdf details: " + "; ".join(errors))
return {"pdf_path": None, "converter": None}
+567
View File
@@ -0,0 +1,567 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import os
import re
import shutil
from dataclasses import asdict, replace
from pathlib import Path
from urllib.parse import quote, urlparse
from edkb_system.contracts import Block, Chunk, Context
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
_EMBEDDED_IMG_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_LOOSE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_ANY_RE = re.compile(
r"!\[[^\]]*\]\(data:image/.*?\)",
re.IGNORECASE | re.DOTALL,
)
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
def _bool_env(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _sanitize_segment(raw: str) -> str:
s = (raw or "").strip()
if not s:
return "untitled"
s = re.sub(r"\s+", "_", s)
s = s.replace("/", "_").replace("\\", "_")
s = re.sub(r"[:*?\"<>|]", "_", s)
s = re.sub(r"_+", "_", s).strip("._")
return s or "untitled"
def _build_object_prefix(
source_category: str, source_rel_path: str, source_file: str
) -> str:
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
category = _sanitize_segment(source_category)
if not category:
if len(parts) >= 2:
category = _sanitize_segment(parts[0])
else:
category = "uncategorized"
if parts and _sanitize_segment(parts[0]) == category:
parts = parts[1:]
if parts:
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
else:
doc_parts = [Path(source_file or "document").stem or "document"]
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
normalized = [p for p in normalized if p]
return "/".join(normalized)
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
endpoint = (raw_endpoint or "").strip()
secure_default = False
if "://" in endpoint:
parsed = urlparse(endpoint)
secure_default = parsed.scheme.lower() == "https"
endpoint = parsed.netloc or parsed.path
endpoint = endpoint.strip().rstrip("/")
return endpoint, secure_default
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
base = (raw_base or "").strip().rstrip("/")
if not base:
scheme = "https" if secure else "http"
return f"{scheme}://{endpoint}".rstrip("/")
if "://" not in base:
scheme = "https" if secure else "http"
return f"{scheme}://{base}".rstrip("/")
return base.rstrip("/")
def _quote_object_name(object_name: str) -> str:
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
def _ext_from_blob(blob: bytes) -> str | None:
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if blob.startswith(b"\xff\xd8\xff"):
return "jpg"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"BM"):
return "bmp"
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
return "webp"
return None
def _normalize_ext(fmt: str, blob: bytes) -> str:
f = (fmt or "").lower().strip()
if f in {"jpeg", "jpg"}:
return "jpg"
if f in {"png", "gif", "bmp", "webp"}:
return f
guessed = _ext_from_blob(blob)
return guessed or "png"
def _content_type_for_ext(ext: str) -> str:
if ext == "jpg":
return "image/jpeg"
if ext == "png":
return "image/png"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
return "application/octet-stream"
def _is_valid_image_blob(blob: bytes) -> bool:
if len(blob) < 8:
return False
if _ext_from_blob(blob):
return True
# Unknown format fallback: keep only if not tiny garbage.
return len(blob) >= 64
class _MinioStorage:
def __init__(
self,
*,
endpoint: str,
bucket_name: str,
access_key: str,
secret_key: str,
secure: bool,
public_base: str,
) -> None:
import importlib
minio_mod = importlib.import_module("minio")
minio_ctor = getattr(minio_mod, "Minio")
self.bucket_name = bucket_name
self.public_base = public_base.rstrip("/")
self.client = minio_ctor(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure,
)
if not self.client.bucket_exists(bucket_name):
self.client.make_bucket(bucket_name)
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
stream = io.BytesIO(blob)
self.client.put_object(
self.bucket_name,
object_name,
stream,
len(blob),
content_type=content_type,
)
def list_prefix(self, prefix: str) -> list[str]:
return [
obj.object_name
for obj in self.client.list_objects(
self.bucket_name,
prefix=prefix,
recursive=True,
)
]
def remove_object(self, object_name: str) -> None:
self.client.remove_object(self.bucket_name, object_name)
def build_url(self, object_name: str) -> str:
return (
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
)
class _RemoteImageRewriter:
def __init__(
self,
*,
context: Context,
source_file: str,
source_rel_path: str,
source_category: str,
) -> None:
self.context = context
self.source_file = source_file
self.source_rel_path = source_rel_path
self.source_category = source_category
self.object_prefix = _build_object_prefix(
source_category, source_rel_path, source_file
)
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
self.storage: _MinioStorage | None = None
self._storage_initialized = False
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, tuple[str, str]] = {}
self.referenced_objects: set[str] = set()
self.uploaded_count = 0
self.reused_count = 0
self.invalid_removed_count = 0
self.kept_embedded_count = 0
self.stale_removed_count = 0
self._upload_error_warn_count = 0
self._saw_embedded_image = False
self._next_image_index = 1
def _build_storage(self) -> _MinioStorage | None:
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
)
return None
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
secure = _bool_env("MINIO_SECURE", secure_default)
if not endpoint:
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled: MINIO_ENDPOINT is empty"
)
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
)
try:
return _MinioStorage(
endpoint=endpoint,
bucket_name=bucket_name,
access_key=access_key,
secret_key=secret_key,
secure=secure,
public_base=public_base,
)
except Exception as exc:
if self.allow_embed_fallback:
self.context.warnings.append(
f"image-hosting unavailable, keep embedded image: {exc}"
)
return None
raise RuntimeError(f"image-hosting unavailable: {exc}")
def _warn_upload_error(self, msg: str) -> None:
if self._upload_error_warn_count < 5:
self.context.warnings.append(msg)
self._upload_error_warn_count += 1
def _ensure_storage(self) -> None:
if self._storage_initialized:
return
self.storage = self._build_storage()
self._storage_initialized = True
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
fmt = (fmt or "png").lower()
b64_clean = re.sub(r"\s+", "", b64_raw)
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
if not _is_valid_image_blob(blob):
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
self._ensure_storage()
if self.storage is None:
if not self.allow_embed_fallback:
raise RuntimeError(
"image-hosting unavailable: embedded fallback is disabled"
)
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
return _KEEP_IMAGE
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
url, object_name = cached_sha
self.referenced_objects.add(object_name)
self.reused_count += 1
self.uri_cache[uri] = url
return url
ext = _normalize_ext(fmt, blob)
content_type = _content_type_for_ext(ext)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
object_name = (
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
)
try:
self.storage.put_bytes(object_name, blob, content_type)
url = self.storage.build_url(object_name)
self.sha_cache[sha] = (url, object_name)
self.referenced_objects.add(object_name)
self.uploaded_count += 1
self.uri_cache[uri] = url
return url
except Exception as exc:
if not self.allow_embed_fallback:
raise RuntimeError(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
) from exc
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
self._warn_upload_error(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
)
return _KEEP_IMAGE
def _process_match(self, m: re.Match[str]) -> str:
return self._process_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
def _process_loose_uri(self, uri: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
head, sep, b64_raw = uri.partition(",")
if not sep:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
fmt = "png"
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
if m:
fmt = (m.group("fmt") or "png").lower()
return self._process_embedded_uri(uri, fmt, b64_raw)
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
self._saw_embedded_image = True
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_match(m)
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
def loose_repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_loose_uri(m.group("uri") or "")
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
if not self.allow_embed_fallback and "data:image/" in out:
dropped_before = self.invalid_removed_count
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
removed = self.invalid_removed_count - dropped_before
if "data:image/" in out:
self.context.warnings.append(
"image-hosting left non-markdown data:image content; kept as-is"
)
else:
self.context.warnings.append(
"image-hosting removed unsupported embedded images"
+ (f": {removed}" if removed > 0 else "")
)
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
return out
def finalize(self) -> None:
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
self._ensure_storage()
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
prefix = f"{self.object_prefix}/"
try:
for object_name in self.storage.list_prefix(prefix):
if object_name in self.referenced_objects:
continue
self.storage.remove_object(object_name)
self.stale_removed_count += 1
except Exception as exc:
self.context.warnings.append(
f"image-hosting cleanup failed ({self.source_file}): {exc}"
)
if self.invalid_removed_count > 0:
self.context.warnings.append(
f"image-hosting removed invalid images: {self.invalid_removed_count}"
)
if self.kept_embedded_count > 0 and self.storage is None:
self.context.warnings.append(
"image-hosting unavailable: keep legacy data:image embeds"
)
if (
self.uploaded_count > 0
or self.reused_count > 0
or self.stale_removed_count > 0
):
self.context.warnings.append(
"image-hosting synced "
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
)
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
source_file = input_data.get("source_file", "")
source_rel_path = input_data.get("source_rel_path", source_file)
source_category = input_data.get("source_category", "")
source_stem = Path(source_file).stem if source_file else out_dir.name
flat_clean_path = Path(
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
)
view_clean_path = out_dir / "03_clean_view.md"
view_images_dir = out_dir / "images_view"
for p in [
out_dir / "01_raw_layout.json",
out_dir / "02_flow_procedure.md",
out_dir / "03_clean.md",
out_dir / "04_chunks.jsonl",
out_dir / "report.md",
view_clean_path,
flat_clean_path,
]:
if p.exists():
p.unlink()
chunks_dir = out_dir / "chunks"
if chunks_dir.exists():
shutil.rmtree(chunks_dir)
if view_images_dir.exists():
shutil.rmtree(view_images_dir)
clean_md: str = input_data.get("clean_md", "")
chunks: list[Chunk] = input_data.get("chunks", [])
blocks: list[Block] = input_data.get("blocks", [])
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
rewriter = _RemoteImageRewriter(
context=context,
source_file=source_file,
source_rel_path=source_rel_path,
source_category=source_category,
)
clean_md = rewriter.replace_text(clean_md)
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
chunks_dir.mkdir(parents=True, exist_ok=True)
for c in exported_chunks:
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
if flow_markdowns:
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
_write(
out_dir / "01_raw_layout.json",
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
)
report_lines = [
f"# Report: {input_data.get('source_file', '')}",
"",
f"- pages: {context.pages}",
f"- images: {context.images}",
f"- ocr_characters: {context.ocr_characters}",
f"- flows_detected: {context.flows_detected}",
f"- confidence: {context.confidence:.2f}",
"",
"## warnings",
]
if context.warnings:
report_lines.extend([f"- {w}" for w in context.warnings])
else:
report_lines.append("- none")
report_lines.extend(
[
"",
"## recommended_dify_settings",
"- Index: High Quality",
"- Retrieval: Hybrid",
"- Chunking: General",
"",
]
)
_write(out_dir / "report.md", "\n".join(report_lines))
return {"out_dir": str(out_dir)}
@@ -0,0 +1,142 @@
from __future__ import annotations
from dataclasses import dataclass
import networkx as nx
from edkb_system.contracts import Block, Context
@dataclass
class Node:
id: str
text: str
page: int
kind: str
bbox: tuple[float, float, float, float]
def _is_decision(text: str) -> bool:
kws = ["判定", "判断", "是否", "if", "check"]
s = text.lower()
return any(k in s for k in kws)
def _dist(a: Node, b: Node) -> float:
ax = (a.bbox[0] + a.bbox[2]) / 2.0
ay = (a.bbox[1] + a.bbox[3]) / 2.0
bx = (b.bbox[0] + b.bbox[2]) / 2.0
by = (b.bbox[1] + b.bbox[3]) / 2.0
return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
def run(input_data: list[Block], context: Context) -> dict:
blocks = [
b
for b in input_data
if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"}
and b.text.strip()
]
by_page: dict[int, list[Block]] = {}
for b in blocks:
by_page.setdefault(b.page, []).append(b)
page_markdowns: list[str] = []
debug: list[dict] = []
for page in sorted(by_page):
cands = by_page[page]
nodes: list[Node] = []
labels: list[Node] = []
for b in cands:
text = b.text.strip()
if b.type == "arrow_label" or text.upper() in {
"NG",
"OK",
"Y",
"N",
"YES",
"NO",
}:
labels.append(Node(b.id, text, b.page, "label", b.bbox))
continue
kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step"
nodes.append(Node(b.id, text, b.page, kind, b.bbox))
nodes = sorted(
nodes,
key=lambda n: (
(n.bbox[1] + n.bbox[3]) / 2.0,
(n.bbox[0] + n.bbox[2]) / 2.0,
),
)
if not nodes:
continue
g = nx.DiGraph()
for n in nodes:
g.add_node(n.id, node=n)
for i, src in enumerate(nodes[:-1]):
dst = nodes[i + 1]
g.add_edge(src.id, dst.id, label=None)
for dec in [n for n in nodes if n.kind == "decision"]:
right_steps = [
n
for n in nodes
if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_steps:
target = min(right_steps, key=lambda x: _dist(dec, x))
label_node = None
right_labels = [
l
for l in labels
if ((l.bbox[0] + l.bbox[2]) / 2.0)
> ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_labels:
label_node = min(right_labels, key=lambda x: _dist(dec, x))
g.add_edge(
dec.id, target.id, label=(label_node.text if label_node else "分支")
)
ordered = nodes
idx_map = {n.id: i + 1 for i, n in enumerate(ordered)}
cycles = list(nx.simple_cycles(g))
cyc_nodes = {nid for cyc in cycles for nid in cyc}
lines = [f"## Page {page} Procedure"]
for n in ordered:
title = n.text
if n.kind == "decision" and not title.startswith("判定"):
title = f"判定:{title}"
lines.append(f"{idx_map[n.id]}. {title}")
if n.kind == "decision":
for _, dst, data in g.out_edges(n.id, data=True):
if data.get("label") is None:
continue
label = data.get("label") or "分支"
if dst in cyc_nodes:
lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}")
else:
dst_text = g.nodes[dst]["node"].text
lines.append(f"- {label} -> {dst_text}")
page_markdowns.append("\n".join(lines))
debug.append(
{
"page": page,
"nodes": [
{"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)}
for n in nodes
],
"edges": [
{"src": s, "dst": d, "label": data.get("label")}
for s, d, data in g.edges(data=True)
],
}
)
context.flows_detected = len(page_markdowns)
return {"flow_markdowns": page_markdowns, "debug": debug}
+419
View File
@@ -0,0 +1,419 @@
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,
)
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
import csv
from pathlib import Path
from edkb_system.contracts import Context
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
raw = None
for enc in ("utf-8-sig", "utf-8", "gb18030"):
try:
raw = file_path.read_text(encoding=enc)
break
except UnicodeDecodeError:
continue
if raw is None:
raw = file_path.read_text(errors="ignore")
sample = raw[:4096]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
delim = dialect.delimiter
except Exception:
delim = ","
rows = [
r
for r in csv.reader(raw.splitlines(), delimiter=delim)
if any(c.strip() for c in r)
]
table = {
"sheet": "csv",
"headers": rows[0] if rows else [],
"rows": rows[1:] if len(rows) > 1 else [],
}
context.extras["tables_count"] = 1
return table
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
def _soffice_candidates() -> list[str]:
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.xlsx"
errors: list[str] = []
for soffice in _soffice_candidates():
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"xlsx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
if proc.returncode == 0 and output.exists():
return output
stderr = (proc.stderr or "").strip()
errors.append(
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
)
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
f" details: {joined}"
)
def _norm(v) -> str:
return "" if v is None else str(v).strip()
def _trim_trailing_empty(vals: list[str]) -> list[str]:
end = len(vals)
while end > 0 and not vals[end - 1]:
end -= 1
return vals[:end]
def run(input_data: dict, context: Context) -> list[dict]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".xls":
file_path = _convert_xls_to_xlsx(file_path, work_dir)
wb = load_workbook(str(file_path), data_only=True)
tables: list[dict] = []
for ws in wb.worksheets:
rows: list[list[str]] = []
for row in ws.iter_rows(values_only=True):
vals = _trim_trailing_empty([_norm(v) for v in row])
if any(vals):
rows.append(vals)
if not rows:
continue
width = max(len(r) for r in rows)
normalized = [r + [""] * (width - len(r)) for r in rows]
tables.append(
{"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]}
)
context.extras["tables_count"] = len(tables)
return tables
+250
View File
@@ -0,0 +1,250 @@
from __future__ import annotations
import base64
import io
from pathlib import Path
from edkb_system.contracts import Block, Context
def _is_scanned(text_chars: int, pages: int) -> bool:
return text_chars < int(300 * max(pages, 1) / 10)
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
b64 = base64.b64encode(blob).decode("ascii")
return f"data:{content_type};base64,{b64}"
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
x0, y0, x1, y1 = bounds
left = min(x0, x1)
right = max(x0, x1)
top = min(y0, y1)
bottom = max(y0, y1)
return (left, top, right, bottom)
def _page_image_stats(
page_width: float,
page_height: float,
image_boxes: list[tuple[float, float, float, float]],
) -> dict[str, float]:
if page_width <= 0 or page_height <= 0 or not image_boxes:
return {
"count": float(len(image_boxes)),
"largest_ratio": 0.0,
"total_ratio": 0.0,
}
page_area = max(page_width * page_height, 1.0)
largest_ratio = 0.0
total_ratio = 0.0
for raw in image_boxes:
x0, y0, x1, y1 = _normalize_box(raw)
width = max(x1 - x0, 0.0)
height = max(y1 - y0, 0.0)
ratio = min((width * height) / page_area, 1.0)
largest_ratio = max(largest_ratio, ratio)
total_ratio += ratio
return {
"count": float(len(image_boxes)),
"largest_ratio": largest_ratio,
"total_ratio": min(total_ratio, 1.5),
}
def _should_use_page_image_mode(
*,
scan_likely: bool,
text_chars: int,
image_count: int,
largest_ratio: float,
total_ratio: float,
) -> bool:
if scan_likely:
if image_count == 0:
return True
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
return True
if text_chars <= 120 and (
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
):
return True
return False
def _collect_image_boxes(
file_path: Path, page_count: int
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
except Exception:
return {}
out: dict[int, list[tuple[float, float, float, float]]] = {}
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
for page_idx in range(page_count):
page = doc[page_idx]
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_idx + 1] = boxes
except Exception:
return {}
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
return out
def _render_page_png(
file_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
blocks: list[Block] = []
try:
from pypdf import PdfReader
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
text = (p.extract_text() or "").strip()
images: list[dict] = []
if text:
text_chars += len(text)
try:
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
data = getattr(img, "data", None)
if not data:
continue
ext = (getattr(img, "image_format", "") or "").lower()
ct = f"image/{ext}" if ext else "image/png"
images.append({"id": img_idx, "data": data, "content_type": ct})
except Exception:
pass
page_payloads.append({"page": page_idx, "text": text, "images": images})
scan_likely = _is_scanned(text_chars, context.pages)
image_boxes_by_page = _collect_image_boxes(file_path, context.pages)
page_image_mode_pages: list[int] = []
for payload in page_payloads:
page_idx = int(payload["page"])
text = str(payload["text"] or "")
page_images = list(payload["images"])
image_boxes = image_boxes_by_page.get(page_idx, [])
stats = _page_image_stats(1000.0, 1000.0, image_boxes)
use_page_image_mode = _should_use_page_image_mode(
scan_likely=scan_likely,
text_chars=len(text),
image_count=len(page_images) or int(stats["count"]),
largest_ratio=float(stats["largest_ratio"]),
total_ratio=float(stats["total_ratio"]),
)
if text:
blocks.append(
Block(
id=f"pdf-{page_idx}",
page=page_idx,
type="paragraph",
text=text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
)
)
if use_page_image_mode:
rendered = _render_page_png(file_path, page_idx)
if rendered:
blocks.append(
Block(
id=f"pdf-page-{page_idx}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"page_image": True,
},
)
)
context.images += 1
page_image_mode_pages.append(page_idx)
continue
for item in page_images:
blocks.append(
Block(
id=f"pdf-{page_idx}-img-{item['id']}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(
item["data"], str(item["content_type"])
)
},
)
)
context.images += 1
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
context.extras["scan_likely"] = True
if page_image_mode_pages:
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
context.warnings.append(
"pdf page-image mode pages: "
+ ", ".join(str(x) for x in page_image_mode_pages)
)
except Exception as exc:
context.warnings.append(f"PDF parse failed: {exc}")
return blocks
+478
View File
@@ -0,0 +1,478 @@
from __future__ import annotations
import base64
import hashlib
import io
import re
import subprocess
from pathlib import Path
from edkb_system.contracts import Block, Context
def _to_data_uri(blob: bytes, content_type: str) -> str:
return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}"
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pptx",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
output = out_dir / f"{path.stem}.pptx"
if not output.exists():
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
return output
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
return None
if proc.returncode != 0:
return None
output = out_dir / f"{path.stem}.pdf"
return output if output.exists() else None
def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]:
out_dir.mkdir(parents=True, exist_ok=True)
app = None
pres = None
output: dict[int, bytes] = {}
try:
from win32com.client import DispatchEx
app = DispatchEx("PowerPoint.Application")
pres = app.Presentations.Open(str(path), WithWindow=False)
for idx, slide in enumerate(pres.Slides, start=1):
target = out_dir / f"slide_{idx:03d}.png"
slide.Export(str(target), "PNG")
if target.exists():
output[idx] = target.read_bytes()
except Exception:
return {}
finally:
if pres is not None:
try:
pres.Close()
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
return output
def _norm_text(text: str) -> str:
return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip()
def _shape_bbox(shape) -> tuple[float, float, float, float]:
left = float(getattr(shape, "left", 0))
top = float(getattr(shape, "top", 0))
width = float(getattr(shape, "width", 0))
height = float(getattr(shape, "height", 0))
return (left, top, left + width, top + height)
def _image_pixel_size(blob: bytes) -> tuple[int, int]:
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
return int(im.width), int(im.height)
except Exception:
return (0, 0)
def _is_small_decorative_image(
blob: bytes, bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
width_px, height_px = _image_pixel_size(blob)
pixel_area = max(width_px, 0) * max(height_px, 0)
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if (
width_px
and height_px
and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400)
):
return True
if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000:
return True
return False
def _is_dominant_picture(
bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if slide_area <= 0:
return False
return box_area / slide_area >= 0.45
def _table_to_markdown(table) -> str:
rows: list[list[str]] = []
for row in table.rows:
vals = [
" ".join(
p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip()
)
for cell in row.cells
]
vals = [v.strip() for v in vals]
if any(vals):
rows.append(vals)
if not rows:
return ""
width = max(len(r) for r in rows)
norm = [r + [""] * (width - len(r)) for r in rows]
header = norm[0]
body = norm[1:]
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
lines.extend("| " + " | ".join(r) + " |" for r in body)
return "\n".join(lines)
def _render_pdf_page_png(
pdf_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(pdf_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def _crop_rendered_region(
rendered: bytes,
*,
crop_bbox: tuple[float, float, float, float],
slide_width: float,
slide_height: float,
padding: float = 0.03,
) -> bytes | None:
try:
from PIL import Image
with Image.open(io.BytesIO(rendered)) as im:
x0, y0, x1, y1 = crop_bbox
pad_x = slide_width * padding
pad_y = slide_height * padding
x0 = max(0.0, x0 - pad_x)
y0 = max(0.0, y0 - pad_y)
x1 = min(slide_width, x1 + pad_x)
y1 = min(slide_height, y1 + pad_y)
if x1 <= x0 or y1 <= y0:
return None
scale_x = im.width / max(slide_width, 1.0)
scale_y = im.height / max(slide_height, 1.0)
box = (
int(x0 * scale_x),
int(y0 * scale_y),
int(x1 * scale_x),
int(y1 * scale_y),
)
cropped = im.crop(box)
buf = io.BytesIO()
cropped.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
def _union_bboxes(
boxes: list[tuple[float, float, float, float]],
) -> tuple[float, float, float, float] | None:
if not boxes:
return None
x0 = min(b[0] for b in boxes)
y0 = min(b[1] for b in boxes)
x1 = max(b[2] for b in boxes)
y1 = max(b[3] for b in boxes)
return (x0, y0, x1, y1)
def _bbox_overlap_ratio(
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
) -> float:
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
ix0 = max(ax0, bx0)
iy0 = max(ay0, by0)
ix1 = min(ax1, bx1)
iy1 = min(ay1, by1)
if ix1 <= ix0 or iy1 <= iy0:
return 0.0
inter = (ix1 - ix0) * (iy1 - iy0)
area = max((ax1 - ax0) * (ay1 - ay0), 1.0)
return inter / area
def _pick_slide_title(flat_shapes) -> str:
candidates: list[tuple[float, float, str]] = []
for shape in flat_shapes:
if not getattr(shape, "has_text_frame", False):
continue
txt = _norm_text(getattr(shape, "text", ""))
if not txt:
continue
top = float(getattr(shape, "top", 0))
left = float(getattr(shape, "left", 0))
candidates.append((top, left, txt))
if not candidates:
return ""
candidates.sort(key=lambda x: (x[0], x[1]))
preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})")
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if preferred_pat.match(first_line) and top <= 1200000:
return first_line
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if 2 <= len(first_line) <= 30 and top <= 1800000:
return first_line
return candidates[0][2].splitlines()[0].strip()
def _iter_shapes(shapes):
from pptx.enum.shapes import MSO_SHAPE_TYPE
for shape in shapes:
yield shape
if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP:
for child in _iter_shapes(shape.shapes):
yield child
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".ppt":
file_path = _convert_ppt_to_pptx(file_path, work_dir)
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
prs = Presentation(str(file_path))
slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides")
pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir)
context.pages = len(prs.slides)
blocks: list[Block] = []
img_idx = 0
blk_idx = 0
slide_area = float(prs.slide_width) * float(prs.slide_height)
for slide_no, slide in enumerate(prs.slides, start=1):
flat_shapes = list(_iter_shapes(slide.shapes))
title_text = _norm_text(
getattr(getattr(slide.shapes, "title", None), "text", "")
)
if not title_text:
title_text = _pick_slide_title(flat_shapes)
heading_text = f"第{slide_no}页"
if title_text:
heading_text = f"第{slide_no}页 {title_text}"
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-heading-{blk_idx}",
page=slide_no,
type="heading",
text=heading_text,
bbox=(0.0, 0.0, 0.0, 0.0),
)
)
seen_image_hashes: set[str] = set()
dominant_pictures = 0
shape_heavy = 0
flow_boxes: list[tuple[float, float, float, float]] = []
suppress_all_images = title_text == "目录"
for shape in flat_shapes:
try:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
if _is_dominant_picture(bbox, slide_area):
dominant_pictures += 1
elif shape.shape_type in {
MSO_SHAPE_TYPE.AUTO_SHAPE,
MSO_SHAPE_TYPE.LINE,
MSO_SHAPE_TYPE.FREEFORM,
}:
shape_heavy += 1
bbox = _shape_bbox(shape)
mid_x = (bbox[0] + bbox[2]) / 2.0
if (
bbox[2] > bbox[0]
and bbox[3] > bbox[1]
and mid_x >= float(prs.slide_width) * 0.18
):
flow_boxes.append(bbox)
except Exception as exc:
context.warnings.append(f"pptx picture skipped: {exc}")
seen_image_hashes.clear()
render_flow_focus = (
(not suppress_all_images)
and bool(slide_pngs or pdf_path)
and shape_heavy >= 8
and dominant_pictures == 0
)
flow_crop: tuple[float, float, float, float] | None = None
if render_flow_focus:
rendered = slide_pngs.get(slide_no)
if rendered is None and pdf_path is not None:
rendered = _render_pdf_page_png(pdf_path, slide_no)
if rendered:
flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height))
img_idx += 1
blocks.append(
Block(
id=f"pptx-flow-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=flow_crop,
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"flow_focus": True,
"flow_focus_source": "pptx",
"rendered_slide": True,
},
)
)
for shape in flat_shapes:
try:
if getattr(shape, "has_table", False):
table_md = _table_to_markdown(shape.table)
if table_md:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-table-{blk_idx}",
page=slide_no,
type="table",
text=table_md,
bbox=_shape_bbox(shape),
)
)
continue
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
if render_flow_focus or suppress_all_images:
continue
is_dominant = False
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
is_dominant = _is_dominant_picture(bbox, slide_area)
img_idx += 1
ext = (getattr(image, "ext", "png") or "png").lower()
ct = f"image/{'jpeg' if ext == 'jpg' else ext}"
meta: dict[str, object] = {
"data_uri": _to_data_uri(image.blob, ct),
"blob_sha1": blob_hash,
}
if is_dominant:
meta["page_image"] = True
meta["page_image_source"] = "pptx"
blocks.append(
Block(
id=f"pptx-img-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=bbox,
meta=meta,
)
)
continue
if getattr(shape, "has_text_frame", False):
txt = _norm_text(shape.text)
bbox = _shape_bbox(shape)
if not txt or txt == title_text:
continue
if title_text and txt.startswith(title_text):
txt = txt[len(title_text) :].lstrip("\n ::;;,,")
txt = _norm_text(txt)
if not txt:
continue
if re.fullmatch(r"\d+", txt):
continue
if flow_crop is not None and len(txt) <= 28:
continue
if txt and txt != title_text:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-text-{blk_idx}",
page=slide_no,
type="paragraph",
text=txt,
bbox=bbox,
)
)
except Exception as exc:
context.warnings.append(f"pptx shape skipped: {exc}")
context.extras["slides_count"] = len(prs.slides)
return blocks
+97
View File
@@ -0,0 +1,97 @@
from __future__ import annotations
import base64
import io
import re
from edkb_system.contracts import Block, Context
def _decode_data_uri_image(data_uri: str):
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
if not m:
return None
try:
raw = base64.b64decode(m.group(1), validate=False)
except Exception:
return None
try:
import numpy as np
from PIL import Image
with Image.open(io.BytesIO(raw)) as im:
return np.array(im.convert("RGB"))
except Exception:
return None
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
blocks = input_data
try:
from rapidocr_onnxruntime import RapidOCR # type: ignore
except Exception:
context.warnings.append("RapidOCR unavailable; skip OCR")
return blocks
engine = RapidOCR()
out: list[Block] = []
for b in blocks:
out.append(b)
if b.type != "image":
continue
context.images += 1
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is None:
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
continue
try:
result, _ = engine(image_obj)
lines = []
for it in result or []:
if len(it) < 3:
continue
txt = str(it[1]).strip()
conf = float(it[2])
if txt and conf >= min_confidence:
lines.append(txt)
if lines:
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
context.ocr_characters += sum(len(x) for x in lines)
else:
text = "OCR_TEXT: <empty>"
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text=text,
bbox=b.bbox,
)
)
except Exception as exc:
context.warnings.append(f"OCR failed: {exc}")
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
return out
+192
View File
@@ -0,0 +1,192 @@
from __future__ import annotations
import json
import re
from pathlib import Path
from edkb_system.contracts import Context
def _has_doc_meta(text: str) -> bool:
flat = " ".join(text.split())
has_header = bool(
re.search(r"制定部门.+制/修订日期.+页码", flat)
or re.search(r"Created Dept\..+Date.+Page", flat)
)
has_meta = bool(
re.search(r"文件编号.+文件级别.+版本", flat)
or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat)
)
return has_header or has_meta
def _expect_doc_meta(text: str) -> bool:
keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"]
return any(k in text for k in keys)
def _expect_flow_artifacts(text: str) -> bool:
if "作业流程图" not in text:
return False
hints = ["序号", "流程说明", "责任", "相关记录"]
return sum(1 for h in hints if h in text) >= 2
def _expect_related_forms_table(text: str) -> bool:
if "相关表单" not in text:
return False
return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text))
def _has_source_images(out_dir: Path) -> bool:
raw = out_dir / "01_raw_layout.json"
if not raw.exists():
return False
try:
data = json.loads(raw.read_text(encoding="utf-8"))
if isinstance(data, list):
for b in data:
if isinstance(b, dict) and b.get("type") == "image":
return True
except Exception:
return False
return False
def _has_markdown_image_reference(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("data:image/"):
return True
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _has_remote_image_url(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _expect_revision_table(text: str) -> bool:
if "文件修订履历" in text:
return True
hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"]
return sum(1 for h in hint if h in text) >= 4
def _collect_issues(text: str) -> list[dict]:
issues: list[dict] = []
lines = text.splitlines()
num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+")
non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()]
if len(non_empty) >= 2:
l1, s1 = non_empty[0]
l2, s2 = non_empty[1]
if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"):
if not re.match(r"^[一二三四五六七八九十]+、", s2):
issues.append(
{
"code": "title_below_meta",
"line": l1,
"text": f"meta before title: {s1[:80]}",
}
)
for i, ln in enumerate(lines, start=1):
s = ln.strip()
if not s:
continue
if s.startswith("|"):
continue
if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s):
issues.append(
{"code": "inline_numbered_sections", "line": i, "text": s[:180]}
)
if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s):
issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]})
for i in range(1, len(lines) - 1):
if lines[i].strip():
continue
prev = lines[i - 1].strip()
nxt = lines[i + 1].strip()
if num_pat.match(prev) and num_pat.match(nxt):
issues.append(
{
"code": "blank_between_numbered_sections",
"line": i + 1,
"text": f"{prev[:70]} / {nxt[:70]}",
}
)
return issues
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
clean_md = input_data.get("clean_md", "")
checks = {
"has_doc_meta": _has_doc_meta(clean_md),
"has_revision_table": bool(
(re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None)
and re.search(r"\|\s*.*修订章节", clean_md)
and re.search(r"\|\s*版本\b", clean_md)
),
"has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md,
"has_related_forms_table": bool(
re.search(r"\|\s*表单编号\s*\|", clean_md)
and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md)
),
"has_flow_file": (out_dir / "02_flow_procedure.md").exists(),
"has_embedded_images": _has_markdown_image_reference(clean_md),
"has_remote_image_urls": _has_remote_image_url(clean_md),
}
flow_expected = _expect_flow_artifacts(clean_md)
expected = {
"has_doc_meta": _expect_doc_meta(clean_md),
"has_revision_table": _expect_revision_table(clean_md),
"has_flow_table": flow_expected,
"has_related_forms_table": _expect_related_forms_table(clean_md),
"has_flow_file": flow_expected,
"has_embedded_images": _has_source_images(out_dir),
}
failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)]
status = "pass" if not failed_required else "fail"
issues = _collect_issues(clean_md)
if expected["has_embedded_images"] and not checks["has_embedded_images"]:
issues.append(
{
"code": "image_not_embedded",
"line": 0,
"text": "source has image blocks but markdown has no image references",
}
)
if "data:image/" in clean_md:
issues.append(
{
"code": "legacy_base64_image",
"line": 0,
"text": "markdown still contains legacy data:image base64 payload",
}
)
return {
"status": status,
"checks": checks,
"expected": expected,
"failed_required": failed_required,
"issues": issues,
"issue_count": len(issues),
"warnings_count": len(context.warnings),
}
@@ -0,0 +1,23 @@
from __future__ import annotations
from edkb_system.contracts import Chunk, Context
def run(input_data: list[Chunk], context: Context) -> list[Chunk]:
chunks = input_data
if not chunks:
context.warnings.append("quality_gate: no chunks generated")
context.confidence = min(context.confidence, 0.5)
return chunks
short_count = sum(1 for c in chunks if len(c.text.strip()) < 60)
if short_count:
context.warnings.append(f"quality_gate: {short_count} short chunks")
context.confidence = min(context.confidence, 0.8)
unique_texts = len({c.text for c in chunks})
if unique_texts < len(chunks):
context.warnings.append("quality_gate: duplicate chunks detected")
context.confidence = min(context.confidence, 0.75)
return chunks
@@ -0,0 +1,55 @@
from __future__ import annotations
from edkb_system.contracts import Context
COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
def _find_col(headers: list[str], kws: list[str]) -> int | None:
for i, h in enumerate(headers):
s = (h or "").lower()
if any(k.lower() in s for k in kws):
return i
return None
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
hs = [h or "-" for h in headers]
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
for r in rows:
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
out.append("| " + " | ".join(vals) + " |")
return "\n".join(out)
def run(input_data: list[dict] | dict, context: Context) -> str:
tables = input_data if isinstance(input_data, list) else [input_data]
parts: list[str] = []
for t in tables:
headers = [str(x).strip() for x in t.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
cidx = _find_col(headers, COND_KWS)
aidx = _find_col(headers, ACT_KWS)
oidx = _find_col(headers, OWN_KWS)
if cidx is not None and aidx is not None:
for row in rows:
cond = row[cidx] if cidx < len(row) else "满足条件"
act = row[aidx] if aidx < len(row) else "执行处理"
owner = (
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
)
parts.append(
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
)
else:
parts.append(_to_table_md(headers, rows))
parts.append("")
return "\n".join(parts).strip() + "\n"
+249
View File
@@ -0,0 +1,249 @@
from __future__ import annotations
import os
import subprocess
import sys
import threading
import time
import ctypes
from pathlib import Path
def _list_winword_pids() -> set[int]:
if os.name != "nt":
return set()
try:
proc = subprocess.run(
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"],
capture_output=True,
text=True,
check=False,
)
except Exception:
return set()
out: set[int] = set()
for line in (proc.stdout or "").splitlines():
line = line.strip()
if not line or line.startswith("INFO:"):
continue
cols = [part.strip().strip('"') for part in line.split('","')]
if len(cols) < 2:
cols = [part.strip().strip('"') for part in line.split(",")]
if len(cols) < 2:
continue
try:
out.add(int(cols[1]))
except ValueError:
continue
return out
def _kill_winword_pids(pids: set[int]) -> None:
if os.name != "nt":
return
for pid in sorted(pids):
try:
subprocess.run(
["taskkill", "/PID", str(pid), "/F"],
capture_output=True,
text=True,
check=False,
)
except Exception:
continue
def _word_timeout_sec() -> int:
raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip()
try:
value = int(raw)
except ValueError:
value = 120
return max(value, 10)
def _should_accept_word_dialog(
window_title: str, child_texts: list[str], button_texts: list[str]
) -> bool:
text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip())
if not text_blob:
return False
has_repair_prompt = any(
token in text_blob
for token in [
"出现严重错误",
"是否仍要打开",
"serious error",
"do you still want to open",
]
)
if not has_repair_prompt:
return False
return any(
text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower()
for text in button_texts
)
def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]:
stop_event = threading.Event()
if os.name != "nt":
return stop_event, None
def _window_text(user32, hwnd: int) -> str:
length = user32.GetWindowTextLengthW(hwnd)
if length <= 0:
return ""
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(hwnd, buf, length + 1)
return buf.value
def _class_name(user32, hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(256)
user32.GetClassNameW(hwnd, buf, 255)
return buf.value
def _click_yes_if_needed() -> None:
user32 = ctypes.windll.user32
bm_click = 0x00F5
vk_return = 0x0D
wm_keydown = 0x0100
wm_keyup = 0x0101
while not stop_event.is_set():
windows: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_windows(hwnd, lparam):
windows.append(int(hwnd))
return True
user32.EnumWindows(enum_windows, 0)
for hwnd in windows:
title = _window_text(user32, hwnd)
cls = _class_name(user32, hwnd).lower()
if "Microsoft Word" not in title and cls != "#32770":
continue
child_hwnds: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_children(child_hwnd, lparam):
child_hwnds.append(int(child_hwnd))
return True
user32.EnumChildWindows(hwnd, enum_children, 0)
child_texts = [_window_text(user32, child) for child in child_hwnds]
button_hwnds = [
child
for child in child_hwnds
if _class_name(user32, child).lower() == "button"
]
button_texts = [_window_text(user32, child) for child in button_hwnds]
if not _should_accept_word_dialog(title, child_texts, button_texts):
continue
user32.SetForegroundWindow(hwnd)
for child, text in zip(button_hwnds, button_texts):
normalized = text.strip().lower()
if normalized.startswith(("是", "yes")) or "&y" in normalized:
user32.SendMessageW(child, bm_click, 0, 0)
break
else:
user32.PostMessageW(hwnd, wm_keydown, vk_return, 0)
user32.PostMessageW(hwnd, wm_keyup, vk_return, 0)
stop_event.wait(0.5)
thread = threading.Thread(target=_click_yes_if_needed, daemon=True)
thread.start()
return stop_event, thread
def convert_with_word(path: Path, output: Path, file_format: int) -> Path:
timeout = _word_timeout_sec()
before_pids = _list_winword_pids()
cmd = [
sys.executable,
"-m",
"edkb_system.skills.word_bridge",
str(path),
str(output),
str(file_format),
]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
after_pids = _list_winword_pids()
_kill_winword_pids(after_pids - before_pids)
raise RuntimeError(
f"Word conversion timed out after {timeout}s: {path.name}"
) from exc
if proc.returncode != 0:
err = (proc.stderr or proc.stdout or "unknown error").strip()
raise RuntimeError(f"Word conversion failed: {err}")
if not output.exists() or output.stat().st_size <= 0:
raise RuntimeError(f"Word conversion produced no output: {output}")
return output
def _child_main(argv: list[str]) -> int:
if len(argv) != 4:
print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr)
return 2
src = Path(argv[1]).resolve()
out = Path(argv[2]).resolve()
file_format = int(argv[3])
out.parent.mkdir(parents=True, exist_ok=True)
stop_event, watcher = _start_word_dialog_watcher()
word = None
doc = None
try:
from win32com.client import DispatchEx
word = DispatchEx("Word.Application")
word.Visible = False
word.DisplayAlerts = 0
try:
word.Options.SaveNormalPrompt = False
except Exception:
pass
doc = word.Documents.Open(
FileName=str(src),
ReadOnly=True,
AddToRecentFiles=False,
ConfirmConversions=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
doc.SaveAs(str(out), FileFormat=file_format)
finally:
stop_event.set()
if watcher is not None:
watcher.join(timeout=1)
if doc is not None:
try:
doc.Close(False)
except Exception:
pass
if word is not None:
try:
word.Quit()
except Exception:
pass
return 0
if __name__ == "__main__":
raise SystemExit(_child_main(sys.argv))