"""Download non-docx wiki nodes (PDF attachments etc.) into data/files.""" import json import os import re import subprocess import sys import time from pathlib import Path for _s in (sys.stdout, sys.stderr): try: _s.reconfigure(encoding="utf-8", errors="replace") except Exception: # noqa: BLE001 pass IS_WIN = os.name == "nt" BASE = [str(Path(os.environ.get("APPDATA", "")) / "npm" / "lark-cli.cmd")] if IS_WIN else ["lark-cli"] def run(args): proc = subprocess.run( BASE + args + ["--json"], capture_output=True, text=True, encoding="utf-8", errors="replace", shell=IS_WIN, ) idx = (proc.stdout or "").find("{") if idx < 0: return None return json.loads(proc.stdout[idx:]) def safe(name): return re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", name).strip()[:100] or "file" def main(): tree = json.load(open("data/wiki_tree.json", encoding="utf-8")) out_dir = Path("data/files") out_dir.mkdir(parents=True, exist_ok=True) ok = fail = 0 for node in tree: if node.get("obj_type") != "file" or not node.get("obj_token"): continue title = node.get("title") or node["obj_token"] ext = Path(title).suffix or ".bin" target = f"data/files/{safe(Path(title).stem or title)}{ext}" res = run(["drive", "+download", "--file-token", node["obj_token"], "--output", target, "--overwrite"]) if res and res.get("ok"): node["file_path"] = target print(f"[ok] {title} -> {target}") ok += 1 else: err = (res or {}).get("error", {}) node["download_error"] = json.dumps(err, ensure_ascii=False) print(f"[fail] {title}: {err.get('message', res)}") fail += 1 time.sleep(0.3) Path("data/wiki_tree.json").write_text( json.dumps(tree, ensure_ascii=False, indent=2), encoding="utf-8" ) print(f"downloaded={ok} failed={fail}") if __name__ == "__main__": main()