File size: 2,310 Bytes
57ef174 c5f19aa 57ef174 2df27a8 57ef174 8c5864d e64fc5c 333ac32 e64fc5c 333ac32 e64fc5c 333ac32 67d7ab8 57ef174 e64fc5c c5f19aa 6c5a9f9 57ef174 c5f19aa 333ac32 c5f19aa 7449b9c c5f19aa e64fc5c 57ef174 e64fc5c 333ac32 e64fc5c c5f19aa e64fc5c 57ef174 333ac32 |
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 |
import pandas as pd
import os
from langchain.chat_models import init_chat_model
from langchain_community.agent_toolkits import create_sql_agent
from langchain_community.utilities import SQLDatabase
from sqlalchemy import create_engine
import gradio as gr
os.environ["GOOGLE_API_KEY"]=os.getenv("GOOGLE_API_KEY")
llm = init_chat_model("gemini-2.5-flash", model_provider="google_genai") #gemini-2.5-flash
# --- Config ---
DATA_FILE = "IPL.csv"
# --- Load IPL Data ---
def load_df():
df = pd.read_csv(DATA_FILE, low_memory=False)
df.columns = df.columns.str.replace(" ", "_").str.lower()
if "date" in df.columns:
df["date"] = pd.to_datetime(df["date"], errors="coerce")
if {"runs_batter", "runs_extras"}.issubset(df.columns):
df["runs_batter"] = pd.to_numeric(df["runs_batter"], errors="coerce").fillna(0)
df["runs_extras"] = pd.to_numeric(df["runs_extras"], errors="coerce").fillna(0)
df["total_runs_this_ball"] = df["runs_batter"] + df["runs_extras"]
return df
_df = load_df()
engine = create_engine("sqlite:///ipl.db")
_df.to_sql("ipl", engine, index=False)
db = SQLDatabase(engine=engine)
print("Db created successfully")
def main(query):
try:
agent_executor = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)
response = agent_executor.invoke({"input": query})
return response["output"]
except:
return "Failed to fetch the required info"
# --- Gradio UI ---
with gr.Blocks() as demo:
gr.Markdown("# 🏏 IPL Cricket Analyst")
gr.Markdown(
"Ask questions about IPL stats from the dataset. Examples:<br>"
"`Top 5 batsmen by total runs`<br>"
"`Who scored the most in 2023?`<br>"
"`Average runs per over in 2022?`"
)
chatbot = gr.Chatbot(label="Cricket Analyst")
msg = gr.Textbox(label="Ask your question here...")
clear = gr.Button("Clear")
def user_input(m, hist):
return "", hist + [[m, None]]
def bot_reply(hist):
q = hist[-1][0]
a = main(q)
hist[-1][1] = a
return hist
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=True).then(
bot_reply, chatbot, chatbot
)
clear.click(lambda: [], None, chatbot)
demo.queue(max_size=20).launch(debug=True)
|