]> code.communitydata.science - cdsc_reddit.git/blob - datasets/submissions_2_parquet_part1.py
remove nsfw subs from topN
[cdsc_reddit.git] / datasets / submissions_2_parquet_part1.py
1 #!/usr/bin/env python3
2
3 # two stages:
4 # 1. from gz to arrow parquet (this script) 
5 # 2. from arrow parquet to spark parquet (submissions_2_parquet_part2.py)
6
7 from datetime import datetime
8 from multiprocessing import Pool
9 from itertools import islice
10 from helper import find_dumps, open_fileset
11 import pandas as pd
12 import pyarrow as pa
13 import pyarrow.parquet as pq
14 import simdjson
15 import fire
16 import os
17
18 parser = simdjson.Parser()
19
20 def parse_submission(post, names = None):
21     if names is None:
22         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','quarantine','error']
23
24     try:
25         post = parser.parse(post)
26     except (ValueError) as e:
27         #        print(e)
28         #        print(post)
29         row = [None for _ in names]
30         row[-1] = "Error parsing json|{0}|{1}".format(e,post)
31         return tuple(row)
32
33     row = []
34
35     for name in names:
36         if name == 'created_utc' or name == 'retrieved_on':
37             val = post.get(name,None)
38             if val is not None:
39                 row.append(datetime.fromtimestamp(int(post[name]),tz=None))
40             else:
41                 row.append(None)
42         elif name == 'edited':
43             val = post[name]
44             if type(val) == bool:
45                 row.append(val)
46                 row.append(None)
47             else:
48                 row.append(True)
49                 row.append(datetime.fromtimestamp(int(val),tz=None))
50         elif name == "time_edited":
51             continue
52         elif name == 'has_media':
53             row.append(post.get('media',None) is not None)
54
55         elif name not in post:
56             row.append(None)
57         else:
58             row.append(post[name])
59     return tuple(row)
60
61 def parse_dump(partition):
62
63     N=10000
64     stream = open_fileset([f"/gscratch/comdata/raw_data/reddit_dumps/submissions/{partition}"])
65     rows = map(parse_submission,stream)
66     schema = pa.schema([
67         pa.field('id', pa.string(),nullable=True),
68         pa.field('author', pa.string(),nullable=True),
69         pa.field('subreddit', pa.string(),nullable=True),
70         pa.field('title', pa.string(),nullable=True),
71         pa.field('created_utc', pa.timestamp('ms'),nullable=True),
72         pa.field('permalink', pa.string(),nullable=True),
73         pa.field('url', pa.string(),nullable=True),
74         pa.field('domain', pa.string(),nullable=True),
75         pa.field('score', pa.int64(),nullable=True),
76         pa.field('ups', pa.int64(),nullable=True),
77         pa.field('downs', pa.int64(),nullable=True),
78         pa.field('over_18', pa.bool_(),nullable=True),
79         pa.field('has_media',pa.bool_(),nullable=True),
80         pa.field('selftext',pa.string(),nullable=True),
81         pa.field('retrieved_on', pa.timestamp('ms'),nullable=True),
82         pa.field('num_comments', pa.int64(),nullable=True),
83         pa.field('gilded',pa.int64(),nullable=True),
84         pa.field('edited',pa.bool_(),nullable=True),
85         pa.field('time_edited',pa.timestamp('ms'),nullable=True),
86         pa.field('subreddit_type',pa.string(),nullable=True),
87         pa.field('subreddit_id',pa.string(),nullable=True),
88         pa.field('subreddit_subscribers',pa.int64(),nullable=True),
89         pa.field('name',pa.string(),nullable=True),
90         pa.field('is_self',pa.bool_(),nullable=True),
91         pa.field('stickied',pa.bool_(),nullable=True),
92         pa.field('quarantine',pa.bool_(),nullable=True),
93         pa.field('error',pa.string(),nullable=True)])
94
95     if not os.path.exists("/gscratch/comdata/output/temp/reddit_submissions.parquet/"):
96         os.mkdir("/gscratch/comdata/output/temp/reddit_submissions.parquet/")
97
98     with pq.ParquetWriter(f"/gscratch/comdata/output/temp/reddit_submissions.parquet/{partition}",schema=schema,compression='snappy',flavor='spark') as writer:
99         while True:
100             chunk = islice(rows,N)
101             pddf = pd.DataFrame(chunk, columns=schema.names)
102             table = pa.Table.from_pandas(pddf,schema=schema)
103             if table.shape[0] == 0:
104                 break
105             writer.write_table(table)
106
107         writer.close()
108
109 def gen_task_list(dumpdir="/gscratch/comdata/raw_data/reddit_dumps/submissions"):
110     files = list(find_dumps(dumpdir,base_pattern="RS_20*.*"))
111     with open("parse_submissions_task_list",'w') as of:
112         for fpath in files:
113             partition = os.path.split(fpath)[1]
114             of.write(f'python3 submissions_2_parquet_part1.py parse_dump {partition}\n')
115
116 if __name__ == "__main__":
117     fire.Fire({'parse_dump':parse_dump,
118               'gen_task_list':gen_task_list})

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