File size: 10,761 Bytes
8a9c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import concurrent.futures
import json
import random
import shlex
from dataclasses import dataclass
from pathlib import Path

from sedweave.execution import run_sed

NAMES = ["alice", "bruno", "chen", "dina", "eli", "farah", "gus", "hana"]
WORDS = ["amber", "birch", "cobalt", "delta", "ember", "fable", "grove", "harbor"]
STATUSES = ["active", "pending", "closed", "ready", "failed"]


@dataclass
class Case:
    request: str
    command: str
    inputs: list[str]
    family: str
    difficulty: int


def text(rng: random.Random, count: int | None = None, separator: str = " ") -> str:
    lines = []
    for _ in range(count or rng.randint(6, 9)):
        fields = [rng.choice(NAMES), rng.choice(WORDS), str(rng.randint(0, 120)), rng.choice(STATUSES)]
        lines.append(separator.join(fields))
    return "\n".join(lines) + "\n"


def pair(rng: random.Random, separator: str = " ", transform=None) -> list[str]:
    values = [text(rng, separator=separator), text(rng, separator=separator)]
    if transform:
        values = [transform(value) for value in values]
    return values


def make_case(family: str, seed: int) -> Case:
    rng = random.Random(seed)
    if family == "substitute_first":
        old, new = rng.sample(WORDS, 2)
        return Case(f"Replace the first occurrence of {old} with {new} on each line.", f"s/{old}/{new}/", pair(rng), family, 1)
    if family == "substitute_global":
        old, new = rng.sample(WORDS, 2)
        return Case(f"Replace every occurrence of {old} with {new} throughout the input.", f"s/{old}/{new}/g", pair(rng), family, 1)
    if family == "regex_delete":
        status = rng.choice(STATUSES)
        return Case(f"Delete every line containing {status}.", f"/{status}/d", pair(rng), family, 1)
    if family == "regex_print":
        status = rng.choice(STATUSES)
        return Case(f"Print only lines containing {status}; suppress all others.", f"-n /{status}/p", pair(rng), family, 1)
    if family == "line_range":
        start = rng.randint(2, 4)
        end = start + rng.randint(1, 3)
        return Case(f"Print lines {start} through {end}, inclusive, and nothing else.", f"-n {start},{end}p", pair(rng), family, 1)
    if family == "delete_range":
        start = rng.randint(2, 4)
        end = start + rng.randint(1, 2)
        return Case(f"Delete lines {start} through {end}, leaving all other lines unchanged.", f"{start},{end}d", pair(rng), family, 1)
    if family == "first_n":
        count = rng.randint(2, 4)
        return Case(f"Print only the first {count} lines.", f"-n 1,{count}p", pair(rng), family, 1)
    if family == "last_line":
        return Case("Print only the last line of the input.", "-n $p", pair(rng), family, 1)
    if family == "delete_last":
        return Case("Delete the last line of the input and print all remaining lines.", "$d", pair(rng), family, 1)
    if family == "every_other":
        return Case("Print odd-numbered lines: lines 1, 3, 5, and so on.", "-n 0~2p", pair(rng), family, 2)
    if family == "append_after":
        status = rng.choice(STATUSES)
        note = rng.choice(["follow_up", "reviewed", "complete"])
        return Case(f"Append the line {note} immediately after every line containing {status}.", f"/{status}/a {note}", pair(rng), family, 2)
    if family == "insert_before":
        status = rng.choice(STATUSES)
        note = rng.choice(["follow_up", "reviewed", "complete"])
        return Case(f"Insert the line {note} immediately before every line containing {status}.", f"/{status}/i {note}", pair(rng), family, 2)
    if family == "change_line":
        status = rng.choice(STATUSES)
        note = rng.choice(["follow_up", "reviewed", "complete"])
        return Case(f"Replace every full line containing {status} with the single line {note}.", f"/{status}/c {note}", pair(rng), family, 2)
    if family == "delete_blank":
        return Case("Delete all empty lines while preserving every nonempty line.", "/^$/d", pair(rng, transform=lambda value: value.replace("\n", "\n\n", 2)), family, 1)
    if family == "strip_leading":
        return Case("Remove all leading spaces and tabs from each line.", "s/^[ \\t]*//", pair(rng, transform=lambda value: value.replace(" ", "  ")), family, 1)
    if family == "strip_trailing":
        return Case("Remove all trailing spaces and tabs from each line.", "s/[ \\t]*$//", pair(rng, transform=lambda value: value.replace(" ", "  ")), family, 1)
    if family == "collapse_space":
        return Case("Collapse every run of spaces or tabs to a single space.", "s/[ \\t]+/ /g", pair(rng, transform=lambda value: value.replace(" ", "  ")), family, 1)
    if family == "uppercase":
        return Case("Convert every input line to uppercase.", "s/.*/\\U&/", pair(rng), family, 1)
    if family == "lowercase":
        return Case("Convert every input line to lowercase.", "s/.*/\\L&/", pair(rng), family, 1)
    if family == "swap_fields":
        return Case("Swap the first two whitespace-separated fields on every line.", "s/\\([^ ]*\\) \\([^ ]*\\)/\\2 \\1/", pair(rng), family, 2)
    if family == "comma_to_tab":
        return Case("Replace every comma with a tab character.", "s/,/\\t/g", pair(rng, separator=","), family, 1)
    if family == "add_prefix":
        prefix = rng.choice(["INFO", "record", "notice"])
        return Case(f"Add the prefix {prefix} followed by a space to the start of every line.", f"s/^/{prefix} /", pair(rng), family, 1)
    if family == "add_suffix":
        suffix = rng.choice(["complete", "reviewed", "done"])
        return Case(f"Append a space and {suffix} to the end of every line.", f"s/$/ {suffix}/", pair(rng), family, 1)
    if family == "comment_lines":
        return Case("Comment out every input line by adding # and a space at the start.", "s/^/# /", pair(rng), family, 1)
    if family == "delete_comments":
        return Case("Delete all lines beginning with #.", "/^#/d", pair(rng, transform=lambda value: value.replace("\n", "\n# note\n", 1)), family, 1)
    if family == "first_chars":
        count = rng.randint(2, 6)
        return Case(f"Print only the first {count} characters of each line.", f"s/^\\(.\\{{{count}\\}}\\).*/\\1/", pair(rng), family, 2)
    if family == "delete_between":
        start, end = rng.sample(WORDS, 2)
        return Case(f"Delete everything from the line containing {start} through the line containing {end}, inclusive.", f"/{start}/,/{end}/d", pair(rng), family, 2)
    if family == "print_between":
        start, end = rng.sample(WORDS, 2)
        return Case(f"Print only the block from the line containing {start} through the line containing {end}, inclusive.", f"-n /{start}/,/{end}/p", pair(rng), family, 2)
    if family == "remove_html":
        return Case("Remove all HTML-like angle-bracket tags from the text.", "s/<[^>]*>//g", ["<p>amber <b>birch</b></p>\n<span>delta</span>\n", "<div>grove <i>fable</i></div>\n",], family, 1)
    if family == "digits_mask":
        return Case("Replace every sequence of digits with the letter N.", "s/[0-9][0-9]*/N/g", pair(rng), family, 1)
    if family == "number_lines":
        return Case("Print each input line's number, without printing the line contents.", "=", pair(rng), family, 1)
    if family == "delete_first_char":
        return Case("Remove the first character from every line.", "s/^.//", pair(rng), family, 1)
    if family == "delete_last_char":
        return Case("Remove the last character from every line.", "s/.$//", pair(rng), family, 1)
    if family == "extract_second_csv":
        return Case("Print only the second comma-separated field from each line.", "s/[^,]*,\\([^,]*\\).*/\\1/", pair(rng, separator=","), family, 2)
    raise ValueError(family)


FAMILIES = [
    "substitute_first", "substitute_global", "regex_delete", "regex_print", "line_range",
    "delete_range", "first_n", "last_line", "delete_last", "every_other", "append_after",
    "insert_before", "change_line", "delete_blank", "strip_leading", "strip_trailing",
    "collapse_space", "uppercase", "lowercase", "swap_fields", "comma_to_tab", "add_prefix",
    "add_suffix", "comment_lines", "delete_comments", "first_chars", "delete_between",
    "print_between", "remove_html", "digits_mask", "number_lines", "delete_first_char",
    "delete_last_char", "extract_second_csv",
]


def shell_command(case_command: str) -> str:
    if case_command.startswith("-n "):
        return "sed -n " + shlex.quote(case_command[3:])
    return "sed " + shlex.quote(case_command)


def generate_row(index: int, seed: int) -> dict:
    family = FAMILIES[index % len(FAMILIES)]
    for attempt in range(100):
        case = make_case(family, seed + index * 1009 + attempt * 1_000_003)
        command = shell_command(case.command)
        try:
            outputs = [run_sed(command, input_text) for input_text in case.inputs]
        except ValueError:
            continue
        if not outputs[0].strip():
            continue
        split = "train" if index % 100 < 90 else "validation" if index % 100 < 95 else "test"
        return {
            "id": f"sedweave-{index:07d}", "request": case.request, "command": command,
            "input_text": case.inputs[0], "expected_output": outputs[0],
            "validation_input": case.inputs[1], "validation_output": outputs[1],
            "family": case.family, "difficulty": case.difficulty, "split": split,
            "source": "original-grammar", "license": "CC-BY-4.0",
        }
    raise RuntimeError(f"Could not generate {family} at {index}")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--count", type=int, default=34_000)
    parser.add_argument("--seed", type=int, default=20261129)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--output", type=Path, default=Path("sedweave-seed.jsonl"))
    args = parser.parse_args()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as handle:
        with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor:
            futures = {executor.submit(generate_row, index, args.seed): index for index in range(args.count)}
            completed = 0
            for future in concurrent.futures.as_completed(futures):
                row = future.result()
                handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
                completed += 1
                if completed % 1000 == 0:
                    handle.flush()
                    print(f"generated {completed}/{args.count}", flush=True)
    print(f"wrote {args.count} rows to {args.output}")


if __name__ == "__main__":
    main()