#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [ # "huggingface_hub>=0.30.0", # "pyarrow>=18.0.0", # ] # /// from __future__ import annotations import argparse import json import os import re import shutil import socket import tempfile import time import urllib.error import urllib.parse import urllib.request from collections import defaultdict from collections.abc import Iterator from datetime import UTC, datetime from pathlib import Path from typing import Any from urllib.parse import urlparse import pyarrow as pa import pyarrow.parquet as pq from huggingface_hub import HfApi, hf_hub_download SCHEMAS: dict[str, pa.Schema] = { "issues": pa.schema( [ ("repo", pa.string()), ("github_id", pa.int64()), ("github_node_id", pa.string()), ("number", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("title", pa.string()), ("body", pa.string()), ("state", pa.string()), ("state_reason", pa.string()), ("locked", pa.bool_()), ("comments_count", pa.int64()), ("labels", pa.list_(pa.string())), ("assignees", pa.list_(pa.string())), ("created_at", pa.string()), ("updated_at", pa.string()), ("closed_at", pa.string()), ("milestone_title", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ("author_login", pa.string()), ("author_id", pa.int64()), ("author_node_id", pa.string()), ("author_type", pa.string()), ("author_site_admin", pa.bool_()), ] ), "pull_requests": pa.schema( [ ("repo", pa.string()), ("github_id", pa.int64()), ("github_node_id", pa.string()), ("number", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("title", pa.string()), ("body", pa.string()), ("state", pa.string()), ("state_reason", pa.string()), ("locked", pa.bool_()), ("comments_count", pa.int64()), ("labels", pa.list_(pa.string())), ("assignees", pa.list_(pa.string())), ("created_at", pa.string()), ("updated_at", pa.string()), ("closed_at", pa.string()), ("merged_at", pa.string()), ("merge_commit_sha", pa.string()), ("merged", pa.bool_()), ("mergeable", pa.bool_()), ("mergeable_state", pa.string()), ("draft", pa.bool_()), ("additions", pa.int64()), ("deletions", pa.int64()), ("changed_files", pa.int64()), ("commits", pa.int64()), ("review_comments_count", pa.int64()), ("maintainer_can_modify", pa.bool_()), ("head_ref", pa.string()), ("head_sha", pa.string()), ("head_repo_full_name", pa.string()), ("base_ref", pa.string()), ("base_sha", pa.string()), ("base_repo_full_name", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ("author_login", pa.string()), ("author_id", pa.int64()), ("author_node_id", pa.string()), ("author_type", pa.string()), ("author_site_admin", pa.bool_()), ] ), "comments": pa.schema( [ ("repo", pa.string()), ("github_id", pa.int64()), ("github_node_id", pa.string()), ("parent_kind", pa.string()), ("parent_number", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("issue_api_url", pa.string()), ("body", pa.string()), ("created_at", pa.string()), ("updated_at", pa.string()), ("author_association", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ("author_login", pa.string()), ("author_id", pa.int64()), ("author_node_id", pa.string()), ("author_type", pa.string()), ("author_site_admin", pa.bool_()), ] ), "reviews": pa.schema( [ ("repo", pa.string()), ("github_id", pa.int64()), ("github_node_id", pa.string()), ("pull_request_number", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("body", pa.string()), ("state", pa.string()), ("submitted_at", pa.string()), ("commit_id", pa.string()), ("author_association", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ("author_login", pa.string()), ("author_id", pa.int64()), ("author_node_id", pa.string()), ("author_type", pa.string()), ("author_site_admin", pa.bool_()), ] ), "review_comments": pa.schema( [ ("repo", pa.string()), ("github_id", pa.int64()), ("github_node_id", pa.string()), ("pull_request_number", pa.int64()), ("review_id", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("pull_request_api_url", pa.string()), ("body", pa.string()), ("path", pa.string()), ("commit_id", pa.string()), ("original_commit_id", pa.string()), ("position", pa.int64()), ("original_position", pa.int64()), ("line", pa.int64()), ("start_line", pa.int64()), ("side", pa.string()), ("start_side", pa.string()), ("subject_type", pa.string()), ("created_at", pa.string()), ("updated_at", pa.string()), ("author_association", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ("author_login", pa.string()), ("author_id", pa.int64()), ("author_node_id", pa.string()), ("author_type", pa.string()), ("author_site_admin", pa.bool_()), ] ), "pr_files": pa.schema( [ ("repo", pa.string()), ("pull_request_number", pa.int64()), ("sha", pa.string()), ("filename", pa.string()), ("status", pa.string()), ("additions", pa.int64()), ("deletions", pa.int64()), ("changes", pa.int64()), ("blob_url", pa.string()), ("raw_url", pa.string()), ("contents_url", pa.string()), ("previous_filename", pa.string()), ("patch", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ] ), "pr_diffs": pa.schema( [ ("repo", pa.string()), ("pull_request_number", pa.int64()), ("html_url", pa.string()), ("api_url", pa.string()), ("diff", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ] ), "links": pa.schema( [ ("repo", pa.string()), ("source_type", pa.string()), ("source_number", pa.int64()), ("source_github_id", pa.int64()), ("target_owner", pa.string()), ("target_repo", pa.string()), ("target_number", pa.int64()), ("link_type", pa.string()), ("link_origin", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ] ), "events": pa.schema( [ ("repo", pa.string()), ("parent_kind", pa.string()), ("parent_number", pa.int64()), ("event", pa.string()), ("created_at", pa.string()), ("actor_login", pa.string()), ("source_issue_number", pa.int64()), ("source_issue_title", pa.string()), ("source_issue_url", pa.string()), ("commit_id", pa.string()), ("label_name", pa.string()), ("snapshot_id", pa.string()), ("extracted_at", pa.string()), ] ), } PRIMARY_KEYS: dict[str, tuple[str, ...]] = { "issues": ("github_id",), "pull_requests": ("github_id",), "comments": ("github_id",), "reviews": ("github_id",), "review_comments": ("github_id",), "pr_files": ("repo", "pull_request_number", "filename"), "pr_diffs": ("repo", "pull_request_number"), "links": ( "repo", "source_type", "source_number", "source_github_id", "target_owner", "target_repo", "target_number", "link_type", "link_origin", ), "events": ( "repo", "parent_kind", "parent_number", "event", "created_at", "actor_login", "source_issue_number", "source_issue_url", "commit_id", "label_name", ), } CHECKPOINT_PREFIXES = ("_checkpoints", "checkpoints") REFERENCE_PATTERN = re.compile(r"(?:(?P[A-Za-z0-9_.-]+)/(?P[A-Za-z0-9_.-]+))?#(?P\d+)") CLOSING_KEYWORD_PATTERN = re.compile( r"\b(?Pclose[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(?:(?P[A-Za-z0-9_.-]+)/(?P[A-Za-z0-9_.-]+))?#(?P\d+)\b", flags=re.IGNORECASE, ) def log(message: str) -> None: stamp = datetime.now(tz=UTC).strftime("%H:%M:%SZ") print(f"[{stamp}] {message}", flush=True) def iso_now() -> str: return datetime.now(tz=UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z") def snapshot_id() -> str: return datetime.now(tz=UTC).strftime("%Y%m%dT%H%M%SZ") class PullRequestDiffTooLargeError(RuntimeError): """Raised when GitHub refuses to render a PR diff because it is too large.""" class GitHubClient: def __init__(self, token: str | None, timeout: int, max_retries: int): self.token = token self.timeout = timeout self.max_retries = max_retries self.base_url = "https://api.github.com" def _request( self, path: str, params: dict[str, object] | None = None, accept: str = "application/vnd.github+json", ) -> tuple[object, dict[str, str]]: query = f"?{urllib.parse.urlencode(params)}" if params else "" url = f"{self.base_url}{path}{query}" request = urllib.request.Request(url) request.add_header("Accept", accept) request.add_header("X-GitHub-Api-Version", "2022-11-28") if self.token: request.add_header("Authorization", f"Bearer {self.token}") attempt = 0 while True: try: with urllib.request.urlopen(request, timeout=self.timeout) as response: payload = response.read().decode("utf-8") headers = {k.lower(): v for k, v in response.headers.items()} return json.loads(payload), headers except urllib.error.HTTPError as exc: if exc.code == 403 and exc.headers.get("X-RateLimit-Remaining") == "0": reset_at = int(exc.headers.get("X-RateLimit-Reset", "0") or "0") sleep_for = max(reset_at - int(time.time()), 1) log(f"GitHub rate limit reached for {path}; sleeping {sleep_for}s until reset") time.sleep(sleep_for) continue detail = exc.read().decode("utf-8", errors="replace") if exc.code == 406 and '"field":"diff"' in detail and '"code":"too_large"' in detail: raise PullRequestDiffTooLargeError(f"GitHub diff too large: {path} {detail}") from exc raise RuntimeError(f"GitHub API request failed: {exc.code} {path} {detail}") from exc except (TimeoutError, socket.timeout, urllib.error.URLError) as exc: attempt += 1 if attempt > self.max_retries: raise RuntimeError(f"GitHub API request failed after retries for {path}: {exc}") from exc sleep_for = min(2**attempt, 30) log(f"Transient network failure for {path}; retrying in {sleep_for}s") time.sleep(sleep_for) def paginate( self, path: str, params: dict[str, object] | None = None, accept: str = "application/vnd.github+json", limit: int | None = None, ) -> Iterator[dict]: page = 1 yielded = 0 params = dict(params or {}) params["per_page"] = 100 while True: params["page"] = page payload, _headers = self._request(path, params=params, accept=accept) if not isinstance(payload, list): raise RuntimeError(f"Expected list payload from {path}, got {type(payload)!r}") if not payload: break for item in payload: if isinstance(item, dict): yield item yielded += 1 if limit is not None and yielded >= limit: return if len(payload) < 100: break page += 1 def _request_text( self, path: str, params: dict[str, object] | None = None, accept: str = "application/vnd.github.diff", ) -> tuple[str, dict[str, str]]: query = f"?{urllib.parse.urlencode(params)}" if params else "" url = f"{self.base_url}{path}{query}" request = urllib.request.Request(url) request.add_header("Accept", accept) request.add_header("X-GitHub-Api-Version", "2022-11-28") if self.token: request.add_header("Authorization", f"Bearer {self.token}") attempt = 0 while True: try: with urllib.request.urlopen(request, timeout=self.timeout) as response: payload = response.read().decode("utf-8", errors="replace") headers = {k.lower(): v for k, v in response.headers.items()} return payload, headers except urllib.error.HTTPError as exc: if exc.code == 403 and exc.headers.get("X-RateLimit-Remaining") == "0": reset_at = int(exc.headers.get("X-RateLimit-Reset", "0") or "0") sleep_for = max(reset_at - int(time.time()), 1) log(f"GitHub rate limit reached for {path}; sleeping {sleep_for}s until reset") time.sleep(sleep_for) continue detail = exc.read().decode("utf-8", errors="replace") if exc.code == 406 and '"field":"diff"' in detail and '"code":"too_large"' in detail: raise PullRequestDiffTooLargeError(f"GitHub diff too large: {path} {detail}") from exc raise RuntimeError(f"GitHub API request failed: {exc.code} {path} {detail}") from exc except (TimeoutError, socket.timeout, urllib.error.URLError) as exc: attempt += 1 if attempt > self.max_retries: raise RuntimeError(f"GitHub API request failed after retries for {path}: {exc}") from exc sleep_for = min(2**attempt, 30) log(f"Transient network failure for {path}; retrying in {sleep_for}s") time.sleep(sleep_for) def get_json(self, path: str, accept: str = "application/vnd.github+json") -> dict: payload, _headers = self._request(path, accept=accept) if not isinstance(payload, dict): raise RuntimeError(f"Expected dict payload from {path}, got {type(payload)!r}") return payload def iter_repo_issues(self, owner: str, repo: str, since: str | None, limit: int | None) -> Iterator[dict]: params: dict[str, object] = {"state": "all", "sort": "updated", "direction": "asc"} if since: params["since"] = since yield from self.paginate(f"/repos/{owner}/{repo}/issues", params=params, limit=limit) def iter_issue_comments_for_number( self, owner: str, repo: str, number: int, since: str | None, limit: int | None ) -> Iterator[dict]: params: dict[str, object] = {"sort": "updated", "direction": "asc"} if since: params["since"] = since yield from self.paginate(f"/repos/{owner}/{repo}/issues/{number}/comments", params=params, limit=limit) def get_pull_request(self, owner: str, repo: str, number: int) -> dict: return self.get_json(f"/repos/{owner}/{repo}/pulls/{number}") def iter_pull_reviews(self, owner: str, repo: str, number: int, limit: int | None) -> Iterator[dict]: yield from self.paginate(f"/repos/{owner}/{repo}/pulls/{number}/reviews", limit=limit) def iter_pull_review_comments(self, owner: str, repo: str, number: int, limit: int | None) -> Iterator[dict]: yield from self.paginate( f"/repos/{owner}/{repo}/pulls/{number}/comments", params={"sort": "updated", "direction": "asc"}, limit=limit, ) def iter_pull_files(self, owner: str, repo: str, number: int, limit: int | None = None) -> Iterator[dict]: yield from self.paginate(f"/repos/{owner}/{repo}/pulls/{number}/files", limit=limit) def get_pull_request_diff(self, owner: str, repo: str, number: int) -> str: path = f"/repos/{owner}/{repo}/pulls/{number}" try: payload, _headers = self._request_text( path, accept="application/vnd.github.diff", ) return payload except PullRequestDiffTooLargeError: log(f"Skipping unified diff for pull request #{number}; GitHub reports diff too large") return "" def iter_issue_timeline(self, owner: str, repo: str, number: int) -> Iterator[dict]: yield from self.paginate( f"/repos/{owner}/{repo}/issues/{number}/timeline", accept="application/vnd.github+json, application/vnd.github.mockingbird-preview+json", ) def get_rate_limit(self) -> dict[str, Any]: return self.get_json("/rate_limit") def user_fields(user: dict[str, Any] | None) -> dict[str, Any]: user = user or {} return { "author_login": user.get("login"), "author_id": user.get("id"), "author_node_id": user.get("node_id"), "author_type": user.get("type"), "author_site_admin": user.get("site_admin"), } def labels(values: list[dict[str, Any]] | None) -> list[str]: return [label.get("name") for label in values or [] if isinstance(label, dict) and label.get("name")] def assignees(values: list[dict[str, Any]] | None) -> list[str]: return [user.get("login") for user in values or [] if isinstance(user, dict) and user.get("login")] def issue_url_to_number(issue_url: str | None) -> int | None: if not issue_url: return None tail = urlparse(issue_url).path.rstrip("/").rsplit("/", 1)[-1] try: return int(tail) except ValueError: return None def normalize_issue(repo_slug: str, item: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: return { "repo": repo_slug, "github_id": item.get("id"), "github_node_id": item.get("node_id"), "number": item.get("number"), "html_url": item.get("html_url"), "api_url": item.get("url"), "title": item.get("title"), "body": item.get("body"), "state": item.get("state"), "state_reason": item.get("state_reason"), "locked": item.get("locked"), "comments_count": item.get("comments"), "labels": labels(item.get("labels")), "assignees": assignees(item.get("assignees")), "created_at": item.get("created_at"), "updated_at": item.get("updated_at"), "closed_at": item.get("closed_at"), "milestone_title": (item.get("milestone") or {}).get("title"), "snapshot_id": sid, "extracted_at": extracted_at, **user_fields(item.get("user")), } def normalize_pull_request(repo_slug: str, stub: dict[str, Any], detail: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: head = detail.get("head") or {} base = detail.get("base") or {} return { "repo": repo_slug, "github_id": detail.get("id") or stub.get("id"), "github_node_id": detail.get("node_id") or stub.get("node_id"), "number": stub.get("number"), "html_url": stub.get("html_url"), "api_url": stub.get("url"), "title": stub.get("title"), "body": stub.get("body"), "state": stub.get("state"), "state_reason": stub.get("state_reason"), "locked": stub.get("locked"), "comments_count": stub.get("comments"), "labels": labels(stub.get("labels")), "assignees": assignees(stub.get("assignees")), "created_at": stub.get("created_at"), "updated_at": stub.get("updated_at"), "closed_at": stub.get("closed_at"), "merged_at": detail.get("merged_at"), "merge_commit_sha": detail.get("merge_commit_sha"), "merged": detail.get("merged"), "mergeable": detail.get("mergeable"), "mergeable_state": detail.get("mergeable_state"), "draft": detail.get("draft"), "additions": detail.get("additions"), "deletions": detail.get("deletions"), "changed_files": detail.get("changed_files"), "commits": detail.get("commits"), "review_comments_count": detail.get("review_comments"), "maintainer_can_modify": detail.get("maintainer_can_modify"), "head_ref": head.get("ref"), "head_sha": head.get("sha"), "head_repo_full_name": (head.get("repo") or {}).get("full_name"), "base_ref": base.get("ref"), "base_sha": base.get("sha"), "base_repo_full_name": (base.get("repo") or {}).get("full_name"), "snapshot_id": sid, "extracted_at": extracted_at, **user_fields(stub.get("user")), } def normalize_comment(repo_slug: str, item: dict[str, Any], parent_kind: str, parent_number: int | None, sid: str, extracted_at: str) -> dict[str, Any]: return { "repo": repo_slug, "github_id": item.get("id"), "github_node_id": item.get("node_id"), "parent_kind": parent_kind, "parent_number": parent_number, "html_url": item.get("html_url"), "api_url": item.get("url"), "issue_api_url": item.get("issue_url"), "body": item.get("body"), "created_at": item.get("created_at"), "updated_at": item.get("updated_at"), "author_association": item.get("author_association"), "snapshot_id": sid, "extracted_at": extracted_at, **user_fields(item.get("user")), } def normalize_review(repo_slug: str, pr_number: int, item: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: return { "repo": repo_slug, "github_id": item.get("id"), "github_node_id": item.get("node_id"), "pull_request_number": pr_number, "html_url": item.get("html_url"), "api_url": item.get("url"), "body": item.get("body"), "state": item.get("state"), "submitted_at": item.get("submitted_at"), "commit_id": item.get("commit_id"), "author_association": item.get("author_association"), "snapshot_id": sid, "extracted_at": extracted_at, **user_fields(item.get("user")), } def normalize_review_comment(repo_slug: str, pr_number: int, item: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: return { "repo": repo_slug, "github_id": item.get("id"), "github_node_id": item.get("node_id"), "pull_request_number": pr_number, "review_id": item.get("pull_request_review_id"), "html_url": item.get("html_url"), "api_url": item.get("url"), "pull_request_api_url": item.get("pull_request_url"), "body": item.get("body"), "path": item.get("path"), "commit_id": item.get("commit_id"), "original_commit_id": item.get("original_commit_id"), "position": item.get("position"), "original_position": item.get("original_position"), "line": item.get("line"), "start_line": item.get("start_line"), "side": item.get("side"), "start_side": item.get("start_side"), "subject_type": item.get("subject_type"), "created_at": item.get("created_at"), "updated_at": item.get("updated_at"), "author_association": item.get("author_association"), "snapshot_id": sid, "extracted_at": extracted_at, **user_fields(item.get("user")), } def normalize_pr_file(repo_slug: str, pr_number: int, item: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: return { "repo": repo_slug, "pull_request_number": pr_number, "sha": item.get("sha"), "filename": item.get("filename"), "status": item.get("status"), "additions": item.get("additions"), "deletions": item.get("deletions"), "changes": item.get("changes"), "blob_url": item.get("blob_url"), "raw_url": item.get("raw_url"), "contents_url": item.get("contents_url"), "previous_filename": item.get("previous_filename"), "patch": item.get("patch"), "snapshot_id": sid, "extracted_at": extracted_at, } def normalize_pr_diff( repo_slug: str, pr_number: int, html_url: str | None, api_url: str | None, diff: str, sid: str, extracted_at: str, ) -> dict[str, Any]: return { "repo": repo_slug, "pull_request_number": pr_number, "html_url": html_url, "api_url": api_url, "diff": diff, "snapshot_id": sid, "extracted_at": extracted_at, } def normalize_timeline_event(repo_slug: str, number: int, parent_kind: str, item: dict[str, Any], sid: str, extracted_at: str) -> dict[str, Any]: source = item.get("source") or {} issue = source.get("issue") or {} return { "repo": repo_slug, "parent_kind": parent_kind, "parent_number": number, "event": item.get("event"), "created_at": item.get("created_at"), "actor_login": (item.get("actor") or {}).get("login"), "source_issue_number": issue.get("number"), "source_issue_title": issue.get("title"), "source_issue_url": issue.get("html_url"), "commit_id": item.get("commit_id"), "label_name": (item.get("label") or {}).get("name"), "snapshot_id": sid, "extracted_at": extracted_at, } def extract_references(text: str | None, owner: str, repo: str) -> list[dict[str, Any]]: if not text: return [] refs: list[dict[str, Any]] = [] for match in REFERENCE_PATTERN.finditer(text): refs.append( { "target_owner": match.group("owner") or owner, "target_repo": match.group("repo") or repo, "target_number": int(match.group("number")), "reference_kind": "mention", } ) for match in CLOSING_KEYWORD_PATTERN.finditer(text): refs.append( { "target_owner": match.group("owner") or owner, "target_repo": match.group("repo") or repo, "target_number": int(match.group("number")), "reference_kind": "closing_reference", } ) return refs def build_text_link_rows( *, repo_slug: str, owner: str, repo: str, source_type: str, source_number: int, source_id: int | None, body: str | None, sid: str, extracted_at: str, ) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] seen: set[tuple[str, str, int, str]] = set() for ref in extract_references(body, owner, repo): key = (ref["target_owner"], ref["target_repo"], ref["target_number"], ref["reference_kind"]) if key in seen: continue seen.add(key) rows.append( { "repo": repo_slug, "source_type": source_type, "source_number": source_number, "source_github_id": source_id, "target_owner": ref["target_owner"], "target_repo": ref["target_repo"], "target_number": ref["target_number"], "link_type": ref["reference_kind"], "link_origin": "text", "snapshot_id": sid, "extracted_at": extracted_at, } ) return rows def build_duplicate_candidate_rows(repo_slug: str, pull_requests: list[dict[str, Any]], link_rows: list[dict[str, Any]], sid: str, extracted_at: str) -> list[dict[str, Any]]: owner, repo = repo_slug.split("/", 1) pr_targets: dict[int, set[int]] = defaultdict(set) for row in link_rows: if row["source_type"] != "pull_request": continue if row["target_owner"] != owner or row["target_repo"] != repo: continue pr_targets[row["source_number"]].add(row["target_number"]) target_to_prs: dict[int, list[int]] = defaultdict(list) for pr_row in pull_requests: for target in sorted(pr_targets.get(pr_row["number"], set())): target_to_prs[target].append(pr_row["number"]) rows: list[dict[str, Any]] = [] for target_number, prs in target_to_prs.items(): if len(prs) < 2: continue for pr_number in prs: rows.append( { "repo": repo_slug, "source_type": "pull_request", "source_number": pr_number, "source_github_id": None, "target_owner": owner, "target_repo": repo, "target_number": target_number, "link_type": "shared_issue_target", "link_origin": "derived", "snapshot_id": sid, "extracted_at": extracted_at, } ) return rows def row_key(row: dict[str, Any], fields: tuple[str, ...]) -> str: return json.dumps([row.get(field) for field in fields], default=str) def merge_rows(table_name: str, previous_rows: list[dict[str, Any]], delta_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: if table_name == "pr_files": refreshed_prs = { (row.get("repo"), row.get("pull_request_number")) for row in delta_rows if row.get("pull_request_number") is not None } previous_rows = [ row for row in previous_rows if (row.get("repo"), row.get("pull_request_number")) not in refreshed_prs ] merged: dict[str, dict[str, Any]] = {} for row in previous_rows: merged[row_key(row, PRIMARY_KEYS[table_name])] = row for row in delta_rows: merged[row_key(row, PRIMARY_KEYS[table_name])] = row return list(merged.values()) def read_rows(path: Path, table_name: str) -> list[dict[str, Any]]: if not path.exists(): return [] return pq.read_table(path).cast(SCHEMAS[table_name]).to_pylist() def write_rows(path: Path, table_name: str, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) table = pa.Table.from_pylist(rows, schema=SCHEMAS[table_name]) pq.write_table(table, path) def load_remote_file(api: HfApi, repo_id: str, path_in_repo: str, local_dir: Path) -> Path | None: try: downloaded = hf_hub_download( repo_id=repo_id, filename=path_in_repo, repo_type="dataset", local_dir=str(local_dir), token=os.getenv("HF_TOKEN"), ) except Exception: return None return Path(downloaded) def load_remote_json_file(api: HfApi, repo_id: str, path_in_repo: str, local_dir: Path) -> dict[str, Any] | None: downloaded = load_remote_file(api, repo_id, path_in_repo, local_dir) if downloaded is None: return None return json.loads(downloaded.read_text(encoding="utf-8")) def list_remote_paths(api: HfApi, repo_id: str) -> set[str]: try: info = api.dataset_info(repo_id=repo_id, files_metadata=True) except TypeError: info = api.dataset_info(repo_id=repo_id) except Exception: return set() return {sibling.rfilename for sibling in getattr(info, "siblings", [])} def stable_snapshot_candidates(latest_payload: dict[str, Any], filename: str) -> list[str]: candidates: list[str] = [] manifest_path = str(latest_payload.get("manifest_path") or "").strip("/") snapshot_dir = str(latest_payload.get("snapshot_dir") or "").strip("/") latest_snapshot_id = str(latest_payload.get("latest_snapshot_id") or "").strip() if filename == "manifest.json" and manifest_path: candidates.append(manifest_path) if snapshot_dir and snapshot_dir not in {".", "/"}: candidates.append(f"{snapshot_dir}/{filename}") if manifest_path and "/" in manifest_path: manifest_dir = manifest_path.rsplit("/", 1)[0] candidates.append(f"{manifest_dir}/{filename}") if latest_snapshot_id: candidates.append(f"snapshots/{latest_snapshot_id}/{filename}") candidates.append(filename) deduped: list[str] = [] seen: set[str] = set() for candidate in candidates: normalized = candidate.lstrip("./") if not normalized or normalized in seen: continue seen.add(normalized) deduped.append(normalized) return deduped def load_remote_table_from_candidates( api: HfApi, repo_id: str, table_name: str, local_dir: Path, candidate_paths: list[str], ) -> list[dict[str, Any]]: for candidate in candidate_paths: downloaded = load_remote_file(api, repo_id, candidate, local_dir) if downloaded is not None: return read_rows(downloaded, table_name) return [] def checkpoint_dirs(remote_paths: set[str]) -> list[tuple[str, str]]: by_sid: dict[str, str] = {} for path in remote_paths: parts = path.split("/") if len(parts) < 3 or parts[0] not in CHECKPOINT_PREFIXES: continue sid = parts[1] prefix = parts[0] current = by_sid.get(sid) if current is None or current.startswith("checkpoints/"): by_sid[sid] = f"{prefix}/{sid}" return [(sid, by_sid[sid]) for sid in sorted(by_sid)] def build_dataset_card(repo_slug: str, sid: str, manifest: dict[str, Any]) -> str: return f"""--- pretty_name: Transformers PR Slop Dataset configs: - config_name: issues data_files: - split: train path: issues.parquet default: true - config_name: prs data_files: - split: train path: pull_requests.parquet - config_name: issue_comments data_files: - split: train path: issue_comments.parquet - config_name: pr_comments data_files: - split: train path: pr_comments.parquet - config_name: pr_files data_files: - split: train path: pr_files.parquet - config_name: pr_diffs data_files: - split: train path: pr_diffs.parquet - config_name: pr_reviews data_files: - split: train path: reviews.parquet - config_name: review_comments data_files: - split: train path: review_comments.parquet - config_name: links data_files: - split: train path: links.parquet - config_name: events data_files: - split: train path: events.parquet --- # Transformers PR Slop Dataset Normalized snapshots of issues, pull requests, comments, reviews, and linkage data from `{repo_slug}`. Files: - `issues.parquet` - `pull_requests.parquet` - `comments.parquet` - `issue_comments.parquet` (derived view of issue discussion comments) - `pr_comments.parquet` (derived view of pull request discussion comments) - `pr_files.parquet` - `pr_diffs.parquet` - `reviews.parquet` - `review_comments.parquet` - `links.parquet` - `events.parquet` Use: - duplicate PR and issue analysis - triage and ranking experiments - eval set creation Notes: - updated daily - latest snapshot: `{sid}` - raw data only; no labels or moderation decisions - PR metadata, file-level patch hunks, and full unified diffs are included - full file contents for changed files are not included """ def viewer_comment_rows( comments: list[dict[str, Any]], pull_requests: list[dict[str, Any]], ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: pr_numbers = {int(row["number"]) for row in pull_requests if row.get("number") is not None} issue_comments: list[dict[str, Any]] = [] pr_comments: list[dict[str, Any]] = [] for row in comments: parent_number = row.get("parent_number") parent_kind = row.get("parent_kind") if parent_kind == "pull_request" or parent_number in pr_numbers: pr_comments.append(row) else: issue_comments.append(row) return issue_comments, pr_comments def write_json_file(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") def upload_delta_checkpoint( *, api: HfApi, repo_id: str, work_dir: Path, repo_slug: str, sid: str, stage: str, delta_tables: dict[str, list[dict[str, Any]]], progress: dict[str, Any], ) -> None: checkpoint_root = work_dir / "checkpoint_upload" if checkpoint_root.exists(): shutil.rmtree(checkpoint_root) checkpoint_root.mkdir(parents=True, exist_ok=True) for table_name, rows in delta_tables.items(): write_rows(checkpoint_root / f"{table_name}.parquet", table_name, rows) write_json_file(checkpoint_root / "progress.json", {"repo": repo_slug, "snapshot_id": sid, **progress}) write_json_file(checkpoint_root / "state" / "in_progress.json", {"repo": repo_slug, "snapshot_id": sid, **progress}) api.upload_folder( folder_path=str(checkpoint_root), path_in_repo=f"_checkpoints/{sid}", repo_id=repo_id, repo_type="dataset", commit_message=f"Checkpoint {sid} ({stage})", ) def remaining_limit(limit: int | None, used: int) -> int | None: if limit is None: return None return max(limit - used, 0) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--repo", default="huggingface/transformers") parser.add_argument("--hf-repo-id", required=True) parser.add_argument("--max-issues", type=int, default=None) parser.add_argument("--max-prs", type=int, default=None) parser.add_argument("--max-issue-comments", type=int, default=None) parser.add_argument("--max-reviews-per-pr", type=int, default=None) parser.add_argument("--max-review-comments-per-pr", type=int, default=None) parser.add_argument("--fetch-timeline", action="store_true") parser.add_argument("--http-timeout", type=int, default=300) parser.add_argument("--http-max-retries", type=int, default=8) parser.add_argument("--checkpoint-every-comments", type=int, default=1000) parser.add_argument("--checkpoint-every-prs", type=int, default=25) parser.add_argument("--private", action="store_true") return parser.parse_args() def main() -> None: args = parse_args() if not os.getenv("HF_TOKEN"): raise RuntimeError("HF_TOKEN must be set for Hub uploads") if not os.getenv("GITHUB_TOKEN"): raise RuntimeError("GITHUB_TOKEN must be set for GitHub API access") owner, repo = args.repo.split("/", 1) repo_slug = f"{owner}/{repo}" sid = snapshot_id() crawl_started_at = iso_now() extracted_at = iso_now() api = HfApi(token=os.getenv("HF_TOKEN")) api.create_repo(repo_id=args.hf_repo_id, repo_type="dataset", private=args.private, exist_ok=True) with tempfile.TemporaryDirectory(prefix="slop-farmer-job-") as tmp: root = Path(tmp) previous_root = root / "previous" output_root = root / "output" previous_root.mkdir(parents=True, exist_ok=True) output_root.mkdir(parents=True, exist_ok=True) remote_paths = list_remote_paths(api, args.hf_repo_id) previous_watermark = load_remote_json_file(api, args.hf_repo_id, "state/watermark.json", previous_root) latest_pointer = ( load_remote_json_file(api, args.hf_repo_id, "snapshots/latest.json", previous_root) if "snapshots/latest.json" in remote_paths else None ) stable_snapshot_id = None if previous_watermark: stable_snapshot_id = previous_watermark.get("last_successful_snapshot_id") elif latest_pointer: stable_snapshot_id = latest_pointer.get("latest_snapshot_id") log(f"Starting scheduled dataset update for {repo_slug}") log(f"Target dataset repo: {args.hf_repo_id}") previous_tables = {table_name: [] for table_name in SCHEMAS} if latest_pointer: for table_name in SCHEMAS: previous_tables[table_name] = load_remote_table_from_candidates( api, args.hf_repo_id, table_name, previous_root, stable_snapshot_candidates(latest_pointer, f"{table_name}.parquet"), ) else: for table_name in SCHEMAS: previous_tables[table_name] = load_remote_table_from_candidates( api, args.hf_repo_id, table_name, previous_root, [f"{table_name}.parquet"], ) checkpoint_progress: dict[str, Any] | None = None best_comment_checkpoint_progress: dict[str, Any] | None = None for checkpoint_sid, checkpoint_dir in checkpoint_dirs(remote_paths): if stable_snapshot_id is None or checkpoint_sid > str(stable_snapshot_id): progress_payload = load_remote_json_file( api, args.hf_repo_id, f"{checkpoint_dir}/progress.json", previous_root ) or load_remote_json_file( api, args.hf_repo_id, f"{checkpoint_dir}/state/in_progress.json", previous_root ) if progress_payload is not None: checkpoint_progress = progress_payload if ( progress_payload.get("effective_since") is None and (progress_payload.get("counts") or {}).get("comments", 0) > 0 ): if best_comment_checkpoint_progress is None or (progress_payload.get("counts") or {}).get( "comments", 0 ) > (best_comment_checkpoint_progress.get("counts") or {}).get("comments", 0): best_comment_checkpoint_progress = progress_payload for table_name in SCHEMAS: checkpoint_rows = load_remote_table_from_candidates( api, args.hf_repo_id, table_name, previous_root, [f"{checkpoint_dir}/{table_name}.parquet"], ) if checkpoint_rows: previous_tables[table_name] = merge_rows( table_name, previous_tables[table_name], checkpoint_rows, ) effective_since = None if checkpoint_progress and checkpoint_progress.get("effective_since") is not None: effective_since = checkpoint_progress.get("effective_since") log(f"Resuming from incomplete checkpoint window starting at {effective_since}") elif previous_watermark and previous_watermark.get("next_since") is not None: effective_since = previous_watermark.get("next_since") log(f"Resuming from remote watermark {effective_since}") else: log("No successful watermark found; running full snapshot") client = GitHubClient( token=os.getenv("GITHUB_TOKEN"), timeout=args.http_timeout, max_retries=args.http_max_retries, ) rate_limit = client.get_rate_limit() core = (rate_limit.get("resources") or {}).get("core") or {} limit = core.get("limit") remaining = core.get("remaining") reset_at = core.get("reset") log(f"GitHub core rate limit: limit={limit} remaining={remaining} reset={reset_at}") if limit is not None and limit <= 60: raise RuntimeError( "GITHUB_TOKEN appears to be missing, invalid, or not being applied; authenticated jobs should not start with the anonymous 60 req/hour limit" ) if remaining == 0 and reset_at: sleep_for = max(int(reset_at) - int(time.time()), 1) log(f"GitHub token is currently exhausted before bootstrap starts; sleeping {sleep_for}s until reset") time.sleep(sleep_for) log("Fetching changed issue and pull request stubs from GitHub") issue_stubs = list(client.iter_repo_issues(owner, repo, effective_since, args.max_issues)) issues = [item for item in issue_stubs if "pull_request" not in item] pr_stubs = [item for item in issue_stubs if "pull_request" in item] if args.max_prs is not None: pr_stubs = pr_stubs[: args.max_prs] log(f"Fetched {len(issue_stubs)} changed stubs") issue_number_to_kind = {item["number"]: ("pull_request" if "pull_request" in item else "issue") for item in issue_stubs} issue_rows = [normalize_issue(repo_slug, item, sid, extracted_at) for item in issues] comment_rows: list[dict[str, Any]] = [] next_comment_checkpoint = args.checkpoint_every_comments reuse_checkpoint_comments = ( stable_snapshot_id is None and effective_since is None and best_comment_checkpoint_progress is not None and bool(previous_tables["comments"]) ) if reuse_checkpoint_comments: log( f"Reusing {len(previous_tables['comments'])} checkpoint comments from prior partial runs; skipping full comment refetch" ) else: for idx, item in enumerate(issue_stubs, start=1): if not item.get("comments"): continue remaining = remaining_limit(args.max_issue_comments, len(comment_rows)) if remaining == 0: break if idx == 1 or idx % 25 == 0: log(f"Collecting discussion comments; {len(comment_rows)} collected so far") for comment in client.iter_issue_comments_for_number(owner, repo, int(item["number"]), effective_since, remaining): parent_number = issue_url_to_number(comment.get("issue_url")) parent_kind = issue_number_to_kind.get(parent_number, "issue_or_pr") comment_rows.append(normalize_comment(repo_slug, comment, parent_kind, parent_number, sid, extracted_at)) remaining = remaining_limit(args.max_issue_comments, len(comment_rows)) if args.checkpoint_every_comments and len(comment_rows) >= next_comment_checkpoint: log(f"Pushing comment checkpoint to Hub at {len(comment_rows)} comments") upload_delta_checkpoint( api=api, repo_id=args.hf_repo_id, work_dir=root, repo_slug=repo_slug, sid=sid, stage="comments", delta_tables={ "issues": issue_rows, "pull_requests": [], "comments": comment_rows, "reviews": [], "review_comments": [], "pr_files": [], "pr_diffs": [], "links": [], "events": [], }, progress={ "stage": "comments", "effective_since": effective_since, "counts": { "issues": len(issue_rows), "comments": len(comment_rows), "pull_requests": 0, "reviews": 0, "review_comments": 0, "pr_files": 0, "pr_diffs": 0, "links": 0, "events": 0, }, }, ) next_comment_checkpoint += args.checkpoint_every_comments if remaining == 0: break pr_rows: list[dict[str, Any]] = [] review_rows: list[dict[str, Any]] = [] review_comment_rows: list[dict[str, Any]] = [] pr_file_rows: list[dict[str, Any]] = [] pr_diff_rows: list[dict[str, Any]] = [] event_rows: list[dict[str, Any]] = [] next_pr_checkpoint = args.checkpoint_every_prs previous_pr_rows_by_number = { int(row["number"]): row for row in previous_tables["pull_requests"] if row.get("number") is not None } previous_review_rows_by_number: dict[int, list[dict[str, Any]]] = defaultdict(list) for row in previous_tables["reviews"]: if row.get("pull_request_number") is not None: previous_review_rows_by_number[int(row["pull_request_number"])].append(row) previous_review_comment_rows_by_number: dict[int, list[dict[str, Any]]] = defaultdict(list) for row in previous_tables["review_comments"]: if row.get("pull_request_number") is not None: previous_review_comment_rows_by_number[int(row["pull_request_number"])].append(row) previous_pr_file_rows_by_number: dict[int, list[dict[str, Any]]] = defaultdict(list) for row in previous_tables["pr_files"]: if row.get("pull_request_number") is not None: previous_pr_file_rows_by_number[int(row["pull_request_number"])].append(row) previous_pr_diff_rows_by_number = { int(row["pull_request_number"]): row for row in previous_tables["pr_diffs"] if row.get("pull_request_number") is not None } previous_pr_event_rows_by_number: dict[int, list[dict[str, Any]]] = defaultdict(list) for row in previous_tables["events"]: if row.get("parent_kind") == "pull_request" and row.get("parent_number") is not None: previous_pr_event_rows_by_number[int(row["parent_number"])].append(row) hydration_pr_stubs: list[dict[str, Any]] = [] for pr_stub in pr_stubs: number = int(pr_stub["number"]) previous_pr_row = previous_pr_rows_by_number.get(number) if previous_pr_row and previous_pr_row.get("updated_at") == pr_stub.get("updated_at"): pr_rows.append(previous_pr_row) review_rows.extend(previous_review_rows_by_number[number]) review_comment_rows.extend(previous_review_comment_rows_by_number[number]) pr_file_rows.extend(previous_pr_file_rows_by_number[number]) if number in previous_pr_diff_rows_by_number: pr_diff_rows.append(previous_pr_diff_rows_by_number[number]) event_rows.extend(previous_pr_event_rows_by_number[number]) continue hydration_pr_stubs.append(pr_stub) reused_pr_count = len(pr_rows) if reused_pr_count: log(f"Reusing hydrated data for {reused_pr_count} pull requests from prior checkpoints") if args.checkpoint_every_prs: while next_pr_checkpoint is not None and reused_pr_count >= next_pr_checkpoint: next_pr_checkpoint += args.checkpoint_every_prs total_prs = len(pr_stubs) remaining_prs = len(hydration_pr_stubs) for idx, pr_stub in enumerate(hydration_pr_stubs, start=1): number = int(pr_stub["number"]) hydrated_count = reused_pr_count + idx if idx == 1 or hydrated_count % 10 == 0 or idx == remaining_prs: log(f"Hydrating pull requests: {hydrated_count}/{total_prs}") detail = client.get_pull_request(owner, repo, number) pr_rows.append(normalize_pull_request(repo_slug, pr_stub, detail, sid, extracted_at)) for review in client.iter_pull_reviews(owner, repo, number, args.max_reviews_per_pr): review_rows.append(normalize_review(repo_slug, number, review, sid, extracted_at)) for comment in client.iter_pull_review_comments(owner, repo, number, args.max_review_comments_per_pr): review_comment_rows.append(normalize_review_comment(repo_slug, number, comment, sid, extracted_at)) for pr_file in client.iter_pull_files(owner, repo, number): pr_file_rows.append(normalize_pr_file(repo_slug, number, pr_file, sid, extracted_at)) pr_diff_rows.append( normalize_pr_diff( repo_slug, number, pr_stub.get("html_url"), pr_stub.get("url"), client.get_pull_request_diff(owner, repo, number), sid, extracted_at, ) ) if args.fetch_timeline: for event in client.iter_issue_timeline(owner, repo, number): event_rows.append(normalize_timeline_event(repo_slug, number, "pull_request", event, sid, extracted_at)) if args.checkpoint_every_prs and next_pr_checkpoint is not None and len(pr_rows) >= next_pr_checkpoint: log(f"Pushing PR checkpoint to Hub at {len(pr_rows)} hydrated PRs") upload_delta_checkpoint( api=api, repo_id=args.hf_repo_id, work_dir=root, repo_slug=repo_slug, sid=sid, stage="pull_requests", delta_tables={ "issues": issue_rows, "pull_requests": pr_rows, "comments": comment_rows, "reviews": review_rows, "review_comments": review_comment_rows, "pr_files": pr_file_rows, "pr_diffs": pr_diff_rows, "links": [], "events": event_rows, }, progress={ "stage": "pull_requests", "effective_since": effective_since, "counts": { "issues": len(issue_rows), "comments": len(comment_rows), "pull_requests": len(pr_rows), "reviews": len(review_rows), "review_comments": len(review_comment_rows), "pr_files": len(pr_file_rows), "pr_diffs": len(pr_diff_rows), "links": 0, "events": len(event_rows), }, }, ) next_pr_checkpoint += args.checkpoint_every_prs if args.fetch_timeline: log(f"Fetching issue timelines for {len(issues)} changed issues") for issue in issues: for event in client.iter_issue_timeline(owner, repo, int(issue["number"])): event_rows.append(normalize_timeline_event(repo_slug, int(issue["number"]), "issue", event, sid, extracted_at)) link_rows: list[dict[str, Any]] = [] for row in issue_rows: link_rows.extend(build_text_link_rows(repo_slug=repo_slug, owner=owner, repo=repo, source_type="issue", source_number=row["number"], source_id=row["github_id"], body=row["body"], sid=sid, extracted_at=extracted_at)) for row in pr_rows: link_rows.extend(build_text_link_rows(repo_slug=repo_slug, owner=owner, repo=repo, source_type="pull_request", source_number=row["number"], source_id=row["github_id"], body=row["body"], sid=sid, extracted_at=extracted_at)) comment_link_rows = comment_rows if comment_rows else previous_tables["comments"] for row in comment_link_rows: if row["parent_number"] is not None: link_rows.extend(build_text_link_rows(repo_slug=repo_slug, owner=owner, repo=repo, source_type="comment", source_number=row["parent_number"], source_id=row["github_id"], body=row["body"], sid=sid, extracted_at=extracted_at)) for row in review_rows: link_rows.extend(build_text_link_rows(repo_slug=repo_slug, owner=owner, repo=repo, source_type="review", source_number=row["pull_request_number"], source_id=row["github_id"], body=row["body"], sid=sid, extracted_at=extracted_at)) for row in review_comment_rows: link_rows.extend(build_text_link_rows(repo_slug=repo_slug, owner=owner, repo=repo, source_type="review_comment", source_number=row["pull_request_number"], source_id=row["github_id"], body=row["body"], sid=sid, extracted_at=extracted_at)) link_rows.extend(build_duplicate_candidate_rows(repo_slug, pr_rows, link_rows, sid, extracted_at)) for event in event_rows: if event.get("source_issue_number"): link_rows.append( { "repo": repo_slug, "source_type": event["parent_kind"], "source_number": event["parent_number"], "source_github_id": None, "target_owner": owner, "target_repo": repo, "target_number": event["source_issue_number"], "link_type": f"timeline:{event['event']}", "link_origin": "timeline", "snapshot_id": sid, "extracted_at": extracted_at, } ) if any([issue_rows, pr_rows, comment_rows, review_rows, review_comment_rows, pr_file_rows, pr_diff_rows, event_rows, link_rows]): log("Pushing final delta checkpoint to Hub before final merge upload") upload_delta_checkpoint( api=api, repo_id=args.hf_repo_id, work_dir=root, repo_slug=repo_slug, sid=sid, stage="final-delta", delta_tables={ "issues": issue_rows, "pull_requests": pr_rows, "comments": comment_rows, "reviews": review_rows, "review_comments": review_comment_rows, "pr_files": pr_file_rows, "pr_diffs": pr_diff_rows, "links": link_rows, "events": event_rows, }, progress={ "stage": "final-delta", "effective_since": effective_since, "counts": { "issues": len(issue_rows), "comments": len(comment_rows), "pull_requests": len(pr_rows), "reviews": len(review_rows), "review_comments": len(review_comment_rows), "pr_files": len(pr_file_rows), "pr_diffs": len(pr_diff_rows), "links": len(link_rows), "events": len(event_rows), }, }, ) delta_tables = { "issues": issue_rows, "pull_requests": pr_rows, "comments": comment_rows, "reviews": review_rows, "review_comments": review_comment_rows, "pr_files": pr_file_rows, "pr_diffs": pr_diff_rows, "links": link_rows, "events": event_rows, } final_tables = { table_name: merge_rows(table_name, previous_tables[table_name], delta_rows) for table_name, delta_rows in delta_tables.items() } manifest = { "repo": repo_slug, "snapshot_id": sid, "crawl_started_at": crawl_started_at, "extracted_at": extracted_at, "watermark": { "effective_since": effective_since, "next_since": crawl_started_at, }, "delta_counts": { "issue_stubs": len(issue_stubs), "issues": len(issue_rows), "pull_requests": len(pr_rows), "comments": len(comment_rows), "reviews": len(review_rows), "review_comments": len(review_comment_rows), "pr_files": len(pr_file_rows), "pr_diffs": len(pr_diff_rows), "timeline_events": len(event_rows), "links": len(link_rows), }, "counts": { "issues": len(final_tables["issues"]), "pull_requests": len(final_tables["pull_requests"]), "comments": len(final_tables["comments"]), "reviews": len(final_tables["reviews"]), "review_comments": len(final_tables["review_comments"]), "pr_files": len(final_tables["pr_files"]), "pr_diffs": len(final_tables["pr_diffs"]), "timeline_events": len(final_tables["events"]), "links": len(final_tables["links"]), }, } log("Writing updated dataset files") for table_name, rows in final_tables.items(): write_rows(output_root / f"{table_name}.parquet", table_name, rows) issue_comment_rows, pr_comment_rows = viewer_comment_rows( final_tables["comments"], final_tables["pull_requests"], ) write_rows(output_root / "issue_comments.parquet", "comments", issue_comment_rows) write_rows(output_root / "pr_comments.parquet", "comments", pr_comment_rows) (output_root / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") (output_root / "README.md").write_text(build_dataset_card(repo_slug, sid, manifest), encoding="utf-8") (output_root / "state").mkdir(parents=True, exist_ok=True) (output_root / "state" / "watermark.json").write_text( json.dumps( { "repo": repo_slug, "last_successful_snapshot_id": sid, "effective_since": effective_since, "next_since": crawl_started_at, "updated_at": extracted_at, }, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) (output_root / "snapshots").mkdir(parents=True, exist_ok=True) (output_root / "snapshots" / sid).mkdir(parents=True, exist_ok=True) (output_root / "snapshots" / sid / "manifest.json").write_text( json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) (output_root / "snapshots" / "latest.json").write_text( json.dumps( { "repo": repo_slug, "latest_snapshot_id": sid, "manifest_path": "manifest.json", "archived_manifest_path": f"snapshots/{sid}/manifest.json", "next_since": crawl_started_at, }, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) log("Uploading updated dataset to the Hub") api.upload_folder( folder_path=str(output_root), repo_id=args.hf_repo_id, repo_type="dataset", commit_message=f"Update transformers dataset snapshot {sid}", ) log(f"Dataset update complete for {args.hf_repo_id}") if __name__ == "__main__": main()