File size: 2,044 Bytes
21e19b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import time
import urllib.parse
import urllib.request
from pathlib import Path

API_ROOT = "https://api.stackexchange.com/2.3"


def get_json(path: str, **params) -> dict:
    query = urllib.parse.urlencode({"site": "stackoverflow", "filter": "withbody", **params})
    request = urllib.request.Request(
        f"{API_ROOT}/{path}?{query}",
        headers={"User-Agent": "Asterbraid-Sedweave-Dataset/1.0"},
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        data = json.load(response)
    if "error_message" in data:
        raise RuntimeError(data["error_message"])
    if data.get("backoff"):
        time.sleep(data["backoff"])
    return data


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-dir", type=Path, default=Path(".tmp"))
    parser.add_argument("--pages", type=int, default=1)
    args = parser.parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)

    questions = []
    for page in range(1, args.pages + 1):
        data = get_json("questions", order="desc", sort="votes", tagged="sed", pagesize=100, page=page)
        questions.extend(data["items"])
        if not data.get("has_more"):
            break
    (args.output_dir / "sed-questions.json").write_text(json.dumps({"items": questions}, indent=2), encoding="utf-8")

    answer_ids = [str(question["accepted_answer_id"]) for question in questions if "accepted_answer_id" in question]
    answers = {}
    for start in range(0, len(answer_ids), 100):
        batch = answer_ids[start:start + 100]
        data = get_json("answers/" + ";".join(batch), order="desc", sort="activity", pagesize=100)
        for answer in data["items"]:
            answers[str(answer["answer_id"])] = answer
    (args.output_dir / "sed-answers.json").write_text(json.dumps(answers, indent=2), encoding="utf-8")
    print(f"saved {len(questions)} questions and {len(answers)} accepted answers")


if __name__ == "__main__":
    main()