File size: 11,582 Bytes
9728219 | 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 | """agentdocs.py MODE SRC OUT.json.gz (11-01, tablinum-3 agent domain, research/agentic.md A) - command-line / sysadmin reference ->
dolma docs (id, text, metadata.title) for dolma_chunk.py doc. One doc per heading section, so a passage title reads
"<page> — <section>".
tldr SRC = tldr-pages repo dir; pages/{common,linux,osx,windows,android,freebsd,...}/*.md (English only), CC BY 4.0.
One doc per command: "tldr: <cmd> (<platform>)" + the description and every example with its command line.
info SRC = dir of GNU info text dumps (local /usr/share/info via `info --subnodes`; GFDL manuals). One doc per node.
html SRC = dir of HTML pages (Arch Wiki from the arch-wiki-docs package, GFDL 1.3+; GNU single-page manuals, GFDL).
Title = <title>; sections split at h1-h4; nav / script / style / sidebar / table-of-contents blocks skipped.
Stdlib only (html.parser), so it runs in the beam venv."""
import gzip, json, os, re, sys
from html.parser import HTMLParser
mode, src, dst = sys.argv[1:4]
out = gzip.open(dst, "wt"); n = 0
def put(title, text, did):
global n
text = re.sub(r"[ \t]+", " ", re.sub(r"\n{3,}", "\n\n", text)).strip()
if len(text.split()) >= 12:
out.write(json.dumps({"id": did, "text": text, "metadata": {"title": title}}, ensure_ascii=False) + "\n"); n += 1
if mode == "tldr":
base = os.path.join(src, "pages")
for plat in sorted(os.listdir(base)):
for f in sorted(os.listdir(os.path.join(base, plat))):
if not f.endswith(".md"): continue
md = open(os.path.join(base, plat, f), encoding="utf-8").read()
lines, cur = [], None
for l in md.splitlines():
l = l.rstrip()
if l.startswith("# "): cmd = l[2:].strip()
elif l.startswith("> "): lines.append(re.sub(r"<(https?://[^>]+)>", r"\1", l[2:]))
elif l.startswith("- "): cur = l[2:]
elif l.startswith("`") and cur: lines.append(f"{cur} Command: {l.strip('`')}"); cur = None
put(f"tldr: {f[:-3]} ({plat})", "\n".join(lines), f"tldr/{plat}/{f}")
elif mode == "info": # SRC = dir of `info --output=- --subnodes NAME` dumps (NAME.txt); one doc per info node
for f in sorted(os.listdir(src)):
man = f[:-4]; node, buf = None, []
for l in open(os.path.join(src, f), encoding="utf-8", errors="replace").read().splitlines() + ["File: end, Node: END"]:
m = re.match(r"^File: [^,]+,\s+Node: ([^,]+)", l)
if m:
if node and node != "END": put(f"GNU {man} manual — {node}" if node != "Top" else f"GNU {man} manual", "\n".join(buf), f"info/{man}/{node}")
node, buf = m.group(1).strip(), []
elif not l.startswith("* ") and not re.match(r"^[*=\-.]{3,}$", l.strip()) and l.strip() != "* Menu:":
buf.append(l)
elif mode == "md": # 11-03 SRC = docs tree of .md/.mdx/.rst/.txt (VS Code, PowerShell, Selenium, MCP, Godot, Playwright...);
# env LABEL = source name in the title, env EXCLUDE = regex of paths to skip. One doc per heading section (md #..#### or rst underline).
LABEL = os.environ.get("LABEL", os.path.basename(src.rstrip("/"))); EXC = re.compile(os.environ.get("EXCLUDE", r"$^"))
RST = re.compile(r"^([=\-~^\"'`#*+])\1{2,}\s*$")
for root, dirs, files in os.walk(src):
dirs[:] = sorted(d for d in dirs if not d.startswith((".", "node_modules")))
for f in sorted(files):
if not f.endswith((".md", ".mdx", ".rst", ".markdown")): continue
path = os.path.join(root, f); rel = os.path.relpath(path, src)
if EXC.search(rel): continue
lines = open(path, encoding="utf-8", errors="replace").read().splitlines(); title = None
if lines and lines[0].strip() == "---": # YAML front matter
for j in range(1, min(len(lines), 80)):
m = re.match(r"^title:\s*['\"]?(.+?)['\"]?\s*$", lines[j])
if m and not title: title = m.group(1)
if lines[j].strip() == "---": lines = lines[j + 1:]; break
secs, sec, buf, fence = [], None, [], False
for j, l in enumerate(lines):
if l.lstrip().startswith(("```", "~~~")): fence = not fence; buf.append(l); continue
if fence: buf.append(l); continue
h = re.match(r"^(#{1,4})\s+(.+?)\s*#*\s*$", l)
if not h and j + 1 < len(lines) and l.strip() and RST.match(lines[j + 1]) and len(lines[j + 1].strip()) >= len(l.strip()) - 1:
h = (None, l.strip())
if h:
secs.append((sec, buf)); sec = h[2] if not isinstance(h, tuple) else h[1]; buf = []
sec = re.sub(r"\{#[^}]*\}|<[^>]+>|`", "", sec).strip(); title = title or sec; continue
if RST.match(l) or re.match(r"^\s*(import |export |<!--|-->|\.\. (toctree|image|figure|raw|include|only|meta|_)|:(orphan|github_url):)", l): continue
l = re.sub(r"</?[A-Z][A-Za-z.]*[^>]*>", "", l) # MDX / JSX components
l = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", l) # md links -> text
l = re.sub(r":(ref|doc|class|meth|func|attr|mod):`([^`<]*?)(\s*<[^>]+>)?`", r"\2", l) # rst roles
buf.append(l)
secs.append((sec, buf)); title = title or f.rsplit(".", 1)[0]
for k, (sc, b) in enumerate(secs):
t = f"{LABEL}: {title}" + (f" — {sc}" if sc and sc != title else "")
put(t, "\n".join(b), f"{LABEL}/{rel}#{k}")
elif mode == "openapi": # 11-03 SRC = APIs.guru openapi-directory APIs/ (CC0); one doc per operation, capped per API
import yaml
CAP = int(os.environ.get("CAP", 60))
for root, _, files in os.walk(src):
for f in sorted(files):
if f not in ("openapi.yaml", "swagger.yaml"): continue
try: d = yaml.safe_load(open(os.path.join(root, f), encoding="utf-8", errors="replace"))
except Exception: continue
if not isinstance(d, dict): continue
info = d.get("info") or {}; api = str(info.get("title") or os.path.relpath(root, src)); k = 0
base = (d.get("servers") or [{}])[0].get("url") if d.get("servers") else (d.get("host", "") + d.get("basePath", ""))
for pth, ops in (d.get("paths") or {}).items():
if not isinstance(ops, dict): continue
for meth, op in ops.items():
if meth not in ("get", "post", "put", "patch", "delete") or not isinstance(op, dict) or k >= CAP: continue
ps = [p for p in (op.get("parameters") or []) if isinstance(p, dict) and p.get("name")]
txt = (f"{meth.upper()} {base or ''}{pth}\n{op.get('summary') or ''}\n{str(op.get('description') or '')[:1500]}\n"
+ ("Parameters: " + "; ".join(f"{p['name']} ({p.get('in','')}{', required' if p.get('required') else ''}): {str(p.get('description') or '')[:200]}" for p in ps[:20]) if ps else ""))
put(f"OpenAPI: {api} — {meth.upper()} {pth}", txt, f"openapi/{os.path.relpath(root, src)}/{meth}{pth}"); k += 1
elif mode == "rosetta": # 11-03 SRC = RosettaCodeData Task/ (rosettacode.org content, GFDL 1.3); task text once + one doc per
# (task, language) for common languages: "<task> (<lang>)" = first 600 chars of the task + up to 2 solutions (<= 4000 chars)
LANGS = {"Python", "JavaScript", "C", "C++", "Java", "Go", "Rust", "Julia", "R", "Haskell", "UNIX-Shell", "Bash", "PowerShell", "SQL",
"Fortran", "Ruby", "Perl", "Lua", "MATLAB", "Octave", "C-sharp", "Kotlin", "Swift", "TypeScript", "Scala", "PHP", "Nim", "Zig",
"Mathematica", "Wolfram-Language", "Common-Lisp", "Racket", "OCaml", "F-Sharp", "Erlang", "Elixir", "Dart", "AWK", "jq"}
for task in sorted(os.listdir(src)):
td = os.path.join(src, task)
if not os.path.isdir(td): continue
try: desc = open(os.path.join(td, "00-TASK.txt"), encoding="utf-8", errors="replace").read()
except OSError: continue
desc = re.sub(r"\[\[(?:[^\]|]*\|)?([^\]]*)\]\]", r"\1", desc); name = task.replace("-", " ")
put(f"Rosetta Code: {name}", desc[:3000], f"rosetta/{task}")
for lang in sorted(os.listdir(td)):
ld = os.path.join(td, lang)
if lang not in LANGS or not os.path.isdir(ld): continue
code = ""
for f in sorted(os.listdir(ld))[:2]:
try: code += open(os.path.join(ld, f), encoding="utf-8", errors="replace").read()[:2500] + "\n\n"
except (OSError, IsADirectoryError): pass
if code.strip(): put(f"Rosetta Code: {name} ({lang.replace('-sharp', '#').replace('-', ' ')})", desc[:600] + "\n\nSolution:\n" + code[:4000], f"rosetta/{task}/{lang}")
elif mode == "html":
SKIP = {"script", "style", "nav", "header", "footer", "noscript"}
SKIP_TOK = {"toc", "navbox", "catlinks", "printfooter", "mw-jump-link", "noprint", "sidebar", "navigation", "nav-panel", "mw-editsection",
"vector-toc", "mw-table-of-contents-container"} # whole class / id tokens only ("vector-toc-available" on <html> hid every Arch page)
class P(HTMLParser):
def __init__(s):
super().__init__(); s.mw = False; s.title = ""; s.sec = ""; s.buf = []; s.secs = []; s.skip = 0; s.stack = []; s.in_title = False; s.in_h = False; s.h = []
def handle_starttag(s, tag, attrs):
a = dict(attrs); toks = set((a.get("class") or "").split()) | {a.get("id") or ""}
hide = tag in SKIP or bool(toks & SKIP_TOK)
if s.mw and "mw-content-text" in toks: hide = -1 # MediaWiki page: only the article body is read
if tag not in ("br", "img", "hr", "meta", "link", "input", "wbr"):
s.stack.append(hide); s.skip += hide
if tag == "title": s.in_title = True
if tag in ("h1", "h2", "h3", "h4") and not s.skip:
s.secs.append((s.sec, "".join(s.buf))); s.buf = []; s.in_h = True; s.h = []
if tag in ("p", "li", "pre", "tr", "div", "dd", "dt", "br") and not s.skip: s.buf.append("\n")
def handle_endtag(s, tag):
if tag == "title": s.in_title = False
if tag in ("h1", "h2", "h3", "h4") and s.in_h:
s.in_h = False; s.sec = re.sub(r"\s+", " ", "".join(s.h)).replace("[edit]", "").strip()
if tag not in ("br", "img", "hr", "meta", "link", "input", "wbr") and s.stack:
s.skip -= s.stack.pop()
def handle_data(s, d):
if s.in_title: s.title += d
elif s.skip: return
elif s.in_h: s.h.append(d)
else: s.buf.append(d)
for root, _, files in os.walk(src):
for f in sorted(files):
if not f.endswith(".html"): continue
html = open(os.path.join(root, f), encoding="utf-8", errors="replace").read(); p = P()
if 'id="mw-content-text"' in html: p.mw = True; p.skip = 1 # hidden until the article body opens
p.feed(html); p.secs.append((p.sec, "".join(p.buf)))
title = re.sub(r"\s*[-–|]\s*(ArchWiki|GNU.*)$", "", re.sub(r"\s+", " ", p.title)).strip() or f[:-5]
for k, (sec, text) in enumerate(p.secs):
put(f"{title} — {sec}" if sec and sec != title else title, text, f"{os.path.relpath(os.path.join(root, f), src)}#{k}")
out.close(); print(mode, n, "docs", file=sys.stderr)
|