File size: 7,239 Bytes
1d8c46a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""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()