zhimin-z commited on
Commit ·
973e5a6
1
Parent(s): edbc9fd
add
Browse filesFiles changed (3)
- .gitignore+5-3
- app.py+95-95
- msr.py+182-88
123456*.claude*.env*.venv*.ipynb*.pyc*.duckdb12345678.claude.vscode.omc.env.venv*.ipynb*.pyc*.duckdb
30 unmodified lines313233343536236 unmodified lines2732742752762772782792802812822832842853 unmodified lines2892902912922932942952962972982993003013023033043053063073081 unmodified line3103113123133143153163173183193201 unmodified line3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484493 unmodified lines45345445545645745845946046146246346446546646746846947028 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205211 unmodified line5235245255265275285296 unmodified lines53653753853954054154285 unmodified lines62862963063163263363414 unmodified lines64965065165265365465565665765865966066166266330 unmodified lines6946956966976986995 unmodified lines70570670770870971030 unmodified lines("Assistant", "string"),("Website", "string"),("Total PRs", "number"),("Total Commits", "number"),("Merged PRs", "number"),("Acceptance Rate (%)", "number"),236 unmodified linesdef create_monthly_metrics_plot(type="pr", top_n=5):"""Create a Plotly figure showing monthly metrics.- For PRs: Acceptance Rate (%) as line curves, Total PRs as bar charts- For Commits: Total Commits as bar chartsEach assistant gets a unique color for both their line and bars.Args:type: Type of metrics to display - "pr" or "commit" (default: "pr")top_n: Number of top assistants to show (default: 5)"""# Determine metrics key and field names based on type3 unmodified linesno_data_msg = "No commit data available for visualization"total_label = "Total Commits"print_msg = "commit"has_rate = Falseelse: # default to "pr"metrics_key = 'pr_monthly_metrics'total_field = 'total_prs'no_data_msg = "No PR data available for visualization"total_label = "Total PRs"print_msg = "PR"has_rate = True# Load from saved datasetsaved_data = load_leaderboard_data_from_hf()if not saved_data or metrics_key not in saved_data:# Return an empty figure with a messagefig = go.Figure()fig.add_annotation(text=no_data_msg,1 unmodified linex=0.5, y=0.5, showarrow=False,font=dict(size=16))fig.update_layout(title=None,xaxis_title=None,height=500)return figmetrics = saved_data[metrics_key]1 unmodified line# Apply top_n filter if specifiedif top_n is not None and top_n > 0 and metrics.get('assistants'):# Calculate total count for each assistantagent_totals = []for agent_name in metrics['assistants']:agent_data = metrics['data'].get(agent_name, {})total_count = sum(agent_data.get(total_field, []))agent_totals.append((agent_name, total_count))# Sort by total count and take top Nagent_totals.sort(key=lambda x: x[1], reverse=True)top_agents = [agent_name for agent_name, _ in agent_totals[:top_n]]# Filter metrics to only include top assistantsmetrics = {'assistants': top_agents,'months': metrics['months'],'data': {assistant: metrics['data'][assistant] for assistant in top_agents if assistant in metrics['data']}}if not metrics['assistants'] or not metrics['months']:# Return an empty figure with a messagefig = go.Figure()fig.add_annotation(text="No data available for visualization",xref="paper", yref="paper",x=0.5, y=0.5, showarrow=False,font=dict(size=16))fig.update_layout(title=None,xaxis_title=None,height=500)return fig# Create figure with secondary y-axis (for PRs) or single axis (for commits)if has_rate:fig = make_subplots(specs=[[{"secondary_y": True}]])else:fig = go.Figure()# Generate unique colors for many assistants using HSL color spacedef generate_color(index, total):"""Generate distinct colors using HSL color space for better distribution"""hue = (index * 360 / total) % 360saturation = 70 + (index % 3) * 10 # Vary saturation slightlylightness = 45 + (index % 2) * 10 # Vary lightness slightlyreturn f'hsl({hue}, {saturation}%, {lightness}%)'assistants = metrics['assistants']months = metrics['months']data = metrics['data']# Generate colors for all assistantsagent_colors = {assistant: generate_color(idx, len(assistants)) for idx, assistant in enumerate(assistants)}# Add traces for each assistantfor idx, agent_name in enumerate(assistants):color = agent_colors[agent_name]agent_data = data[agent_name]if has_rate:# Add line trace for acceptance rate (left y-axis) - PR onlyacceptance_rates = agent_data['acceptance_rates']# Filter out None values for plottingx_acceptance = [month for month, rate in zip(months, acceptance_rates) if rate is not None]y_acceptance = [rate for rate in acceptance_rates if rate is not None]if x_acceptance and y_acceptance: # Only add trace if there's datafig.add_trace(go.Scatter(x=x_acceptance,y=y_acceptance,name=agent_name,mode='lines+markers',line=dict(color=color, width=2),marker=dict(size=8),legendgroup=agent_name,showlegend=(top_n is not None and top_n <= 10), # Show legend for top N assistantshovertemplate='<b>Assistant: %{fullData.name}</b><br>' +'Month: %{x}<br>' +'Acceptance Rate: %{y:.2f}%<br>' +'<extra></extra>'),secondary_y=False)# Add bar trace for total count (right y-axis for PRs, single axis for commits)# Only show bars for months where assistant has datax_bars = []y_bars = []for month, count in zip(months, agent_data[total_field]):if count > 0: # Only include months with datax_bars.append(month)y_bars.append(count)if x_bars and y_bars: # Only add trace if there's datatrace_args = {'x': x_bars,'y': y_bars,'name': agent_name,'marker': dict(color=color, opacity=0.7 if type == "commit" else 0.6),'legendgroup': agent_name,'showlegend': False if has_rate else (top_n is not None and top_n <= 10),'hovertemplate': f'<b>Assistant: %{{fullData.name}}</b><br>' +f'Month: %{{x}}<br>' +f'{total_label}: %{{y}}<br>' +'<extra></extra>','offsetgroup': agent_name}if has_rate:fig.add_trace(go.Bar(**trace_args), secondary_y=True)else:fig.add_trace(go.Bar(**trace_args))# Update axes labelsfig.update_xaxes(title_text=None)if has_rate:# For PRs: dual y-axesfig.update_yaxes(title_text="<b>Acceptance Rate (%)</b>",range=[0, 100],secondary_y=False,showticklabels=True,3 unmodified lines)fig.update_yaxes(title_text=f"<b>{total_label}</b>", secondary_y=True)else:# For commits: single y-axisfig.update_yaxes(title_text=f"<b>{total_label}</b>")# Update layoutshow_legend = (top_n is not None and top_n <= 10)fig.update_layout(title=None,hovermode='closest', # Show individual assistant info on hoverbarmode='group',height=600,showlegend=show_legend,margin=dict(l=50, r=150 if show_legend else 50, t=50, b=50) # More right margin when legend is shown)return fig28 unmodified linesfiltered_count = 0for identifier, data in cache_dict.items():total_prs = data.get('total_prs', 0)# Filter out assistants with zero total PRsif total_prs == 0:filtered_count += 1continue# Only include display-relevant fieldsrows.append([data.get('name', 'Unknown'),data.get('website', 'N/A'),total_prs,data.get('total_commits', 0),data.get('merged_prs', 0),data.get('acceptance_rate', 0.0),])print(f"Filtered out {filtered_count} assistants with 0 PRs")print(f"Leaderboard will show {len(rows)} assistants")# Create DataFrame1 unmodified linedf = pd.DataFrame(rows, columns=column_names)# Ensure numeric typesnumeric_cols = ["Total PRs", "Total Commits", "Merged PRs", "Acceptance Rate (%)"]for col in numeric_cols:if col in df.columns:df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)6 unmodified lines# Add a placeholder row when there's only 1 recordif len(df) == 1:placeholder_row = pd.DataFrame([["Submit yours to join!", "—", 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, 0]], columns=df.columns)df = pd.concat([df, placeholder_row], ignore_index=True)print("Added placeholder row for single-record workaround")85 unmodified lines# GRADIO APPLICATION# =============================================================================print(f"\nStarting SWE Assistant PR Leaderboard")print(f" Data source: {LEADERBOARD_REPO}")print(f" Reload frequency: Daily at 12:00 AM UTC\n")14 unmodified linesprint(f"{'='*80}\n")# Create Gradio interfacewith gr.Blocks(title="SWE Assistant PR & Commit Leaderboard", theme=gr.themes.Soft()) as app:gr.Markdown("# SWE Assistant PR & Commit Leaderboard")gr.Markdown(f"Track and compare GitHub pull request and commit statistics for SWE assistants")with gr.Tabs():# Leaderboard Tabwith gr.Tab("Leaderboard"):gr.Markdown("*Statistics are based on assistant PR and commit activity tracked by the system*")leaderboard_table = Leaderboard(value=pd.DataFrame(columns=[col[0] for col in LEADERBOARD_COLUMNS]), # Empty initiallydatatype=LEADERBOARD_COLUMNS,30 unmodified linesgr.Markdown("*Commit volume over time*")commit_monthly_metrics_plot = gr.Plot()# Load monthly metrics when app startsapp.load(fn=lambda: create_monthly_metrics_plot(),5 unmodified linesinputs=[],outputs=[commit_monthly_metrics_plot])# Submit Assistant Tab30 unmodified lines31323334353637236 unmodified lines2742752762772782792802812822832842852862873 unmodified lines2912922932942952962972982993003013023033043053063073083093103113123133143153163173183191 unmodified line3213223233243253263271 unmodified line3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374383 unmodified lines44244344444544644744844945045145245345445545628 unmodified lines4854864874884894904914924934944954964974984995005015025035045055065075085091 unmodified line5115125135145155165175185195206 unmodified lines52752852953053153253385 unmodified lines61962062162262362462514 unmodified lines64064164264364464564664764864965065165265365430 unmodified lines6856866876886896906916926936945 unmodified lines70070170270370470570670770870971030 unmodified lines("Assistant", "string"),("Website", "string"),("Total PRs", "number"),("Total Reviews", "number"),("Total Commits", "number"),("Merged PRs", "number"),("Acceptance Rate (%)", "number"),236 unmodified linesdef create_monthly_metrics_plot(type="pr", top_n=5):"""Create a Plotly figure showing monthly metrics.- For PRs: Acceptance Rate (%) as line curves + Total PRs as bar charts (dual y-axes)- For Commits: Total Commits as bar charts (single y-axis)- For Reviews: Total Reviews as bar charts (single y-axis)Each assistant gets a unique color for both their line and bars.Args:type: Type of metrics to display - "pr", "commit", or "review" (default: "pr")top_n: Number of top assistants to show (default: 5)"""# Determine metrics key and field names based on type3 unmodified linesno_data_msg = "No commit data available for visualization"total_label = "Total Commits"print_msg = "commit"rate_field = Nonerate_label = Noneelif type == "review":metrics_key = 'review_monthly_metrics'total_field = 'total_reviews'no_data_msg = "No review data available for visualization"total_label = "Total Reviews"print_msg = "review"rate_field = Nonerate_label = Noneelse: # default to "pr"metrics_key = 'pr_monthly_metrics'total_field = 'total_prs'no_data_msg = "No PR data available for visualization"total_label = "Total PRs"print_msg = "PR"rate_field = 'acceptance_rates'rate_label = "Acceptance Rate"# Load from saved datasetsaved_data = load_leaderboard_data_from_hf()if not saved_data or metrics_key not in saved_data:fig = go.Figure()fig.add_annotation(text=no_data_msg,1 unmodified linex=0.5, y=0.5, showarrow=False,font=dict(size=16))fig.update_layout(title=None, xaxis_title=None, height=500)return figmetrics = saved_data[metrics_key]1 unmodified line# Apply top_n filter if specifiedif top_n is not None and top_n > 0 and metrics.get('assistants'):agent_totals = []for agent_name in metrics['assistants']:agent_data = metrics['data'].get(agent_name, {})total_count = sum(agent_data.get(total_field, []))agent_totals.append((agent_name, total_count))agent_totals.sort(key=lambda x: x[1], reverse=True)top_agents = [agent_name for agent_name, _ in agent_totals[:top_n]]metrics = {'assistants': top_agents,'months': metrics['months'],'data': {a: metrics['data'][a] for a in top_agents if a in metrics['data']}}if not metrics['assistants'] or not metrics['months']:fig = go.Figure()fig.add_annotation(text=no_data_msg,xref="paper", yref="paper",x=0.5, y=0.5, showarrow=False,font=dict(size=16))fig.update_layout(title=None, xaxis_title=None, height=500)return fig# Create figure — dual y-axes when rate data exists, single axis otherwiseif rate_field:fig = make_subplots(specs=[[{"secondary_y": True}]])else:fig = go.Figure()# Generate unique colors using HSL color spacedef generate_color(index, total):hue = (index * 360 / total) % 360saturation = 70 + (index % 3) * 10lightness = 45 + (index % 2) * 10return f'hsl({hue}, {saturation}%, {lightness}%)'assistants = metrics['assistants']months = metrics['months']data = metrics['data']show_legend = (top_n is not None and top_n <= 10)agent_colors = {a: generate_color(i, len(assistants)) for i, a in enumerate(assistants)}for agent_name in assistants:color = agent_colors[agent_name]agent_data = data[agent_name]# Rate line trace (left y-axis) — only for types with rate dataif rate_field:rates = agent_data[rate_field]x_rates = [m for m, r in zip(months, rates) if r is not None]y_rates = [r for r in rates if r is not None]if x_rates and y_rates:fig.add_trace(go.Scatter(x=x_rates,y=y_rates,name=agent_name,mode='lines+markers',line=dict(color=color, width=2),marker=dict(size=8),legendgroup=agent_name,showlegend=show_legend,hovertemplate=f'<b>Assistant: %{{fullData.name}}</b><br>'f'Month: %{{x}}<br>'f'{rate_label}: %{{y:.2f}}%<br>'f'<extra></extra>'),secondary_y=False)# Bar trace for total countx_bars = [m for m, c in zip(months, agent_data[total_field]) if c > 0]y_bars = [c for c in agent_data[total_field] if c > 0]if x_bars and y_bars:bar_trace = go.Bar(x=x_bars,y=y_bars,name=agent_name,marker=dict(color=color, opacity=0.6),legendgroup=agent_name,showlegend=False if rate_field else show_legend,hovertemplate=f'<b>Assistant: %{{fullData.name}}</b><br>'f'Month: %{{x}}<br>'f'{total_label}: %{{y}}<br>'f'<extra></extra>',offsetgroup=agent_name)if rate_field:fig.add_trace(bar_trace, secondary_y=True)else:fig.add_trace(bar_trace)# Update axesfig.update_xaxes(title_text=None)if rate_field:fig.update_yaxes(title_text=f"<b>{rate_label} (%)</b>",range=[0, 100],secondary_y=False,showticklabels=True,3 unmodified lines)fig.update_yaxes(title_text=f"<b>{total_label}</b>", secondary_y=True)else:fig.update_yaxes(title_text=f"<b>{total_label}</b>")fig.update_layout(title=None,hovermode='closest',barmode='group',height=600,showlegend=show_legend,margin=dict(l=50, r=150 if show_legend else 50, t=50, b=50))return fig28 unmodified linesfiltered_count = 0for identifier, data in cache_dict.items():total_prs = data.get('total_prs', 0)total_reviews = data.get('total_reviews', 0)total_commits = data.get('total_commits', 0)# Filter out assistants with no activityif total_prs == 0 and total_reviews == 0 and total_commits == 0:filtered_count += 1continuerows.append([data.get('name', 'Unknown'),data.get('website', 'N/A'),total_prs,total_reviews,total_commits,data.get('merged_prs', 0),data.get('acceptance_rate', 0.0),])print(f"Filtered out {filtered_count} assistants with no activity")print(f"Leaderboard will show {len(rows)} assistants")# Create DataFrame1 unmodified linedf = pd.DataFrame(rows, columns=column_names)# Ensure numeric typesnumeric_cols = ["Total PRs", "Total Reviews", "Total Commits","Merged PRs", "Acceptance Rate (%)",]for col in numeric_cols:if col in df.columns:df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)6 unmodified lines# Add a placeholder row when there's only 1 recordif len(df) == 1:placeholder_row = pd.DataFrame([["Submit yours to join!", "—", 0, 0, 0, 0, 0.0]], columns=df.columns)df = pd.concat([df, placeholder_row], ignore_index=True)print("Added placeholder row for single-record workaround")85 unmodified lines# GRADIO APPLICATION# =============================================================================print(f"\nStarting SWE Assistant PR, Commit & Review Leaderboard")print(f" Data source: {LEADERBOARD_REPO}")print(f" Reload frequency: Daily at 12:00 AM UTC\n")14 unmodified linesprint(f"{'='*80}\n")# Create Gradio interfacewith gr.Blocks(title="SWE Assistant PR, Commit & Review Leaderboard") as app:gr.Markdown("# SWE Assistant PR, Commit & Review Leaderboard")gr.Markdown(f"Track and compare GitHub pull request, commit, and review statistics for SWE assistants")with gr.Tabs():# Leaderboard Tabwith gr.Tab("Leaderboard"):gr.Markdown("*Statistics are based on assistant PR, commit, and review activity tracked by the system*")leaderboard_table = Leaderboard(value=pd.DataFrame(columns=[col[0] for col in LEADERBOARD_COLUMNS]), # Empty initiallydatatype=LEADERBOARD_COLUMNS,30 unmodified linesgr.Markdown("*Commit volume over time*")commit_monthly_metrics_plot = gr.Plot()with gr.Column():gr.Markdown("*Review volume over time*")review_monthly_metrics_plot = gr.Plot()# Load monthly metrics when app startsapp.load(fn=lambda: create_monthly_metrics_plot(),5 unmodified linesinputs=[],outputs=[commit_monthly_metrics_plot])app.load(fn=lambda: create_monthly_metrics_plot(type="review"),inputs=[],outputs=[review_monthly_metrics_plot])# Submit Assistant Tab
137 unmodified lines138139140141142143144145146149 unmodified lines29629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233315 unmodified lines3493503513523533543553563573583593603613623634 unmodified lines3683693703713723737 unmodified lines3813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414 unmodified lines4464474484494504514524534544554564574584594604614624634644654663 unmodified lines4704714724734744754764774784794804814824834844854864874884894905 unmodified lines49649749849950050150250350450550650757 unmodified lines5655665675685695705715725735 unmodified lines57958058158258358489 unmodified lines67467567667767867968068168220 unmodified lines7037047057067077087097107117127137147157167177185 unmodified lines7247257267277287297307317327337347357367377387397407417427437447457467477487497508 unmodified lines75976076176276376476524 unmodified lines79079179279379479579679712 unmodified lines8108118128138148158161 unmodified line8188198208218228238248258268278288298308318328338348358368378382 unmodified lines841842843844845846847848849850851852853854855856857858859860861862863864865866867868137 unmodified linesurls.append(url)current_date += timedelta(days=1)for url in urls:download_file(url)# =============================================================================# HUGGINGFACE API WRAPPERS149 unmodified linesdef fetch_all_metadata_streaming(conn, identifiers, start_date, end_date):"""QUERY: Fetch both commit and PR metadata using streaming batch processing:- PushEvent (for commit tracking)- PullRequestEvent (for PR tracking)Args:conn: DuckDB connection instanceidentifiers: List of GitHub usernames/bot identifiers (~1500)start_date: Start datetime (timezone-aware)end_date: End datetime (timezone-aware)Returns:Dictionary with two keys:- 'commits': {author: [commit_metadata]} for commit tracking- 'prs': {author: [pr_metadata]} for PR tracking"""identifier_list = ', '.join([f"'{id}'" for id in identifiers])# Storage for commitscommits_by_agent = defaultdict(list)# Storage for PRsprs_by_agent = defaultdict(list)# Calculate total batchestotal_days = (end_date - start_date).daystotal_batches = (total_days // BATCH_SIZE_DAYS) + 1# Process in configurable batchescurrent_date = start_datebatch_num = 0total_commits = 0total_prs = 0print(f" Streaming {total_batches} batches of {BATCH_SIZE_DAYS}-day intervals...")15 unmodified lines# Build file patterns SQL for THIS BATCHfile_patterns_sql = '[' + ', '.join([f"'{fp}'" for fp in file_patterns]) + ']'# UNIFIED QUERY: Fetch both commits (PushEvent) and PRs (PullRequestEvent)# Post-process in Python to separate themunified_query = f"""SELECTtype,-- Commit fields (from PushEvent)TRY_CAST(json_extract_string(to_json(actor), '$.login') AS VARCHAR) as author,TRY_CAST(json_extract_string(to_json(payload), '$.head') AS VARCHAR) as commit_sha,-- PR fields (from PullRequestEvent)CONCAT(REPLACE(repo.url, 'api.github.com/repos/', 'github.com/'),'/pull/',4 unmodified linesTRY_CAST(json_extract_string(to_json(payload), '$.pull_request.created_at') AS VARCHAR) as pr_created_at,TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.merged_at') AS VARCHAR) as pr_merged_at,TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.closed_at') AS VARCHAR) as pr_closed_at,created_atFROM read_json({file_patterns_sql},7 unmodified lines-- PushEvent: Commits by assistants(type = 'PushEvent'AND TRY_CAST(json_extract_string(to_json(payload), '$.head') AS VARCHAR) IS NOT NULLAND TRY_CAST(json_extract_string(to_json(actor), '$.login') AS VARCHAR) IN ({identifier_list}))OR-- PullRequestEvent: PRs by assistants(type = 'PullRequestEvent'AND payload.pull_request.number IS NOT NULLAND TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.created_at') AS VARCHAR) IS NOT NULLAND TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.user.login') AS VARCHAR) IN ({identifier_list})AND TRY_CAST(json_extract_string(to_json(payload), '$.action') AS VARCHAR) IN ('opened', 'closed'))"""try:all_results = conn.execute(unified_query).fetchall()# Post-process results to separate commits and PRs# Row structure: [type, author, commit_sha, pr_url, action, pr_author,# pr_created_at, pr_merged_at, pr_closed_at, created_at]commit_events = []pr_events_list = []for row in all_results:event_type = row[0]if event_type == 'PushEvent':commit_events.append(row)elif event_type == 'PullRequestEvent':pr_events_list.append(row)# Process commitsbatch_commits = 0for row in commit_events:author = row[1]sha = row[2]created_at = normalize_date_format(row[9]) if row[9] else Noneif not author or not sha:continue# Build commit metadatacommit_metadata = {'sha': sha,'created_at': created_at,}commits_by_agent[author].append(commit_metadata)batch_commits += 1total_commits += 1# Process PRs# Group events by PR URL to merge opened and closed eventspr_events = defaultdict(lambda: {'opened': None, 'closed': None})for row in pr_events_list:pr_url = row[3]action = row[4]pr_author = row[5]4 unmodified linesif not pr_url or not action:continueevent_data = {'pr_author': pr_author,'created_at': pr_created_at,'merged_at': pr_merged_at,'closed_at': pr_closed_at,}pr_events[pr_url][action] = event_data# Only include PRs that have an 'opened' event# Use closed event data (if available) to get merged_at and closed_atbatch_prs = 0for url, events in pr_events.items():if not events['opened']:# Skip PRs without an 'opened' event in this time framecontinueopened_event = events['opened']3 unmodified linesif not pr_author:continue# Build complete PR metadata# created_at comes from opened event# merged_at and closed_at come from closed event (if available)pr_metadata = {'html_url': url,'created_at': opened_event['created_at'],'merged_at': closed_event['merged_at'] if closed_event else None,'closed_at': closed_event['closed_at'] if closed_event else None,}prs_by_agent[pr_author].append(pr_metadata)batch_prs += 1total_prs += 1print(f"✓ {batch_commits} commits, {batch_prs} PRs found")except Exception as e:print(f"\n ✗ Batch {batch_num} error: {str(e)}")5 unmodified lines# Final summaryagents_with_commits = sum(1 for commits in commits_by_agent.values() if commits)agents_with_prs = sum(1 for prs in prs_by_agent.values() if prs)print(f"\n ✓ Complete: {total_commits} commits for {agents_with_commits}/{len(identifiers)} assistants")print(f" ✓ Complete: {total_prs} PRs for {agents_with_prs}/{len(identifiers)} assistants")return {'commits': dict(commits_by_agent),'prs': dict(prs_by_agent)}57 unmodified linesdef calculate_pr_stats_from_metadata(metadata_list):"""Calculate statistics from a list of PR metadata."""total_prs = len(metadata_list)merged = sum(1 for pr_meta in metadata_list if pr_meta.get('merged_at'))closed_not_merged = sum(1 for pr_meta in metadata_listif pr_meta.get('closed_at') and not pr_meta.get('merged_at'))total_decisions = merged + closed_not_mergedacceptance_rate = (merged / total_decisions * 100) if total_decisions > 0 else 05 unmodified lines}def calculate_monthly_metrics_by_agent_commits(all_metadata_dict, assistants):"""Calculate monthly metrics for commits for all assistants for visualization."""identifier_to_name = {assistant.get('github_identifier'): assistant.get('name') for assistant in assistants if assistant.get('github_identifier')}89 unmodified linesfor month in months:prs_in_month = month_dict.get(month, [])merged_count = sum(1 for pr in prs_in_month if pr.get('merged_at'))closed_not_merged_count = sum(1 for pr in prs_in_monthif pr.get('closed_at') and not pr.get('merged_at'))total_count = len(prs_in_month)total_decisions = merged_count + closed_not_merged_count20 unmodified lines}def construct_leaderboard_from_metadata(commit_metadata_dict, pr_metadata_dict, assistants):"""Construct leaderboard from in-memory commit and PR metadata.Args:commit_metadata_dict: Dictionary mapping assistant ID to list of commit metadatapr_metadata_dict: Dictionary mapping assistant ID to list of PR metadataassistants: List of assistant metadataReturns:Dictionary with leaderboard data including both commit and PR statistics"""if not assistants:print("Error: No assistants found")5 unmodified linesidentifier = assistant.get('github_identifier')agent_name = assistant.get('name', 'Unknown')# Get commit and PR metadatacommit_metadata = commit_metadata_dict.get(identifier, [])pr_metadata = pr_metadata_dict.get(identifier, [])# Calculate statisticscommit_stats = calculate_commit_stats_from_metadata(commit_metadata)pr_stats = calculate_pr_stats_from_metadata(pr_metadata)cache_dict[identifier] = {'name': agent_name,'website': assistant.get('website', 'N/A'),'github_identifier': identifier,**commit_stats,**pr_stats}return cache_dictdef save_leaderboard_data_to_hf(leaderboard_dict, commit_monthly_metrics, pr_monthly_metrics):"""Save leaderboard data, commit monthly metrics, and PR monthly metrics to HuggingFace dataset."""try:token = get_hf_token()if not token:8 unmodified lines},'leaderboard': leaderboard_dict,'commit_monthly_metrics': commit_monthly_metrics,'pr_monthly_metrics': pr_monthly_metrics}with open(LEADERBOARD_FILENAME, 'w') as f:24 unmodified linesdef mine_all_agents():"""Mine commit and PR metadata for all assistants using STREAMING batch processing.Downloads GHArchive data, then uses UNIFIED BATCH-based DuckDB queries."""print(f"\n[1/4] Downloading GHArchive data...")12 unmodified linesprint("Error: No valid assistant identifiers found")returnprint(f"\n[3/4] Mining commit and PR metadata ({len(identifiers)} assistants, {LEADERBOARD_TIME_FRAME_DAYS} days)...")try:conn = get_duckdb_connection()1 unmodified lineprint(f"Failed to initialize DuckDB connection: {str(e)}")returncurrent_time = datetime.now(timezone.utc)end_date = current_time.replace(hour=0, minute=0, second=0, microsecond=0)start_date = end_date - timedelta(days=LEADERBOARD_TIME_FRAME_DAYS)try:# USE UNIFIED STREAMING FUNCTION for both commits and PRsresults = fetch_all_metadata_streaming(conn, identifiers, start_date, end_date)# Separate commits and PRscommit_metadata = results['commits']pr_metadata = results['prs']except Exception as e:print(f"Error during DuckDB fetch: {str(e)}")traceback.print_exc()returnfinally:2 unmodified linesprint(f"\n[4/4] Saving leaderboard...")try:# Construct leaderboard with both commit and PR dataleaderboard_dict = construct_leaderboard_from_metadata(commit_metadata, pr_metadata, assistants)# Calculate monthly metrics for both commits and PRscommit_monthly_metrics = calculate_monthly_metrics_by_agent_commits(commit_metadata, assistants)pr_monthly_metrics = calculate_monthly_metrics_by_agent_prs(pr_metadata, assistants)# Save everythingsave_leaderboard_data_to_hf(leaderboard_dict, commit_monthly_metrics, pr_monthly_metrics)except Exception as e:print(f"Error saving leaderboard: {str(e)}")traceback.print_exc()finally:# Clean up DuckDB cache file to save storageif os.path.exists(DUCKDB_CACHE_FILE):try:os.remove(DUCKDB_CACHE_FILE)137 unmodified lines138139140141142143144145146147148149149 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633715 unmodified lines3533543553563573583593603613623633644 unmodified lines3693703713723733743757 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534 unmodified lines4584594604614624634644654664674684694704714724733 unmodified lines4774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145 unmodified lines52052152252352452552652752852953053153253353457 unmodified lines5925935945955965975985995 unmodified lines60560660760860961061161261361461561661761861962062162262362462562662789 unmodified lines71771871972072172272372420 unmodified lines7457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128135 unmodified lines8198208218228238248258268278288298308318328338348358368378388398408418428438448458468 unmodified lines85585685785885986086186224 unmodified lines88788888989089189289389412 unmodified lines9079089099109119129139149151 unmodified line9179189199209219229239249259269279289299309319329332 unmodified lines936937938939940941942943944945946947948949950951952953954955956957958959960961962137 unmodified linesurls.append(url)current_date += timedelta(days=1)success = Truefor url in urls:if not download_file(url):success = Falsereturn success# =============================================================================# HUGGINGFACE API WRAPPERS149 unmodified linesdef fetch_all_metadata_streaming(conn, identifiers, start_date, end_date):"""UNIFIED QUERY: Fetch commit, PR, and review metadata using streaming batch processing.Single query per batch retrieves all event types and post-processes in Python:- PushEvent (commits)- PullRequestEvent (authored PRs)- PullRequestReviewEvent & PullRequestReviewCommentEvent (reviews)Args:conn: DuckDB connection instanceidentifiers: List of GitHub usernames/bot identifiersstart_date: Start datetime (timezone-aware)end_date: End datetime (timezone-aware)Returns:Dictionary with three keys:- 'commits': {author: [commit_metadata]}- 'prs': {author: [pr_metadata]}- 'reviews': {reviewer: [review_metadata]}"""identifier_list = ', '.join([f"'{id}'" for id in identifiers])identifiers_set = set(identifiers)commits_by_agent = defaultdict(list)prs_by_agent = defaultdict(list)reviews_by_agent = defaultdict(list)total_days = (end_date - start_date).daystotal_batches = (total_days // BATCH_SIZE_DAYS) + 1current_date = start_datebatch_num = 0total_commits = 0total_prs = 0total_reviews = 0print(f" Streaming {total_batches} batches of {BATCH_SIZE_DAYS}-day intervals...")15 unmodified lines# Build file patterns SQL for THIS BATCHfile_patterns_sql = '[' + ', '.join([f"'{fp}'" for fp in file_patterns]) + ']'# UNIFIED QUERY: Fetch commits, PRs, and reviews in a single passunified_query = f"""SELECTtype,TRY_CAST(json_extract_string(to_json(actor), '$.login') AS VARCHAR) as actor_login,TRY_CAST(json_extract_string(to_json(payload), '$.head') AS VARCHAR) as commit_sha,CONCAT(REPLACE(repo.url, 'api.github.com/repos/', 'github.com/'),'/pull/',4 unmodified linesTRY_CAST(json_extract_string(to_json(payload), '$.pull_request.created_at') AS VARCHAR) as pr_created_at,TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.merged_at') AS VARCHAR) as pr_merged_at,TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.closed_at') AS VARCHAR) as pr_closed_at,TRY_CAST(json_extract_string(to_json(payload), '$.comment.user.login') AS VARCHAR) as comment_user_login,created_atFROM read_json({file_patterns_sql},7 unmodified lines-- PushEvent: Commits by assistants(type = 'PushEvent'AND TRY_CAST(json_extract_string(to_json(payload), '$.head') AS VARCHAR) IS NOT NULLAND TRY_CAST(json_extract_string(to_json(actor), '$.login') AS VARCHAR) IN ({identifier_list}))OR-- PullRequestEvent: PRs authored by assistants (opened/closed)(type = 'PullRequestEvent'AND payload.pull_request.number IS NOT NULLAND TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.created_at') AS VARCHAR) IS NOT NULLAND TRY_CAST(json_extract_string(to_json(payload), '$.pull_request.user.login') AS VARCHAR) IN ({identifier_list})AND TRY_CAST(json_extract_string(to_json(payload), '$.action') AS VARCHAR) IN ('opened', 'closed'))OR-- PullRequestReviewEvent: Reviews by assistants(type = 'PullRequestReviewEvent'AND payload.pull_request.number IS NOT NULLAND TRY_CAST(json_extract_string(to_json(actor), '$.login') AS VARCHAR) IN ({identifier_list}))OR-- PullRequestReviewCommentEvent: Review comments by assistants(type = 'PullRequestReviewCommentEvent'AND payload.pull_request.number IS NOT NULLAND TRY_CAST(json_extract_string(to_json(payload), '$.comment.user.login') AS VARCHAR) IN ({identifier_list}))"""try:all_results = conn.execute(unified_query).fetchall()# Post-process results to separate commits, PRs, and reviews# Row: (type, actor_login, commit_sha, pr_url, action, pr_author,# pr_created_at, pr_merged_at, pr_closed_at, comment_user_login, created_at)commit_rows = []authored_pr_rows = []review_rows = []for row in all_results:event_type = row[0]if event_type == 'PushEvent':commit_rows.append(row)elif event_type in ('PullRequestReviewEvent', 'PullRequestReviewCommentEvent'):review_rows.append(row)elif event_type == 'PullRequestEvent':action = row[4]pr_author = row[5]if pr_author in identifiers_set and action in ('opened', 'closed'):authored_pr_rows.append(row)# --- Process commits ---batch_commits = 0for row in commit_rows:author = row[1]sha = row[2]created_at = normalize_date_format(row[10]) if row[10] else Noneif not author or not sha:continuecommits_by_agent[author].append({'sha': sha,'created_at': created_at,})batch_commits += 1total_commits += 1# --- Process authored PRs ---# Group events by PR URL to merge opened and closed eventspr_events = defaultdict(lambda: {'opened': None, 'closed': None})for row in authored_pr_rows:pr_url = row[3]action = row[4]pr_author = row[5]4 unmodified linesif not pr_url or not action:continuepr_events[pr_url][action] = {'pr_author': pr_author,'created_at': pr_created_at,'merged_at': pr_merged_at,'closed_at': pr_closed_at,}batch_prs = 0for url, events in pr_events.items():if not events['opened']:continueopened_event = events['opened']3 unmodified linesif not pr_author:continueprs_by_agent[pr_author].append({'html_url': url,'created_at': opened_event['created_at'],'merged_at': closed_event['merged_at'] if closed_event else None,'closed_at': closed_event['closed_at'] if closed_event else None,})batch_prs += 1total_prs += 1# --- Process reviews ---batch_reviews = 0for row in review_rows:event_type = row[0]if event_type == 'PullRequestReviewEvent':reviewer = row[1] # actor_loginelse: # PullRequestReviewCommentEventreviewer = row[9] # comment_user_loginpr_url = row[3]reviewed_at = normalize_date_format(row[10]) if row[10] else Noneif not reviewer or not pr_url or not reviewed_at:continuereviews_by_agent[reviewer].append({'url': pr_url,'reviewed_at': reviewed_at,})batch_reviews += 1total_reviews += 1print(f"✓ {batch_commits} commits, {batch_prs} PRs, {batch_reviews} reviews found")except Exception as e:print(f"\n ✗ Batch {batch_num} error: {str(e)}")5 unmodified lines# Final summaryagents_with_commits = sum(1 for commits in commits_by_agent.values() if commits)agents_with_prs = sum(1 for prs in prs_by_agent.values() if prs)agents_with_reviews = sum(1 for reviews in reviews_by_agent.values() if reviews)print(f"\n ✓ Complete: {total_commits} commits for {agents_with_commits}/{len(identifiers)} assistants")print(f" ✓ Complete: {total_prs} PRs for {agents_with_prs}/{len(identifiers)} assistants")print(f" ✓ Complete: {total_reviews} reviews for {agents_with_reviews}/{len(identifiers)} assistants")return {'commits': dict(commits_by_agent),'prs': dict(prs_by_agent),'reviews': dict(reviews_by_agent),}57 unmodified linesdef calculate_pr_stats_from_metadata(metadata_list):"""Calculate statistics from a list of PR metadata."""total_prs = len(metadata_list)merged = sum(1 for pr_meta in metadata_list if get_pr_status(pr_meta) == 'merged')closed_not_merged = sum(1 for pr_meta in metadata_list if get_pr_status(pr_meta) == 'closed')total_decisions = merged + closed_not_mergedacceptance_rate = (merged / total_decisions * 100) if total_decisions > 0 else 05 unmodified lines}def get_pr_status(meta):"""Derive PR status from merged_at and closed_at fields."""if meta.get('merged_at'):return 'merged'elif meta.get('closed_at'):return 'closed'else:return 'open'def calculate_review_stats_from_metadata(metadata_list):"""Calculate statistics from a list of review metadata."""return {'total_reviews': len(metadata_list),}def calculate_monthly_metrics_by_agent_commits(all_metadata_dict, assistants):"""Calculate monthly metrics for commits for all assistants for visualization."""identifier_to_name = {assistant.get('github_identifier'): assistant.get('name') for assistant in assistants if assistant.get('github_identifier')}89 unmodified linesfor month in months:prs_in_month = month_dict.get(month, [])merged_count = sum(1 for pr in prs_in_month if get_pr_status(pr) == 'merged')closed_not_merged_count = sum(1 for pr in prs_in_month if get_pr_status(pr) == 'closed')total_count = len(prs_in_month)total_decisions = merged_count + closed_not_merged_count20 unmodified lines}def calculate_monthly_metrics_by_agent_reviews(all_metadata_dict, assistants):"""Calculate monthly metrics for reviews for all assistants for visualization."""identifier_to_name = {assistant.get('github_identifier'): assistant.get('name') for assistant in assistants if assistant.get('github_identifier')}if not all_metadata_dict:return {'assistants': [], 'months': [], 'data': {}}agent_month_data = defaultdict(lambda: defaultdict(list))for agent_identifier, metadata_list in all_metadata_dict.items():for review_meta in metadata_list:reviewed_at = review_meta.get('reviewed_at')if not reviewed_at:continueagent_name = identifier_to_name.get(agent_identifier, agent_identifier)try:dt = datetime.fromisoformat(reviewed_at.replace('Z', '+00:00'))month_key = f"{dt.year}-{dt.month:02d}"agent_month_data[agent_name][month_key].append(review_meta)except Exception as e:print(f"Warning: Could not parse date '{reviewed_at}': {e}")continueall_months = set()for agent_data in agent_month_data.values():all_months.update(agent_data.keys())months = sorted(list(all_months))result_data = {}for agent_name, month_dict in agent_month_data.items():total_reviews_list = []for month in months:reviews_in_month = month_dict.get(month, [])total_reviews_list.append(len(reviews_in_month))result_data[agent_name] = {'total_reviews': total_reviews_list,}agents_list = sorted(list(agent_month_data.keys()))return {'assistants': agents_list,'months': months,'data': result_data}def construct_leaderboard_from_metadata(commit_metadata_dict, pr_metadata_dict, review_metadata_dict, assistants):"""Construct leaderboard from in-memory commit, PR, and review metadata.Args:commit_metadata_dict: Dictionary mapping assistant ID to list of commit metadatapr_metadata_dict: Dictionary mapping assistant ID to list of PR metadatareview_metadata_dict: Dictionary mapping assistant ID to list of review metadataassistants: List of assistant metadataReturns:Dictionary with leaderboard data including commit, PR, and review statistics"""if not assistants:print("Error: No assistants found")5 unmodified linesidentifier = assistant.get('github_identifier')agent_name = assistant.get('name', 'Unknown')commit_metadata = commit_metadata_dict.get(identifier, [])pr_metadata = pr_metadata_dict.get(identifier, [])review_data = review_metadata_dict.get(identifier, [])commit_stats = calculate_commit_stats_from_metadata(commit_metadata)pr_stats = calculate_pr_stats_from_metadata(pr_metadata)review_stats = calculate_review_stats_from_metadata(review_data)cache_dict[identifier] = {'name': agent_name,'website': assistant.get('website', 'N/A'),'github_identifier': identifier,**commit_stats,**pr_stats,**review_stats}return cache_dictdef save_leaderboard_data_to_hf(leaderboard_dict, commit_monthly_metrics, pr_monthly_metrics, review_monthly_metrics):"""Save leaderboard data and all monthly metrics to HuggingFace dataset."""try:token = get_hf_token()if not token:8 unmodified lines},'leaderboard': leaderboard_dict,'commit_monthly_metrics': commit_monthly_metrics,'pr_monthly_metrics': pr_monthly_metrics,'review_monthly_metrics': review_monthly_metrics}with open(LEADERBOARD_FILENAME, 'w') as f:24 unmodified linesdef mine_all_agents():"""Mine commit, PR, and review metadata for all assistants using STREAMING batch processing.Downloads GHArchive data, then uses BATCH-based DuckDB queries."""print(f"\n[1/4] Downloading GHArchive data...")12 unmodified linesprint("Error: No valid assistant identifiers found")returncurrent_time = datetime.now(timezone.utc)end_date = current_time.replace(hour=0, minute=0, second=0, microsecond=0)start_date = end_date - timedelta(days=LEADERBOARD_TIME_FRAME_DAYS)try:conn = get_duckdb_connection()1 unmodified lineprint(f"Failed to initialize DuckDB connection: {str(e)}")returnprint(f"\n[3/4] Mining commit, PR, and review metadata ({len(identifiers)} assistants, {LEADERBOARD_TIME_FRAME_DAYS} days)...")try:results = fetch_all_metadata_streaming(conn, identifiers, start_date, end_date)commit_metadata = results['commits']pr_metadata = results['prs']review_metadata = results['reviews']except Exception as e:print(f"Error during metadata fetch: {str(e)}")traceback.print_exc()returnfinally:2 unmodified linesprint(f"\n[4/4] Saving leaderboard...")try:leaderboard_dict = construct_leaderboard_from_metadata(commit_metadata, pr_metadata, review_metadata, assistants)commit_monthly_metrics = calculate_monthly_metrics_by_agent_commits(commit_metadata, assistants)pr_monthly_metrics = calculate_monthly_metrics_by_agent_prs(pr_metadata, assistants)review_monthly_metrics = calculate_monthly_metrics_by_agent_reviews(review_metadata, assistants)save_leaderboard_data_to_hf(leaderboard_dict, commit_monthly_metrics, pr_monthly_metrics, review_monthly_metrics)except Exception as e:print(f"Error saving leaderboard: {str(e)}")traceback.print_exc()finally:if os.path.exists(DUCKDB_CACHE_FILE):try:os.remove(DUCKDB_CACHE_FILE)
.gitignore+5-3
app.py+95-95
msr.py+182-88