utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import requests
  2. import yaml
  3. import pandas as pd
  4. import logging
  5. logger = logging.getLogger(__name__)
  6. logger.addHandler(logging.StreamHandler())
  7. CFG = yaml.safe_load(open("config.yaml", "r"))
  8. def fetch_github_endpoint(url):
  9. headers = {
  10. "Authorization": f"Bearer {CFG['github_token']}",
  11. "Content-Type": "application/json"
  12. }
  13. logger.debug(f"Requesting url: {url}")
  14. response = requests.get(url, headers=headers, timeout=10)
  15. return response
  16. def fetch_repo_issues(repo, start_date=None, end_date=None):
  17. time_filter = ""
  18. if start_date and not end_date:
  19. time_filter = f"+created:>{start_date}"
  20. if end_date and not start_date:
  21. time_filter = f"+created:<{end_date}"
  22. if start_date and end_date:
  23. time_filter = f"+created:{start_date}..{end_date}"
  24. url = f"https://api.github.com/search/issues?per_page=100&sort=created&order=asc&q=repo:{repo}+is:issue{time_filter}"
  25. samples = []
  26. while True:
  27. response = fetch_github_endpoint(url)
  28. if response.status_code == 200:
  29. issues = response.json()['items']
  30. for issue in issues:
  31. if issue['body'] is None:
  32. continue
  33. issue['discussion'] = issue['title'] + "\n" + issue['body']
  34. if issue['comments'] > 0:
  35. comments_response = fetch_github_endpoint(issue['comments_url']).json()
  36. comments = "\n> ".join([x['body'] for x in comments_response])
  37. issue['discussion'] += "\n> " + comments
  38. samples.append(issue)
  39. # Check if there are more pages
  40. if "Link" in response.headers:
  41. link_header = [h.split(';') for h in response.headers["Link"].split(', ')]
  42. link_header = [x for x in link_header if "next" in x[1]]
  43. if link_header:
  44. url = link_header[0][0].strip().replace('<', '').replace('>','')
  45. else:
  46. break
  47. else:
  48. break
  49. else:
  50. raise Exception(f"Fetching issues failed with Error: {response.status_code} on url {url}")
  51. rows = [{
  52. "repo_name": repo,
  53. "number": d['number'],
  54. "html_url": d['html_url'],
  55. "closed": (d['state'] == 'closed'),
  56. "num_comments": d['comments'],
  57. "created_at": d["created_at"],
  58. "discussion": d['discussion'],
  59. } for d in samples]
  60. logger.info(f"Fetched {len(samples)} issues on {repo} from {start_date} to {end_date}")
  61. return pd.DataFrame(rows)
  62. def fetch_repo_stats(repo):
  63. repo_info = fetch_github_endpoint(f"https://api.github.com/repos/{repo}").json()
  64. repo_stats = {
  65. "Total Open Issues": repo_info['open_issues_count'],
  66. "Total Stars": repo_info['stargazers_count'],
  67. "Total Forks": repo_info['forks_count'],
  68. }
  69. return repo_stats
  70. def validate_df_values(df, out_folder=None, name=None):
  71. df.columns = df.columns.str.lower().str.replace(" ", "_").str.replace("-", "_")
  72. if out_folder is not None:
  73. path = f"{out_folder}/{name}.csv"
  74. df.to_csv(path, index=False)
  75. logger.info(f"Data saved to {path}")
  76. return df