Hasitha16 commited on
Commit
9aa56c6
Β·
verified Β·
1 Parent(s): 555c12b

Update frontend.py

Browse files
Files changed (1) hide show
  1. frontend.py +32 -85
frontend.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import streamlit as st
2
  import requests
3
  import pandas as pd
@@ -7,7 +9,7 @@ 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)
@@ -44,15 +46,15 @@ if st.session_state.dark_mode:
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
 
@@ -63,8 +65,8 @@ with st.sidebar:
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
 
@@ -78,14 +80,14 @@ def speak(text, lang='en'):
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)
@@ -94,8 +96,8 @@ with tab1:
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()
@@ -108,7 +110,7 @@ with tab1:
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 = {
@@ -131,21 +133,27 @@ with tab1:
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..."):
@@ -165,66 +173,5 @@ with tab1:
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}")
 
1
+ # [STREAMLIT FRONTEND - Product Feedback AI Assistant]
2
+
3
  import streamlit as st
4
  import requests
5
  import pandas as pd
 
9
  import os
10
  import plotly.express as px
11
 
12
+ st.set_page_config(page_title="PM Feedback Assistant", page_icon="🧠", layout="wide")
13
 
14
  if os.path.exists("logo.png"):
15
  st.image("logo.png", width=180)
 
46
  </style>
47
  """, unsafe_allow_html=True)
48
 
49
+ # Sidebar
50
  with st.sidebar:
51
+ st.header("βš™οΈ PM Config")
52
  st.session_state.dark_mode = st.toggle("πŸŒ™ Dark Mode", value=st.session_state.dark_mode)
53
  st.session_state.intelligence_mode = st.toggle("🧠 Intelligence Mode", value=st.session_state.intelligence_mode)
54
 
55
  api_token = st.text_input("πŸ” API Token", value="my-secret-key", type="password")
56
  if not api_token or api_token.strip() == "my-secret-key":
57
+ st.warning("πŸ§ͺ Demo Mode β€” Not all features active.")
58
 
59
  backend_url = st.text_input("🌐 Backend URL", value="http://localhost:8000")
60
 
 
65
  ])
66
  industry = st.selectbox("🏭 Industry", ["Auto-detect", "Generic", "E-commerce", "Healthcare", "Education"])
67
  product_category = st.selectbox("🧩 Product Category", ["Auto-detect", "General", "Mobile Devices", "Laptops"])
68
+ use_aspects = st.checkbox("πŸ” Detect Pain Points")
69
+ use_explain_bulk = st.checkbox("🧠 Generate PM Insight (Bulk)")
70
  verbosity = st.radio("πŸ—£οΈ Response Style", ["Brief", "Detailed"])
71
  voice_lang = st.selectbox("πŸ”ˆ Voice Language", ["en", "fr", "es", "de", "hi", "zh"])
72
 
 
80
  mp3.seek(0)
81
  return mp3
82
 
83
+ tab1, tab2 = st.tabs(["🧠 Analyze Review", "πŸ“š Bulk Reviews"])
84
 
85
+ # === SINGLE REVIEW ===
86
  with tab1:
87
+ st.title("πŸ“Š Product Feedback AI Assistant")
88
+ st.markdown("Get insights from real user feedback to reduce churn and improve product strategy.")
89
 
90
+ review = st.text_area("πŸ“ Enter Customer Feedback", value=st.session_state.review, height=180)
91
  st.session_state.review = review
92
 
93
  col1, col2, col3 = st.columns(3)
 
96
  with col2:
97
  if st.button("🎲 Example"):
98
  st.session_state.review = (
99
+ "The app crashes every time I try to checkout. It's so slow and unresponsive. "
100
+ "Customer support never replied. I'm switching to another brand."
101
  )
102
  st.session_state.trigger_example_analysis = True
103
  st.rerun()
 
110
  if (analyze or st.session_state.trigger_example_analysis) and st.session_state.review:
111
  st.session_state.trigger_example_analysis = False
112
  st.session_state.followup_answer = None
113
+ with st.spinner("Analyzing feedback..."):
114
  try:
115
  model = None if sentiment_model == "Auto-detect" else sentiment_model
116
  payload = {
 
133
 
134
  data = st.session_state.last_response
135
  if data:
136
+ st.subheader("πŸ“Œ PM Insight Summary")
137
  st.info(data["summary"])
138
+ st.caption("πŸ”Ž Summary Model: facebook/bart-large-cnn | " + verbosity + " response")
139
+ st.markdown(f"**Industry:** `{data['industry']}` | **Category:** `{data['product_category']}` | **Device:** Web")
140
 
141
  st.metric("πŸ“Š Sentiment", data["sentiment"]["label"], delta=f"{data['sentiment']['score']:.2%}")
142
  st.info(f"πŸ’’ Emotion: {data['emotion']}")
143
+
144
+ if "churn_risk" in data:
145
+ st.warning(f"⚠️ Estimated Churn Risk: {data['churn_risk']}")
146
+ if "pain_points" in data and data["pain_points"]:
147
+ st.error("πŸ” Pain Points: " + ", ".join(data["pain_points"]))
148
+
149
+ st.subheader("πŸ”Š Audio Summary")
150
  audio = speak(data["summary"], lang=voice_lang)
151
+ st.download_button("⬇️ Download Audio", audio.read(), "summary.mp3")
152
 
153
+ st.markdown("### πŸ” Ask a Follow-Up")
154
+ sample_questions = ["What made the user upset?", "Any feature complaints?", "How urgent is this?"]
155
+ selected_q = st.selectbox("πŸ’‘ Suggested Questions", ["Type your own..."] + sample_questions)
156
+ custom_q = selected_q if selected_q != "Type your own..." else st.text_input("πŸ” Follow-up Question")
157
 
158
  if custom_q:
159
  with st.spinner("Thinking..."):
 
173
  st.error(f"⚠️ Follow-up error: {e}")
174
 
175
  if st.session_state.followup_answer:
176
+ st.subheader("βœ… Answer")
177
  st.success(st.session_state.followup_answer)