saikumar27 commited on
Commit
01d46f7
·
verified ·
1 Parent(s): 17332cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +175 -270
app.py CHANGED
@@ -1,287 +1,192 @@
1
- # 1. IMPORTS (NON-STREAMLIT)
2
  import streamlit as st
3
  import pandas as pd
4
- import matplotlib.pyplot as plt
5
- import seaborn as sns
6
- import plotly.express as px
7
- from PIL import Image
8
  import requests
9
- from io import BytesIO
10
-
11
- # 2. PAGE CONFIG - MUST BE FIRST STREAMLIT COMMAND
12
- st.set_page_config(
13
- page_title="🏏 Cricket Analytics Dashboard",
14
- page_icon="🏏",
15
- layout="wide",
16
- initial_sidebar_state="expanded",
17
- menu_items={
18
- 'Get Help': 'https://github.com/yourusername/cricket-analytics',
19
- 'Report a bug': "https://github.com/yourusername/cricket-analytics/issues",
20
- 'About': """
21
- ## Cricket Analytics Dashboard
22
- A comprehensive tool for cricket statistics analysis and match predictions.
23
- Developed using Streamlit.
24
- """
25
- }
26
- )
27
-
28
- # 3. DATA LOADING (AFTER PAGE CONFIG)
29
- @st.cache_data
30
- def load_data():
31
- # In production, replace with actual API call
32
- return pd.read_csv("My_Cricket.csv") # Your dataset
33
 
34
- df = load_data()
 
 
35
 
36
- # 4. PAGE COMPONENTS (DEFINE ALL FUNCTIONS BEFORE main())
37
- def show_player_stats():
38
- st.header("📊 Player Statistics Explorer")
39
-
40
- col1, col2 = st.columns(2)
41
- with col1:
42
- player = st.selectbox("Select Player", df['Player'].unique())
43
- with col2:
44
- format_type = st.selectbox("Select Format", ["Test", "ODI", "T20", "IPL"])
45
-
46
- player_data = df[df['Player'] == player].iloc[0]
47
-
48
- # Display stats
49
- st.subheader(f"{player}'s {format_type} Statistics")
50
- col1, col2, col3 = st.columns(3)
51
- col1.metric("Matches", player_data[f"Matches_{format_type}"])
52
- col2.metric("Runs", player_data[f"batting_Runs_{format_type}"])
53
- col3.metric("Average", player_data[f"batting_Average_{format_type}"])
54
-
55
- # Visualization
56
- fig = px.bar(
57
- x=["Matches", "Runs", "Average", "Strike Rate"],
58
- y=[
59
- player_data[f"Matches_{format_type}"],
60
- player_data[f"batting_Runs_{format_type}"],
61
- player_data[f"batting_Average_{format_type}"],
62
- player_data[f"batting_SR_{format_type}"]
63
- ],
64
- title=f"{player}'s {format_type} Performance"
65
- )
66
- st.plotly_chart(fig, use_container_width=True)
67
 
68
- def show_player_comparison():
69
- st.header("🆚 Player Comparison")
70
-
71
- col1, col2 = st.columns(2)
72
- with col1:
73
- player1 = st.selectbox("Player 1", df['Player'].unique())
74
- with col2:
75
- player2 = st.selectbox("Player 2", df['Player'].unique(), index=1)
76
-
77
- # Comparison logic
78
- st.subheader(f"{player1} vs {player2}")
79
- format_type = st.selectbox("Compare in Format", ["Test", "ODI", "T20"])
80
-
81
- # Create comparison table
82
- comparison_df = pd.DataFrame({
83
- "Metric": ["Matches", "Runs", "Average", "Strike Rate", "50s", "100s"],
84
- player1: [
85
- df.loc[df['Player'] == player1, f"Matches_{format_type}"].values[0],
86
- df.loc[df['Player'] == player1, f"batting_Runs_{format_type}"].values[0],
87
- df.loc[df['Player'] == player1, f"batting_Average_{format_type}"].values[0],
88
- df.loc[df['Player'] == player1, f"batting_SR_{format_type}"].values[0],
89
- df.loc[df['Player'] == player1, f"batting_50s_{format_type}"].values[0],
90
- df.loc[df['Player'] == player1, f"batting_100s_{format_type}"].values[0],
91
- ],
92
- player2: [
93
- df.loc[df['Player'] == player2, f"Matches_{format_type}"].values[0],
94
- df.loc[df['Player'] == player2, f"batting_Runs_{format_type}"].values[0],
95
- df.loc[df['Player'] == player2, f"batting_Average_{format_type}"].values[0],
96
- df.loc[df['Player'] == player2, f"batting_SR_{format_type}"].values[0],
97
- df.loc[df['Player'] == player2, f"batting_50s_{format_type}"].values[0],
98
- df.loc[df['Player'] == player2, f"batting_100s_{format_type}"].values[0],
99
- ]
100
- })
101
-
102
- st.dataframe(comparison_df.set_index("Metric"), width=800)
103
-
104
- # Visual comparison
105
- fig = px.bar(
106
- comparison_df.melt(id_vars="Metric"),
107
- x="Metric", y="value", color="variable",
108
- barmode="group", title="Player Comparison"
109
- )
110
- st.plotly_chart(fig, use_container_width=True)
111
 
112
- def show_team_comparison():
113
- st.header("🏴 Team Comparison")
114
-
115
- # Get unique teams from the data
116
- teams = df['Player_Team'].unique()
117
-
118
- col1, col2 = st.columns(2)
119
- with col1:
120
- team1 = st.selectbox("Team 1", teams)
121
- with col2:
122
- team2 = st.selectbox("Team 2", [t for t in teams if t != team1])
123
-
124
- st.subheader(f"{team1} vs {team2} - Overall Comparison")
125
-
126
- # Calculate team averages
127
- team1_stats = df[df['Player_Team'] == team1].mean(numeric_only=True)
128
- team2_stats = df[df['Player_Team'] == team2].mean(numeric_only=True)
129
-
130
- # Key metrics to compare
131
- metrics = ["batting_Average_Test", "batting_SR_ODI", "bowling_Test_Avg", "bowling_ODI_Eco"]
132
- comparison = pd.DataFrame({
133
- "Metric": ["Test Batting Avg", "ODI Strike Rate", "Test Bowling Avg", "ODI Economy"],
134
- team1: [team1_stats[m] for m in metrics],
135
- team2: [team2_stats[m] for m in metrics]
136
- })
137
-
138
- st.dataframe(comparison.set_index("Metric"), width=800)
139
-
140
- # Radar chart for comparison
141
- fig = px.line_polar(
142
- comparison.melt(id_vars="Metric"),
143
- r="value", theta="Metric", color="variable",
144
- line_close=True,
145
- title="Team Comparison Radar Chart"
146
- )
147
- st.plotly_chart(fig, use_container_width=True)
148
 
149
- def show_score_predictor():
150
- st.header("🔮 Team Score Predictor")
151
-
152
- # Input parameters
153
- col1, col2 = st.columns(2)
154
-
155
- with col1:
156
- team = st.selectbox("Select Batting Team", df['Player_Team'].unique())
157
- venue = st.selectbox("Select Venue", ["Home", "Neutral", "Away"])
158
- opposition = st.selectbox("Select Opposition",
159
- [t for t in df['Player_Team'].unique() if t != team])
160
-
161
- with col2:
162
- toss = st.selectbox("Toss Result", ["Won", "Lost"])
163
- players_available = st.slider("Key Players Available", 1, 7, 5)
164
- pitch_condition = st.select_slider("Pitch Condition",
165
- ["Very Slow", "Slow", "Normal", "Fast", "Very Fast"])
166
-
167
- # Prediction button
168
- if st.button("Predict Score"):
169
- # Placeholder for actual ML model
170
- base_score = 250 # This would come from your trained model
171
- adjustments = {
172
- "Home": 15, "Neutral": 0, "Away": -10,
173
- "Won": 10, "Lost": -5,
174
- "Very Slow": -20, "Slow": -10, "Normal": 0, "Fast": 15, "Very Fast": 25
175
- }
176
 
177
- predicted_score = base_score + adjustments[venue] + adjustments[toss] + \
178
- (players_available * 5) + adjustments[pitch_condition]
179
-
180
- st.success(f"**Predicted Score Range**: {predicted_score-15} - {predicted_score+15}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
- # Show factors affecting prediction
183
- st.subheader("Key Factors Considered")
184
- factors = pd.DataFrame({
185
- "Factor": ["Venue", "Toss", "Players Available", "Pitch Condition"],
186
- "Impact": [
187
- f"{'+' if adjustments[venue] > 0 else ''}{adjustments[venue]}",
188
- f"{'+' if adjustments[toss] > 0 else ''}{adjustments[toss]}",
189
- f"+{players_available * 5}",
190
- f"{'+' if adjustments[pitch_condition] > 0 else ''}{adjustments[pitch_condition]}"
191
- ]
192
- })
193
- st.dataframe(factors.set_index("Factor"))
194
 
195
- def show_winner_prediction():
196
- st.header("🏆 Match Winner Prediction")
197
-
198
- col1, col2 = st.columns(2)
199
-
200
- with col1:
201
- team_a = st.selectbox("Team A", df['Player_Team'].unique())
202
- team_a_form = st.slider(f"{team_a} Recent Form (1-10)", 1, 10, 7)
203
- team_a_key_players = st.multiselect(
204
- f"{team_a} Key Players",
205
- df[df['Player_Team'] == team_a]['Player'].unique()
206
- )
207
-
208
- with col2:
209
- team_b = st.selectbox("Team B", df['Player_Team'].unique(), index=1)
210
- team_b_form = st.slider(f"{team_b} Recent Form (1-10)", 1, 10, 6)
211
- team_b_key_players = st.multiselect(
212
- f"{team_b} Key Players",
213
- df[df['Player_Team'] == team_b]['Player'].unique()
214
- )
215
-
216
- # Additional factors
217
- venue = st.selectbox("Match Venue", ["Home", "Neutral", "Away"])
218
- toss_winner = st.radio("Toss Winner", [team_a, team_b])
219
- pitch_type = st.selectbox("Pitch Type", ["Batting", "Bowling", "Balanced"])
220
-
221
- if st.button("Predict Winner"):
222
- # Placeholder for actual model prediction
223
- team_a_score = team_a_form * 10 + len(team_a_key_players) * 5
224
- team_b_score = team_b_form * 10 + len(team_b_key_players) * 5
 
 
 
 
 
 
 
225
 
226
- # Adjustments
227
- if venue == "Home":
228
- team_a_score += 15
229
- elif venue == "Away":
230
- team_b_score += 15
231
 
232
- if toss_winner == team_a:
233
- team_a_score += 10
234
- else:
235
- team_b_score += 10
 
 
 
 
 
236
 
237
- if pitch_type == "Batting":
238
- team_a_score += 5 if team_a == "India" else 0 # Example bias
239
- elif pitch_type == "Bowling":
240
- team_b_score += 5 if team_b == "Australia" else 0
241
-
242
- # Display result
243
- if team_a_score > team_b_score:
244
- st.success(f"**Predicted Winner**: {team_a} (Confidence: {team_a_score/(team_a_score+team_b_score)*100:.1f}%)")
245
  else:
246
- st.success(f"**Predicted Winner**: {team_b} (Confidence: {team_b_score/(team_a_score+team_b_score)*100:.1f}%)")
247
-
248
- # Show comparison
249
- fig = px.bar(
250
- x=[team_a, team_b],
251
- y=[team_a_score, team_b_score],
252
- title="Team Comparison Score"
253
- )
254
- st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
- # 5. MAIN APP FUNCTION (DEFINED AFTER ALL PAGE FUNCTIONS)
257
- def main():
258
- st.title("🏏 Cricket Analytics Dashboard")
259
- st.markdown("""
260
- Explore player statistics, compare teams, and predict match outcomes using advanced analytics.
261
- """)
262
-
263
- # Sidebar navigation
264
- st.sidebar.header("Navigation")
265
- app_mode = st.sidebar.selectbox("Choose Analysis Mode", [
266
- "📊 Player Statistics",
267
- "🆚 Player Comparison",
268
- "🏴 Team Comparison",
269
- "🔮 Score Predictor",
270
- "🏆 Match Winner Prediction"
271
- ])
272
-
273
- # Page routing
274
- if app_mode == "📊 Player Statistics":
275
- show_player_stats()
276
- elif app_mode == "🆚 Player Comparison":
277
- show_player_comparison()
278
- elif app_mode == "🏴 Team Comparison":
279
- show_team_comparison()
280
- elif app_mode == "🔮 Score Predictor":
281
- show_score_predictor()
282
- elif app_mode == "🏆 Match Winner Prediction":
283
- show_winner_prediction()
284
 
285
- # 6. RUN THE APP
286
- if __name__ == "__main__":
287
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
 
 
 
 
3
  import requests
4
+ import os
5
+ from PIL import Image
6
+ import io
7
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Initialize session state
10
+ if 'local_db' not in st.session_state:
11
+ st.session_state.local_db = pd.DataFrame(columns=['Player', 'ID', 'Type', 'Format', 'Stats'])
12
 
13
+ class CricketStatsApp:
14
+ def __init__(self):
15
+ self.api_key = os.getenv("RAPIDAPI_KEY") or "your-api-key-here"
16
+ self.headers = {
17
+ "x-rapidapi-key": self.api_key,
18
+ "x-rapidapi-host": "cricbuzz-cricket.p.rapidapi.com"
19
+ }
20
+
21
+ def search_local_db(self, player_name):
22
+ """Search for player in local database"""
23
+ if not st.session_state.local_db.empty:
24
+ return st.session_state.local_db[
25
+ st.session_state.local_db['Player'].str.contains(player_name, case=False)
26
+ ]
27
+ return pd.DataFrame()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ def fetch_from_api(self, player_name):
30
+ """Fetch player data from API"""
31
+ search_url = "https://cricbuzz-cricket2.p.rapidapi.com/stats/v1/player/search"
32
+ params = {"plrN": player_name}
33
+
34
+ try:
35
+ response = requests.get(search_url, headers=self.headers, params=params)
36
+ if response.status_code == 200:
37
+ data = response.json()
38
+ if data.get('player'):
39
+ return data['player'][0] # Return first match
40
+ except Exception as e:
41
+ st.error(f"API Error: {e}")
42
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ def get_player_stats(self, player_id, stat_type="batting"):
45
+ """Get specific stats for a player"""
46
+ stats_url = f"https://cricbuzz-cricket.p.rapidapi.com/stats/v1/player/{player_id}/{stat_type}"
47
+ try:
48
+ response = requests.get(stats_url, headers=self.headers)
49
+ if response.status_code == 200:
50
+ return response.json()
51
+ except Exception as e:
52
+ st.error(f"Stats API Error: {e}")
53
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ def process_stats(self, raw_stats):
56
+ """Process raw stats into display format"""
57
+ formats = raw_stats.get('headers', [])[1:]
58
+ stats_values = raw_stats.get('values', [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ processed = {}
61
+ for stat in stats_values:
62
+ category = stat['values'][0]
63
+ for i, fmt in enumerate(formats, start=1):
64
+ if fmt not in processed:
65
+ processed[fmt] = {}
66
+ processed[fmt][category] = stat['values'][i]
67
+ return processed
68
+
69
+ def update_local_db(self, player_info, stats_data):
70
+ """Add new player data to local database"""
71
+ new_rows = []
72
+ for stat_type in ['batting', 'bowling']:
73
+ if stat_type in stats_data:
74
+ processed = self.process_stats(stats_data[stat_type])
75
+ for fmt, stats in processed.items():
76
+ new_rows.append({
77
+ 'Player': player_info['name'],
78
+ 'ID': player_info['id'],
79
+ 'Type': stat_type,
80
+ 'Format': fmt,
81
+ 'Stats': str(stats)
82
+ })
83
 
84
+ if new_rows:
85
+ new_df = pd.DataFrame(new_rows)
86
+ st.session_state.local_db = pd.concat([st.session_state.local_db, new_df], ignore_index=True)
87
+ return True
88
+ return False
 
 
 
 
 
 
 
89
 
90
+ def display_stats(self, stats):
91
+ """Display stats in Streamlit"""
92
+ for format_type, stats in stats.items():
93
+ with st.expander(f"{format_type} Statistics"):
94
+ df = pd.DataFrame.from_dict(stats, orient='index', columns=['Value'])
95
+ st.dataframe(df.style.highlight_max(axis=0))
96
+
97
+ def get_player_image(self, image_url):
98
+ """Fetch and display player image"""
99
+ try:
100
+ response = requests.get(image_url)
101
+ img = Image.open(io.BytesIO(response.content))
102
+ st.image(img, caption="Player Image", width=200)
103
+ except:
104
+ st.warning("Could not load player image")
105
+
106
+ # Create app instance
107
+ app = CricketStatsApp()
108
+
109
+ # Streamlit UI
110
+ st.title("🏏 Cricket Player Stats Explorer")
111
+ st.markdown("""
112
+ Search for any international cricket player to view their statistics.
113
+ The app will first check local database before making API calls.
114
+ """)
115
+
116
+ # Search section
117
+ col1, col2 = st.columns([3, 1])
118
+ with col1:
119
+ player_query = st.text_input("Enter player name:", placeholder="e.g. Virat Kohli")
120
+ with col2:
121
+ stat_type = st.selectbox("Stat Type", ["batting", "bowling"], index=0)
122
+
123
+ if player_query:
124
+ with st.spinner("Searching for player..."):
125
+ # First check local database
126
+ local_results = app.search_local_db(player_query)
127
 
128
+ if not local_results.empty:
129
+ st.success("Found in local database!")
130
+ player_name = local_results.iloc[0]['Player']
131
+ player_id = local_results.iloc[0]['ID']
 
132
 
133
+ # Get all stats for this player from local DB
134
+ player_stats = {}
135
+ for _, row in local_results.iterrows():
136
+ if row['Format'] not in player_stats:
137
+ player_stats[row['Format']] = {}
138
+ player_stats[row['Format']].update(eval(row['Stats']))
139
+
140
+ st.subheader(f"Player: {player_name}")
141
+ app.display_stats(player_stats)
142
 
 
 
 
 
 
 
 
 
143
  else:
144
+ # Fall back to API
145
+ st.info("Not found locally, checking API...")
146
+ player_info = app.fetch_from_api(player_query)
147
+
148
+ if player_info:
149
+ st.success(f"Found: {player_info['name']}")
150
+
151
+ # Get stats from API
152
+ with st.spinner(f"Fetching {stat_type} stats..."):
153
+ stats_data = {stat_type: app.get_player_stats(player_info['id'], stat_type)}
154
+
155
+ if stats_data[stat_type]:
156
+ # Update local database
157
+ if app.update_local_db(player_info, stats_data):
158
+ st.success("Added to local database!")
159
+
160
+ # Display results
161
+ st.subheader(f"Player: {player_info['name']}")
162
+
163
+ # Show image if available
164
+ if 'imageUrl' in player_info:
165
+ app.get_player_image(player_info['imageUrl'])
166
+
167
+ # Process and display stats
168
+ processed_stats = app.process_stats(stats_data[stat_type])
169
+ app.display_stats(processed_stats)
170
+ else:
171
+ st.error("Could not fetch player stats")
172
+ else:
173
+ st.error("Player not found in API")
174
 
175
+ # Show local database in expander
176
+ with st.expander("Show Local Database"):
177
+ st.dataframe(st.session_state.local_db)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ # Add some sample players if database is empty
180
+ if st.session_state.local_db.empty:
181
+ if st.button("Load Sample Players"):
182
+ sample_data = {
183
+ 'Player': ['Virat Kohli', 'MS Dhoni', 'Jasprit Bumrah'],
184
+ 'ID': ['1413', '28081', '625383'],
185
+ 'Type': ['batting', 'batting', 'bowling'],
186
+ 'Format': ['ODI', 'ODI', 'Test'],
187
+ 'Stats': [str({'Runs': '12898', 'Avg': '57.32'}),
188
+ str({'Runs': '10773', 'Avg': '50.58'}),
189
+ str({'Wickets': '128', 'Avg': '21.99'})]
190
+ }
191
+ st.session_state.local_db = pd.DataFrame(sample_data)
192
+ st.success("Added sample players!")