plots.py 7.5 KB

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