asterbraid commited on
Commit
8a9c862
·
verified ·
1 Parent(s): f36a2fc

Sedweave: 34k execution-verified natural-language-to-sed examples

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/train.jsonl filter=lfs diff=lfs merge=lfs -text
DATASET_LICENSE.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Awkweave dataset rows are licensed under the Creative Commons Attribution 4.0 International License (CC BY 4.0).
2
+
3
+ Copyright 2026 Asterbraid.
4
+
5
+ You are free to share and adapt the dataset, including for commercial purposes, provided that you give appropriate credit to Asterbraid, provide a link to the license, and indicate if changes were made. You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
6
+
7
+ The full license and its disclaimer of warranties and limitation of liability are available at:
8
+ https://creativecommons.org/licenses/by/4.0/
9
+ https://creativecommons.org/licenses/by/4.0/legalcode
10
+
11
+ This notice applies to dataset rows, not to the Apache-2.0-licensed code or model weights.
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ language: en
4
+ pretty_name: Sedweave Data
5
+ size_categories:
6
+ - 10K<n<100K
7
+ task_categories:
8
+ - text-generation
9
+ tags:
10
+ - sed
11
+ - code-generation
12
+ - text-to-code
13
+ - execution-verified
14
+ - synthetic-data
15
+ configs:
16
+ - config_name: default
17
+ data_files:
18
+ - split: train
19
+ path: data/train.jsonl
20
+ - split: validation
21
+ path: data/validation.jsonl
22
+ - split: test
23
+ path: data/test.jsonl
24
+ ---
25
+
26
+ # Sedweave Data
27
+
28
+ Execution-verified natural-language-to-`sed` examples for training and evaluating small local code models.
29
+
30
+ ## Rows
31
+
32
+ | Split | Rows | Purpose |
33
+ | --- | ---: | --- |
34
+ | train | 30600 | Supervised fine-tuning |
35
+ | validation | 1700 | Training diagnostics |
36
+ | test | 1700 | Held-out grammar-generated evaluation |
37
+ | **total** | **34000** | |
38
+
39
+ Each row contains a request, a bare `sed` command with no filename, two different input texts, and exact outputs produced by real GNU sed for each input. The generator covers 34 task families: substitutions, filtering, line ranges, insertion, field edits, case changes, whitespace cleanup, delimiter conversion, and marker blocks.
40
+
41
+ ## Verification
42
+
43
+ Every row was re-executed with `/usr/bin/sed (GNU sed) 4.8` on both inputs: **68000 successful executions, 0 errors**. `validation.json` contains hashes, full counts, and split integrity.
44
+
45
+ The command guard accepts only `sed` on stdin/stdout and rejects filenames, in-place edits, file commands, pipes, and shell execution. The included `sedweave.execution` module applies the same restrictions and resource limits.
46
+
47
+ ## Use
48
+
49
+ ```python
50
+ from datasets import load_dataset
51
+
52
+ ds = load_dataset("asterbraid/sedweave-data")
53
+ print(ds["train"][0]["request"])
54
+ print(ds["train"][0]["command"])
55
+ ```
56
+
57
+ ## Scope and limitations
58
+
59
+ - English only; output is a `sed` command, not a general shell assistant.
60
+ - No filenames, in-place edits, file commands, external pipelines, or shell execution.
61
+ - Train, validation, and test come from the same 34-family grammar with different random records. Input texts are disjoint, but identical request/command pairs can recur with different input records. Test accuracy is in-distribution only.
62
+ - Exact execution verifies reference commands, not that every request is unambiguous or model generations will be correct.
63
+
64
+ ## Provenance and license
65
+
66
+ All commands, inputs, and outputs are original synthetic artifacts with no scraped text or personal data. Rows are **CC-BY-4.0**; attribute **Asterbraid**. Included code is Apache-2.0.
data/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/train.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e999823ff312342e5c014044279c9a0e0717020ef961e312cb57472736b6294e
3
+ size 28327180
data/validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
generate_data.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import concurrent.futures
5
+ import json
6
+ import random
7
+ import shlex
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from sedweave.execution import run_sed
12
+
13
+ NAMES = ["alice", "bruno", "chen", "dina", "eli", "farah", "gus", "hana"]
14
+ WORDS = ["amber", "birch", "cobalt", "delta", "ember", "fable", "grove", "harbor"]
15
+ STATUSES = ["active", "pending", "closed", "ready", "failed"]
16
+
17
+
18
+ @dataclass
19
+ class Case:
20
+ request: str
21
+ command: str
22
+ inputs: list[str]
23
+ family: str
24
+ difficulty: int
25
+
26
+
27
+ def text(rng: random.Random, count: int | None = None, separator: str = " ") -> str:
28
+ lines = []
29
+ for _ in range(count or rng.randint(6, 9)):
30
+ fields = [rng.choice(NAMES), rng.choice(WORDS), str(rng.randint(0, 120)), rng.choice(STATUSES)]
31
+ lines.append(separator.join(fields))
32
+ return "\n".join(lines) + "\n"
33
+
34
+
35
+ def pair(rng: random.Random, separator: str = " ", transform=None) -> list[str]:
36
+ values = [text(rng, separator=separator), text(rng, separator=separator)]
37
+ if transform:
38
+ values = [transform(value) for value in values]
39
+ return values
40
+
41
+
42
+ def make_case(family: str, seed: int) -> Case:
43
+ rng = random.Random(seed)
44
+ if family == "substitute_first":
45
+ old, new = rng.sample(WORDS, 2)
46
+ return Case(f"Replace the first occurrence of {old} with {new} on each line.", f"s/{old}/{new}/", pair(rng), family, 1)
47
+ if family == "substitute_global":
48
+ old, new = rng.sample(WORDS, 2)
49
+ return Case(f"Replace every occurrence of {old} with {new} throughout the input.", f"s/{old}/{new}/g", pair(rng), family, 1)
50
+ if family == "regex_delete":
51
+ status = rng.choice(STATUSES)
52
+ return Case(f"Delete every line containing {status}.", f"/{status}/d", pair(rng), family, 1)
53
+ if family == "regex_print":
54
+ status = rng.choice(STATUSES)
55
+ return Case(f"Print only lines containing {status}; suppress all others.", f"-n /{status}/p", pair(rng), family, 1)
56
+ if family == "line_range":
57
+ start = rng.randint(2, 4)
58
+ end = start + rng.randint(1, 3)
59
+ return Case(f"Print lines {start} through {end}, inclusive, and nothing else.", f"-n {start},{end}p", pair(rng), family, 1)
60
+ if family == "delete_range":
61
+ start = rng.randint(2, 4)
62
+ end = start + rng.randint(1, 2)
63
+ return Case(f"Delete lines {start} through {end}, leaving all other lines unchanged.", f"{start},{end}d", pair(rng), family, 1)
64
+ if family == "first_n":
65
+ count = rng.randint(2, 4)
66
+ return Case(f"Print only the first {count} lines.", f"-n 1,{count}p", pair(rng), family, 1)
67
+ if family == "last_line":
68
+ return Case("Print only the last line of the input.", "-n $p", pair(rng), family, 1)
69
+ if family == "delete_last":
70
+ return Case("Delete the last line of the input and print all remaining lines.", "$d", pair(rng), family, 1)
71
+ if family == "every_other":
72
+ return Case("Print odd-numbered lines: lines 1, 3, 5, and so on.", "-n 0~2p", pair(rng), family, 2)
73
+ if family == "append_after":
74
+ status = rng.choice(STATUSES)
75
+ note = rng.choice(["follow_up", "reviewed", "complete"])
76
+ return Case(f"Append the line {note} immediately after every line containing {status}.", f"/{status}/a {note}", pair(rng), family, 2)
77
+ if family == "insert_before":
78
+ status = rng.choice(STATUSES)
79
+ note = rng.choice(["follow_up", "reviewed", "complete"])
80
+ return Case(f"Insert the line {note} immediately before every line containing {status}.", f"/{status}/i {note}", pair(rng), family, 2)
81
+ if family == "change_line":
82
+ status = rng.choice(STATUSES)
83
+ note = rng.choice(["follow_up", "reviewed", "complete"])
84
+ return Case(f"Replace every full line containing {status} with the single line {note}.", f"/{status}/c {note}", pair(rng), family, 2)
85
+ if family == "delete_blank":
86
+ 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)
87
+ if family == "strip_leading":
88
+ return Case("Remove all leading spaces and tabs from each line.", "s/^[ \\t]*//", pair(rng, transform=lambda value: value.replace(" ", " ")), family, 1)
89
+ if family == "strip_trailing":
90
+ return Case("Remove all trailing spaces and tabs from each line.", "s/[ \\t]*$//", pair(rng, transform=lambda value: value.replace(" ", " ")), family, 1)
91
+ if family == "collapse_space":
92
+ 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)
93
+ if family == "uppercase":
94
+ return Case("Convert every input line to uppercase.", "s/.*/\\U&/", pair(rng), family, 1)
95
+ if family == "lowercase":
96
+ return Case("Convert every input line to lowercase.", "s/.*/\\L&/", pair(rng), family, 1)
97
+ if family == "swap_fields":
98
+ return Case("Swap the first two whitespace-separated fields on every line.", "s/\\([^ ]*\\) \\([^ ]*\\)/\\2 \\1/", pair(rng), family, 2)
99
+ if family == "comma_to_tab":
100
+ return Case("Replace every comma with a tab character.", "s/,/\\t/g", pair(rng, separator=","), family, 1)
101
+ if family == "add_prefix":
102
+ prefix = rng.choice(["INFO", "record", "notice"])
103
+ return Case(f"Add the prefix {prefix} followed by a space to the start of every line.", f"s/^/{prefix} /", pair(rng), family, 1)
104
+ if family == "add_suffix":
105
+ suffix = rng.choice(["complete", "reviewed", "done"])
106
+ return Case(f"Append a space and {suffix} to the end of every line.", f"s/$/ {suffix}/", pair(rng), family, 1)
107
+ if family == "comment_lines":
108
+ return Case("Comment out every input line by adding # and a space at the start.", "s/^/# /", pair(rng), family, 1)
109
+ if family == "delete_comments":
110
+ return Case("Delete all lines beginning with #.", "/^#/d", pair(rng, transform=lambda value: value.replace("\n", "\n# note\n", 1)), family, 1)
111
+ if family == "first_chars":
112
+ count = rng.randint(2, 6)
113
+ return Case(f"Print only the first {count} characters of each line.", f"s/^\\(.\\{{{count}\\}}\\).*/\\1/", pair(rng), family, 2)
114
+ if family == "delete_between":
115
+ start, end = rng.sample(WORDS, 2)
116
+ return Case(f"Delete everything from the line containing {start} through the line containing {end}, inclusive.", f"/{start}/,/{end}/d", pair(rng), family, 2)
117
+ if family == "print_between":
118
+ start, end = rng.sample(WORDS, 2)
119
+ 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)
120
+ if family == "remove_html":
121
+ 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)
122
+ if family == "digits_mask":
123
+ return Case("Replace every sequence of digits with the letter N.", "s/[0-9][0-9]*/N/g", pair(rng), family, 1)
124
+ if family == "number_lines":
125
+ return Case("Print each input line's number, without printing the line contents.", "=", pair(rng), family, 1)
126
+ if family == "delete_first_char":
127
+ return Case("Remove the first character from every line.", "s/^.//", pair(rng), family, 1)
128
+ if family == "delete_last_char":
129
+ return Case("Remove the last character from every line.", "s/.$//", pair(rng), family, 1)
130
+ if family == "extract_second_csv":
131
+ return Case("Print only the second comma-separated field from each line.", "s/[^,]*,\\([^,]*\\).*/\\1/", pair(rng, separator=","), family, 2)
132
+ raise ValueError(family)
133
+
134
+
135
+ FAMILIES = [
136
+ "substitute_first", "substitute_global", "regex_delete", "regex_print", "line_range",
137
+ "delete_range", "first_n", "last_line", "delete_last", "every_other", "append_after",
138
+ "insert_before", "change_line", "delete_blank", "strip_leading", "strip_trailing",
139
+ "collapse_space", "uppercase", "lowercase", "swap_fields", "comma_to_tab", "add_prefix",
140
+ "add_suffix", "comment_lines", "delete_comments", "first_chars", "delete_between",
141
+ "print_between", "remove_html", "digits_mask", "number_lines", "delete_first_char",
142
+ "delete_last_char", "extract_second_csv",
143
+ ]
144
+
145
+
146
+ def shell_command(case_command: str) -> str:
147
+ if case_command.startswith("-n "):
148
+ return "sed -n " + shlex.quote(case_command[3:])
149
+ return "sed " + shlex.quote(case_command)
150
+
151
+
152
+ def generate_row(index: int, seed: int) -> dict:
153
+ family = FAMILIES[index % len(FAMILIES)]
154
+ for attempt in range(100):
155
+ case = make_case(family, seed + index * 1009 + attempt * 1_000_003)
156
+ command = shell_command(case.command)
157
+ try:
158
+ outputs = [run_sed(command, input_text) for input_text in case.inputs]
159
+ except ValueError:
160
+ continue
161
+ if not outputs[0].strip():
162
+ continue
163
+ split = "train" if index % 100 < 90 else "validation" if index % 100 < 95 else "test"
164
+ return {
165
+ "id": f"sedweave-{index:07d}", "request": case.request, "command": command,
166
+ "input_text": case.inputs[0], "expected_output": outputs[0],
167
+ "validation_input": case.inputs[1], "validation_output": outputs[1],
168
+ "family": case.family, "difficulty": case.difficulty, "split": split,
169
+ "source": "original-grammar", "license": "CC-BY-4.0",
170
+ }
171
+ raise RuntimeError(f"Could not generate {family} at {index}")
172
+
173
+
174
+ def main() -> None:
175
+ parser = argparse.ArgumentParser()
176
+ parser.add_argument("--count", type=int, default=34_000)
177
+ parser.add_argument("--seed", type=int, default=20261129)
178
+ parser.add_argument("--workers", type=int, default=8)
179
+ parser.add_argument("--output", type=Path, default=Path("sedweave-seed.jsonl"))
180
+ args = parser.parse_args()
181
+ args.output.parent.mkdir(parents=True, exist_ok=True)
182
+ with args.output.open("w", encoding="utf-8") as handle:
183
+ with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor:
184
+ futures = {executor.submit(generate_row, index, args.seed): index for index in range(args.count)}
185
+ completed = 0
186
+ for future in concurrent.futures.as_completed(futures):
187
+ row = future.result()
188
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
189
+ completed += 1
190
+ if completed % 1000 == 0:
191
+ handle.flush()
192
+ print(f"generated {completed}/{args.count}", flush=True)
193
+ print(f"wrote {args.count} rows to {args.output}")
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
sedweave/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Sedweave: execution-verified natural-language-to-sed tools."""
2
+
3
+ __version__ = "0.1.0"
sedweave/execution.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import resource
5
+ import shlex
6
+ import shutil
7
+ import subprocess
8
+
9
+ MAX_INPUT_BYTES = 1_000_000
10
+ MAX_COMMAND_CHARS = 4_000
11
+ FILE_COMMAND_PATTERN = re.compile(r"(?:^|[;{\s'\"])[rRwWe!|](?:\s|$)")
12
+ SHELL_PATTERN = re.compile(r"[`|]")
13
+
14
+
15
+ class UnsafeCommandError(ValueError):
16
+ pass
17
+
18
+
19
+ def check_command(command: str) -> list[str]:
20
+ if not command.strip():
21
+ raise UnsafeCommandError("The sed command is empty.")
22
+ if len(command) > MAX_COMMAND_CHARS:
23
+ raise UnsafeCommandError("The sed command is too long.")
24
+ try:
25
+ arguments = shlex.split(command)
26
+ except ValueError as error:
27
+ raise UnsafeCommandError(f"Cannot parse sed command: {error}") from error
28
+ if not arguments or arguments[0] != "sed":
29
+ raise UnsafeCommandError("Only sed commands are allowed.")
30
+ if SHELL_PATTERN.search(command):
31
+ raise UnsafeCommandError("Pipes and shell control operators are not allowed.")
32
+ if FILE_COMMAND_PATTERN.search(command):
33
+ raise UnsafeCommandError("File and process commands are not allowed.")
34
+ index = 1
35
+ scripts = 0
36
+ while index < len(arguments):
37
+ argument = arguments[index]
38
+ if argument in {"-n", "--quiet", "--silent"}:
39
+ index += 1
40
+ elif argument in {"-e", "--expression"}:
41
+ if index + 1 >= len(arguments):
42
+ raise UnsafeCommandError("Missing sed expression.")
43
+ scripts += 1
44
+ index += 2
45
+ elif argument.startswith("-"):
46
+ raise UnsafeCommandError(f"Unsupported sed option: {argument}")
47
+ else:
48
+ scripts += 1
49
+ index += 1
50
+ if scripts != 1:
51
+ raise UnsafeCommandError("Expected exactly one sed expression and no filenames.")
52
+ return arguments
53
+
54
+
55
+ def limit_resources() -> None:
56
+ resource.setrlimit(resource.RLIMIT_CPU, (2, 2))
57
+ resource.setrlimit(resource.RLIMIT_AS, (256_000_000, 256_000_000))
58
+ resource.setrlimit(resource.RLIMIT_FSIZE, (1_000_000, 1_000_000))
59
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
60
+ resource.setrlimit(resource.RLIMIT_NOFILE, (16, 16))
61
+
62
+
63
+ def run_sed(command: str, input_text: str, timeout: float = 3.0) -> str:
64
+ arguments = check_command(command)
65
+ if len(input_text.encode("utf-8")) > MAX_INPUT_BYTES:
66
+ raise ValueError("Input text exceeds the 1 MB limit.")
67
+ executable = shutil.which("sed")
68
+ if executable is None:
69
+ raise RuntimeError("No sed executable is available on PATH.")
70
+ result = subprocess.run(
71
+ [executable, *arguments[1:]],
72
+ input=input_text,
73
+ text=True,
74
+ capture_output=True,
75
+ timeout=timeout,
76
+ env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"},
77
+ preexec_fn=limit_resources,
78
+ start_new_session=True,
79
+ check=False,
80
+ )
81
+ if result.returncode != 0:
82
+ raise ValueError(result.stderr.strip() or f"sed exited with status {result.returncode}")
83
+ return result.stdout
sedweave/prompts.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SYSTEM_PROMPT = """You write safe sed commands for text-processing requests. Given a request and sample input, return only a sed command with no filenames or Markdown. Use stdin and stdout only. Do not read or write files, invoke commands, use pipes, or explain."""
2
+
3
+
4
+ def user_prompt(request: str, input_text: str) -> str:
5
+ return f"Request:\n{request.strip()}\n\nSample input:\n```text\n{input_text.rstrip()}\n```"
6
+
7
+
8
+ def messages(request: str, input_text: str) -> list[dict[str, str]]:
9
+ return [
10
+ {"role": "system", "content": SYSTEM_PROMPT},
11
+ {"role": "user", "content": user_prompt(request, input_text)},
12
+ ]
validate_dataset.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import collections
5
+ import concurrent.futures
6
+ import hashlib
7
+ import json
8
+ import shutil
9
+ import subprocess
10
+ from pathlib import Path
11
+
12
+ from sedweave.execution import run_sed
13
+
14
+
15
+ def sed_version() -> str:
16
+ executable = shutil.which("sed")
17
+ if executable is None:
18
+ return "sed unavailable"
19
+ result = subprocess.run([executable, "--version"], capture_output=True, text=True, check=False)
20
+ output = (result.stdout or result.stderr).strip().splitlines()
21
+ if result.returncode == 0 and output:
22
+ return output[0]
23
+ return "unknown sed"
24
+
25
+
26
+ def validate_row(row: dict) -> tuple[str, str | None]:
27
+ try:
28
+ if run_sed(row["command"], row["input_text"]) != row["expected_output"]:
29
+ return row["id"], "primary output mismatch"
30
+ if run_sed(row["command"], row["validation_input"]) != row["validation_output"]:
31
+ return row["id"], "validation output mismatch"
32
+ return row["id"], None
33
+ except Exception as error:
34
+ return row["id"], str(error)[:500]
35
+
36
+
37
+ def main() -> None:
38
+ parser = argparse.ArgumentParser()
39
+ parser.add_argument("data", type=Path)
40
+ parser.add_argument("--workers", type=int, default=8)
41
+ parser.add_argument("--output", type=Path)
42
+ args = parser.parse_args()
43
+ rows = [json.loads(line) for line in args.data.open(encoding="utf-8")]
44
+ ids = [row["id"] for row in rows]
45
+ if len(ids) != len(set(ids)):
46
+ raise ValueError("Duplicate row IDs")
47
+ by_id = {row["id"]: row for row in rows}
48
+ for row in rows:
49
+ if row.get("paraphrase_of"):
50
+ original = by_id.get(row["paraphrase_of"])
51
+ if original is None:
52
+ raise ValueError(f"Missing paraphrase source: {row['id']}")
53
+ for key in ("command", "input_text", "expected_output", "validation_input", "validation_output", "split"):
54
+ if row[key] != original[key]:
55
+ raise ValueError(f"Paraphrase changed {key}: {row['id']}")
56
+ if row["split"] != "train":
57
+ raise ValueError(f"Paraphrase outside train split: {row['id']}")
58
+
59
+ errors = []
60
+ with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor:
61
+ for completed, (row_id, error) in enumerate(executor.map(validate_row, rows, chunksize=20), 1):
62
+ if error:
63
+ errors.append({"id": row_id, "error": error})
64
+ if completed % 5000 == 0:
65
+ print(f"validated {completed}/{len(rows)}", flush=True)
66
+ split_integrity = {}
67
+ for left, right in (
68
+ ("train", "validation"), ("train", "test"), ("validation", "test"),
69
+ ("train", "challenge"), ("validation", "challenge"), ("test", "challenge"),
70
+ ):
71
+ left_rows = [row for row in rows if row["split"] == left and not row.get("paraphrase_of")]
72
+ right_rows = [row for row in rows if row["split"] == right and not row.get("paraphrase_of")]
73
+ split_integrity[f"{left}-{right}"] = {
74
+ "input_overlap": len({row["input_text"] for row in left_rows} & {row["input_text"] for row in right_rows}),
75
+ "request_command_overlap": len(
76
+ {(row["request"], row["command"]) for row in left_rows}
77
+ & {(row["request"], row["command"]) for row in right_rows}
78
+ ),
79
+ }
80
+ summary = {
81
+ "data": str(args.data),
82
+ "sha256": hashlib.sha256(args.data.read_bytes()).hexdigest(),
83
+ "rows": len(rows),
84
+ "executions": len(rows) * 2,
85
+ "sed_version": sed_version(),
86
+ "errors": errors,
87
+ "splits": dict(collections.Counter(row["split"] for row in rows)),
88
+ "sources": dict(collections.Counter(row["source"] for row in rows)),
89
+ "families": dict(collections.Counter(row["family"] for row in rows)),
90
+ "unique_requests": len({row["request"] for row in rows}),
91
+ "unique_commands": len({row["command"] for row in rows}),
92
+ "split_integrity": split_integrity,
93
+ }
94
+ text = json.dumps(summary, indent=2)
95
+ if args.output:
96
+ args.output.write_text(text, encoding="utf-8")
97
+ print(text)
98
+ if errors:
99
+ raise SystemExit(1)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
validation.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "data": "/outputs/67be6bf7-2cc6-4b92-a88f-88554d26e52a/sedweave-seed.jsonl",
3
+ "sha256": "73e826ec0b3be33d7bb1da6a94fb6c38cea137d57146fcbfaacf22f99f7afc06",
4
+ "rows": 34000,
5
+ "executions": 68000,
6
+ "sed_version": "/usr/bin/sed (GNU sed) 4.8",
7
+ "errors": [],
8
+ "splits": {
9
+ "train": 30600,
10
+ "validation": 1700,
11
+ "test": 1700
12
+ },
13
+ "sources": {
14
+ "original-grammar": 34000
15
+ },
16
+ "families": {
17
+ "first_n": 1000,
18
+ "add_suffix": 1000,
19
+ "comment_lines": 1000,
20
+ "line_range": 1000,
21
+ "delete_range": 1000,
22
+ "add_prefix": 1000,
23
+ "regex_print": 1000,
24
+ "comma_to_tab": 1000,
25
+ "regex_delete": 1000,
26
+ "swap_fields": 1000,
27
+ "substitute_global": 1000,
28
+ "delete_blank": 1000,
29
+ "substitute_first": 1000,
30
+ "lowercase": 1000,
31
+ "extract_second_csv": 1000,
32
+ "uppercase": 1000,
33
+ "delete_last_char": 1000,
34
+ "collapse_space": 1000,
35
+ "delete_first_char": 1000,
36
+ "strip_trailing": 1000,
37
+ "number_lines": 1000,
38
+ "strip_leading": 1000,
39
+ "digits_mask": 1000,
40
+ "remove_html": 1000,
41
+ "change_line": 1000,
42
+ "print_between": 1000,
43
+ "insert_before": 1000,
44
+ "delete_between": 1000,
45
+ "append_after": 1000,
46
+ "first_chars": 1000,
47
+ "every_other": 1000,
48
+ "delete_comments": 1000,
49
+ "delete_last": 1000,
50
+ "last_line": 1000
51
+ },
52
+ "unique_requests": 327,
53
+ "unique_commands": 327,
54
+ "split_integrity": {
55
+ "train-validation": {
56
+ "input_overlap": 1,
57
+ "request_command_overlap": 240
58
+ },
59
+ "train-test": {
60
+ "input_overlap": 1,
61
+ "request_command_overlap": 238
62
+ },
63
+ "validation-test": {
64
+ "input_overlap": 1,
65
+ "request_command_overlap": 185
66
+ },
67
+ "train-challenge": {
68
+ "input_overlap": 0,
69
+ "request_command_overlap": 0
70
+ },
71
+ "validation-challenge": {
72
+ "input_overlap": 0,
73
+ "request_command_overlap": 0
74
+ },
75
+ "test-challenge": {
76
+ "input_overlap": 0,
77
+ "request_command_overlap": 0
78
+ }
79
+ }
80
+ }