Product-AI / app.py
Chand11's picture
Update app.py
e8e3406 verified
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
from google import genai
# πŸ”‘ ADD YOUR GEMINI API KEY
client = genai.Client(api_key="AIzaSyCvvewIh6BVyULlEmw1QE75vWsEmu8QNH0")
# ---------- READ FILE ----------
def read_file(file):
try:
if file is None:
return pd.DataFrame()
if file.name.endswith(".xlsx"):
return pd.read_excel(file.name)
else:
return pd.read_csv(file.name, engine="python")
except:
return pd.DataFrame()
# ---------- PREVIEW ----------
def preview(file):
df = read_file(file)
if df.empty:
return pd.DataFrame({"Message": ["Could not read file"]})
return df.head(20)
# ---------- CONVERSION ----------
def convert(file):
df = read_file(file)
if df.empty:
return pd.DataFrame({"Message": ["No data"]})
if "Time in Session (minutes)" not in df.columns:
return pd.DataFrame({"Message": ["No recognizable webinar structure"]})
df["Time in Session (minutes)"] = pd.to_numeric(
df["Time in Session (minutes)"], errors="coerce"
)
df = df.dropna()
if df.empty:
return pd.DataFrame({"Message": ["No usable data"]})
total = len(df)
completed = df[df["Time in Session (minutes)"] > 60]
completion = (len(completed) / total) * 100
avg_time = df["Time in Session (minutes)"].mean()
if avg_time > 150:
satisfaction, nps = 4.6, 75
elif avg_time > 100:
satisfaction, nps = 4.2, 65
elif avg_time > 60:
satisfaction, nps = 3.9, 55
else:
satisfaction, nps = 3.5, 40
result = pd.DataFrame({
"Course Name": ["Webinar Course"],
"NPS Score": [nps],
"Completion Rate (%)": [round(completion, 2)],
"Satisfaction (1-5)": [satisfaction]
})
result["Health Score"] = (
(result["NPS Score"] * 0.4) +
(result["Completion Rate (%)"] * 0.3) +
(result["Satisfaction (1-5)"] * 20 * 0.3)
)
return result
# ---------- CHART ----------
def make_chart(df):
if df is None or df.empty or "Course Name" not in df.columns:
return None
fig, ax = plt.subplots()
ax.bar(df["Course Name"], df["Health Score"])
plt.xticks(rotation=45)
plt.title("Course Health Score")
return fig
# ---------- AI CHAT ----------
def chat_with_data(file, message, history):
if history is None:
history = []
try:
df = read_file(file)
preview_text = df.head(20).to_string()
prompt = f"""
You are a data assistant.
Dataset preview:
{preview_text}
User question:
{message}
Explain:
- what this dataset is
- what issues exist
- how to structure it into course metrics
"""
response = client.models.generate_content(
model="gemini-1.5-flash",
contents=prompt
)
reply = response.text
except Exception as e:
reply = str(e)
# βœ… OLD FORMAT (COMPATIBLE)
history.append((message, reply))
return history, history
# ---------- UI ----------
with gr.Blocks() as app:
gr.Markdown("# πŸ“Š Course Quality Tracker + AI Assistant")
file_input = gr.File(label="Upload CSV / Excel")
gr.Markdown("## πŸ” Data Preview")
preview_table = gr.Dataframe()
gr.Markdown("## βš™οΈ Auto Conversion")
result_table = gr.Dataframe()
chart = gr.Plot()
gr.Markdown("## πŸ€– Ask AI about your data")
chatbot = gr.Chatbot() # βœ… FIXED (no type)
msg = gr.Textbox(label="Ask anything about your dataset")
file_input.change(
fn=preview,
inputs=file_input,
outputs=preview_table
)
file_input.change(
fn=convert,
inputs=file_input,
outputs=result_table
)
result_table.change(
fn=make_chart,
inputs=result_table,
outputs=chart
)
msg.submit(
fn=chat_with_data,
inputs=[file_input, msg, chatbot],
outputs=[chatbot, chatbot]
)
app.launch()