Spaces:
Sleeping
Sleeping
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 | |
import plotly.express as px | |
st.set_page_config(page_title="NeuroPulse AI", page_icon="๐ง ", layout="wide") | |
# Load logo | |
logo_path = "logo.png" | |
if os.path.exists(logo_path): | |
st.image(logo_path, width=160) | |
# Session State | |
if "review" not in st.session_state: | |
st.session_state.review = "" | |
if "dark_mode" not in st.session_state: | |
st.session_state.dark_mode = False | |
if "intelligence_mode" not in st.session_state: | |
st.session_state.intelligence_mode = True | |
# Apply Dark Mode Styling | |
if st.session_state.dark_mode: | |
st.markdown(""" | |
<style> | |
html, body, [class*="st-"] { | |
background-color: #1e1e1e; | |
color: #f5f5f5; | |
} | |
.stTextInput > div > div > input, .stTextArea > div > textarea { | |
background-color: #2b2b2b; | |
color: white; | |
} | |
.stButton > button { | |
background-color: #333; | |
color: white; | |
} | |
.stDownloadButton > button { | |
background-color: #444; | |
color: white; | |
} | |
.stSelectbox, .stCheckbox, .stRadio, .stFileUploader { | |
background-color: #2b2b2b; | |
color: white; | |
} | |
</style> | |
""", unsafe_allow_html=True) | |
# Sidebar controls | |
with st.sidebar: | |
st.header("โ๏ธ Global Settings") | |
st.session_state.dark_mode = st.toggle("๐ Dark Mode", value=st.session_state.dark_mode) | |
st.session_state.intelligence_mode = st.toggle("๐ง Intelligence Mode", value=st.session_state.intelligence_mode) | |
api_token = st.text_input("๐ API Token", type="password") | |
backend_url = st.text_input("๐ Backend URL", value="http://localhost:8000") | |
sentiment_model = st.selectbox("๐ Sentiment Model", [ | |
"distilbert-base-uncased-finetuned-sst-2-english", | |
"nlptown/bert-base-multilingual-uncased-sentiment" | |
]) | |
industry = st.selectbox("๐ญ Industry", [ | |
"Auto-detect", "Generic", "E-commerce", "Healthcare", "Education", "Travel", "Banking", "Insurance", "Gaming", "Food Delivery", "Real Estate", "Fitness", "Entertainment" | |
]) | |
product_category = st.selectbox("๐งฉ Product Category", [ | |
"Auto-detect", "General", "Mobile Devices", "Laptops", "Healthcare Devices", "Banking App", "Travel Service", "Educational Tool", "Insurance Portal", "Streaming App", "Wearables", "Home Appliances", "Food Apps" | |
]) | |
device_type = st.selectbox("๐ป Device", [ | |
"Auto-detect", "Web", "Android", "iOS", "Desktop", "Smartwatch", "Kiosk" | |
]) | |
use_aspects = st.checkbox("๐ฌ Enable Aspect Analysis") | |
use_smart_summary = st.checkbox("๐ง Smart Summary (Single)") | |
use_smart_summary_bulk = st.checkbox("๐ง Smart Summary for Bulk") | |
verbosity = st.radio("๐ฃ๏ธ Response Style", ["Brief", "Detailed"]) | |
follow_up = st.text_input("๐ Follow-up Question") | |
voice_lang = st.selectbox("๐ Voice Language", ["en", "fr", "es", "de", "hi", "zh"]) | |
# Text-to-Speech Helper | |
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 | |
# Tabs | |
tab1, tab2 = st.tabs(["๐ง Single Review", "๐ Bulk CSV"]) | |
# --- SINGLE --- | |
with tab1: | |
st.title("๐ง NeuroPulse AI โ Multimodal Review Analyzer") | |
st.markdown("<div style='font-size:16px;color:#aaa;'>Minimum 50โ100 words recommended.</div>", unsafe_allow_html=True) | |
review = st.text_area("๐ Enter Review", value=st.session_state.review, height=180) | |
col1, col2, col3 = st.columns(3) | |
with col1: | |
analyze = st.button("๐ Analyze", use_container_width=True, disabled=not api_token) | |
with col2: | |
if st.button("๐ฒ Example", use_container_width=True): | |
st.session_state.review = "App was smooth, but the transaction failed twice on Android during checkout." | |
st.rerun() | |
with col3: | |
if st.button("๐งน Clear", use_container_width=True): | |
st.session_state.review = "" | |
st.rerun() | |
if analyze and review: | |
if len(review.split()) < 50: | |
st.warning("โ ๏ธ Please enter at least 50 words.") | |
else: | |
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, | |
"verbosity": verbosity, | |
"intelligence": st.session_state.intelligence_mode | |
} | |
headers = {"x-api-key": api_token} | |
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' if use_smart_summary else 'Standard'}") | |
st.markdown(f"**Context:** {industry} | {product_category} | {device_type}") | |
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"]) | |
if data.get("explanation"): | |
st.subheader("๐งฎ Explain This") | |
st.markdown(data["explanation"]) | |
else: | |
st.error(f"โ API Error {res.status_code}: {res.json().get('detail', 'Unknown error')}") | |
except Exception as e: | |
st.error(f"๐ซ Exception occurred: {e}") | |
# --- BULK --- | |
with tab2: | |
st.title("๐ Bulk CSV Upload") | |
st.markdown(""" | |
Upload a CSV with the following columns:<br> | |
<code>review</code> (required), <code>industry</code>, <code>product_category</code>, <code>device</code> (optional) | |
""", unsafe_allow_html=True) | |
with st.expander("๐ Sample CSV"): | |
with open("sample_reviews.csv", "rb") as f: | |
st.download_button("โฌ๏ธ Download sample CSV", f, file_name="sample_reviews.csv") | |
uploaded_file = st.file_uploader("๐ Upload your CSV", type="csv") | |
if uploaded_file and api_token: | |
try: | |
df = pd.read_csv(uploaded_file) | |
if "review" not in df.columns: | |
st.error("CSV must contain a `review` column.") | |
else: | |
st.success(f"โ Loaded {len(df)} reviews") | |
for col in ["industry", "product_category", "device"]: | |
if col not in df.columns: | |
df[col] = [industry if industry != "Auto-detect" else "Generic"] * len(df) | |
df[col] = df[col].fillna("").astype(str) | |
if st.button("๐ Analyze Bulk Reviews", use_container_width=True): | |
with st.spinner("Processing..."): | |
try: | |
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(), | |
"intelligence": st.session_state.intelligence_mode | |
} | |
headers = {"x-api-key": api_token} | |
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"]) | |
st.dataframe(results) | |
if "sentiment" in results: | |
fig = px.pie(results, names="sentiment", title="Sentiment Distribution") | |
st.plotly_chart(fig) | |
st.download_button("โฌ๏ธ Download Results CSV", results.to_csv(index=False), "results.csv", mime="text/csv") | |
else: | |
st.error(f"โ Bulk Error {res.status_code}: {res.json().get('detail', 'Unknown error')}") | |
except Exception as e: | |
st.error(f"๐จ Processing Error: {e}") | |
except Exception as e: | |
st.error(f"โ File Read Error: {e}") | |