GLAkavya commited on
Commit
0928dc0
Β·
verified Β·
1 Parent(s): 1609deb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -0
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import pandas as pd
4
+ import random
5
+ import time
6
+ import plotly.express as px
7
+ import requests
8
+ import os
9
+
10
+ # ---------------------------
11
+ # Load Hugging Face sentiment model
12
+ # ---------------------------
13
+ sentiment_model = pipeline("sentiment-analysis")
14
+
15
+ # ---------------------------
16
+ # Gemini API Config
17
+ # ---------------------------
18
+ GEMINI_API_KEY = os.getenv("GOOGLE_API_KEY")
19
+
20
+ def gemini_sentiment(text):
21
+ """Use Gemini API for sentiment analysis"""
22
+ if not GEMINI_API_KEY:
23
+ return {"label": "NEUTRAL", "score": 0.0}
24
+
25
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
26
+ headers = {"Content-Type": "application/json", "X-goog-api-key": GEMINI_API_KEY}
27
+ payload = {
28
+ "contents": [{"parts": [{"text": f"Classify sentiment of this text as Positive, Negative or Neutral:\n\n{text}"}]}]
29
+ }
30
+ resp = requests.post(url, headers=headers, json=payload)
31
+ if resp.status_code == 200:
32
+ ai_text = resp.json()["candidates"][0]["content"]["parts"][0]["text"].strip().lower()
33
+ if "positive" in ai_text:
34
+ return {"label": "POSITIVE", "score": 0.9}
35
+ elif "negative" in ai_text:
36
+ return {"label": "NEGATIVE", "score": 0.9}
37
+ else:
38
+ return {"label": "NEUTRAL", "score": 0.5}
39
+ return {"label": "NEUTRAL", "score": 0.0}
40
+
41
+ # ---------------------------
42
+ # Mock social posts generator
43
+ # ---------------------------
44
+ def fetch_posts(hashtag, n=20):
45
+ samples = [
46
+ f"I love {hashtag}! It's amazing ❀️",
47
+ f"{hashtag} is the worst thing ever 😑",
48
+ f"Not sure how I feel about {hashtag} πŸ€”",
49
+ f"Super excited about {hashtag} πŸ”₯",
50
+ f"{hashtag} totally failed expectations 😞",
51
+ f"People are talking about {hashtag} everywhere 🌍",
52
+ f"I'm disappointed with {hashtag} πŸ’”",
53
+ f"{hashtag} campaign is the best thing this year πŸŽ‰",
54
+ ]
55
+ return [random.choice(samples) for _ in range(n)]
56
+
57
+ # ---------------------------
58
+ # Analyzer function
59
+ # ---------------------------
60
+ def analyze_hashtag(hashtag, n_posts=20, chart_type="Bar", use_gemini=False):
61
+ posts = fetch_posts(hashtag, n_posts)
62
+ results = []
63
+
64
+ for p in posts:
65
+ if use_gemini:
66
+ result = gemini_sentiment(p)
67
+ else:
68
+ result = sentiment_model(p)[0]
69
+ results.append({"Post": p, "Sentiment": result["label"], "Confidence": round(result["score"], 2)})
70
+ time.sleep(0.05) # simulate streaming
71
+
72
+ df = pd.DataFrame(results)
73
+
74
+ # Count distribution
75
+ sentiment_counts = df["Sentiment"].value_counts().reset_index()
76
+ sentiment_counts.columns = ["Sentiment", "Count"]
77
+
78
+ # Plotly Graph
79
+ if chart_type == "Bar":
80
+ fig = px.bar(sentiment_counts, x="Sentiment", y="Count", color="Sentiment",
81
+ title=f"Sentiment Distribution for {hashtag}")
82
+ elif chart_type == "Pie":
83
+ fig = px.pie(sentiment_counts, names="Sentiment", values="Count",
84
+ title=f"Sentiment Share for {hashtag}")
85
+ else: # Line chart (simulate rolling trend)
86
+ fig = px.line(sentiment_counts, x="Sentiment", y="Count", markers=True,
87
+ title=f"Sentiment Rolling Trend for {hashtag}")
88
+
89
+ return df, fig
90
+
91
+ # ---------------------------
92
+ # Gradio UI
93
+ # ---------------------------
94
+ with gr.Blocks(css=".footer {text-align:center; font-size:16px; color:#ff66cc; font-weight:bold; animation: glow 1.5s ease-in-out infinite alternate;} @keyframes glow { from { text-shadow: 0 0 10px #ff66cc; } to { text-shadow: 0 0 20px #ff33aa; }}") as demo:
95
+ gr.Markdown(
96
+ """
97
+ <div style='text-align:center; padding: 20px; background: linear-gradient(90deg, #1e3c72, #2a5298); color: white; border-radius: 12px;'>
98
+ <h1>πŸ“Š Social Media Sentiment Analyzer</h1>
99
+ <p>Stream posts β€’ Analyze moods β€’ Visualize trends</p>
100
+ </div>
101
+ """
102
+ )
103
+
104
+ with gr.Row():
105
+ with gr.Column(scale=1):
106
+ hashtag = gr.Textbox(label="Enter Hashtag", placeholder="#YourCampaign")
107
+ n_posts = gr.Slider(5, 50, step=5, value=20, label="Number of Posts")
108
+ chart_type = gr.Dropdown(["Bar", "Pie", "Line"], value="Bar", label="Choose Visualization")
109
+ use_gemini = gr.Checkbox(label="Use Gemini Advanced Analysis", value=False)
110
+ btn = gr.Button("πŸš€ Run Analysis", variant="primary")
111
+
112
+ with gr.Column(scale=2):
113
+ output_table = gr.Dataframe(label="Posts & Sentiments", wrap=True)
114
+ output_plot = gr.Plot(label="Visualization")
115
+
116
+ btn.click(fn=analyze_hashtag, inputs=[hashtag, n_posts, chart_type, use_gemini], outputs=[output_table, output_plot])
117
+
118
+ gr.HTML("<div class='footer'>✨ Made with πŸ’œ by Kavya</div>")
119
+
120
+ demo.launch()