Datasets:
Download paraphrase_real_data.py from asterbraid/jqweave-real-train-data: direct link, hf CLI and curl.
- Browser
- Download file 6.12 kB
-
https://huggingface.co/datasets/asterbraid/jqweave-real-train-data/resolve/main/paraphrase_real_data.py
- Command line
-
hf download hf://datasets/asterbraid/jqweave-real-train-data/paraphrase_real_data.py
-
curl -L -o paraphrase_real_data.py https://huggingface.co/datasets/asterbraid/jqweave-real-train-data/resolve/main/paraphrase_real_data.py
6.12 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 | |
| MODEL = "qwen/qwen3.7-plus" | |
| NUMBER_PATTERN = re.compile(r"(?<![A-Za-z_])\d+(?:\.\d+)?(?![A-Za-z_])") | |
| QUOTED_PATTERN = re.compile(r"'([^']+)'|\"([^\"]+)\"|`([^`]+)`") | |
| def number_aliases(number: int) -> set[str]: | |
| units = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] | |
| teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] | |
| tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] | |
| if number < 10: | |
| words = units[number] | |
| elif number < 20: | |
| words = teens[number - 10] | |
| elif number < 100: | |
| words = tens[number // 10] + ("-" + units[number % 10] if number % 10 else "") | |
| else: | |
| words = str(number) | |
| ordinals = { | |
| 0: "zeroth", 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", | |
| 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", | |
| 12: "twelfth", 13: "thirteenth", 14: "fourteenth", 15: "fifteenth", 16: "sixteenth", | |
| 17: "seventeenth", 18: "eighteenth", 19: "nineteenth", 20: "twentieth", 30: "thirtieth", | |
| 40: "fortieth", 50: "fiftieth", 60: "sixtieth", 70: "seventieth", 80: "eightieth", 90: "ninetieth", | |
| } | |
| ordinal = ordinals.get(number, str(number)) | |
| return {str(number), words, words.replace("-", " "), ordinal, ordinal.replace("-", " ")} | |
| def valid_paraphrase(original: str, paraphrase: str) -> bool: | |
| paraphrase = paraphrase.strip() | |
| if not 10 <= len(paraphrase) <= 500 or paraphrase == original.strip(): | |
| return False | |
| if "\n" in paraphrase or "```" in paraphrase: | |
| return False | |
| lowered = paraphrase.lower() | |
| for value in set(NUMBER_PATTERN.findall(original)): | |
| aliases = number_aliases(int(value)) if value.isdigit() else {value} | |
| if not any(re.search(r"(?<![a-z0-9])" + re.escape(alias) + r"(?![a-z0-9])", lowered) for alias in aliases): | |
| return False | |
| for groups in QUOTED_PATTERN.findall(original): | |
| literal = next(value for value in groups if value) | |
| if literal not in paraphrase: | |
| return False | |
| return True | |
| def request_batch(batch: list[dict]) -> list[str]: | |
| payload = { | |
| "model": MODEL, | |
| "messages": [ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "Paraphrase technical text-processing requests. Return only valid JSON. Preserve the exact operation, " | |
| "every number, literal string, pattern, position, separator, output format, ordering, and constraint. " | |
| "Keep all quoted literals unchanged. Do not add or remove requirements. Keep each request concise and " | |
| "natural, and vary sentence structure." | |
| ), | |
| }, | |
| { | |
| "role": "user", | |
| "content": "Return {\"paraphrases\": [...]} with exactly one paraphrase per numbered input, in order.\n" | |
| + "\n".join(f"{index}. {row['request']}" for index, row in enumerate(batch, 1)), | |
| }, | |
| ], | |
| "response_format": {"type": "json_object"}, | |
| "temperature": 0.8, | |
| "max_tokens": 4000, | |
| "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) | |
| values = json.loads(data["choices"][0]["message"]["content"])["paraphrases"] | |
| if not isinstance(values, list) or len(values) != len(batch): | |
| raise ValueError("Wrong paraphrase count") | |
| return [str(value).strip() for value in values] | |
| 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() | |
| rows = [json.loads(line) for line in args.input.open(encoding="utf-8")] | |
| if any(row["split"] != "train" for row in rows): | |
| raise ValueError("Paraphrases are allowed only for training rows") | |
| batches = [rows[index:index + 12] for index in range(0, len(rows), 12)] | |
| paraphrases = [] | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: | |
| futures = {executor.submit(request_batch, batch): batch for batch in batches} | |
| for future in concurrent.futures.as_completed(futures): | |
| batch = futures[future] | |
| try: | |
| values = future.result() | |
| except Exception as error: | |
| print("batch failed", error, flush=True) | |
| continue | |
| for row, value in zip(batch, values): | |
| if not valid_paraphrase(row["request"], value): | |
| continue | |
| new_row = dict(row) | |
| new_row["id"] = row["id"] + "-p1" | |
| new_row["paraphrase_of"] = row["id"] | |
| new_row["request"] = value | |
| new_row["source"] = "openrouter-paraphrase" | |
| new_row["paraphrase_model"] = MODEL | |
| paraphrases.append(new_row) | |
| output = rows + paraphrases | |
| output.sort(key=lambda row: row["id"]) | |
| with args.output.open("w", encoding="utf-8") as handle: | |
| for row in output: | |
| handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| print(f"wrote {len(rows)} originals and {len(paraphrases)} guarded paraphrases") | |
| if __name__ == "__main__": | |
| main() | |