Datasets:
File size: 7,473 Bytes
b85888c 00af1ab b85888c 00af1ab b85888c 00af1ab b85888c 00af1ab b85888c 00af1ab 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 | from __future__ import annotations
import argparse
import concurrent.futures
import html
import html.parser
import json
import os
import time
import urllib.request
from pathlib import Path
from awkweave.execution import run_awk
MODEL = "qwen/qwen3.7-plus"
class TextExtractor(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self.parts = []
self.skip = 0
def handle_starttag(self, tag, attrs):
if tag in {"script", "style"}:
self.skip += 1
if tag in {"p", "br", "pre", "code", "li", "tr"}:
self.parts.append("\n")
def handle_endtag(self, tag):
if tag in {"script", "style"} and self.skip:
self.skip -= 1
if tag in {"p", "pre", "code", "li", "tr"}:
self.parts.append("\n")
def handle_data(self, data):
if not self.skip:
self.parts.append(data)
def plain(value: str) -> str:
parser = TextExtractor()
parser.feed(value)
text = html.unescape("".join(parser.parts))
return "\n".join(line.strip() for line in text.splitlines() if line.strip())
def convert_batch(items: list[dict]) -> list[dict]:
context = []
for item in items:
question = item["question"]
answer = item["answer"]
context.append({
"question_id": question["question_id"],
"title": question["title"],
"question": plain(question["body"])[:5000],
"accepted_answer": plain(answer["body"])[:5000],
})
payload = {
"model": MODEL,
"messages": [
{
"role": "system",
"content": (
"Convert real Stack Overflow awk questions into executable training tasks. Return only valid JSON "
"with a tasks array. Include only questions solvable by one POSIX awk program reading a single text "
"stream on stdin. Skip sed-only, multi-file, pipeline, file access, shell variable, interactive, "
"network, and general discussion questions. For each suitable question return question_id, request, "
"program, input_text, and validation_input. The request must be a natural, self-contained English "
"instruction preserving the question's intent. The program must be bare awk without the awk executable "
"or filename and must not use system, getline, ARGV, ENVIRON, pipes, or output redirection. Provide "
"two different representative inputs with up to 8 lines each and the same schema. Do not hardcode "
"answers into the program. Do not include expected outputs; they will be computed by execution."
),
},
{"role": "user", "content": "Return {\"tasks\": [...]} or an empty list when unsuitable.\n" + json.dumps(context, ensure_ascii=False)},
],
"response_format": {"type": "json_object"},
"temperature": 0.2,
"max_tokens": 6000,
"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(5):
try:
with urllib.request.urlopen(request, timeout=180) as response:
data = json.load(response)
return json.loads(data["choices"][0]["message"]["content"])["tasks"]
except Exception:
if attempt == 4:
raise
time.sleep(min(30, 2 ** attempt))
raise AssertionError("unreachable")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--questions", default=".tmp/awk-questions.json")
parser.add_argument("--answers", default=".tmp/awk-answers.json")
parser.add_argument("--output", default="awkweave-so.jsonl")
parser.add_argument("--raw-output", default=".tmp/awk-converted-raw.json")
parser.add_argument("--skipped-output", default=".tmp/awk-converted-skipped.json")
args = parser.parse_args()
questions = json.load(open(args.questions))["items"]
answers = json.load(open(args.answers))
items = []
for question in questions:
if "accepted_answer_id" in question:
items.append({"question": question, "answer": answers[str(question["accepted_answer_id"])]})
batches = [items[index:index + 4] for index in range(0, len(items), 4)]
raw = []
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
futures = {executor.submit(convert_batch, batch): batch for batch in batches}
for future in concurrent.futures.as_completed(futures):
try:
raw.extend(future.result())
except Exception as error:
print("batch failed", error, flush=True)
Path(args.raw_output).write_text(json.dumps(raw, indent=2), encoding="utf-8")
accepted = []
skipped = []
seen = set()
for item in raw:
question_id = item.get("question_id")
if question_id in seen:
continue
seen.add(question_id)
matching = next((entry for entry in items if entry["question"]["question_id"] == question_id), None)
if matching is None:
continue
try:
request_text = item["request"].strip()
program = item["program"].strip()
input_text = item["input_text"]
validation_input = item["validation_input"]
if not request_text or input_text == validation_input:
raise ValueError("Missing request or identical inputs")
expected = run_awk(program, input_text)
validation_expected = run_awk(program, validation_input)
if not expected.strip() or not validation_expected.strip():
raise ValueError("Empty output")
question = matching["question"]
answer = matching["answer"]
accepted.append({
"id": f"so-{question_id}", "request": request_text, "program": program,
"input_text": input_text, "expected_output": expected,
"validation_input": validation_input, "validation_output": validation_expected,
"family": "real-stackoverflow", "difficulty": 3, "split": "train",
"source": "stackoverflow-accepted-answer", "license": "CC-BY-SA-4.0",
"question_url": question["link"], "question_title": question["title"],
"question_owner": question["owner"].get("display_name"),
"answer_owner": answer["owner"].get("display_name"),
"answer_id": answer["answer_id"], "question_score": question["score"],
})
except Exception as error:
skipped.append({"question_id": question_id, "reason": str(error)[:300]})
with open(args.output, "w", encoding="utf-8") as handle:
for row in accepted:
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
Path(args.skipped_output).write_text(json.dumps(skipped, indent=2), encoding="utf-8")
print(f"accepted {len(accepted)} tasks; skipped {len(skipped)} invalid tasks from {len(raw)} candidates")
if __name__ == "__main__":
main()
|