-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreddit_parser.py
2447 lines (2060 loc) · 116 KB
/
reddit_parser.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
import bz2
import copy
import errno
import lzma
import zstandard as zstd
from langdetect import DetectorFactory
from langdetect import detect
from collections import defaultdict, OrderedDict
import datetime
import itertools
import scipy
import glob
import hashlib
import html
import json
import multiprocessing
import spacy
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import numpy as np
from math import floor,ceil
import os
import io
from pathlib2 import Path
import pickle
import re
import time
import subprocess
from pycorenlp import StanfordCoreNLP
import sys
from textblob import TextBlob
from config import *
from Utils import *
from transformers import BertTokenizer
# from simpletransformers.classification import ClassificationModel
import pandas as pd
import logging
import fnmatch
from sklearn.metrics import accuracy_score,cohen_kappa_score
from sklearn.model_selection import KFold
from keras.preprocessing.sequence import pad_sequences
import hashlib
import csv
import shutil
import ahocorasick
### Wrapper for the multi-processing parser
# NOTE: This needs to be importable from the main module for multiprocessing
# https://stackoverflow.com/questions/24728084/why-does-this-implementation-of-multiprocessing-pool-not-work
def parse_one_month_wrapper(args):
year, month, on_file, kwargs = args
Parser(**kwargs).parse_one_month(year, month)
### Create global helper function for formatting names of data files
## Format dates to be consistent with pushshift file names
def format_date(yr, mo):
if len(str(mo)) < 2:
mo = '0{}'.format(mo)
assert len(str(yr)) == 4
assert len(str(mo)) == 2
return "{}-{}".format(yr, mo)
## Raw Reddit data filename format. The compression types for dates handcoded
# based on https://files.pushshift.io/reddit/comments/
# IMPORTANT: Remember to recode the filenames below accordingly if the RC files
# have been downloaded and transformed into a different compression type than
# shown to prevent filename errors
def get_rc_filename(yr, mo):
date = format_date(yr, mo)
if (yr == 2017 and mo == 12) or (yr == 2018 and mo < 10):
return 'RC_{}.xz'.format(date)
elif (yr == 2018 and mo >= 10) or (yr > 2018):
return 'RC_{}.zst'.format(date)
else:
return 'RC_{}.bz2'.format(date)
## based on provided dates, gather a list of months for which data is already
# available
on_file = []
for date in dates:
mo, yr = date[0], date[1]
proper_filename = get_rc_filename(mo, yr)
if Path(data_path + proper_filename).is_file():
on_file.append(proper_filename)
### Define the parser class
class Parser(object):
# Parameters:
# dates: a list of (year,month) tuples for which data is to be processed
# path: Path for data and output files.
# stop: List of stopwords.
# vote_counting: Include number of votes per comment in parsed file.
# NN: Parse for neural net.
# write_original: Write a copy of the raw file.
# download_raw: If the raw data doesn't exist in path, download a copy from
# https://files.pushshift.io/reddit/comments/.
# clean_raw: Delete the raw data file when finished.
def __init__(self, nlp_wrapper=StanfordCoreNLP('http://localhost:9000'),bert_tokenizer=BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True), clean_raw=CLEAN_RAW, dates=dates,
download_raw=DOWNLOAD_RAW, hashsums=None, NN=NN, data_path=data_path,
model_path=model_path,engineering=engineering, genetic=genetic, disease=disease,
stop=stop, write_original=WRITE_ORIGINAL,array=None,calculate_perc_rel=calculate_perc_rel,
vote_counting=vote_counting,author=author, sentiment=sentiment,
add_sentiment=add_sentiment,balanced_rel_sample=balanced_rel_sample,
machine=None, on_file=on_file, num_process=num_process,
rel_sample_num=rel_sample_num, num_cores=num_cores,num_annot=num_annot,
Neural_Relevance_Filtering=Neural_Relevance_Filtering):
# check input arguments for valid type
assert type(vote_counting) is bool
assert type(author) is bool
assert type(sentiment) is bool
assert type(add_sentiment) is bool
assert type(NN) is bool
assert type(write_original) is bool
assert type(download_raw) is bool
assert type(clean_raw) is bool
assert type(data_path) is str
assert type(model_path) is str
assert type(num_cores) is int
# check the given path
if not os.path.exists(data_path) or not os.path.exists(model_path):
raise Exception('Invalid path')
assert type(stop) is set or type(stop) is list
self.clean_raw = CLEAN_RAW
self.dates = dates
self.download_raw = download_raw
self.hashsums = hashsums
self.NN = NN
self.data_path = data_path
self.model_path = model_path
self.engineering = engineering
self.disease = disease
self.genetic = genetic
self.stop = stop
self.write_original = write_original
self.calculate_perc_rel = calculate_perc_rel
self.vote_counting = vote_counting
self.author = author
self.sentiment = sentiment
self.add_sentiment = add_sentiment
self.num_cores = num_cores
self.num_annot = num_annot
self.array = array
self.machine = machine
self.on_file = on_file
self.bert_tokenizer = bert_tokenizer
# connect the Python wrapper to the server
# Instantiate CoreNLP wrapper than can be used across multiple threads
self.nlp_wrapper = nlp_wrapper
self.num_process = num_process
self.rel_sample_num = rel_sample_num
self.balanced_rel_sample = balanced_rel_sample
self.Neural_Relevance_Filtering = Neural_Relevance_Filtering
### calculate the yearly relevant comment counts
def Get_Counts(self,model_path=model_path, random=False, frequency="monthly"):
assert frequency in ("monthly", "yearly")
fns=self.get_parser_fns()
fn=fns["counts"] if not random else fns["counts_random"]
# check for monthly relevant comment counts
if not Path(fn).is_file():
raise Exception('The cummulative monthly counts could not be found')
# load monthly relevant comment counts
with open(fn,'r') as f:
timelist = []
for line in f:
if line.strip() != "":
timelist.append(int(line))
# intialize lists and counters
cumulative = [] # cummulative number of comments per interval
per = [] # number of comments per interval
month_counter = 0
# iterate through monthly counts
for index,number in enumerate(timelist): # for each month
month_counter += 1 # update counter
if frequency=="monthly":
cumulative.append(number) # add the cummulative count
if index == 0: # for the first month
per.append(number) # append the cummulative value to number of comments per year
else: # for the other months, subtract the last two cummulative values to find the number of relevant comments in that year
per.append(number - cumulative[-2])
else:
if (month_counter % 12) == 0 or index == len(timelist) - 1: # if at the end of the year or the corpus
cumulative.append(number) # add the cummulative count
if index + 1 == 12: # for the first year
per.append(number) # append the cummulative value to number of comments per year
else: # for the other years, subtract the last two cummulative values to find the number of relevant comments in that year
per.append(number - cumulative[-2])
month_counter = 0 # reset the counter at the end of the year
assert sum(per) == cumulative[-1], "Monthly counts do not add up to the total count"
assert cumulative[-1] == timelist[-1], "Total count does not add up to the number of posts on file"
return per,cumulative
## Download Reddit comment data
def download(self, year=None, month=None, filename=None):
assert not all([isinstance(year, type(None)),
isinstance(month, type(None)),
isinstance(filename, type(None))
])
assert isinstance(filename, type(None)) or (isinstance(year, type(None))
and isinstance(month, type(None)))
BASE_URL = 'https://files.pushshift.io/reddit/comments/'
if not isinstance(filename, type(None)):
url = BASE_URL + filename
else:
url = BASE_URL + get_rc_filename(year, month)
print('Sending request to {}.'.format(url))
try:
os.system('cd {} && wget -nv {}'.format(self.data_path, url)) # non-verbose
except: # if download fails, mark the months affected so that they can
# be re-downloaded
print("Download error for year "+str(year)+", month "+str(month))
with open(self.data_path+"Download_Errors.txt","a+") as file:
file.write(str(year)+","+str(month)+"\n")
## Get Reddit compressed data file hashsums to check downloaded files'
# integrity
def Get_Hashsums(self):
# notify the user
print('Retrieving hashsums to check file integrity')
# set the URL to download hashsums from
url = 'https://files.pushshift.io/reddit/comments/sha256sum.txt'
# remove any old hashsum file
if Path(self.model_path + '/sha256sum.txt').is_file():
os.remove(self.model_path + '/sha256sum.txt')
# download hashsums
os.system('cd {} && wget {}'.format(self.model_path, url))
# retrieve the correct hashsums
hashsums = {}
with open(self.model_path + '/sha256sum.txt', 'rb') as f:
for line in f:
line = line.decode("utf-8")
if line.strip() != "":
(val, key) = str(line).split()
hashsums[key] = val
return hashsums
## calculate hashsums for downloaded files in chunks of size 4096B
def sha256(self, fname):
hash_sha256 = hashlib.sha256()
with open("{}/{}".format(self.model_path, fname), "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
## Define the function for parts of preprocessing that are shared between
# LDA and neural nets
def _clean(self, text):
# check input arguments for valid type
assert type(text) is str
replace = {"should've": "shouldve", "mustn't": "mustnt",
"shouldn't": "shouldnt", "couldn't": "couldnt", "shan't": "shant",
"needn't": "neednt", "-": ""}
substrs = sorted(replace, key=len, reverse=True)
regexp = re.compile('|'.join(map(re.escape, substrs)))
stop_free = regexp.sub(
lambda match: replace[match.group(0)], text)
# remove special characters
special_free = ""
for word in stop_free.split():
if "http" not in word and "www" not in word: # remove links
word = re.sub('[^A-Za-z0-9]+', ' ', word)
if word.strip() != "":
special_free = special_free + " " + word.strip()
# check for stopwords again
special_free = " ".join([i for i in special_free.split() if i not in
self.stop])
return special_free
## NN_encode: uses the BERT tokenizer to process a comment into its
## sentence-by-sentence segment IDs and vocabulary IDs
def NN_encode(self, text):
# check input arguments for valid type
assert type(text) is list or type(text) is str
# Create 2d arrays for sentence ids and segment ids.
sentence_ids = [] # each subarray is an array of vocab ids for each token in the sentence
segment_ids = [] # each subarray is an array of ids indicating which sentence each token belongs to
# The following code will:
# (1) Tokenize each sentence.
# (2) Prepend the `[CLS]` token to the start of each sentence.
# (3) Append the `[SEP]` token to the end of each sentence.
# (4) Map tokens to their IDs.
id = 0
for index, sent in enumerate(text): # iterate over the sentences
encoded_sent = self.bert_tokenizer.encode(sent, # Sentence to encode
add_special_tokens=True) # Add '[CLS]' and '[SEP]'
segment = [id] * len(self.bert_tokenizer.tokenize(sent))
sentence_ids.append(encoded_sent)
segment_ids.append(segment)
# # alternate segment id between 0 and 1
# # TODO: Ask Babak about this
id = 1 - id
return sentence_ids, segment_ids
## Gets attention masks so BERT knows which tokens correspond to real words vs padding
def NN_attention_masks(self, input_ids):
# Create attention masks
attention_masks = []
for sent in input_ids:
# Create mask.
# - If a token ID is 0, it's padding -- set the mask to 0.
# - If a token ID is > 0, it's a real token -- set the mask to 1.
att_mask = [int(token_id > 0) for token_id in sent]
# Store the attention mask for this sentence.
attention_masks.append(att_mask)
return attention_masks
## Main parsing function for BERT
def parse_for_bert(self, body):
# Encode the sentences into sentence and segment ids using BERT
sentence_ids, segment_ids = self.NN_encode(body) # encode the text for NN
# TODO: double check with Babak on max length
max_length = 128
# Pad our input tokens with value 0.
# "post" indicates that we want to pad and truncate at the end of the sequence,
# as opposed to the beginning.
# Pad sentences to fit length
padded_sentence_ids = pad_sequences(segment_ids, maxlen=max_length, dtype="long",
value=0, truncating="post", padding="post")
# Create attention masks
attention_masks = self.NN_attention_masks(padded_sentence_ids)
data_to_write = {
'tokenized_sentences': body,
'sentence_ids': padded_sentence_ids.tolist(),
## These below should also be ndarrays
'segment_ids': segment_ids,
'attention_masks': attention_masks
}
return data_to_write
## define the preprocessing function to lemmatize, and remove punctuation,
# special characters and stopwords (LDA)
# NOTE: Since LDA doesn't care about sentence structure, unlike NN_clean,
# the entire comment should be fed into this function as a continuous string
# NOTE: Quotes (marked by > in the original dataset) are not removed
def LDA_clean(self, text):
special_free = self._clean(text)
# remove stopwords --> check to see if apostrophes are properly encoded
stop_free = " ".join([i for i in special_free.lower().split() if i.lower() not
in self.stop])
# load lemmatizer with automatic POS tagging
lemmatizer = spacy.load('en', disable=['parser', 'ner'])
# Extract the lemma for each token and join
lemmatized = lemmatizer(stop_free)
normalized = " ".join([token.lemma_ for token in lemmatized])
return normalized
## Define the input/output paths and filenames for the parser
def get_parser_fns(self, year=None, month=None):
assert ((isinstance(year, type(None)) and isinstance(month, type(None))) or
(not isinstance(year, type(None)) and not isinstance(month, type(None))))
if isinstance(year, type(None)) and isinstance(month, type(None)):
suffix = ""
else:
suffix = "-{}-{}".format(year, month)
fns = dict((("original_comm", "{}/original_comm/original_comm{}".format(self.model_path, suffix)),
("original_indices", "{}/original_indices/original_indices{}".format(self.model_path, suffix)),
("counts", "{}/counts/RC_Count_List{}".format(self.model_path, suffix)),
("timedict", "{}/timedict/RC_Count_Dict{}".format(self.model_path, suffix))
))
if self.NN:
# fns["nn_prep"] = "{}/nn_prep/nn_prep{}".format(self.model_path, suffix)
fns["bert_prep"] = "{}/bert_prep/bert_prep{}.json".format(self.model_path, suffix)
else:
fns["lda_prep"] = "{}/lda_prep/lda_prep{}".format(self.model_path, suffix)
if self.calculate_perc_rel:
fns["total_count"] = "{}/total_count/total_count{}".format(self.model_path, suffix)
if self.vote_counting:
fns["votes"] = "{}/votes/votes{}".format(self.model_path, suffix)
if self.author:
fns["author"] = "{}/author/author{}".format(self.model_path, suffix)
if self.sentiment:
fns["t_sentiments"] = "{}/t_sentiments/t_sentiments{}".format(self.model_path, suffix)
fns["v_sentiments"] = "{}/v_sentiments/v_sentiments{}".format(self.model_path, suffix)
if not self.add_sentiment:
fns["sentiments"] = "{}/sentiments/sentiments{}".format(self.model_path, suffix)
return fns
## Receives as input one document and its index, as well as output address
# writes sentiment values derived from 2 packages separately to file,
# averages them if add_sentiment == False, and stores the average as well
# NOTE: If add_sentiment == True, the averaging will happen through
# add_sentiment() within NN_Book_Keeping.py
def write_avg_sentiment(self, original_body, month, main_counter, fns, v_sentiments=None,
t_sentiments=None,sentiments=None):
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
tokenized = sent_detector.tokenize(original_body)
total_vader = 0
total_textblob = 0
if self.machine == "local":
with open(fns["v_sentiments"], "a+") as v_sentiments, open(fns["t_sentiments"], "a+") as t_sentiments:
for sentence in tokenized:
# Vader score
sid = SentimentIntensityAnalyzer()
score_dict = sid.polarity_scores(sentence)
total_vader += score_dict['compound']
v_sentiments.write(str(score_dict['compound']) + ",")
# Get TextBlob sentiment
blob = TextBlob(sentence)
total_textblob += blob.sentiment[0]
t_sentiments.write(str(blob.sentiment[0]) + ",")
v_sentiments.write("\n")
t_sentiments.write("\n")
elif self.machine == "ccv":
v_per_sentence = []
t_per_sentence = []
for sentence in tokenized:
# Vader score
sid = SentimentIntensityAnalyzer()
score_dict = sid.polarity_scores(sentence)
total_vader += score_dict['compound']
v_per_sentence.append(str(score_dict['compound']))
# Get TextBlob sentiment
blob = TextBlob(sentence)
total_textblob += blob.sentiment[0]
t_per_sentence.append(str(blob.sentiment[0]))
v_sentiments.append(",".join(v_per_sentence))
t_sentiments.append(",".join(t_per_sentence))
avg_vader = total_vader / len(tokenized)
avg_blob = total_textblob / len(tokenized)
if not self.add_sentiment:
avg_score = (avg_vader + avg_blob) / 2
if self.machine == "local":
print(avg_score, file=sentiments)
elif self.machine == "ccv":
sentiments.append(avg_score)
# @staticmethod
# def is_relevant(text, automaton_marijuana, automaton_legal, regex_marijuana, regex_legal):
# """
# This function determines if a given comment is relevant (it mentions both marijuana and legal topics).
# :param text: lower case text of a comment
# :param automaton_marijuana: ahocorasick.Automaton object containing the marijuana key words
# :param automaton_legal: ahocorasick.Automaton object containing the legal key words
# :param regex_marijuana: a single regular expression
# :param regex_legal: a single regular expression
# :return: Boolean, True if text is relevant, False otherwise
# """
# for _ in automaton_marijuana.iter(text):
# # note that we enter the loop only 1% of the time
# for _ in automaton_legal.iter(text):
# if not regex_marijuana.search(text) is None:
# # if the comment is marijuana relevant, check if it legal-relevant
# if not regex_legal.search(text) is None:
# return True
# else:
# # the comment is marijuana relevant, but not legal relevant
# return False
# else:
# # the marijuana regex didn't match anything. So the comment is NOT relevant.
# return False
# # the automaton_legal didn't find anything, so the comment is NOT relevant
# return False
# # the automaton_marijuana didn't find anything, so the comment is NOT relevant
# return False
def LDA_Prep(self):
if not Path(self.model_path + "/original_comm/original_comm").is_file():
raise Exception('Original comments could not be found')
for yr,mo in self.dates:
if not Path(self.model_path + "/original_comm/original_comm-{}-{}".format(yr,mo)).is_file():
raise Exception('Monthly original comments could not be found.')
if not os.path.exists(self.model_path + "/lda_prep/"):
print("Creating directories to store the additional sentiment output")
os.makedirs(self.model_path + "/lda_prep")
empty_counter = 0
for yr,mo in self.dates:
with open(self.model_path + "/original_comm/original_comm-{}-{}".format(yr,mo),"r") as fin, open(self.model_path + "/lda_prep/lda_prep-{}-{}".format(yr,mo),"w") as fout, open(self.model_path + "/lda_prep/lda_prep","a+") as general:
for line in fin: # for each comment
original_body = line.strip()
# clean the text for LDA
body = self.LDA_clean(original_body)
if body.strip() == "": # if the comment is not empty after preprocessing
empty_counter += 1
print("",end="\n", file = general)
print("",end="\n", file = fout)
else:
# remove mid-comment lines
body = body.replace("\n", "")
body = " ".join(body.split())
# print the comment to file
print(body, sep=" ", end="\n", file=general)
print(body, sep=" ", end="\n", file=fout)
# timer
print("Finished parsing month {} of year {}".format(mo,yr)+ "at " + time.strftime('%l:%M%p, %m/%d/%Y'))
print("Warning! {} documents became empty after preprocessing.".format(empty_counter))
def LDA_Prep(self):
if not Path(self.model_path + "/original_comm/original_comm").is_file():
raise Exception('Original comments could not be found')
for yr,mo in self.dates:
if not Path(self.model_path + "/original_comm/original_comm-{}-{}".format(yr,mo)).is_file():
raise Exception('Monthly original comments could not be found.')
if not os.path.exists(self.model_path + "/lda_prep/"):
print("Creating directories to store the additional sentiment output")
os.makedirs(self.model_path + "/lda_prep")
empty_counter = 0
for yr,mo in self.dates:
with open(self.model_path + "/original_comm/original_comm-{}-{}".format(yr,mo),"r") as fin, open(self.model_path + "/lda_prep/lda_prep-{}-{}".format(yr,mo),"w") as fout, open(self.model_path + "/lda_prep/lda_prep","a+") as general:
for line in fin: # for each comment
original_body = line.strip()
# clean the text for LDA
body = self.LDA_clean(original_body)
if body.strip() == "": # if the comment is not empty after preprocessing
empty_counter += 1
print("",end="\n", file = general)
print("",end="\n", file = fout)
else:
# remove mid-comment lines
body = body.replace("\n", "")
body = " ".join(body.split())
# print the comment to file
print(body, sep=" ", end="\n", file=general)
print(body, sep=" ", end="\n", file=fout)
# timer
print("Finished parsing month {} of year {}".format(mo,yr)+ "at " + time.strftime('%l:%M%p, %m/%d/%Y'))
print("Warning! {} documents became empty after preprocessing.".format(empty_counter))
## The main parsing function
# NOTE: Parses for LDA if NN = False
# NOTE: Saves the text of the non-processed comment to file as well if write_original = True
def parse_one_month(self, year, month):
timedict = dict()
# get the relevant compressed data file name
filename = get_rc_filename(year, month)
# Get names of processing files
fns = self.get_parser_fns(year, month)
if self.NN or self.sentiment: # if parsing for an NN or calculating sentiment
# import the pre-trained PUNKT tokenizer for determining sentence boundaries
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
decoder = json.JSONDecoder()
# check to see if fully preprocessed data for a certain month exists
missing_parsing_files = []
for file in fns.keys():
if not Path(fns[file]).is_file():
missing_parsing_files.append(fns[file])
if len(missing_parsing_files) != 0: # if the processed data is incpmplete
# this will be used for efficient word searching
# marijuana_keywords, legal_keywords = [], []
# with open("alt_marijuana.txt", 'r') as f:
# for line in f:
# marijuana_keywords.append(line.lower().rstrip("\n"))
#
# with open("alt_legality.txt", 'r') as f:
# for line in f:
# legal_keywords.append(line.lower().rstrip("\n"))
#
# automaton_marijuana = ahocorasick.Automaton()
# automaton_legal = ahocorasick.Automaton()
#
# for idx, key in enumerate(marijuana_keywords):
# automaton_marijuana.add_word(key, (idx, key))
#
# for idx, key in enumerate(marijuana_keywords):
# automaton_legal.add_word(key, (idx, key))
#
# automaton_marijuana.make_automaton()
# automaton_legal.make_automaton()
print("The following needed processed file(s) were missing for "
+ str(year) + ", month " + str(month) + ":")
print(missing_parsing_files)
print("Initiating preprocessing of " + filename + " at "
+ time.strftime('%l:%M%p, %m/%d/%Y'))
# preprocess raw data
# if the file is available on disk and download is on, prevent deletion
if not filename in self.on_file and self.download_raw:
self.download(year, month) # download the relevant file
# check data file integrity and download again if needed
# NOTE: sometimes inaccurate reported hashsums in the online dataset
# cause this check to invariably fail. Comment out the code section
# below if that becomes a problem.
# calculate hashsum for the data file on disk
filesum = self.sha256(filename)
attempt = 0 # number of hashsum check trials for the current file
# # if the file hashsum does not match the correct hashsum
# while filesum != self.hashsums[filename]:
# attempt += 1 # update hashsum check counter
# if attempt == 3: # if failed hashsum check three times,
# # ignore the error to prevent an infinite loop
# print("Failed to pass hashsum check 3 times. Ignoring.")
# break
# # notify the user
# print("Corrupt data file detected")
# print("Expected hashsum value: " +
# self.hashsums[filename]+"\nBut calculated: "+filesum)
# os.remove(self.path+'/'+filename) # remove the corrupted file
# self.download(year, month) # download it again
# if the file is not available, but download is turned off
elif not filename in self.on_file:
# notify the user
print('Can\'t find data for {}/{}. Skipping.'.format(month, year))
return
# create a file to write the processed text to
if self.NN and self.machine == "local": # if doing NN on a local computer
fout = open(fns["bert_prep"], 'w')
elif self.NN and self.machine == "ccv": # on a cluster
with open(fns["bert_prep"], 'w') as f: # TODO: dummy file to prevent downstream errors. Fix later
pass
fout = []
elif not self.NN and self.machine == "local": # if doing LDA on a local computer
fout = open(fns["lda_prep"], 'w')
elif not self.NN and self.machine == "ccv":
fout = []
else:
raise Exception("Machine specification variable not found.")
# create a file if we want to write the original comments and their indices to disk
if self.write_original and self.machine == "local":
foriginal = open(fns["original_comm"], 'w')
main_indices = open(fns["original_indices"], 'w')
elif self.write_original and self.machine == "ccv":
foriginal = []
main_indices = []
elif self.write_original:
raise Exception("Machine specification variable not found.")
# if we want to record the votes
if self.vote_counting and self.machine == "local":
# create a file for storing whether a relevant comment has been upvoted or downvoted more often or neither
vote = open(fns["votes"], 'w')
elif self.vote_counting and self.machine == "ccv":
vote = []
elif self.vote_counting:
raise Exception("Machine specification variable not found.")
# if we want to record the author
if self.author and self.machine == "local":
# create a file for storing whether a relevant comment has been upvoted or downvoted more often or neither
author = open(fns["author"], 'w')
elif self.author and self.machine == "ccv":
author = []
elif self.author:
raise Exception("Machine specification variable not found.")
if self.sentiment and self.machine == "local":
# docs for sentence-level sentiments of posts
v_sentiments = open(fns["v_sentiments"], 'w')
t_sentiments = open(fns["t_sentiments"], 'w')
if not self.add_sentiment: # doc for average post sentiment
sentiments = open(fns["sentiments"], 'w')
elif self.sentiment and self.machine == "ccv":
# lists for sentence-level sentiments of posts
v_sentiments = []
t_sentiments = []
if not self.add_sentiment: # list for average post sentiment
sentiments = []
elif self.sentiment:
raise Exception("Machine specification variable not found.")
# create a file to store the relevant cummulative indices for each month
ccount = open(fns["counts"], 'w')
warning_counter = 0
main_counter = 0
# open the file as a text file, in utf8 encoding, based on encoding type
if '.zst' in filename:
file = open(self.data_path + filename, 'rb')
dctx = zstd.ZstdDecompressor()
stream_reader = dctx.stream_reader(file)
fin = io.TextIOWrapper(stream_reader, encoding='utf-8', errors='ignore')
elif '.xz' in filename:
fin = lzma.open(self.data_path + filename, 'r')
elif '.bz2' in filename:
fin = bz2.BZ2File(self.data_path + filename, 'r')
else:
raise Exception('File format not recognized')
# read data
per_file_counter = 0
for line in fin: # for each comment
main_counter += 1 # update the general counter
if '.zst' not in filename:
line = line.decode('utf-8','ignore')
try:
comment = decoder.decode(line)
original_body = html.unescape(comment["body"]) # original text
except:
warning_counter += 1
if warning_counter < 10:
print("Warning! Invalid JSON sequence encountered. Ignoring this document.")
continue
elif warning_counter == 10:
print("Too many errors. Warnings turned off.")
continue
else:
continue
original_body = html.unescape(comment["body"]) # original text
if any(not exp.search(original_body.lower()) is None for exp in genetic) and any(
not exp.search(original_body.lower()) is None for exp in engineering) and any(not exp.search(original_body.lower()) is None for exp in disease):
# preprocess the comments
if self.NN:
# Tokenize the sentences
# body = sent_detector.tokenize(
# original_body)
# Get JSON formatted objects for BERT
# data_to_write = self.parse_for_bert(body)
# Write to bert_prep folder
# with open(fns["bert_prep"]) as readfile:
# if readfile.read(1) == "":
# data = {}
# data["parsed_data"] = [data_to_write]
# with open(fns["bert_prep"], 'w') as outfile:
# json.dump(data, outfile, indent=5)
# else:
# content = readfile.read()
# data = json.loads(content)
# temp = data['parsed_data']
# temp.append(data_to_write)
# data = temp
# with open(fns["bert_prep"], 'w') as outfile:
# json.dump(data, outfile, indent=5)
# If calculating sentiment, write the average sentiment to
# file. Range is -1 to 1, with values below 0 meaning neg
# sentiment.
# body = self._clean(original_body).lower()
non_url = 0
for word in original_body.strip().split():
if "http" not in word and "www" not in word: # remove links
non_url += 1
if non_url == 0:
body = ""
else:
body = original_body
else: # if doing LDA
# clean the text for LDA
body = self.LDA_clean(original_body)
if body.strip() == "": # if the comment is not empty after preprocessing
pass
else:
if not self.NN:
# remove mid-comment lines
body = body.replace("\n", "")
body = " ".join(body.split())
# If calculating sentiment, write the average sentiment.
# Range is -1 to 1, with values below 0 meaning neg
if self.sentiment and not self.add_sentiment:
self.write_avg_sentiment(original_body,month,
main_counter, fns,
v_sentiments,t_sentiments,
sentiments)
elif self.sentiment:
self.write_avg_sentiment(original_body,month,
main_counter, fns,
v_sentiments,t_sentiments)
if self.machine == "local": # write comment-by-comment
# print the comment to file
print(body, sep=" ", end="\n", file=fout)
# if we want to write the original comment to disk
if self.write_original:
original_body = original_body.replace(
"\n", "") # remove mid-comment lines
# record the original comment
print(" ".join(original_body.split()), file=foriginal)
# record the index in the original files
print(main_counter, file=main_indices)
# if we are interested in the upvotes
if self.vote_counting:
if type(comment["score"]) is int:
print(int(comment["score"]), end="\n", file=vote)
# write the fuzzed number of upvotes to file
# Some of the scores for banned subreddits like "incels"
# are not available in the original dataset. Write NA for
# those
elif comment["score"] is None:
print("None", end="\n", file=vote)
# if we are interested in the author of the posts
if self.author:
# write their username to file
print(comment["author"].strip(),
end="\n", file=author)
elif self.machine == "ccv":
if not self.NN:
fout.append(body + "\n")
if self.write_original:
original_body = original_body.replace(
"\n", "") # remove mid-comment lines
# record the original comment
original_body = " ".join(original_body.split())
foriginal.append(original_body)
# record the index in the original files
main_indices.append(main_counter)
if self.vote_counting:
if type(comment["score"]) is int:
vote.append(int(comment["score"]))
# write the fuzzed number of upvotes to file
# Some of the scores for banned subreddits like "incels"
# are not available in the original dataset. Write NA for
# those
elif comment["score"] is None:
vote.append("None")
if self.author:
author.append(comment["author"].strip())
else:
raise Exception("Machine identification variable not found")
# record the number of documents by year and month
created_at = datetime.datetime.fromtimestamp(
int(comment["created_utc"])).strftime('%Y-%m')
timedict[created_at] = timedict.get(created_at, 0)
timedict[created_at] += 1
per_file_counter += 1
# write the total number of posts from the month to disk to aid in
# calculating proportion relevant if calculate_perc_rel = True
if calculate_perc_rel:
with open(fns["total_count"], 'w') as counter_file:
print(str(main_counter), end="\n", file=counter_file)
# close the files to save the data
fin.close()
if self.machine == "local":
fout.close()
elif self.machine == "ccv" and not self.NN:
with open(fns["lda_prep"], 'w') as f:
for element in fout:
f.write(str(element)+"\n")
# BUG: I'm ignoring the case where self.NN AND self.machine == "ccv".
# This is because currently we're not doing any preprocessing on the
# neural network input. Should add another condition if we do at
# some point
if self.vote_counting and self.machine == "local":
vote.close()
elif self.vote_counting:
with open(fns["votes"], 'w') as f:
for element in vote:
f.write(str(element)+"\n")
if self.write_original and self.machine == "local":
foriginal.close()
main_indices.close()
elif self.write_original and self.machine == "ccv":
with open(fns["original_comm"], 'w') as f:
for element in foriginal:
f.write(str(element)+"\n")
with open(fns["original_indices"], 'w') as f:
for element in main_indices:
f.write(str(element)+"\n")
if self.author and self.machine == "local":
author.close()
elif self.author and self.machine == "ccv":
with open(fns["author"],'w') as f:
for element in author:
f.write(str(element)+"\n")
if self.sentiment and self.machine == "local":
v_sentiments.close()
t_sentiments.close()
if not self.add_sentiment:
sentiments.close()
elif self.sentiment and self.machine == "ccv":
assert len(v_sentiments) == per_file_counter
assert len(t_sentiments) == per_file_counter
if not self.add_sentiment:
assert len(sentiments) == per_file_counter
with open(fns["sentiments"],'w') as f:
for element in sentiments:
f.write(str(element)+"\n")
with open(fns["v_sentiments"], 'w') as g:
for element in v_sentiments:
g.write(str(element)+"\n")
with open(fns["t_sentiments"], 'w') as h:
for element in t_sentiments:
h.write(str(element)+"\n")
ccount.write(str(per_file_counter)+"\n")
ccount.close()
with open(fns["timedict"], "wb") as wfh:
pickle.dump(timedict, wfh)
# reset the missing files list for the next month
missing_parsing_files = []
# timer
print("Finished parsing " + filename + " at " + time.strftime('%l:%M%p, %m/%d/%Y'))
# if the user wishes compressed data files to be removed after processing
if self.clean_raw and filename not in self.on_file and Path(self.data_path + filename).is_file():
print("Cleaning up {}{}.".format(self.data_path, filename))
# delete the recently processed file
os.system('cd {} && rm {}'.format(self.data_path, filename))
return
## Pool parsed monthly data
def pool_parsing_data(self):
fns = self.get_parser_fns()
# Initialize an "overall" timedict
timedict = defaultdict(lambda: 0)
for kind in fns.keys():
fns_ = [self.get_parser_fns(year, month)[kind] for year, month in
self.dates]
if kind == "counts":
continue
if kind == "timedict":
# Update overall timedict with data from each year
for fn_ in fns_:
with open(fn_, "rb") as rfh:
minitimedict = pickle.load(rfh)
for mo, val in minitimedict.items():
timedict[mo] += val
with open(fns["timedict"], "w") as tdfh:
with open(fns["counts"], "w") as cfh:
cumul_docs = 0
for date in self.dates:
month = format_date(*date)
docs = timedict[month]
print(month + " " + str(docs), end='\n', file=tdfh)
# Use timedict data to populate counts file