-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpushshift_python.py
1870 lines (1700 loc) · 67.5 KB
/
pushshift_python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Witten by: Cason Konzer
pushshift_python is a wrapper for reddit community analytics.
read the docs at: https://github.com/casonk/pushshift_python/blob/master/documentation.ipynb
"""
# Import relative libraries.
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from dateutil.relativedelta import relativedelta
from sklearn.feature_selection import RFE
from sklearn.svm import SVC
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import roc_curve
from sklearn.metrics import f1_score
from sklearn.metrics import SCORERS
from sklearn.metrics import auc
from sklearn.utils import resample
from dataclasses import dataclass
import matplotlib.pyplot as plt
from datetime import datetime
from pathlib import Path
from zlib import crc32
import networkx as nx
import seaborn as sns
import pandas as pd
import numpy as np
import zstandard
import requests
import time
import math
import json
import csv
import sys
import re
import os
# Setup default plotter.
plt.style.use("dark_background")
plt.rcParams["figure.figsize"] = [16, 9]
plt.rcParams.update({"font.size": 18})
plt.rcParams.update({"text.usetex": True})
# Create global column numeric scaling function.
def numeric_scaler(col, df):
col_max = df[col].max()
col_min = df[col].min()
col_range = col_max - col_min
scaled = df[col].apply(lambda x: (x - col_min) / col_range)
return scaled
# Create global column boolean scaling function.
def boolean_scaler(col, df):
scaled = df[col].copy()
scaled.replace(True, 1, inplace=True)
scaled.replace(False, 1, inplace=True)
return scaled
# Create global column string hasing function.
def string_scaler(col, df):
def string_hasher(string):
s = str(string).encode("utf-8")
try:
unscaled_hash = float(crc32(s) & 0xFFFFFFFF)
except:
unscaled_hash = np.nan()
string_hash = unscaled_hash / 2 ** 32
return string_hash
scaled = df[col].apply(lambda x: string_hasher(x))
return scaled
# Create object for direct reddit api queries.
@dataclass
class api_agent:
"""
Class object for making various reddit API requests.
----------
paramaters
----------
api_credentials: dictionary containing your api application credentials...
{
"user_agent" : "user_agent",
"user_pass" : "user_pass",
"client_id" : "client_id",
"client_secret" : "client_secret",
"application_name" : "application_name"
}
"""
def __init__(self, api_credentials):
self.user_agent = api_credentials["user_agent"]
self.user_pass = api_credentials["user_pass"]
self.client_id = api_credentials["client_id"]
self.client_secret = api_credentials["client_secret"]
self.application_name = api_credentials["application_name"]
def renew_auth_token(self):
"""
Renew Reddit API O-Auth
"""
auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
data = {
"grant_type": "password",
"username": self.user_agent,
"password": self.user_pass,
}
self.headers = {"User-Agent": "{}}/0.0.0".format(self.application_name)}
request = requests.post(
"https://www.reddit.com/api/v1/access_token",
auth=auth,
data=data,
headers=self.headers,
)
TOKEN = request.json()["access_token"]
self.headers["Authorization"] = f"bearer {TOKEN}"
def get_top_subreddits(self, payload):
def hit():
try:
r = requests.get(
"https://oauth.reddit.com/subreddits/new",
headers=self.headers,
params=payload,
)
status = r.status_code
print("> http response is:", status)
except:
r = ""
status = " NO HANDSHAKE "
print("> http response is:", status)
return r, status
retry = 0
while True:
retry += 1
r, status = hit()
if status == 200:
break
time.sleep(5 * retry)
print(" >> rety_#: {}".format(retry))
if retry % 3 == 0:
self.renew_auth_token()
print("\nAUTH_RENEWED\n")
subreddits = json.loads(r.text, strict=False)
return subreddits
def make_subreddits(self, path="subreddit_list.csv"):
self.renew_auth_token()
self.subreddits_path = path
with open(self.subreddits_path, "w", newline="", encoding="utf-8") as _red_list:
_red_writer = csv.writer(_red_list, delimiter=",")
_headers = ["subreddit", "num_subscribers", "creation_utc", "nsfw_bool"]
_red_writer.writerow(_headers)
_payload = {"limit": "100"}
_subreddits = self.get_top_subreddits(_payload)
_before = ""
while len(_subreddits) > 0:
for key in _subreddits["data"]["children"]:
try:
_title = str(key["data"]["title"])
except:
_title = "NA"
try:
_subscribers = str(key["data"]["subscribers"])
except:
_subscribers = "NA"
try:
_created_utc = str(key["data"]["created_utc"])
except:
_created_utc = "NA"
try:
_over18 = str(key["data"]["over18"])
except:
_over18 = "NA"
_after = key["data"]["name"]
_rho = [_title, _subscribers, _created_utc, _over18]
_red_writer.writerow(_rho)
_payload = {"limit": "100", "after": _after}
if _before == _after:
break
else:
print(" >>> after : {}".format(_after))
_subreddits = self.get_top_subreddits(_payload)
_before = _after
self.subreddits_df = pd.read_csv(self.subreddits_path, low_memory=False)
self.subreddits_df = self.subreddits_df.sort_values(
by="num_subscribers", ascending=False
)
self.subreddits_df.to_csv(
path_or_buf=self.subreddits_path, sep=",", na_rep="nan", index="subreddit"
)
# Create query superclass
@dataclass
class query:
"""
SuperClass for compiling reddit queries.
----------
paramaters
----------
query_type:
subreddit- query provided subreddit.
keyword- query all subreddits for provided keyword.
query: provided subreddit or keyword.
time_range: dictionary input {'before' : latest post time, 'after' : earliest post time}
times can be given in unix epoch timestamp or datetime format.
time_format:
'unix'- defaults to unix epoch timestamp.
'datetime'- set this option is specifing time_range in datetime format.
post_type: selection to query for comments or submissions, defaults to both.
'comment'- only query comments.
'submission'- only query submission.
defaults to query both comments and submissions.
"""
def __init__(
self, query_type, query, time_range, time_format="unix", post_type=None
):
"""
Initilization of query object.
"""
self.type = query_type.lower()
self.query = query.lower()
if time_format == "datetime":
time_range["before"] = int(
datetime.timestamp(datetime.strptime(time_range["before"], "%Y-%m-%d"))
)
time_range["after"] = int(
datetime.timestamp(datetime.strptime(time_range["after"], "%Y-%m-%d"))
)
self.before = int(time_range["before"])
self.before_dt = datetime.fromtimestamp(self.before)
self.after = int(time_range["after"])
self.after_dt = datetime.fromtimestamp(self.after)
try:
self.post_type = post_type.lower()
except:
self.post_type = post_type
def create_common_data(self, p_type_, post):
"""
Helper function to collect values common between both comments and submissions.
"""
try:
subreddit = post["subreddit"]
post_id = post["id"]
try:
parent_id = post["parent_id"]
except KeyError:
parent_id = "nan"
try:
link_id = post["link_id"]
except KeyError:
link_id = "nan"
try:
url = post["url"]
except KeyError:
url = "nan"
try:
permalink = post["permalink"]
except:
permalink = "nan"
created_utc = post["created_utc"]
t = datetime.fromtimestamp(created_utc)
date = t.strftime("%m/%d/%Y")
score = post["score"]
try:
upvote_ratio = post["upvote_ratio"]
except KeyError:
upvote_ratio = "nan"
try:
num_comments = post["num_comments"]
except KeyError:
num_comments = "nan"
try:
controversiality = post["controversiality"]
except:
controversiality = "nan"
try:
total_awards_received = post["total_awards_received"]
except:
total_awards_received = "nan"
try:
stickied = post["stickied"]
except:
stickied = "nan"
try:
post_hint = post["post_hint"]
except:
post_hint = "nan"
try:
is_self = post["is_self"]
except KeyError:
is_self = "nan"
try:
is_video = post["is_video"]
except KeyError:
is_video = "nan"
try:
title = post["title"]
title = r"{}".format(title)
except KeyError:
title = "nan"
author = post["author"]
author = r"{}".format(author)
try:
author_premium = post["author_premium"]
except:
author_premium = "nan"
if p_type_ == "comment":
try:
body = post["body"]
body = r"{}".format(body)
except KeyError:
body = "nan"
elif p_type_ == "submission":
try:
body = post["selftext"]
body = r"{}".format(body)
except KeyError:
body = "nan"
post_type = p_type_
post_data = {
"post_type": post_type,
"subreddit": subreddit,
"id": post_id,
"parent_id": parent_id,
"link_id": link_id,
"url": url,
"permalink": permalink,
"created_utc": created_utc,
"datetime": date,
"score": score,
"upvote_ratio": upvote_ratio,
"num_comments": num_comments,
"controversiality": controversiality,
"total_awards_received": total_awards_received,
"stickied": stickied,
"post_hint": post_hint,
"is_self": is_self,
"is_video": is_video,
"title": title,
"body": body,
"author": author,
"author_premium": author_premium,
}
return post_data
except KeyboardInterrupt:
pass
# Create pushshift file query object
@dataclass
class pushshift_file_query(query):
"""
Class for compiling pushshift file queries.
Respective files can be downloaded from : https://files.pushshift.io/reddit/
----------
paramaters
----------
query_type:
'subreddit'- query provided subreddit.
'keyword'- query all subreddits for provided keyword.
query: provided subreddit or keyword.
time_range: dictionary input {'before' : latest post time, 'after' : earliest post time}
times can be given in unix epoch timestamp or datetime format.
time_format:
'unix'- defaults to unix epoch timestamp.
'datetime'- set this option is specifing time_range in datetime format.
post_type: selection to query for comments or submissions, defaults to both.
'comment'- only query comments.
'submission'- only query submission.
defaults to query both comments and submissions.
"""
def __init__(
self, query_type, query, time_range, time_format="unix", post_type=None
):
"""
Initilization of query object.
"""
super().__init__(query_type, query, time_range, time_format, post_type)
self.submission_folder_path = Path(
"F:/Research/Funded/Ethical_Reccomendations/Python/Push_File/RS/2019+/"
)
self.comment_folder_path = Path(
"F:/Research/Funded/Ethical_Reccomendations/Python/Push_File/RC/2019+/"
)
self.line_counter = 0
self.post_counter = 0
self.file_counter = 0
self.errors = 0
def set_parent_folders(self, submission_folder_path, comment_folder_path):
"""
Set paths to pushshift files.
"""
self.submission_folder_path = Path(submission_folder_path)
self.comment_folder_path = Path(comment_folder_path)
def read_lines_zst(self):
"""
Helper function for reading from ztandandard compressed ndjson files.
"""
with open(self.working_file, "rb") as file_handle:
buffer = ""
reader = zstandard.ZstdDecompressor(max_window_size=2 ** 31).stream_reader(
file_handle
)
while True:
chunk = reader.read(2 ** 27).decode()
if not chunk:
break
lines = (buffer + chunk).split("\n")
for line in lines[:-1]:
yield line, file_handle.tell()
buffer = lines[-1]
reader.close()
def make_query(self, oversized=False):
"""
Initialize the query.
"""
self.oversized = oversized
self.headers = [
"post_type",
"subreddit",
"id",
"parent_id",
"link_id",
"url",
"permalink",
"created_utc",
"datetime",
"score",
"upvote_ratio",
"num_comments",
"controversiality",
"total_awards_received",
"stickied",
"post_hint",
"is_self",
"is_video",
"title",
"body",
"author",
"author_premium",
]
if self.oversized:
self.write_path = os.getcwd() + "\\{}.csv".format(self.query)
self.csv = open(self.write_path, "w", newline="", encoding="utf-8")
self.csv_writer = csv.writer(self.csv, delimiter=",")
self.csv_writer.writerow(self.headers)
self.df = pd.DataFrame(columns=self.headers)
self.submissions = self.df.copy()
self.comments = self.df.copy()
def search(self, _post_type):
"""
Helper function to parse comment json objects.
"""
for line, file_bytes_processed in self.read_lines_zst():
self.line_counter += 1
if self.line_counter % 1000000 == 0:
print(
" >> Processed {} Posts, Found {} Posts".format(
self.line_counter, self.post_counter
)
)
try:
_post = json.loads(line)
if self.type == "subreddit":
if int(_post["created_utc"]) >= int(self.after):
if int(_post["created_utc"]) <= int(self.before):
if _post["subreddit"] == self.query:
self.post_counter += 1
post_data = self.create_common_data(
p_type_=_post_type, post=_post
)
if post_data == "comment":
try:
if self.oversized:
self.csv_writer.writerow(
list(post_data.values())
)
else:
self.comments = self.comments.append(
post_data, ignore_index=True
)
except KeyboardInterrupt:
if self.oversized:
self.csv_writer.writerow(
list(post_data.values())
)
else:
self.comments = self.comments.append(
post_data, ignore_index=True
)
print(
"Keyboard Interrupt Detected, please Interrupt again to break parent function."
)
break
elif post_data == "submission":
try:
if self.oversized:
self.csv_writer.writerow(
list(post_data.values())
)
else:
self.submissions = (
self.submissions.append(
post_data, ignore_index=True
)
)
except KeyboardInterrupt:
if self.oversized:
self.csv_writer.writerow(
list(post_data.values())
)
else:
self.submissions = (
self.submissions.append(
post_data, ignore_index=True
)
)
print(
"Keyboard Interrupt Detected, please Interrupt again to break parent function."
)
break
except (KeyError, json.JSONDecodeError):
self.errors += 1
def make_time_list(self):
"""
Helper function to create time lists to use for parsing pushshift.io downloaded files.
"""
first = self.after_dt
last = self.before_dt
self.time_list = []
while first <= last:
self.time_list.append(first.strftime("%Y-%m"))
first += relativedelta(months=1)
if last.strftime("%Y-%m") in self.time_list:
pass
else:
self.time_list.append(last.strftime("%Y-%m"))
make_time_list(self=self)
all_submission_files = [
submission_file for submission_file in self.submission_folder_path.iterdir()
]
if self.post_type == "comment":
pass
else:
for file in all_submission_files:
try:
for time in self.time_list:
if time in file.name:
self.working_file = str(file.as_posix())
print("> Parsing : {}".format(file.name))
try:
search(self=self, _post_type="submission")
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
self.file_counter += 1
print(
" >>> Total Files Parsed : {}, Total Posts Parsed : {}, Total Posts Collected : {}, Total Errors Found : {}".format(
self.file_counter,
self.line_counter,
self.post_counter,
self.errors,
)
)
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
all_comment_files = [
comment_file for comment_file in self.comment_folder_path.iterdir()
]
if self.post_type == "submission":
pass
else:
for file in all_comment_files:
try:
for time in self.time_list:
if time in file.name:
self.working_file = str(file.as_posix())
print("> Parsing : {}".format(file.name))
try:
search(self=self, _post_type="comment")
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
self.file_counter += 1
print(
" >>> Total Files Parsed : {}, Total Posts Parsed : {}, Total Posts Collected : {}, Total Errors Found : {}".format(
self.file_counter,
self.line_counter,
self.post_counter,
self.errors,
)
)
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
if self.oversized:
self.df = pd.read_csv(self.write_path, low_memory=False)
else:
self.df = self.submissions.append(self.comments)
def export(self, path, to_export="df", export_format="pkl"):
"""
Easily save and export your data for future analytics.
----------
paramaters
----------
path: path to save output data to.
to_export: select what data you wish to export
'df'- all data.
'submissions'- only submission data.
'comments'- only comment data.
export_format:
'.pkl'- default, exports to pickle.
'.csv'- export to comma seperated file.
"""
if to_export == "df":
if export_format == "pkl":
self.df.to_pickle(path=path)
elif export_format == "csv":
self.df.to_csv(path_or_buf=path)
elif to_export == "submissions":
if export_format == "pkl":
self.submissions.to_pickle(path=path)
elif export_format == "csv":
self.submissions.to_csv(path_or_buf=path)
elif to_export == "comments":
if export_format == "pkl":
self.comments.to_pickle(path=path)
elif export_format == "csv":
self.comments.to_csv(path_or_buf=path)
# Create pushshift web query object
@dataclass
class pushshift_web_query(query):
"""
Class for compiling pushshift web queries.
----------
paramaters
----------
query_type:
subreddit- query provided subreddit.
keyword- query all subreddits for provided keyword.
query: provided subreddit or keyword.
time_range: dictionary input {'before' : latest post time, 'after' : earliest post time}
times can be given in unix epoch timestamp or datetime format.
time_format:
'unix'- defaults to unix epoch timestamp.
'datetime'- set this option is specifing time_range in datetime format.
post_type: selection to query for comments or submissions, defaults to both.
'comment'- only query comments.
'submission'- only query submission.
defaults to query both comments and submissions.
"""
def __init__(
self, query_type, query, time_range, time_format="unix", post_type=None
):
"""
Initilization of query object.
"""
super().__init__(query_type, query, time_range, time_format, post_type)
self.api_hit_counter = 0
def update_url(self):
"""
Helper function to update timestamp after each API request.
"""
try:
if self.type == "subreddit":
self.comment_url = "https://api.pushshift.io/reddit/search/{}/?after={}&before={}&subreddit={}&size={}".format(
str("comment"),
str(self.current_time),
str(self.before),
str(self.query),
"12345",
)
self.submission_url = "https://api.pushshift.io/reddit/search/{}/?after={}&before={}&subreddit={}&size={}".format(
str("submission"),
str(self.current_time),
str(self.before),
str(self.query),
"12345",
)
elif self.type == "keyword":
self.comment_url = "https://api.pushshift.io/reddit/search/{}/?q={}&after={}&before={}&size={}".format(
str("comment"),
str(self.query),
str(self.current_time),
str(self.before),
"12345",
)
self.submission_url = "https://api.pushshift.io/reddit/search/{}/?q={}&after={}&before={}&size={}".format(
str("submission"),
str(self.query),
str(self.current_time),
str(self.before),
"12345",
)
except KeyboardInterrupt:
pass
def make_query(self, oversized=False, _path=None):
"""
Initialize the query.
"""
self.oversized = oversized
self.headers = [
"post_type",
"subreddit",
"id",
"parent_id",
"link_id",
"url",
"permalink",
"created_utc",
"datetime",
"score",
"upvote_ratio",
"num_comments",
"controversiality",
"total_awards_received",
"stickied",
"post_hint",
"is_self",
"is_video",
"title",
"body",
"author",
"author_premium",
]
if self.oversized:
if _path == None:
self.write_path = os.getcwd() + "\\{}.csv".format(self.query)
else:
self.write_path = _path
self.csv = open(self.write_path, "w", newline="", encoding="utf-8")
self.csv_writer = csv.writer(self.csv, delimiter=",", escapechar='\\')
self.csv_writer.writerow(self.headers)
self.df = pd.DataFrame(columns=self.headers)
self.submissions = self.df.copy()
self.comments = self.df.copy()
def web_hit(self, url):
"""
Helper function to make the API request.
----------
paramaters
----------
url: provide either self.submission_url or self.comment_url depending on post type.
"""
try:
self.api_hit_counter += 1
try:
r = requests.get(url)
status = r.status_code
print("> http response is:", status)
except:
status = "NO HANDSHAKE WITH API"
print(status)
if status != 200:
retry = 0
while True:
retry += 1
print(
"\nAPI DECLINED REQUEST\n\n>> This is retry #:",
retry,
"<<\n",
)
time.sleep(2.5 * retry)
try:
r = requests.get(url)
status = r.status_code
print("> retry http response is:", status)
except:
status = "NO HANDSHAKE WITH API"
print(status)
if status == 200:
break
print(" >> Web Hit On", self.query, "# :", self.api_hit_counter)
print(
" >>> Current Post Time :",
str(datetime.fromtimestamp(self.current_time)),
)
self.web_data = json.loads(r.text, strict=False)
time.sleep(0.25)
if (status % 2) == 0:
self.current_time = self.current_time + (60*60*2)
self.update_url()
except KeyboardInterrupt:
pass
def save(self, _post_type):
"""
Helper function to save comments to self.comments.
"""
for _post in self.web_data["data"]:
post_data = self.create_common_data(p_type_=_post_type, post=_post)
if _post_type == "comment":
try:
if self.oversized:
self.csv_writer.writerow(list(post_data.values()))
else:
self.comments = self.comments.append(
post_data, ignore_index=True
)
self.current_time = post_data["created_utc"]
except KeyboardInterrupt:
if self.oversized:
self.csv_writer.writerow(list(post_data.values()))
else:
self.comments = self.comments.append(
post_data, ignore_index=True
)
self.current_time = post_data["created_utc"]
print(
"Keyboard Interrupt Detected, please Interrupt again to break parent function."
)
break
elif _post_type == "submission":
try:
if self.oversized:
self.csv_writer.writerow(list(post_data.values()))
else:
self.submissions = self.submissions.append(
post_data, ignore_index=True
)
self.current_time = post_data["created_utc"]
except KeyboardInterrupt:
if self.oversized:
self.csv_writer.writerow(list(post_data.values()))
else:
self.submissions = self.submissions.append(
post_data, ignore_index=True
)
self.current_time = post_data["created_utc"]
print(
"Keyboard Interrupt Detected, please Interrupt again to break parent function."
)
break
def collect_submissions(self):
"""
Master function to chain previous helper functions and collect the requested data for submissions.
"""
self.current_time = self.after
if self.post_type == "comment":
pass
else:
while self.current_time < self.before:
self.update_url()
web_hit(self=self, url=self.submission_url)
if len(self.web_data["data"]) == 0:
break
else:
try:
save(self=self, _post_type="submission")
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
def collect_comments(self):
"""
Master function to chain previous helper functions and collect the requested data for comments.
"""
self.current_time = self.after
if self.post_type == "submission":
pass
else:
while self.current_time < self.before:
self.update_url()
web_hit(self=self, url=self.comment_url)
if len(self.web_data["data"]) == 0:
break
else:
try:
save(self=self, _post_type="comment")
except KeyboardInterrupt:
print(
"Keyboard Interrupt Detected, your object's values are secure"
)
break
collect_submissions(self=self)
collect_comments(self=self)
try:
self.df = pd.read_csv(self.write_path, low_memory=False)
except:
self.df = self.submissions.append(self.comments)
def export(self, path, to_export="df", export_format="pkl"):
"""
Easily save and export your data for future analytics.
----------
paramaters
----------
path: path to save output data to.
to_export: select what data you wish to export
'df'- all data.
'submissions'- only submission data.
'comments'- only comment data.
export_format:
'.pkl'- default, exports to pickle.
'.csv'- export to comma seperated file.
"""
if to_export == "df":
if export_format == "pkl":
self.df.to_pickle(path=path)
elif export_format == "csv":
self.df.to_csv(path_or_buf=path)
elif to_export == "submissions":
if export_format == "pkl":
self.submissions.to_pickle(path=path)
elif export_format == "csv":
self.submissions.to_csv(path_or_buf=path)
elif to_export == "comments":
if export_format == "pkl":
self.comments.to_pickle(path=path)
elif export_format == "csv":
self.comments.to_csv(path_or_buf=path)
# Create community object
@dataclass
class community:
def __init__(
self,
name="community",
path=None,
dataframe=None,
columns=None,
file_format=None,
set_id=True
):
"""
Initilization of object, created DataFrame for provided community.
----------
paramaters
----------
path: path to file location.
datafram: pass a corresponding community dataframe.
columns: selected colums to read, only applicable for .csv.
file_format: defaults to "None" when passed a pandas dataframe.
"csv"- for passing DataFrame stored as csv.