File size: 9,393 Bytes
b85888c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import re
import time
import urllib.error
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_])")
LITERAL_PATTERN = re.compile(r'"([^"\n]+)"')


def literals_to_preserve(row: dict) -> list[str]:
    values = []
    for value in LITERAL_PATTERN.findall(row["program"]):
        if "\\" in value or "%" in value or value in {" ", ",", "\\t"}:
            continue
        if len(value) >= 2:
            values.append(value)
    values.extend(re.findall(r"/\^?([A-Z][A-Z0-9 _-]{1,})/", row["program"]))
    return sorted(set(values))


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 "")
    elif number < 120:
        remainder = number % 100
        tail = units[remainder] if remainder < 10 else teens[remainder - 10]
        words = "one hundred" + (" " + tail if remainder 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",
        100: "one hundredth",
    }
    if number in ordinals:
        ordinal = ordinals[number]
    elif number < 100:
        ordinal = tens[number // 10] + "-" + ordinals[number % 10]
    else:
        ordinal = str(number)
    return {str(number), words, words.replace("-", " "), ordinal, ordinal.replace("-", " ")}


def valid_paraphrase(original: str, paraphrase: str, row: dict) -> bool:
    paraphrase = paraphrase.strip()
    if not 10 <= len(paraphrase) <= 400 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
    if any(value not in paraphrase for value in literals_to_preserve(row)):
        return False
    for marker in ("comma-separated", "tab-separated", "first appearance", "two decimal places"):
        if marker in original.lower() and marker not in lowered:
            synonyms = {
                "comma-separated": ("comma separated", "csv"),
                "tab-separated": ("tab separated", "tsv"),
                "first appearance": ("first appear", "order in which", "order they appear"),
                "two decimal places": ("2 decimal places", "two decimals"),
            }
            if not any(term in lowered for term in synonyms[marker]):
                return False
    return True


def request_batch(batch: list[dict], timeout: int = 120) -> list[str]:
    payload = {
        "model": MODEL,
        "messages": [
            {
                "role": "system",
                "content": (
                    "You paraphrase technical text-processing requests. Return only valid JSON. "
                    "Preserve the exact operation, every numeric value as an Arabic numeral, all field "
                    "positions and names, literal values, input separator, output formatting, ordering, "
                    "and tie-breaking requirements. Do not add or remove constraints. Keep each request "
                    "concise and natural, and vary sentence structure. Keep every numeric value unchanged."
                ),
            },
            {
                "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.85,
        "max_tokens": 3000,
        "reasoning": {"enabled": False},
    }
    base_url = os.environ["OPENROUTER_BASE_URL"].rstrip("/")
    request = urllib.request.Request(
        base_url + "/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=timeout) as response:
                data = json.load(response)
            content = data["choices"][0]["message"]["content"]
            parsed = json.loads(content)
            paraphrases = parsed["paraphrases"]
            if not isinstance(paraphrases, list) or len(paraphrases) != len(batch):
                raise ValueError("Wrong paraphrase count")
            return [str(value).strip() for value in paraphrases]
        except (urllib.error.URLError, urllib.error.HTTPError, KeyError, ValueError, json.JSONDecodeError) as error:
            if attempt == 3:
                raise RuntimeError(f"Paraphrase request failed after retries: {error}") from error
            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)
    parser.add_argument("--batch-size", type=int, default=12)
    parser.add_argument("--workers", type=int, default=16)
    parser.add_argument("--limit", type=int)
    args = parser.parse_args()

    rows = [json.loads(line) for line in args.input.open(encoding="utf-8")]
    rows.sort(key=lambda row: row["id"])
    eligible = [row for row in rows if row["split"] == "train"]
    if args.limit:
        eligible = eligible[: args.limit]

    existing_paraphrases = {}
    if args.output.exists():
        for line in args.output.open(encoding="utf-8"):
            row = json.loads(line)
            if row.get("paraphrase_of"):
                existing_paraphrases[row["paraphrase_of"]] = row
    batches = [eligible[index:index + args.batch_size] for index in range(0, len(eligible), args.batch_size)]
    batches = [batch for batch in batches if any(row["id"] not in existing_paraphrases for row in batch)]

    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
        for row in existing_paraphrases.values():
            handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")

    accepted = 0
    fallback = 0
    completed = 0
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) 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:
                paraphrases = future.result()
            except Exception as error:
                print(f"batch failed; retaining originals: {error}", flush=True)
                paraphrases = [row["request"] for row in batch]
            new_rows = []
            for row, paraphrase in zip(batch, paraphrases):
                if row["id"] in existing_paraphrases:
                    continue
                new_row = dict(row)
                new_row["id"] = row["id"] + "-p1"
                new_row["paraphrase_of"] = row["id"]
                new_row["paraphrase_model"] = MODEL
                if valid_paraphrase(row["request"], paraphrase, row):
                    new_row["request"] = paraphrase
                    new_row["source"] = "openrouter-paraphrase"
                    accepted += 1
                else:
                    new_row["source"] = "original-grammar-copy"
                    fallback += 1
                new_rows.append(new_row)
            with args.output.open("a", encoding="utf-8") as handle:
                for row in new_rows:
                    handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
            completed += len(batch)
            if completed % 240 == 0 or completed == len(eligible):
                print(f"paraphrased {completed}/{len(eligible)}; accepted={accepted}; guarded={fallback}", flush=True)
    print(f"wrote {len(rows) + len(eligible)} rows to {args.output}; accepted={accepted}; guarded={fallback}")


if __name__ == "__main__":
    main()