Pro-Coder commited on
Commit
534ee48
ยท
verified ยท
1 Parent(s): 346bce9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -23
app.py CHANGED
@@ -1,47 +1,85 @@
1
  import gradio as gr
 
 
 
 
 
 
2
  import pandas as pd
3
- from pipeline import process_comment
4
 
5
- def analyze_single(text):
6
- sentiment, summary, wc_img = process_comment(text)
7
- result = f"**Label:** {sentiment['label']} | **Score:** {sentiment['score']:.2f}"
8
- return result, summary, wc_img
 
 
 
 
 
9
 
10
- def analyze_batch(file):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  df = pd.read_csv(file_path)
12
- results = []
13
- summaries = []
14
  combined_text = ""
15
 
16
- for comment in df["comment"]:
17
  sentiment, summary, _ = process_comment(comment)
18
- results.append(f"{sentiment['label']} ({sentiment['score']:.2f})")
19
  summaries.append(summary)
20
  combined_text += " " + comment
21
 
22
- # Generate one big word cloud for all comments
23
- _, _, wc_img = process_comment(combined_text)
24
 
25
  df["Sentiment"] = results
26
  df["Summary"] = summaries
27
-
28
  return df, wc_img
29
 
 
30
  with gr.Blocks() as demo:
31
- gr.Markdown("# ๐Ÿ›๏ธ E-Consultation Sentiment Analysis\nAnalyze stakeholder comments with AI.")
32
-
33
  with gr.Tab("Single Comment"):
34
- inp = gr.Textbox(lines=5, placeholder="Enter stakeholder comment...")
35
  out1 = gr.Textbox(label="Sentiment")
36
  out2 = gr.Textbox(label="Summary")
37
  out3 = gr.Image(label="Word Cloud")
38
- btn = gr.Button("Analyze")
39
- btn.click(analyze_single, inputs=inp, outputs=[out1, out2, out3])
40
 
41
- with gr.Tab("Batch Upload (CSV)"):
42
  file_in = gr.File(label="Upload CSV with 'comment' column", type="filepath")
43
- df_out = gr.Dataframe(label="Analysis Results")
44
- wc_out = gr.Image(label="Word Cloud")
45
- file_in.change(analyze_batch, inputs=file_in, outputs=[df_out, wc_out])
46
 
47
- demo.launch()
 
 
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()