Files
syops/backend/edkb_system/controller.py
T
2026-08-20 19:37:09 +08:00

1013 lines
34 KiB
Python

"""
edkb_system/controller.py
用途:edkb 单文件清洗编排(intake → loader → OCR → clean → export)。
依赖:edkb_system.skills.*、SystemConfig、common.is_figure_rich_handbook。
逻辑:由 knowledge_cleaning.edkb_adapter / CLI 调用;手册类跳过丢图并强制 OCR。
"""
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, is_figure_rich_handbook
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 _strip_in_memory_images(blocks: list) -> list:
out = []
for b in blocks:
meta = dict(getattr(b, "meta", {}) or {})
if "image" in meta:
meta.pop("image", None)
b = type(b)(
id=b.id,
page=b.page,
type=b.type,
text=b.text,
bbox=b.bbox,
meta=meta,
)
out.append(b)
return out
def _normalize_path_for_match(p: Path | str) -> str:
return str(p).replace("\\", "/")
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
_PDF_TIMEOUT_EXTS = {".pdf"}
# Excel/CSV are fast and in-process; skip spawn timeout wrapper (macOS/gevent safe).
_FAST_PATH_EXTS = {".xlsx", ".xls", ".csv", ".txt", ".md"}
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
raw = str(os.environ.get(name, default)).strip()
try:
value = int(raw)
except ValueError:
value = 0
return value if value > 0 else None
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
"""
按源文件类型选择清洗子进程的最长运行时间。
图文 PDF 的 OCR、版面恢复和分段通常显著慢于 Office 文档;若直接复用全局
时限,大型手册会在内容尚未产出时被误杀。PDF 可用独立环境变量延长时限,
其他格式仍使用全局上限,避免异常任务无限占用 worker。
Args:
file_path: 待清洗源文件路径;仅使用其扩展名进行策略选择。
Returns:
正整数秒数表示启用子进程时限;None 表示该格式不使用 spawn 时限包装。
"""
suffix = str(getattr(file_path, "suffix", "") or "").lower()
if suffix in _FAST_PATH_EXTS:
return None
if suffix in _WORD_TIMEOUT_EXTS:
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
if specific:
return specific
if suffix in _PDF_TIMEOUT_EXTS:
specific = _parse_timeout_env("EDKB_PDF_FILE_TIMEOUT_SEC")
if specific:
return specific
return _parse_timeout_env("EDKB_FILE_TIMEOUT_SEC")
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 _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool:
"""
判断当前文档是否需要跑 OCR。
核心逻辑:PPT 跳过;Word 仅在 pipeline 显式请求时跑;PDF 在扫描/整页图模式
或图文手册(有 image block)时强制跑,以便写入「图中文字」供问答。
Args:
profile: intake 文档画像。
cfg: SystemConfig。
blocks: loader 产出的块。
context: 可选上下文(含 scan_likely / figure_rich_handbook 等 extras)。
Returns:
True 表示应执行 edkb-ocr。
"""
if not blocks or not cfg.ocr.enable:
return False
if profile.file_type in {"ppt", "pptx"}:
return False
pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline
has_image_blocks = any(b.type == "image" for b in blocks)
extras = getattr(context, "extras", {}) or {} if context is not None else {}
# [STEP] 机械设计手册等:只要有图就 OCR,避免只剩正文导致问答丢图信息
if has_image_blocks and extras.get("figure_rich_handbook"):
return True
# Word documents often contain decorative or embedded images. If intake
# did not explicitly request OCR, do not force a slow OCR pass just because
# image blocks exist.
if profile.file_type in {"doc", "docx"} and not pipeline_requests_ocr:
return False
if profile.file_type == "pdf" and not pipeline_requests_ocr:
return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages"))
return pipeline_requests_ocr or has_image_blocks
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(file_path)
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")
figure_rich_handbook = bool(
ctx.extras.get("figure_rich_handbook")
or is_figure_rich_handbook(file_path.name)
)
if figure_rich_handbook:
ctx.extras["figure_rich_handbook"] = True
should_ocr = _should_run_ocr(profile, cfg, blocks, ctx)
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")
blocks = _strip_in_memory_images(blocks)
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"}
)
# [STEP] policy_text/flow 默认丢图;手册类必须保留 image+ocr_text 供问答
suppress_images = False
if (
profile.file_type not in {"ppt", "pptx"}
and not has_figure_anchor
and not figure_rich_handbook
):
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)")
elif figure_rich_handbook:
trace_steps.append("edkb-image-keep(figure_rich_handbook)")
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, keep_figure_ocr=figure_rich_handbook
)
text = _inject_doc_header_from_flow(text, flow_mds)
elif tables is not None:
_announce("table linearize")
t0 = time.perf_counter()
# Excel/CSV 在此按完整原始行组段;不可依赖后续通用 chunk 的字符切分,
# 否则 Dify 段可能在一条表格记录中间断开。
text = table_linearize.run(
tables,
ctx,
table_segment_max_chars=cfg.table.table_segment_max_chars,
)
_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