Download scripts/crawl_wiki.py from NoahIsARider/SCUT-SS: direct link, hf CLI and curl.
- Browser
- Download file 7.24 kB
-
https://huggingface.co/datasets/NoahIsARider/SCUT-SS/resolve/main/scripts/crawl_wiki.py
- Command line
-
hf download hf://datasets/NoahIsARider/SCUT-SS/scripts/crawl_wiki.py
-
curl -L -o crawl_wiki.py https://huggingface.co/datasets/NoahIsARider/SCUT-SS/resolve/main/scripts/crawl_wiki.py
7.24 kB
| """Crawl a Lark wiki space into local raw files (markdown + metadata). | |
| Usage: | |
| python scripts/crawl_wiki.py [--space-id <id>] [--root <node_token>] [--out data/raw] | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| for _stream in (sys.stdout, sys.stderr): | |
| try: | |
| _stream.reconfigure(encoding="utf-8", errors="replace") | |
| except Exception: # noqa: BLE001 | |
| pass | |
| DEFAULT_SPACE_ID = "7351449686093365276" | |
| DEFAULT_ROOT = "TH9BwldF0iZ7qCkxC24cQnjinsc" # wiki node from the shared URL | |
| IS_WIN = os.name == "nt" | |
| def _base_cmd(): | |
| """Resolve the lark-cli launcher (on Windows npm ships .cmd/.ps1 shims).""" | |
| if IS_WIN: | |
| npm = Path(os.environ.get("APPDATA", "")) / "npm" / "lark-cli.cmd" | |
| if npm.exists(): | |
| return [str(npm)] | |
| for name in ("lark-cli.cmd", "lark-cli.exe"): | |
| which = _which(name) | |
| if which: | |
| return [which] | |
| return ["lark-cli"] | |
| def _which(name): | |
| from shutil import which as _w | |
| return _w(name) | |
| def cli(args, retries=4): | |
| """Run lark-cli, return data envelope. Strips non-JSON progress lines.""" | |
| base = _base_cmd() | |
| last_err = None | |
| for attempt in range(retries): | |
| proc = subprocess.run( | |
| base + args + ["--json"], | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| shell=IS_WIN, | |
| ) | |
| out = proc.stdout or "" | |
| idx = out.find("{") | |
| if idx >= 0: | |
| try: | |
| data = json.loads(out[idx:]) | |
| except json.JSONDecodeError as exc: | |
| last_err = f"bad json: {exc}: {out[:200]}" | |
| time.sleep(1 + attempt) | |
| continue | |
| if data.get("ok"): | |
| return data.get("data", {}) | |
| err = data.get("error", {}) | |
| subtype = err.get("subtype", "") | |
| if subtype == "rate_limit" or err.get("code") == 99991400: | |
| time.sleep(2 ** attempt) | |
| continue | |
| last_err = json.dumps(err, ensure_ascii=False) | |
| if subtype in ("permission_denied", "not_found"): | |
| return {"__error__": last_err} | |
| time.sleep(1 + attempt) | |
| continue | |
| last_err = f"no json output: {out[:200]} {(proc.stderr or '')[:200]}" | |
| time.sleep(1 + attempt) | |
| raise RuntimeError(f"lark-cli {' '.join(args)} failed: {last_err}") | |
| def slugify(title, used): | |
| base = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", (title or "untitled").strip()) | |
| base = re.sub(r"\s+", " ", base)[:80] or "untitled" | |
| name = base | |
| n = 2 | |
| while name in used: | |
| name = f"{base}_{n}" | |
| n += 1 | |
| used.add(name) | |
| return name | |
| def list_children(space_id, parent=None): | |
| args = ["wiki", "+node-list", "--space-id", space_id, "--page-size", "50", "--page-all", "--page-limit", "0"] | |
| if parent: | |
| args += ["--parent-node-token", parent] | |
| data = cli(args) | |
| if "__error__" in data: | |
| return [] | |
| return data.get("nodes", []) or [] | |
| def fetch_docx(obj_token): | |
| data = cli( | |
| [ | |
| "docs", | |
| "+fetch", | |
| "--doc", | |
| obj_token, | |
| "--scope", | |
| "full", | |
| "--doc-format", | |
| "markdown", | |
| ] | |
| ) | |
| if "__error__" in data: | |
| return None, data["__error__"] | |
| doc = data.get("document", {}) | |
| return doc.get("content", ""), doc.get("revision_id") | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--space-id", default=DEFAULT_SPACE_ID) | |
| ap.add_argument("--root", default=DEFAULT_ROOT, help="root wiki node token") | |
| ap.add_argument("--out", default="data/raw") | |
| args = ap.parse_args() | |
| out_dir = Path(args.out) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| # Root node metadata (the node referenced by the shared URL). | |
| node_index = [] | |
| try: | |
| root_info = cli(["wiki", "+node-get", "--node-token", args.root]) | |
| node_index.append( | |
| { | |
| "node_token": args.root, | |
| "obj_token": root_info.get("obj_token"), | |
| "obj_type": root_info.get("obj_type"), | |
| "title": root_info.get("title"), | |
| "parent_node_token": root_info.get("parent_node_token", ""), | |
| "space_id": root_info.get("space_id"), | |
| "path": [root_info.get("title", "")], | |
| "url": f"https://a1npn29y3xu.feishu.cn/wiki/{args.root}", | |
| } | |
| ) | |
| except Exception as exc: # noqa: BLE001 | |
| print(f"[warn] root node-get failed: {exc}", file=sys.stderr) | |
| # BFS over the tree. | |
| queue = [("", None)] # (parent_node_token, path list) | |
| used_names = set() | |
| total = 0 | |
| while queue: | |
| parent, path = queue.pop(0) | |
| children = list_children(args.space_id, parent or None) | |
| for node in children: | |
| title = node.get("title", "") | |
| node_path = (path or []) + [title] | |
| entry = { | |
| "node_token": node.get("node_token"), | |
| "obj_token": node.get("obj_token"), | |
| "obj_type": node.get("obj_type"), | |
| "title": title, | |
| "parent_node_token": node.get("parent_node_token", ""), | |
| "space_id": node.get("space_id"), | |
| "has_child": node.get("has_child", False), | |
| "path": node_path, | |
| "url": f"https://a1npn29y3xu.feishu.cn/wiki/{node.get('node_token')}", | |
| } | |
| node_index.append(entry) | |
| total += 1 | |
| print(f"[tree] {'/'.join(node_path)} ({node.get('obj_type')})") | |
| if node.get("has_child"): | |
| queue.append((node.get("node_token"), node_path)) | |
| # Fetch content for every docx. | |
| fetched = 0 | |
| for entry in node_index: | |
| if entry["obj_type"] != "docx" or not entry.get("obj_token"): | |
| continue | |
| content, rev_or_err = fetch_docx(entry["obj_token"]) | |
| if content is None: | |
| entry["fetch_error"] = rev_or_err | |
| print(f"[skip] {entry['title']}: {rev_or_err}", file=sys.stderr) | |
| continue | |
| name = slugify(entry["title"], used_names) | |
| entry["file"] = f"{name}.md" | |
| md_path = out_dir / entry["file"] | |
| header = ( | |
| f"---\ntitle: {entry['title']}\n" | |
| f"path: {'/'.join(entry['path'])}\n" | |
| f"url: {entry['url']}\n" | |
| f"obj_token: {entry['obj_token']}\n---\n\n" | |
| ) | |
| md_path.write_text(header + content, encoding="utf-8") | |
| fetched += 1 | |
| print(f"[doc] {entry['title']} ({len(content)} chars)") | |
| index_path = Path(args.out).parent / "wiki_tree.json" | |
| index_path.write_text( | |
| json.dumps(node_index, ensure_ascii=False, indent=2), encoding="utf-8" | |
| ) | |
| print(f"\nDone. nodes={total + 1} docx_fetched={fetched} -> {out_dir} / {index_path}") | |
| if __name__ == "__main__": | |
| main() | |