Streamlit-Testing / src /streamlit_app.py
ajaykumar0712's picture
Applying try except safety block for rate limit error
f5237b3 verified
Raw History Blame
7.48 kB
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
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 = ""
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]
# Create impression of thinking and a spinning icon
# with st.spinner("Consulting the AI panel..."):
# Safety net to check rate limit error
try:
agent_outputs = run_agents("match", teamA, teamB)
except Exception as e:
if "RateLimit" in str(e):
st.warning("Rate limit hit. Retrying in 12 seconds...")
time.sleep(12)
agent_outputs = run_agents("match", teamA, teamB)
else:
raise e
stats_output = agent_outputs["stats"]
strategist_output = agent_outputs["strategist"]
chaos_output = agent_outputs["chaos"]
compere_output = agent_outputs["compere"]
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:
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())
teamB_bat = team_map.get(teamB.upper(), teamB.upper())
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 βœ…")