import requests import time import csv import os from datetime import datetime, timedelta import sys from github_tokens import init_rest_client_auth tokens: list[str] = [] authorization_headers: list[dict[str, str]] = [] token_index = 0 def _ensure_auth() -> None: global tokens, authorization_headers if not tokens: tokens, authorization_headers = init_rest_client_auth() def makeRequest(api_url, params): global token_index _ensure_auth() num_tries = 0 max_tries = 3 headers = authorization_headers[token_index] while True: num_tries += 1 if num_tries > max_tries: print(' Max retries reached. Exiting...') break while True: try: response = requests.get(api_url, headers=headers, params=params, timeout=30) break except requests.exceptions.RequestException as e: print(f'Request error: {e}. Retrying in 60 seconds...') time.sleep(60) except Exception as e: print(f'Another request error: {e}. Retrying in 60 seconds...') time.sleep(60) if response.status_code == 200: return response.json() elif response.status_code == 403 and ('message' in response.json() and 'rate limit' in response.json()['message'].lower()): token_index += 1 if token_index < len(authorization_headers): print(f"Rate limit exceeded for GitHub token index[{token_index-1}]. Proceeding with index[{token_index}].") headers = authorization_headers[token_index] else: reset_timestamp = int(response.headers.get('X-RateLimit-Reset', time.time() + 60)) current_timestamp = int(time.time()) wait_time = reset_timestamp - current_timestamp print(f' Rate limit exceeded. Waiting for {wait_time} seconds...') time.sleep(wait_time + 1) token_index = 0 elif response.status_code == 422: return {'total_count': 0} else: print(f' Request failed with status code {response.status_code}. Retrying... ' + api_url) time.sleep(1) def extract_fields(data): # Fields to extract fields = [ 'id', 'full_name', 'language', 'size', 'has_issues', 'open_issues_count', 'has_projects', 'created_at', 'updated_at', 'pushed_at', 'watchers_count', 'archived', 'disabled', 'allow_forking', 'forks_count', 'is_template', 'visibility', 'default_branch', 'stargazers_count', 'owner_type', 'license_key', 'topics', 'description' ] flattened_fields = { 'owner': {'type': 'owner_type'}, 'license': {'key': 'license_key'} } extracted = {field: data.get(field, '').strip() if isinstance(data.get(field, ''), str) else data.get(field, '') for field in fields if field and field not in ['owner_type', 'license_key']} # Flatten nested fields for key, subfields in flattened_fields.items(): if data.get(key) is not None: for subfield, flat_name in subfields.items(): extracted[flat_name] = data[key].get(subfield, '') # Handle list fields like 'topics' as comma-separated strings if isinstance(extracted.get('topics'), list): extracted['topics'] = ', '.join(extracted['topics']) row = [extracted.get(field, '') for field in fields] return row def search_repositories_by_topic_with_date_range(query, start_date, end_date, interval_days, csv_file, csv_writer, previous_repos): GITHUB_API_URL = 'https://api.github.com/search/repositories' page = 1 current_repos = set() while True: params = { 'q': f'{query} created:{start_date}..{end_date}', 'per_page': 100, 'page': page, } data = makeRequest(GITHUB_API_URL, params) if not data: break total_count = data.get('total_count', 0) if total_count == 0 and page == 1: print(f'Total count {total_count}. No collection for this interval.') return total_count if total_count <= 1000 and page == 1: print(f'Total count {total_count}. Now collecting pages:') if total_count > 1000 and page == 1: print(f'Total count {total_count} (>1000) for interval {interval_days}') return total_count print(f' Page {page} for query: {query} from {start_date} to {end_date}') items = data.get('items', []) for item in items: repo_name = item.get('full_name') if repo_name not in previous_repos: current_repos.add(repo_name) data_row = extract_fields(item) csv_writer.writerow(data_row) csv_file.flush() if len(items) < 100: break page += 1 previous_repos.clear() previous_repos.update(current_repos) return total_count def get_hourly_intervals(total_count): num_intervals = -(-total_count // 500) minutes_per_interval, extra = divmod(24 * 60, num_intervals) return [minutes_per_interval + (i < extra) for i in range(num_intervals)] def split_search_by_datetime(query, start_date, end_date, interval_days, csv_file, csv_writer): previous_repos = set() start = datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%S') end = datetime.strptime(end_date, '%Y-%m-%dT%H:%M:%S') original_interval = interval_days while start < end: next_end = min(start + (timedelta(days=interval_days) - timedelta(seconds=1)), end) print(f'Checking repositories from {start.strftime("%Y-%m-%dT%H:%M:%S")} to {next_end.strftime("%Y-%m-%dT%H:%M:%S")}') total_count = search_repositories_by_topic_with_date_range( query, start.strftime('%Y-%m-%dT%H:%M:%S'), next_end.strftime('%Y-%m-%dT%H:%M:%S'), interval_days, csv_file, csv_writer, previous_repos ) if total_count and total_count > 1000: # If total_count exceeds 1000, reduce interval reduced_interval = interval_days while total_count > 1000: reduced_interval = max(reduced_interval // 2, 1) print(f'Reducing interval to {reduced_interval} day{'s' if reduced_interval > 1 else ''} for query: {query}') next_end = min(start + (timedelta(days=reduced_interval) - timedelta(seconds=1)), end) print(f'Checking repositories from {start.strftime("%Y-%m-%dT%H:%M:%S")} to {next_end.strftime("%Y-%m-%dT%H:%M:%S")}') total_count = search_repositories_by_topic_with_date_range( query, start.strftime('%Y-%m-%dT%H:%M:%S'), next_end.strftime('%Y-%m-%dT%H:%M:%S'), interval_days, csv_file, csv_writer, previous_repos ) if reduced_interval == 1: if total_count > 1000: # Split the day into multiple sub-intervals (every hour) sub_intervals = get_hourly_intervals(total_count) hour_start = start for sub_interval in sub_intervals: hour_end = hour_start + (timedelta(minutes=sub_interval) - timedelta(seconds=1)) print(f'Checking repositories every {sub_interval/60} hours: from {hour_start.strftime("%Y-%m-%dT%H:%M:%S")} to {hour_end.strftime("%Y-%m-%dT%H:%M:%S")}') total_count = search_repositories_by_topic_with_date_range( query, hour_start.strftime('%Y-%m-%dT%H:%M:%S'), hour_end.strftime('%Y-%m-%dT%H:%M:%S'), interval_days, csv_file, csv_writer, previous_repos ) hour_start = hour_end + timedelta(seconds=1) # Restore the original interval for the next iteration interval_days = original_interval start = next_end + timedelta(seconds=1) def collect_repos_for_all_topics(data_path, search_criteria, start_year, end_year, interval_days): for criterion, criterion_values in search_criteria.items(): for criterion_value in criterion_values: query = f'{criterion}:{criterion_value} stars:>=5 fork:false archived:false' output_file_name = f'{data_path}/{criterion}_{criterion_value}_{csv_file_suffix}' csv_output_file_path = output_file_name + '.csv' first_time_csv = not os.path.exists(csv_output_file_path) csv_file = open(csv_output_file_path, 'a', newline='', encoding='utf-8') csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) if first_time_csv: csv_writer.writerow(['id', 'full_name', 'language', 'size', 'has_issues', 'open_issues_count', 'has_projects', 'created_at', 'updated_at', 'pushed_at', 'watchers_count', 'archived', 'disabled', 'allow_forking', 'forks_count', 'is_template', 'visibility', 'default_branch', 'stargazers_count', 'owner_type', 'license_key', 'topics', 'description']) print(f'Starting search for {criterion} "{criterion_value}" from {start_year} to {end_year - 1}.') for year in range(start_year, end_year): year_start_date = f'{year}-01-01T00:00:00' year_end_date = f'{year}-04-30T23:59:59' if year == 2026 else f'{year}-12-31T23:59:59' split_search_by_datetime( query, year_start_date, year_end_date, interval_days=interval_days, csv_file=csv_file, csv_writer=csv_writer ) csv_file.close() print(f'Finished search for {criterion} "{criterion_value}". Results saved to {csv_output_file_path}.') def combine_csv_files(input_folder, output_file, deduplicate_by='full_name'): """ Combine all CSV files in a folder into one CSV file. Args: input_folder (str): Folder containing CSV files output_file (str): Output combined CSV file deduplicate_by (str): Column used for deduplication """ combined_rows = [] seen = set() header = None csv_files = [f for f in os.listdir(input_folder) if f.endswith('.csv')] print(f'\nFound {len(csv_files)} CSV files to combine.') for file_name in csv_files: file_path = os.path.join(input_folder, file_name) print(f'Reading: {file_name}') with open(file_path, 'r', encoding='utf-8') as csv_file: reader = csv.DictReader(csv_file) # Save header once if header is None: header = reader.fieldnames for row in reader: unique_value = row.get(deduplicate_by) if unique_value not in seen: seen.add(unique_value) combined_rows.append(row) # Write combined file with open(output_file, 'w', newline='', encoding='utf-8') as out_file: writer = csv.DictWriter(out_file, fieldnames=header) writer.writeheader() writer.writerows(combined_rows) print(f'\nCombined CSV saved to: {output_file}') print(f'Total unique repositories: {len(combined_rows)}') if __name__ == '__main__': # Define your search criteria here search_criteria = { 'topic': ['etl', 'etl-pipeline', 'etl-framework', 'elt', 'data-engineering', 'data-engineering-pipeline', 'data-integration', 'airflow', 'data-pipeline', 'data-pipelines', 'data-orchestrator', 'workflow-orchestration'], # Add more topics as needed } data_path = '../Data' if not os.path.exists(data_path): os.mkdir(data_path) start_year = 2008 end_year = 2026 interval_days = 128 # Starting with 128 days, adjust if needed csv_file_suffix = '2008-01-01_2026-04-30' # Start the collection for all topics collect_repos_for_all_topics(data_path, search_criteria, start_year, end_year, interval_days) # Combine all generated CSV files combine_csv_files(data_path, f'{data_path}/all_DE_repositories.csv', deduplicate_by='full_name')