1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
5 from pathlib import Path
6 from similarities_helper import prep_tfidf_entries, read_tfidf_matrix, select_topN_subreddits, column_similarities
9 def cosine_similarities(infile, term_colname, outfile, min_df=None, included_subreddits=None, topN=500, exclude_phrases=False):
10 spark = SparkSession.builder.getOrCreate()
11 conf = spark.sparkContext.getConf()
13 print(exclude_phrases)
15 tfidf = spark.read.parquet(infile)
17 if included_subreddits is None:
18 included_subreddits = select_topN_subreddits(topN)
20 included_subreddits = set(open(included_subreddits))
22 if exclude_phrases == True:
23 tfidf = tfidf.filter(~f.col(term_colname).contains("_"))
25 print("creating temporary parquet with matrix indicies")
26 tempdir = prep_tfidf_entries(tfidf, term_colname, min_df, included_subreddits)
27 tfidf = spark.read.parquet(tempdir.name)
28 subreddit_names = tfidf.select(['subreddit','subreddit_id_new']).distinct().toPandas()
29 subreddit_names = subreddit_names.sort_values("subreddit_id_new")
30 subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
33 print("loading matrix")
34 mat = read_tfidf_matrix(tempdir.name, term_colname)
35 print('computing similarities')
36 sims = column_similarities(mat)
39 sims = pd.DataFrame(sims.todense())
40 sims = sims.rename({i:sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
41 sims['subreddit'] = subreddit_names.subreddit.values
45 output_feather = Path(str(p).replace("".join(p.suffixes), ".feather"))
46 output_csv = Path(str(p).replace("".join(p.suffixes), ".csv"))
47 output_parquet = Path(str(p).replace("".join(p.suffixes), ".parquet"))
49 sims.to_feather(outfile)
52 def term_cosine_similarities(outfile, min_df=None, included_subreddits=None, topN=500, exclude_phrases=False):
53 return cosine_similarities('/gscratch/comdata/output/reddit_similarity/tfidf/comment_terms.parquet',
61 def author_cosine_similarities(outfile, min_df=2, included_subreddits=None, topN=10000):
62 return cosine_similarities('/gscratch/comdata/output/reddit_similarity/tfidf/comment_authors.parquet',
68 exclude_phrases=False)
70 if __name__ == "__main__":
71 fire.Fire({'term':term_cosine_similarities,
72 'author':author_cosine_similarities})