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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Tuple
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import seaborn as sns
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from wordcloud import WordCloud
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
def _rename_columns(df: pd.DataFrame, is_tournament: bool) -> pd.DataFrame:
|
| 12 |
+
columns = {
|
| 13 |
+
"Rating": "rating",
|
| 14 |
+
"Result": "result",
|
| 15 |
+
"Scores": "scores",
|
| 16 |
+
"Opponent": "opponent",
|
| 17 |
+
"OpponentRating": "opponent_rating",
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
if is_tournament:
|
| 21 |
+
columns.update({
|
| 22 |
+
"TournamentStartDate": "tournament_start_date",
|
| 23 |
+
"TournamentEndDate": "tournament_end_date",
|
| 24 |
+
" Touranament": "tournament",
|
| 25 |
+
})
|
| 26 |
+
else:
|
| 27 |
+
columns.update({
|
| 28 |
+
"EventDate": "event_date",
|
| 29 |
+
"LeagueName": "league_name"
|
| 30 |
+
})
|
| 31 |
+
|
| 32 |
+
return df.rename(columns=columns)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _fix_dtypes(df: pd.DataFrame, is_tournament: bool) -> pd.DataFrame:
|
| 36 |
+
if is_tournament:
|
| 37 |
+
df["tournament_start_date"] = pd.to_datetime(df["tournament_start_date"])
|
| 38 |
+
df["tournament_end_date"] = pd.to_datetime(df["tournament_end_date"])
|
| 39 |
+
df["tournament"] = df["tournament"].astype('category')
|
| 40 |
+
else:
|
| 41 |
+
df["event_date"] = pd.to_datetime(df["event_date"])
|
| 42 |
+
df["league_name"] = df["league_name"].astype('string')
|
| 43 |
+
|
| 44 |
+
df["rating"] = df["rating"].astype('int')
|
| 45 |
+
df["result"] = df["result"].astype('category')
|
| 46 |
+
df["scores"] = df["scores"].astype('string')
|
| 47 |
+
df["opponent"] = df["opponent"].astype('category')
|
| 48 |
+
df["opponent_rating"] = df["opponent_rating"].astype('int')
|
| 49 |
+
|
| 50 |
+
return df
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _check_match_type(match_type: str) -> str:
|
| 54 |
+
allowed_match_types = {"tournament", "league"}
|
| 55 |
+
if match_type not in allowed_match_types:
|
| 56 |
+
raise ValueError(
|
| 57 |
+
f"The only supported match types are {allowed_match_types}. Found match type of '{match_type}'.")
|
| 58 |
+
return match_type
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_num_competitions_played(df: pd.DataFrame, is_tournament: bool) -> int:
|
| 62 |
+
key_name = "tournament" if is_tournament else "event_date"
|
| 63 |
+
return df[key_name].nunique()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_matches_per_competition_fig(df: pd.DataFrame, is_tournament: bool):
|
| 67 |
+
fig = plt.figure()
|
| 68 |
+
plt.title('Matches per competition')
|
| 69 |
+
sns.histplot(df.groupby('tournament' if is_tournament else "event_date").size())
|
| 70 |
+
plt.xlabel('Number of matches in competition')
|
| 71 |
+
return fig
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_competition_name_word_cloud_fig(df: pd.DataFrame, is_tournament: bool):
|
| 75 |
+
fig = plt.figure()
|
| 76 |
+
key_name = "tournament" if is_tournament else "league_name"
|
| 77 |
+
wordcloud = WordCloud().generate(" ".join(df[key_name].values.tolist()))
|
| 78 |
+
plt.imshow(wordcloud, interpolation='bilinear')
|
| 79 |
+
plt.axis("off")
|
| 80 |
+
return fig
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_opponent_name_word_cloud_fig(df: pd.DataFrame):
|
| 84 |
+
fig = plt.figure()
|
| 85 |
+
wordcloud = WordCloud().generate(" ".join(df.opponent.values.tolist()))
|
| 86 |
+
plt.imshow(wordcloud, interpolation='bilinear')
|
| 87 |
+
plt.axis("off")
|
| 88 |
+
return fig
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_rating_over_time_fig(df: pd.DataFrame, is_tournament: bool):
|
| 92 |
+
fig = plt.figure()
|
| 93 |
+
plt.title('Rating over time')
|
| 94 |
+
sns.lineplot(data=df,
|
| 95 |
+
x="tournament_end_date" if is_tournament else "event_date",
|
| 96 |
+
y="rating",
|
| 97 |
+
marker='.',
|
| 98 |
+
markersize=10)
|
| 99 |
+
plt.xlabel('Competition date')
|
| 100 |
+
plt.ylabel('Rating')
|
| 101 |
+
return fig
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_max_int(int_csv_str: str) -> int:
|
| 105 |
+
"""Get the max int from an int CSV."""
|
| 106 |
+
ints = [int(i.strip()) for i in int_csv_str.split(',')]
|
| 107 |
+
return max(ints)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_match_with_longest_game(df: pd.DataFrame, is_tournament: bool) -> Optional[pd.DataFrame]:
|
| 111 |
+
if not is_tournament:
|
| 112 |
+
return None
|
| 113 |
+
return df.loc[[np.argmax(df.scores.apply(get_max_int))]]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_opponent_rating_distr_fig(df: pd.DataFrame):
|
| 117 |
+
fig = plt.figure()
|
| 118 |
+
plt.title('Opponent rating distribution')
|
| 119 |
+
sns.histplot(data=df, x="opponent_rating", hue='result')
|
| 120 |
+
plt.xlabel('Opponent rating')
|
| 121 |
+
return fig
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_opponent_rating_dist_over_time_fig(df: pd.DataFrame, is_tournament: bool):
|
| 125 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
| 126 |
+
plt.title(f'Opponent rating distribution over time')
|
| 127 |
+
x_key_name = "tournament_end_date" if is_tournament else "event_date"
|
| 128 |
+
sns.violinplot(data=df,
|
| 129 |
+
x=df[x_key_name].dt.year,
|
| 130 |
+
y="opponent_rating",
|
| 131 |
+
hue="result",
|
| 132 |
+
split=True,
|
| 133 |
+
inner='points',
|
| 134 |
+
cut=1,
|
| 135 |
+
ax=ax)
|
| 136 |
+
plt.xlabel('Competition year')
|
| 137 |
+
plt.ylabel('Opponent rating')
|
| 138 |
+
return fig
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def load_match_df(file_path: Path) -> Tuple[pd.DataFrame, bool]:
|
| 142 |
+
match_type = _check_match_type(file_path.name.split('_')[0])
|
| 143 |
+
is_tournament = match_type == "tournament"
|
| 144 |
+
|
| 145 |
+
df = pd.read_csv(file_path)
|
| 146 |
+
df = _rename_columns(df, is_tournament)
|
| 147 |
+
df = _fix_dtypes(df, is_tournament)
|
| 148 |
+
|
| 149 |
+
return df, is_tournament
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def usatt_rating_analyzer(file_obj):
|
| 153 |
+
# Load data.
|
| 154 |
+
df, is_tournament = load_match_df(Path(file_obj.name))
|
| 155 |
+
|
| 156 |
+
# Create outputs.
|
| 157 |
+
n_competitions_played = get_num_competitions_played(df, is_tournament)
|
| 158 |
+
n_matches_played = len(df)
|
| 159 |
+
matches_per_competition_fig = get_matches_per_competition_fig(df, is_tournament)
|
| 160 |
+
opponent_name_word_cloud_fig = get_opponent_name_word_cloud_fig(df)
|
| 161 |
+
competition_name_word_cloud_fig = get_competition_name_word_cloud_fig(df, is_tournament)
|
| 162 |
+
rating_over_time_fig = get_rating_over_time_fig(df, is_tournament)
|
| 163 |
+
match_with_longest_game = get_match_with_longest_game(df, is_tournament)
|
| 164 |
+
opponent_rating_distr_fig = get_opponent_rating_distr_fig(df)
|
| 165 |
+
opponent_rating_dist_over_time_fig = get_opponent_rating_dist_over_time_fig(df, is_tournament)
|
| 166 |
+
|
| 167 |
+
return (n_competitions_played,
|
| 168 |
+
n_matches_played,
|
| 169 |
+
matches_per_competition_fig,
|
| 170 |
+
opponent_name_word_cloud_fig,
|
| 171 |
+
competition_name_word_cloud_fig,
|
| 172 |
+
rating_over_time_fig,
|
| 173 |
+
match_with_longest_game,
|
| 174 |
+
opponent_rating_distr_fig,
|
| 175 |
+
opponent_rating_dist_over_time_fig,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
with gr.Blocks() as demo:
|
| 180 |
+
gr.Markdown("""# USATT rating analyzer
|
| 181 |
+
Analyze USA table tennis tournament and league results.
|
| 182 |
+
|
| 183 |
+
## Downloading match results
|
| 184 |
+
1. Make sure you are [logged in](https://usatt.simplycompete.com/login/auth).
|
| 185 |
+
2. Find the *active* player you wish to analyze (e.g., [Kanak Jha](https://usatt.simplycompete.com/userAccount/up/3431)).
|
| 186 |
+
3. Under 'Tournaments' or 'Leagues', click *Download Tournament/League Match History*.
|
| 187 |
+
""")
|
| 188 |
+
with gr.Row():
|
| 189 |
+
with gr.Column():
|
| 190 |
+
input_file = gr.File(label='USATT Results File', file_types=['file'])
|
| 191 |
+
btn = gr.Button("Analyze")
|
| 192 |
+
|
| 193 |
+
with gr.Group():
|
| 194 |
+
with gr.Row():
|
| 195 |
+
with gr.Column():
|
| 196 |
+
num_comps_box = gr.Textbox(lines=1, label="Number of competitions (tournaments/leagues) played")
|
| 197 |
+
with gr.Column():
|
| 198 |
+
num_matches_box = gr.Textbox(lines=1, label="Number of matches played")
|
| 199 |
+
rating_over_time_plot = gr.Plot(show_label=False)
|
| 200 |
+
matches_per_comp_plot = gr.Plot(show_label=False)
|
| 201 |
+
with gr.Row():
|
| 202 |
+
with gr.Column():
|
| 203 |
+
opponent_names_plot = gr.Plot(label="Opponent names")
|
| 204 |
+
with gr.Column():
|
| 205 |
+
comp_names_plot = gr.Plot(label="Competition names")
|
| 206 |
+
|
| 207 |
+
match_longest_game_gdf = gr.Dataframe(label="Match with longest game", max_rows=1)
|
| 208 |
+
opponent_rating_dist_plot = gr.Plot(show_label=False)
|
| 209 |
+
opponent_rating_dist_over_time_plot = gr.Plot(show_label=False)
|
| 210 |
+
|
| 211 |
+
inputs = [input_file]
|
| 212 |
+
outputs = [
|
| 213 |
+
num_comps_box,
|
| 214 |
+
num_matches_box,
|
| 215 |
+
matches_per_comp_plot,
|
| 216 |
+
opponent_names_plot,
|
| 217 |
+
comp_names_plot,
|
| 218 |
+
rating_over_time_plot,
|
| 219 |
+
match_longest_game_gdf,
|
| 220 |
+
opponent_rating_dist_plot,
|
| 221 |
+
opponent_rating_dist_over_time_plot,
|
| 222 |
+
]
|
| 223 |
+
|
| 224 |
+
btn.click(usatt_rating_analyzer, inputs=inputs, outputs=outputs)
|
| 225 |
+
|
| 226 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
seaborn
|
| 3 |
+
matplotlib
|
| 4 |
+
wordcloud
|
| 5 |
+
numpy
|