Pro-Coder commited on
Commit
5935e64
Β·
verified Β·
1 Parent(s): 711eab8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -56
app.py CHANGED
@@ -1,57 +1,90 @@
1
- # app.py
2
-
3
  import streamlit as st
4
- from modules.data_loader import load_texts
5
- from modules.preprocessing import preprocess_texts
6
- from modules.sentiment_analysis import analyze_sentiment
7
- from modules.summarizer import summarize_texts
8
- from modules.visualization import generate_wordcloud, plot_sentiment_distribution
9
- from modules.utils import save_results_to_csv, display_dataframe
10
- from config.settings import DATA_PATH
11
-
12
- # Title
13
- st.title("πŸ“Š Sentiment Analysis of E-Consultation Comments")
14
- st.write("AI-powered tool for sentiment analysis, summarization, and visualization.")
15
-
16
- # File uploader
17
- uploaded_file = st.file_uploader("Upload a .txt file (one comment per line)", type=["txt"])
18
-
19
- if uploaded_file:
20
- # Save uploaded file
21
- with open(DATA_PATH, "wb") as f:
22
- f.write(uploaded_file.read())
23
- st.success("βœ… File uploaded successfully!")
24
-
25
- # Load data
26
- texts = load_texts(DATA_PATH)
27
- st.write(f"Loaded **{len(texts)}** comments.")
28
-
29
- # Preprocess
30
- clean_texts = preprocess_texts(texts)
31
-
32
- # Sentiment Analysis
33
- st.subheader("πŸ” Sentiment Analysis")
34
- sentiment_results = analyze_sentiment(clean_texts)
35
- sentiment_chart = plot_sentiment_distribution(sentiment_results)
36
- st.image(sentiment_chart, caption="Sentiment Distribution")
37
-
38
- # Summarization
39
- st.subheader("πŸ“ Summarization")
40
- summaries = summarize_texts(clean_texts)
41
- st.write("Here are some summaries:")
42
- for s in summaries[:5]:
43
- st.write(f"- {s['summary']}")
44
-
45
- # Word Cloud
46
- st.subheader("☁ Word Cloud")
47
- wc_image = generate_wordcloud(clean_texts)
48
- st.image(wc_image, caption="Word Cloud of Comments")
49
-
50
- # Results Table
51
- st.subheader("πŸ“‘ Results Table")
52
- df = display_dataframe(sentiment_results, summaries)
53
- st.dataframe(df)
54
-
55
- # Save results
56
- results_path = save_results_to_csv(sentiment_results, summaries)
57
- st.download_button("πŸ“₯ Download Results CSV", data=open(results_path, "rb"), file_name="results.csv")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ from wordcloud import WordCloud
4
+ import matplotlib.pyplot as plt
5
+ from transformers import pipeline
6
+
7
+ # Load Hugging Face models
8
+ sentiment_analyzer = pipeline("sentiment-analysis")
9
+ summarizer = pipeline("summarization")
10
+
11
+ st.set_page_config(page_title="Sentiment Analysis App", layout="wide")
12
+
13
+ st.title("πŸ“Š Sentiment Analysis of e-Consultation Comments")
14
+ st.write("Analyze single or multiple comments: sentiment, summary, and word cloud.")
15
+
16
+ # --- Sidebar mode selection ---
17
+ mode = st.sidebar.radio("Choose mode:", ["Single Comment", "Upload File"])
18
+
19
+ # --- Mode 1: Single Comment Analysis ---
20
+ if mode == "Single Comment":
21
+ user_input = st.text_area("Enter a comment:", height=150)
22
+
23
+ if st.button("Analyze Comment"):
24
+ if user_input.strip():
25
+ # Sentiment
26
+ sentiment = sentiment_analyzer(user_input)[0]
27
+ st.subheader("πŸ”Ή Sentiment Analysis")
28
+ st.write(f"**Label:** {sentiment['label']} | **Score:** {sentiment['score']:.2f}")
29
+
30
+ # Summarization (if long enough)
31
+ if len(user_input.split()) > 30:
32
+ summary = summarizer(user_input, max_length=50, min_length=20, do_sample=False)[0]['summary_text']
33
+ st.subheader("πŸ”Ή Summary")
34
+ st.write(summary)
35
+ else:
36
+ st.info("Not enough text for summarization (need > 30 words).")
37
+
38
+ # Word Cloud
39
+ st.subheader("πŸ”Ή Word Cloud")
40
+ wordcloud = WordCloud(width=800, height=400, background_color="white").generate(user_input)
41
+ fig, ax = plt.subplots(figsize=(10, 5))
42
+ ax.imshow(wordcloud, interpolation="bilinear")
43
+ ax.axis("off")
44
+ st.pyplot(fig)
45
+ else:
46
+ st.warning("⚠️ Please enter a comment before analyzing.")
47
+
48
+ # --- Mode 2: Batch Analysis from File ---
49
+ else:
50
+ st.info("Upload a CSV or Excel file containing a column named **comment**.")
51
+
52
+ uploaded_file = st.file_uploader("Upload file", type=["csv", "xlsx"])
53
+
54
+ if uploaded_file:
55
+ # Read file
56
+ if uploaded_file.name.endswith(".csv"):
57
+ df = pd.read_csv(uploaded_file)
58
+ else:
59
+ df = pd.read_excel(uploaded_file)
60
+
61
+ if "comment" not in df.columns:
62
+ st.error("❌ File must contain a column named 'comment'.")
63
+ else:
64
+ st.write("### Uploaded Data", df.head())
65
+
66
+ if st.button("Analyze All Comments"):
67
+ sentiments = []
68
+ all_text = " "
69
+
70
+ for text in df["comment"].dropna():
71
+ result = sentiment_analyzer(str(text))[0]
72
+ sentiments.append(result["label"])
73
+ all_text += " " + str(text)
74
+
75
+ df["sentiment"] = sentiments
76
+
77
+ st.subheader("πŸ”Ή Sentiment Results")
78
+ st.write(df)
79
+
80
+ # Overall Word Cloud
81
+ st.subheader("πŸ”Ή Word Cloud (All Comments)")
82
+ wordcloud = WordCloud(width=800, height=400, background_color="white").generate(all_text)
83
+ fig, ax = plt.subplots(figsize=(10, 5))
84
+ ax.imshow(wordcloud, interpolation="bilinear")
85
+ ax.axis("off")
86
+ st.pyplot(fig)
87
+
88
+ # Sentiment Distribution
89
+ st.subheader("πŸ”Ή Sentiment Distribution")
90
+ st.bar_chart(df["sentiment"].value_counts())