Download generate_data.py from asterbraid/awkweave-data: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/datasets/asterbraid/awkweave-data/resolve/main/generate_data.py
- Command line
-
hf download hf://datasets/asterbraid/awkweave-data/generate_data.py
-
curl -L -o generate_data.py https://huggingface.co/datasets/asterbraid/awkweave-data/resolve/main/generate_data.py
19.2 kB
| from __future__ import annotations | |
| import argparse | |
| import concurrent.futures | |
| import json | |
| import random | |
| import re | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from awkweave.execution import run_awk | |
| NAMES = ["alice", "bruno", "chen", "dina", "eli", "farah", "gus", "hana", "ivan", "jules", "kim", "lina"] | |
| WORDS = ["amber", "birch", "cobalt", "delta", "ember", "fable", "grove", "harbor", "indigo", "juniper"] | |
| STATUSES = ["active", "pending", "closed", "ready", "paused", "failed"] | |
| CATEGORIES = ["alpha", "beta", "gamma", "delta"] | |
| LEVELS = ["INFO", "WARN", "ERROR", "DEBUG"] | |
| class Case: | |
| request: str | |
| program: str | |
| inputs: list[str] | |
| family: str | |
| difficulty: int | |
| def rows(rng: random.Random, kinds: list[str], count: int | None = None) -> list[list[str]]: | |
| result = [] | |
| for row_index in range(count or rng.randint(6, 10)): | |
| row = [] | |
| for column_index, kind in enumerate(kinds): | |
| if kind == "name": | |
| value = rng.choice(NAMES) | |
| elif kind == "word": | |
| value = rng.choice(WORDS) | |
| elif kind == "status": | |
| value = rng.choice(STATUSES) | |
| elif kind == "category": | |
| value = rng.choice(CATEGORIES) | |
| elif kind == "level": | |
| value = rng.choice(LEVELS) | |
| elif kind == "int": | |
| value = str(rng.randint(0, 120)) | |
| elif kind == "smallint": | |
| value = str(rng.randint(1, 30)) | |
| elif kind == "float": | |
| value = f"{rng.uniform(0.5, 99.5):.2f}" | |
| elif kind == "underscore": | |
| value = f"{rng.choice(WORDS)}_{rng.choice(WORDS)}" | |
| elif kind == "id": | |
| value = f"r{row_index + 1:03d}" | |
| else: | |
| raise ValueError(kind) | |
| row.append(value) | |
| result.append(row) | |
| return result | |
| def render(rows_: list[list[str]], separator: str = " ", header: list[str] | None = None) -> str: | |
| all_rows = ([header] if header else []) + rows_ | |
| return "\n".join(separator.join(row) for row in all_rows) + "\n" | |
| def pair(rng: random.Random, kinds: list[str], separator: str = " ", header: list[str] | None = None) -> list[str]: | |
| return [render(rows(rng, kinds), separator, header), render(rows(rng, kinds), separator, header)] | |
| def ordinal(number: int) -> str: | |
| suffix = "th" if 10 <= number % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(number % 10, "th") | |
| return f"{number}{suffix}" | |
| def make_case(family: str, seed: int) -> Case: | |
| rng = random.Random(seed) | |
| if family == "project_fields": | |
| kinds = [rng.choice(["name", "word", "int", "status"]) for _ in range(rng.randint(4, 6))] | |
| first, second = sorted(rng.sample(range(1, len(kinds) + 1), 2)) | |
| request = rng.choice([ | |
| f"Print column {second} followed by column {first} for every record.", | |
| f"For each line, output fields {second} and {first}, in that order.", | |
| f"Select the {ordinal(second)} and {ordinal(first)} fields in that order.", | |
| ]) | |
| return Case(request, f"{{print ${second}, ${first}}}", pair(rng, kinds), family, 1) | |
| if family == "last_field": | |
| kinds = [rng.choice(["name", "word", "int", "status"]) for _ in range(rng.randint(3, 7))] | |
| return Case("Print the last field of every input line.", "{print $NF}", pair(rng, kinds), family, 1) | |
| if family == "numeric_filter": | |
| kinds = [rng.choice(["name", "word", "status"]) for _ in range(rng.randint(2, 4))] | |
| position = rng.randrange(len(kinds)) | |
| kinds.insert(position, "int") | |
| column = position + 1 | |
| threshold = rng.randint(20, 80) | |
| operator = rng.choice([">", ">=", "<", "<="]) | |
| phrase = {">": "greater than", ">=": "at least", "<": "less than", "<=": "at most"}[operator] | |
| request = f"Print the complete records where column {column} is {phrase} {threshold}." | |
| return Case(request, f"${column} {operator} {threshold}", pair(rng, kinds), family, 1) | |
| if family == "numeric_range": | |
| kinds = [rng.choice(["name", "word", "status"]) for _ in range(3)] | |
| position = rng.randrange(3) | |
| kinds.insert(position, "smallint") | |
| column = position + 1 | |
| low = rng.randint(3, 12) | |
| high = rng.randint(18, 29) | |
| request = f"Show whole lines whose {ordinal(column)} field is between {low} and {high}, inclusive." | |
| return Case(request, f"${column} >= {low} && ${column} <= {high}", pair(rng, kinds), family, 1) | |
| if family == "string_filter": | |
| kinds = ["name", "status", "word", "int"] | |
| rng.shuffle(kinds) | |
| status_column = kinds.index("status") + 1 | |
| id_column = kinds.index("name") + 1 | |
| value = rng.choice(STATUSES) | |
| request = f"Print column {id_column} only for rows where column {status_column} is exactly {value}." | |
| program = f'${status_column} == "{value}"{{print ${id_column}}}' | |
| return Case(request, program, pair(rng, kinds), family, 1) | |
| if family == "regex_filter": | |
| kinds = ["level", "word", "int"] | |
| rng.shuffle(kinds) | |
| column = kinds.index("level") + 1 | |
| level = rng.choice(["INFO", "WARN", "ERROR"]) | |
| request = f"Print all fields from lines where field {column} begins with {level}." | |
| return Case(request, f'${column} ~ /^{level}/', pair(rng, kinds), family, 1) | |
| if family == "exclude_regex": | |
| kinds = ["word", "int", "status"] | |
| excluded = rng.choice(WORDS) | |
| inputs = pair(rng, kinds) | |
| inputs = [text + f"{excluded} 999 active\n" for text in inputs] | |
| request = f"Print every line except those containing the exact text {excluded}." | |
| return Case(request, f'$0 !~ /{excluded}/', inputs, family, 1) | |
| if family == "line_range": | |
| inputs = pair(rng, ["name", "word", "int"]) | |
| start = rng.randint(2, 4) | |
| end = start + rng.randint(1, 3) | |
| request = f"Print lines {start} through {end}, including both endpoints." | |
| return Case(request, f"NR >= {start} && NR <= {end}", inputs, family, 1) | |
| if family == "first_n": | |
| count = rng.randint(2, 5) | |
| return Case(f"Output only the first {count} records.", f"NR <= {count}", pair(rng, ["name", "int", "word"]), family, 1) | |
| if family == "skip_header": | |
| return Case("Skip the first line and print every remaining line unchanged.", "NR > 1", pair(rng, ["name", "int", "word"]), family, 1) | |
| if family == "count_matches": | |
| kinds = ["name", "status", "int"] | |
| value = rng.choice(STATUSES) | |
| request = f"Count how many records have {value} in column 2. Print 0 if there are none." | |
| program = f'$2 == "{value}"{{n++}}END{{print n+0}}' | |
| return Case(request, program, pair(rng, kinds), family, 1) | |
| if family == "sum_field": | |
| kinds = ["name", "smallint", "word"] | |
| rng.shuffle(kinds) | |
| column = kinds.index("smallint") + 1 | |
| request = f"Calculate and print the sum of the integers in column {column}." | |
| return Case(request, f"{{s+=${column}}}END{{print s+0}}", pair(rng, kinds), family, 1) | |
| if family == "average_field": | |
| kinds = ["name", "smallint", "word"] | |
| rng.shuffle(kinds) | |
| column = kinds.index("smallint") + 1 | |
| request = f"Print the arithmetic mean of column {column}, rounded to exactly two decimal places." | |
| program = f'{{s+=${column};n++}}END{{printf "%.2f\\n",s/n}}' | |
| return Case(request, program, pair(rng, kinds), family, 2) | |
| if family in {"min_field", "max_field"}: | |
| kinds = ["name", "smallint", "word"] | |
| rng.shuffle(kinds) | |
| column = kinds.index("smallint") + 1 | |
| is_min = family == "min_field" | |
| request = f"Find and print the {'smallest' if is_min else 'largest'} numeric value in column {column}." | |
| comparison = "<" if is_min else ">" | |
| program = f"NR==1||${column}{comparison}extreme{{extreme=${column}}}END{{print extreme}}" | |
| return Case(request, program, pair(rng, kinds), family, 1) | |
| if family == "count_records": | |
| return Case("Count all input records and print the total.", "END{print NR}", pair(rng, ["name", "int"]), family, 1) | |
| if family == "dedup_lines": | |
| inputs = pair(rng, ["name", "word", "int"]) | |
| enriched = [] | |
| for text in inputs: | |
| lines = text.splitlines() | |
| lines.insert(rng.randrange(len(lines)), rng.choice(lines)) | |
| enriched.append("\n".join(lines) + "\n") | |
| return Case("Remove exact duplicate lines, preserving the first occurrence and original order.", "!seen[$0]++", enriched, family, 2) | |
| if family == "dedup_field": | |
| kinds = ["name", "word", "int"] | |
| column = rng.randint(1, 3) | |
| request = f"Keep only the first line for each distinct value in column {column}; preserve input order." | |
| return Case(request, f"!seen[${column}]++", pair(rng, kinds), family, 2) | |
| if family == "running_total": | |
| kinds = ["name", "smallint", "word"] | |
| request = "For each record, print column 1 and the running sum of column 2, separated by a space." | |
| return Case(request, "{s+=$2;print $1,s}", pair(rng, kinds), family, 2) | |
| if family == "computed_field": | |
| kinds = ["name", "smallint", "smallint", "word"] | |
| request = "For every row, print field 1 followed by the sum of fields 2 and 3." | |
| return Case(request, "{print $1,$2+$3}", pair(rng, kinds), family, 1) | |
| if family == "conditional_label": | |
| threshold = rng.randint(20, 27) | |
| kinds = ["name", "smallint"] | |
| request = f"Print column 1 and pass when column 2 is at least {threshold}; otherwise print fail." | |
| program = f'{{print $1,($2>={threshold}?"pass":"fail")}}' | |
| return Case(request, program, pair(rng, kinds), family, 2) | |
| if family == "uppercase": | |
| column = rng.choice([1, 2]) | |
| request = f"Convert column {column} to uppercase and print only that column." | |
| return Case(request, f"{{print toupper(${column})}}", pair(rng, ["name", "word", "int"]), family, 1) | |
| if family == "substring": | |
| start = rng.randint(1, 3) | |
| length = rng.randint(2, 4) | |
| request = f"From column 1, print {length} characters starting at character {start}." | |
| return Case(request, f"{{print substr($1,{start},{length})}}", pair(rng, ["word", "int"]), family, 1) | |
| if family == "replace_underscores": | |
| request = "Replace every underscore in column 1 with a space and print the resulting values." | |
| return Case(request, '{gsub(/_/," ",$1);print $1}', pair(rng, ["underscore", "int"]), family, 1) | |
| if family == "reverse_fields": | |
| program = '{for(i=NF;i>=1;i--)printf "%s%s",$i,(i>1?OFS:ORS)}' | |
| return Case("Reverse the order of fields on every line and print all fields.", program, pair(rng, ["name", "word", "int", "status"]), family, 2) | |
| if family == "field_count": | |
| return Case("Print the number of whitespace-separated fields on each line.", "{print NF}", pair(rng, ["name", "word", "int", "status"]), family, 1) | |
| if family == "count_by_key": | |
| program = "{if(!($2 in counts))order[++n]=$2;counts[$2]++}END{for(i=1;i<=n;i++)print order[i],counts[order[i]]}" | |
| request = "Count records for each value in column 2. Print each value and its count in order of first appearance." | |
| return Case(request, program, pair(rng, ["name", "category", "int"]), family, 2) | |
| if family == "sum_by_key": | |
| program = "{if(!($2 in sums))order[++n]=$2;sums[$2]+=$3}END{for(i=1;i<=n;i++)print order[i],sums[order[i]]}" | |
| request = "Sum column 3 for each category in column 2, printing groups in order of first appearance." | |
| return Case(request, program, pair(rng, ["name", "category", "smallint"]), family, 2) | |
| if family == "duplicates_only": | |
| program = "{if(!($1 in counts))order[++n]=$1;counts[$1]++}END{for(i=1;i<=n;i++)if(counts[order[i]]>1)print order[i],counts[order[i]]}" | |
| request = "Print each repeated value from column 1 with its number of occurrences, in first-appearance order." | |
| return Case(request, program, pair(rng, ["category", "word", "int"]), family, 2) | |
| if family == "header_projection": | |
| headers = rng.sample(["record_id", "display_name", "score", "state", "region", "note"], 4) | |
| kinds = ["id", "name", "smallint", "status"] | |
| wanted = rng.randrange(1, 4) | |
| request = f"The first row is a header. Print the {headers[wanted]} column for every data row." | |
| program = f'NR==1{{for(i=1;i<=NF;i++)h[$i]=i;next}}{{print $h["{headers[wanted]}"]}}' | |
| return Case(request, program, pair(rng, kinds, header=headers), family, 2) | |
| if family == "header_filter": | |
| headers = ["record_id", "display_name", "score", "state"] | |
| kinds = ["id", "name", "smallint", "status"] | |
| threshold = rng.randint(8, 24) | |
| request = f"The first row is a header. Print display_name for data rows whose score is greater than {threshold}." | |
| program = f'NR==1{{for(i=1;i<=NF;i++)h[$i]=i;next}}$h["score"]>{threshold}{{print $h["display_name"]}}' | |
| return Case(request, program, pair(rng, kinds, header=headers), family, 2) | |
| if family == "tsv_projection": | |
| kinds = ["name", "smallint", "status"] | |
| column = rng.randint(1, 3) | |
| request = f"The input is tab-separated. Print column {column} from every record." | |
| return Case(request, f'BEGIN{{FS=OFS="\\t"}}{{print ${column}}}', pair(rng, kinds, "\t"), family, 1) | |
| if family == "csv_filter": | |
| kinds = ["name", "smallint", "status"] | |
| threshold = rng.randint(8, 24) | |
| request = f"The input is simple comma-separated data with no quoted commas. Print column 1 when column 2 exceeds {threshold}." | |
| return Case(request, f'BEGIN{{FS=OFS=","}}$2>{threshold}{{print $1}}', pair(rng, kinds, ","), family, 2) | |
| if family == "normalize_whitespace": | |
| inputs = [] | |
| for rows_ in (rows(rng, ["name", "word", "int"]), rows(rng, ["name", "word", "int"])): | |
| inputs.append("\n".join((" " if rng.random() < 0.5 else "") + rng.choice([" ", " ", "\t"]).join(row) + (" " if rng.random() < 0.5 else "") for row in rows_) + "\n") | |
| return Case("Trim leading and trailing whitespace and collapse internal whitespace to single spaces.", "{$1=$1;print}", inputs, family, 2) | |
| if family == "longest_line": | |
| return Case("Find and print the longest input line; if tied, keep the earliest.", "{if(length($0)>length(best))best=$0}END{print best}", pair(rng, ["name", "word", "int", "status"]), family, 2) | |
| if family == "every_nth": | |
| step = rng.randint(2, 4) | |
| offset = rng.randint(1, step) | |
| request = f"Print every {step}{'nd' if step == 2 else 'rd' if step == 3 else 'th'} line starting at line {offset} (then line {offset + step}, and so on)." | |
| return Case(request, f"NR%{step}=={offset % step}", pair(rng, ["name", "int"]), family, 1) | |
| if family == "distinct_count": | |
| column = rng.randint(1, 2) | |
| request = f"Count the distinct values in column {column} and print only the count." | |
| return Case(request, f"{{if(!seen[${column}]++)n++}}END{{print n+0}}", pair(rng, ["category", "word", "int"]), family, 2) | |
| if family == "ratio": | |
| request = "For each row, print column 1 and column 2 divided by column 3 to two decimal places; skip rows where column 3 is zero." | |
| inputs = pair(rng, ["name", "smallint", "smallint"]) | |
| inputs = [re.sub(r"^(\w+ \d+ )\d+", r"\g<1>0", text, count=1, flags=re.MULTILINE) for text in inputs] | |
| return Case(request, '{if($3!=0)printf "%s %.2f\\n",$1,$2/$3}', inputs, family, 2) | |
| if family == "top_three": | |
| program = "{value[NR]=$3;line[NR]=$0}END{for(i=2;i<=NR;i++){v=value[i];text=line[i];j=i-1;while(j>=1&&value[j]<v){value[j+1]=value[j];line[j+1]=line[j];j--}value[j+1]=v;line[j+1]=text}for(i=1;i<=3&&i<=NR;i++)print line[i]}" | |
| request = "Print the three complete records with the highest numeric values in column 3, sorted descending. Preserve input order for ties." | |
| return Case(request, program, pair(rng, ["name", "word", "smallint"]), family, 3) | |
| raise ValueError(family) | |
| FAMILIES = [ | |
| "project_fields", "last_field", "numeric_filter", "numeric_range", "string_filter", | |
| "regex_filter", "exclude_regex", "line_range", "first_n", "skip_header", | |
| "count_matches", "sum_field", "average_field", "min_field", "max_field", | |
| "count_records", "dedup_lines", "dedup_field", "running_total", "computed_field", | |
| "conditional_label", "uppercase", "substring", "replace_underscores", "reverse_fields", | |
| "field_count", "count_by_key", "sum_by_key", "duplicates_only", "header_projection", | |
| "header_filter", "tsv_projection", "csv_filter", "normalize_whitespace", "longest_line", | |
| "every_nth", "distinct_count", "ratio", "top_three", | |
| ] | |
| def generate_row(index: int, base_seed: int) -> dict: | |
| family = FAMILIES[index % len(FAMILIES)] | |
| for attempt in range(100): | |
| case = make_case(family, base_seed + index * 1009 + attempt * 1_000_003) | |
| try: | |
| outputs = [run_awk(case.program, text) for text in case.inputs] | |
| except ValueError: | |
| continue | |
| if not outputs[0].strip(): | |
| continue | |
| split = "train" if index % 100 < 90 else "validation" if index % 100 < 95 else "test" | |
| return { | |
| "id": f"awkweave-{index:07d}", | |
| "request": case.request, | |
| "program": case.program, | |
| "input_text": case.inputs[0], | |
| "expected_output": outputs[0], | |
| "validation_input": case.inputs[1], | |
| "validation_output": outputs[1], | |
| "family": case.family, | |
| "difficulty": case.difficulty, | |
| "split": split, | |
| "source": "original-grammar", | |
| "license": "CC-BY-4.0", | |
| } | |
| raise RuntimeError(f"Could not generate a non-empty case for {family} at index {index}") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--count", type=int, default=60_000) | |
| parser.add_argument("--seed", type=int, default=20261128) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument("--output", type=Path, default=Path("awkweave-seed.jsonl")) | |
| args = parser.parse_args() | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| with args.output.open("w", encoding="utf-8") as handle: | |
| with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor: | |
| futures = {executor.submit(generate_row, index, args.seed): index for index in range(args.count)} | |
| completed = 0 | |
| for future in concurrent.futures.as_completed(futures): | |
| index = futures[future] | |
| row = future.result() | |
| handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| completed += 1 | |
| if completed % 1000 == 0: | |
| handle.flush() | |
| print(f"generated {completed}/{args.count}", flush=True) | |
| print(f"wrote {args.count} rows to {args.output}") | |
| if __name__ == "__main__": | |
| main() | |