File size: 9,794 Bytes
c7afdb3
a0d321e
 
 
41acde8
4f22948
a0d321e
99cc8a0
01fac65
a0d321e
 
 
01fac65
a0d321e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01fac65
 
 
a0d321e
 
 
 
 
 
 
eb0c61d
a0d321e
 
 
 
 
 
 
 
 
 
 
4f22948
 
 
 
a0d321e
4f22948
5c48228
4f22948
 
 
 
 
 
f5237b3
 
a0d321e
 
f5237b3
 
323b3fb
 
 
4f22948
 
5c48228
 
 
4f22948
5c48228
4f22948
 
 
 
 
 
 
368b082
4f22948
 
 
 
 
 
 
 
 
 
323b3fb
 
 
 
 
 
 
 
 
eb0c61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022a797
2f001f0
 
 
 
01fac65
022a797
 
a0d321e
 
01fac65
99cc8a0
 
a0d321e
 
 
 
01fac65
 
a0d321e
 
 
 
 
 
 
 
 
 
 
 
41acde8
 
 
a0d321e
 
99cc8a0
 
 
 
 
 
41acde8
99cc8a0
41acde8
 
a0d321e
 
99cc8a0
41acde8
99cc8a0
41acde8
 
a0d321e
 
99cc8a0
 
 
41acde8
 
a0d321e
 
99cc8a0
41acde8
99cc8a0
41acde8
 
a0d321e
99cc8a0
a0d321e
 
 
 
 
 
 
4f22948
a0d321e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c48228
 
99cc8a0
a0d321e
92432ee
a0d321e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99cc8a0
 
 
a0d321e
92432ee
a0d321e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import time 
from agents import run_agents, detect_intent
from probability_engine import elo_probability
from data_loader import teams, team_map

# =========================
# LOAD DATA
# =========================

batters = pd.read_csv("src/data/batters.csv")
bowlers = pd.read_csv("src/data/bowlers.csv")
teams = pd.read_csv("src/data/teams.csv")
venues = pd.read_csv("src/data/venue.csv")

# =========================
# PAGE CONFIG
# =========================

st.set_page_config(layout="wide")
st.title("🏏 Cricket World Cup AI Panel")

# =========================
# MAIN LAYOUT
# =========================

left, right = st.columns([4,6])

# =========================
# LEFT SIDE CHAT
# =========================

with left:

    st.header("Ask the AI Panel")

    # Initialize variables
    stats_output = ""
    strategist_output = ""
    chaos_output = ""
    compere_output = ""
    agent_outputs = None
    
    teamA = None
    teamB = None
    
    probA = None
    probB = None

    query = st.text_input("Example: IND vs AUS")

    if query:

        # words = query.upper().split()

        # teamA = words[0]
        # teamB = words[2]

        intent_data = detect_intent(query)
        st.write("DEBUG:", intent_data)

        intent = intent_data.get("intent")
        teamA = intent_data.get("teamA")
        teamB = intent_data.get("teamB")
        group = intent_data.get("group")
        venue = intent_data.get("venue")
        
        # Create impression of thinking and a spinning icon
        # with st.spinner("Consulting the AI panel..."):

        # Safety net to check rate limit error
        
        max_retries = 3
        for attempt in range(max_retries):
            try:
                if intent == "match_prediction":
                    if not teamA or not teamB:
                        st.error("❌ Could not detect both teams. Try: India vs Australia")
                        st.stop()
                
                    agent_outputs = run_agents("match", teamA, teamB)
                
                    probs = elo_probability(teamA, teamB)
                    probA = probs["probA"]
                    probB = probs["probB"]
                elif intent == "group_progression":
                    if not group:
                        st.error("Please specify a group (e.g. Group D)")
                        break
                    agent_outputs = run_agents("group", group = group)
                    # no probability here
                    probA = None
                    probB = None
                elif intent == "tournament_prediction":
                    agent_outputs = run_agents("tournament", intent_data.get("tournament_team"))
                    probA = None
                    probB = None
                else:
                    st.error("Could not understand query")
                    break
                break
            except Exception as e:
                if "RateLimit" in str(e):
                    wait = 10 + attempt * 5
                    st.warning(f"Rate limit hit. Waiting {wait} seconds...")
                    time.sleep(wait)
                else:
                    raise e
        
        # stats_output = agent_outputs["stats"]
        # strategist_output = agent_outputs["strategist"]
        # chaos_output = agent_outputs["chaos"]
        # compere_output = agent_outputs["compere"]

        if isinstance(agent_outputs, dict):
            stats_output = agent_outputs.get("stats", "")
            strategist_output = agent_outputs.get("strategist", "")
            chaos_output = agent_outputs.get("chaos", "")
            compere_output = agent_outputs.get("compere", "")
        elif isinstance(agent_outputs, str):
            # fallback if agents return raw string
            stats_output = ""
            strategist_output = ""
            chaos_output = ""
            compere_output = agent_outputs
        else:
            stats_output = ""
            strategist_output = ""
            chaos_output = ""
            compere_output = ""

        # Run probabilities
        probs = elo_probability(teamA, teamB)
        probA = probs["probA"]
        probB = probs["probB"]

        # st.write("### Panel Verdict")
        # st.write(compere_output)

# =========================
# RIGHT SIDE TABS
# =========================

with right:

    tab1, tab2 = st.tabs(["Agent Panel", "Insights"])


# =========================
# TAB 1 : AGENT PANEL
# =========================

    with tab1:

        st.subheader("Expert Debate Panel")

        # explanation box
        st.info("🧠 Our AI expert panel debates the match before announcing the final prediction.")

        col1, col2 = st.columns(2)
        col3, col4 = st.columns(2)
    
        stat_placeholder = col1.empty()
        strat_placeholder = col2.empty()
        chaos_placeholder = col3.empty()
        compere_placeholder = col4.empty()
    
        # Statistician
        with stat_placeholder.container():
            with st.spinner("Statistician analyzing numbers..."):
                time.sleep(1.5)
            st.markdown("### πŸ“Š Statistician")
            st.write(stats_output)
    
        # Strategist
        with strat_placeholder.container():
            with st.spinner("Strategist planning tactics..."):
                time.sleep(1.5)
            st.markdown("### 🧠 Strategist")
            st.write(strategist_output)
    
        # Chaos agent
        with chaos_placeholder.container():
            with st.spinner("Chaos agent considering unpredictable factors..."):
                time.sleep(1.5)
            st.markdown("### 🎲 Chaos Agent")
            st.write(chaos_output)
    
        # Compere
        with compere_placeholder.container():
            with st.spinner("Compere summarizing the debate..."):
                time.sleep(1.5)
            st.markdown("### 🎀 Compere")
            st.write(compere_output)

# =========================
# TAB 2 : INSIGHTS
# =========================

    with tab2:

        if query and intent == "match_prediction":

            st.subheader("Win Probability")

            # SPEEDOMETER
            fig = go.Figure(go.Indicator(
                mode="gauge+number",
                value=probA*100,
                title={'text': f"{teamA} Win Probability"},
                gauge={
                    'axis': {'range': [0,100]},
                    'bar': {'color': "darkblue"},
                    'steps': [
                        {'range': [0,40], 'color': "red"},
                        {'range': [40,60], 'color': "orange"},
                        {'range': [60,100], 'color': "green"}
                    ]
                }
            ))

            st.plotly_chart(fig, use_container_width=True)


# =========================
# BATTER COMPARISON
# =========================

            st.subheader("Batting Comparison")

            teamA_bat = team_map.get(teamA.upper(), teamA.upper()) if teamA else None
            teamB_bat = team_map.get(teamB.upper(), teamB.upper()) if teamB else None

            team_batters = batters[
                batters["team"].str.upper().isin([teamA_bat.upper(), teamB_bat.upper()])
            ]

            fig2 = px.bar(
                team_batters,
                x="player",
                y="strike_rate",
                color="team",
                title="Strike Rate Comparison"
            )

            st.plotly_chart(fig2, use_container_width=True)


# =========================
# BOWLING COMPARISON
# =========================

            st.subheader("Bowling Comparison")

            teamA_bowl = team_map.get(teamA.upper(), teamA.upper())
            teamB_bowl = team_map.get(teamB.upper(), teamB.upper())

            team_bowlers = bowlers[
                bowlers["team"].str.upper().isin([teamA_bowl.upper(), teamB_bowl.upper()])
            ]

            fig3 = px.bar(
                team_bowlers,
                x="player",
                y="economy",
                color="team",
                title="Economy Rate Comparison"
            )

            st.plotly_chart(fig3, use_container_width=True)

# ##########################################################################################
# ##########################################################################################

# import streamlit as st

# st.set_page_config(page_title="Hello Chat App", layout="wide")

# # --- Sidebar ---
# st.sidebar.title("Controls")
# theme = st.sidebar.selectbox("Theme (demo)", ["Light", "Dark"])
# st.sidebar.info("This is the sidebar area.")

# # --- Main layout panels ---
# st.title("Streamlit Chat Input Demo")

# left, right = st.columns([2, 1])

# with left:
#     st.subheader("Chat Panel")

#     # session state to store messages
#     if "messages" not in st.session_state:
#         st.session_state.messages = [
#             {"role": "assistant", "content": "Hi! Type anything β€” I always say hello."}
#         ]

#     # display chat history
#     for msg in st.session_state.messages:
#         with st.chat_message(msg["role"]):
#             st.write(msg["content"])

#     # chat input
#     user_text = st.chat_input("Enter free text here...")
#     if user_text:
#         st.session_state.messages.append({"role": "user", "content": user_text})
#         st.session_state.messages.append({"role": "assistant", "content": "hello"})

#         # re-render
#         st.rerun()

# with right:
#     st.subheader("Info Panel")
#     st.write("Sidebar selection:", theme)
#     st.write("Messages so far:", len(st.session_state.messages))
#     st.success("Bot response is always: hello βœ…")