Datasets:
Jqweave: 39k execution-verified natural-language-to-jq examples across 39 task families
2c911b5 verified Download generate_data.py from asterbraid/jqweave-data: direct link, hf CLI and curl.
- Browser
- Download file 9.48 kB
-
https://huggingface.co/datasets/asterbraid/jqweave-data/resolve/main/generate_data.py
- Command line
-
hf download hf://datasets/asterbraid/jqweave-data/generate_data.py
-
curl -L -o generate_data.py https://huggingface.co/datasets/asterbraid/jqweave-data/resolve/main/generate_data.py
9.48 kB
| from __future__ import annotations | |
| import concurrent.futures | |
| import json | |
| import random | |
| from pathlib import Path | |
| from jqweave.execution import run_jq | |
| NAMES = ["alice", "bruno", "chen", "dina", "eli", "farah", "gus", "hana", "iris", "jules", "kira", "liam", "mira", "nina", "omar", "petra"] | |
| CATEGORIES = ["alpha", "beta", "gamma", "delta"] | |
| STATUSES = ["ready", "pending", "failed", "closed"] | |
| FAMILIES = [ | |
| ("select_field", "Extract the value of the 'name' field.", "jq '.name'", "object"), | |
| ("nested_field", "Extract the city from the user's address.", "jq '.user.address.city'", "nested"), | |
| ("array_first", "Return the first element of the array.", "jq '.[0]'", "records"), | |
| ("array_last", "Return the last element of the array.", "jq '.[-1]'", "records"), | |
| ("array_index", "Return the third element of the array.", "jq '.[2]'", "records"), | |
| ("array_length", "Count the number of records in the array.", "jq 'length'", "records"), | |
| ("object_keys", "List the object's keys in sorted order.", "jq 'keys'", "object"), | |
| ("object_values", "Return the object's values as an array.", "jq '[.[]]'", "object"), | |
| ("select_array_field", "Extract the name field from every record as a stream.", "jq '.[] | .name'", "records"), | |
| ("pluck_array", "Build an array containing every record's name.", "jq '[.[] | .name]'", "records"), | |
| ("filter_active", "Keep only records whose active flag is true.", "jq '[.[] | select(.active == true)]'", "records"), | |
| ("filter_score", "Keep only records with a score of at least __THRESHOLD__.", "jq '[.[] | select(.score >= __THRESHOLD__)]'", "records"), | |
| ("filter_status", "Keep only records whose status is '__STATUS__'.", "jq '[.[] | select(.status == \"__STATUS__\")]'", "records"), | |
| ("map_number", "Double the score in every record.", "jq '[.[] | .score * 2]'", "records"), | |
| ("map_string", "Convert every record's name to uppercase.", "jq '[.[] | .name | ascii_upcase]'", "records"), | |
| ("sum_field", "Sum all record scores.", "jq '[.[] | .score] | add'", "records"), | |
| ("average_field", "Compute the average of all record scores.", "jq '[.[] | .score] | add / length'", "records"), | |
| ("min_field", "Find the smallest record score.", "jq '[.[] | .score] | min'", "records"), | |
| ("max_field", "Find the largest record score.", "jq '[.[] | .score] | max'", "records"), | |
| ("unique_categories", "List the unique categories in sorted order.", "jq '[.[] | .category] | unique'", "records"), | |
| ("group_count", "Group records by category and return each category with its record count.", "jq 'group_by(.category) | map({category: .[0].category, count: length})'", "records"), | |
| ("sort_score", "Sort records by score in ascending order.", "jq 'sort_by(.score)'", "records"), | |
| ("reverse_array", "Reverse the order of the array.", "jq 'reverse'", "records"), | |
| ("flatten_array", "Flatten all nested arrays into a single array.", "jq 'flatten'", "array_arrays"), | |
| ("join_strings", "Join all strings with a comma and a space.", "jq 'join(\", \")'", "strings"), | |
| ("to_entries", "Convert the object into an array of key-value entries.", "jq 'to_entries'", "object"), | |
| ("from_entries", "Convert the key-value entries back into an object.", "jq 'from_entries'", "entries"), | |
| ("has_key", "Check whether the object contains the key 'name'.", "jq 'has(\"name\")'", "object"), | |
| ("delete_key", "Remove the password field from the object.", "jq 'del(.password)'", "object"), | |
| ("rename_key", "Rename the username field to name while preserving the id field.", "jq '{name: .username, id: .id}'", "object"), | |
| ("concat_arrays", "Concatenate arrays a and b into one array.", "jq '.a + .b'", "concat"), | |
| ("merge_objects", "Merge objects a and b into one object.", "jq '.a + .b'", "merge"), | |
| ("raw_strings", "Print every string without JSON quotes.", "jq -r '.[]'", "strings"), | |
| ("csv_convert", "Convert each record's name and score into a CSV row.", "jq -r '.[] | [.name,.score] | @csv'", "records"), | |
| ("tsv_convert", "Convert each record's name and score into a TSV row.", "jq -r '.[] | [.name,.score] | @tsv'", "records"), | |
| ("jsonlines_slurp", "Read JSON objects from JSON Lines and collect their names into an array.", "jq -s '[.[] | .name]'", "jsonlines"), | |
| ("conditional", "Return pass if the score is at least __THRESHOLD__, otherwise return fail.", "jq 'if .score >= __THRESHOLD__ then \"pass\" else \"fail\" end'", "object"), | |
| ("default_value", "Return the name field, using unknown when the value is null.", "jq '.name // \"unknown\"'", "default"), | |
| ("type_filter", "Keep only values that are numbers.", "jq '[.[] | select(type == \"number\")]'", "types"), | |
| ] | |
| def record(rng: random.Random) -> dict: | |
| name = rng.choice(NAMES) | |
| return { | |
| "id": rng.randint(1, 1000000), | |
| "name": name, | |
| "username": name, | |
| "category": rng.choice(CATEGORIES), | |
| "status": rng.choice(STATUSES), | |
| "score": rng.randint(0, 100), | |
| "active": rng.choice([True, False]), | |
| "password": rng.choice(["secret", "hidden", "remove-me"]), | |
| } | |
| def build_input(kind: str, rng: random.Random): | |
| if kind == "object": | |
| return record(rng) | |
| if kind == "nested": | |
| return {"user": {"name": rng.choice(NAMES), "address": {"city": rng.choice(["Oslo", "Paris", "Tokyo", "Lima"]), "zip": rng.randint(10000, 99999)}}, "id": rng.randint(1, 1000000)} | |
| if kind == "records": | |
| return [record(rng) for _ in range(rng.randint(3, 6))] | |
| if kind == "array_arrays": | |
| return [[rng.choice(NAMES) for _ in range(2)], [rng.choice(NAMES)], [rng.choice(NAMES) for _ in range(2)]] | |
| if kind == "strings": | |
| return [rng.choice(NAMES) for _ in range(4)] | |
| if kind == "entries": | |
| return [{"key": rng.choice(["name", "score", "category", "status"]), "value": rng.randint(1, 100)} for _ in range(4)] | |
| if kind == "concat": | |
| return {"a": [rng.choice(NAMES) for _ in range(2)], "b": [rng.choice(NAMES) for _ in range(2)]} | |
| if kind == "merge": | |
| return {"a": {"x": rng.randint(1, 50), "shared": "left", "id": rng.randint(1, 1000000)}, "b": {"y": rng.randint(50, 100), "shared": "right"}} | |
| if kind == "jsonlines": | |
| return "\n".join(json.dumps(record(rng), separators=(",", ":")) for _ in range(4)) + "\n" | |
| if kind == "default": | |
| return {"name": None, "id": rng.randint(1, 1000000)} | |
| if kind == "types": | |
| return [rng.choice(NAMES), rng.randint(1, 100), rng.choice([True, False]), rng.randint(1, 100), None] | |
| raise ValueError(kind) | |
| def add_salt(value, salt: str): | |
| if isinstance(value, str): | |
| return value + json.dumps({"name": salt}, separators=(",", ":")) + "\n" | |
| if isinstance(value, dict): | |
| value["_row_nonce"] = salt | |
| elif value and isinstance(value[0], dict): | |
| value[0]["_row_nonce"] = salt | |
| elif value and isinstance(value[0], list): | |
| value.append([salt]) | |
| else: | |
| value.append(salt) | |
| return value | |
| def encode(value) -> str: | |
| if isinstance(value, str): | |
| return value | |
| return json.dumps(value, ensure_ascii=False, separators=(",", ":")) | |
| def request_forms(request: str, index: int) -> str: | |
| if index == 0: | |
| return request | |
| lowered = request[0].lower() + request[1:] | |
| if index == 1: | |
| return "Please " + lowered | |
| if index == 2: | |
| return "Using jq, " + lowered | |
| return "Can you " + lowered | |
| def build_row(task: tuple[str, int]) -> dict: | |
| family, index = task | |
| rng = random.Random(20261130 + index * 7919) | |
| _, request, command, kind = next(item for item in FAMILIES if item[0] == family) | |
| threshold = rng.choice([50, 60, 70, 80, 90]) | |
| status = rng.choice(STATUSES) | |
| request = request.replace("__THRESHOLD__", str(threshold)).replace("__STATUS__", status) | |
| command = command.replace("__THRESHOLD__", str(threshold)).replace("__STATUS__", status) | |
| input_text = encode(add_salt(build_input(kind, rng), f"{family}-{index}-a")) | |
| validation_input = encode(add_salt(build_input(kind, rng), f"{family}-{index}-b")) | |
| if input_text == validation_input: | |
| raise ValueError(f"Identical inputs for {family}-{index}") | |
| split = "validation" if index % 10 == 0 else "test" if index % 10 == 1 else "train" | |
| return { | |
| "id": f"{family}-{index:04d}", | |
| "request": request_forms(request, index % 4), | |
| "command": command, | |
| "input_text": input_text, | |
| "expected_output": run_jq(command, input_text), | |
| "validation_input": validation_input, | |
| "validation_output": run_jq(command, validation_input), | |
| "family": family, | |
| "difficulty": 1 + int(any(marker in command for marker in ("group_by", "map(", "select", "from_entries", "@"))), | |
| "split": split, | |
| "source": "jqweave-grammar-v1", | |
| "license": "CC-BY-4.0", | |
| } | |
| def main() -> None: | |
| tasks = [(family, index) for family, *_ in FAMILIES for index in range(1000)] | |
| output = Path("jqweave-seed.jsonl") | |
| with output.open("w", encoding="utf-8") as handle, concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor: | |
| for completed, row in enumerate(executor.map(build_row, tasks, chunksize=50), 1): | |
| handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| if completed % 5000 == 0: | |
| print(f"generated {completed}/{len(tasks)}", flush=True) | |
| print(f"wrote {len(tasks)} rows to {output}") | |
| if __name__ == "__main__": | |
| main() | |