SCUT-SS / scripts /build_dataset.py
NoahIsARider's picture
SCUT-SS: drop 41 heading-only chunks and the non-course branches; 2386 chunks, 113 pages
0d75da0 verified
Raw History Blame Contribute Delete
10.5 kB
"""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()