import streamlit as st import pandas as pd from wordcloud import WordCloud import matplotlib.pyplot as plt from transformers import pipeline # Load Hugging Face models sentiment_analyzer = pipeline("sentiment-analysis") summarizer = pipeline("summarization") st.set_page_config(page_title="Sentiment Analysis App", layout="wide") st.title("📊 Sentiment Analysis of e-Consultation Comments") st.write("Analyze single or multiple comments: sentiment, summary, and word cloud.") # --- Sidebar mode selection --- mode = st.sidebar.radio("Choose mode:", ["Single Comment", "Upload File"]) # --- Mode 1: Single Comment Analysis --- if mode == "Single Comment": user_input = st.text_area("Enter a comment:", height=150) if st.button("Analyze Comment"): if user_input.strip(): # Sentiment sentiment = sentiment_analyzer(user_input)[0] st.subheader("🔹 Sentiment Analysis") st.write(f"**Label:** {sentiment['label']} | **Score:** {sentiment['score']:.2f}") # Summarization (if long enough) if len(user_input.split()) > 30: summary = summarizer(user_input, max_length=50, min_length=20, do_sample=False)[0]['summary_text'] st.subheader("🔹 Summary") st.write(summary) else: st.info("Not enough text for summarization (need > 30 words).") # Word Cloud st.subheader("🔹 Word Cloud") wordcloud = WordCloud(width=800, height=400, background_color="white").generate(user_input) fig, ax = plt.subplots(figsize=(10, 5)) ax.imshow(wordcloud, interpolation="bilinear") ax.axis("off") st.pyplot(fig) else: st.warning("⚠️ Please enter a comment before analyzing.") # --- Mode 2: Batch Analysis from File --- else: st.info("Upload a CSV or Excel file containing a column named **comment**.") uploaded_file = st.file_uploader("Upload file", type=["csv", "xlsx"]) if uploaded_file: # Read file if uploaded_file.name.endswith(".csv"): df = pd.read_csv(uploaded_file) else: df = pd.read_excel(uploaded_file) if "comment" not in df.columns: st.error("❌ File must contain a column named 'comment'.") else: st.write("### Uploaded Data", df.head()) if st.button("Analyze All Comments"): sentiments = [] all_text = " " for text in df["comment"].dropna(): result = sentiment_analyzer(str(text))[0] sentiments.append(result["label"]) all_text += " " + str(text) df["sentiment"] = sentiments st.subheader("🔹 Sentiment Results") st.write(df) # Overall Word Cloud st.subheader("🔹 Word Cloud (All Comments)") wordcloud = WordCloud(width=800, height=400, background_color="white").generate(all_text) fig, ax = plt.subplots(figsize=(10, 5)) ax.imshow(wordcloud, interpolation="bilinear") ax.axis("off") st.pyplot(fig) # Sentiment Distribution st.subheader("🔹 Sentiment Distribution") st.bar_chart(df["sentiment"].value_counts())