Spaces:
Runtime error
Runtime error
Update mca_comment_analyzer.py
Browse files123451 unmodified line7891011121314151617181920212223242526272829303132333435363738394041424344454674 unmodified lines121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169import osimport streamlit as stimport pandas as pdimport torchfrom transformers import pipeline1 unmodified lineimport matplotlib.pyplot as pltfrom collections import Counterimport nltkfrom nltk.corpus import stopwordsimport randomfrom datetime import datetime, timedelta# ---- Configos.environ["MPLCONFIGDIR"] = "/tmp/.matplotlib"st.set_page_config(page_title="MCA Demo Comment Analyzer", layout="wide")# ---- NLTKnltk.download('stopwords', quiet=True)STOPWORDS = set(stopwords.words('english'))# ---- Lightweight MCA Analyzerclass MCACommentAnalyzer:def __init__(self):device = 0 if torch.cuda.is_available() else -1print("Using device:", "GPU" if device==0 else "CPU")# Lightweight sentiment modelself.sentiment_model = pipeline("sentiment-analysis",model="distilbert-base-uncased-finetuned-sst-2-english",device=device)# Lightweight summarizerself.summarizer = pipeline("summarization",model="t5-small",device=device)self.stop_words = STOPWORDSdef map_sentiment(self, pred, text):74 unmodified linesif filename:plt.savefig(filename, bbox_inches='tight')return plt# ---- Streamlit UIst.title("π MCA Demo Comment Analyzer")st.sidebar.header("Upload or Enter Comments")upload_file = st.sidebar.file_uploader("Upload CSV/Excel/TXT", type=["csv","xlsx","txt"])manual_input = st.sidebar.text_area("Or enter comments manually (one per line)")comments = []if upload_file:try:if upload_file.name.endswith(".csv"):df_file = pd.read_csv(upload_file)if 'comment' in df_file.columns:comments = df_file['comment'].astype(str).tolist()else:comments = df_file.iloc[:,0].astype(str).tolist()elif upload_file.name.endswith(".xlsx"):df_file = pd.read_excel(upload_file)if 'comment' in df_file.columns:comments = df_file['comment'].astype(str).tolist()else:comments = df_file.iloc[:,0].astype(str).tolist()else:comments = upload_file.read().decode("utf-8").splitlines()except Exception as e:st.error(f"File format not supported or corrupted. {e}")elif manual_input.strip():comments = manual_input.strip().split("\n")if st.sidebar.button("Analyze"):if comments:analyzer = MCACommentAnalyzer()df, keyword_freq = analyzer.process_comments(comments)st.subheader("π Analysis Results")st.dataframe(df, use_container_width=True)st.subheader("π Sentiment Distribution")st.bar_chart(df["Sentiment"].value_counts())st.subheader("βοΈ Word Cloud")plt_obj = analyzer.generate_wordcloud(keyword_freq)st.pyplot(plt_obj)else:st.warning("β οΈ Provide comments manually or upload a supported file.")1234561 unmodified line891011121314151617181920212223242526272829303132333435363738394041424344454647484974 unmodified lines124125126# mca_comment_analyzer.pyimport osimport pandas as pdimport torchfrom transformers import pipeline1 unmodified lineimport matplotlib.pyplot as pltfrom collections import Counterimport nltkimport randomfrom datetime import datetime, timedelta# -----------------------------# Configs# -----------------------------os.environ["MPLCONFIGDIR"] = "/tmp/.matplotlib"os.environ["NLTK_DATA"] = "/tmp/nltk_data"# NLTK Stopwordsnltk.download('stopwords', download_dir="/tmp/nltk_data", quiet=True)from nltk.corpus import stopwordsSTOPWORDS = set(stopwords.words('english'))# -----------------------------# MCA Comment Analyzer# -----------------------------class MCACommentAnalyzer:def __init__(self):device = 0 if torch.cuda.is_available() else -1print("Using device:", "GPU" if device==0 else "CPU")# Sentiment modelself.sentiment_model = pipeline("sentiment-analysis",model="distilbert-base-uncased-finetuned-sst-2-english",device=device)# Summarizerself.summarizer = pipeline("summarization",model="t5-small",device=device)self.stop_words = STOPWORDSdef map_sentiment(self, pred, text):74 unmodified linesif filename:plt.savefig(filename, bbox_inches='tight')return plt
mca_comment_analyzer.py+17-60