150 lines
6.1 KiB
Python
150 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Turn the pinned Kubernetes sources into text records for pretraining.
|
|
|
|
Docs: each English Markdown page becomes one record, with Hugo front matter and shortcodes
|
|
removed. Glossary tooltips keep their term text.
|
|
|
|
OpenAPI: each operation and each object definition becomes one prose record, generated
|
|
from the spec, so every fact comes from the spec and nothing is written by hand.
|
|
|
|
Every record carries its source path, the pinned commit and its license, so attribution
|
|
stays with the text. Run after cloning the sources listed in sources/kubernetes-sources.json.
|
|
"""
|
|
import argparse
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
RESERVED = ("<|pad|>", "<|im_start|>", "<|im_end|>")
|
|
SHORTCODE = re.compile(r"\{\{[<%]\s*(/?)\s*([A-Za-z_][\w-]*)([^>%]*)[>%]\}\}")
|
|
TOOLTIP_TEXT = re.compile(r'text="([^"]*)"')
|
|
METHODS = ("get", "put", "post", "delete", "patch")
|
|
|
|
|
|
def strip_front_matter(text):
|
|
if text.startswith("---"):
|
|
end = text.find("\n---", 3)
|
|
if end != -1:
|
|
return text[end + 4:]
|
|
return text
|
|
|
|
|
|
def clean_markdown(text):
|
|
text = strip_front_matter(text)
|
|
|
|
def replace(match):
|
|
name, args = match.group(2), match.group(3)
|
|
if name == "glossary_tooltip":
|
|
found = TOOLTIP_TEXT.search(args)
|
|
return found.group(1) if found else ""
|
|
return ""
|
|
|
|
text = SHORTCODE.sub(replace, text)
|
|
text = re.sub(r"<br\s*/?>", "\n", text)
|
|
text = re.sub(r"<[^>]+>", " ", text)
|
|
text = html.unescape(text)
|
|
text = "\n".join(re.sub(r"[ \t]+", " ", line).strip() for line in text.splitlines())
|
|
text = re.sub(r"\n{3,}", "\n\n", text)
|
|
return text.strip()
|
|
|
|
|
|
def usable(text, min_words):
|
|
return len(text.split()) >= min_words and not any(token in text for token in RESERVED)
|
|
|
|
|
|
def docs_records(root, commit, min_words):
|
|
base = root / "content" / "en" / "docs"
|
|
for path in sorted(base.rglob("*.md")):
|
|
text = clean_markdown(path.read_text(encoding="utf-8"))
|
|
if usable(text, min_words):
|
|
yield {"text": text, "source": str(path.relative_to(root)), "commit": commit,
|
|
"license": "CC-BY-4.0"}
|
|
|
|
|
|
def describe(parameter):
|
|
required = "required" if parameter.get("required") else "optional"
|
|
location = parameter.get("in", "")
|
|
detail = parameter.get("description", "").strip()
|
|
return f"{parameter.get('name', '')} ({location}, {required})" + (f": {detail}" if detail else "")
|
|
|
|
|
|
def operation_text(path, method, operation):
|
|
summary = (operation.get("summary") or operation.get("description") or "").strip()
|
|
if summary and summary[-1] not in ".!?":
|
|
summary += "."
|
|
lines = [f"{method.upper()} {path} is a Kubernetes API operation. {summary}".strip()]
|
|
if operation.get("operationId"):
|
|
lines.append(f"Its operation ID is {operation['operationId']}.")
|
|
parameters = [describe(p) for p in operation.get("parameters", []) if "name" in p]
|
|
if parameters:
|
|
lines.append("Parameters: " + "; ".join(parameters) + ".")
|
|
for code, response in operation.get("responses", {}).items():
|
|
description = response.get("description", "").strip()
|
|
if description:
|
|
lines.append(f"Response {code}: {description}")
|
|
return " ".join(lines)
|
|
|
|
|
|
def openapi_records(spec_path, commit, sha256, min_words):
|
|
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
|
for path, item in sorted(spec.get("paths", {}).items()):
|
|
for method in METHODS:
|
|
if method in item:
|
|
text = operation_text(path, method, item[method])
|
|
if usable(text, min_words):
|
|
yield {"text": text, "source": f"paths{path}.{method}", "commit": commit,
|
|
"sha256": sha256, "license": "Apache-2.0"}
|
|
for name, definition in sorted(spec.get("definitions", {}).items()):
|
|
# io.k8s.api.apps.v1.Deployment -> "apps/v1 Deployment"
|
|
parts = name.split(".")
|
|
kind = parts[-1]
|
|
group_version = "/".join(parts[-3:-1]) if len(parts) >= 3 else ""
|
|
header = f"{kind} is a Kubernetes object ({group_version})." if group_version else f"{kind}."
|
|
lines = [header, definition.get("description", "").strip()]
|
|
properties = definition.get("properties", {})
|
|
for field, schema in sorted(properties.items()):
|
|
kind_of = schema.get("type") or schema.get("$ref", "").split(".")[-1]
|
|
detail = schema.get("description", "").strip()
|
|
lines.append(f"Field {field} ({kind_of}): {detail}" if detail else f"Field {field} ({kind_of}).")
|
|
text = " ".join(line for line in lines if line)
|
|
if usable(text, min_words):
|
|
yield {"text": text, "source": f"definitions/{name}", "commit": commit,
|
|
"sha256": sha256, "license": "Apache-2.0"}
|
|
|
|
|
|
def write(path, records):
|
|
count = 0
|
|
with path.open("x", encoding="utf-8") as stream:
|
|
for record in records:
|
|
stream.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
count += 1
|
|
return count
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--website", required=True, type=Path)
|
|
parser.add_argument("--website-commit", required=True)
|
|
parser.add_argument("--swagger", required=True, type=Path)
|
|
parser.add_argument("--swagger-commit", required=True)
|
|
parser.add_argument("--swagger-sha256", required=True)
|
|
parser.add_argument("--corpora", type=Path, default=Path("corpora"))
|
|
parser.add_argument("--min-words", type=int, default=20)
|
|
args = parser.parse_args()
|
|
args.corpora.mkdir(parents=True, exist_ok=True)
|
|
docs = args.corpora / "kubernetes-docs.jsonl"
|
|
api = args.corpora / "kubernetes-openapi.jsonl"
|
|
for path in (docs, api):
|
|
if path.exists():
|
|
parser.error(f"refusing to overwrite: {path}")
|
|
n_docs = write(docs, docs_records(args.website, args.website_commit, args.min_words))
|
|
n_api = write(api, openapi_records(args.swagger, args.swagger_commit, args.swagger_sha256,
|
|
args.min_words))
|
|
print(json.dumps({"docs_records": n_docs, "openapi_records": n_api}, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|