Files
kuberdata/scripts/build-ops-docs-text.py
T

95 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Turn the pinned deployment docs into one text corpus for pretraining.
Reads sources/deployment-docs-sources.json and cleans every .md and .rst file under each
listed path. Markdown loses front matter, Hugo shortcodes and HTML tags. reStructuredText
loses directive lines, label targets and heading underlines, and keeps directive bodies.
Each record carries its project, source path, pinned commit and license.
"""
import argparse
import html
import json
import re
import sys
from pathlib import Path
RESERVED = ("<|pad|>", "<|im_start|>", "<|im_end|>")
SHORTCODE = re.compile(r"\{\{[<%].*?[>%]\}\}", re.S)
TAG = re.compile(r"<[^>]+>")
RST_DIRECTIVE = re.compile(r"^\s*\.\.\s+[\w:-]+::.*$")
RST_LABEL = re.compile(r"^\s*\.\.\s+_[^:]+:\s*$")
RST_COMMENT = re.compile(r"^\s*\.\.\s.*$")
RST_UNDERLINE = re.compile(r"^([=\-~^\"'`#*+_:])\1{2,}\s*$")
RST_ROLE = re.compile(r":[\w:-]+:`([^`]*)`")
def clean_markdown(text):
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
text = text[end + 4:]
text = SHORTCODE.sub("", text)
text = TAG.sub(" ", text)
return html.unescape(text)
def clean_rst(text):
lines = []
for line in text.splitlines():
if RST_LABEL.match(line) or (RST_COMMENT.match(line) and not RST_DIRECTIVE.match(line)):
continue
if RST_DIRECTIVE.match(line) or RST_UNDERLINE.match(line.strip()):
continue
lines.append(RST_ROLE.sub(r"\1", line))
return "\n".join(lines)
def tidy(text):
text = "\n".join(re.sub(r"[ \t]+", " ", line).rstrip() for line in text.splitlines())
return re.sub(r"\n{3,}", "\n\n", text).strip()
def records(root, source, min_words):
for relative in source["paths"]:
base = root / relative
for path in sorted(base.rglob("*")):
if path.suffix not in (".md", ".rst") or not path.is_file():
continue
raw = path.read_text(encoding="utf-8", errors="replace")
text = tidy(clean_markdown(raw) if path.suffix == ".md" else clean_rst(raw))
if len(text.split()) < min_words or any(token in text for token in RESERVED):
continue
yield {"text": text, "project": source["name"],
"source": str(path.relative_to(root)), "commit": source["commit"],
"license": source["license"]}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--raw", type=Path, default=Path("sources/raw"))
parser.add_argument("--manifest", type=Path, default=Path("sources/deployment-docs-sources.json"))
parser.add_argument("--output-file", type=Path, default=Path("corpora/deployment-docs.jsonl"))
parser.add_argument("--min-words", type=int, default=20)
args = parser.parse_args()
if args.output_file.exists():
parser.error(f"refusing to overwrite: {args.output_file}")
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
counts = {}
args.output_file.parent.mkdir(parents=True, exist_ok=True)
with args.output_file.open("x", encoding="utf-8") as out:
for source in manifest["sources"]:
root = args.raw / source["name"]
if not root.is_dir():
parser.error(f"missing clone: {root}")
written = 0
for record in records(root, source, args.min_words):
out.write(json.dumps(record, ensure_ascii=False) + "\n")
written += 1
counts[source["name"]] = written
print(json.dumps(counts, indent=2))
print(f"total records: {sum(counts.values())}")
if __name__ == "__main__":
sys.exit(main())