Add Kubernetes docs and OpenAPI text builder with pinned sources
This commit is contained in:
1 parent
b37df2b05a
commit
f67cbce688
3 files changed
+189
No files matched your search
@@ -118,3 +118,21 @@ held-out document removed, matched by identifier. It fails if any held-out ident
|
||||
Known limits: the generated items come from templates, so they test recognition of these
|
||||
phrasings, not general language. Some concept questions will overlap with the Kubernetes docs,
|
||||
so keep those docs out of the training data if you use this set to judge knowledge.
|
||||
|
||||
### Kubernetes text (`sources/kubernetes-sources.json`)
|
||||
|
||||
The pinned sources are the English Kubernetes docs (`kubernetes/website`, CC BY 4.0) and the
|
||||
OpenAPI spec (`kubernetes/kubernetes`, Apache-2.0). Clone them into `sources/raw/` at the commits
|
||||
in the manifest, then run:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/build-k8s-text.py \
|
||||
--website sources/raw/kubernetes-website --website-commit <commit> \
|
||||
--swagger sources/raw/openapi/swagger.json --swagger-commit <commit> \
|
||||
--swagger-sha256 <sha256>
|
||||
```
|
||||
|
||||
This writes `corpora/kubernetes-docs.jsonl` (1,381 pages, about 1.6M words) and
|
||||
`corpora/kubernetes-openapi.jsonl` (1,985 operation and object descriptions, about 0.27M words).
|
||||
Each record keeps its source path, commit and license. Docs are cleaned of front matter, Hugo
|
||||
shortcodes and HTML. OpenAPI prose is generated from the spec, not written by hand.
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"sources": [
|
||||
{
|
||||
"name": "kubernetes-website",
|
||||
"repository": "https://github.com/kubernetes/website",
|
||||
"commit": "f2db56e570a59d1afb0bacabd0f26f6b8538ea91",
|
||||
"paths": ["content/en/docs"],
|
||||
"license": "CC-BY-4.0",
|
||||
"license_file": "LICENSE",
|
||||
"notes": "Markdown with front matter and Hugo shortcodes; strip before use."
|
||||
},
|
||||
{
|
||||
"name": "kubernetes-openapi-swagger",
|
||||
"repository": "https://github.com/kubernetes/kubernetes",
|
||||
"commit": "80d51ceb32d28aa2d3df01ed80a649533add021b",
|
||||
"paths": ["api/openapi-spec/swagger.json"],
|
||||
"license": "Apache-2.0",
|
||||
"sha256": "a5ffd0509edb2be823776fd0432bd480de8d0783038331a8087435c8ac1de66f",
|
||||
"notes": "Swagger 2.0 JSON, 588 paths and 838 definitions. Convert to prose and tables before use."
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user