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( """ """, 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'{t}' for t in res["key_themes"]), unsafe_allow_html=True) with col_b: st.markdown("### Sentiment Distribution") sent = res["sentiment"] st.markdown( f"""