Mpavan45 commited on
Commit
96bec45
·
verified ·
1 Parent(s): 67bda8e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -237
app.py CHANGED
@@ -1,134 +1,3 @@
1
- # import streamlit as st
2
- # import pandas as pd
3
- # import plotly.express as px
4
- # import os
5
- # from langchain_google_genai import GoogleGenerativeAI
6
- # from langchain_core.prompts import ChatPromptTemplate
7
- # from langchain_core.output_parsers import StrOutputParser
8
-
9
- # # Streamlit App
10
- # st.set_page_config(page_title="Cricket Player Stats Dashboard", layout="wide")
11
-
12
- # # Create a folder to save CSVs if not exists
13
- # data_folder = "data"
14
- # os.makedirs(data_folder, exist_ok=True)
15
-
16
- # # File paths
17
- # batting_path = "Batting_10_Teams_Final.csv"
18
- # bowling_path = "Bowling_10_Teams_Final.csv"
19
-
20
- # # Load saved CSVs
21
- # batting_df = pd.read_csv(batting_path)
22
- # bowling_df = pd.read_csv(bowling_path)
23
-
24
- # # Extract unique teams and players
25
- # teams = sorted(set(batting_df['Country'].unique()).union(bowling_df['Country'].unique()))
26
- # team = st.sidebar.selectbox("Select Team", teams)
27
-
28
- # # Filter players by team
29
- # batting_players = batting_df[batting_df['Country'] == team]['player_name'].unique()
30
- # bowling_players = bowling_df[bowling_df['Country'] == team]['player_name'].unique()
31
- # players = sorted(set(batting_players).union(bowling_players))
32
- # player = st.sidebar.selectbox("Select Player", players)
33
-
34
- # # Filter data for the selected player
35
- # player_batting = batting_df[(batting_df['player_name'] == player) & (batting_df['Country'] == team)]
36
- # player_bowling = bowling_df[(bowling_df['player_name'] == player) & (bowling_df['Country'] == team)]
37
-
38
- # st.title(f"{player}")
39
-
40
- # # ✅ Integrating LLMs using Gen-AI
41
-
42
- # # Loading API key and creating model
43
- # api_key = st.secrets.get('genai_key')
44
- # model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
45
-
46
- # # Creating output parser to generate output
47
- # out_par = StrOutputParser()
48
-
49
- # # Creating prompt template
50
- # prompt = ChatPromptTemplate.from_messages([
51
- # ("system", '''You are an AI cricket player information provider. Display the player's complete bio data in a
52
- # detailed table format with rows and columns, including personal information. Below the table,
53
- # include debut details for all formats. Additionally, provide a brief description of the player
54
- # underneath. Only include player information, not their performance statistics.'''),
55
- # ("human", "{player_name}")
56
- # ])
57
-
58
- # # Creating chain
59
- # chain = prompt | model | out_par
60
-
61
- # # Query GenAI with the player's name
62
- # response = chain.invoke({"player_name": player})
63
- # st.write(response)
64
-
65
- # # Buttons for Batting and Bowling Cards with Toggle Feature
66
- # col_card1, col_card2 = st.columns(2)
67
- # if "batting_card" not in st.session_state:
68
- # st.session_state["batting_card"] = False
69
- # if "bowling_card" not in st.session_state:
70
- # st.session_state["bowling_card"] = False
71
-
72
- # with col_card1:
73
- # if st.button("Batting Card"):
74
- # st.session_state["batting_card"] = not st.session_state["batting_card"]
75
-
76
- # if st.session_state["batting_card"]:
77
- # if len(player_batting) > 0:
78
- # st.write("### Batting Data")
79
- # st.dataframe(player_batting.iloc[:, :16]) # Display first 16 columns
80
- # else:
81
- # st.write("No batting data available.")
82
-
83
- # with col_card2:
84
- # if st.button("Bowling Card"):
85
- # st.session_state["bowling_card"] = not st.session_state["bowling_card"]
86
-
87
- # if st.session_state["bowling_card"]:
88
- # if len(player_bowling) > 0:
89
- # st.write("### Bowling Data")
90
- # st.dataframe(player_bowling.iloc[:, :15]) # Display first 15 columns
91
- # else:
92
- # st.write("No bowling data available.")
93
-
94
-
95
-
96
-
97
- # # Batting Visualization
98
- # if not player_batting.empty:
99
- # st.subheader("Batting Stats")
100
- # col1, col2 = st.columns(2)
101
- # with col1:
102
- # fig_bat_runs = px.bar(player_batting, x='Format', y='Runs', color='Format', title='Runs by Format')
103
- # st.plotly_chart(fig_bat_runs, use_container_width=True)
104
- # with col2:
105
- # fig_bat_sr = px.line(player_batting, x='Format', y='SR', title='Strike Rate by Format')
106
- # st.plotly_chart(fig_bat_sr, use_container_width=True)
107
-
108
- # # Batting Pie Chart
109
- # fig_bat_pie = px.pie(player_batting, values='Runs', names='Format',
110
- # title='Runs Distribution Across Formats',
111
- # color_discrete_map={"ODI": "red", "T20": "green", "Test": "blue"})
112
- # st.plotly_chart(fig_bat_pie, use_container_width=True)
113
-
114
- # # Bowling Visualization
115
- # if not player_bowling.empty:
116
- # st.subheader("Bowling Stats")
117
- # col3, col4 = st.columns(2)
118
- # with col3:
119
- # fig_bowl_wickets = px.bar(player_bowling, x='Format', y='Wickets', color='Format', title='Wickets by Format')
120
- # st.plotly_chart(fig_bowl_wickets, use_container_width=True)
121
- # with col4:
122
- # fig_bowl_eco = px.line(player_bowling, x='Format', y='Eco', title='Economy Rate by Format')
123
- # st.plotly_chart(fig_bowl_eco, use_container_width=True)
124
-
125
- # # Bowling Pie Chart
126
- # fig_bowl_pie = px.pie(player_bowling, values='Wickets', names='Format',
127
- # title='Wickets Distribution Across Formats',
128
- # color_discrete_map={"ODI": "yellow", "T20": "purple", "Test": "brown"})
129
- # st.plotly_chart(fig_bowl_pie, use_container_width=True)
130
-
131
-
132
  import streamlit as st
133
  import pandas as pd
134
  import plotly.express as px
@@ -138,13 +7,12 @@ from langchain_core.prompts import ChatPromptTemplate
138
  from langchain_core.output_parsers import StrOutputParser
139
 
140
  # Set page config
141
- st.set_page_config(page_title="🏏 Ultimate Cricket Analytics", layout="wide")
142
 
143
  # Create a folder to save CSVs if not exists
144
  data_folder = "data"
145
  os.makedirs(data_folder, exist_ok=True)
146
 
147
-
148
  # Load all three formats
149
  odi_df = pd.read_csv("odi.xls")
150
  t20_df = pd.read_csv("t20.xls")
@@ -154,30 +22,97 @@ test_df = pd.read_csv("test.xls")
154
  batting_df = pd.read_csv("Batting_10_Teams_Final.csv")
155
  bowling_df = pd.read_csv("Bowling_10_Teams_Final.csv")
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
- # Tabs for navigation
159
- tab1, tab2, tab3 = st.tabs(["🏏 Player Dashboard", "📊 Team Comparison", "📚 GenAI Team Bio"])
160
-
161
- # ---------------- TAB 1: Player Dashboard ----------------
162
- with tab1:
163
- st.title("🏏 Player Dashboard")
164
- teams = sorted(set(batting_df['Country'].unique()).union(bowling_df['Country'].unique()))
165
- team = st.sidebar.selectbox("Select Team", teams)
166
-
167
- batting_players = batting_df[batting_df['Country'] == team]['player_name'].unique()
168
- bowling_players = bowling_df[bowling_df['Country'] == team]['player_name'].unique()
169
- players = sorted(set(batting_players).union(bowling_players))
170
- player = st.sidebar.selectbox("Select Player", players)
171
-
172
- player_batting = batting_df[(batting_df['player_name'] == player) & (batting_df['Country'] == team)]
173
- player_bowling = bowling_df[(bowling_df['player_name'] == player) & (bowling_df['Country'] == team)]
174
-
175
- st.header(player)
176
-
177
- # GenAI Player Info
178
- api_key = st.secrets.get('genai_key')
179
- model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
180
- out_par = StrOutputParser()
181
  prompt = ChatPromptTemplate.from_messages([
182
  ("system", '''You are an AI cricket player information provider. Display the player's complete bio data in a
183
  detailed table format with rows and columns, including personal information. Below the table,
@@ -186,15 +121,13 @@ with tab1:
186
  ("human", "{player_name}")
187
  ])
188
  chain = prompt | model | out_par
189
- st.write(chain.invoke({"player_name": player}))
190
 
191
- # Toggle Cards
192
  if st.button("Show Batting Card"):
193
  st.dataframe(player_batting.iloc[:, :16])
194
  if st.button("Show Bowling Card"):
195
  st.dataframe(player_bowling.iloc[:, :15])
196
 
197
- # Visuals
198
  if not player_batting.empty:
199
  st.subheader("Batting Visualizations")
200
  col1, col2 = st.columns(2)
@@ -213,85 +146,20 @@ with tab1:
213
  st.plotly_chart(px.line(player_bowling, x='Format', y='Eco'))
214
  st.plotly_chart(px.pie(player_bowling, values='Wickets', names='Format'))
215
 
216
- # ---------------- TAB 2: Team Comparison ----------------
217
- # ---------------- TAB 2: Team Comparison ----------------
218
- # ---------------- TAB 2: Team Comparison ----------------
219
- with tab2:
220
- st.title("📊 Team Comparison")
221
-
222
- try:
223
- # Tag the format for clarity
224
- odi_df['Format'] = 'ODI'
225
- t20_df['Format'] = 'T20'
226
- test_df['Format'] = 'Test'
227
-
228
- # Combine all formats
229
- combined_df = pd.concat([odi_df, t20_df, test_df], ignore_index=True)
230
-
231
- # Columns as per your data
232
- team_column = 'Team'
233
-
234
- # Team selection
235
- selected_teams = st.multiselect("Select Teams to Compare (up to 3)", combined_df[team_column].unique(), max_selections=3)
236
-
237
- if selected_teams:
238
- selected_data = combined_df[combined_df[team_column].isin(selected_teams)]
239
-
240
- # Map column names to user-friendly labels
241
- stat_options = {
242
- 'Mat': 'Matches',
243
- 'Won': 'Wins',
244
- 'Lost': 'Losses',
245
- 'Draw': 'Draws',
246
- 'Tied': 'Ties',
247
- 'W/L': 'Win/Loss Ratio',
248
- '%W': 'Win %',
249
- '%L': 'Loss %',
250
- '%D': 'Draw %'
251
- }
252
-
253
- stat_choice = st.selectbox("Select Stat to Compare", list(stat_options.keys()), format_func=lambda x: stat_options[x])
254
-
255
- st.subheader(f"{stat_options[stat_choice]} Comparison")
256
-
257
- fig = px.bar(
258
- selected_data,
259
- x='Team',
260
- y=stat_choice,
261
- color='Format',
262
- barmode='group',
263
- title=f"{stat_options[stat_choice]} by Team and Format"
264
- )
265
- st.plotly_chart(fig, use_container_width=True)
266
 
267
- if st.checkbox("Show Raw Team Data Table"):
268
- st.dataframe(selected_data.reset_index(drop=True))
 
 
 
269
 
270
- # GenAI Team Summary
271
- st.subheader("📘 GenAI Team Summary")
272
- for team in selected_teams:
273
- st.markdown(f"#### {team}")
274
- team_prompt = ChatPromptTemplate.from_messages([
275
- ("system", "You are an AI cricket historian. Provide a brief yet detailed overview of the team."),
276
- ("human", "{team_name}")
277
- ])
278
- team_chain = team_prompt | model | out_par
279
- bio = team_chain.invoke({"team_name": team})
280
- st.write(bio)
281
- else:
282
- st.info("Please select at least one team to compare.")
283
 
284
- except Exception as e:
285
- st.error(f"Error loading team data: {e}")
286
 
287
- # ---------------- TAB 3: Team GenAI Bio ----------------
288
- with tab3:
289
- st.title("📚 Team GenAI Bio")
290
- team_input = st.text_input("Enter Team Name (e.g., India, Australia)")
291
- if team_input:
292
- team_prompt = ChatPromptTemplate.from_messages([
293
- ("system", "You are an AI cricket historian. Provide a brief yet detailed overview of the team."),
294
- ("human", "{team_name}")
295
- ])
296
- team_chain = team_prompt | model | out_par
297
- st.write(team_chain.invoke({"team_name": team_input}))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
 
7
  from langchain_core.output_parsers import StrOutputParser
8
 
9
  # Set page config
10
+ st.set_page_config(page_title="\ud83c\udfcf Ultimate Cricket Analytics", layout="wide")
11
 
12
  # Create a folder to save CSVs if not exists
13
  data_folder = "data"
14
  os.makedirs(data_folder, exist_ok=True)
15
 
 
16
  # Load all three formats
17
  odi_df = pd.read_csv("odi.xls")
18
  t20_df = pd.read_csv("t20.xls")
 
22
  batting_df = pd.read_csv("Batting_10_Teams_Final.csv")
23
  bowling_df = pd.read_csv("Bowling_10_Teams_Final.csv")
24
 
25
+ # Sidebar Navigation
26
+ st.sidebar.title("\ud83c\udfcf Navigation Panel")
27
+ option = st.sidebar.selectbox("Choose Option", [
28
+ "Team Info",
29
+ "Team Stats Comparison",
30
+ "Player Stats",
31
+ "Player Comparison"
32
+ ])
33
+
34
+ # Sidebar UI based on selection
35
+ team_info = selected_teams_stats = selected_format = None
36
+ selected_team = selected_player = None
37
+ player1 = player2 = None
38
+
39
+ if option == "Team Info":
40
+ team_info = st.sidebar.selectbox("Select Team", sorted(batting_df['Country'].unique()))
41
+
42
+ elif option == "Team Stats Comparison":
43
+ num_teams = st.sidebar.selectbox("Select Number of Teams", [2, 3])
44
+ selected_teams_stats = st.sidebar.multiselect("Select Teams", sorted(batting_df['Country'].unique()), max_selections=num_teams)
45
+ selected_format = st.sidebar.selectbox("Select Format", ["ODI", "T20", "Test"])
46
+
47
+ elif option == "Player Stats":
48
+ selected_team = st.sidebar.selectbox("Select Team", sorted(batting_df['Country'].unique()))
49
+ players_list = sorted(set(batting_df[batting_df['Country'] == selected_team]['player_name']).union(
50
+ bowling_df[bowling_df['Country'] == selected_team]['player_name']
51
+ ))
52
+ selected_player = st.sidebar.selectbox("Select Player", players_list)
53
+
54
+ elif option == "Player Comparison":
55
+ selected_team_for_players = st.sidebar.selectbox("Select Team", sorted(batting_df['Country'].unique()))
56
+ players_team = sorted(set(batting_df[batting_df['Country'] == selected_team_for_players]['player_name']).union(
57
+ bowling_df[bowling_df['Country'] == selected_team_for_players]['player_name']
58
+ ))
59
+ player1 = st.sidebar.selectbox("Select Player 1", players_team)
60
+ player2 = st.sidebar.selectbox("Select Player 2", [p for p in players_team if p != player1])
61
+
62
+ # Load GenAI
63
+ api_key = st.secrets.get('genai_key')
64
+ model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
65
+ out_par = StrOutputParser()
66
+
67
+ # ---- Main Content ----
68
+ if option == "Team Info" and team_info:
69
+ st.title(f"\ud83d\udcc3 Team Bio - {team_info}")
70
+ team_prompt = ChatPromptTemplate.from_messages([
71
+ ("system", "You are an AI cricket historian. Provide a brief yet detailed overview of the team."),
72
+ ("human", "{team_name}")
73
+ ])
74
+ team_chain = team_prompt | model | out_par
75
+ st.write(team_chain.invoke({"team_name": team_info}))
76
+
77
+ elif option == "Team Stats Comparison" and selected_teams_stats:
78
+ st.title("\ud83d\udcca Team Stats Comparison")
79
+ odi_df['Format'] = 'ODI'
80
+ t20_df['Format'] = 'T20'
81
+ test_df['Format'] = 'Test'
82
+ combined_df = pd.concat([odi_df, t20_df, test_df], ignore_index=True)
83
+
84
+ selected_data = combined_df[(combined_df['Team'].isin(selected_teams_stats)) & (combined_df['Format'] == selected_format)]
85
+
86
+ stat_options = {
87
+ 'Mat': 'Matches',
88
+ 'Won': 'Wins',
89
+ 'Lost': 'Losses',
90
+ 'Draw': 'Draws',
91
+ 'Tied': 'Ties',
92
+ 'W/L': 'Win/Loss Ratio',
93
+ '%W': 'Win %',
94
+ '%L': 'Loss %',
95
+ '%D': 'Draw %'
96
+ }
97
+ stat_choice = st.selectbox("Select Stat to Compare", list(stat_options.keys()), format_func=lambda x: stat_options[x])
98
+
99
+ fig = px.bar(
100
+ selected_data,
101
+ x='Team',
102
+ y=stat_choice,
103
+ color='Format',
104
+ barmode='group',
105
+ title=f"{stat_options[stat_choice]} by Team in {selected_format}"
106
+ )
107
+ st.plotly_chart(fig, use_container_width=True)
108
+ st.dataframe(selected_data.reset_index(drop=True))
109
+
110
+ elif option == "Player Stats" and selected_player:
111
+ st.title(f"\ud83c\udfcf Player Dashboard - {selected_player}")
112
+
113
+ player_batting = batting_df[(batting_df['player_name'] == selected_player) & (batting_df['Country'] == selected_team)]
114
+ player_bowling = bowling_df[(bowling_df['player_name'] == selected_player) & (bowling_df['Country'] == selected_team)]
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  prompt = ChatPromptTemplate.from_messages([
117
  ("system", '''You are an AI cricket player information provider. Display the player's complete bio data in a
118
  detailed table format with rows and columns, including personal information. Below the table,
 
121
  ("human", "{player_name}")
122
  ])
123
  chain = prompt | model | out_par
124
+ st.write(chain.invoke({"player_name": selected_player}))
125
 
 
126
  if st.button("Show Batting Card"):
127
  st.dataframe(player_batting.iloc[:, :16])
128
  if st.button("Show Bowling Card"):
129
  st.dataframe(player_bowling.iloc[:, :15])
130
 
 
131
  if not player_batting.empty:
132
  st.subheader("Batting Visualizations")
133
  col1, col2 = st.columns(2)
 
146
  st.plotly_chart(px.line(player_bowling, x='Format', y='Eco'))
147
  st.plotly_chart(px.pie(player_bowling, values='Wickets', names='Format'))
148
 
149
+ elif option == "Player Comparison" and player1 and player2:
150
+ st.title(f"\ud83d\udcc8 Player Comparison: {player1} vs {player2}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+ def get_player_data(name):
153
+ return (
154
+ batting_df[batting_df['player_name'] == name],
155
+ bowling_df[bowling_df['player_name'] == name]
156
+ )
157
 
158
+ bat1, bowl1 = get_player_data(player1)
159
+ bat2, bowl2 = get_player_data(player2)
 
 
 
 
 
 
 
 
 
 
 
160
 
161
+ st.subheader("Batting Comparison")
162
+ st.plotly_chart(px.bar(pd.concat([bat1, bat2]), x='Format', y='Runs', color='player_name', barmode='group'))
163
 
164
+ st.subheader("Bowling Comparison")
165
+ st.plotly_chart(px.bar(pd.concat([bowl1, bowl2]), x='Format', y='Wickets', color='player_name', barmode='group'))