File size: 8,633 Bytes
a83deda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e76a85
7adc39b
 
0e76a85
 
a83deda
0e76a85
a83deda
0e76a85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83deda
 
 
 
 
 
 
 
 
 
0e76a85
 
 
 
 
 
7adc39b
0e76a85
7adc39b
 
0e76a85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7adc39b
0e76a85
 
7adc39b
0e76a85
7adc39b
0e76a85
 
 
 
 
7adc39b
 
0e76a85
 
7adc39b
0e76a85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7adc39b
0e76a85
 
 
 
 
 
 
 
 
 
 
 
 
13606c8
 
 
0e76a85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 defaults
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

# Shared Sidebar Controls
with st.sidebar:
    st.header("βš™οΈ Global Settings")
    st.session_state.dark_mode = st.toggle("πŸŒ™ Dark Mode", value=st.session_state.dark_mode)

    api_token = st.text_input("πŸ” API Token", type="password")
    backend_url = st.text_input("πŸ–₯️ Backend URL", value="http://0.0.0.0:8000")

    sentiment_model = st.selectbox("πŸ“Š Sentiment Model", [
        "distilbert-base-uncased-finetuned-sst-2-english",
        "nlptown/bert-base-multilingual-uncased-sentiment"
    ])

    industry = st.selectbox("🏭 Industry Context", [
        "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 Type", [
        "Auto-detect", "Web", "Android", "iOS", "Desktop", "Smartwatch", "Kiosk"
    ])

    use_aspects = st.checkbox("πŸ”¬ Enable Aspect Analysis")
    use_smart_summary = st.checkbox("🧠 Use Smart Summary (Single)")
    use_smart_summary_bulk = st.checkbox("🧠 Smart Summary for Bulk")
    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 for modes
tab1, tab2 = st.tabs(["🧠 Single Review", "πŸ“š Bulk CSV"])

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

    review = st.text_area("πŸ“ Enter a 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.error("⚠️ Please enter at least 50 words for meaningful analysis.")
        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
                    }
                    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 Summary' if use_smart_summary else 'Standard Model'}")
                        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"])
                    else:
                        st.error(f"❌ API Error: {res.status_code}")
                except Exception as e:
                    st.error(f"🚫 {e}")

# --- BULK REVIEW MODE ---
with tab2:
    st.title("πŸ“š Bulk CSV Upload")
    st.markdown("""
        <div style='font-size:16px;'>Upload a CSV with the following columns:<br>
        <code>review</code> <span style='color:#aaa;'>(required)</span>,
        <code>industry</code>, <code>product_category</code>, <code>device</code> <span style='color:#aaa;'>(optional)</span></div>
    """, 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 CSV..."):
                        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()
                            }
                            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"])
                                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}")
                        except Exception as e:
                            st.error(f"πŸ’₯ Error: {e}")
        except Exception as e:
            st.error(f"❌ File Error: {e}")