Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplotsfrom sklearn.preprocessing import MinMaxScalerfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error, r2_score# --------------------------# 1. PAGE CONFIGURATION# --------------------------st.set_page_config(page_title="๐ Cricket Analytics Pro",page_icon="๐",layout="wide",initial_sidebar_state="expanded")# Custom CSS for better stylingst.markdown("""<style>.metric-card {background-color: #f8f9fa;border-radius: 10px;padding: 15px;margin-bottom: 15px;box-shadow: 0 4px 6px rgba(0,0,0,0.1);}.metric-title {font-size: 14px;color: #6c757d;margin-bottom: 5px;}.metric-value {font-size: 24px;font-weight: bold;color: #212529;}.player-card {border-radius: 10px;padding: 15px;margin-bottom: 15px;background-color: #ffffff;box-shadow: 0 4px 6px rgba(0,0,0,0.1);}.stSelectbox div[data-baseweb="select"] > div {border-radius: 10px !important;}</style>""", unsafe_allow_html=True)# --------------------------# 2. DATA LOADING & PREPROCESSING# --------------------------@st.cache_datadef load_data():# Load your dataset heredf = pd.read_csv("All_Teams_updated.csv")# For demo purposes, creating synthetic dataplayers = ['Virat Kohli', 'Rohit Sharma', 'Jasprit Bumrah', 'Ben Stokes','Steve Smith', 'Kane Williamson', 'Babar Azam', 'Rashid Khan']teams = ['India', 'India', 'India', 'England', 'Australia', 'New Zealand', 'Pakistan', 'Afghanistan']data = {'Player': players * 4,'Player_Team': teams * 4,'Format': ['Test']*8 + ['ODI']*8 + ['T20']*8 + ['IPL']*8}# Generate random stats for each player-format combinationfor stat in ['Matches', 'batting_Runs', 'batting_Average', 'batting_SR','batting_Fours', 'batting_Sixes', 'batting_50s', 'batting_100s','bowling_Wickets', 'bowling_Avg', 'bowling_Eco', 'bowling_SR']:data[stat] = np.random.randint(1, 100, 32)df = pd.DataFrame(data)# Pivot to match your original structuredf = df.pivot(index=['Player', 'Player_Team'], columns='Format').reset_index()df.columns = ['_'.join(col).strip() for col in df.columns.values]# Calculate derived metricsfor fmt in ['Test', 'ODI', 'T20', 'IPL']:# Batting metricsdf[f'batting_Boundary%_{fmt}'] = ((df[f'batting_Fours_{fmt}'] * 4 + df[f'batting_Sixes_{fmt}'] * 6) /df[f'batting_Runs_{fmt}'].replace(0, 1)) * 100# Bowling metricsdf[f'bowling_Dots%_{fmt}'] = ((df[f'bowling_Maidens_{fmt}'] * 6) /df[f'bowling_Balls_{fmt}'].replace(0, 1)) * 100# Player type classificationdf[f'Player_Type_{fmt}'] = np.where((df[f'batting_Runs_{fmt}'] > 1000) & (df[f'bowling_Wickets_{fmt}'] > 50),'All-Rounder',np.where(df[f'batting_Runs_{fmt}'] > 1000,'Batsman',np.where(df[f'bowling_Wickets_{fmt}'] > 50,'Bowler','Other')))return dfdf = load_data()# --------------------------# 3. VISUALIZATION FUNCTIONS (ENHANCED)# --------------------------def create_metric_card(title, value, delta=None):"""Create a styled metric card"""delta_html = f"<div class='metric-title'>{title}</div><div class='metric-value'>{value}</div>"if delta:delta_html += f"<div style='font-size:12px;color:#28a745'>{delta}</div>"return st.markdown(f"<div class='metric-card'>{delta_html}</div>", unsafe_allow_html=True)def plot_player_radar(player):"""Enhanced radar chart with more metrics"""metrics = ['Runs', 'Average', 'SR', 'Wickets', 'Economy', '50+', 'Boundary%']formats = ['Test', 'ODI', 'T20', 'IPL']fig = go.Figure()for fmt in formats:values = [df.loc[df['Player'] == player, f'batting_Runs_{fmt}'].values[0],df.loc[df['Player'] == player, f'batting_Average_{fmt}'].values[0],df.loc[df['Player'] == player, f'batting_SR_{fmt}'].values[0],df.loc[df['Player'] == player, f'bowling_Wickets_{fmt}'].values[0],df.loc[df['Player'] == player, f'bowling_Eco_{fmt}'].values[0],df.loc[df['Player'] == player, f'batting_50s_{fmt}'].values[0] +df.loc[df['Player'] == player, f'batting_100s_{fmt}'].values[0],df.loc[df['Player'] == player, f'batting_Boundary%_{fmt}'].values[0]]# Normalize valuesscaler = MinMaxScaler()values_normalized = scaler.fit_transform(np.array(values).reshape(-1, 1)).flatten()fig.add_trace(go.Scatterpolar(r=values_normalized,theta=metrics,fill='toself',name=fmt,hovertext=[f"{metrics[i]}: {values[i]}" for i in range(len(metrics))],line=dict(width=2),opacity=0.8))fig.update_layout(polar=dict(radialaxis=dict(visible=True,range=[0, 1],gridcolor='rgba(0,0,0,0.1)'),angularaxis=dict(gridcolor='rgba(0,0,0,0.1)')),title=f"{player}'s Performance Across Formats",height=600,hovermode="closest",paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)',legend=dict(orientation="h",yanchor="bottom",y=1.02,xanchor="right",x=1))return figdef plot_format_comparison(players, format_type):"""Enhanced comparison with more metrics"""fig = make_subplots(rows=2, cols=2,specs=[[{'type':'xy'}, {'type':'polar'}],subplot_titles=('Batting Comparison', 'Bowling Comparison','Milestones', 'Run Composition'),vertical_spacing=0.15)# Batting comparison (bar chart)batting_metrics = ['Runs', 'Average', 'SR', '50s', '100s', 'Boundary%']for i, player in enumerate(players):fig.add_trace(go.Bar(x=batting_metrics,y=[df.loc[df['Player'] == player, f'batting_Runs_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_Average_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_SR_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_50s_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_100s_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_Boundary%_{format_type}'].values[0]],name=player,marker_color=px.colors.qualitative.Plotly[i],opacity=0.8), row=1, col=1)# Bowling comparison (radar chart)bowling_metrics = ['Wickets', 'Avg', 'Eco', 'SR', '4w', '5w', 'Dots%']for i, player in enumerate(players):values = [df.loc[df['Player'] == player, f'bowling_Wickets_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_Avg_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_Eco_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_SR_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_4w_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_5w_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_Dots%_{format_type}'].values[0]]fig.add_trace(go.Scatterpolar(r=values,theta=bowling_metrics,fill='toself',name=player,line_color=px.colors.qualitative.Plotly[i],opacity=0.8), row=1, col=2)# Milestones (scatter plot)for i, player in enumerate(players):fig.add_trace(go.Scatter(x=['50s', '100s', '4w', '5w'],y=[df.loc[df['Player'] == player, f'batting_50s_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_100s_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_4w_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_5w_{format_type}'].values[0]],mode='markers',marker=dict(size=20,color=px.colors.qualitative.Plotly[i],opacity=0.8),name=player,showlegend=False), row=2, col=1)# Run composition (pie chart)for i, player in enumerate(players):runs = df.loc[df['Player'] == player, f'batting_Runs_{format_type}'].values[0]fours = df.loc[df['Player'] == player, f'batting_Fours_{format_type}'].values[0]sixes = df.loc[df['Player'] == player, f'batting_Sixes_{format_type}'].values[0]fig.add_trace(go.Pie(labels=['Fours', 'Sixes', 'Other Runs'],values=[fours*4, sixes*6, max(1, runs - (fours*4 + sixes*6))],name=player,marker_colors=[px.colors.qualitative.Plotly[i],px.colors.qualitative.Plotly[i+1],'#f0f0f0'],textinfo='none',hoverinfo='label+value+name',domain=dict(x=[0.5, 1], y=[0, 0.5]),row=2, col=2)fig.update_layout(title_text=f"Player Comparison - {format_type} Format",height=800,showlegend=True,paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)',margin=dict(t=100, b=50))# Update subplot titlesfor i in fig['layout']['annotations']:i['font'] = dict(size=12)return figdef plot_career_progression(player):"""Enhanced career timeline with more metrics"""formats = ['Test', 'ODI', 'T20', 'IPL']data = []for fmt in formats:data.append({'Format': fmt,'Matches': df.loc[df['Player'] == player, f'Matches_{fmt}'].values[0],'Runs': df.loc[df['Player'] == player, f'batting_Runs_{fmt}'].values[0],'Wickets': df.loc[df['Player'] == player, f'bowling_Wickets_{fmt}'].values[0],'Avg': df.loc[df['Player'] == player, f'batting_Average_{fmt}'].values[0],'SR': df.loc[df['Player'] == player, f'batting_SR_{fmt}'].values[0],'Eco': df.loc[df['Player'] == player, f'bowling_Eco_{fmt}'].values[0]})timeline_df = pd.DataFrame(data)fig = make_subplots(rows=2, cols=1,shared_xaxes=True,vertical_spacing=0.1,subplot_titles=('Batting Performance', 'Bowling Performance'))# Batting metricsfig.add_trace(go.Bar(x=timeline_df['Format'],y=timeline_df['Runs'],name='Runs',marker_color='#1f77b4',opacity=0.8), row=1, col=1)fig.add_trace(go.Scatter(x=timeline_df['Format'],y=timeline_df['Avg'],name='Average',mode='lines+markers',line=dict(color='#ff7f0e', width=2),yaxis='y2'), row=1, col=1)fig.add_trace(go.Scatter(x=timeline_df['Format'],y=timeline_df['SR'],name='Strike Rate',mode='lines+markers',line=dict(color='#2ca02c', width=2),yaxis='y3'), row=1, col=1)# Bowling metricsfig.add_trace(go.Bar(x=timeline_df['Format'],y=timeline_df['Wickets'],name='Wickets',marker_color='#d62728',opacity=0.8), row=2, col=1)fig.add_trace(go.Scatter(x=timeline_df['Format'],y=timeline_df['Eco'],name='Economy',mode='lines+markers',line=dict(color='#9467bd', width=2)), row=2, col=1)fig.update_layout(title=f"{player}'s Career Progression Across Formats",height=600,paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)',hovermode="x unified",legend=dict(orientation="h",yanchor="bottom",y=1.02,xanchor="right",x=1))# Add secondary y-axes for battingfig.update_yaxes(title_text="Runs", row=1, col=1)fig.update_yaxes(title_text="Average", secondary_y=True, row=1, col=1)fig.update_yaxes(title_text="Strike Rate", secondary_y=True, row=1, col=1,overlaying='y', side='right')# Update y-axis for bowlingfig.update_yaxes(title_text="Wickets", row=2, col=1)fig.update_yaxes(title_text="Economy", secondary_y=True, row=2, col=1)return figdef plot_team_strengths(team):"""Enhanced team strength visualization"""team_df = df[df['Player_Team'] == team]# Calculate team strengths by formatformats = ['Test', 'ODI', 'T20', 'IPL']strength_data = []for fmt in formats:batting = team_df[f'batting_Runs_{fmt}'].sum()bowling = team_df[f'bowling_Wickets_{fmt}'].sum()allround = team_df[(team_df[f'batting_Runs_{fmt}'] > team_df[f'batting_Runs_{fmt}'].median()) &(team_df[f'bowling_Wickets_{fmt}'] > team_df[f'bowling_Wickets_{fmt}'].median())].shape[0]strength_data.append({'Format': fmt,'Batting': batting,'Bowling': bowling,'All-Rounders': allround})strength_df = pd.DataFrame(strength_data)# Create radar chart for team strengthsfig1 = go.Figure()for col in ['Batting', 'Bowling', 'All-Rounders']:fig1.add_trace(go.Scatterpolar(r=strength_df[col],theta=strength_df['Format'],fill='toself',name=col,line=dict(width=2)))fig1.update_layout(polar=dict(radialaxis=dict(visible=True,gridcolor='rgba(0,0,0,0.1)')),title=f"{team}'s Relative Strengths by Format",height=400,paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)')# Create sunburst chart for player rolesrole_data = []for fmt in formats:role_counts = team_df[f'Player_Type_{fmt}'].value_counts().reset_index()role_counts['Format'] = fmtrole_data.append(role_counts)role_df = pd.concat(role_data)fig2 = px.sunburst(role_df,path=['Format', 'Player_Type_Test'],values='count',color='Player_Type_Test',title=f"{team} Player Roles by Format",height=400)return fig1, fig2def predict_performance():"""Performance prediction using ML"""st.header("๐ฎ Performance Predictor")# Feature selectioncol1, col2 = st.columns(2)with col1:target = st.selectbox("Predict", ["Batting Runs", "Bowling Wickets"])format_type = st.selectbox("Format", ["Test", "ODI", "T20", "IPL"])with col2:model_type = st.selectbox("Model", ["Random Forest", "Linear Regression"])test_size = st.slider("Test Size", 0.1, 0.5, 0.2)# Prepare dataif target == "Batting Runs":features = [f'Matches_{format_type}',f'batting_Innings_{format_type}',f'batting_Balls_{format_type}',f'batting_Average_{format_type}',f'batting_SR_{format_type}']target_col = f'batting_Runs_{format_type}'else:features = [f'Matches_{format_type}',f'bowling_Innings_{format_type}',f'bowling_Balls_{format_type}',f'bowling_Avg_{format_type}',f'bowling_Eco_{format_type}']target_col = f'bowling_Wickets_{format_type}'# Filter datamodel_df = df[features + [target_col]].dropna()X = model_df[features]y = model_df[target_col]# Train-test splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42)# Train modelif model_type == "Random Forest":model = RandomForestRegressor(n_estimators=100, random_state=42)else:from sklearn.linear_model import LinearRegressionmodel = LinearRegression()model.fit(X_train, y_train)# Evaluatey_pred = model.predict(X_test)mse = mean_squared_error(y_test, y_pred)r2 = r2_score(y_test, y_pred)# Show resultscol1, col2 = st.columns(2)with col1:st.metric("Mean Squared Error", f"{mse:.2f}")with col2:st.metric("Rยฒ Score", f"{r2:.2f}")# Feature importanceif model_type == "Random Forest":importance = pd.DataFrame({'Feature': features,'Importance': model.feature_importances_}).sort_values('Importance', ascending=False)fig = px.bar(importance,x='Feature',y='Importance',title='Feature Importance')st.plotly_chart(fig, use_container_width=True)# Prediction interfacest.subheader("Make Custom Prediction")input_data = {}cols = st.columns(len(features))for i, feature in enumerate(features):min_val = float(df[feature].min())max_val = float(df[feature].max())mean_val = float(df[feature].mean())with cols[i]:input_data[feature] = st.slider(feature.replace('_', ' '),min_val,max_val,mean_val)if st.button("Predict"):input_df = pd.DataFrame([input_data])prediction = model.predict(input_df)st.success(f"Predicted {target}: {prediction[0]:.1f}")# --------------------------# 4. PAGE COMPONENTS (ENHANCED)# --------------------------def player_analysis():st.header("๐ Player Performance Analysis")col1, col2 = st.columns([1, 3])with col1:player = st.selectbox("Select Player", df['Player'].unique())format_type = st.selectbox("Select Format", ["Test", "ODI", "T20", "IPL"])analysis_type = st.radio("Analysis Type",["Overview", "Batting", "Bowling", "Career"])with col2:st.markdown(f"<div class='player-card'><h3>{player}</h3><p>{df[df['Player'] == player]['Player_Team'].values[0]}</p></div>",unsafe_allow_html=True)if analysis_type == "Overview":st.plotly_chart(plot_player_radar(player), use_container_width=True)# Key metrics cardscols = st.columns(4)with cols[0]:create_metric_card("Matches",df.loc[df['Player'] == player, f'Matches_{format_type}'].values[0])with cols[1]:create_metric_card("Runs",df.loc[df['Player'] == player, f'batting_Runs_{format_type}'].values[0])with cols[2]:create_metric_card("Wickets",df.loc[df['Player'] == player, f'bowling_Wickets_{format_type}'].values[0])with cols[3]:create_metric_card("Player Type",df.loc[df['Player'] == player, f'Player_Type_{format_type}'].values[0])elif analysis_type == "Batting":fig = make_subplots(rows=1, cols=2, subplot_titles=('Run Composition', 'Milestones'))# Run compositionruns = df.loc[df['Player'] == player, f'batting_Runs_{format_type}'].values[0]fours = df.loc[df['Player'] == player, f'batting_Fours_{format_type}'].values[0]sixes = df.loc[df['Player'] == player, f'batting_Sixes_{format_type}'].values[0]fig.add_trace(go.Pie(labels=['Fours', 'Sixes', 'Other Runs'],values=[fours*4, sixes*6, max(1, runs - (fours*4 + sixes*6))],hole=0.4,marker_colors=['#1f77b4', '#ff7f0e', '#2ca02c'],name="Run Composition"), row=1, col=1)# Milestonesfig.add_trace(go.Bar(x=['50s', '100s', 'Highest'],y=[df.loc[df['Player'] == player, f'batting_50s_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_100s_{format_type}'].values[0],df.loc[df['Player'] == player, f'batting_Highest_{format_type}'].values[0]],marker_color=['#1f77b4', '#ff7f0e', '#2ca02c']), row=1, col=2)fig.update_layout(title_text=f"{player}'s Batting Analysis - {format_type}",height=400,showlegend=False)st.plotly_chart(fig, use_container_width=True)elif analysis_type == "Bowling":fig = go.Figure()metrics = ['Wickets', 'Avg', 'Eco', 'SR', '4w', '5w']values = [df.loc[df['Player'] == player, f'bowling_Wickets_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_Avg_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_Eco_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_SR_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_4w_{format_type}'].values[0],df.loc[df['Player'] == player, f'bowling_5w_{format_type}'].values[0]]fig.add_trace(go.Bar(x=metrics,y=values,marker_color=px.colors.sequential.Viridis,text=values,textposition='auto'))fig.update_layout(title=f"{player}'s Bowling Metrics - {format_type}",height=400,xaxis_title="Metric",yaxis_title="Value")st.plotly_chart(fig, use_container_width=True)else: # Careerst.plotly_chart(plot_career_progression(player), use_container_width=True)def player_comparison():st.header("๐ฅ Head-to-Head Player Comparison")col1, col2 = st.columns(2)with col1:player1 = st.selectbox("Player 1", df['Player'].unique(), key='p1')with col2:player2 = st.selectbox("Player 2", df['Player'].unique(), index=1, key='p2')format_type = st.selectbox("Compare in Format", ["Test", "ODI", "T20", "IPL"])st.plotly_chart(plot_format_comparison([player1, player2], format_type),use_container_width=True)# Detailed comparison table with metricsst.subheader("Detailed Comparison")comparison_metrics = [('Matches', 'Matches'),('Runs', 'batting_Runs'),('Average', 'batting_Average'),('SR', 'batting_SR'),('50s', 'batting_50s'),('100s', 'batting_100s'),('Wickets', 'bowling_Wickets'),('Bowl Avg', 'bowling_Avg'),('Economy', 'bowling_Eco')]comparison_data = []for display_name, metric in comparison_metrics:if metric == 'Matches':key = f"{metric}_{format_type}"elif metric.startswith('batting'):key = f"{metric}_{format_type}"else:key = f"bowling_{format_type}_{metric.split('_')[1]}"p1_val = df.loc[df['Player'] == player1, key].values[0]p2_val = df.loc[df['Player'] == player2, key].values[0]# Calculate differenceif isinstance(p1_val, (int, float)) and isinstance(p2_val, (int, float)):diff = p1_val - p2_valdiff_str = f"+{diff:.1f}" if diff > 0 else f"{diff:.1f}"else:diff_str = ""comparison_data.append([display_name, p1_val, p2_val, diff_str])comp_df = pd.DataFrame(comparison_data,columns=['Metric', player1, player2, 'Difference'])# Apply conditional formattingdef color_diff(val):if isinstance(val, str) and val.startswith('+'):return 'color: green'elif isinstance(val, str) and '-' in val:return 'color: red'return ''st.dataframe(comp_df.style.applymap(color_diff, subset=['Difference']).format({player1: "{:.1f}", player2: "{:.1f}"},na_rep="N/A"),use_container_width=True)def team_analysis():st.header("๐ Team Composition Analysis")team = st.selectbox("Select Team", df['Player_Team'].unique())format_type = st.selectbox("Select Format", ["Test", "ODI", "T20", "IPL"])# Team strengths visualizationfig1, fig2 = plot_team_strengths(team)st.plotly_chart(fig1, use_container_width=True)st.plotly_chart(fig2, use_container_width=True)# Top performersst.subheader(f"Top Performers - {format_type}")col1, col2 = st.columns(2)with col1:st.markdown("**Top Batsmen**")top_batsmen = df[df['Player_Team'] == team][['Player', f'batting_Runs_{format_type}',f'batting_Average_{format_type}',f'batting_SR_{format_type}']].sort_values(f'batting_Runs_{format_type}', ascending=False).head(5)st.dataframe(top_batsmen, hide_index=True)with col2:st.markdown("**Top Bowlers**")top_bowlers = df[df['Player_Team'] == team][['Player', f'bowling_Wickets_{format_type}',f'bowling_Avg_{format_type}',f'bowling_Eco_{format_type}']].sort_values(f'bowling_Wickets_{format_type}', ascending=False).head(5)st.dataframe(top_bowlers, hide_index=True)# Team comparisonst.subheader("Compare With Another Team")other_team = st.selectbox("Select Team to Compare",[t for t in df['Player_Team'].unique() if t != team])# Comparison metricscomparison_metrics = [('Total Runs', 'batting_Runs'),('Batting Average', 'batting_Average'),('Total Wickets', 'bowling_Wickets'),('Bowling Average', 'bowling_Avg')]comparison_data = []for display_name, metric in comparison_metrics:if metric.startswith('batting'):key = f"{metric}_{format_type}"else:key = f"bowling_{format_type}_{metric.split('_')[1]}"team_val = df[df['Player_Team'] == team][key].sum()other_val = df[df['Player_Team'] == other_team][key].sum()comparison_data.append([display_name, team_val, other_val])comp_df = pd.DataFrame(comparison_data,columns=['Metric', team, other_team])# Visualize comparisonfig = px.bar(comp_df.melt(id_vars='Metric', var_name='Team', value_name='Value'),x='Metric',y='Value',color='Team',barmode='group',title=f"{team} vs {other_team} - {format_type}")st.plotly_chart(fig, use_container_width=True)# --------------------------# 5. MAIN APP FUNCTION# --------------------------def main():st.title("๐ Cricket Analytics Pro")st.markdown("""<style>.stApp {background-color: #f8f9fa;}.css-18e3th9 {padding-top: 2rem;padding-bottom: 2rem;}</style>""", unsafe_allow_html=True)# Sidebar navigationst.sidebar.header("Navigation")app_mode = st.sidebar.selectbox("Choose Analysis Mode", ["๐ Player Analysis","๐ฅ Player Comparison","๐ Team Analysis","๐ฎ Performance Predictor"])# Page routingif app_mode == "๐ Player Analysis":player_analysis()elif app_mode == "๐ฅ Player Comparison":player_comparison()elif app_mode == "๐ Team Analysis":team_analysis()elif app_mode == "๐ฎ Performance Predictor":predict_performance()# Footerst.sidebar.markdown("---")st.sidebar.markdown("""**Cricket Analytics Pro**Advanced cricket statistics and predictive analytics[GitHub Repo](#) | [Data Source](#)""")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286import streamlit as stimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.express as pxfrom PIL import Imageimport requestsfrom io import BytesIO# 2. PAGE CONFIG - MUST BE FIRST STREAMLIT COMMANDst.set_page_config(page_title="๐ Cricket Analytics Dashboard",page_icon="๐",layout="wide",initial_sidebar_state="expanded",menu_items={'Get Help': 'https://github.com/yourusername/cricket-analytics','Report a bug': "https://github.com/yourusername/cricket-analytics/issues",'About': """## Cricket Analytics DashboardA comprehensive tool for cricket statistics analysis and match predictions.Developed using Streamlit."""})# 3. DATA LOADING (AFTER PAGE CONFIG)@st.cache_datadef load_data():# In production, replace with actual API callreturn pd.read_csv("My_Cricket.csv") # Your datasetdf = load_data()# 4. PAGE COMPONENTS (DEFINE ALL FUNCTIONS BEFORE main())def show_player_stats():st.header("๐ Player Statistics Explorer")col1, col2 = st.columns(2)with col1:player = st.selectbox("Select Player", df['Player'].unique())with col2:format_type = st.selectbox("Select Format", ["Test", "ODI", "T20", "IPL"])player_data = df[df['Player'] == player].iloc[0]# Display statsst.subheader(f"{player}'s {format_type} Statistics")col1, col2, col3 = st.columns(3)col1.metric("Matches", player_data[f"Matches_{format_type}"])col2.metric("Runs", player_data[f"batting_Runs_{format_type}"])col3.metric("Average", player_data[f"batting_Average_{format_type}"])# Visualizationfig = px.bar(x=["Matches", "Runs", "Average", "Strike Rate"],y=[player_data[f"Matches_{format_type}"],player_data[f"batting_Runs_{format_type}"],player_data[f"batting_Average_{format_type}"],player_data[f"batting_SR_{format_type}"]],title=f"{player}'s {format_type} Performance")st.plotly_chart(fig, use_container_width=True)def show_player_comparison():st.header("๐ Player Comparison")col1, col2 = st.columns(2)with col1:player1 = st.selectbox("Player 1", df['Player'].unique())with col2:player2 = st.selectbox("Player 2", df['Player'].unique(), index=1)# Comparison logicst.subheader(f"{player1} vs {player2}")format_type = st.selectbox("Compare in Format", ["Test", "ODI", "T20"])# Create comparison tablecomparison_df = pd.DataFrame({"Metric": ["Matches", "Runs", "Average", "Strike Rate", "50s", "100s"],player1: [df.loc[df['Player'] == player1, f"Matches_{format_type}"].values[0],df.loc[df['Player'] == player1, f"batting_Runs_{format_type}"].values[0],df.loc[df['Player'] == player1, f"batting_Average_{format_type}"].values[0],df.loc[df['Player'] == player1, f"batting_SR_{format_type}"].values[0],df.loc[df['Player'] == player1, f"batting_50s_{format_type}"].values[0],df.loc[df['Player'] == player1, f"batting_100s_{format_type}"].values[0],],player2: [df.loc[df['Player'] == player2, f"Matches_{format_type}"].values[0],df.loc[df['Player'] == player2, f"batting_Runs_{format_type}"].values[0],df.loc[df['Player'] == player2, f"batting_Average_{format_type}"].values[0],df.loc[df['Player'] == player2, f"batting_SR_{format_type}"].values[0],df.loc[df['Player'] == player2, f"batting_50s_{format_type}"].values[0],df.loc[df['Player'] == player2, f"batting_100s_{format_type}"].values[0],]})st.dataframe(comparison_df.set_index("Metric"), width=800)# Visual comparisonfig = px.bar(comparison_df.melt(id_vars="Metric"),x="Metric", y="value", color="variable",barmode="group", title="Player Comparison")st.plotly_chart(fig, use_container_width=True)def show_team_comparison():st.header("๐ด Team Comparison")# Get unique teams from the datateams = df['Player_Team'].unique()col1, col2 = st.columns(2)with col1:team1 = st.selectbox("Team 1", teams)with col2:team2 = st.selectbox("Team 2", [t for t in teams if t != team1])st.subheader(f"{team1} vs {team2} - Overall Comparison")# Calculate team averagesteam1_stats = df[df['Player_Team'] == team1].mean(numeric_only=True)team2_stats = df[df['Player_Team'] == team2].mean(numeric_only=True)# Key metrics to comparemetrics = ["batting_Average_Test", "batting_SR_ODI", "bowling_Test_Avg", "bowling_ODI_Eco"]comparison = pd.DataFrame({"Metric": ["Test Batting Avg", "ODI Strike Rate", "Test Bowling Avg", "ODI Economy"],team1: [team1_stats[m] for m in metrics],team2: [team2_stats[m] for m in metrics]})st.dataframe(comparison.set_index("Metric"), width=800)# Radar chart for comparisonfig = px.line_polar(comparison.melt(id_vars="Metric"),r="value", theta="Metric", color="variable",line_close=True,title="Team Comparison Radar Chart")st.plotly_chart(fig, use_container_width=True)def show_score_predictor():st.header("๐ฎ Team Score Predictor")# Input parameterscol1, col2 = st.columns(2)with col1:team = st.selectbox("Select Batting Team", df['Player_Team'].unique())venue = st.selectbox("Select Venue", ["Home", "Neutral", "Away"])opposition = st.selectbox("Select Opposition",[t for t in df['Player_Team'].unique() if t != team])with col2:toss = st.selectbox("Toss Result", ["Won", "Lost"])players_available = st.slider("Key Players Available", 1, 7, 5)pitch_condition = st.select_slider("Pitch Condition",["Very Slow", "Slow", "Normal", "Fast", "Very Fast"])# Prediction buttonif st.button("Predict Score"):# Placeholder for actual ML modelbase_score = 250 # This would come from your trained modeladjustments = {"Home": 15, "Neutral": 0, "Away": -10,"Won": 10, "Lost": -5,"Very Slow": -20, "Slow": -10, "Normal": 0, "Fast": 15, "Very Fast": 25}predicted_score = base_score + adjustments[venue] + adjustments[toss] + \(players_available * 5) + adjustments[pitch_condition]st.success(f"*Predicted Score Range*: {predicted_score-15} - {predicted_score+15}")# Show factors affecting predictionst.subheader("Key Factors Considered")factors = pd.DataFrame({"Factor": ["Venue", "Toss", "Players Available", "Pitch Condition"],"Impact": [f"{'+' if adjustments[venue] > 0 else ''}{adjustments[venue]}",f"{'+' if adjustments[toss] > 0 else ''}{adjustments[toss]}",f"+{players_available * 5}",f"{'+' if adjustments[pitch_condition] > 0 else ''}{adjustments[pitch_condition]}"]})st.dataframe(factors.set_index("Factor"))def show_winner_prediction():st.header("๐ Match Winner Prediction")col1, col2 = st.columns(2)with col1:team_a = st.selectbox("Team A", df['Player_Team'].unique())team_a_form = st.slider(f"{team_a} Recent Form (1-10)", 1, 10, 7)team_a_key_players = st.multiselect(f"{team_a} Key Players",df[df['Player_Team'] == team_a]['Player'].unique())with col2:team_b = st.selectbox("Team B", df['Player_Team'].unique(), index=1)team_b_form = st.slider(f"{team_b} Recent Form (1-10)", 1, 10, 6)team_b_key_players = st.multiselect(f"{team_b} Key Players",df[df['Player_Team'] == team_b]['Player'].unique())# Additional factorsvenue = st.selectbox("Match Venue", ["Home", "Neutral", "Away"])toss_winner = st.radio("Toss Winner", [team_a, team_b])pitch_type = st.selectbox("Pitch Type", ["Batting", "Bowling", "Balanced"])if st.button("Predict Winner"):# Placeholder for actual model predictionteam_a_score = team_a_form * 10 + len(team_a_key_players) * 5team_b_score = team_b_form * 10 + len(team_b_key_players) * 5# Adjustmentsif venue == "Home":team_a_score += 15elif venue == "Away":team_b_score += 15if toss_winner == team_a:team_a_score += 10else:team_b_score += 10if pitch_type == "Batting":team_a_score += 5 if team_a == "India" else 0 # Example biaselif pitch_type == "Bowling":team_b_score += 5 if team_b == "Australia" else 0# Display resultif team_a_score > team_b_score:st.success(f"*Predicted Winner*: {team_a} (Confidence: {team_a_score/(team_a_score+team_b_score)*100:.1f}%)")else:st.success(f"*Predicted Winner*: {team_b} (Confidence: {team_b_score/(team_a_score+team_b_score)*100:.1f}%)")# Show comparisonfig = px.bar(x=[team_a, team_b],y=[team_a_score, team_b_score],title="Team Comparison Score")st.plotly_chart(fig, use_container_width=True)# 5. MAIN APP FUNCTION (DEFINED AFTER ALL PAGE FUNCTIONS)def main():st.title("๐ Cricket Analytics Dashboard")st.markdown("""Explore player statistics, compare teams, and predict match outcomes using advanced analytics.""")# Sidebar navigationst.sidebar.header("Navigation")app_mode = st.sidebar.selectbox("Choose Analysis Mode", ["๐ Player Statistics","๐ Player Comparison","๐ด Team Comparison","๐ฎ Score Predictor","๐ Match Winner Prediction"])# Page routingif app_mode == "๐ Player Statistics":show_player_stats()elif app_mode == "๐ Player Comparison":show_player_comparison()elif app_mode == "๐ด Team Comparison":show_team_comparison()elif app_mode == "๐ฎ Score Predictor":show_score_predictor()elif app_mode == "๐ Match Winner Prediction":show_winner_prediction()# 6. RUN THE APPif _name_ == "_main_":main()
app.py+222-797