55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from common import markdown_table, read_json, write_json, write_text
|
|
|
|
|
|
def normalize_spec(spec: Any) -> list[dict[str, Any]]:
|
|
if isinstance(spec, dict):
|
|
tables = spec.get("tables", [])
|
|
elif isinstance(spec, list):
|
|
tables = spec
|
|
else:
|
|
tables = []
|
|
return [item for item in tables if isinstance(item, dict)]
|
|
|
|
|
|
def save_table(out_dir: Path, file_name: str, title: str, headers: list[str], rows: list[list[str]]) -> dict[str, Any]:
|
|
content = "\n".join([f"# {title}", "", markdown_table(headers, rows)])
|
|
path = out_dir / file_name
|
|
write_text(path, content)
|
|
return {
|
|
"title": title,
|
|
"path": str(path),
|
|
"headers": headers,
|
|
"rows": rows,
|
|
}
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--spec", required=True)
|
|
parser.add_argument("--out", required=True)
|
|
args = parser.parse_args()
|
|
|
|
out_dir = Path(args.out).resolve()
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
tables = normalize_spec(read_json(Path(args.spec).resolve()))
|
|
|
|
manifest: list[dict[str, Any]] = []
|
|
for index, table in enumerate(tables, start=1):
|
|
title = table.get("title") or f"表格{index}"
|
|
headers = table.get("headers") or []
|
|
rows = table.get("rows") or []
|
|
file_name = table.get("file_name") or f"table_{index}.md"
|
|
manifest.append(save_table(out_dir, file_name, title, headers, rows))
|
|
|
|
write_json(out_dir / "tables_manifest.json", manifest)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|