Datasets:
Sedweave real train/dev/frozen data with original and unselected candidate evaluations
d96cf4e verified Download vary_real_inputs.py from asterbraid/sedweave-real-data: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/datasets/asterbraid/sedweave-real-data/resolve/main/vary_real_inputs.py
- Command line
-
hf download hf://datasets/asterbraid/sedweave-real-data/vary_real_inputs.py
-
curl -L -o vary_real_inputs.py https://huggingface.co/datasets/asterbraid/sedweave-real-data/resolve/main/vary_real_inputs.py
6.08 kB
| from __future__ import annotations | |
| import argparse | |
| import concurrent.futures | |
| import json | |
| import os | |
| import re | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| from sedweave.execution import run_sed | |
| MODEL = "qwen/qwen3.7-plus" | |
| def request_batch(rows: list[dict]) -> list[dict]: | |
| context = [ | |
| { | |
| "id": row["id"], | |
| "request": row["request"], | |
| "command": row["command"], | |
| "example_input": row["input_text"], | |
| } | |
| for row in rows | |
| ] | |
| payload = { | |
| "model": MODEL, | |
| "messages": [ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "Create fresh representative inputs for natural-language-to-sed training tasks. Return only valid " | |
| "JSON with a variations array containing exactly two objects per input task. Each object must have " | |
| "id, input_text, and validation_input. Both inputs must exercise the requested operation, use up to " | |
| "8 lines, differ from each other and from the example input, and include realistic values rather than " | |
| "the expected output. Keep the same schema as the example while varying values and edge cases. Every " | |
| "literal pattern, marker, key name, and delimiter used by the command must remain unchanged; do not " | |
| "invent different markers. Both new inputs must exercise the operation. Use the original task id exactly " | |
| "as id. Do not change the command or request. Expected outputs will be computed by execution." | |
| ), | |
| }, | |
| {"role": "user", "content": json.dumps(context, ensure_ascii=False)}, | |
| ], | |
| "response_format": {"type": "json_object"}, | |
| "temperature": 0.7, | |
| "max_tokens": 6000, | |
| "reasoning": {"enabled": False}, | |
| } | |
| request = urllib.request.Request( | |
| os.environ["OPENROUTER_BASE_URL"].rstrip("/") + "/chat/completions", | |
| data=json.dumps(payload).encode("utf-8"), | |
| headers={"Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"], "Content-Type": "application/json"}, | |
| ) | |
| for attempt in range(4): | |
| try: | |
| with urllib.request.urlopen(request, timeout=180) as response: | |
| data = json.load(response) | |
| return json.loads(data["choices"][0]["message"]["content"])["variations"] | |
| except Exception: | |
| if attempt == 3: | |
| raise | |
| time.sleep(2 ** attempt) | |
| raise AssertionError("unreachable") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("input", type=Path) | |
| parser.add_argument("output", type=Path) | |
| args = parser.parse_args() | |
| originals = [json.loads(line) for line in args.input.open(encoding="utf-8")] | |
| if any(row["split"] != "train" for row in originals): | |
| raise ValueError("Input variations are allowed only for training rows") | |
| by_id = {row["id"]: row for row in originals} | |
| batches = [originals[index:index + 4] for index in range(0, len(originals), 4)] | |
| candidates = [] | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: | |
| futures = [executor.submit(request_batch, batch) for batch in batches] | |
| for future in concurrent.futures.as_completed(futures): | |
| try: | |
| candidates.extend(future.result()) | |
| except Exception as error: | |
| print("batch failed", error, flush=True) | |
| raw_path = args.output.parent / ".tmp" / "so-v2" / "variations-raw.json" | |
| raw_path.parent.mkdir(parents=True, exist_ok=True) | |
| raw_path.write_text(json.dumps(candidates, indent=2), encoding="utf-8") | |
| variants = [] | |
| seen_inputs = {row["input_text"] for row in originals} | |
| counts = {row["id"]: 0 for row in originals} | |
| for candidate in candidates: | |
| row_id = re.sub(r"-var\d+$", "", str(candidate.get("id"))) | |
| if row_id not in by_id or counts[row_id] >= 2: | |
| continue | |
| try: | |
| input_text = candidate["input_text"] | |
| validation_input = candidate["validation_input"] | |
| if input_text == validation_input or input_text in seen_inputs or validation_input in seen_inputs: | |
| raise ValueError("Duplicate input") | |
| literals = [next(value for value in groups if value) for groups in re.findall(r"'([^']+)'|\"([^\"]+)\"|`([^`]+)`", by_id[row_id]["request"])] | |
| if literals and not any(any(literal in text for literal in literals) for text in (input_text, validation_input)): | |
| raise ValueError("No request literal appears in either input") | |
| row = dict(by_id[row_id]) | |
| row["input_text"] = input_text | |
| row["validation_input"] = validation_input | |
| row["expected_output"] = run_sed(row["command"], input_text) | |
| row["validation_output"] = run_sed(row["command"], validation_input) | |
| if not row["expected_output"].strip() or not row["validation_output"].strip(): | |
| raise ValueError("Empty output") | |
| if row["expected_output"] == input_text and row["validation_output"] == validation_input: | |
| raise ValueError("No transformation") | |
| counts[row_id] += 1 | |
| row["id"] = f"{row_id}-v{counts[row_id]}" | |
| row["variation_of"] = row_id | |
| row["source"] = "openrouter-input-variation" | |
| row["variation_model"] = MODEL | |
| seen_inputs.update((input_text, validation_input)) | |
| variants.append(row) | |
| except Exception as error: | |
| print("variant skipped", row_id, str(error)[:160], flush=True) | |
| rows = originals + variants | |
| rows.sort(key=lambda row: row["id"]) | |
| with args.output.open("w", encoding="utf-8") as handle: | |
| for row in rows: | |
| handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| print(f"wrote {len(originals)} originals and {len(variants)} input variations") | |
| if __name__ == "__main__": | |
| main() | |