Py.Cafe

OnLinE2176/

powerlifting-awards-analysis

Powerlifting Awards Analysis

DocsPricing
  • app.py
  • index.html
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import streamlit as st
import pandas as pd
import io

# ==============================================================================
# Main App Logic
# ==============================================================================

def process_data(uploaded_file):
    """
    This function contains the core logic from your original script.
    It takes an uploaded file, processes it, and returns the final awards CSV as a string.
    """
    
    # --- PART 1: FILE FORMATTING ---
    # The uploaded_file from Streamlit is already in a file-like format
    df = pd.read_csv(uploaded_file)
    
    # Check if all required columns exist in the uploaded file
    required_columns = [
        'Name', 'Gender', 'Raw/Equipped', 'Team', 'Awards Division',
        'Body Weight (kg)', 'Weight Class', 'Squat 1', 'Squat 2', 'Squat 3', 'Best Squat',
        'Bench 1', 'Bench 2', 'Bench 3', 'Best Bench', 'Subtotal',
        'Deadlift 1', 'Deadlift 2', 'Deadlift 3', 'Best Deadlift', 'Total',
        'IPF Points', 'Place'
    ]
    
    # Find which columns are missing, if any
    missing_cols = [col for col in required_columns if col not in df.columns]
    if missing_cols:
        # Raise an exception with a helpful error message
        raise ValueError(f"The uploaded CSV is missing the following required columns: {', '.join(missing_cols)}")

    df_formatted = df[required_columns].copy()

    team_col_index = df_formatted.columns.get_loc('Team')
    df_formatted.insert(team_col_index + 1, 'School', '')

    def split_team_affiliation(row):
        team_val = row['Team']
        if isinstance(team_val, str) and '/' in team_val:
            parts = team_val.split('/', 1)
            row['Team'] = parts[0].strip()
            row['School'] = parts[1].strip()
        return row

    df_formatted = df_formatted.apply(split_team_affiliation, axis=1)

    final_column_order = [
        'Name', 'Gender', 'Raw/Equipped', 'Team', 'School', 'Awards Division',
        'Body Weight (kg)', 'Weight Class', 'Squat 1', 'Squat 2', 'Squat 3', 'Best Squat',
        'Bench 1', 'Bench 2', 'Bench 3', 'Best Bench', 'Subtotal',
        'Deadlift 1', 'Deadlift 2', 'Deadlift 3', 'Best Deadlift', 'Total',
        'IPF Points', 'Place'
    ]
    df_formatted = df_formatted[final_column_order]
    df_formatted.rename(columns={'School': ''}, inplace=True)
    
    # --- PART 2: AWARDS CALCULATION ---
    df_awards = df_formatted.rename(columns={'': 'School'})
    all_awards_dfs = []

    # --- Section 1: Best Lifter Awards ---
    df_best_lifter = df_awards[~df_awards['Awards Division'].str.contains("Guest", na=False)].copy()
    df_best_lifter['IPF Points'] = pd.to_numeric(df_best_lifter['IPF Points'], errors='coerce')
    best_lifters_idx = df_best_lifter.groupby(['Gender', 'Awards Division'])['IPF Points'].idxmax()
    best_lifters = df_best_lifter.loc[best_lifters_idx].sort_values(by=['Gender', 'Awards Division'])
    
    best_lifters_list_for_csv = []
    for index, lifter in best_lifters.iterrows():
        category_name = f"Best Lifter - {lifter['Gender'].title()}'s {lifter['Awards Division']}"
        winner_name = f"1st - {lifter['Name']}"
        best_lifters_list_for_csv.append([category_name, winner_name])

    all_awards_dfs.append(pd.DataFrame([['--- Best Lifter Awards ---', '']]))
    all_awards_dfs.append(pd.DataFrame(best_lifters_list_for_csv, columns=['Category', 'Winner']))
    all_awards_dfs.append(pd.DataFrame([['', '']]))

    # --- Section 2: Individual Standings ---
    df_standings = df_awards[~df_awards['Awards Division'].str.contains("Guest", na=False)].copy()
    df_standings['Place'] = pd.to_numeric(df_standings['Place'], errors='coerce')
    df_standings = df_standings[df_standings['Place'].isin([1, 2, 3])]
    df_standings['Weight Class Sortable'] = df_standings['Weight Class'].apply(lambda wc: float(str(wc).replace('+', '.1')))
    df_standings = df_standings.sort_values(by=['Gender', 'Awards Division', 'Weight Class Sortable', 'Place'])

    medal_map = {1: "Gold (1st)", 2: "Silver (2nd)", 3: "Bronze (3rd)"}
    standings_list_for_csv = []
    
    for division in df_standings['Awards Division'].unique():
        gender = df_standings[df_standings['Awards Division'] == division]['Gender'].iloc[0].title()
        division_df = df_standings[df_standings['Awards Division'] == division]
        for wc in division_df['Weight Class Sortable'].unique():
            wc_str = str(division_df[division_df['Weight Class Sortable']==wc]['Weight Class'].iloc[0])
            wc_df = division_df[division_df['Weight Class Sortable'] == wc]
            for _, row in wc_df.iterrows():
                medal = medal_map.get(row['Place'], f"{int(row['Place'])}th")
                standings_list_for_csv.append({
                    'Division': f"{gender}'s {division}",
                    'Weight Class': f"{wc_str}kg",
                    'Medal': medal,
                    'Name': row['Name'],
                    'Total (kg)': row['Total']
                })
    
    all_awards_dfs.append(pd.DataFrame([['--- Individual Standings ---', '', '', '', '']]))
    all_awards_dfs.append(pd.DataFrame(standings_list_for_csv))
    all_awards_dfs.append(pd.DataFrame([['', '']]))

    # --- Section 3: Best Team & School Awards ---
    def get_team_points(place):
        place = int(place)
        points_map = {1: 12, 2: 9, 3: 8, 4: 7, 5: 6, 6: 5, 7: 4, 8: 3, 9: 2}
        return points_map.get(place, 1)

    df_team_awards = df_awards[df_awards['Total'] > 0].copy()
    df_team_awards['Place'] = pd.to_numeric(df_team_awards['Place'], errors='coerce').fillna(0)
    df_team_awards = df_team_awards[df_team_awards['Place'] > 0]
    df_team_awards['Team Points'] = df_team_awards['Place'].apply(get_team_points)
    
    df_teams = df_team_awards[df_team_awards['Team'].str.lower() != 'individual'].copy()
    team_scores = df_teams.groupby(['Awards Division', 'Team'])['Team Points'].apply(lambda x: x.nlargest(5).sum()).reset_index()
    top_teams = team_scores.groupby('Awards Division').apply(lambda x: x.nlargest(3, 'Team Points')).reset_index(drop=True)
    
    team_list_for_csv = []
    for division in top_teams['Awards Division'].unique():
        division_teams = top_teams[top_teams['Awards Division'] == division]
        for i, (index, row) in enumerate(division_teams.iterrows()):
            team_name = row['Team']
            lifters = df_teams[(df_teams['Awards Division'] == division) & (df_teams['Team'] == team_name)]['Name'].tolist()
            team_list_for_csv.append({
                'Division': f"Best Team - {division}",
                'Rank': i + 1,
                'Team': team_name,
                'Points': row['Team Points'],
                'Contributing Lifters': ", ".join(lifters)
            })

    all_awards_dfs.append(pd.DataFrame([['--- Best Team Awards ---', '', '', '', '']]))
    all_awards_dfs.append(pd.DataFrame(team_list_for_csv))
    all_awards_dfs.append(pd.DataFrame([['', '']]))
    
    df_schools = df_team_awards[df_team_awards['School'].notna() & (df_team_awards['School'] != '')].copy()
    school_list_for_csv = []

    school_categories = {
        "Men's College": df_schools[df_schools['Awards Division'].str.contains("College") & (df_schools['Gender'] == 'MALE')],
        "Women's College": df_schools[df_schools['Awards Division'].str.contains("College") & (df_schools['Gender'] == 'FEMALE')],
        "Men's High School": df_schools[df_schools['Awards Division'].str.contains("High School") & (df_schools['Gender'] == 'MALE')],
        "Women's High School": df_schools[df_schools['Awards Division'].str.contains("High School") & (df_schools['Gender'] == 'FEMALE')]
    }

    def process_school_awards(df, category_name):
        if df.empty:
            return []
        school_scores = df.groupby('School')['Team Points'].apply(lambda x: x.nlargest(5).sum()).reset_index()
        top_schools = school_scores.nlargest(3, 'Team Points')
        awards_list = []
        for i, (index, row) in enumerate(top_schools.iterrows()):
            school_name = row['School']
            lifters = df[df['School'] == school_name]['Name'].tolist()
            awards_list.append({
                'Category': f"Best School - {category_name}",
                'Rank': i + 1,
                'School': school_name,
                'Points': row['Team Points'],
                'Contributing Lifters': ", ".join(lifters)
            })
        return awards_list

    all_awards_dfs.append(pd.DataFrame([['--- Best School Awards ---', '', '', '', '']]))
    for name, df_cat in school_categories.items():
        school_awards_data = process_school_awards(df_cat, name)
        if school_awards_data:
            school_list_for_csv.extend(school_awards_data)

    all_awards_dfs.append(pd.DataFrame(school_list_for_csv))

    # --- Final CSV Export ---
    final_awards_df = pd.concat(all_awards_dfs).fillna('')
    return final_awards_df.to_csv(index=False, header=False).encode('utf-8')

# ==============================================================================
# Streamlit UI
# ==============================================================================

st.set_page_config(layout="wide")
st.title('Powerlifting Championships Awards Generator')

st.write("""
Upload the unformatted results CSV file to automatically calculate and generate the awards report. 
The CSV must contain the following columns: 'Name', 'Gender', 'Team', 'Awards Division', 'Body Weight (kg)', 'Weight Class', 'Best Squat', 'Best Bench', 'Best Deadlift', 'Total', 'IPF Points', and 'Place'.
""")

uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

if uploaded_file is not None:
    
    if st.button('Generate Awards Report'):
        with st.spinner('Calculating awards... Please wait.'):
            try:
                # When the button is clicked, process the data
                awards_csv_data = process_data(uploaded_file)
                st.balloons()
                st.success('Awards calculation complete!')
                
                # Provide the download button for the generated file
                st.download_button(
                   label="Download Awards CSV",
                   data=awards_csv_data,
                   file_name='powerlifting_awards.csv',
                   mime='text/csv',
                )
            except Exception as e:
                # If any error occurs during processing, show it in the app
                st.error(f"An error occurred: {e}")