Files
2026-05-12 08:16:42 +08:00

168 lines
5.4 KiB
Python

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()