File size: 10,575 Bytes
fc94552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import streamlit as st
import requests
import pandas as pd
from gtts import gTTS
import base64
from io import BytesIO
import os
import plotly.express as px

st.set_page_config(page_title="NeuroPulse AI", page_icon="🧠", layout="wide")

if os.path.exists("logo.png"):
    st.image("logo.png", width=180)

# Session state setup
defaults = {
    "review": "",
    "dark_mode": False,
    "intelligence_mode": True,
    "trigger_example_analysis": False,
    "last_response": None,
    "followup_answer": None
}
for k, v in defaults.items():
    if k not in st.session_state:
        st.session_state[k] = v

# Dark mode styling
if st.session_state.dark_mode:
    st.markdown("""
    <style>
    html, body, [class*="st-"] {
        background-color: #121212;
        color: #f5f5f5;
    }
    .stTextInput > div > div > input,
    .stTextArea > div > textarea,
    .stSelectbox div div,
    .stDownloadButton > button,
    .stButton > button {
        background-color: #1e1e1e;
        color: white;
    }
    </style>
    """, unsafe_allow_html=True)

# Sidebar settings
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", value="my-secret-key", type="password")
    if not api_token or api_token.strip() == "my-secret-key":
        st.warning("πŸ§ͺ Running in demo mode β€” for full access, enter a valid API key.")

    backend_url = st.text_input("🌐 Backend URL", value="http://localhost:8000")

    sentiment_model = st.selectbox("πŸ“Š Sentiment Model", [
        "Auto-detect", 
        "distilbert-base-uncased-finetuned-sst-2-english",
        "nlptown/bert-base-multilingual-uncased-sentiment"
    ])
    industry = st.selectbox("🏭 Industry", ["Auto-detect", "Generic", "E-commerce", "Healthcare", "Education"])
    product_category = st.selectbox("🧩 Product Category", ["Auto-detect", "General", "Mobile Devices", "Laptops"])
    use_aspects = st.checkbox("πŸ”¬ Enable Aspect Analysis")
    use_explain_bulk = st.checkbox("🧠 Generate Explanations (Bulk)")
    verbosity = st.radio("πŸ—£οΈ Response Style", ["Brief", "Detailed"])
    voice_lang = st.selectbox("πŸ”ˆ Voice Language", ["en", "fr", "es", "de", "hi", "zh"])

# TTS
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

tab1, tab2 = st.tabs(["🧠 Single Review", "πŸ“š Bulk CSV"])

# ==== SINGLE REVIEW ====
with tab1:
    st.title("🧠 NeuroPulse AI – Multimodal Review Analyzer")
    st.markdown("<div style='font-size:16px;color:#888;'>Minimum 20–50 words recommended.</div>", unsafe_allow_html=True)

    review = st.text_area("πŸ“ Enter Review", value=st.session_state.review, height=180)
    st.session_state.review = review

    col1, col2, col3 = st.columns(3)
    with col1:
        analyze = st.button("πŸ” Analyze")
    with col2:
        if st.button("🎲 Example"):
            st.session_state.review = (
                "I love this phone! Super fast performance, great battery, and smooth UI. "
                "Camera is awesome too, though the price is a bit high. Overall, very happy."
            )
            st.session_state.trigger_example_analysis = True
            st.rerun()
    with col3:
        if st.button("🧹 Clear"):
            for key in ["review", "last_response", "followup_answer"]:
                st.session_state[key] = ""
            st.rerun()

    if (analyze or st.session_state.trigger_example_analysis) and st.session_state.review:
        st.session_state.trigger_example_analysis = False
        st.session_state.followup_answer = None
        with st.spinner("Analyzing..."):
            try:
                model = None if sentiment_model == "Auto-detect" else sentiment_model
                payload = {
                    "text": st.session_state.review,
                    "model": model or "distilbert-base-uncased-finetuned-sst-2-english",
                    "industry": industry,
                    "product_category": product_category,
                    "verbosity": verbosity,
                    "aspects": use_aspects,
                    "intelligence": st.session_state.intelligence_mode
                }
                headers = {"x-api-key": api_token}
                res = requests.post(f"{backend_url}/analyze/", json=payload, headers=headers)
                if res.status_code == 200:
                    st.session_state.last_response = res.json()
                else:
                    st.error(f"API error: {res.status_code} - {res.json().get('detail')}")
            except Exception as e:
                st.error(f"🚫 Exception: {e}")

    data = st.session_state.last_response
    if data:
        st.subheader("πŸ“Œ Summary")
        st.info(data["summary"])
        st.caption("🧠 Summary Model: facebook/bart-large-cnn | " + verbosity + " response")
        st.markdown(f"**Context:** `{data['industry']}` | `{data['product_category']}` | `Web`")

        st.metric("πŸ“Š Sentiment", data["sentiment"]["label"], delta=f"{data['sentiment']['score']:.2%}")
        st.info(f"πŸ’’ Emotion: {data['emotion']}")
        st.subheader("πŸ”Š Audio")
        audio = speak(data["summary"], lang=voice_lang)
        st.download_button("⬇️ Download Summary Audio", audio.read(), "summary.mp3")

        st.markdown("### πŸ” Got questions?")
        sample_questions = ["What did the user like most?", "Any complaints mentioned?", "Is it positive overall?"]
        selected_q = st.selectbox("πŸ’‘ Sample Questions", ["Type your own..."] + sample_questions)
        custom_q = selected_q if selected_q != "Type your own..." else st.text_input("πŸ” Ask a follow-up")

        if custom_q:
            with st.spinner("Thinking..."):
                try:
                    follow_payload = {
                        "text": st.session_state.review,
                        "question": custom_q,
                        "verbosity": verbosity
                    }
                    headers = {"x-api-key": api_token}
                    res = requests.post(f"{backend_url}/followup/", json=follow_payload, headers=headers)
                    if res.status_code == 200:
                        st.session_state.followup_answer = res.json().get("answer")
                    else:
                        st.error(f"❌ Follow-up failed: {res.json().get('detail')}")
                except Exception as e:
                    st.error(f"⚠️ Follow-up error: {e}")

    if st.session_state.followup_answer:
        st.subheader("πŸ” Follow-Up Answer")
        st.success(st.session_state.followup_answer)

# ==== BULK CSV ====
with tab2:
    st.title("πŸ“š Bulk CSV Upload")
    st.markdown("""
    Upload a CSV with columns:<br>
    <code>review</code>, <code>industry</code>, <code>product_category</code>, <code>device</code>, <code>follow_up</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:
        if not api_token:
            st.error("πŸ” Please enter your API token in the sidebar.")
        else:
            try:
                df = pd.read_csv(uploaded_file)
                if "review" not in df.columns:
                    st.error("CSV must contain a `review` column.")
                else:
                    for col in ["industry", "product_category", "device", "follow_up"]:
                        if col not in df.columns:
                            df[col] = ["Auto-detect"] * len(df)
                        df[col] = df[col].fillna("Auto-detect").astype(str)

                    df["industry"] = df["industry"].apply(lambda x: "Generic" if x.lower() == "auto-detect" else x)
                    df["product_category"] = df["product_category"].apply(lambda x: "General" if x.lower() == "auto-detect" else x)
                    df["device"] = df["device"].apply(lambda x: "Web" if x.lower() == "auto-detect" else x)

                    if st.button("πŸ“Š Analyze Bulk Reviews", use_container_width=True):
                        with st.spinner("Processing..."):
                            try:
                                payload = {
                                    "reviews": df["review"].tolist(),
                                    "model": None if sentiment_model == "Auto-detect" else sentiment_model,
                                    "industry": df["industry"].tolist(),
                                    "product_category": df["product_category"].tolist(),
                                    "device": df["device"].tolist(),
                                    "follow_up": df["follow_up"].tolist(),
                                    "explain": use_explain_bulk,
                                    "aspects": use_aspects,
                                    "intelligence": st.session_state.intelligence_mode
                                }
                                res = requests.post(f"{backend_url}/bulk/?token={api_token}", json=payload)
                                if res.status_code == 200:
                                    results = pd.DataFrame(res.json()["results"])
                                    st.dataframe(results)
                                    if "sentiment" in results.columns:
                                        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')}")
                            except Exception as e:
                                st.error(f"🚨 Bulk Processing Error: {e}")
            except Exception as e:
                st.error(f"❌ File Read Error: {e}")