Mpavan45 commited on
Commit
a0a40ba
·
verified ·
1 Parent(s): 25dfd95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -124
app.py CHANGED
@@ -1,83 +1,123 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
 
4
  from PIL import Image
5
  import os
6
  from langchain_google_genai import GoogleGenerativeAI
7
  from langchain_core.prompts import ChatPromptTemplate
8
  from langchain_core.output_parsers import StrOutputParser
 
9
 
10
  # Set page config
 
11
 
12
- st.set_page_config(page_title="🏏 Ultimate Cricket Analytics", layout="wide")
13
- # Define the URL of the background image (use your own image URL)
14
-
15
- # ---- Background Styling ----
16
- background_image_url = "https://cdn-uploads.huggingface.co/production/uploads/675fab3a2d0851e23d23cad3/zNRb7r4eec-FQ0LUfJLfW.jpeg" # You can replace with any other beautiful cricket image
17
-
18
  st.markdown(
19
- f"""
20
  <style>
21
- .stApp {{
22
- background-image: url("{background_image_url}");
23
  background-size: cover;
24
  background-repeat: no-repeat;
25
  background-attachment: fixed;
26
- }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  </style>
28
  """,
29
  unsafe_allow_html=True
30
  )
31
 
32
  # ---- Sidebar ----
33
- option = st.sidebar.selectbox(
34
- "Choose Option",
35
- ["Main Page", "Team Info", "Team Stats Comparison", "Player Stats", "Player Comparison"],
36
- index=0 # Set "Main Page" as the default option
37
- )
 
 
 
38
 
39
  # ---- Main Page ----
40
  if option == "Main Page":
41
  st.markdown(
42
  """
43
- <div style="text-align: center; padding-top: 100px;">
44
- <h1 style="font-size: 64px; color: #ffcc00; font-weight: bold;">🏏 Ultimate Cricket Analytics</h1>
45
- <h3 style="font-size: 28px; color: #4caf50;">Dive deep into the world of cricket with powerful data-driven insights!</h3>
 
 
46
  <br>
47
- <img src="https://www.wallpapertip.com/wpic/mwiJbR_cricket-stadium-wallpaper-hd/" width="400">
48
  <br><br>
49
- <p style="font-size: 20px; color: white;">Select an option from the sidebar to begin your cricket journey! 🧠📊</p>
 
 
50
  </div>
51
  """,
52
  unsafe_allow_html=True
53
  )
54
 
55
-
56
  # Create a folder to save CSVs if not exists
57
  data_folder = "data"
58
  os.makedirs(data_folder, exist_ok=True)
59
 
60
- # Load all three formats
61
  odi_df = pd.read_csv("odi.xls")
62
  t20_df = pd.read_csv("t20.xls")
63
  test_df = pd.read_csv("test.xls")
64
-
65
  test_teams_df = pd.read_csv("test-teams.xls")
66
  odi_teams_df = pd.read_csv("odi-teams.xls")
67
  t20_teams_df = pd.read_csv("t20-teams.xls")
68
-
69
- # Load CSV files
70
  batting_df = pd.read_csv("Batting_10_Teams_Final.csv")
71
  bowling_df = pd.read_csv("Bowling_10_Teams_Final.csv")
72
 
73
- # # Sidebar Navigation
74
- # st.sidebar.title("Navigation Panel")
75
- # option = st.sidebar.selectbox("Choose Option", [
76
- # "Team Info",
77
- # "Team Stats Comparison",
78
- # "Player Stats",
79
- # "Player Comparison"
80
- # ])
81
 
82
  # Sidebar UI based on selection
83
  team_info = selected_teams_stats = selected_format = None
@@ -88,7 +128,7 @@ if option == "Team Info":
88
  team_info = st.sidebar.selectbox("Select Team", sorted(batting_df['Country'].unique()))
89
 
90
  elif option == "Team Stats Comparison":
91
- num_teams = st.sidebar.selectbox("Select Number of Teams",[2,3])
92
  selected_teams_stats = st.sidebar.multiselect("Select Teams", sorted(batting_df['Country'].unique()), max_selections=num_teams)
93
  selected_format = st.sidebar.selectbox("Select Format", ["ODI", "T20", "Test"])
94
 
@@ -104,57 +144,70 @@ elif option == "Player Comparison":
104
  player1 = st.sidebar.selectbox("Select Player 1", all_players)
105
  player2 = st.sidebar.selectbox("Select Player 2", [p for p in all_players if p != player1])
106
 
107
-
108
- # Load GenAI
109
- api_key = st.secrets.get('genai_key')
110
- model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
111
- out_par = StrOutputParser()
112
-
113
  # ---- Main Content ----
114
  if option == "Team Info" and team_info:
115
- st.title(f"Team Bio - {team_info}")
116
  team_prompt = ChatPromptTemplate.from_messages([
117
  ("system",
118
- '''You are an AI cricket historian.Give the text in the black color. First, provide a brief overview of the team and its history.
119
-
120
  Then, provide a 'Debut Details' section with the following format:
121
  - Add a heading **Debut Details**
122
  - Under that, use subheadings **Test Debut**, **ODI Debut**, and **T20 Debut**
123
  - For each debut format, include:
124
- - Opponent team
125
- - Date of debut
126
- - Stadium or venue
127
  Ensure a clear structure with headings and subheadings. Do not include performance stats.'''),
128
  ("human", "{team_name}")
129
  ])
130
  team_chain = team_prompt | model | out_par
 
131
  st.write(team_chain.invoke({"team_name": team_info}))
 
132
 
133
  # Combine all formats
134
  odi_teams_df['Format'] = 'ODI'
135
  t20_teams_df['Format'] = 'T20'
136
- test_teams_df ['Format'] = 'Test'
137
  combined_stats_df = pd.concat([odi_teams_df, t20_teams_df, test_teams_df], ignore_index=True)
138
 
139
  # Show format-wise stats for selected team
140
- st.subheader(f"{team_info} Format-wise Statistics")
141
  team_stats = combined_stats_df[combined_stats_df['Team'] == team_info]
142
- st.dataframe(team_stats.reset_index(drop=True))
143
- st.subheader(f"{team_info} Format-wise Statistics")
 
144
 
145
  if st.button("Show Format-wise Visualizations"):
146
- st.plotly_chart(px.bar(team_stats, x='Format', y='Mat', color='Format', title="Matches by Format"))
147
- st.plotly_chart(px.pie(team_stats, values='Won', names='Format', title="Win Distribution by Format"))
148
- st.plotly_chart(px.line(team_stats, x='Format', y='W/L', title="Win/Loss Ratio by Format"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
- # if st.button("Show Raw Data"):
151
- # st.dataframe(team_stats.reset_index(drop=True))
152
-
153
-
154
- # 3. Team Stats Comparison
155
  elif option == "Team Stats Comparison" and selected_teams_stats:
156
- st.title("Team Stats Comparison")
157
-
158
  odi_df['Format'] = 'ODI'
159
  t20_df['Format'] = 'T20'
160
  test_df['Format'] = 'Test'
@@ -175,76 +228,117 @@ elif option == "Team Stats Comparison" and selected_teams_stats:
175
  }
176
  stat_choice = st.selectbox("Select Stat to Compare", list(stat_options.keys()), format_func=lambda x: stat_options[x])
177
 
178
- st.subheader("Bar Chart")
 
 
179
  fig = px.bar(
180
  selected_data,
181
  x='Team',
182
  y=stat_choice,
183
  color='Team',
184
  barmode='group',
185
- title=f"{stat_options[stat_choice]} by Team in {selected_format}"
 
186
  )
 
187
  st.plotly_chart(fig, use_container_width=True)
188
 
189
- # Type 2: Win % Pie Chart
190
- st.subheader("Win Percentage Pie Chart")
191
  pie_data = selected_data[['Team', '%W']]
192
- fig_pie = px.pie(pie_data, values='%W', names='Team', title='Win % Comparison')
193
- st.plotly_chart(fig_pie)
194
-
195
- # Type 3: Stacked Bar Chart (Won + Lost + Draw)
196
- st.subheader("Stacked Bar Chart (Won, Lost, Draw)")
197
- stack_df = selected_data[['Team', 'Won', 'Lost', 'Draw']]
198
- stack_df = stack_df.melt(id_vars='Team', var_name='Result', value_name='Count')
199
- fig_stack = px.bar(stack_df, x='Team', y='Count', color='Result', barmode='stack')
200
- st.plotly_chart(fig_stack)
 
 
 
201
 
202
  if st.button("Show Raw Data"):
203
- st.dataframe(selected_data.reset_index(drop=True))
204
-
 
205
 
206
  elif option == "Player Stats" and selected_player:
207
- st.title(f"Player Dashboard - {selected_player}")
208
 
209
  player_batting = batting_df[(batting_df['player_name'] == selected_player) & (batting_df['Country'] == selected_team)]
210
  player_bowling = bowling_df[(bowling_df['player_name'] == selected_player) & (bowling_df['Country'] == selected_team)]
211
 
212
  prompt = ChatPromptTemplate.from_messages([
213
  ("system", '''You are an AI cricket player information provider. Display the player's complete bio data in a
214
- detailed table format with rows and columns, including personal information. Below the table,
215
- include debut details for all formats. Additionally, provide a brief description of the player
216
- underneath. Only include player information, not their performance statistics.Give the text in the black color'''),
217
  ("human", "{player_name}")
218
  ])
219
  chain = prompt | model | out_par
 
220
  st.write(chain.invoke({"player_name": selected_player}))
221
-
222
- if st.button("Show Batting Card"):
223
- st.dataframe(player_batting.iloc[:, :16])
224
- if st.button("Show Bowling Card"):
225
- st.dataframe(player_bowling.iloc[:, :15])
 
 
 
 
 
 
 
 
226
 
227
  if not player_batting.empty:
228
- st.subheader("Batting Visualizations")
 
229
  col1, col2 = st.columns(2)
230
  with col1:
231
- st.plotly_chart(px.bar(player_batting, x='Format', y='Runs', color='Format'))
 
 
 
232
  with col2:
233
- st.plotly_chart(px.line(player_batting, x='Format', y='SR'))
234
- st.plotly_chart(px.pie(player_batting, values='Runs', names='Format'))
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
  if not player_bowling.empty:
237
- st.subheader("Bowling Visualizations")
 
238
  col3, col4 = st.columns(2)
239
  with col3:
240
- st.plotly_chart(px.bar(player_bowling, x='Format', y='Wickets', color='Format'))
 
 
 
241
  with col4:
242
- st.plotly_chart(px.line(player_bowling, x='Format', y='Eco'))
243
- st.plotly_chart(px.pie(player_bowling, values='Wickets', names='Format'))
 
 
 
 
 
244
 
245
- # 4. Player Comparison
246
  elif option == "Player Comparison" and player1 and player2:
247
- st.title(f"Player Comparison: {player1} vs {player2}")
248
 
249
  def get_player_data(name):
250
  return (
@@ -255,42 +349,56 @@ elif option == "Player Comparison" and player1 and player2:
255
  bat1, bowl1 = get_player_data(player1)
256
  bat2, bowl2 = get_player_data(player2)
257
 
258
- # Type 1: Batting Line Chart
259
- st.subheader("Batting Line Chart")
260
- bat_combined = pd.concat([bat1, bat2])
261
- fig_bat_line = px.line(bat_combined, x='Format', y='Runs', color='player_name', markers=True)
262
- st.plotly_chart(fig_bat_line)
263
-
264
- # Type 2: Bowling Line Chart
265
- st.subheader("Bowling Line Chart")
 
 
 
 
 
 
 
 
 
266
  bowl_combined = pd.concat([bowl1, bowl2])
267
- fig_bowl_line = px.line(bowl_combined, x='Format', y='Wickets', color='player_name', markers=True)
268
- st.plotly_chart(fig_bowl_line)
269
-
270
- # Batting Bar Chart
271
- st.subheader("🔹 Type 1: Batting Bar Chart")
272
- bat_combined = pd.DataFrame({
273
- 'Player': [player1, player2],
274
- 'Total Runs': [bat1['Runs'].sum(), bat2['Runs'].sum()],
275
- 'Batting Average': [bat1['Ave'].dropna().mean(), bat2['Ave'].dropna().mean()],
276
- 'Strike Rate': [bat1['SR'].mean(), bat2['SR'].mean()],
277
- 'Matches': [bat1['Mat'].sum(), bat2['Mat'].sum()]
278
- })
279
-
280
- bat_melted = bat_combined.melt(id_vars='Player', var_name='Stat', value_name='Value')
281
- fig_bat_bar = px.bar(bat_melted, x='Player', y='Value', color='Stat', barmode='group')
282
- st.plotly_chart(fig_bat_bar)
283
-
284
- # Add a Pie Chart for Total Runs Comparison
285
- st.subheader("🔹 Total Runs Comparison (Pie Chart)")
286
  total_runs = [bat1['Runs'].sum(), bat2['Runs'].sum()]
287
  runs_data = pd.DataFrame({
288
  'Player': [player1, player2],
289
  'Total Runs': total_runs
290
  })
 
 
 
 
291
 
292
- fig_pie = px.pie(runs_data, names='Player', values='Total Runs', title="Proportion of Total Runs")
293
- st.plotly_chart(fig_pie)
 
 
 
 
 
 
 
 
 
 
294
 
295
  if st.button("Show Raw Stats"):
296
- st.dataframe(pd.concat([bat1, bowl1, bat2, bowl2]))
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
4
+ import plotly.graph_objects as go
5
  from PIL import Image
6
  import os
7
  from langchain_google_genai import GoogleGenerativeAI
8
  from langchain_core.prompts import ChatPromptTemplate
9
  from langchain_core.output_parsers import StrOutputParser
10
+ import uuid
11
 
12
  # Set page config
13
+ st.set_page_config(page_title="🏏 Ultimate Cricket Analytics", layout="wide", initial_sidebar_state="expanded")
14
 
15
+ # ---- Custom CSS for Styling ----
 
 
 
 
 
16
  st.markdown(
17
+ """
18
  <style>
19
+ .stApp {
20
+ background-image: url("https://cdn-uploads.huggingface.co/production/uploads/675fab3a2d0851e23d23cad3/zNRb7r4eec-FQ0LUfJLfW.jpeg");
21
  background-size: cover;
22
  background-repeat: no-repeat;
23
  background-attachment: fixed;
24
+ background-color: rgba(0, 0, 0, 0.5); /* Subtle overlay */
25
+ color: #ffffff;
26
+ }
27
+ .sidebar .sidebar-content {
28
+ background: linear-gradient(180deg, #1e3c72, #2a5298);
29
+ border-radius: 10px;
30
+ padding: 20px;
31
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
32
+ }
33
+ h1 {
34
+ color: #ffcc00;
35
+ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
36
+ font-size: 48px;
37
+ text-align: center;
38
+ }
39
+ h2 {
40
+ color: #4caf50;
41
+ font-size: 32px;
42
+ margin-top: 20px;
43
+ }
44
+ h3 {
45
+ color: #ff5733;
46
+ font-size: 24px;
47
+ }
48
+ .stButton>button {
49
+ background-color: #ff5733;
50
+ color: white;
51
+ border-radius: 8px;
52
+ padding: 10px 20px;
53
+ font-weight: bold;
54
+ transition: all 0.3s ease;
55
+ }
56
+ .stButton>button:hover {
57
+ background-color: #c70039;
58
+ transform: scale(1.05);
59
+ }
60
+ .card {
61
+ background-color: rgba(255, 255, 255, 0.9);
62
+ border-radius: 10px;
63
+ padding: 20px;
64
+ margin: 10px 0;
65
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
66
+ color: #333;
67
+ }
68
  </style>
69
  """,
70
  unsafe_allow_html=True
71
  )
72
 
73
  # ---- Sidebar ----
74
+ with st.sidebar:
75
+ st.markdown("<h2 style='color: #ffcc00;'>Cricket Analytics Hub</h2>", unsafe_allow_html=True)
76
+ option = st.selectbox(
77
+ "Choose Option",
78
+ ["Main Page", "Team Info", "Team Stats Comparison", "Player Stats", "Player Comparison"],
79
+ index=0,
80
+ format_func=lambda x: f"🏏 {x}"
81
+ )
82
 
83
  # ---- Main Page ----
84
  if option == "Main Page":
85
  st.markdown(
86
  """
87
+ <div style="text-align: center; padding: 50px;">
88
+ <h1 style="background: linear-gradient(45deg, #ffcc00, #ff5733); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
89
+ 🏏 Ultimate Cricket Analytics
90
+ </h1>
91
+ <h3 style="color: #4caf50;">Unleash the Power of Cricket Data!</h3>
92
  <br>
93
+ <img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjZ0d3J3eTB2Z3M4b2F2eHl0Y3I0c2x5c3A4YzR2c2JpdnZ6c3VqZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3o7aD2vNtfVly3p3qM/giphy.gif" width="400">
94
  <br><br>
95
+ <p style="font-size: 20px; color: white; background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 8px;">
96
+ Select an option from the sidebar to explore cricket insights! 📊🔥
97
+ </p>
98
  </div>
99
  """,
100
  unsafe_allow_html=True
101
  )
102
 
 
103
  # Create a folder to save CSVs if not exists
104
  data_folder = "data"
105
  os.makedirs(data_folder, exist_ok=True)
106
 
107
+ # Load data (assuming files are available)
108
  odi_df = pd.read_csv("odi.xls")
109
  t20_df = pd.read_csv("t20.xls")
110
  test_df = pd.read_csv("test.xls")
 
111
  test_teams_df = pd.read_csv("test-teams.xls")
112
  odi_teams_df = pd.read_csv("odi-teams.xls")
113
  t20_teams_df = pd.read_csv("t20-teams.xls")
 
 
114
  batting_df = pd.read_csv("Batting_10_Teams_Final.csv")
115
  bowling_df = pd.read_csv("Bowling_10_Teams_Final.csv")
116
 
117
+ # Load GenAI
118
+ api_key = st.secrets.get('genai_key')
119
+ model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
120
+ out_par = StrOutputParser()
 
 
 
 
121
 
122
  # Sidebar UI based on selection
123
  team_info = selected_teams_stats = selected_format = None
 
128
  team_info = st.sidebar.selectbox("Select Team", sorted(batting_df['Country'].unique()))
129
 
130
  elif option == "Team Stats Comparison":
131
+ num_teams = st.sidebar.selectbox("Select Number of Teams", [2, 3])
132
  selected_teams_stats = st.sidebar.multiselect("Select Teams", sorted(batting_df['Country'].unique()), max_selections=num_teams)
133
  selected_format = st.sidebar.selectbox("Select Format", ["ODI", "T20", "Test"])
134
 
 
144
  player1 = st.sidebar.selectbox("Select Player 1", all_players)
145
  player2 = st.sidebar.selectbox("Select Player 2", [p for p in all_players if p != player1])
146
 
 
 
 
 
 
 
147
  # ---- Main Content ----
148
  if option == "Team Info" and team_info:
149
+ st.markdown(f"<h1>Team Bio - {team_info}</h1>", unsafe_allow_html=True)
150
  team_prompt = ChatPromptTemplate.from_messages([
151
  ("system",
152
+ '''You are an AI cricket historian. Provide a brief overview of the team and its history in black text.
 
153
  Then, provide a 'Debut Details' section with the following format:
154
  - Add a heading **Debut Details**
155
  - Under that, use subheadings **Test Debut**, **ODI Debut**, and **T20 Debut**
156
  - For each debut format, include:
157
+ - Opponent team
158
+ - Date of debut
159
+ - Stadium or venue
160
  Ensure a clear structure with headings and subheadings. Do not include performance stats.'''),
161
  ("human", "{team_name}")
162
  ])
163
  team_chain = team_prompt | model | out_par
164
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
165
  st.write(team_chain.invoke({"team_name": team_info}))
166
+ st.markdown("</div>", unsafe_allow_html=True)
167
 
168
  # Combine all formats
169
  odi_teams_df['Format'] = 'ODI'
170
  t20_teams_df['Format'] = 'T20'
171
+ test_teams_df['Format'] = 'Test'
172
  combined_stats_df = pd.concat([odi_teams_df, t20_teams_df, test_teams_df], ignore_index=True)
173
 
174
  # Show format-wise stats for selected team
175
+ st.markdown(f"<h2>{team_info} Format-wise Statistics</h2>", unsafe_allow_html=True)
176
  team_stats = combined_stats_df[combined_stats_df['Team'] == team_info]
177
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
178
+ st.dataframe(team_stats.reset_index(drop=True), use_container_width=True)
179
+ st.markdown("</div>", unsafe_allow_html=True)
180
 
181
  if st.button("Show Format-wise Visualizations"):
182
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
183
+ # Bar Chart
184
+ fig_bar = px.bar(team_stats, x='Format', y='Mat', color='Format', title="Matches by Format",
185
+ color_discrete_sequence=px.colors.qualitative.Vivid)
186
+ fig_bar.update_layout(transition_duration=500)
187
+ st.plotly_chart(fig_bar, use_container_width=True)
188
+
189
+ # Donut Chart
190
+ fig_donut = px.pie(team_stats, values='Won', names='Format', title="Win Distribution by Format",
191
+ hole=0.4, color_discrete_sequence=px.colors.qualitative.Bold)
192
+ fig_donut.update_traces(textinfo='percent+label', pull=[0.1, 0, 0])
193
+ st.plotly_chart(fig_donut, use_container_width=True)
194
+
195
+ # Radar Chart
196
+ fig_radar = go.Figure()
197
+ for _, row in team_stats.iterrows():
198
+ fig_radar.add_trace(go.Scatterpolar(
199
+ r=[row['Mat'], row['Won'], row['Lost'], row['W/L']],
200
+ theta=['Matches', 'Wins', 'Losses', 'W/L Ratio'],
201
+ fill='toself',
202
+ name=row['Format']
203
+ ))
204
+ fig_radar.update_layout(polar=dict(radialaxis=dict(visible=True)), showlegend=True, title="Format-wise Radar")
205
+ st.plotly_chart(fig_radar, use_container_width=True)
206
+ st.markdown("</div>", unsafe_allow_html=True)
207
 
 
 
 
 
 
208
  elif option == "Team Stats Comparison" and selected_teams_stats:
209
+ st.markdown("<h1>Team Stats Comparison</h1>", unsafe_allow_html=True)
210
+
211
  odi_df['Format'] = 'ODI'
212
  t20_df['Format'] = 'T20'
213
  test_df['Format'] = 'Test'
 
228
  }
229
  stat_choice = st.selectbox("Select Stat to Compare", list(stat_options.keys()), format_func=lambda x: stat_options[x])
230
 
231
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
232
+ # Bar Chart
233
+ st.markdown("<h3>Comparison Bar Chart</h3>", unsafe_allow_html=True)
234
  fig = px.bar(
235
  selected_data,
236
  x='Team',
237
  y=stat_choice,
238
  color='Team',
239
  barmode='group',
240
+ title=f"{stat_options[stat_choice]} by Team in {selected_format}",
241
+ color_discrete_sequence=px.colors.qualitative.Set2
242
  )
243
+ fig.update_layout(transition_duration=500)
244
  st.plotly_chart(fig, use_container_width=True)
245
 
246
+ # Donut Chart
247
+ st.markdown("<h3>Win Percentage Donut Chart</h3>", unsafe_allow_html=True)
248
  pie_data = selected_data[['Team', '%W']]
249
+ fig_pie = px.pie(pie_data, values='%W', names='Team', title='Win % Comparison',
250
+ hole=0.4, color_discrete_sequence=px.colors.qualitative.Pastel)
251
+ fig_pie.update_traces(textinfo='percent+label', pull=[0.1, 0])
252
+ st.plotly_chart(fig_pie, use_container_width=True)
253
+
254
+ # Heatmap
255
+ st.markdown("<h3>Performance Heatmap</h3>", unsafe_allow_html=True)
256
+ heatmap_data = selected_data[['Team', 'Mat', 'Won', 'Lost', 'Draw']].set_index('Team')
257
+ fig_heatmap = px.imshow(heatmap_data, text_auto=True, aspect="auto",
258
+ color_continuous_scale='Viridis', title="Team Stats Heatmap")
259
+ st.plotly_chart(fig_heatmap, use_container_width=True)
260
+ st.markdown("</div>", unsafe_allow_html=True)
261
 
262
  if st.button("Show Raw Data"):
263
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
264
+ st.dataframe(selected_data.reset_index(drop=True), use_container_width=True)
265
+ st.markdown("</div>", unsafe_allow_html=True)
266
 
267
  elif option == "Player Stats" and selected_player:
268
+ st.markdown(f"<h1>Player Dashboard - {selected_player}</h1>", unsafe_allow_html=True)
269
 
270
  player_batting = batting_df[(batting_df['player_name'] == selected_player) & (batting_df['Country'] == selected_team)]
271
  player_bowling = bowling_df[(bowling_df['player_name'] == selected_player) & (bowling_df['Country'] == selected_team)]
272
 
273
  prompt = ChatPromptTemplate.from_messages([
274
  ("system", '''You are an AI cricket player information provider. Display the player's complete bio data in a
275
+ detailed table format with rows and columns, including personal information in black text.
276
+ Below the table, include debut details for all formats. Additionally, provide a brief description
277
+ of the player underneath. Only include player information, not their performance statistics.'''),
278
  ("human", "{player_name}")
279
  ])
280
  chain = prompt | model | out_par
281
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
282
  st.write(chain.invoke({"player_name": selected_player}))
283
+ st.markdown("</div>", unsafe_allow_html=True)
284
+
285
+ col1, col2 = st.columns(2)
286
+ with col1:
287
+ if st.button("Show Batting Card"):
288
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
289
+ st.dataframe(player_batting.iloc[:, :16], use_container_width=True)
290
+ st.markdown("</div>", unsafe_allow_html=True)
291
+ with col2:
292
+ if st.button("Show Bowling Card"):
293
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
294
+ st.dataframe(player_bowling.iloc[:, :15], use_container_width=True)
295
+ st.markdown("</div>", unsafe_allow_html=True)
296
 
297
  if not player_batting.empty:
298
+ st.markdown("<h2>Batting Visualizations</h2>", unsafe_allow_html=True)
299
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
300
  col1, col2 = st.columns(2)
301
  with col1:
302
+ fig_bar = px.bar(player_batting, x='Format', y='Runs', color='Format',
303
+ title="Runs by Format", color_discrete_sequence=px.colors.qualitative.D3)
304
+ fig_bar.update_layout(transition_duration=500)
305
+ st.plotly_chart(fig_bar, use_container_width=True)
306
  with col2:
307
+ fig_radar = go.Figure()
308
+ fig_radar.add_trace(go.Scatterpolar(
309
+ r=[player_batting['Runs'].mean(), player_batting['SR'].mean(), player_batting['Ave'].mean()],
310
+ theta=['Runs', 'Strike Rate', 'Average'],
311
+ fill='toself',
312
+ name='Batting Stats'
313
+ ))
314
+ fig_radar.update_layout(polar=dict(radialaxis=dict(visible=True)), showlegend=True, title="Batting Radar")
315
+ st.plotly_chart(fig_radar, use_container_width=True)
316
+ fig_donut = px.pie(player_batting, values='Runs', names='Format', title="Runs Distribution",
317
+ hole=0.4, color_discrete_sequence=px.colors.qualitative.T10)
318
+ fig_donut.update_traces(textinfo='percent+label')
319
+ st.plotly_chart(fig_donut, use_container_width=True)
320
+ st.markdown("</div>", unsafe_allow_html=True)
321
 
322
  if not player_bowling.empty:
323
+ st.markdown("<h2>Bowling Visualizations</h2>", unsafe_allow_html=True)
324
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
325
  col3, col4 = st.columns(2)
326
  with col3:
327
+ fig_bar = px.bar(player_bowling, x='Format', y='Wickets', color='Format',
328
+ title="Wickets by Format", color_discrete_sequence=px.colors.qualitative.Set1)
329
+ fig_bar.update_layout(transition_duration=500)
330
+ st.plotly_chart(fig_bar, use_container_width=True)
331
  with col4:
332
+ fig_line = px.line(player_bowling, x='Format', y='Eco', title="Economy Rate",
333
+ color_discrete_sequence=['#00cc96'])
334
+ st.plotly_chart(fig_line, use_container_width=True)
335
+ fig_heatmap = px.imshow(player_bowling[['Wickets', 'Eco', 'Ave']].T, text_auto=True,
336
+ color_continuous_scale='Plasma', title="Bowling Stats Heatmap")
337
+ st.plotly_chart(fig_heatmap, use_container_width=True)
338
+ st.markdown("</div>", unsafe_allow_html=True)
339
 
 
340
  elif option == "Player Comparison" and player1 and player2:
341
+ st.markdown(f"<h1>Player Comparison: {player1} vs {player2}</h1>", unsafe_allow_html=True)
342
 
343
  def get_player_data(name):
344
  return (
 
349
  bat1, bowl1 = get_player_data(player1)
350
  bat2, bowl2 = get_player_data(player2)
351
 
352
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
353
+ # Batting Radar Chart
354
+ st.markdown("<h3>Batting Radar Chart</h3>", unsafe_allow_html=True)
355
+ fig_radar = go.Figure()
356
+ for player, bat in [(player1, bat1), (player2, bat2)]:
357
+ if not bat.empty:
358
+ fig_radar.add_trace(go.Scatterpolar(
359
+ r=[bat['Runs'].mean(), bat['SR'].mean(), bat['Ave'].mean()],
360
+ theta=['Runs', 'Strike Rate', 'Average'],
361
+ fill='toself',
362
+ name=player
363
+ ))
364
+ fig_radar.update_layout(polar=dict(radialaxis=dict(visible=True)), showlegend=True, title="Batting Comparison")
365
+ st.plotly_chart(fig_radar, use_container_width=True)
366
+
367
+ # Bowling Bar Chart
368
+ st.markdown("<h3>Bowling Bar Chart</h3>", unsafe_allow_html=True)
369
  bowl_combined = pd.concat([bowl1, bowl2])
370
+ fig_bowl_bar = px.bar(bowl_combined, x='player_name', y='Wickets', color='Format',
371
+ barmode='group', title="Wickets Comparison",
372
+ color_discrete_sequence=px.colors.qualitative.Plotly)
373
+ fig_bowl_bar.update_layout(transition_duration=500)
374
+ st.plotly_chart(fig_bowl_bar, use_container_width=True)
375
+
376
+ # Runs Donut Chart
377
+ st.markdown("<h3>Total Runs Donut Chart</h3>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
378
  total_runs = [bat1['Runs'].sum(), bat2['Runs'].sum()]
379
  runs_data = pd.DataFrame({
380
  'Player': [player1, player2],
381
  'Total Runs': total_runs
382
  })
383
+ fig_pie = px.pie(runs_data, names='Player', values='Total Runs', title="Proportion of Total Runs",
384
+ hole=0.4, color_discrete_sequence=px.colors.qualitative.G10)
385
+ fig_pie.update_traces(textinfo='percent+label')
386
+ st.plotly_chart(fig_pie, use_container_width=True)
387
 
388
+ # Heatmap for Batting Stats
389
+ st.markdown("<h3>Batting Stats Heatmap</h3>", unsafe_allow_html=True)
390
+ bat_combined = pd.DataFrame({
391
+ 'Player': [player1, player2],
392
+ 'Total Runs': [bat1['Runs'].sum(), bat2['Runs'].sum()],
393
+ 'Batting Average': [bat1['Ave'].dropna().mean(), bat2['Ave'].dropna().mean()],
394
+ 'Strike Rate': [bat1['SR'].mean(), bat2['SR'].mean()]
395
+ }).set_index('Player')
396
+ fig_heatmap = px.imshow(bat_combined, text_auto=True, aspect="auto",
397
+ color_continuous_scale='RdBu', title="Batting Stats Heatmap")
398
+ st.plotly_chart(fig_heatmap, use_container_width=True)
399
+ st.markdown("</div>", unsafe_allow_html=True)
400
 
401
  if st.button("Show Raw Stats"):
402
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
403
+ st.dataframe(pd.concat([bat1, bowl1, bat2, bowl2]), use_container_width=True)
404
+ st.markdown("</div>", unsafe_allow_html=True)