diff --git a/get_rankings.py b/get_rankings.py index 46a419d..da43824 100644 --- a/get_rankings.py +++ b/get_rankings.py @@ -1,9 +1,13 @@ from pathlib import Path +from typing import Optional import tbaapiv3client from tbaapiv3client.rest import ApiException from pprint import pprint from datetime import datetime as dt +from openpyxl import Workbook, worksheet, load_workbook +from openpyxl.worksheet.table import Table, TableStyleInfo + from csv import DictWriter # Setup Config @@ -44,7 +48,6 @@ def get_rankings(api_client: tbaapiv3client.ApiClient, seasons: list[str]) -> li points_event1 = event.total points_event1_na = event.qual_points + event.elim_points + event.alliance_points - if len(result.event_points) > 1: event = result.event_points[1] points_event1 = event.total @@ -61,7 +64,8 @@ def get_rankings(api_client: tbaapiv3client.ApiClient, seasons: list[str]) -> li return rankings -def get_event_teams(api_client: tbaapiv3client.ApiClient, season:str) -> dict[dict]: + +def get_event_teams(api_client: tbaapiv3client.ApiClient, season: str) -> dict[dict]: api_district = tbaapiv3client.DistrictApi(api_client) api_event = tbaapiv3client.EventApi(api_client) @@ -82,7 +86,8 @@ def get_event_teams(api_client: tbaapiv3client.ApiClient, season:str) -> dict[di team_results = api_event.get_event_teams_keys(key) except ApiException as e: - print("Exception when calling EventApi->get_event_teams_keys: %s\n" % e) + print( + "Exception when calling EventApi->get_event_teams_keys: %s\n" % e) else: event_teams[key] = { 'key': key, @@ -94,13 +99,14 @@ def get_event_teams(api_client: tbaapiv3client.ApiClient, season:str) -> dict[di return event_teams -def write_power_rank(path: str | Path, rankings: list[dict], seasons:list[str]) -> None: + +def write_power_rank(path: str | Path, rankings: list[dict], seasons: list[str]) -> None: # Create annual rank CSV - results_list:list[dict] = [] + results_list: list[dict] = [] for team, ranks in rankings.items(): result = { - 'team': team + 'team': team } rank_sum = 0 @@ -148,7 +154,6 @@ def write_power_rank(path: str | Path, rankings: list[dict], seasons:list[str]) result[f'{season} Points District'] = point_district result[f'{season} Points District No Awards'] = point_district_na - rank_avg = '' point_total_avg = '' point_district_avg = '' @@ -165,18 +170,18 @@ def write_power_rank(path: str | Path, rankings: list[dict], seasons:list[str]) result[f'Avg Points District'] = point_district_avg result[f'Avg Points District No Awards'] = point_district_na_avg - results_list.append(result) - write_result(path, results_list) + write_result(path, results_list,"Power Ranking") -def write_rank(path: str | Path, rankings: list[dict], seasons:list[str]) -> None: + +def write_rank(path: str | Path, rankings: list[dict], seasons: list[str]) -> None: # Create annual rank CSV - results_list:list[dict] = [] + results_list: list[dict] = [] for team, ranks in rankings.items(): result = { - 'team': team + 'team': team } for season in seasons: @@ -190,13 +195,14 @@ def write_rank(path: str | Path, rankings: list[dict], seasons:list[str]) -> Non write_result(path, results_list) -def write_point_total(path: str | Path, rankings: list[dict], seasons:list[str]) -> None: + +def write_point_total(path: str | Path, rankings: list[dict], seasons: list[str]) -> None: # Create annual rank CSV - results_list:list[dict] = [] + results_list: list[dict] = [] for team, ranks in rankings.items(): result = { - 'team': team + 'team': team } for season in seasons: @@ -210,13 +216,14 @@ def write_point_total(path: str | Path, rankings: list[dict], seasons:list[str]) write_result(path, results_list) -def write_points_events(path: str | Path, rankings: list[dict], seasons:list[str]) -> None: + +def write_points_events(path: str | Path, rankings: list[dict], seasons: list[str]) -> None: # Create annual rank CSV - results_list:list[dict] = [] + results_list: list[dict] = [] for team, ranks in rankings.items(): result = { - 'team': team + 'team': team } for season in seasons: @@ -226,7 +233,7 @@ def write_points_events(path: str | Path, rankings: list[dict], seasons:list[str if ranks[season]['points_event1'] is not None: value += ranks[season]['points_event1'] - + if ranks[season]['points_event2'] is not None: value += ranks[season]['points_event2'] @@ -236,26 +243,59 @@ def write_points_events(path: str | Path, rankings: list[dict], seasons:list[str write_result(path, results_list) -def write_result(path: str| Path, results_list:list[dict]) -> None: + +def write_result(path: str | Path, results_list: list[dict], sheet_name:Optional[str] = None, sheet_index:Optional[int]=None, headers:Optional[list[str]]=None) -> None: + # Convert path to Path type if it isn't already if not isinstance(path, Path): path = Path(path) - with open(path, 'w', newline='') as f: - writer = DictWriter(f, results_list[0].keys()) + # Get headers + if headers is None: + headers = list(results_list[0].keys()) - writer.writeheader() - writer.writerows(results_list) + # Open workbook + wb:Workbook = None + ws = None + if path.exists(): + wb = load_workbook(path) + ws = wb.create_sheet(sheet_name,sheet_index) + else: + wb = Workbook() + ws = wb.active + + if sheet_name is not None: + ws.title = sheet_name + # Write Header + ws.append(headers) + + # Write Results + + for row in results_list: + values = [] + + for header in headers: + if header in row: + values.append(row[header]) + else: + values.append(None) + + ws.append(values) + + # Enable Filter + ws.auto_filter.ref = ws.dimensions + + # Save Workbook + wb.save(path) def main(): - + run_time = dt.now() run_time_str = run_time.strftime('%Y%m%d_%H%M') seasons = ['2022fim', '2023fim', '2024fim'] root_dir = Path('results') - with tbaapiv3client.ApiClient(config) as api_client: rankings = get_rankings(api_client, seasons) event_teams = get_event_teams(api_client, '2025fim') @@ -287,17 +327,17 @@ def main(): if season in rankings[team]: team_season = rankings[team][season] - rank = team_season['rank'] - point_total = team_season['point_total'] + rank = team_season['rank'] + point_total = team_season['point_total'] point_district = 0 point_district_na = 0 - + if team_season['points_event1'] is not None: point_district += team_season['points_event1'] if team_season['points_event2'] is not None: point_district += team_season['points_event2'] - + if team_season['points_event1_na'] is not None: point_district_na += team_season['points_event1_na'] @@ -322,23 +362,17 @@ def main(): team_details[f'{season} point district no awards'] = '' event_details.append(team_details) - - - if len(event_details): - # Write Event Details - with open(root_dir / f'{run_time_str} - {key} details.csv', 'w', newline='') as f: - writer = DictWriter(f, event_details[0]) - writer.writeheader() - writer.writerows(event_details) - + if len(event_details): + write_result(root_dir / f'{run_time_str} - Event Details.xlsx', event_details, key) + # Generate Event Summary rank_avg = '' point_total_avg = '' point_district_avg = '' point_district_na_avg = '' - if entry_count > 0: + if entry_count > 0: rank_avg = rank_sum / entry_count point_total_avg = point_total_sum / entry_count point_district_avg = point_district_sum / entry_count @@ -357,15 +391,12 @@ def main(): 'team count': len(event['teams']) }) - # Write Event Summary - with open(root_dir / f'{run_time_str} - event summary.csv', 'w', newline='') as f: - writer = DictWriter(f, event_summary[0].keys()) + write_result(root_dir / f'{run_time_str} - Event Details.xlsx', event_summary, "Summary", 0) - writer.writeheader() - writer.writerows(event_summary) - - write_power_rank(root_dir / f"{run_time_str} - season_power_rank.csv", rankings, seasons) + # Write Power Rankings + write_power_rank( + root_dir / f"Power Ranking.xlsx", rankings, seasons) if __name__ == '__main__':