File size: 10,525 Bytes
1d8c46a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d75da0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8c46a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d75da0
1d8c46a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d75da0
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""Turn crawled raw files into a clean dataset (pages.jsonl + chunks.jsonl).



Inputs : data/raw/*.md (crawled docx), data/files/*.pdf (crawled attachments)

Outputs: data/dataset/pages.jsonl, data/dataset/chunks.jsonl, data/dataset/stats.json

"""

import json
import re
import sys
from pathlib import Path

for _s in (sys.stdout, sys.stderr):
    try:
        _s.reconfigure(encoding="utf-8", errors="replace")
    except Exception:  # noqa: BLE001
        pass

ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "data" / "raw"
FILES = ROOT / "data" / "files"
OUT = ROOT / "data" / "dataset"
TREE = ROOT / "data" / "wiki_tree.json"

FRONTMATTER = re.compile(r"^---\n(.*?)\n---\n", re.S)
FIGURE = re.compile(r"<figure[^>]*>.*?</figure>", re.S)
FIGURE_SRC = re.compile(r'<source\s+name="([^"]+)"')
RESIDUAL_TAG = re.compile(r"</?(?:title|sub-page-list|p|fragment|source|figure)[^>]*/?>", re.S)
HEADING = re.compile(r"^(#{1,6})\s+(.*)$", re.M)
WS3 = re.compile(r"\n{3,}")
SPACES = re.compile(r"[ \t]+\n")

SKIP_TITLES = {"欢迎使用知识库 / Welcome to Wiki", "管理员手册 / Administrator Manual", "成员手册 / Member Manual"}

# Whole branches that are not course material and would only pollute retrieval:
# Feishu's own product manual, the wiki's member/admin handbook, the 高考 recall papers
# that were parked in the same workspace, and the guestbook. Dropping them is recorded
# in the dataset card; nothing from a course is removed.
EXCLUDE_COURSES = {
    "管理员手册 / Administrator Manual",
    "成员手册 / Member Manual",
    "历年考生回忆版新高考卷",
    "期末休息区",
}


def parse_frontmatter(text):
    m = FRONTMATTER.match(text)
    meta = {}
    if m:
        for line in m.group(1).splitlines():
            if ":" in line:
                k, v = line.split(":", 1)
                meta[k.strip()] = v.strip()
        text = text[m.end():]
    return meta, text


def clean_markdown(text):
    text = RESIDUAL_TAG.sub("", text)
    text = FIGURE.sub(lambda m: "[附件: %s]" % (FIGURE_SRC.search(m.group(0)).group(1) if FIGURE_SRC.search(m.group(0)) else "附件"), text)
    text = re.sub(r"<[^>]{1,80}>", "", text)
    text = SPACES.sub("\n", text)
    text = WS3.sub("\n\n", text)
    return text.strip()


def split_sections(text):
    """Split markdown into (heading_path, body) sections."""
    sections = []
    current = [""]
    buf = []
    for line in text.splitlines():
        m = HEADING.match(line)
        if m:
            if buf:
                sections.append((list(current), "\n".join(buf).strip()))
                buf = []
            level = len(m.group(1))
            title = m.group(2).strip()
            current = current[: level - 1] + [title]
        else:
            buf.append(line)
    if buf:
        sections.append((list(current), "\n".join(buf).strip()))
    return [(h, b) for h, b in sections if b]


def chunk_text(text, size=700, overlap=100):
    text = text.strip()
    if len(text) <= size:
        return [text] if text else []
    chunks = []
    start = 0
    while start < len(text):
        end = start + size
        if end < len(text):
            cut = max(text.rfind("\n\n", start, end), text.rfind("\n", start, end), text.rfind("。", start, end))
            if cut > start + size // 2:
                end = cut + 1
        chunks.append(text[start:end].strip())
        if end >= len(text):
            break
        start = max(end - overlap, start + 1)
    return [c for c in chunks if c]


def is_low_information(chunk, title, course, section):
    """True for chunks whose text is nothing but the title/path repeated.



    The wiki stores a heading for every page, and the chunker sometimes keeps only that

    heading, which produces a "chunk" like "3.5➡️3.0 数据库系统 / DataBase System" repeated.

    Those match any query that mentions the course name and push real content down.

    """
    junk = chunk
    for s in (title, course, section or ""):
        for part in str(s).split("/"):
            part = part.strip()
            if len(part) > 3:
                junk = junk.replace(part, "")
    junk = re.sub(r"[\s\-—·・/|*#>\[\]()()。,、::]", "", junk)
    return len(junk) < 20


def pdf_to_text(path):
    try:
        from pypdf import PdfReader
    except ImportError:
        return None
    try:
        reader = PdfReader(str(path))
    except Exception:  # noqa: BLE001
        return None
    pages = []
    for i, page in enumerate(reader.pages):
        try:
            pages.append(page.extract_text() or "")
        except Exception:  # noqa: BLE001
            pages.append("")
    return "\n\n".join(pages).strip()


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    tree = json.load(open(TREE, encoding="utf-8")) if TREE.exists() else []
    meta_by_token = {n.get("obj_token"): n for n in tree}
    meta_by_file = {n.get("file"): n for n in tree if n.get("file")}

    pages, chunks = [], []

    # --- docx pages ---
    for md_path in sorted(RAW.glob("*.md")):
        raw = md_path.read_text(encoding="utf-8", errors="replace")
        meta, body = parse_frontmatter(raw)
        title = meta.get("title") or md_path.stem
        if title in SKIP_TITLES:
            continue
        node = meta_by_file.get(md_path.name) or meta_by_token.get(meta.get("obj_token")) or {}
        path_list = node.get("path") or (meta.get("path", "").split("/") if meta.get("path") else [title])
        course = path_list[0] if path_list else title
        if course in EXCLUDE_COURSES:
            continue
        body = clean_markdown(body)
        if not body:
            continue
        page_id = f"docx::{node.get('node_token') or md_path.stem}"
        pages.append(
            {
                "id": page_id,
                "title": title,
                "course": course,
                "path": "/".join(path_list),
                "url": meta.get("url") or node.get("url") or "",
                "source_type": "docx",
                "obj_token": meta.get("obj_token", ""),
                "n_chars": len(body),
                "text": body,
            }
        )
        for heading, sec in split_sections(body):
            for ci, ctext in enumerate(chunk_text(sec)):
                if len(ctext) < 20 or is_low_information(ctext, title, course, "/".join([h for h in heading if h])):
                    continue
                chunks.append(
                    {
                        "id": f"{page_id}::{len(chunks)}",
                        "page_id": page_id,
                        "title": title,
                        "course": course,
                        "path": "/".join(path_list),
                        "section": "/".join([h for h in heading if h]) or title,
                        "url": meta.get("url") or node.get("url") or "",
                        "source_type": "docx",
                        "n_chars": len(ctext),
                        "text": ctext,
                    }
                )

    # --- pdf attachments ---
    pdf_meta = {n.get("file_path"): n for n in tree if n.get("file_path")}
    for pdf_path in sorted(FILES.glob("*.pdf")):
        rel = str(pdf_path.relative_to(ROOT)).replace("\\", "/")
        node = pdf_meta.get(rel) or {}
        text = pdf_to_text(pdf_path)
        if not text or len(text) < 50:
            continue
        path_list = node.get("path") or [pdf_path.name]
        page_id = f"pdf::{pdf_path.stem}"
        pages.append(
            {
                "id": page_id,
                "title": node.get("title") or pdf_path.name,
                "course": path_list[0] if path_list else "附件",
                "path": "/".join(path_list),
                "url": node.get("url") or "",
                "source_type": "pdf",
                "obj_token": node.get("obj_token", ""),
                "n_chars": len(text),
                "text": text,
            }
        )
        for ctext in chunk_text(text, size=700, overlap=100):
            if len(ctext) < 20 or is_low_information(ctext, pdf_path.name, path_list[0] if path_list else "", pdf_path.name):
                continue
            chunks.append(
                {
                    "id": f"{page_id}::{len(chunks)}",
                    "page_id": page_id,
                    "title": node.get("title") or pdf_path.name,
                    "course": path_list[0] if path_list else "附件",
                    "path": "/".join(path_list),
                    "section": pdf_path.name,
                    "url": node.get("url") or "",
                    "source_type": "pdf",
                    "n_chars": len(ctext),
                    "text": ctext,
                }
            )

    def dump(name, rows):
        p = OUT / name
        with p.open("w", encoding="utf-8") as f:
            for r in rows:
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
        return p

    dump("pages.jsonl", pages)
    dump("chunks.jsonl", chunks)

    # Node tree (flattened: path joined by " / ") for the HF dataset viewer.
    tree_rows = [
        {
            "node_token": n.get("node_token"),
            "title": n.get("title"),
            "obj_type": n.get("obj_type"),
            "path": " / ".join(n.get("path") or []),
            "course": (n.get("path") or [None])[0],
            "url": n.get("url", ""),
            "file": n.get("file", ""),
            "file_path": n.get("file_path", ""),
        }
        for n in tree
        if ((n.get("path") or [None])[0] not in EXCLUDE_COURSES)
    ]
    dump("tree.jsonl", tree_rows)

    stats = {
        "n_pages": len(pages),
        "n_chunks": len(chunks),
        "n_nodes": len(tree_rows),
        "excluded_courses": sorted(EXCLUDE_COURSES),
        "n_chars": sum(p["n_chars"] for p in pages),
        "courses": sorted({p["course"] for p in pages}),
        "source_types": {t: sum(1 for p in pages if p["source_type"] == t) for t in {p["source_type"] for p in pages}},
    }
    (OUT / "stats.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(stats, ensure_ascii=False, indent=2))
    print(f"\n-> {OUT}")


if __name__ == "__main__":
    main()