Pro-Coder commited on
Commit
d4ac33d
·
verified ·
1 Parent(s): d0735e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tweepy
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ from wordcloud import WordCloud
6
+ from transformers import pipeline
7
+
8
+ # Hugging Face Models
9
+ sentiment_analyzer = pipeline("sentiment-analysis")
10
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
11
+
12
+ # Twitter API Setup (replace with your Bearer Token)
13
+ BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAN3g3wEAAAAA33Fzyb2P1rQzFwmXPIh4OHIw7e8%3DJY5zPrXhmzlht200jSaA8dgQixPX6idTvk2HWX0LgKwruozAsC"
14
+ client = tweepy.Client(bearer_token=BEARER_TOKEN)
15
+
16
+ # Function: Fetch Tweets
17
+ def fetch_tweets(username, count=50):
18
+ tweets = client.get_users_tweets(
19
+ id=client.get_user(username=username).data.id,
20
+ max_results=min(count, 100)
21
+ )
22
+ texts = [t.text for t in tweets.data] if tweets.data else []
23
+ df = pd.DataFrame(texts, columns=["text"])
24
+ return df
25
+
26
+ # Function: Load file (CSV/XLSX)
27
+ def load_file(file):
28
+ if file.name.endswith(".csv"):
29
+ return pd.read_csv(file.name)
30
+ elif file.name.endswith(".xlsx"):
31
+ return pd.read_excel(file.name)
32
+ else:
33
+ return pd.DataFrame(columns=["text"])
34
+
35
+ # Function: Clean text
36
+ def clean_text(df):
37
+ df["cleaned_text"] = (
38
+ df["text"].astype(str)
39
+ .str.replace(r"http\S+", "", regex=True)
40
+ .str.replace(r"@\w+", "", regex=True)
41
+ .str.replace(r"[^A-Za-z0-9\s]", "", regex=True)
42
+ .str.strip()
43
+ )
44
+ return df
45
+
46
+ # Function: Sentiment, Summary & WordCloud
47
+ def analyze_data(df):
48
+ if df.empty:
49
+ return "No data found", None, None
50
+
51
+ df = clean_text(df)
52
+
53
+ # Sentiment
54
+ df["sentiment"] = df["cleaned_text"].apply(
55
+ lambda x: sentiment_analyzer(x[:512])[0]["label"] if len(x) > 0 else "neutral"
56
+ )
57
+
58
+ # Summary (combine text for summarization)
59
+ full_text = " ".join(df["cleaned_text"].tolist())[:3000]
60
+ summary = summarizer(full_text, max_length=100, min_length=30, do_sample=False)[0]["summary_text"]
61
+
62
+ # WordCloud
63
+ text_for_wc = " ".join(df["cleaned_text"].tolist())
64
+ wordcloud = WordCloud(width=800, height=400, background_color="white").generate(text_for_wc)
65
+ plt.figure(figsize=(8, 4))
66
+ plt.imshow(wordcloud, interpolation="bilinear")
67
+ plt.axis("off")
68
+ plt.tight_layout()
69
+ plt.savefig("wordcloud.png")
70
+
71
+ return summary, df, "wordcloud.png"
72
+
73
+ # Gradio UI
74
+ with gr.Blocks() as demo:
75
+ gr.Markdown("# 📊 Twitter & File Sentiment Analysis Prototype")
76
+
77
+ with gr.Tab("Fetch Tweets"):
78
+ username = gr.Textbox(label="Twitter Username (without @)")
79
+ count = gr.Slider(10, 100, value=50, step=10, label="Number of Tweets")
80
+ btn_fetch = gr.Button("Fetch & Analyze")
81
+ summary_out = gr.Textbox(label="Summary")
82
+ df_out = gr.Dataframe()
83
+ img_out = gr.Image()
84
+
85
+ with gr.Tab("Upload File"):
86
+ file_in = gr.File(label="Upload CSV/XLSX")
87
+ btn_file = gr.Button("Analyze File")
88
+ summary_out2 = gr.Textbox(label="Summary")
89
+ df_out2 = gr.Dataframe()
90
+ img_out2 = gr.Image()
91
+
92
+ # Actions
93
+ btn_fetch.click(
94
+ lambda u, c: analyze_data(fetch_tweets(u, c)),
95
+ inputs=[username, count],
96
+ outputs=[summary_out, df_out, img_out],
97
+ )
98
+ btn_file.click(
99
+ lambda f: analyze_data(load_file(f)),
100
+ inputs=[file_in],
101
+ outputs=[summary_out2, df_out2, img_out2],
102
+ )
103
+
104
+ demo.launch()