plots.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import matplotlib.pyplot as plt
  2. import pandas as pd
  3. import plotly.graph_objects as go
  4. from utils import fetch_github_endpoint
  5. def plot_views_clones(repo_name, out_folder):
  6. def json_to_df(json_data, key):
  7. df = pd.DataFrame(json_data[key])
  8. df['timestamp'] = df['timestamp'].apply(lambda x: x[5:10])
  9. if key in ['clones', 'views']:
  10. df.rename(columns={'uniques': key}, inplace=True)
  11. df.drop(columns=['count'], inplace=True)
  12. return df
  13. unique_clones_2w = fetch_github_endpoint(f"https://api.github.com/repos/{repo_name}/traffic/clones").json()
  14. unique_views_2w = fetch_github_endpoint(f"https://api.github.com/repos/{repo_name}/traffic/views").json()
  15. df1 = json_to_df(unique_clones_2w, 'clones')
  16. df2 = json_to_df(unique_views_2w, 'views')
  17. df = df1.merge(df2, on='timestamp', how='inner')
  18. fig, ax1 = plt.subplots(figsize=(10, 6))
  19. ax1.plot(df['timestamp'], df['views'], color='blue')
  20. ax1.set_xlabel('Day', fontsize=18)
  21. ax1.set_ylabel('Unique Views', color='blue', fontsize=18)
  22. ax1.tick_params(axis='y', labelcolor='blue')
  23. ax2 = ax1.twinx()
  24. ax2.bar(df['timestamp'], df['clones'], color='red')
  25. ax2.set_ylabel('Unique Clones', color='red', fontsize=18)
  26. ax2.tick_params(axis='y', labelcolor='red')
  27. plt.title('Views & Clones in the last 2 weeks', fontsize=24)
  28. plt.savefig(f'{out_folder}/views_clones.png', dpi=120)
  29. plt.close()
  30. def plot_high_traffic_resources(repo_name, out_folder):
  31. popular_paths_2w = fetch_github_endpoint(f"https://api.github.com/repos/{repo_name}/traffic/popular/paths").json()
  32. df = pd.DataFrame(popular_paths_2w)
  33. df['path'] = df['path'].apply(lambda x: '/'.join(x.split('/')[-2:]))
  34. df = df.sort_values(by='uniques', ascending=False).head(10)
  35. plt.figure(figsize=(10, 6))
  36. plt.barh(df['path'], df['uniques'])
  37. plt.xlabel('Unique traffic in the last 2 weeks', fontsize=18)
  38. # plt.ylabel('Resource', fontsize=18, labelpad=15)
  39. plt.title("Popular Resources on the Repository", fontsize=24)
  40. plt.tight_layout()
  41. plt.savefig(f'{out_folder}/resources.png', dpi=120)
  42. plt.close()
  43. def plot_high_traffic_referrers(repo_name, out_folder):
  44. popular_referrer_2w = fetch_github_endpoint(f"https://api.github.com/repos/{repo_name}/traffic/popular/referrers").json()
  45. df = pd.DataFrame(popular_referrer_2w)
  46. df = df.sort_values(by='uniques', ascending=False)
  47. plt.figure(figsize=(10, 6))
  48. plt.barh(df['referrer'], df['uniques'])
  49. plt.xlabel('Unique traffic in the last 2 weeks', fontsize=18)
  50. plt.ylabel('Referrer', fontsize=18)
  51. plt.title("Popular Referrers to the Repository", fontsize=24)
  52. plt.savefig(f'{out_folder}/referrers.png', dpi=120)
  53. plt.close()
  54. def plot_commit_activity(repo_name, out_folder):
  55. limit = 10
  56. today = pd.to_datetime('today')
  57. weekly_commit_count_52w = fetch_github_endpoint(f"https://api.github.com/repos/{repo_name}/stats/participation").json()['all'][-limit:]
  58. timestamps = [(today - pd.Timedelta(days=7*(i+1))) for i in range(limit)]
  59. df = pd.DataFrame({'timestamp': timestamps, 'commit_count': weekly_commit_count_52w})
  60. plt.figure(figsize=(10, 6))
  61. plt.bar(df['timestamp'], df['commit_count'])
  62. plt.xlabel('Week', fontsize=18)
  63. plt.ylabel('Commit Count', fontsize=18)
  64. plt.title(f"Commits in the last {limit} weeks", fontsize=24)
  65. plt.savefig(f'{out_folder}/commits.png', dpi=120)
  66. plt.close()
  67. def plot_user_expertise(df, out_folder):
  68. d = df.to_dict('records')[0]
  69. levels = ['Beginner', 'Intermediate', 'Advanced']
  70. keys = [f"op_expertise_count_{x.lower()}" for x in levels]
  71. data = pd.DataFrame({'Expertise': levels, 'Count': [d.get(k, 0) for k in keys]})
  72. plt.figure(figsize=(10, 6))
  73. plt.barh(data['Expertise'], data['Count'])
  74. plt.xlabel('Count', fontsize=18)
  75. plt.title('User Expertise', fontsize=24)
  76. plt.savefig(f'{out_folder}/expertise.png', dpi=120)
  77. plt.close()
  78. def plot_severity(df, out_folder):
  79. d = df.to_dict('records')[0]
  80. levels = ['Trivial', 'Minor', "Major", 'Critical']
  81. keys = [f"severity_count_{x.lower()}" for x in levels]
  82. data = pd.DataFrame({'Severity': levels, 'Count': [d.get(k, 0) for k in keys]})
  83. plt.figure(figsize=(10, 6))
  84. plt.barh(data['Severity'], data['Count'])
  85. plt.xlabel('Count', fontsize=18)
  86. plt.title('Severity', fontsize=24)
  87. plt.savefig(f'{out_folder}/severity.png', dpi=120)
  88. plt.close()
  89. def plot_sentiment(df, out_folder):
  90. d = df.to_dict('records')[0]
  91. levels = ['Positive', 'Neutral', 'Negative']
  92. keys = [f"sentiment_count_{x.lower()}" for x in levels]
  93. data = pd.DataFrame({'Sentiment': levels, 'Count': [d.get(k, 0) for k in keys]})
  94. plt.figure(figsize=(10, 6))
  95. plt.barh(data['Sentiment'], data['Count'])
  96. plt.xlabel('Count', fontsize=18)
  97. plt.title('Sentiment', fontsize=24)
  98. plt.savefig(f'{out_folder}/sentiment.png', dpi=120)
  99. plt.close()
  100. def plot_themes(df, out_folder):
  101. d = df.to_dict('records')[0]
  102. levels = ['Documentation', 'Installation and Environment', 'Model Inference', 'Model Fine Tuning and Training', 'Model Evaluation and Benchmarking', 'Model Conversion', 'Cloud Compute', 'CUDA Compatibility', 'Distributed Training and Multi-GPU', 'Invalid', 'Miscellaneous']
  103. keys = [f'themes_count_{x.lower().replace(" ", "_").replace("-", "_")}' for x in levels]
  104. data = pd.DataFrame({'Theme': levels, 'Count': [d.get(k, 0) for k in keys]})
  105. plt.figure(figsize=(10, 6))
  106. plt.barh(data['Theme'], data['Count'])
  107. plt.xlabel('Count', fontsize=18)
  108. # plt.ylabel('Theme', fontsize=18)
  109. plt.title('Themes', fontsize=24)
  110. plt.tight_layout()
  111. plt.savefig(f'{out_folder}/themes.png', dpi=120)
  112. plt.close()
  113. def issue_activity_sankey(df, out_folder):
  114. d = df.to_dict('records')[0]
  115. label = ["New Issues", "Issues Under Discussion", "Issues Discussed and Closed", "Issues Not Responded to", "Issues Closed Without Discussion"]
  116. values = [
  117. d['issues_created'],
  118. d['open_discussion'] + d['closed_discussion'], # 7
  119. d['closed_discussion'], # 3
  120. d['open_no_discussion'] + d['closed_no_discussion'],
  121. d['closed_no_discussion']
  122. ]
  123. fig = go.Figure(data=[go.Sankey(
  124. node = dict(
  125. pad = 15,
  126. thickness = 20,
  127. line = dict(color = "black", width = 0.5),
  128. label = [f"{l} ({values[i]})" for i, l in enumerate(label)],
  129. color = ["#007bff", "#17a2b8", "#6610f2", "#dc3545", "#6c757d"] # color scheme to highlight different flows
  130. ),
  131. link = dict(
  132. source = [0, 1, 0, 3], # indices correspond to labels, eg A1, A2, etc
  133. target = [1, 2, 3, 4],
  134. value = [v if v > 0 else 1e-9 for v in values[1:]]
  135. ))])
  136. fig.update_layout(title_text="Issue Flow", font_size=16)
  137. fig.update_layout(margin=dict(l=20, r=20, t=60, b=20)) # adjust margins to make text more visible
  138. fig.write_image(f"{out_folder}/engagement_sankey.png")
  139. def draw_all_plots(repo_name, out_folder, overview):
  140. func1 = [plot_views_clones, plot_high_traffic_resources, plot_high_traffic_referrers, plot_commit_activity]
  141. func2 = [plot_user_expertise, plot_severity, plot_sentiment, plot_themes, issue_activity_sankey]
  142. for func in func1:
  143. try:
  144. func(repo_name, out_folder)
  145. except:
  146. print(f"Github fetch failed for {func}. Make sure you have push-access to {repo_name}!")
  147. for func in func2:
  148. func(overview, out_folder)