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( """
๐Ÿ Cricket AI Studio โ€“ Predict & Debate
""", 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"]])