4 import pyarrow.dataset as ds
 
   5 import pyarrow.parquet as pq
 
   6 from itertools import groupby, islice, chain
 
   8 from collections import Counter
 
  11 from nltk import wordpunct_tokenize, MWETokenizer, sent_tokenize
 
  12 from nltk.corpus import stopwords
 
  13 from nltk.util import ngrams
 
  15 from random import random
 
  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()@:%_\+.~#?&//=]*)")
 
  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/")
 
  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/")
 
  30     ngram_output = partition.replace("parquet","txt")
 
  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}")
 
  36     batches = dataset.to_batches(columns=['CreatedAt','subreddit','body','author'])
 
  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)]
 
  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)]
 
  51     dfs = (b.to_pandas() for b in batches)
 
  54         df['week'] = (df.CreatedAt - pd.to_timedelta(df.CreatedAt.dt.dayofweek, unit='d')).dt.date
 
  57     dfs = (add_week(df) for df in dfs)
 
  59     def iterate_rows(dfs):
 
  61             for row in df.itertuples():
 
  64     rows = iterate_rows(dfs)
 
  66     subreddit_weeks = groupby(rows, lambda r: (r.subreddit, r.week))
 
  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
 
  77         mwe_tokenize = MWETokenizer().tokenize
 
  79     def remove_punct(sentence):
 
  81         for token in sentence:
 
  84                 if c not in string.punctuation:
 
  86             if len(new_token) > 0:
 
  87                 new_sentence.append(new_token)
 
  90     stopWords = set(stopwords.words('english'))
 
  92     # we follow the approach described in datta, phelan, adar 2017
 
  93     def my_tokenizer(text):
 
  94         # remove stopwords, punctuation, urls, lower case
 
  99         text = urlregex.sub("", text)
 
 102         sentences = sent_tokenize(text)
 
 105         sentences = map(wordpunct_tokenize, sentences)
 
 109         sentences = map(remove_punct, sentences)
 
 111         # remove sentences with less than 2 words
 
 112         sentences = filter(lambda sentence: len(sentence) > 2, sentences)
 
 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:
 
 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:
 
 124                             gram_file.write(' '.join(ng) + '\n')
 
 125                 for token in sentence:
 
 126                     if token not in 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:
 
 137     def tf_comments(subreddit_weeks):
 
 138         for key, posts in subreddit_weeks:
 
 139             subreddit, week = key
 
 141             authors = Counter([])
 
 143                 tokens = my_tokenizer(post.body)
 
 145                 authors.update([post.author])
 
 147             for term, tf in tfs.items():
 
 148                 yield [True, subreddit, term, week, tf]
 
 150             for author, tf in authors.items():
 
 151                 yield [False, subreddit, author, week, tf]
 
 153     outrows = tf_comments(subreddit_weeks)
 
 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:
 
 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)
 
 172             if table.shape[0] != 0:
 
 173                 writer.write_table(table)
 
 175             if author_table.shape[0] != 0:
 
 176                 author_writer.write_table(author_table)
 
 183         author_writer.close()
 
 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:
 
 190             if f.endswith(".parquet"):
 
 191                 outfile.write(f"./tf_comments.py weekly_tf --mwe-pass {mwe_pass} {f}\n")
 
 193 if __name__ == "__main__":
 
 194     fire.Fire({"gen_task_list":gen_task_list,
 
 195                "weekly_tf":weekly_tf})