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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import datetime
|
| 4 |
+
import tqdm
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import matplotlib
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
import snscrape.modules.twitter as sntwitter
|
| 10 |
+
|
| 11 |
+
matplotlib.use("Agg")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
with gr.Blocks() as demo:
|
| 15 |
+
def search(text,username,since,until,retweet,replies):
|
| 16 |
+
global filename
|
| 17 |
+
q = text
|
| 18 |
+
if username!='':
|
| 19 |
+
q += f" from:{username}"
|
| 20 |
+
if until=='':
|
| 21 |
+
until = datetime.datetime.strftime(datetime.date.today(), '%Y-%m-%d')
|
| 22 |
+
q += f" until:{until}"
|
| 23 |
+
if since=='':
|
| 24 |
+
since = datetime.datetime.strftime(datetime.datetime.strptime(until, '%Y-%m-%d') - datetime.timedelta(days=7), '%Y-%m-%d')
|
| 25 |
+
q += f" since:{since}"
|
| 26 |
+
if retweet == True:
|
| 27 |
+
q += f" exclude:retweets"
|
| 28 |
+
if replies == True:
|
| 29 |
+
q += f" exclude:replies"
|
| 30 |
+
if username!='' and text!='':
|
| 31 |
+
filename = f"{since}_{until}_{username}_{text}.csv"
|
| 32 |
+
elif username!="":
|
| 33 |
+
filename = f"{since}_{until}_{username}.csv"
|
| 34 |
+
else:
|
| 35 |
+
filename = f"{since}_{until}_{text}.csv"
|
| 36 |
+
print(filename)
|
| 37 |
+
return q
|
| 38 |
+
|
| 39 |
+
def scrape_tweets(text,username,since,until,retweets,replies,count,progress=gr.Progress()):
|
| 40 |
+
print(text,username,since,until,retweets,replies,count)
|
| 41 |
+
q = search(text,username,since,until,retweets,replies)
|
| 42 |
+
# Creating list to append tweet data
|
| 43 |
+
tweets_list1 = []
|
| 44 |
+
|
| 45 |
+
# Using TwitterSearchScraper to scrape data and append tweets to list
|
| 46 |
+
if count == -1:
|
| 47 |
+
for i,tweet in progress.tqdm(enumerate(sntwitter.TwitterSearchScraper(q).get_items())):
|
| 48 |
+
tweets_list1.append([tweet.date, tweet.id, tweet.content, tweet.user.username,tweet.lang,tweet.hashtags,tweet.replyCount,tweet.retweetCount,tweet.likeCount,tweet.quoteCount,tweet.media])
|
| 49 |
+
else:
|
| 50 |
+
for i,tweet in progress.tqdm(enumerate(sntwitter.TwitterSearchScraper(q).get_items())):
|
| 51 |
+
if i>=count: #number of tweets you want to scrape
|
| 52 |
+
break
|
| 53 |
+
tweets_list1.append([tweet.date, tweet.id, tweet.content, tweet.user.username,tweet.lang,tweet.hashtags,tweet.replyCount,tweet.retweetCount,tweet.likeCount,tweet.quoteCount,tweet.media])
|
| 54 |
+
# pbar.update(1)
|
| 55 |
+
# Creating a dataframe from the tweets list above
|
| 56 |
+
tweets_df1 = pd.DataFrame(tweets_list1, columns=['DateTime', 'TweetId', 'Text', 'Username','Language',
|
| 57 |
+
'Hashtags','ReplyCount','RetweetCount','LikeCount','QuoteCount','Media'])
|
| 58 |
+
#print(tweets_df1)
|
| 59 |
+
tweets_df1['Hour'] = tweets_df1['DateTime'].dt.hour
|
| 60 |
+
tweets_df1['Year'] = tweets_df1['DateTime'].dt.year
|
| 61 |
+
tweets_df1['Month'] = tweets_df1['DateTime'].dt.month
|
| 62 |
+
tweets_df1['MonthName'] = tweets_df1['DateTime'].dt.month_name()
|
| 63 |
+
tweets_df1['MonthDay'] = tweets_df1['DateTime'].dt.day
|
| 64 |
+
tweets_df1['DayName'] = tweets_df1['DateTime'].dt.day_name()
|
| 65 |
+
tweets_df1['Week'] = tweets_df1['DateTime'].dt.isocalendar().week
|
| 66 |
+
tweets_df1['Date'] = [d.date() for d in tweets_df1['DateTime']]
|
| 67 |
+
tweets_df1['Time'] = [d.time() for d in tweets_df1['DateTime']]
|
| 68 |
+
tweets_df1.drop('DateTime',axis=1,inplace=True)
|
| 69 |
+
tweets_df1.drop('Media',axis=1,inplace=True)
|
| 70 |
+
|
| 71 |
+
'''fig,ax = plt.subplots()
|
| 72 |
+
plt.plot(df["day"], df[countries].to_numpy())
|
| 73 |
+
|
| 74 |
+
#plt.title("Outbreak in " + month)
|
| 75 |
+
#plt.ylabel("Cases")
|
| 76 |
+
#plt.xlabel("Days since Day 0")
|
| 77 |
+
#plt.legend(countries)
|
| 78 |
+
return fig'''
|
| 79 |
+
|
| 80 |
+
f, ax = plt.subplots()
|
| 81 |
+
sns.countplot(x= tweets_df1['Year'])
|
| 82 |
+
for p in ax.patches:
|
| 83 |
+
ax.annotate(int(p.get_height()), (p.get_x()+0.05, p.get_height()+20), fontsize = 12)
|
| 84 |
+
|
| 85 |
+
f2,ax2 = plt.subplots()
|
| 86 |
+
sns.lineplot(tweets_df1.Year.value_counts().index,tweets_df1.Year.value_counts().values)
|
| 87 |
+
ax2.set_xlabel("Year")
|
| 88 |
+
ax2.set_ylabel('Count')
|
| 89 |
+
ax2.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 90 |
+
#f2 = plt.figure()
|
| 91 |
+
#plt.plot(np.arange(2021,2023,1), tweets_df1.Year.value_counts())
|
| 92 |
+
|
| 93 |
+
f3,ax3 = plt.subplots()
|
| 94 |
+
sns.histplot(x=tweets_df1.Year,stat='count',binwidth=1,kde='true',discrete=True)
|
| 95 |
+
ax3.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 96 |
+
|
| 97 |
+
f4,ax4 = plt.subplots()
|
| 98 |
+
sns.kdeplot(x=tweets_df1.Year,fill=True)
|
| 99 |
+
ax4.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 100 |
+
|
| 101 |
+
f5,ax5 = plt.subplots()
|
| 102 |
+
sns.kdeplot(x=tweets_df1.Year,fill=True,bw_adjust=3)
|
| 103 |
+
ax5.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 104 |
+
|
| 105 |
+
f6, ax6 = plt.subplots()
|
| 106 |
+
sns.countplot(x= tweets_df1['Month'])
|
| 107 |
+
for p in ax6.patches:
|
| 108 |
+
ax6.annotate(int(p.get_height()), (p.get_x()+0.05, p.get_height()+20), fontsize = 12)
|
| 109 |
+
|
| 110 |
+
f7,ax7 = plt.subplots()
|
| 111 |
+
sns.lineplot(tweets_df1.Month.value_counts().index,tweets_df1.Month.value_counts().values)
|
| 112 |
+
ax7.set_xlabel("Month")
|
| 113 |
+
ax7.set_ylabel('Count')
|
| 114 |
+
ax7.set_xticks(np.arange(1,13,1))
|
| 115 |
+
#f2 = plt.figure()
|
| 116 |
+
#plt.plot(np.arange(2021,2023,1), tweets_df1.Year.value_counts())
|
| 117 |
+
|
| 118 |
+
f8,ax8 = plt.subplots()
|
| 119 |
+
sns.histplot(x=tweets_df1.Month,stat='count',binwidth=1,kde='true',discrete=True)
|
| 120 |
+
ax8.set_xticks(np.arange(1,13,1))
|
| 121 |
+
|
| 122 |
+
f9,ax9 = plt.subplots()
|
| 123 |
+
sns.kdeplot(x=tweets_df1.Month,fill=True)
|
| 124 |
+
ax9.set_xticks(np.arange(1,13,1))
|
| 125 |
+
|
| 126 |
+
f10,ax10 = plt.subplots()
|
| 127 |
+
sns.kdeplot(x=tweets_df1.Month,fill=True,bw_adjust=3)
|
| 128 |
+
ax10.set_xticks(np.arange(1,13,1))
|
| 129 |
+
|
| 130 |
+
f11, ax11 = plt.subplots()
|
| 131 |
+
sns.countplot(x= tweets_df1['Week'])
|
| 132 |
+
for p in ax11.patches:
|
| 133 |
+
ax11.annotate(int(p.get_height()), (p.get_x()+0.005, p.get_height()+1), fontsize = 10)
|
| 134 |
+
plt.xticks(fontsize=7, rotation=45,horizontalalignment = 'center')
|
| 135 |
+
#plt.setp(ax11.get_xticklabels(), rotation=30)
|
| 136 |
+
|
| 137 |
+
f12,ax12 = plt.subplots()
|
| 138 |
+
sns.lineplot(tweets_df1.Week.value_counts().index,tweets_df1.Week.value_counts().values)
|
| 139 |
+
ax12.set_xlabel("Week")
|
| 140 |
+
ax12.set_ylabel('Count')
|
| 141 |
+
#ax12.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 142 |
+
#f2 = plt.figure()
|
| 143 |
+
#plt.plot(np.arange(2021,2023,1), tweets_df1.Year.value_counts())
|
| 144 |
+
|
| 145 |
+
f13,ax13 = plt.subplots()
|
| 146 |
+
sns.histplot(x=tweets_df1.Week,stat='count',binwidth=1,kde='true',discrete=True)
|
| 147 |
+
#ax13.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 148 |
+
|
| 149 |
+
f14,ax14 = plt.subplots()
|
| 150 |
+
sns.kdeplot(x=tweets_df1.Week,fill=True)
|
| 151 |
+
#ax14.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 152 |
+
|
| 153 |
+
f15,ax15 = plt.subplots()
|
| 154 |
+
sns.kdeplot(x=tweets_df1.Week,fill=True,bw_adjust=3)
|
| 155 |
+
#ax15.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 156 |
+
|
| 157 |
+
f16, ax16 = plt.subplots()
|
| 158 |
+
sns.countplot(x= tweets_df1['MonthDay'])
|
| 159 |
+
for p in ax16.patches:
|
| 160 |
+
ax16.annotate(int(p.get_height()), (p.get_x()+0.05, p.get_height()+10), fontsize = 12)
|
| 161 |
+
plt.xticks(fontsize=10, rotation=45,horizontalalignment = 'center')
|
| 162 |
+
|
| 163 |
+
f17,ax17 = plt.subplots()
|
| 164 |
+
sns.lineplot(tweets_df1.MonthDay.value_counts().index,tweets_df1.MonthDay.value_counts().values)
|
| 165 |
+
ax17.set_xlabel("MonthDay")
|
| 166 |
+
ax17.set_ylabel('Count')
|
| 167 |
+
#ax17.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 168 |
+
#f2 = plt.figure()
|
| 169 |
+
#plt.plot(np.arange(2021,2023,1), tweets_df1.Year.value_counts())
|
| 170 |
+
|
| 171 |
+
f18,ax18 = plt.subplots()
|
| 172 |
+
sns.histplot(x=tweets_df1.MonthDay,stat='count',binwidth=1,kde='true',discrete=True)
|
| 173 |
+
#ax18.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 174 |
+
|
| 175 |
+
f19,ax19 = plt.subplots()
|
| 176 |
+
sns.kdeplot(x=tweets_df1.MonthDay,fill=True)
|
| 177 |
+
#ax19.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 178 |
+
|
| 179 |
+
f20,ax20 = plt.subplots()
|
| 180 |
+
sns.kdeplot(x=tweets_df1.MonthDay,fill=True,bw_adjust=3)
|
| 181 |
+
#ax20.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 182 |
+
|
| 183 |
+
f21, ax21 = plt.subplots()
|
| 184 |
+
sns.countplot(x= tweets_df1['Hour'])
|
| 185 |
+
for p in ax21.patches:
|
| 186 |
+
ax21.annotate(int(p.get_height()), (p.get_x()+0.05, p.get_height()+10), fontsize = 12)
|
| 187 |
+
|
| 188 |
+
f22,ax22 = plt.subplots()
|
| 189 |
+
sns.lineplot(tweets_df1.Hour.value_counts().index,tweets_df1.Hour.value_counts().values)
|
| 190 |
+
ax22.set_xlabel("Hour")
|
| 191 |
+
ax22.set_ylabel('Count')
|
| 192 |
+
#ax22.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 193 |
+
#f2 = plt.figure()
|
| 194 |
+
#plt.plot(np.arange(2021,2023,1), tweets_df1.Year.value_counts())
|
| 195 |
+
|
| 196 |
+
f23,ax23 = plt.subplots()
|
| 197 |
+
sns.histplot(x=tweets_df1.Hour,stat='count',binwidth=1,kde='true',discrete=True)
|
| 198 |
+
#ax23.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 199 |
+
|
| 200 |
+
f24,ax24 = plt.subplots()
|
| 201 |
+
sns.kdeplot(x=tweets_df1.Hour,fill=True)
|
| 202 |
+
#ax4.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 203 |
+
|
| 204 |
+
f25,ax25 = plt.subplots()
|
| 205 |
+
sns.kdeplot(x=tweets_df1.Hour,fill=True,bw_adjust=3)
|
| 206 |
+
#ax5.set_xticks(np.arange(int(since[0:4]),int(until[0:4])+1,1))
|
| 207 |
+
|
| 208 |
+
return [tweets_df1,f,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,f25]
|
| 209 |
+
#gr.Markdown("Start typing below and then click **Run** to see the output.")
|
| 210 |
+
with gr.Tab("Input"):
|
| 211 |
+
with gr.Row():
|
| 212 |
+
text = gr.Textbox(label="Query text to be matched (Optional)",max_lines=1,value = 'python')
|
| 213 |
+
username = gr.Textbox(label="Twitter Username",max_lines=1,value = 'DataScienceDojo')
|
| 214 |
+
with gr.Row():
|
| 215 |
+
since = gr.Textbox(label="Start Date",placeholder='yyyy-mm-dd',max_lines=1,value = '2021-01-01')
|
| 216 |
+
until = gr.Textbox(label="End Date",max_lines=1,placeholder='yyyy-mm-dd',value = '2022-12-31')
|
| 217 |
+
with gr.Row():
|
| 218 |
+
retweets = gr.Checkbox(label="Exclude Retweets?")
|
| 219 |
+
replies = gr.Checkbox(label="Exclude Replies")
|
| 220 |
+
with gr.Row():
|
| 221 |
+
count = gr.Slider(label="Count (-1 to retrive all tweets)",value=-1, minimum=-1,maximum = 2000, step=1)
|
| 222 |
+
with gr.Row():
|
| 223 |
+
submit_btn = gr.Button("Submit")
|
| 224 |
+
with gr.Row():
|
| 225 |
+
out = gr.DataFrame(overflow_row_behaviour="show_ends",wrap=True)
|
| 226 |
+
|
| 227 |
+
with gr.Tab("Visualization by Hour"):
|
| 228 |
+
with gr.Row():
|
| 229 |
+
out22 = gr.Plot()
|
| 230 |
+
out23 = gr.Plot()
|
| 231 |
+
with gr.Row():
|
| 232 |
+
out24 = gr.Plot()
|
| 233 |
+
out25 = gr.Plot()
|
| 234 |
+
with gr.Row():
|
| 235 |
+
out26 = gr.Plot()
|
| 236 |
+
with gr.Tab("Visualization by Day"):
|
| 237 |
+
with gr.Row():
|
| 238 |
+
out17 = gr.Plot()
|
| 239 |
+
out18 = gr.Plot()
|
| 240 |
+
with gr.Row():
|
| 241 |
+
out19 = gr.Plot()
|
| 242 |
+
out20 = gr.Plot()
|
| 243 |
+
with gr.Row():
|
| 244 |
+
out21 = gr.Plot()
|
| 245 |
+
with gr.Tab("Visualization by Week"):
|
| 246 |
+
with gr.Row():
|
| 247 |
+
out12 = gr.Plot()
|
| 248 |
+
out13 = gr.Plot()
|
| 249 |
+
with gr.Row():
|
| 250 |
+
out14 = gr.Plot()
|
| 251 |
+
out15 = gr.Plot()
|
| 252 |
+
with gr.Row():
|
| 253 |
+
out16 = gr.Plot()
|
| 254 |
+
with gr.Tab("Visualization by Month"):
|
| 255 |
+
with gr.Row():
|
| 256 |
+
out7 = gr.Plot()
|
| 257 |
+
out8 = gr.Plot()
|
| 258 |
+
with gr.Row():
|
| 259 |
+
out9 = gr.Plot()
|
| 260 |
+
out10 = gr.Plot()
|
| 261 |
+
with gr.Row():
|
| 262 |
+
out11 = gr.Plot()
|
| 263 |
+
with gr.Tab("Visualization by Year"):
|
| 264 |
+
with gr.Row():
|
| 265 |
+
out2 = gr.Plot()
|
| 266 |
+
out3 = gr.Plot()
|
| 267 |
+
with gr.Row():
|
| 268 |
+
out4 = gr.Plot()
|
| 269 |
+
out5 = gr.Plot()
|
| 270 |
+
with gr.Row():
|
| 271 |
+
out6 = gr.Plot()
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
submit_btn.click(fn=scrape_tweets, inputs=[text,username,since,until,retweets,replies,count], outputs=[out,out2,out3,out4,out5,out6,out7,out8,out9,out10,out11,out12,out13,out14,out15,out16,out17,out18,out19,out20,out21,out22,out23,out24,out25,out26])
|
| 276 |
+
|
| 277 |
+
#demo.launch(debug=True)
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
demo.queue(concurrency_count=5).launch()
|