File size: 6,118 Bytes
d96cf4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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()