Spaces:
Sleeping

File size: 9,002 Bytes
339e91b
 
 
5b4d2a8
d24742b
bef6158
d24742b
634da92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d24742b
 
5b4d2a8
339e91b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d24742b
 
339e91b
 
 
 
 
 
d24742b
 
 
 
 
339e91b
d24742b
339e91b
 
 
 
 
 
 
 
d24742b
 
 
 
 
339e91b
 
 
 
 
 
d24742b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339e91b
d24742b
 
 
 
 
 
 
339e91b
 
 
 
 
 
d24742b
 
 
339e91b
 
 
 
 
 
 
d24742b
339e91b
 
 
 
 
 
d24742b
 
339e91b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d24742b
339e91b
 
 
 
 
 
 
 
 
d24742b
339e91b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import time
from datetime import datetime
from typing import Dict
import streamlit as st
import pandas as pd

# homemade helpers

# ---------- Helpers ----------
def parse_comment_file(file_content: str) -> Dict:
    """Parse comment file and validate simple `comment | rating` format."""
    return none 


def count_words(text: str) -> int:
    return len(text.split()) if text.strip() else 0


def generate_mock_analysis(comment_count: int, original_text: str) -> Dict:
    """Returns a deterministic mock analysis payload."""
    return {
        "id": str(int(time.time())),
        "summary": (
            f"Based on analysis of {comment_count} customer comments, the feedback shows strong overall "
            "satisfaction with the product. Customers appreciate quality, intuitive design, and value. "
            "Pain points: shipping times and initial setup. Sentiment is mostly positive."
        ),
        "key_themes": [
            "Product Quality",
            "Ease of Use",
            "Value for Money",
            "Shipping & Delivery",
            "Customer Support",
            "Design & Functionality",
            "Reliability",
        ],
        "sentiment": {"positive": 72, "neutral": 18, "negative": 10},
        "insights": [
            "Quality and design receive the highest praise.",
            "Shipping and delivery times are primary pain points.",
            "Customer support responsiveness is well-regarded.",
            "Value perception is strong across segments.",
            "Reliability meets or exceeds expectations.",
            "Setup complexity is a minor barrier for some.",
        ],
        "timestamp": datetime.now().isoformat(),
    }


#TODO add a slider selecting how many lines of summarized text we want

# ---------- Page config ----------
st.set_page_config(
    page_title="Comment Summary AI",
    page_icon="💬",
    layout="wide",
    initial_sidebar_state="collapsed",
)

# ---------- Styles ----------
st.markdown(
    """
<style>
    .main-header {
        background: white;
        padding: 1rem 2rem;
        border-bottom: 1px solid #e2e8f0;
        margin: -1rem -1rem 2rem -1rem;
    }
    .metric-card {
        background: white;
        padding: 1rem;
        border-radius: 0.5rem;
        border: 1px solid #e2e8f0;
        margin: 0.5rem 0;
    }
    .sentiment-positive { background:#dcfce7; color:#166534; padding:0.25rem 0.5rem; border-radius:0.25rem; font-size:0.75rem; }
    .sentiment-neutral  { background:#f3f4f6; color:#374151; padding:0.25rem 0.5rem; border-radius:0.25rem; font-size:0.75rem; }
    .sentiment-negative { background:#fecaca; color:#991b1b; padding:0.25rem 0.5rem; border-radius:0.25rem; font-size:0.75rem; }
    .theme-badge {
        background:#f1f5f9; color:#334155; padding:0.25rem 0.5rem; border-radius:0.25rem; font-size:0.75rem;
        margin:0.25rem; display:inline-block; border:1px solid #e2e8f0;
    }
    .insight-item {
        display:flex; align-items:flex-start; margin:0.5rem 0; padding:0.5rem; background:#f8fafc; border-radius:0.25rem;
    }
</style>
""",
    unsafe_allow_html=True,
)

# ---------- Session state ----------
ss = st.session_state
ss.setdefault("comment_file", None)
ss.setdefault("comment_content", "")
ss.setdefault("target_text", "")
ss.setdefault("target_text_file", None)  # target file is the press release.
ss.setdefault("analysis_result", None)
ss.setdefault("is_loading", False)




# ---------- Title ----------
st.title(
    "_AI_ comment :blue[analyzer] :brain:"
    )
# ---------- Subtitle ----------

st.text(
    "Upload a comments file and the original text to generate a concise summary with themes and sentiment."
)

# ---------- Inputs ----------
left, right = st.columns(2)

with left:
    st.markdown("### Comments File")
    ss.comments_file = st.file_uploader("Upload .csv with `comment, rating, theme` per line", type=["csv"], key="comment_file_uploader")
    if ss.comments_file is not None:
        df_comments = pd.read_csv(ss.comments_file, sep=",", header=0)
        st.dataframe(df_comments)
        st.success(f"✅ {ss.comments_file.name} — {len(df_comments)} comments")
    elif ss.comment_file:
        st.info(f"📄 Loaded: {ss.comment_file['comment_count']} comments")

with right:
    st.markdown("### Original Text")
    st.caption("Press release / article / product description being discussed.")

    uploaded_file = st.file_uploader("Upload .txt", type=["txt"], key="original_file_uploader")

    if uploaded_file is not None:
        # read file content as text
        text_content = uploaded_file.read().decode("utf-8", errors="replace")

        # store in session state
        ss.target_text_file = {
            "content": text_content,
            "word_count": count_words(text_content),
            "name": uploaded_file.name,
        }
        ss.target_text = text_content

        # show success message
        st.success(f"✅ {uploaded_file.name} — {ss.target_text_file['word_count']} words")

        # preview
        with st.expander("Preview"):
            preview = text_content[:800] + ("..." if len(text_content) > 800 else "")
            st.text(preview)

    elif ss.get("target_text_file"):
        # fallback if already stored in session
        st.info(f"📄 Loaded: {ss.target_text_file['word_count']} words")


    st.markdown("---")
    st.markdown("**Or paste text:**")
    pasted = st.text_area("Paste original text here…", height=150, key="direct_text_input")
    if st.button("Use Pasted Text"):
        if pasted.strip():
            ss.target_text_file = {"content": pasted, "word_count": count_words(pasted), "name": "Manual Input"}
            ss.target_text = pasted
            st.success(f"✅ Text added — {ss.target_text_file['word_count']} words")
            st.rerun()

# ---------- Controls ----------
st.markdown("---")
st.markdown("## AI Analysis")
st.caption("Preset prompt: *Analyze customer feedback to create a comprehensive summary.*")

can_run = bool(ss.comment_file and ss.target_text_file)
c1, c2, _ = st.columns([1, 1, 4])

with c1:
    if st.button("🔄 Reset", disabled=ss.is_loading):
        ss.comment_file = None
        ss.comment_content = ""
        ss.target_text = ""
        ss.target_text_file = None
        ss.analysis_result = None
        ss.is_loading = False
        st.rerun()

with c2:
    if st.button("▶️ Run Analysis", disabled=(not can_run) or ss.is_loading):
        if can_run:
            ss.is_loading = True
            st.rerun()

# ---------- Analysis runner ----------
if ss.is_loading:
    with st.spinner("Analyzing comments…"):
        time.sleep(2.0)  # simulate work
        ss.analysis_result = generate_mock_analysis(
            ss.comment_file["comment_count"], ss.target_text
        )
        ss.is_loading = False
        st.rerun()

# ---------- Guidance if inputs missing ----------
if not can_run and not ss.analysis_result:
    st.warning("⚠️ Missing required inputs.")
    if not ss.comment_file:
        st.markdown("- Upload a comments file (`comment | rating` per line).")
    if not ss.target_text_file:
        st.markdown("- Provide the original text (upload or paste).")

# ---------- Results ----------
if ss.analysis_result:
    res = ss.analysis_result
    st.markdown("---")
    st.markdown("## ✨ Generated Summary")
    ts = datetime.fromisoformat(res["timestamp"]).strftime("%H:%M:%S")
    st.caption(f"Generated at {ts}")

    st.markdown("### Summary")
    st.write(res["summary"])

    col_a, col_b = st.columns(2)
    with col_a:
        st.markdown("### Key Themes")
        st.markdown("".join(f'<span class="theme-badge">{t}</span>' for t in res["key_themes"]), unsafe_allow_html=True)

    with col_b:
        st.markdown("### Sentiment Distribution")
        sent = res["sentiment"]
        st.markdown(
            f"""
<div style="margin:0.5rem 0;">
  <div style="display:flex;justify-content:space-between;align-items:center;margin:0.5rem 0;">
    <span>Positive</span><span class="sentiment-positive">{sent['positive']}%</span>
  </div>
  <div style="display:flex;justify-content:space-between;align-items:center;margin:0.5rem 0;">
    <span>Neutral</span><span class="sentiment-neutral">{sent['neutral']}%</span>
  </div>
  <div style="display:flex;justify-content:space-between;align-items:center;margin:0.5rem 0;">
    <span>Negative</span><span class="sentiment-negative">{sent['negative']}%</span>
  </div>
</div>
""",
            unsafe_allow_html=True,
        )

    st.markdown("### Key Insights")
    for ins in res["insights"]:
        st.markdown(
            f"""
<div class="insight-item">
  <span style="margin-right:0.5rem;">📈</span>
  <span style="font-size:0.9rem; color:#475569;">{ins}</span>
</div>
""",
            unsafe_allow_html=True,
        )
else:
    st.markdown("---")
    st.markdown("## 📄 Summary will appear here")
    st.caption("Upload a comments file and the original text, then click **Run Analysis**.")