Download audit_paraphrases.py from asterbraid/awkweave-data: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/datasets/asterbraid/awkweave-data/resolve/main/audit_paraphrases.py
- Command line
-
hf download hf://datasets/asterbraid/awkweave-data/audit_paraphrases.py
-
curl -L -o audit_paraphrases.py https://huggingface.co/datasets/asterbraid/awkweave-data/resolve/main/audit_paraphrases.py
5.46 kB
| from __future__ import annotations | |
| import argparse | |
| import concurrent.futures | |
| import json | |
| import os | |
| import random | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| MODEL = "qwen/qwen3.5-9b" | |
| def audit_batch(rows: list[dict]) -> list[bool]: | |
| pairs = [{"original": row["original_request"], "paraphrase": row["request"]} for row in rows] | |
| payload = { | |
| "model": MODEL, | |
| "messages": [ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "You audit technical paraphrases. Return only valid JSON. Mark equivalence true " | |
| "only when both requests describe exactly the same text-processing operation, " | |
| "including field positions and names, literal values, inclusion and exclusion, " | |
| "input separators, output formatting, ordering, and tie-breaking. Wording may differ. " | |
| "If either request adds, removes, or changes a constraint, mark false." | |
| ), | |
| }, | |
| { | |
| "role": "user", | |
| "content": "Return {\"equivalent\": [true or false, ...]} with one boolean per pair.\n" | |
| + json.dumps(pairs, ensure_ascii=False), | |
| }, | |
| ], | |
| "response_format": {"type": "json_object"}, | |
| "temperature": 0, | |
| "max_tokens": 2000, | |
| "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(6): | |
| try: | |
| with urllib.request.urlopen(request, timeout=120) as response: | |
| data = json.load(response) | |
| result = json.loads(data["choices"][0]["message"]["content"])["equivalent"] | |
| if not isinstance(result, list) or len(result) != len(rows) or not all(isinstance(value, bool) for value in result): | |
| raise ValueError("Invalid equivalence response") | |
| return result | |
| except Exception: | |
| if attempt == 5: | |
| raise | |
| time.sleep(min(30, 2 ** attempt)) | |
| raise AssertionError("unreachable") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("data", type=Path) | |
| parser.add_argument("output", type=Path) | |
| parser.add_argument("--rows", type=int, default=500) | |
| parser.add_argument("--batch-size", type=int, default=10) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument("--seed", type=int, default=20261128) | |
| args = parser.parse_args() | |
| all_rows = [json.loads(line) for line in args.data.open(encoding="utf-8")] | |
| originals = {row["id"]: row for row in all_rows if not row.get("paraphrase_of")} | |
| candidates = [row for row in all_rows if row["source"] == "openrouter-paraphrase"] | |
| random.Random(args.seed).shuffle(candidates) | |
| selected = candidates[: args.rows] | |
| for row in selected: | |
| row["original_request"] = originals[row["paraphrase_of"]]["request"] | |
| existing = {} | |
| if args.output.exists(): | |
| for line in args.output.open(encoding="utf-8"): | |
| row = json.loads(line) | |
| existing[row["id"]] = row | |
| pending = [row for row in selected if row["id"] not in existing] | |
| batches = [pending[index:index + args.batch_size] for index in range(0, len(pending), args.batch_size)] | |
| failures = 0 | |
| completed = len(selected) - len(pending) | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor: | |
| futures = {executor.submit(audit_batch, batch): batch for batch in batches} | |
| for future in concurrent.futures.as_completed(futures): | |
| batch = futures[future] | |
| try: | |
| verdicts = future.result() | |
| except Exception as error: | |
| failures += len(batch) | |
| print(f"Audit batch failed; rerun to resume: {error}", flush=True) | |
| continue | |
| with args.output.open("a", encoding="utf-8") as handle: | |
| for row, equivalent in zip(batch, verdicts): | |
| handle.write(json.dumps({ | |
| "id": row["id"], "original": row["original_request"], | |
| "paraphrase": row["request"], "equivalent": equivalent, | |
| }, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| completed += len(batch) | |
| print(f"audited {completed}/{len(selected)}", flush=True) | |
| results = list(existing.values()) | |
| if args.output.exists(): | |
| results = [json.loads(line) for line in args.output.open(encoding="utf-8")] | |
| results.sort(key=lambda row: row["id"]) | |
| summary = { | |
| "model": MODEL, "seed": args.seed, "rows": len(results), "requested": len(selected), | |
| "missing": len(selected) - len(results), "equivalent": sum(row["equivalent"] for row in results), | |
| "disputed": sum(not row["equivalent"] for row in results), | |
| "audit_file": str(args.output), | |
| } | |
| args.output.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") | |
| print(json.dumps(summary, indent=2)) | |
| if failures or len(results) != len(selected): | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |