churnsight-ai / frontend.py
Hasitha16's picture
Update frontend.py
a83deda verified
raw
history blame
7.01 kB
import streamlit as st
import requests
import pandas as pd
from gtts import gTTS
import base64
from io import BytesIO
from PIL import Image
import os
st.set_page_config(page_title="NeuroPulse AI", page_icon="🧠", layout="wide")
logo_path = os.path.join("app", "static", "logo.png")
if os.path.exists(logo_path):
st.image(logo_path, width=160)
# Session state
if "history" not in st.session_state:
st.session_state.history = []
if "dark_mode" not in st.session_state:
st.session_state.dark_mode = False
# Sidebar
with st.sidebar:
st.header("βš™οΈ Settings")
st.session_state.dark_mode = st.toggle("πŸŒ™ Dark Mode", value=st.session_state.dark_mode)
sentiment_model = st.selectbox("πŸ“Š Sentiment Model", [
"distilbert-base-uncased-finetuned-sst-2-english",
"nlptown/bert-base-multilingual-uncased-sentiment"
])
industry = st.selectbox("🏭 Industry Context", [
"Generic", "E-commerce", "Healthcare", "Education", "Travel", "Banking", "Insurance"
])
product_category = st.selectbox("🧩 Product Category", [
"General", "Mobile Devices", "Laptops", "Healthcare Devices", "Banking App",
"Travel Service", "Educational Tool", "Insurance Portal"
])
device_type = st.selectbox("πŸ’» Device Type", [
"Web", "Android", "iOS", "Desktop", "Smartwatch", "Kiosk"
])
use_aspects = st.checkbox("πŸ“ˆ Enable Aspect-Based Analysis")
use_smart_summary = st.checkbox("🧠 Use Smart Summary (clustered key points)")
use_smart_summary_bulk = st.checkbox("🧠 Smart Summary for Bulk CSV")
follow_up = st.text_input("πŸ” Follow-up Question")
voice_lang = st.selectbox("πŸ”ˆ Voice Language", ["en", "fr", "es", "de", "hi", "zh"])
backend_url = st.text_input("πŸ–₯️ Backend URL", value="http://0.0.0.0:8000")
api_token = st.text_input("πŸ” API Token", type="password")
# Tabs
tab1, tab2 = st.tabs(["🧠 Single Review", "πŸ“š Bulk CSV"])
def speak(text, lang='en'):
tts = gTTS(text, lang=lang)
mp3 = BytesIO()
tts.write_to_fp(mp3)
b64 = base64.b64encode(mp3.getvalue()).decode()
st.markdown(f'<audio controls><source src="data:audio/mp3;base64,{b64}" type="audio/mp3"></audio>', unsafe_allow_html=True)
mp3.seek(0)
return mp3
# Tab: Single Review
with tab1:
st.title("🧠 NeuroPulse AI – Multimodal Review Analyzer")
review = st.session_state.get("review", "")
review = st.text_area("πŸ“ Enter a Review", value=review, height=160)
col1, col2, col3 = st.columns(3)
with col1:
analyze = st.button("πŸ” Analyze")
with col2:
if st.button("🎲 Example"):
st.session_state["review"] = "App was smooth, but the transaction failed twice on Android."
st.rerun()
with col3:
if st.button("🧹 Clear"):
st.session_state["review"] = ""
st.rerun()
if analyze and review:
with st.spinner("Analyzing..."):
try:
payload = {
"text": review,
"model": sentiment_model,
"industry": industry,
"aspects": use_aspects,
"follow_up": follow_up,
"product_category": product_category,
"device": device_type
}
headers = {"X-API-Key": api_token} if api_token else {}
params = {"smart": "1"} if use_smart_summary else {}
res = requests.post(f"{backend_url}/analyze/", json=payload, headers=headers, params=params)
if res.status_code == 200:
data = res.json()
st.success("βœ… Analysis Complete")
st.subheader("πŸ“Œ Summary")
st.info(data["summary"])
st.caption(f"🧠 Summary Type: {'Smart Summary' if use_smart_summary else 'Standard Model'}")
st.subheader("πŸ”Š Audio")
audio = speak(data["summary"], lang=voice_lang)
st.download_button("⬇️ Download Summary Audio", audio.read(), "summary.mp3", mime="audio/mp3")
st.metric("πŸ“Š Sentiment", data["sentiment"]["label"], delta=f"{data['sentiment']['score']:.2%}")
st.info(f"πŸ’’ Emotion: {data['emotion']}")
if data.get("aspects"):
st.subheader("πŸ”¬ Aspects")
for a in data["aspects"]:
st.write(f"πŸ”Ή {a['aspect']}: {a['sentiment']} ({a['score']:.2%})")
if data.get("follow_up"):
st.subheader("πŸ€– Follow-Up Response")
st.warning(data["follow_up"])
else:
st.error(f"❌ API Error: {res.status_code}")
except Exception as e:
st.error(f"🚫 {e}")
# Tab: Bulk CSV
with tab2:
st.title("πŸ“š Bulk CSV Upload")
uploaded_file = st.file_uploader("Upload CSV with `review` column", type="csv")
if uploaded_file:
try:
df = pd.read_csv(uploaded_file)
if "review" in df.columns:
st.success(f"βœ… Loaded {len(df)} reviews")
for col in ["industry", "product_category", "device"]:
if col not in df.columns:
df[col] = [""] * len(df)
df[col] = df[col].fillna("").astype(str)
if st.button("πŸ“Š Analyze Bulk Reviews"):
with st.spinner("Processing..."):
payload = {
"reviews": df["review"].tolist(),
"model": sentiment_model,
"aspects": use_aspects,
"industry": df["industry"].tolist(),
"product_category": df["product_category"].tolist(),
"device": df["device"].tolist()
}
headers = {"X-API-Key": api_token} if api_token else {}
params = {"smart": "1"} if use_smart_summary_bulk else {}
res = requests.post(f"{backend_url}/bulk/", json=payload, headers=headers, params=params)
if res.status_code == 200:
results = pd.DataFrame(res.json()["results"])
results["summary_type"] = "Smart" if use_smart_summary_bulk else "Standard"
st.dataframe(results)
st.download_button("⬇️ Download Results CSV", results.to_csv(index=False), "bulk_results.csv", mime="text/csv")
else:
st.error(f"❌ Bulk Analysis Failed: {res.status_code}")
else:
st.error("CSV must contain a column named `review`.")
except Exception as e:
st.error(f"❌ File Error: {e}")