Sahitha09 commited on
Commit
12792ec
Β·
verified Β·
1 Parent(s): 39c279a

initial commit

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +363 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,365 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import random
4
+ import time
5
+ from datetime import datetime
6
+
7
+ st.set_page_config(page_title="Cricket AI Studio", page_icon="🏏", layout="wide")
8
+
9
+ # -----------------------------
10
+ # Utilities
11
+ # -----------------------------
12
+ AGENTS = [
13
+ {
14
+ "id": "statistician",
15
+ "title": "1️⃣ Statistician Agent",
16
+ "subtitle": "Uses Elo + rankings",
17
+ },
18
+ {
19
+ "id": "strategist",
20
+ "title": "2️⃣ Strategist Agent",
21
+ "subtitle": "Uses players + venue",
22
+ },
23
+ {
24
+ "id": "form_expert",
25
+ "title": "3️⃣ Form Expert Agent",
26
+ "subtitle": "Uses momentum logic",
27
+ },
28
+ {
29
+ "id": "chaos",
30
+ "title": "4️⃣ Chaos Agent",
31
+ "subtitle": "Predicts upsets",
32
+ },
33
+ ]
34
+
35
+ TEAMS = ["India", "Australia", "England", "Pakistan", "New Zealand", "South Africa", "Sri Lanka", "Bangladesh"]
36
+ VENUES = ["Wankhede", "Eden Gardens", "MCG", "Lords", "The Oval", "Gaddafi Stadium", "Newlands", "Basin Reserve"]
37
+
38
+
39
+ def _softmax(scores):
40
+ exps = [pow(2.71828, s) for s in scores]
41
+ s = sum(exps)
42
+ return [e / s for e in exps]
43
+
44
+
45
+ # -----------------------------
46
+ # CrewAI placeholder: run_analysis(query) -> JSON
47
+ # Replace agent_* bodies with real CrewAI calls later.
48
+ # -----------------------------
49
+ def run_analysis(query: str) -> dict:
50
+ # Parse-ish (dummy): pick two teams + venue
51
+ team_a = random.choice(TEAMS)
52
+ team_b = random.choice([t for t in TEAMS if t != team_a])
53
+ venue = random.choice(VENUES)
54
+
55
+ # --- Agent outputs (dummy logic) ---
56
+ # Statistician (Elo-ish)
57
+ elo_a = random.randint(1600, 1950)
58
+ elo_b = random.randint(1600, 1950)
59
+ stat_scores = [elo_a / 1000, elo_b / 1000]
60
+ stat_probs = _softmax(stat_scores)
61
+
62
+ stat_winner = team_a if stat_probs[0] >= stat_probs[1] else team_b
63
+ stat_conf = round(max(stat_probs), 2)
64
+
65
+ # Strategist (players + venue)
66
+ venue_bias = random.choice([team_a, team_b, "neutral"])
67
+ strat_winner = venue_bias if venue_bias != "neutral" else random.choice([team_a, team_b])
68
+ strat_conf = round(random.uniform(0.55, 0.85), 2)
69
+
70
+ # Form Expert (momentum)
71
+ form_pick = random.choice([team_a, team_b])
72
+ streak = random.randint(1, 6)
73
+ form_conf = round(0.52 + streak * 0.05 + random.uniform(-0.03, 0.03), 2)
74
+ form_conf = min(0.93, max(0.52, form_conf))
75
+
76
+ # Chaos (upset)
77
+ chaos_pick = random.choice([team_a, team_b])
78
+ upset_prob = round(random.uniform(0.08, 0.28), 2)
79
+
80
+ # --- Aggregate final prediction ---
81
+ # Weighted blend: Statistician 0.35, Strategist 0.25, Form 0.25, Chaos 0.15
82
+ weights = {"stat": 0.35, "strat": 0.25, "form": 0.25, "chaos": 0.15}
83
+
84
+ score_a = 0
85
+ score_b = 0
86
+
87
+ score_a += weights["stat"] * (stat_probs[0])
88
+ score_b += weights["stat"] * (stat_probs[1])
89
+
90
+ score_a += weights["strat"] * (1 if strat_winner == team_a else 0)
91
+ score_b += weights["strat"] * (1 if strat_winner == team_b else 0)
92
+
93
+ score_a += weights["form"] * (1 if form_pick == team_a else 0)
94
+ score_b += weights["form"] * (1 if form_pick == team_b else 0)
95
+
96
+ # chaos adds probability to whichever it picks
97
+ score_a += weights["chaos"] * (upset_prob if chaos_pick == team_a else (1 - upset_prob))
98
+ score_b += weights["chaos"] * (upset_prob if chaos_pick == team_b else (1 - upset_prob))
99
+
100
+ final_winner = team_a if score_a >= score_b else team_b
101
+ final_conf = round(max(score_a, score_b), 2)
102
+
103
+ # --- Visuals: Win probability across 20 overs (dummy) ---
104
+ overs = list(range(1, 21))
105
+ base = 0.45 if final_winner == team_a else 0.55
106
+ wp = []
107
+ cur = base
108
+ for o in overs:
109
+ cur += random.uniform(-0.03, 0.05)
110
+ cur = min(0.95, max(0.05, cur))
111
+ wp.append(cur)
112
+
113
+ # Phase impact breakdown (dummy)
114
+ impact = [
115
+ {"metric": "Powerplay", "impact": random.randint(15, 35)},
116
+ {"metric": "Middle overs", "impact": random.randint(20, 40)},
117
+ {"metric": "Death overs", "impact": random.randint(20, 45)},
118
+ ]
119
+
120
+ # Debate points
121
+ debate_for = [
122
+ f"{final_winner} has a stronger match-up at {venue} (demo logic).",
123
+ "Bowling depth in the death overs is projected to be higher.",
124
+ ]
125
+ debate_against = [
126
+ "Toss + dew can swing the outcome significantly.",
127
+ "Variance in powerplay wickets makes this prediction fragile.",
128
+ ]
129
+
130
+ return {
131
+ "query": query,
132
+ "context": {"team_a": team_a, "team_b": team_b, "venue": venue},
133
+ "timestamp": datetime.now().isoformat(timespec="seconds"),
134
+ "final": {"winner": final_winner, "confidence": final_conf},
135
+ "agents": [
136
+ {
137
+ "id": "statistician",
138
+ "name": "Statistician Agent",
139
+ "method": "Elo + rankings",
140
+ "output": {
141
+ "winner": stat_winner,
142
+ "confidence": stat_conf,
143
+ "elo": {team_a: elo_a, team_b: elo_b},
144
+ "notes": "Elo-derived softmax probability (demo).",
145
+ },
146
+ },
147
+ {
148
+ "id": "strategist",
149
+ "name": "Strategist Agent",
150
+ "method": "Players + venue",
151
+ "output": {
152
+ "winner": strat_winner,
153
+ "confidence": strat_conf,
154
+ "venue_bias": venue_bias,
155
+ "notes": "Venue bias + match-up heuristics (demo).",
156
+ },
157
+ },
158
+ {
159
+ "id": "form_expert",
160
+ "name": "Form Expert Agent",
161
+ "method": "Momentum logic",
162
+ "output": {
163
+ "winner": form_pick,
164
+ "confidence": form_conf,
165
+ "streak": streak,
166
+ "notes": "Momentum-based confidence (demo).",
167
+ },
168
+ },
169
+ {
170
+ "id": "chaos",
171
+ "name": "Chaos Agent",
172
+ "method": "Upset predictor",
173
+ "output": {
174
+ "upset_pick": chaos_pick,
175
+ "upset_probability": upset_prob,
176
+ "notes": "Upset probability injection (demo).",
177
+ },
178
+ },
179
+ ],
180
+ "debate": {"for": debate_for, "against": debate_against},
181
+ "visuals": {
182
+ "win_probability_over_overs": [{"over": o, "win_prob": p} for o, p in zip(overs, wp)],
183
+ "phase_impact": impact,
184
+ },
185
+ }
186
+
187
+
188
+ # -----------------------------
189
+ # Session state
190
+ # -----------------------------
191
+ if "messages" not in st.session_state:
192
+ st.session_state.messages = [
193
+ {"role": "assistant", "content": "Hi! I’m Cricket AI Studio (demo). Ask a match question and I’ll predict + debate. 🏏"}
194
+ ]
195
+ if "last_result" not in st.session_state:
196
+ st.session_state.last_result = None
197
+ if "agent_status" not in st.session_state:
198
+ st.session_state.agent_status = {a["id"]: "idle" for a in AGENTS}
199
+
200
+
201
+ # -----------------------------
202
+ # HEADER
203
+ # -----------------------------
204
+ st.markdown(
205
+ """
206
+ <div style="
207
+ padding: 14px 18px;
208
+ border-radius: 14px;
209
+ background: linear-gradient(90deg, rgba(40,120,255,0.12), rgba(180,80,255,0.10));
210
+ border: 1px solid rgba(255,255,255,0.08);
211
+ margin-bottom: 14px;">
212
+ <div style="font-size: 28px; font-weight: 800;">🏏 Cricket AI Studio – Predict & Debate</div>
213
+ </div>
214
+ """,
215
+ unsafe_allow_html=True,
216
+ )
217
+
218
+ # -----------------------------
219
+ # TWO COLUMN BODY: 40 / 60
220
+ # -----------------------------
221
+ left, right = st.columns([40, 60], gap="large")
222
+
223
+ with left:
224
+ st.subheader("Chat + User Input")
225
+
226
+ # Render chat
227
+ for m in st.session_state.messages:
228
+ with st.chat_message(m["role"]):
229
+ st.markdown(m["content"])
230
+
231
+ # Input
232
+ user_query = st.chat_input("Try: 'Predict IND vs AUS at Wankhede' or 'Debate chasing 180 at Eden Gardens'")
233
+
234
+ if user_query:
235
+ st.session_state.messages.append({"role": "user", "content": user_query})
236
+
237
+ # show agent running states
238
+ for a in AGENTS:
239
+ st.session_state.agent_status[a["id"]] = "running"
240
+ st.session_state.last_result = None
241
+
242
+ # Simulate stepwise agent progress to feel like CrewAI
243
+ with st.spinner("Running CrewAI agents (demo simulation)..."):
244
+ time.sleep(0.4)
245
+ st.session_state.agent_status["statistician"] = "complete"
246
+ time.sleep(0.3)
247
+ st.session_state.agent_status["strategist"] = "complete"
248
+ time.sleep(0.3)
249
+ st.session_state.agent_status["form_expert"] = "complete"
250
+ time.sleep(0.3)
251
+ st.session_state.agent_status["chaos"] = "complete"
252
+
253
+ result = run_analysis(user_query)
254
+ st.session_state.last_result = result
255
+
256
+ # Assistant summary
257
+ st.session_state.messages.append(
258
+ {
259
+ "role": "assistant",
260
+ "content": f"Final pick: **{result['final']['winner']}** (confidence **{int(result['final']['confidence']*100)}%**) β€” see Agent Panel + Visual Insights."
261
+ }
262
+ )
263
+ st.rerun()
264
+
265
+ with st.expander("Controls", expanded=False):
266
+ c1, c2 = st.columns(2)
267
+ with c1:
268
+ if st.button("🧹 Clear chat", use_container_width=True):
269
+ st.session_state.messages = [
270
+ {"role": "assistant", "content": "Chat cleared. Ask another cricket question 🏏"}
271
+ ]
272
+ st.session_state.last_result = None
273
+ st.session_state.agent_status = {a["id"]: "idle" for a in AGENTS}
274
+ st.rerun()
275
+ with c2:
276
+ st.download_button(
277
+ "⬇️ Download JSON",
278
+ data=(str(st.session_state.last_result) if st.session_state.last_result else "{}"),
279
+ file_name="analysis.json",
280
+ mime="application/json",
281
+ use_container_width=True,
282
+ )
283
+
284
+ with right:
285
+ st.subheader("Agent Panel")
286
+
287
+ # Agent list with statuses
288
+ for a in AGENTS:
289
+ status = st.session_state.agent_status.get(a["id"], "idle")
290
+ icon = "⏳" if status == "running" else ("βœ…" if status == "complete" else "βšͺ")
291
+ with st.container(border=True):
292
+ st.markdown(f"### {icon} {a['title']}")
293
+ st.caption(a["subtitle"])
294
+
295
+ # Render agent output when available
296
+ if st.session_state.last_result:
297
+ agent_data = next((x for x in st.session_state.last_result["agents"] if x["id"] == a["id"]), None)
298
+ if agent_data:
299
+ out = agent_data["output"]
300
+ if a["id"] == "chaos":
301
+ st.write(f"**Upset pick:** {out['upset_pick']}")
302
+ st.write(f"**Upset probability:** {int(out['upset_probability']*100)}%")
303
+ st.caption(out["notes"])
304
+ elif a["id"] == "statistician":
305
+ st.write(f"**Winner:** {out['winner']}")
306
+ st.write(f"**Confidence:** {int(out['confidence']*100)}%")
307
+ st.write("**Elo:** " + ", ".join([f"{k}: {v}" for k, v in out["elo"].items()]))
308
+ st.caption(out["notes"])
309
+ else:
310
+ st.write(f"**Winner:** {out['winner']}")
311
+ st.write(f"**Confidence:** {int(out['confidence']*100)}%")
312
+ # show extra fields if present
313
+ for k, v in out.items():
314
+ if k in ("winner", "confidence", "notes"):
315
+ continue
316
+ st.write(f"**{k.replace('_',' ').title()}:** {v}")
317
+ st.caption(out["notes"])
318
+ else:
319
+ st.caption("Run a query to populate outputs.")
320
+
321
+ # Final callout + debate
322
+ if st.session_state.last_result:
323
+ st.divider()
324
+ res = st.session_state.last_result
325
+ st.markdown("## πŸ† Final Prediction")
326
+ k1, k2, k3 = st.columns(3)
327
+ k1.metric("Winner", res["final"]["winner"])
328
+ k2.metric("Confidence", f"{int(res['final']['confidence']*100)}%")
329
+ k3.metric("Venue", res["context"]["venue"])
330
+
331
+ st.markdown("### πŸ—£οΈ Debate")
332
+ d1, d2 = st.columns(2)
333
+ with d1:
334
+ st.markdown("**βœ… For**")
335
+ for p in res["debate"]["for"]:
336
+ st.write("β€’ " + p)
337
+ with d2:
338
+ st.markdown("**⚠️ Against**")
339
+ for p in res["debate"]["against"]:
340
+ st.write("β€’ " + p)
341
+
342
+ # -----------------------------
343
+ # VISUAL INSIGHTS / GRAPHS (full width bottom)
344
+ # -----------------------------
345
+ st.markdown("## πŸ“ˆ Visual Insights / Graphs")
346
+
347
+ if st.session_state.last_result:
348
+ vis = st.session_state.last_result["visuals"]
349
+ df_wp = pd.DataFrame(vis["win_probability_over_overs"])
350
+ df_imp = pd.DataFrame(vis["phase_impact"])
351
+
352
+ g1, g2 = st.columns([65, 35], gap="large")
353
+
354
+ with g1:
355
+ st.markdown("### Win Probability Over Overs (Demo)")
356
+ st.line_chart(df_wp.set_index("over"))
357
+
358
+ with g2:
359
+ st.markdown("### Phase Impact Breakdown (Demo)")
360
+ st.bar_chart(df_imp.set_index("metric"))
361
 
362
+ with st.expander("Show raw JSON", expanded=False):
363
+ st.json(st.session_state.last_result)
364
+ else:
365
+ st.caption("Run a query to display charts.")