Spaces:
Sleeping
Sleeping
Delete frontend.py
Browse files- frontend.py +0 -230
frontend.py
DELETED
@@ -1,230 +0,0 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import requests
|
3 |
-
import pandas as pd
|
4 |
-
from gtts import gTTS
|
5 |
-
import base64
|
6 |
-
from io import BytesIO
|
7 |
-
import os
|
8 |
-
import plotly.express as px
|
9 |
-
|
10 |
-
st.set_page_config(page_title="NeuroPulse AI", page_icon="π§ ", layout="wide")
|
11 |
-
|
12 |
-
if os.path.exists("logo.png"):
|
13 |
-
st.image("logo.png", width=180)
|
14 |
-
|
15 |
-
# Session state setup
|
16 |
-
defaults = {
|
17 |
-
"review": "",
|
18 |
-
"dark_mode": False,
|
19 |
-
"intelligence_mode": True,
|
20 |
-
"trigger_example_analysis": False,
|
21 |
-
"last_response": None,
|
22 |
-
"followup_answer": None
|
23 |
-
}
|
24 |
-
for k, v in defaults.items():
|
25 |
-
if k not in st.session_state:
|
26 |
-
st.session_state[k] = v
|
27 |
-
|
28 |
-
# Dark mode styling
|
29 |
-
if st.session_state.dark_mode:
|
30 |
-
st.markdown("""
|
31 |
-
<style>
|
32 |
-
html, body, [class*="st-"] {
|
33 |
-
background-color: #121212;
|
34 |
-
color: #f5f5f5;
|
35 |
-
}
|
36 |
-
.stTextInput > div > div > input,
|
37 |
-
.stTextArea > div > textarea,
|
38 |
-
.stSelectbox div div,
|
39 |
-
.stDownloadButton > button,
|
40 |
-
.stButton > button {
|
41 |
-
background-color: #1e1e1e;
|
42 |
-
color: white;
|
43 |
-
}
|
44 |
-
</style>
|
45 |
-
""", unsafe_allow_html=True)
|
46 |
-
|
47 |
-
# Sidebar settings
|
48 |
-
with st.sidebar:
|
49 |
-
st.header("βοΈ Global Settings")
|
50 |
-
st.session_state.dark_mode = st.toggle("π Dark Mode", value=st.session_state.dark_mode)
|
51 |
-
st.session_state.intelligence_mode = st.toggle("π§ Intelligence Mode", value=st.session_state.intelligence_mode)
|
52 |
-
|
53 |
-
api_token = st.text_input("π API Token", value="my-secret-key", type="password")
|
54 |
-
if not api_token or api_token.strip() == "my-secret-key":
|
55 |
-
st.warning("π§ͺ Running in demo mode β for full access, enter a valid API key.")
|
56 |
-
|
57 |
-
backend_url = st.text_input("π Backend URL", value="http://localhost:8000")
|
58 |
-
|
59 |
-
sentiment_model = st.selectbox("π Sentiment Model", [
|
60 |
-
"Auto-detect",
|
61 |
-
"distilbert-base-uncased-finetuned-sst-2-english",
|
62 |
-
"nlptown/bert-base-multilingual-uncased-sentiment"
|
63 |
-
])
|
64 |
-
industry = st.selectbox("π Industry", ["Auto-detect", "Generic", "E-commerce", "Healthcare", "Education"])
|
65 |
-
product_category = st.selectbox("π§© Product Category", ["Auto-detect", "General", "Mobile Devices", "Laptops"])
|
66 |
-
use_aspects = st.checkbox("π¬ Enable Aspect Analysis")
|
67 |
-
use_explain_bulk = st.checkbox("π§ Generate Explanations (Bulk)")
|
68 |
-
verbosity = st.radio("π£οΈ Response Style", ["Brief", "Detailed"])
|
69 |
-
voice_lang = st.selectbox("π Voice Language", ["en", "fr", "es", "de", "hi", "zh"])
|
70 |
-
|
71 |
-
# TTS
|
72 |
-
def speak(text, lang='en'):
|
73 |
-
tts = gTTS(text, lang=lang)
|
74 |
-
mp3 = BytesIO()
|
75 |
-
tts.write_to_fp(mp3)
|
76 |
-
b64 = base64.b64encode(mp3.getvalue()).decode()
|
77 |
-
st.markdown(f'<audio controls><source src="data:audio/mp3;base64,{b64}" type="audio/mp3"></audio>', unsafe_allow_html=True)
|
78 |
-
mp3.seek(0)
|
79 |
-
return mp3
|
80 |
-
|
81 |
-
tab1, tab2 = st.tabs(["π§ Single Review", "π Bulk CSV"])
|
82 |
-
|
83 |
-
# ==== SINGLE REVIEW ====
|
84 |
-
with tab1:
|
85 |
-
st.title("π§ NeuroPulse AI β Multimodal Review Analyzer")
|
86 |
-
st.markdown("<div style='font-size:16px;color:#888;'>Minimum 20β50 words recommended.</div>", unsafe_allow_html=True)
|
87 |
-
|
88 |
-
review = st.text_area("π Enter Review", value=st.session_state.review, height=180)
|
89 |
-
st.session_state.review = review
|
90 |
-
|
91 |
-
col1, col2, col3 = st.columns(3)
|
92 |
-
with col1:
|
93 |
-
analyze = st.button("π Analyze")
|
94 |
-
with col2:
|
95 |
-
if st.button("π² Example"):
|
96 |
-
st.session_state.review = (
|
97 |
-
"I love this phone! Super fast performance, great battery, and smooth UI. "
|
98 |
-
"Camera is awesome too, though the price is a bit high. Overall, very happy."
|
99 |
-
)
|
100 |
-
st.session_state.trigger_example_analysis = True
|
101 |
-
st.rerun()
|
102 |
-
with col3:
|
103 |
-
if st.button("π§Ή Clear"):
|
104 |
-
for key in ["review", "last_response", "followup_answer"]:
|
105 |
-
st.session_state[key] = ""
|
106 |
-
st.rerun()
|
107 |
-
|
108 |
-
if (analyze or st.session_state.trigger_example_analysis) and st.session_state.review:
|
109 |
-
st.session_state.trigger_example_analysis = False
|
110 |
-
st.session_state.followup_answer = None
|
111 |
-
with st.spinner("Analyzing..."):
|
112 |
-
try:
|
113 |
-
model = None if sentiment_model == "Auto-detect" else sentiment_model
|
114 |
-
payload = {
|
115 |
-
"text": st.session_state.review,
|
116 |
-
"model": model or "distilbert-base-uncased-finetuned-sst-2-english",
|
117 |
-
"industry": industry,
|
118 |
-
"product_category": product_category,
|
119 |
-
"verbosity": verbosity,
|
120 |
-
"aspects": use_aspects,
|
121 |
-
"intelligence": st.session_state.intelligence_mode
|
122 |
-
}
|
123 |
-
headers = {"x-api-key": api_token}
|
124 |
-
res = requests.post(f"{backend_url}/analyze/", json=payload, headers=headers)
|
125 |
-
if res.status_code == 200:
|
126 |
-
st.session_state.last_response = res.json()
|
127 |
-
else:
|
128 |
-
st.error(f"API error: {res.status_code} - {res.json().get('detail')}")
|
129 |
-
except Exception as e:
|
130 |
-
st.error(f"π« Exception: {e}")
|
131 |
-
|
132 |
-
data = st.session_state.last_response
|
133 |
-
if data:
|
134 |
-
st.subheader("π Summary")
|
135 |
-
st.info(data["summary"])
|
136 |
-
st.caption("π§ Summary Model: facebook/bart-large-cnn | " + verbosity + " response")
|
137 |
-
st.markdown(f"**Context:** `{data['industry']}` | `{data['product_category']}` | `Web`")
|
138 |
-
|
139 |
-
st.metric("π Sentiment", data["sentiment"]["label"], delta=f"{data['sentiment']['score']:.2%}")
|
140 |
-
st.info(f"π’ Emotion: {data['emotion']}")
|
141 |
-
st.subheader("π Audio")
|
142 |
-
audio = speak(data["summary"], lang=voice_lang)
|
143 |
-
st.download_button("β¬οΈ Download Summary Audio", audio.read(), "summary.mp3")
|
144 |
-
|
145 |
-
st.markdown("### π Got questions?")
|
146 |
-
sample_questions = ["What did the user like most?", "Any complaints mentioned?", "Is it positive overall?"]
|
147 |
-
selected_q = st.selectbox("π‘ Sample Questions", ["Type your own..."] + sample_questions)
|
148 |
-
custom_q = selected_q if selected_q != "Type your own..." else st.text_input("π Ask a follow-up")
|
149 |
-
|
150 |
-
if custom_q:
|
151 |
-
with st.spinner("Thinking..."):
|
152 |
-
try:
|
153 |
-
follow_payload = {
|
154 |
-
"text": st.session_state.review,
|
155 |
-
"question": custom_q,
|
156 |
-
"verbosity": verbosity
|
157 |
-
}
|
158 |
-
headers = {"x-api-key": api_token}
|
159 |
-
res = requests.post(f"{backend_url}/followup/", json=follow_payload, headers=headers)
|
160 |
-
if res.status_code == 200:
|
161 |
-
st.session_state.followup_answer = res.json().get("answer")
|
162 |
-
else:
|
163 |
-
st.error(f"β Follow-up failed: {res.json().get('detail')}")
|
164 |
-
except Exception as e:
|
165 |
-
st.error(f"β οΈ Follow-up error: {e}")
|
166 |
-
|
167 |
-
if st.session_state.followup_answer:
|
168 |
-
st.subheader("π Follow-Up Answer")
|
169 |
-
st.success(st.session_state.followup_answer)
|
170 |
-
|
171 |
-
# ==== BULK CSV ====
|
172 |
-
with tab2:
|
173 |
-
st.title("π Bulk CSV Upload")
|
174 |
-
st.markdown("""
|
175 |
-
Upload a CSV with columns:<br>
|
176 |
-
<code>review</code>, <code>industry</code>, <code>product_category</code>, <code>device</code>, <code>follow_up</code> (optional)
|
177 |
-
""", unsafe_allow_html=True)
|
178 |
-
|
179 |
-
with st.expander("π Sample CSV"):
|
180 |
-
with open("sample_reviews.csv", "rb") as f:
|
181 |
-
st.download_button("β¬οΈ Download sample CSV", f, file_name="sample_reviews.csv")
|
182 |
-
|
183 |
-
uploaded_file = st.file_uploader("π Upload your CSV", type="csv")
|
184 |
-
|
185 |
-
if uploaded_file:
|
186 |
-
if not api_token:
|
187 |
-
st.error("π Please enter your API token in the sidebar.")
|
188 |
-
else:
|
189 |
-
try:
|
190 |
-
df = pd.read_csv(uploaded_file)
|
191 |
-
if "review" not in df.columns:
|
192 |
-
st.error("CSV must contain a `review` column.")
|
193 |
-
else:
|
194 |
-
for col in ["industry", "product_category", "device", "follow_up"]:
|
195 |
-
if col not in df.columns:
|
196 |
-
df[col] = ["Auto-detect"] * len(df)
|
197 |
-
df[col] = df[col].fillna("Auto-detect").astype(str)
|
198 |
-
|
199 |
-
df["industry"] = df["industry"].apply(lambda x: "Generic" if x.lower() == "auto-detect" else x)
|
200 |
-
df["product_category"] = df["product_category"].apply(lambda x: "General" if x.lower() == "auto-detect" else x)
|
201 |
-
df["device"] = df["device"].apply(lambda x: "Web" if x.lower() == "auto-detect" else x)
|
202 |
-
|
203 |
-
if st.button("π Analyze Bulk Reviews", use_container_width=True):
|
204 |
-
with st.spinner("Processing..."):
|
205 |
-
try:
|
206 |
-
payload = {
|
207 |
-
"reviews": df["review"].tolist(),
|
208 |
-
"model": None if sentiment_model == "Auto-detect" else sentiment_model,
|
209 |
-
"industry": df["industry"].tolist(),
|
210 |
-
"product_category": df["product_category"].tolist(),
|
211 |
-
"device": df["device"].tolist(),
|
212 |
-
"follow_up": df["follow_up"].tolist(),
|
213 |
-
"explain": use_explain_bulk,
|
214 |
-
"aspects": use_aspects,
|
215 |
-
"intelligence": st.session_state.intelligence_mode
|
216 |
-
}
|
217 |
-
res = requests.post(f"{backend_url}/bulk/?token={api_token}", json=payload)
|
218 |
-
if res.status_code == 200:
|
219 |
-
results = pd.DataFrame(res.json()["results"])
|
220 |
-
st.dataframe(results)
|
221 |
-
if "sentiment" in results.columns:
|
222 |
-
fig = px.pie(results, names="sentiment", title="Sentiment Distribution")
|
223 |
-
st.plotly_chart(fig)
|
224 |
-
st.download_button("β¬οΈ Download Results CSV", results.to_csv(index=False), "results.csv", mime="text/csv")
|
225 |
-
else:
|
226 |
-
st.error(f"β Bulk Error {res.status_code}: {res.json().get('detail')}")
|
227 |
-
except Exception as e:
|
228 |
-
st.error(f"π¨ Bulk Processing Error: {e}")
|
229 |
-
except Exception as e:
|
230 |
-
st.error(f"β File Read Error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|