File size: 7,386 Bytes
0eb2e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Collect candidate GitHub issue threads about deploying AI apps.

Read-only GitHub REST API (search + issues + comments). Token from `gh auth token`.
Steps:
  1. one search query per (repo, title term): `repo:R is:issue "term" in:title created:>=since`
  2. local filters (see filters.py) -> keep_filter True/False
  3. per-repo cap (best-match order) and global per-author cap
  4. fetch issue + comments for kept threads, compute metrics
Outputs (in ../raw/, local only, never published):
  search_hits.jsonl  all search hits (title, url, repo, filter decision; no body)
  threads.jsonl      kept threads with body/comment text truncated (for coding only)
Logins are never written: only sha256(salt + login).
Usage: python3 -I scripts/collect.py [config.json] [out_dir]   (defaults: scripts/repos.json, raw/)
"""
import json, os, re, subprocess, sys, time, hashlib, urllib.request, urllib.parse
from datetime import datetime

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import filters  # noqa: E402

ROOT = os.path.dirname(HERE)
CFG_PATH = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "repos.json")
RAW = sys.argv[2] if len(sys.argv) > 2 else os.path.join(ROOT, "raw")
os.makedirs(RAW, exist_ok=True)
CFG = json.load(open(CFG_PATH))
SALT_PATH = os.path.join(ROOT, "raw", "salt.txt")
SALT = open(SALT_PATH).read().strip()
TOKEN = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True).stdout.strip()


def ahash(login):
    return hashlib.sha256((SALT + (login or "")).encode()).hexdigest()[:16]


def get(url, params=None):
    if params:
        url += "?" + urllib.parse.urlencode(params)
    for attempt in range(5):
        req = urllib.request.Request(url, headers={
            "Authorization": f"Bearer {TOKEN}",
            "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28",
            "User-Agent": "hal9-research-pilot"})
        try:
            with urllib.request.urlopen(req, timeout=60) as r:
                return json.load(r)
        except urllib.error.HTTPError as e:
            if e.code in (403, 429):
                time.sleep(30 * (attempt + 1)); continue
            if e.code == 422:
                print("422", url, file=sys.stderr); return None
            raise
    return None


def ts(s):
    return datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None


def hours(a, b):
    return round((b - a).total_seconds() / 3600, 1) if a and b else None


def search():
    hits = {}
    for r in CFG["repos"]:
        for term in r["title_terms"]:
            q = f'repo:{r["repo"]} is:issue "{term}" in:title created:>={CFG["since"]}'
            items, total = [], None
            for page in range(1, CFG.get("pages", 1) + 1):
                res = get("https://api.github.com/search/issues", {"q": q, "per_page": 100, "page": page})
                time.sleep(2.2)  # search API: 30 requests/minute
                if not res:
                    break
                total = res.get("total_count")
                items += res.get("items", [])
                if len(items) >= min(total, 1000) or not res.get("items"):
                    break
            for rank, it in enumerate(items):
                if "pull_request" in it:
                    continue
                u = it["html_url"]
                h = hits.setdefault(u, {"url": u, "repo": r["repo"], "group": r["group"],
                                        "title": it["title"], "created_at": it["created_at"],
                                        "author_hash": ahash(it["user"]["login"]),
                                        "body": (it.get("body") or "")[:6000],
                                        "terms": [], "best_rank": rank, "_item": it})
                h["terms"].append(term)
                h["best_rank"] = min(h["best_rank"], rank)
            print(f'{r["repo"]:50s} {term:20s} {total}', file=sys.stderr)
    return list(hits.values())


def main():
    hits = search()
    for h in hits:
        h["keep_filter"], h["filter_reason"] = filters.keep(h)
    # caps: per repo by best rank (more matching terms first), then per author globally
    kept, per_author = [], {}
    by_repo = {}
    for h in hits:
        if h["keep_filter"]:
            by_repo.setdefault(h["repo"], []).append(h)
    repo_cap = {r["repo"]: r["cap"] for r in CFG["repos"] if "cap" in r}
    for repo, lst in by_repo.items():
        lst.sort(key=lambda h: (-len(h["terms"]), h["best_rank"]))
        n = 0
        for h in lst:
            if n >= repo_cap.get(repo, CFG["per_repo_cap"]):
                h["cap"] = "repo_cap"; continue
            if per_author.get(h["author_hash"], 0) >= CFG["per_author_cap"]:
                h["cap"] = "author_cap"; continue
            per_author[h["author_hash"]] = per_author.get(h["author_hash"], 0) + 1
            h["cap"] = "kept"; n += 1
            kept.append(h)
    with open(os.path.join(RAW, "search_hits.jsonl"), "w") as f:
        for h in hits:
            f.write(json.dumps({k: v for k, v in h.items() if k not in ("body", "_item")}) + "\n")
    print(f"hits={len(hits)} pass_filter={sum(h['keep_filter'] for h in hits)} kept={len(kept)}", file=sys.stderr)

    tpath = os.path.join(RAW, "threads.jsonl")
    done = set()
    if os.path.exists(tpath):  # resume: skip threads already fetched
        done = {json.loads(l)["url"] for l in open(tpath)}
    out = open(tpath, "a")
    for h in kept:
        if h["url"] in done:
            continue
        owner_repo, num = h["repo"], h["url"].rsplit("/", 1)[1]
        api = f"https://api.github.com/repos/{owner_repo}/issues/{num}"
        iss = h["_item"]  # search items carry state, state_reason, reactions, labels
        coms = (get(api + "/comments", {"per_page": 100}) or []) if iss["comments"] else []
        author = iss["user"]["login"]
        created = ts(iss["created_at"])
        first_other = next((c for c in coms if c["user"]["login"] != author
                            and not c["user"]["login"].endswith("[bot]")
                            and c["user"].get("type") != "Bot"), None)
        rec = {
            "source": "github_issues", "repo": owner_repo, "group": h["group"],
            "url": iss["html_url"], "created_at": iss["created_at"], "title": iss["title"],
            "n_comments": iss["comments"], "n_reactions": iss.get("reactions", {}).get("total_count", 0),
            "state": iss["state"], "state_reason": iss.get("state_reason"),
            "closed_at": iss.get("closed_at"),
            "labels": [l["name"] for l in iss.get("labels", [])],
            "time_to_first_response_h": hours(created, ts(first_other["created_at"])) if first_other else None,
            "time_to_close_h": hours(created, ts(iss.get("closed_at"))),
            "author_hash": ahash(author), "terms": h["terms"],
            "body": (iss.get("body") or "")[:6000],
            "comments": [{"by_author": c["user"]["login"] == author,
                          "is_bot": c["user"]["login"].endswith("[bot]") or c["user"].get("type") == "Bot",
                          "assoc": c.get("author_association"),
                          "body": (c.get("body") or "")[:1500]} for c in coms],
        }
        out.write(json.dumps(rec) + "\n"); out.flush()
    out.close()


if __name__ == "__main__":
    main()