]> code.communitydata.science - cdsc_reddit.git/blob - submissions_2_parquet.py
014221044fb266a02d071b0106aeb59a02ed7e24
[cdsc_reddit.git] / submissions_2_parquet.py
1 #!/usr/bin/env python3
2
3 # two stages:
4 # 1. from gz to arrow parquet
5 # 2. from arrow parquet to spark parquet
6
7 from collections import defaultdict
8 from os import path
9 import glob
10 import json
11 import re
12 from datetime import datetime
13 from subprocess import Popen, PIPE
14 from multiprocessing import Pool, SimpleQueue
15
16 dumpdir = "/gscratch/comdata/raw_data/reddit_dumps/submissions"
17
18 def find_json_files(dumpdir):
19     base_pattern = "RS_20*.*"
20
21     files = glob.glob(path.join(dumpdir,base_pattern))
22
23     # build a dictionary of possible extensions for each dump
24     dumpext = defaultdict(list)
25     for fpath in files:
26         fname, ext = path.splitext(fpath)
27         dumpext[fname].append(ext)
28
29     ext_priority = ['.zst','.xz','.bz2']
30
31     for base, exts in dumpext.items():
32         found = False
33         if len(exts) == 1:
34             yield base + exts[0]
35             found = True
36         else:
37             for ext in ext_priority:
38                 if ext in exts:
39                     yield base + ext
40                     found = True
41         assert(found == True)
42
43 files = list(find_json_files(dumpdir))
44
45 def read_file(fh):
46     lines = open_input_file(fh)
47     for line in lines:
48         yield line
49
50 def open_fileset(files):
51     for fh in files:
52         print(fh)
53         lines = open_input_file(fh)
54         for line in lines:
55             yield line
56
57 def open_input_file(input_filename):
58     if re.match(r'.*\.7z$', input_filename):
59         cmd = ["7za", "x", "-so", input_filename, '*'] 
60     elif re.match(r'.*\.gz$', input_filename):
61         cmd = ["zcat", input_filename] 
62     elif re.match(r'.*\.bz2$', input_filename):
63         cmd = ["bzcat", "-dk", input_filename] 
64     elif re.match(r'.*\.bz', input_filename):
65         cmd = ["bzcat", "-dk", input_filename] 
66     elif re.match(r'.*\.xz', input_filename):
67         cmd = ["xzcat",'-dk', '-T 20',input_filename]
68     elif re.match(r'.*\.zst',input_filename):
69         cmd = ['zstd','-dck', input_filename]
70     try:
71         input_file = Popen(cmd, stdout=PIPE).stdout
72     except NameError as e:
73         print(e)
74         input_file = open(input_filename, 'r')
75     return input_file
76
77
78 def parse_submission(post, names = None):
79     if names is None:
80         names = ['id','author','subreddit','title','created_utc','permalink','url','domain','score','ups','downs','over_18','has_media','selftext','retrieved_on','num_comments','gilded','edited','time_edited','subreddit_type','subreddit_id','subreddit_subscribers','name','is_self','stickied','is_submitter','quarantine','error']
81
82     try:
83         post = json.loads(post)
84     except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
85         #        print(e)
86         #        print(post)
87         row = [None for _ in names]
88         row[-1] = "json.decoder.JSONDecodeError|{0}|{1}".format(e,post)
89         return tuple(row)
90
91     row = []
92
93     for name in names:
94         if name == 'created_utc' or name == 'retrieved_on':
95             val = post.get(name,None)
96             if val is not None:
97                 row.append(datetime.fromtimestamp(int(post[name]),tz=None))
98             else:
99                 row.append(None)
100         elif name == 'edited':
101             val = post[name]
102             if type(val) == bool:
103                 row.append(val)
104                 row.append(None)
105             else:
106                 row.append(True)
107                 row.append(datetime.fromtimestamp(int(val),tz=None))
108         elif name == "time_edited":
109             continue
110         elif name == 'has_media':
111             row.append(post.get('media',None) is not None)
112
113         elif name not in post:
114             row.append(None)
115         else:
116             row.append(post[name])
117     return tuple(row)
118
119 pool = Pool(28)
120
121 stream = open_fileset(files)
122
123 N = 100000
124
125 rows = pool.imap_unordered(parse_submission, stream, chunksize=int(N/28))
126
127 from itertools import islice
128 import pandas as pd
129 import pyarrow as pa
130 import pyarrow.parquet as pq
131
132 schema = pa.schema([
133     pa.field('id', pa.string(),nullable=True),
134     pa.field('author', pa.string(),nullable=True),
135     pa.field('subreddit', pa.string(),nullable=True),
136     pa.field('title', pa.string(),nullable=True),
137     pa.field('created_utc', pa.timestamp('ms'),nullable=True),
138     pa.field('permalink', pa.string(),nullable=True),
139     pa.field('url', pa.string(),nullable=True),
140     pa.field('domain', pa.string(),nullable=True),
141     pa.field('score', pa.int64(),nullable=True),
142     pa.field('ups', pa.int64(),nullable=True),
143     pa.field('downs', pa.int64(),nullable=True),
144     pa.field('over_18', pa.bool_(),nullable=True),
145     pa.field('has_media',pa.bool_(),nullable=True),
146     pa.field('selftext',pa.string(),nullable=True),
147     pa.field('retrieved_on', pa.timestamp('ms'),nullable=True),
148     pa.field('num_comments', pa.int64(),nullable=True),
149     pa.field('gilded',pa.int64(),nullable=True),
150     pa.field('edited',pa.bool_(),nullable=True),
151     pa.field('time_edited',pa.timestamp('ms'),nullable=True),
152     pa.field('subreddit_type',pa.string(),nullable=True),
153     pa.field('subreddit_id',pa.string(),nullable=True),
154     pa.field('subreddit_subscribers',pa.int64(),nullable=True),
155     pa.field('name',pa.string(),nullable=True),
156     pa.field('is_self',pa.bool_(),nullable=True),
157     pa.field('stickied',pa.bool_(),nullable=True),
158     pa.field('is_submitter',pa.bool_(),nullable=True),
159     pa.field('quarantine',pa.bool_(),nullable=True),
160     pa.field('error',pa.string(),nullable=True)])
161
162 with  pq.ParquetWriter("/gscratch/comdata/output/reddit_submissions.parquet_temp",schema=schema,compression='snappy',flavor='spark') as writer:
163     while True:
164         chunk = islice(rows,N)
165         pddf = pd.DataFrame(chunk, columns=schema.names)
166         table = pa.Table.from_pandas(pddf,schema=schema)
167         if table.shape[0] == 0:
168             break
169         writer.write_table(table)
170
171     writer.close()
172
173 import pyspark
174 from pyspark.sql import functions as f
175 from pyspark.sql.types import *
176 from pyspark import SparkConf, SparkContext
177 from pyspark.sql import SparkSession, SQLContext
178
179 spark = SparkSession.builder.getOrCreate()
180 sc = spark.sparkContext
181
182 conf = SparkConf().setAppName("Reddit submissions to parquet")
183 conf = conf.set('spark.sql.crossJoin.enabled',"true")
184
185 sqlContext = pyspark.SQLContext(sc)
186
187 df = spark.read.parquet("/gscratch/comdata/output/reddit_submissions.parquet_temp")
188
189 df = df.withColumn("subreddit_2", f.lower(f.col('subreddit')))
190 df = df.drop('subreddit')
191 df = df.withColumnRenamed('subreddit_2','subreddit')
192 df = df.withColumnRenamed("created_utc","CreatedAt")
193 df = df.withColumn("Month",f.month(f.col("CreatedAt")))
194 df = df.withColumn("Year",f.year(f.col("CreatedAt")))
195 df = df.withColumn("Day",f.dayofmonth(f.col("CreatedAt")))
196 df = df.withColumn("subreddit_hash",f.sha2(f.col("subreddit"), 256)[0:3])
197
198 # next we gotta resort it all.
199 df2 = df.sort(["subreddit","author","id","Year","Month","Day"],ascending=True)
200 df2.write.parquet("/gscratch/comdata/output/reddit_submissions_by_subreddit.parquet", partitionBy=["Year",'Month'], mode='overwrite')
201
202
203 # we also want to have parquet files sorted by author then reddit. 
204 df3 = df.sort(["author","CreatedAt","subreddit","id","Year","Month","Day"],ascending=True)
205 df3.write.parquet("/gscratch/comdata/output/reddit_submissions_by_author.parquet", partitionBy=["Year",'Month'], mode='overwrite')
206
207 os.remove("/gscratch/comdata/output/reddit_submissions.parquet_temp")

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