| |
| """Build the mash finetune dataset: (mangled | natural-language) -> correct command. |
| |
| Sources, in order of quality: |
| 1. Your own accepted fixes from ~/.fash/events.jsonl (kind=fix/args with a chosen |
| command) — real human pairs, mixed in automatically. |
| 2. tldr-pages (github.com/tldr-pages/tldr, CC-BY-4.0): canonical example |
| invocations for ~3000 commands, with per-example descriptions. Descriptions |
| become natural-language -> command pairs; the commands get synthetically |
| mangled into typo -> command pairs. |
| |
| Mangling taxonomy (mirrors how commands really break — cf. thefuck's rules): |
| transposed chars (gti status), dropped chars (grp), adjacent-key typos |
| (gir status), doubled chars, single/double dash confusion (-help / --l), |
| merged words (cd.. / gitpush), and stripped quotes. |
| |
| Output: train/valid/test .jsonl in mlx-lm chat format, ready for `mlx_lm.lora`. |
| |
| Usage: |
| uv run python training/build_dataset.py --out training/data |
| uv run python training/build_dataset.py --out training/data --max-pairs 20000 --no-events |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import io |
| import json |
| import random |
| import re |
| import sys |
| import urllib.request |
| import zipfile |
| from pathlib import Path |
|
|
| |
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
| from fash.llm.prompts import local_context_block |
|
|
| SYSTEM_PROMPT = "Return the shell command the user most likely wants. Reply with the command only." |
|
|
| TLDR_ZIP_URL = "https://github.com/tldr-pages/tldr/archive/refs/heads/main.zip" |
| TLDR_SECTIONS = ("pages/common/", "pages/osx/", "pages/linux/") |
| EVENTS_PATH = Path("~/.fash/events.jsonl").expanduser() |
|
|
| |
|
|
| _EXAMPLE_RE = re.compile(r"^- (?P<desc>.+?):\s*$") |
| _CODE_RE = re.compile(r"^`(?P<cmd>.+)`\s*$") |
| _PLACEHOLDER_RE = re.compile(r"\{\{(.+?)\}\}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| FILE_SCENARIOS = [ |
| ("settings", ["settings.json", "settings.toml", "settings.yaml", "settings.ini"]), |
| ("config", ["config.yaml", "config.json", "config.toml"]), |
| ("notes", ["notes.txt", "notes.md"]), |
| ("readme", ["README.md", "README.rst", "readme.txt"]), |
| ("log", ["app.log", "server.log", "debug.log"]), |
| ("deploy script", ["deploy.sh", "deploy.py"]), |
| ("data", ["data.csv", "data.json"]), |
| ("backup", ["backup.tar.gz", "backup.zip"]), |
| ("env", [".env", ".env.local", ".env.production"]), |
| ] |
| DIR_SCENARIOS = [ |
| ("source", ["./src"]), |
| ("build", ["./build", "./dist"]), |
| ("project", ["~/projects/demo"]), |
| ("downloads", ["~/Downloads"]), |
| ("temp", ["/tmp/scratch"]), |
| ] |
|
|
| LISTING_DISTRACTORS = [ |
| "main.py", "package.json", "Makefile", ".gitignore", "src/", "tests/", |
| "index.ts", "Dockerfile", "pyproject.toml", "LICENSE", "app.py", |
| "utils.py", ".git/", "docs/", "scripts/", "requirements.txt", |
| ] |
| CWD_POOL = ["~/projects/demo", "~/work/api", "~/code/webapp", "/opt/services/worker", "~/dev/tool"] |
|
|
| _FILE_PLACEHOLDER_RE = re.compile(r"path/to/.*file|filename|file", re.I) |
| _DIR_PLACEHOLDER_RE = re.compile(r"path/to/.*dir|directory|folder", re.I) |
|
|
| _PLACEHOLDER_VALUES = [ |
| (re.compile(r"branch", re.I), "main"), |
| (re.compile(r"remote", re.I), "origin"), |
| (re.compile(r"url|link", re.I), "https://example.com"), |
| (re.compile(r"package|module|library", re.I), "requests"), |
| (re.compile(r"port", re.I), "8080"), |
| (re.compile(r"pid|process_id", re.I), "12345"), |
| (re.compile(r"user(name)?", re.I), "alice"), |
| (re.compile(r"host|server|ip", re.I), "example.com"), |
| (re.compile(r"pattern|regex|search_term|query", re.I), "TODO"), |
| (re.compile(r"message|commit", re.I), '"update readme"'), |
| (re.compile(r"image", re.I), "ubuntu"), |
| (re.compile(r"container", re.I), "web"), |
| (re.compile(r"version|tag", re.I), "1.2.0"), |
| (re.compile(r"count|number|n\b", re.I), "5"), |
| (re.compile(r"name", re.I), "demo"), |
| ] |
|
|
|
|
| def _fill_static(inner: str) -> str: |
| for pattern, value in _PLACEHOLDER_VALUES: |
| if pattern.search(inner): |
| return value |
| |
| token = inner.strip().split("/")[-1] or "value" |
| return re.sub(r"[^A-Za-z0-9._-]", "", token) or "value" |
|
|
|
|
| _GENERIC_FILE_RE = re.compile(r"\b(?:a|the)\s+(?:specific|specified|given|particular)\s+files?\b|\ba file\b", re.I) |
| _GENERIC_DIR_RE = re.compile( |
| r"\b(?:a|the)\s+(?:specific|specified|given|particular)\s+(?:directory|folder)\b|\ba (?:directory|folder)\b", re.I |
| ) |
|
|
|
|
| def _pick_scenario(scenarios: list, hints: str, rng: random.Random) -> tuple[str, list[str]]: |
| """Prefer the scenario the example already talks about ('config', 'log', …).""" |
| for noun, variants in scenarios: |
| if noun.split()[0] in hints: |
| return noun, variants |
| return rng.choice(scenarios) |
|
|
|
|
| def make_listing(must_contain: list[str], rng: random.Random) -> list[str]: |
| """A plausible cwd listing containing the target entries plus distractors. |
| |
| Distractors never include confusable siblings of the targets, so exactly |
| one 'settings.*' (etc.) exists and the model must use the one that's there. |
| """ |
| entries = set(must_contain) |
| entries.update(rng.sample(LISTING_DISTRACTORS, rng.randint(4, 8))) |
| return sorted(entries, key=str.lower) |
|
|
|
|
| def fill_example(description: str, command_template: str, rng: random.Random) -> tuple[str, str, str]: |
| """Fill placeholders with a concrete scenario; rewrite the description to |
| match; return a context header grounding the choice in a directory listing. |
| |
| 'Open a specific file:' + `joe {{path/to/file}}` -> |
| ('Open the settings file:', 'joe settings.toml', |
| 'cwd: ~/work/api\\nfiles: .git/ Makefile settings.toml src/') |
| """ |
| hints = f"{description} {command_template}".lower() |
| file_noun, file_variants = _pick_scenario(FILE_SCENARIOS, hints, rng) |
| file_value = rng.choice(file_variants) |
| dir_noun, dir_variants = _pick_scenario(DIR_SCENARIOS, hints, rng) |
| dir_value = rng.choice(dir_variants) |
| used = {"file": False, "dir": False} |
|
|
| typed_files: list[str] = [] |
|
|
| def _fill(match: re.Match) -> str: |
| inner = match.group(1).split("|")[0] |
| if _DIR_PLACEHOLDER_RE.search(inner): |
| used["dir"] = True |
| return dir_value |
| if _FILE_PLACEHOLDER_RE.search(inner): |
| base = inner.strip().split("/")[-1] |
| |
| |
| if re.search(r"\.[A-Za-z0-9]{1,6}$", base): |
| cleaned = re.sub(r"[^A-Za-z0-9._-]", "", base) |
| typed_files.append(cleaned) |
| return cleaned |
| used["file"] = True |
| return file_value |
| return _fill_static(inner) |
|
|
| command = _PLACEHOLDER_RE.sub(_fill, command_template).strip() |
| context = "" |
| targets: list[str] = [] |
| if used["file"]: |
| description = _GENERIC_FILE_RE.sub(f"the {file_noun} file", description) |
| targets.append(file_value) |
| targets.extend(typed_files) |
| if used["dir"]: |
| description = _GENERIC_DIR_RE.sub(f"the {dir_noun} directory", description) |
| if dir_value.startswith("./"): |
| targets.append(dir_value[2:] + "/") |
| if targets: |
| context = local_context_block(rng.choice(CWD_POOL), make_listing(targets, rng)) |
| return description, command, context |
|
|
|
|
| def parse_tldr_page(text: str) -> list[tuple[str, str]]: |
| """Return (description, command_template) pairs from one tldr page body. |
| |
| Placeholders are left intact — fill_example() resolves them per example so |
| the description and the filled command stay coherent. |
| """ |
| pairs: list[tuple[str, str]] = [] |
| description = "" |
| for line in text.splitlines(): |
| described = _EXAMPLE_RE.match(line) |
| if described: |
| description = described.group("desc").strip() |
| continue |
| code = _CODE_RE.match(line) |
| if code: |
| command = code.group("cmd").strip() |
| if command and len(command) <= 160 and not command.startswith("#"): |
| pairs.append((description, command)) |
| description = "" |
| return pairs |
|
|
|
|
| def load_tldr_pairs(cache_dir: Path) -> list[tuple[str, str]]: |
| cache_dir.mkdir(parents=True, exist_ok=True) |
| zip_path = cache_dir / "tldr-main.zip" |
| if zip_path.exists() and not zipfile.is_zipfile(zip_path): |
| print("cached tldr zip is corrupt (interrupted download?) — refetching") |
| zip_path.unlink() |
| if not zip_path.exists(): |
| print(f"downloading tldr-pages ({TLDR_ZIP_URL}) …") |
| partial = zip_path.with_suffix(".part") |
| with urllib.request.urlopen(TLDR_ZIP_URL, timeout=120) as response: |
| partial.write_bytes(response.read()) |
| if not zipfile.is_zipfile(partial): |
| partial.unlink(missing_ok=True) |
| raise SystemExit("downloaded tldr archive is not a valid zip — try again") |
| partial.rename(zip_path) |
| pairs: list[tuple[str, str]] = [] |
| with zipfile.ZipFile(io.BytesIO(zip_path.read_bytes())) as archive: |
| for name in archive.namelist(): |
| if not name.endswith(".md"): |
| continue |
| if not any(section in name for section in TLDR_SECTIONS): |
| continue |
| pairs.extend(parse_tldr_page(archive.read(name).decode("utf-8", errors="replace"))) |
| return pairs |
|
|
|
|
| |
|
|
| _STOPWORDS = {"a", "an", "the", "your", "specific", "given", "particular", "certain", "currently"} |
| _VERB_SWAPS = [ |
| (re.compile(r"^display\b"), "show"), |
| (re.compile(r"^print\b"), "show"), |
| (re.compile(r"^view\b"), "show"), |
| (re.compile(r"^remove\b"), "delete"), |
| (re.compile(r"^execute\b"), "run"), |
| ] |
|
|
|
|
| def casualize(description: str, rng: random.Random) -> list[str]: |
| """Terse request variants of a tldr description — how people actually type. |
| |
| 'Commit staged files to the repository with a message:' -> |
| ['commit staged files with message', 'commit staged files'] |
| """ |
| base = description.rstrip(":").strip().lower() |
| if not base: |
| return [] |
| |
| base = base.split(";")[0].split(". ")[0] |
| words = [w for w in base.split() if w not in _STOPWORDS] |
| if not words: |
| return [] |
| terse = " ".join(words) |
| for pattern, replacement in _VERB_SWAPS: |
| terse = pattern.sub(replacement, terse) |
| variants = [terse] |
| |
| comma_cut = terse.split(",")[0].strip() |
| if comma_cut != terse and len(comma_cut.split()) >= 2: |
| variants.append(comma_cut) |
| words = terse.split() |
| if len(words) > 5: |
| for cut_word in ("to", "from", "in", "with", "using", "for"): |
| if cut_word in words[2:]: |
| short = " ".join(words[: words[2:].index(cut_word) + 2]).strip() |
| if len(short.split()) >= 2: |
| variants.append(short) |
| break |
| |
| seen: list[str] = [] |
| for variant in variants: |
| if variant not in seen: |
| seen.append(variant) |
| if len(seen) > 2: |
| seen = [seen[0], rng.choice(seen[1:])] |
| return seen |
|
|
|
|
| |
|
|
| |
| COMMON_TYPOS = { |
| "git": ["gti", "gt", "gitt", "igt"], |
| "grep": ["gerp", "grpe", "gerep"], |
| "ls": ["sl", "lls", "l s"], |
| "cd": ["dc", "cd.."], |
| "clear": ["celar", "claer", "clera"], |
| "sudo": ["suod", "sudp", "sduo"], |
| "python": ["pyhton", "pytohn", "pythno"], |
| "python3": ["pyhton3", "pytohn3"], |
| "docker": ["dokcer", "docekr", "dcoker"], |
| "kubectl": ["kubeclt", "kubctl", "kubetcl"], |
| "npm": ["nmp", "npn"], |
| "make": ["mkae", "amke"], |
| "ssh": ["shh", "ssh-"], |
| "curl": ["culr", "crul"], |
| "brew": ["brwe", "berw"], |
| "cargo": ["cagro", "carog"], |
| "vim": ["ivm", "vmi"], |
| "tar": ["tra", "atr"], |
| "find": ["fnid", "fidn"], |
| "chmod": ["chmdo", "cmhod"], |
| } |
|
|
|
|
| def head_typo(command: str, rng: random.Random) -> str | None: |
| head, _, rest = command.partition(" ") |
| typos = COMMON_TYPOS.get(head) |
| if not typos: |
| return None |
| mangled_head = rng.choice(typos) |
| return f"{mangled_head} {rest}".strip() |
|
|
|
|
| |
|
|
| QWERTY_NEIGHBORS = { |
| "q": "wa", "w": "qes", "e": "wrd", "r": "etf", "t": "ryg", "y": "tuh", |
| "u": "yij", "i": "uok", "o": "ipl", "p": "o", "a": "qsz", "s": "adwx", |
| "d": "sfec", "f": "dgrv", "g": "fhtb", "h": "gjyn", "j": "hkum", |
| "k": "jli", "l": "ko", "z": "asx", "x": "zsdc", "c": "xdfv", |
| "v": "cfgb", "b": "vghn", "n": "bhjm", "m": "njk", |
| } |
|
|
|
|
| def _word_spans(command: str) -> list[tuple[int, int]]: |
| """Spans of alphabetic words worth corrupting (commands/subcommands, not values).""" |
| spans = [] |
| for match in re.finditer(r"[A-Za-z]{3,}", command): |
| |
| prefix = command[: match.start()] |
| if prefix.count('"') % 2 == 0 and prefix.count("'") % 2 == 0: |
| spans.append(match.span()) |
| return spans[:3] |
|
|
|
|
| def mangle_transpose(command: str, rng: random.Random) -> str | None: |
| spans = _word_spans(command) |
| if not spans: |
| return None |
| start, end = rng.choice(spans) |
| if end - start < 3: |
| return None |
| i = rng.randrange(start, end - 1) |
| chars = list(command) |
| chars[i], chars[i + 1] = chars[i + 1], chars[i] |
| return "".join(chars) |
|
|
|
|
| def mangle_drop(command: str, rng: random.Random) -> str | None: |
| spans = _word_spans(command) |
| if not spans: |
| return None |
| start, end = rng.choice(spans) |
| i = rng.randrange(start, end) |
| return command[:i] + command[i + 1 :] |
|
|
|
|
| def mangle_adjacent(command: str, rng: random.Random) -> str | None: |
| spans = _word_spans(command) |
| if not spans: |
| return None |
| start, end = rng.choice(spans) |
| candidates = [i for i in range(start, end) if command[i].lower() in QWERTY_NEIGHBORS] |
| if not candidates: |
| return None |
| i = rng.choice(candidates) |
| replacement = rng.choice(QWERTY_NEIGHBORS[command[i].lower()]) |
| if command[i].isupper(): |
| replacement = replacement.upper() |
| return command[:i] + replacement + command[i + 1 :] |
|
|
|
|
| def mangle_double(command: str, rng: random.Random) -> str | None: |
| spans = _word_spans(command) |
| if not spans: |
| return None |
| start, end = rng.choice(spans) |
| i = rng.randrange(start, end) |
| return command[:i] + command[i] + command[i:] |
|
|
|
|
| def mangle_dashes(command: str, rng: random.Random) -> str | None: |
| double = list(re.finditer(r"(?<!\S)--(\w[\w-]+)", command)) |
| single = list(re.finditer(r"(?<!\S)-(\w)(?!\w)", command)) |
| if double and (not single or rng.random() < 0.5): |
| match = rng.choice(double) |
| return command[: match.start()] + "-" + match.group(1) + command[match.end() :] |
| if single: |
| match = rng.choice(single) |
| return command[: match.start()] + "--" + match.group(1) + command[match.end() :] |
| return None |
|
|
|
|
| def mangle_merge_words(command: str, rng: random.Random) -> str | None: |
| spaces = [i for i, ch in enumerate(command) if ch == " "] |
| if not spaces: |
| return None |
| i = rng.choice(spaces[:2]) |
| return command[:i] + command[i + 1 :] |
|
|
|
|
| def mangle_unquote(command: str, rng: random.Random) -> str | None: |
| match = re.search(r"([\"'])(.+?)\1", command) |
| if not match: |
| return None |
| return command[: match.start()] + match.group(2) + command[match.end() :] |
|
|
|
|
| def mangle_sudo(command: str, rng: random.Random) -> str | None: |
| |
| if command.startswith("sudo "): |
| return command[len("sudo ") :] |
| if rng.random() < 0.3 and not command.startswith(("cd", "export")): |
| return "sudo " + command |
| return None |
|
|
|
|
| def mangle_prompt_prefix(command: str, rng: random.Random) -> str | None: |
| |
| return ("$ " if rng.random() < 0.8 else "> ") + command |
|
|
|
|
| def mangle_dup_word(command: str, rng: random.Random) -> str | None: |
| head, sep, rest = command.partition(" ") |
| if not sep: |
| return None |
| return f"{head} {head} {rest}" |
|
|
|
|
| _SMART_SWAPS = [("'", "’"), ('"', "“"), ("--", "–")] |
|
|
|
|
| def mangle_smart_chars(command: str, rng: random.Random) -> str | None: |
| |
| applicable = [(a, b) for a, b in _SMART_SWAPS if a in command] |
| if not applicable: |
| return None |
| plain, smart = rng.choice(applicable) |
| return command.replace(plain, smart, 1) |
|
|
|
|
| MANGLERS = [ |
| (mangle_transpose, 0.24), |
| (mangle_drop, 0.12), |
| (mangle_adjacent, 0.16), |
| (mangle_double, 0.08), |
| (mangle_dashes, 0.09), |
| (mangle_merge_words, 0.08), |
| (mangle_unquote, 0.04), |
| (mangle_sudo, 0.08), |
| (mangle_prompt_prefix, 0.06), |
| (mangle_dup_word, 0.03), |
| (mangle_smart_chars, 0.02), |
| ] |
|
|
|
|
| def mangle(command: str, rng: random.Random) -> str | None: |
| """Apply one weighted-random corruption; occasionally two.""" |
| result = command |
| rounds = 2 if rng.random() < 0.15 else 1 |
| changed = False |
| for _ in range(rounds): |
| |
| |
| ordered = sorted(MANGLERS, key=lambda mw: rng.random() ** (1.0 / mw[1]), reverse=True) |
| for fn, _ in ordered: |
| mangled = fn(result, rng) |
| if mangled and mangled != result: |
| result = mangled |
| changed = True |
| break |
| return result if changed and result != command else None |
|
|
|
|
| |
|
|
| NL2BASH_CM_URL = "https://raw.githubusercontent.com/TellinaTool/nl2bash/master/data/bash/all.cm" |
| NL2BASH_NL_URL = "https://raw.githubusercontent.com/TellinaTool/nl2bash/master/data/bash/all.nl" |
|
|
|
|
| def load_nl2bash_pairs(cache_dir: Path) -> list[tuple[str, str]]: |
| """(description, command) pairs from the NL2Bash corpus (MIT). Best-effort.""" |
| cache_dir.mkdir(parents=True, exist_ok=True) |
| texts: list[str] = [] |
| for url, name in ((NL2BASH_NL_URL, "nl2bash.nl"), (NL2BASH_CM_URL, "nl2bash.cm")): |
| path = cache_dir / name |
| try: |
| if not path.exists(): |
| with urllib.request.urlopen(url, timeout=60) as response: |
| path.write_bytes(response.read()) |
| texts.append(path.read_text(encoding="utf-8", errors="replace")) |
| except (OSError, urllib.error.URLError): |
| print(f"note: could not fetch {name} — continuing without nl2bash") |
| return [] |
| descriptions, commands = texts[0].splitlines(), texts[1].splitlines() |
| pairs: list[tuple[str, str]] = [] |
| for desc, cmd in zip(descriptions, commands): |
| desc, cmd = desc.strip(), cmd.strip() |
| if desc and cmd and len(cmd) <= 120: |
| pairs.append((desc, cmd)) |
| return pairs |
|
|
|
|
| |
|
|
| _COMMAND_FILE_RE = re.compile( |
| r"\b[\w.-]+\.(?:gz|tgz|tar|zip|txt|csv|tsv|json|yaml|yml|toml|md|log|py|sh|rb|js|ts|go|rs|c|cpp|h|pdf|png|jpg|mov|mp4|conf|cfg|ini|sql|env)\b" |
| ) |
|
|
|
|
| def extract_files_from_command(command: str) -> list[str]: |
| """Concrete filenames already present in a command (nl2bash rows have no |
| placeholders) — they seed a listing so context-conditioning covers that |
| corpus too.""" |
| return list(dict.fromkeys(_COMMAND_FILE_RE.findall(command)))[:3] |
|
|
|
|
| def load_event_pairs() -> list[tuple[str, str]]: |
| """Accepted fixes from your own fash usage: the highest-quality pairs.""" |
| if not EVENTS_PATH.exists(): |
| return [] |
| pairs: list[tuple[str, str]] = [] |
| with EVENTS_PATH.open("r", encoding="utf-8") as handle: |
| for raw in handle: |
| try: |
| event = json.loads(raw) |
| except json.JSONDecodeError: |
| continue |
| if event.get("kind") in {"fix", "args"} and event.get("chosen") and event.get("line"): |
| pairs.append((str(event["line"]), str(event["chosen"]))) |
| return pairs |
|
|
|
|
| |
|
|
| def row(user: str, assistant: str) -> dict: |
| return { |
| "messages": [ |
| {"role": "system", "content": SYSTEM_PROMPT}, |
| {"role": "user", "content": user}, |
| {"role": "assistant", "content": assistant}, |
| ] |
| } |
|
|
|
|
| def build(out_dir: Path, max_pairs: int, seed: int, include_events: bool, nl_share: float) -> None: |
| rng = random.Random(seed) |
| cache = Path(__file__).parent / ".cache" |
| tldr = load_tldr_pairs(cache) |
| print(f"tldr examples: {len(tldr)}") |
| nl2bash = load_nl2bash_pairs(cache) |
| print(f"nl2bash examples: {len(nl2bash)}") |
| corpus = tldr + nl2bash |
| rng.shuffle(corpus) |
|
|
| def with_context(user: str, context: str, probability: float) -> str: |
| """Attach the cwd/files header some of the time — Mash must work both |
| with context (to resolve 'the settings file' against the listing) and |
| bare (context capture may be unavailable).""" |
| if context and rng.random() < probability: |
| return f"{context}\n{user}" |
| return user |
|
|
| rows: list[dict] = [] |
| for raw_description, template in corpus: |
| description, command, context = fill_example(raw_description, template, rng) |
| if not command or len(command) > 120: |
| continue |
| if not context: |
| named = extract_files_from_command(command) |
| if named: |
| context = local_context_block(rng.choice(CWD_POOL), make_listing(named, rng)) |
| elif rng.random() < 0.08: |
| |
| context = local_context_block(rng.choice(CWD_POOL), make_listing([], rng)) |
| mangled = mangle(command, rng) |
| if mangled: |
| rows.append(row(with_context(mangled, context, 0.5), command)) |
| typo = head_typo(command, rng) |
| if typo: |
| rows.append(row(typo, command)) |
| if description and rng.random() < nl_share: |
| for variant in casualize(description, rng): |
| |
| |
| rows.append(row(with_context(variant, context, 0.85), command)) |
| |
| |
| |
| |
| if rng.random() < 0.10: |
| rows.append(row(command, command)) |
| if len(rows) >= max_pairs: |
| break |
|
|
| event_rows: list[dict] = [] |
| if include_events: |
| event_pairs = list(dict.fromkeys(load_event_pairs())) |
| print(f"pairs from your fash history: {len(event_pairs)}") |
| event_rows = [row(garbled, chosen) for garbled, chosen in event_pairs] |
| rows.extend(event_rows) |
|
|
| rng.shuffle(rows) |
| n = len(rows) |
| valid_n = max(64, int(n * 0.02)) if n > 200 else max(1, n // 10) |
| splits = { |
| "valid": rows[:valid_n], |
| "test": rows[valid_n : valid_n * 2], |
| "train": rows[valid_n * 2 :], |
| } |
| if event_rows: |
| |
| |
| event_keys = {json.dumps(r, sort_keys=True) for r in event_rows} |
| extra = [r for r in splits["train"] if json.dumps(r, sort_keys=True) in event_keys] |
| splits["train"].extend(extra * 2) |
| rng.shuffle(splits["train"]) |
| out_dir.mkdir(parents=True, exist_ok=True) |
| for name, split_rows in splits.items(): |
| path = out_dir / f"{name}.jsonl" |
| with path.open("w", encoding="utf-8") as handle: |
| for item in split_rows: |
| handle.write(json.dumps(item, ensure_ascii=False) + "\n") |
| print(f"{path}: {len(split_rows)} rows") |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--out", type=Path, default=Path(__file__).parent / "data") |
| parser.add_argument("--max-pairs", type=int, default=42000) |
| parser.add_argument("--seed", type=int, default=7) |
| parser.add_argument("--nl-share", type=float, default=0.4, help="fraction of examples that also emit natural-language request pairs") |
| parser.add_argument("--no-events", dest="events", action="store_false", help="skip pairs from ~/.fash/events.jsonl") |
| args = parser.parse_args() |
| build(args.out, args.max_pairs, args.seed, args.events, args.nl_share) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|