-
Notifications
You must be signed in to change notification settings - Fork 3
Use GH Archive to pull 2024 stats #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
edmundmiller
wants to merge
10
commits into
main
Choose a base branch
from
gharchive
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
134941c
feat: Add initial gharchive pipeline
edmundmiller 8443da0
refactor: Use BigQuery to get data
edmundmiller d430d81
refactor: Use connectorx
edmundmiller 967f377
build: meltano init
edmundmiller 6d016e4
feat: We are only missing "Number GitHub Contributors", "Number close…
edmundmiller bcdfffb
build: Switch to tap-github
edmundmiller a4ed3d6
fix: Set up motherduck
edmundmiller 55c5ca7
Get PRs releases, contributors and stargazers
edmundmiller b2ffb5d
Try parsing the gharchive jsons
edmundmiller f8c4885
Merge branch 'main' into gharchive
mashehu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,5 +8,6 @@ static/data | |
| .vscode/settings.json | ||
| .env | ||
| .evidence/meta | ||
| .meltano/ | ||
| *.pyc | ||
| __pycache__ | ||
| __pycache__ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| version: 1 | ||
| default_environment: dev | ||
| project_id: 64e752dd-4728-4bbd-b8d0-9af37a481f6b | ||
| environments: | ||
| - name: dev | ||
| - name: staging | ||
| - name: prod | ||
| send_anonymous_usage_stats: false | ||
| plugins: | ||
| extractors: | ||
| - name: tap-gharchive | ||
| namespace: tap_gharchive | ||
| pip_url: -e . | ||
| executable: tap-gharchive | ||
| config: | ||
| api_url: https://data.gharchive.org | ||
| streams: | ||
| - name: github_events | ||
| path: /2023-10-01-0.json.gz | ||
| primary_keys: | ||
| - id | ||
| schema: | ||
| properties: | ||
| type: | ||
| type: string | ||
| actor: | ||
| type: object | ||
| repo: | ||
| type: object | ||
| created_at: | ||
| type: string | ||
| org: | ||
| type: object | ||
| payload: | ||
| type: object | ||
| start_date: '2023-10-01' | ||
| loaders: | ||
| - name: target-jsonl | ||
| variant: andyh1203 | ||
| pip_url: target-jsonl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,218 @@ | ||
| import dlt | ||
| from dlt.sources.sql_database import sql_table | ||
| import pendulum | ||
| from typing import Iterator, Dict, List | ||
| from collections import defaultdict | ||
| import os | ||
|
|
||
|
|
||
| def process_events_for_stats(events: List[Dict]) -> Dict: | ||
| """Process a batch of events to calculate statistics.""" | ||
| stats = { | ||
| "repo_metrics": defaultdict( | ||
| lambda: { | ||
| "stars": 0, | ||
| "forks": 0, | ||
| "watchers": 0, | ||
| } | ||
| ), | ||
| "traffic": defaultdict( | ||
| lambda: { | ||
| "views": defaultdict(int), | ||
| "clones": defaultdict(int), | ||
| "unique_views": defaultdict(int), | ||
| "unique_clones": defaultdict(int), | ||
| } | ||
| ), | ||
| "contributors": defaultdict( | ||
| lambda: { | ||
| "commits": 0, | ||
| "additions": 0, | ||
| "deletions": 0, | ||
| "first_contribution": None, | ||
| } | ||
| ), | ||
| "issues": { | ||
| "total": 0, | ||
| "open": 0, | ||
| "closed": 0, | ||
| "response_times": [], | ||
| "close_times": [], | ||
| "daily_opened": defaultdict(int), | ||
| "daily_closed": defaultdict(int), | ||
| }, | ||
| "pull_requests": { | ||
| "total": 0, | ||
| "open": 0, | ||
| "closed": 0, | ||
| "response_times": [], | ||
| "close_times": [], | ||
| "daily_opened": defaultdict(int), | ||
| "daily_closed": defaultdict(int), | ||
| }, | ||
| } | ||
|
|
||
| for event in events: | ||
| repo_name = event.get("repo", {}).get("name", "").split("/")[-1] | ||
| event_type = event.get("type") | ||
|
|
||
| # Process different event types | ||
| if event_type == "WatchEvent": | ||
| stats["repo_metrics"][repo_name]["stars"] += 1 | ||
| elif event_type == "ForkEvent": | ||
| stats["repo_metrics"][repo_name]["forks"] += 1 | ||
| elif event_type == "PushEvent": | ||
| author = event.get("actor", {}).get("login") | ||
| if author: | ||
| stats["contributors"][author]["commits"] += len( | ||
| event.get("payload", {}).get("commits", []) | ||
| ) | ||
| for commit in event.get("payload", {}).get("commits", []): | ||
| stats["contributors"][author]["additions"] += commit.get( | ||
| "stats", {} | ||
| ).get("additions", 0) | ||
| stats["contributors"][author]["deletions"] += commit.get( | ||
| "stats", {} | ||
| ).get("deletions", 0) | ||
| elif event_type == "IssuesEvent": | ||
| action = event.get("payload", {}).get("action") | ||
| issue = event.get("payload", {}).get("issue", {}) | ||
| is_pr = "pull_request" in issue | ||
|
|
||
| stats_key = "pull_requests" if is_pr else "issues" | ||
| stats[stats_key]["total"] += 1 | ||
|
|
||
| if action == "opened": | ||
| stats[stats_key]["open"] += 1 | ||
| created_date = pendulum.parse(issue.get("created_at")).format( | ||
| "YYYY-MM-DD" | ||
| ) | ||
| stats[stats_key]["daily_opened"][created_date] += 1 | ||
| elif action == "closed": | ||
| stats[stats_key]["closed"] += 1 | ||
| closed_date = pendulum.parse(event.get("created_at")).format( | ||
| "YYYY-MM-DD" | ||
| ) | ||
| stats[stats_key]["daily_closed"][closed_date] += 1 | ||
|
|
||
| # Calculate close time | ||
| if issue.get("created_at"): | ||
| created_time = pendulum.parse(issue["created_at"]) | ||
| closed_time = pendulum.parse(event.get("created_at")) | ||
| close_time = (closed_time - created_time).total_seconds() | ||
| stats[stats_key]["close_times"].append(close_time) | ||
|
|
||
| elif event_type == "IssueCommentEvent": | ||
| issue = event.get("payload", {}).get("issue", {}) | ||
| is_pr = "pull_request" in issue | ||
| stats_key = "pull_requests" if is_pr else "issues" | ||
|
|
||
| # Calculate response time for first comment | ||
| if issue.get("created_at") and event.get("created_at"): | ||
| created_time = pendulum.parse(issue["created_at"]) | ||
| comment_time = pendulum.parse(event.get("created_at")) | ||
| response_time = (comment_time - created_time).total_seconds() | ||
| stats[stats_key]["response_times"].append(response_time) | ||
|
|
||
| return stats | ||
|
|
||
|
|
||
| @dlt.source | ||
| def gharchive_source(start_date: str = "2024-01-01", end_date: str = None): | ||
| """ | ||
| Load GitHub events for nf-core organization from GH Archive BigQuery dataset. | ||
|
|
||
| Args: | ||
| start_date: Start date in YYYY-MM-DD format | ||
| end_date: End date in YYYY-MM-DD format (defaults to current date) | ||
| """ | ||
| if end_date is None: | ||
| end_date = pendulum.now().format("YYYY-MM-DD") | ||
|
|
||
| # Get BigQuery credentials path from environment | ||
| # credentials_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS') | ||
| # if not credentials_path: | ||
| # raise ValueError("GOOGLE_APPLICATION_CREDENTIALS environment variable must be set") | ||
|
|
||
| # Construct BigQuery connection string for ConnectorX | ||
| conn = f"bigquery://{credentials_path}" | ||
|
|
||
| @dlt.resource(write_disposition="append", name="raw_events") | ||
| def events( | ||
| start_date: str = start_date, end_date: str = end_date | ||
| ) -> Iterator[Dict]: | ||
| """Query GitHub events from BigQuery.""" | ||
| query = f""" | ||
| SELECT * | ||
| FROM `githubarchive.day.*` | ||
| WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE('{start_date}')) | ||
| AND FORMAT_DATE('%Y%m%d', DATE('{end_date}')) | ||
| AND JSON_EXTRACT_SCALAR(payload, '$.organization.login') = 'nf-core' | ||
| """ | ||
|
|
||
| # Create sql_table with ConnectorX backend | ||
| table = sql_table( | ||
| conn, # BigQuery connection string | ||
| query=query, | ||
| chunk_size=100000, # Process in chunks for better memory usage | ||
| backend="connectorx", # Use ConnectorX backend for better performance | ||
| reflection_level="full_with_precision", # Get exact data types | ||
| backend_kwargs={"return_type": "arrow"}, # Use Arrow for better performance | ||
| ) | ||
| yield from table | ||
|
|
||
| @dlt.resource(write_disposition="merge", primary_key="date", name="daily_stats") | ||
| def daily_statistics( | ||
| start_date: str = start_date, end_date: str = end_date | ||
| ) -> Iterator[Dict]: | ||
| """Calculate daily statistics from BigQuery events.""" | ||
| start = pendulum.parse(start_date) | ||
| end = pendulum.parse(end_date) | ||
| current = start | ||
|
|
||
| while current <= end: | ||
| query = f""" | ||
| SELECT * | ||
| FROM `githubarchive.day.{current.format("YYYYMMDD")}` | ||
| WHERE JSON_EXTRACT_SCALAR(payload, '$.organization.login') = 'nf-core' | ||
| """ | ||
|
|
||
| # Create sql_table with ConnectorX backend | ||
| table = sql_table( | ||
| conn, | ||
| query=query, | ||
| chunk_size=100000, | ||
| backend="connectorx", | ||
| reflection_level="full_with_precision", | ||
| backend_kwargs={"return_type": "arrow"}, | ||
| ) | ||
| daily_events = list(table) | ||
|
|
||
| if daily_events: | ||
| stats = process_events_for_stats(daily_events) | ||
| yield {"date": current.format("YYYY-MM-DD"), "stats": stats} | ||
|
|
||
| current = current.add(days=1) | ||
|
|
||
| return events, daily_statistics | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Initialize the pipeline | ||
| pipeline = dlt.pipeline( | ||
| pipeline_name="gharchive", | ||
| destination="duckdb", | ||
| dataset_name="github_events", | ||
| progress="log", # Add progress logging | ||
| dev_mode=True, # Enable dev mode for better debugging | ||
| ) | ||
|
|
||
| # Run the pipeline for 2024 data | ||
| load_info = pipeline.run( | ||
| gharchive_source( | ||
| start_date="2024-01-01", end_date=pendulum.now().format("YYYY-MM-DD") | ||
| ), | ||
| loader_file_format="parquet", # Use parquet for better performance | ||
| ) | ||
|
|
||
| print(load_info) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| { | ||
| "plugin_type": "extractors", | ||
| "name": "tap-bigquery", | ||
| "namespace": "tap_bigquery", | ||
| "variant": "anelendata", | ||
| "label": "BigQuery", | ||
| "docs": "https://hub.meltano.com/extractors/tap-bigquery--anelendata", | ||
| "repo": "https://github.com/anelendata/tap-bigquery", | ||
| "pip_url": "tap-bigquery", | ||
| "description": "BigQuery data warehouse extractor", | ||
| "logo_url": "https://hub.meltano.com/assets/logos/extractors/bigquery.png", | ||
| "capabilities": [ | ||
| "catalog", | ||
| "discover", | ||
| "state" | ||
| ], | ||
| "settings_group_validation": [ | ||
| [ | ||
| "streams", | ||
| "start_datetime", | ||
| "credentials_path" | ||
| ] | ||
| ], | ||
| "settings": [ | ||
| { | ||
| "name": "streams", | ||
| "kind": "array", | ||
| "label": "Streams", | ||
| "description": "Array of objects with `name`, `table`, `columns`, `datetime_key`, and `filters` keys:\n\n- `name`: The entity name, used by most loaders as the name of the table to be created.\n- `table`: Fully qualified table name in BigQuery, with format `` `<project>.<dataset>.<table>` ``. Since backticks have special meaning in YAML, values in `meltano.yml` should be wrapped in double quotes.\n- `columns`: Array of column names to select. Using `[\"*\"]` is not recommended as it can become very expensive for a table with a large number of columns.\n- `datetime_key`: Name of datetime column to use as [replication key](https://docs.meltano.com/guide/integration#replication-key).\n- `filters`: Optional array of `WHERE` clauses to filter extracted data, e.g. `\"column='value'\"`.\n" | ||
| }, | ||
| { | ||
| "name": "credentials_path", | ||
| "env": "GOOGLE_APPLICATION_CREDENTIALS", | ||
| "value": "$MELTANO_PROJECT_ROOT/client_secrets.json", | ||
| "label": "Credentials Path", | ||
| "description": "Fully qualified path to `client_secrets.json` for your service account.\n\nSee the [\"Activate the Google BigQuery API\" section of the repository's README](https://github.com/anelendata/tap-bigquery#step-1-activate-the-google-bigquery-api) and <https://cloud.google.com/docs/authentication/production>.\n\nBy default, this file is expected to be at the root of your project directory.\n" | ||
| }, | ||
| { | ||
| "name": "start_datetime", | ||
| "kind": "date_iso8601", | ||
| "label": "Start Datetime", | ||
| "description": "Determines how much historical data will be extracted. Please be aware that the larger the time period and amount of data, the longer the initial extraction can be expected to take." | ||
| }, | ||
| { | ||
| "name": "end_datetime", | ||
| "kind": "date_iso8601", | ||
| "label": "End Datetime", | ||
| "description": "Date up to when historical data will be extracted." | ||
| }, | ||
| { | ||
| "name": "limit", | ||
| "kind": "integer", | ||
| "label": "Limit", | ||
| "description": "Limits the number of records returned in each stream, applied as a limit in the query." | ||
| }, | ||
| { | ||
| "name": "start_always_inclusive", | ||
| "kind": "boolean", | ||
| "value": true, | ||
| "label": "Start Always Inclusive", | ||
| "description": "When replicating incrementally, disable to only select records whose `datetime_key` is greater than the maximum value replicated in the last run, by excluding records whose timestamps match exactly. This could cause records to be missed that were created after the last run finished, but during the same second and with the same timestamp." | ||
| } | ||
| ] | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this version seems to not be available?