Spaces:
Sleeping

Democus / src /streamlit_app.py
feldon0606's picture
Streamlit issue 5
634da92
Raw History Blame Contribute Delete
9 kB
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**.")