Pro-Coder commited on
Commit
4aaebc3
Β·
verified Β·
1 Parent(s): a35916e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -85
app.py CHANGED
@@ -1,85 +1,57 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- from wordcloud import WordCloud
4
- import matplotlib
5
- matplotlib.use("Agg") # fix for HF Spaces
6
- import matplotlib.pyplot as plt
7
- import io
8
- import pandas as pd
9
-
10
- # Load Hugging Face pipelines with smaller stable models
11
- sentiment_model = pipeline(
12
- "sentiment-analysis",
13
- model="distilbert-base-uncased-finetuned-sst-2-english"
14
- )
15
- summarizer = pipeline(
16
- "summarization",
17
- model="sshleifer/distilbart-cnn-12-6"
18
- )
19
-
20
- # Word cloud generator
21
- def generate_wordcloud(text):
22
- wordcloud = WordCloud(width=800, height=400, background_color="white").generate(text)
23
- img = io.BytesIO()
24
- plt.figure(figsize=(8, 4))
25
- plt.imshow(wordcloud, interpolation="bilinear")
26
- plt.axis("off")
27
- plt.savefig(img, format="png")
28
- plt.close()
29
- img.seek(0)
30
- return img
31
-
32
- # Process single comment
33
- def process_comment(comment):
34
- # Sentiment
35
- sentiment = sentiment_model(comment)[0]
36
-
37
- # Summary
38
- try:
39
- summary = summarizer(comment, max_length=60, min_length=10, do_sample=False)[0]['summary_text']
40
- except Exception:
41
- summary = "Summary not available for short text."
42
-
43
- # Word cloud
44
- wc_img = generate_wordcloud(comment)
45
-
46
- return f"{sentiment['label']} ({sentiment['score']:.2f})", summary, wc_img
47
-
48
- # Batch processing from CSV
49
- def analyze_batch(file_path):
50
- df = pd.read_csv(file_path)
51
- results, summaries = [], []
52
- combined_text = ""
53
-
54
- for comment in df["comment"].astype(str):
55
- sentiment, summary, _ = process_comment(comment)
56
- results.append(sentiment)
57
- summaries.append(summary)
58
- combined_text += " " + comment
59
-
60
- # One word cloud for all comments
61
- wc_img = generate_wordcloud(combined_text)
62
-
63
- df["Sentiment"] = results
64
- df["Summary"] = summaries
65
- return df, wc_img
66
-
67
- # Gradio UI
68
- with gr.Blocks() as demo:
69
- gr.Markdown("## πŸ“ E-Consultation Sentiment Analysis")
70
-
71
- with gr.Tab("Single Comment"):
72
- inp = gr.Textbox(label="Enter Comment")
73
- out1 = gr.Textbox(label="Sentiment")
74
- out2 = gr.Textbox(label="Summary")
75
- out3 = gr.Image(label="Word Cloud")
76
- inp.submit(process_comment, inp, [out1, out2, out3])
77
-
78
- with gr.Tab("Batch Upload"):
79
- file_in = gr.File(label="Upload CSV with 'comment' column", type="filepath")
80
- out_df = gr.Dataframe(label="Results")
81
- out_wc = gr.Image(label="Word Cloud (All Comments)")
82
- file_in.change(analyze_batch, file_in, [out_df, out_wc])
83
-
84
- if __name__ == "__main__":
85
- demo.launch()
 
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")