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 sedweave.execution import run_sed 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 sed questions into executable evaluation tasks. Return only valid JSON " "with a tasks array. Include only questions solvable by one POSIX sed command reading a single text " "stream on stdin and writing to stdout. Skip multi-file, in-place editing, filename, pipeline, shell " "variable, file access, subprocess, interactive, network, and general discussion questions. For each " "suitable question return question_id, request, command, input_text, and validation_input. The request " "must be a natural, self-contained English instruction preserving the question's intent. The command " "must start with sed, contain exactly one expression and no filename, and use no options except -n or " "-e. Do not use -i, r, R, w, W, e, pipes, or shell expansion. Prefer POSIX syntax but allow GNU sed " "supported by the accepted answer, simplified only when needed for stdin and stdout. Provide two " "different representative inputs with up to 8 lines each and the same schema. Do not hardcode answers " "into the command. 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/sed-questions.json") parser.add_argument("--answers", default=".tmp/sed-answers.json") parser.add_argument("--output", default="sedweave-so.jsonl") parser.add_argument("--raw-output", default=".tmp/sed-converted-raw.json") parser.add_argument("--skipped-output", default=".tmp/sed-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).parent.mkdir(parents=True, exist_ok=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() command = item["command"].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_sed(command, input_text) validation_expected = run_sed(command, validation_input) if not expected.strip() or not validation_expected.strip(): raise ValueError("Empty output") if expected == input_text and validation_expected == validation_input: raise ValueError("No transformation") question = matching["question"] answer = matching["answer"] accepted.append({ "id": f"so-{question_id}", "request": request_text, "command": command, "input_text": input_text, "expected_output": expected, "validation_input": validation_input, "validation_output": validation_expected, "family": "real-stackoverflow", "difficulty": 3, "split": "test", "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]}) accepted.sort(key=lambda row: row["id"]) 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()