Spaces:
Sleeping
Sleeping
File size: 8,191 Bytes
a2651b0 12792ec 32a5e44 ec5fd70 12792ec 5a9bc2e 12792ec ec5fd70 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec 5a9bc2e 12792ec ec5fd70 12792ec 5a9bc2e 12792ec 5bcb18b 12792ec 5a9bc2e 12792ec ec5fd70 5a9bc2e ec5fd70 5a9bc2e ec5fd70 064234e ec5fd70 064234e 5a9bc2e ec5fd70 5a9bc2e | 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 | import streamlit as st
import pandas as pd
import json
import random
st.set_page_config(page_title="Cricket AI Studio", page_icon="π", layout="wide")
# ------------------------------------------------------------
# Sample JSON (simulate backend response). Replace later with real API.
# ------------------------------------------------------------
SAMPLE_RESPONSE = {
"query": "SA vs ZIM",
"probability": {
"team_a": "South Africa",
"team_b": "Zimbabwe",
"team_a_win_prob": 0.78,
"team_b_win_prob": 0.22
},
"agents": {
"stats_agent": "South Africa has a 78% win probability based on Elo ratings.",
"strategist_agent": "South Africa's pace attack matches the Perth conditions.",
"chaos_agent": "Zimbabwe still has a 22% chance which is significant in T20.",
"compere_agent": "The panel agrees South Africa are favorites but Zimbabwe has upset potential."
},
"batting_chart": [
{"player": "Klaasen", "team": "SA", "sr": 160},
{"player": "Markram", "team": "SA", "sr": 148},
{"player": "Raza", "team": "ZIM", "sr": 140}
]
}
def run_analysis(query: str) -> dict:
# For now: return sample JSON but overwrite the query so chat reflects user input
resp = dict(SAMPLE_RESPONSE)
resp["query"] = query
return resp
# ------------------------------------------------------------
# Session state
# ------------------------------------------------------------
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "assistant", "content": "Hi! Iβm Cricket AI Studio (demo). Ask a match question and Iβll predict + debate. π"}
]
if "last_result" not in st.session_state:
st.session_state.last_result = None
# ------------------------------------------------------------
# Header
# ------------------------------------------------------------
st.markdown(
"""
<div style="
padding: 14px 18px;
border-radius: 14px;
background: linear-gradient(90deg, rgba(40,120,255,0.12), rgba(180,80,255,0.10));
border: 1px solid rgba(255,255,255,0.08);
margin-bottom: 14px;">
<div style="font-size: 28px; font-weight: 800;">π Cricket AI Studio β Predict & Debate</div>
</div>
""",
unsafe_allow_html=True,
)
# ------------------------------------------------------------
# Layout: Left 40% / Right 60%
# ------------------------------------------------------------
left, right = st.columns([40, 60], gap="large")
# ---------------- LEFT: Chat ----------------
with left:
st.subheader("Chat + User Input")
# Render chat history
for m in st.session_state.messages:
with st.chat_message(m["role"]):
st.markdown(m["content"])
# Input
user_query = st.chat_input("Try: 'Predict SA vs ZIM' or 'IND vs AUS at Wankhede'")
if user_query:
st.session_state.messages.append({"role": "user", "content": user_query})
with st.spinner("Running analysis (JSON contract)..."):
result = run_analysis(user_query)
st.session_state.last_result = result
prob = result["probability"]
team_a = prob["team_a"]
team_b = prob["team_b"]
pa = int(prob["team_a_win_prob"] * 100)
pb = int(prob["team_b_win_prob"] * 100)
pick = team_a if prob["team_a_win_prob"] >= prob["team_b_win_prob"] else team_b
st.session_state.messages.append(
{"role": "assistant", "content": f"Prediction: **{pick}**. Win probability: **{team_a} {pa}%** vs **{team_b} {pb}%**. Check Agents + Graphs β"}
)
st.rerun()
with st.expander("Controls", expanded=False):
c1, c2 = st.columns(2)
with c1:
if st.button("π§Ή Clear chat", use_container_width=True):
st.session_state.messages = [
{"role": "assistant", "content": "Chat cleared. Ask another match question π"}
]
st.session_state.last_result = None
st.rerun()
with c2:
st.download_button(
"β¬οΈ Download JSON",
data=(json.dumps(st.session_state.last_result, indent=2) if st.session_state.last_result else "{}"),
file_name="analysis.json",
mime="application/json",
use_container_width=True,
)
# ---------------- RIGHT: Agent Panel (2x2) + Graphs tab ----------------
with right:
st.subheader("Agent Panel")
tab_agents, tab_graphs = st.tabs(["π€ Agents", "π Graphs"])
if not st.session_state.last_result:
with tab_agents:
st.info("Run a query from the left chat to populate the agent panel.")
with tab_graphs:
st.info("Run a query to generate graphs.")
else:
res = st.session_state.last_result
prob = res["probability"]
team_a = prob["team_a"]
team_b = prob["team_b"]
pa = prob["team_a_win_prob"]
pb = prob["team_b_win_prob"]
pa_pct = int(pa * 100)
pb_pct = int(pb * 100)
fav = team_a if pa >= pb else team_b
dog = team_b if fav == team_a else team_a
fav_pct = max(pa_pct, pb_pct)
dog_pct = min(pa_pct, pb_pct)
agents = res.get("agents", {})
def random_agent_metrics():
"""
Randomly adds a compact metrics line to make each agent card feel richer.
We keep it consistent with the match probability from JSON, but vary presentation.
"""
variants = [
f"**Pick:** {fav} Β· **Win prob:** {fav_pct}% Β· **Alt:** {dog} {dog_pct}%",
f"**Fav:** {fav} ({fav_pct}%) Β· **Underdog:** {dog} ({dog_pct}%)",
f"**Outcome:** {fav} likely Β· **Confidence band:** {random.randint(max(55, fav_pct-10), min(95, fav_pct+6))}%",
]
return random.choice(variants)
def agent_card(title: str, subtitle: str, statement: str):
with st.container(border=True):
st.markdown(f"### {title}")
st.caption(subtitle)
# Agent statement from JSON
st.write(statement if statement else "β")
# Random additional metrics line
st.markdown(random_agent_metrics())
# ---- Agents tab (2x2 grid) ----
with tab_agents:
# Note: query not displayed at top (per requirement)
k1, k2, k3 = st.columns(3)
k1.metric("Favoured Team", fav)
k2.metric("Win Prob (fav)", f"{fav_pct}%")
k3.metric("Opponent", dog)
st.divider()
r1 = st.columns(2, gap="large")
with r1[0]:
agent_card("1οΈβ£ Statistician Agent", "Uses Elo + rankings", agents.get("stats_agent", "β"))
with r1[1]:
agent_card("2οΈβ£ Strategist Agent", "Uses players + venue", agents.get("strategist_agent", "β"))
r2 = st.columns(2, gap="large")
with r2[0]:
agent_card("3οΈβ£ Chaos Agent", "Predicts upsets", agents.get("chaos_agent", "β"))
with r2[1]:
agent_card("4οΈβ£ Compere Agent", "Summarizes panel consensus", agents.get("compere_agent", "β"))
# ---- Graphs tab ----
with tab_graphs:
st.markdown("### π Visual Insights / Graphs")
# Win probability graph (bar)
wp_df = pd.DataFrame(
[
{"team": team_a, "win_prob": pa},
{"team": team_b, "win_prob": pb},
]
).set_index("team")
st.markdown("#### Win Probability")
st.bar_chart(wp_df)
# Batting chart (strike rate)
bat = pd.DataFrame(res.get("batting_chart", []))
st.markdown("#### Batting Strike Rate")
if bat.empty:
st.info("No batting_chart data in JSON.")
else:
bat = bat.sort_values("sr", ascending=False)
st.dataframe(bat, use_container_width=True)
st.bar_chart(bat.set_index("player")[["sr"]]) |