]> code.communitydata.science - cdsc_reddit.git/blob - ngrams/tf_comments.py
version of weekly_cosine_similarities.py from klone
[cdsc_reddit.git] / ngrams / tf_comments.py
1 #!/usr/bin/env python3
2 import pandas as pd
3 import pyarrow as pa
4 import pyarrow.dataset as ds
5 import pyarrow.parquet as pq
6 from itertools import groupby, islice, chain
7 import fire
8 from collections import Counter
9 import os
10 import re
11 from nltk import wordpunct_tokenize, MWETokenizer, sent_tokenize
12 from nltk.corpus import stopwords
13 from nltk.util import ngrams
14 import string
15 from random import random
16
17 # remove urls
18 # taken from https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
19 urlregex = re.compile(r"[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)")
20
21 # compute term frequencies for comments in each subreddit by week
22 def weekly_tf(partition, mwe_pass = 'first'):
23     dataset = ds.dataset(f'/gscratch/comdata/output/reddit_comments_by_subreddit.parquet/{partition}', format='parquet')
24     if not os.path.exists("/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/"):
25         os.mkdir("/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/")
26
27     if not os.path.exists("/gscratch/comdata/users/nathante/reddit_tfidf_test_authors.parquet_temp/"):
28         os.mkdir("/gscratch/comdata/users/nathante/reddit_tfidf_test_authors.parquet_temp/")
29
30     ngram_output = partition.replace("parquet","txt")
31
32     if mwe_pass == 'first':
33         if os.path.exists(f"/gscratch/comdata/output/reddit_ngrams/comment_ngrams_10p_sample/{ngram_output}"):
34             os.remove(f"/gscratch/comdata/output/reddit_ngrams/comment_ngrams_10p_sample/{ngram_output}")
35     
36     batches = dataset.to_batches(columns=['CreatedAt','subreddit','body','author'])
37
38
39     schema = pa.schema([pa.field('subreddit', pa.string(), nullable=False),
40                         pa.field('term', pa.string(), nullable=False),
41                         pa.field('week', pa.date32(), nullable=False),
42                         pa.field('tf', pa.int64(), nullable=False)]
43     )
44
45     author_schema = pa.schema([pa.field('subreddit', pa.string(), nullable=False),
46                                pa.field('author', pa.string(), nullable=False),
47                                pa.field('week', pa.date32(), nullable=False),
48                                pa.field('tf', pa.int64(), nullable=False)]
49     )
50
51     dfs = (b.to_pandas() for b in batches)
52
53     def add_week(df):
54         df['week'] = (df.CreatedAt - pd.to_timedelta(df.CreatedAt.dt.dayofweek, unit='d')).dt.date
55         return(df)
56
57     dfs = (add_week(df) for df in dfs)
58
59     def iterate_rows(dfs):
60         for df in dfs:
61             for row in df.itertuples():
62                 yield row
63
64     rows = iterate_rows(dfs)
65
66     subreddit_weeks = groupby(rows, lambda r: (r.subreddit, r.week))
67
68     if mwe_pass != 'first':
69         mwe_dataset = pd.read_feather(f'/gscratch/comdata/output/reddit_ngrams/multiword_expressions.feather')
70         mwe_dataset = mwe_dataset.sort_values(['phrasePWMI'],ascending=False)
71         mwe_phrases = list(mwe_dataset.phrase)
72         mwe_phrases = [tuple(s.split(' ')) for s in mwe_phrases]
73         mwe_tokenizer = MWETokenizer(mwe_phrases)
74         mwe_tokenize = mwe_tokenizer.tokenize
75     
76     else:
77         mwe_tokenize = MWETokenizer().tokenize
78
79     def remove_punct(sentence):
80         new_sentence = []
81         for token in sentence:
82             new_token = ''
83             for c in token:
84                 if c not in string.punctuation:
85                     new_token += c
86             if len(new_token) > 0:
87                 new_sentence.append(new_token)
88         return new_sentence
89
90     stopWords = set(stopwords.words('english'))
91
92     # we follow the approach described in datta, phelan, adar 2017
93     def my_tokenizer(text):
94         # remove stopwords, punctuation, urls, lower case
95         # lowercase        
96         text = text.lower()
97
98         # remove urls
99         text = urlregex.sub("", text)
100
101         # sentence tokenize
102         sentences = sent_tokenize(text)
103
104         # wordpunct_tokenize
105         sentences = map(wordpunct_tokenize, sentences)
106
107         # remove punctuation
108                         
109         sentences = map(remove_punct, sentences)
110
111         # remove sentences with less than 2 words
112         sentences = filter(lambda sentence: len(sentence) > 2, sentences)
113
114         # datta et al. select relatively common phrases from the reddit corpus, but they don't really explain how. We'll try that in a second phase.
115         # they say that the extract 1-4 grams from 10% of the sentences and then find phrases that appear often relative to the original terms
116         # here we take a 10 percent sample of sentences 
117         if mwe_pass == 'first':
118             sentences = list(sentences)
119             for sentence in sentences:
120                 if random() <= 0.1:
121                     grams = list(chain(*map(lambda i : ngrams(sentence,i),range(4))))
122                     with open(f'/gscratch/comdata/output/reddit_ngrams/comment_ngrams_10p_sample/{ngram_output}','a') as gram_file:
123                         for ng in grams:
124                             gram_file.write(' '.join(ng) + '\n')
125                 for token in sentence:
126                     if token not in stopWords:
127                         yield token
128
129         else:
130             # remove stopWords
131             sentences = map(mwe_tokenize, sentences)
132             sentences = map(lambda s: filter(lambda token: token not in stopWords, s), sentences)
133             for sentence in sentences:
134                 for token in sentence:
135                     yield token
136
137     def tf_comments(subreddit_weeks):
138         for key, posts in subreddit_weeks:
139             subreddit, week = key
140             tfs = Counter([])
141             authors = Counter([])
142             for post in posts:
143                 tokens = my_tokenizer(post.body)
144                 tfs.update(tokens)
145                 authors.update([post.author])
146
147             for term, tf in tfs.items():
148                 yield [True, subreddit, term, week, tf]
149
150             for author, tf in authors.items():
151                 yield [False, subreddit, author, week, tf]
152
153     outrows = tf_comments(subreddit_weeks)
154
155     outchunksize = 10000
156
157     with pq.ParquetWriter(f"/gscratch/comdata/output/reddit_ngrams/comment_terms.parquet/{partition}",schema=schema,compression='snappy',flavor='spark') as writer, pq.ParquetWriter(f"/gscratch/comdata/output/reddit_ngrams/comment_authors.parquet/{partition}",schema=author_schema,compression='snappy',flavor='spark') as author_writer:
158     
159         while True:
160
161             chunk = islice(outrows,outchunksize)
162             chunk = (c for c in chunk if c[1] is not None)
163             pddf = pd.DataFrame(chunk, columns=["is_token"] + schema.names)
164             author_pddf = pddf.loc[pddf.is_token == False, schema.names]
165             pddf = pddf.loc[pddf.is_token == True, schema.names]
166             author_pddf = author_pddf.rename({'term':'author'}, axis='columns')
167             author_pddf = author_pddf.loc[:,author_schema.names]
168             table = pa.Table.from_pandas(pddf,schema=schema)
169             author_table = pa.Table.from_pandas(author_pddf,schema=author_schema)
170             do_break = True
171
172             if table.shape[0] != 0:
173                 writer.write_table(table)
174                 do_break = False
175             if author_table.shape[0] != 0:
176                 author_writer.write_table(author_table)
177                 do_break = False
178
179             if do_break:
180                 break
181
182         writer.close()
183         author_writer.close()
184
185
186 def gen_task_list(mwe_pass='first'):
187     files = os.listdir("/gscratch/comdata/output/reddit_comments_by_subreddit.parquet/")
188     with open("tf_task_list",'w') as outfile:
189         for f in files:
190             if f.endswith(".parquet"):
191                 outfile.write(f"./tf_comments.py weekly_tf --mwe-pass {mwe_pass} {f}\n")
192
193 if __name__ == "__main__":
194     fire.Fire({"gen_task_list":gen_task_list,
195                "weekly_tf":weekly_tf})

Community Data Science Collective || Want to submit a patch?