KaraKaraWitch commited on
Commit
9eec092
·
verified ·
1 Parent(s): 1af74bb

Upload Scripts/RedditScoring.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Scripts/RedditScoring.py +265 -0
Scripts/RedditScoring.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import multiprocessing
3
+ import pathlib
4
+
5
+ import numpy
6
+ import orjson
7
+ import pandas
8
+ import seaborn
9
+ import tqdm
10
+ import typer
11
+ from loguru import logger
12
+ from matplotlib import pyplot as plt
13
+
14
+ app = typer.Typer()
15
+
16
+ GB = 2**30
17
+
18
+ def read_lines_jsonl(file_name, chunk_size=GB // 2):
19
+ with open(file_name, "rb") as file_handle:
20
+ buffer = b""
21
+ while True:
22
+ chunk = file_handle.read(chunk_size)
23
+
24
+ if not chunk:
25
+ break
26
+ lines = (buffer + chunk).split(b"\n")
27
+
28
+ for line in lines[:-1]:
29
+ yield line.strip()
30
+
31
+ buffer = lines[-1]
32
+
33
+ def compute_subreddit_score(
34
+ subs: pathlib.Path, comments: pathlib.Path, stats_out: pathlib.Path
35
+ ):
36
+ submission_data = {"authors": set(), "submissions": 0, "media": 0}
37
+ logger.debug(f"Gather Subs: {subs}")
38
+ for line in read_lines_jsonl(subs):
39
+ sub_data = orjson.loads(line)
40
+ if sub_data["author"]:
41
+ submission_data["authors"].add(sub_data["author"]["name"])
42
+ submission_data["submissions"] += 1
43
+ if not sub_data["text"]:
44
+ submission_data["media"] += 1
45
+ logger.debug(f"Done Gather Subs for: {subs}")
46
+ submission_data["authors"] = len(submission_data["authors"])
47
+ comment_data = {
48
+ "authors": set(),
49
+ "comments": 0,
50
+ }
51
+ logger.debug(f"Gather Comments: {comments}")
52
+ for line in read_lines_jsonl(comments):
53
+ sub_data = orjson.loads(line)
54
+ if sub_data["author"]:
55
+ comment_data["authors"].add(sub_data["author"]["name"])
56
+ comment_data["comments"] += 1
57
+ comment_data["authors"] = len(comment_data["authors"])
58
+
59
+ # Asked ChatGPT for formula advice...
60
+ engagement = comment_data["comments"] / submission_data["submissions"]
61
+ richness = (submission_data["media"] / submission_data["submissions"]) ** 2
62
+ diversity = (
63
+ comment_data["authors"] + submission_data["authors"]
64
+ ) / submission_data["submissions"]
65
+
66
+ wrapped = orjson.dumps(
67
+ {
68
+ "submission": submission_data,
69
+ "comment": comment_data,
70
+ "qscore": {
71
+ "engagement": engagement,
72
+ "richness": richness,
73
+ "diversity": diversity,
74
+ "compound": engagement * richness * diversity,
75
+ },
76
+ }
77
+ )
78
+ stats_out.write_bytes(wrapped)
79
+ logger.debug(f"{stats_out.name}: {wrapped}")
80
+
81
+ def err_cb(err):
82
+ logger.exception(err)
83
+
84
+ @app.command()
85
+ def compute_scores(output_path:pathlib.Path):
86
+ # pathlib.Path("subreddits_M700")
87
+ with multiprocessing.Pool(processes=32) as pool:
88
+ fns = []
89
+ for sub in [
90
+ i
91
+ for i in output_path.iterdir()
92
+ if i.stem.endswith("_Submission")
93
+ ]:
94
+ root_sub = sub.with_stem(sub.stem[: -len("_Submission")])
95
+ comments = root_sub.with_stem(root_sub.stem + "_Comments")
96
+ if sub.exists() and comments.exists():
97
+ stats = root_sub.with_stem(root_sub.stem + "_Scores")
98
+ fns.append(
99
+ pool.apply_async(
100
+ compute_subreddit_score,
101
+ args=(
102
+ sub,
103
+ comments,
104
+ stats,
105
+ ),
106
+ error_callback=err_cb,
107
+ )
108
+ )
109
+ else:
110
+ logger.warning(f"Mismatched: {sub} {comments}")
111
+ sub.unlink() if sub.exists() else None
112
+ comments.unlink() if comments.exists() else None
113
+ [i.wait() for i in fns]
114
+
115
+ @app.command()
116
+ def makefilter(merged_stats: pathlib.Path, output_file: pathlib.Path, mode="text"):
117
+ reddits = []
118
+ with open(merged_stats, "rb") as f:
119
+ for stats in tqdm.tqdm(f):
120
+ stats_data = orjson.loads(stats)
121
+ if "qscore" not in stats_data:
122
+ logger.warning(f"{stats} did not have any qscores.")
123
+ continue
124
+ qscores: dict = stats_data["qscore"]
125
+ if mode == "text":
126
+ # Baseline author filters
127
+ if (
128
+ stats_data["submission"]["authors"] < 70
129
+ or stats_data["comment"]["authors"] < 20
130
+ or stats_data["submission"]["submissions"] < 450
131
+ or stats_data["comment"]["comments"] < 585
132
+ ):
133
+ continue
134
+ # QScores
135
+ if qscores["engagement"] < 1.05:
136
+ # Low amount of engagement
137
+ continue
138
+ elif qscores["engagement"] > 50:
139
+ # Excessive engagement.
140
+ continue
141
+ elif qscores["compound"] < 0.05:
142
+ # Close to 0 compound is probably not worth
143
+ continue
144
+ elif qscores["richness"] < 0.01 or qscores["richness"] > 0.95:
145
+ # low richness means it's probably mostly text.
146
+ #
147
+ # High richness means almost or mostly images.
148
+ continue
149
+ elif qscores["diversity"] < 0.05 or qscores["diversity"] > 5:
150
+ # Too little diversity: Too many submission authors, not enough comment authors
151
+ # > 2: Too many comment authors, not enough submission authors.
152
+ continue
153
+ reddits.append(stats_data)
154
+ elif mode == "media":
155
+ # For media, we don't care too much about a lot of stats for text and
156
+ # more interested about raw media stuff.
157
+
158
+ # Biased richness score for images
159
+ image_bias_richness = math.sqrt(math.sqrt(qscores["richness"]))
160
+
161
+ if (
162
+ stats_data["submission"]["authors"] < 70
163
+ or stats_data["comment"]["authors"] < 20
164
+ or stats_data["submission"]["submissions"] < 450
165
+ or stats_data["comment"]["comments"] < 585
166
+ ):
167
+ continue
168
+
169
+ if qscores["engagement"] < 0.5:
170
+ # Low amount of engagement
171
+ continue
172
+ elif qscores["engagement"] > 50:
173
+ # Excessive engagement.
174
+ continue
175
+ elif qscores["compound"] < 0.05:
176
+ # Close to 0 compound is probably not worth
177
+ continue
178
+ elif image_bias_richness < 0.15 or image_bias_richness > 0.95:
179
+ # low richness means it's probably mostly text.
180
+ #
181
+ # High richness means almost or mostly images.
182
+ continue
183
+ reddits.append(stats_data)
184
+ output_file.write_bytes(
185
+ b"\n".join([orjson.dumps(reddit) for reddit in reddits])
186
+ )
187
+
188
+
189
+ @app.command()
190
+ def merge_stats(folder: pathlib.Path, output_file: pathlib.Path):
191
+ with open(output_file, "wb") as fp:
192
+ scores = [i for i in folder.iterdir() if i.stem.endswith("_Scores")]
193
+ for stats in tqdm.tqdm(scores):
194
+ stats_data = orjson.loads(stats.read_bytes())
195
+ if "qscore" not in stats_data:
196
+ logger.warning(f"{stats} did not have any qscores.")
197
+ continue
198
+ fp.write(
199
+ orjson.dumps(
200
+ {"file": stats.name, **stats_data},
201
+ option=orjson.OPT_APPEND_NEWLINE,
202
+ )
203
+ )
204
+
205
+ @app.command()
206
+ def plot(file: pathlib.Path):
207
+ total_stats = {}
208
+ with open(file, "rb") as f:
209
+ for stats in tqdm.tqdm(f):
210
+ stats = orjson.loads(stats)
211
+ if "qscore" in stats:
212
+ for key, value in stats["qscore"].items():
213
+ vv_stats = total_stats.setdefault(key, [])
214
+ vv_stats.append(value)
215
+ total_stats[key] = vv_stats
216
+ for key, value in stats["submission"].items():
217
+ key = f"submissions_{key}"
218
+ vv_stats = total_stats.setdefault(key, [])
219
+ vv_stats.append(value)
220
+ total_stats[key] = vv_stats
221
+ for key, value in stats["submission"].items():
222
+ key = f"submissions_{key}"
223
+ vv_stats = total_stats.setdefault(key, [])
224
+ vv_stats.append(value)
225
+ total_stats[key] = vv_stats
226
+ for key, value in stats["comment"].items():
227
+ key = f"comments_{key}"
228
+ vv_stats = total_stats.setdefault(key, [])
229
+ vv_stats.append(value)
230
+ total_stats[key] = vv_stats
231
+
232
+ for key in total_stats.keys():
233
+ if key == "richness":
234
+ total_stats[key] = [i for i in total_stats[key] if i > 0 and i < 10]
235
+ elif key.startswith(("submission", "comment")):
236
+ total_stats[key] = [i for i in total_stats[key] if i > 0 and i < 100_000]
237
+ else:
238
+ total_stats[key] = [i for i in total_stats[key] if i > 0 and i < 100]
239
+ df = pandas.DataFrame.from_dict(
240
+ {k: v for k, v in total_stats.items() if k == key}
241
+ )
242
+ if key == "richness":
243
+ fg = seaborn.displot(df, x=key, bins=500, log_scale=(False, False))
244
+ elif key.startswith(("submission", "comment")):
245
+ fg = seaborn.displot(df, x=key, bins=50, log_scale=(False, False))
246
+ else:
247
+ fg = seaborn.displot(df, x=key, bins=500, log_scale=(False, False))
248
+ nuarr = numpy.array(total_stats[key])
249
+ percentiles = [
250
+ numpy.percentile(nuarr, 95),
251
+ numpy.percentile(nuarr, 90),
252
+ numpy.percentile(nuarr, 50),
253
+ numpy.percentile(nuarr, 10),
254
+ numpy.percentile(nuarr, 5),
255
+ ]
256
+ plt.axvline(x=percentiles[0], color="cyan")
257
+ plt.axvline(x=percentiles[1], color="blue")
258
+ print(percentiles, "pct for", key)
259
+ print("Save fig")
260
+
261
+ fg.savefig(f"test-{key}.png", dpi=120)
262
+
263
+
264
+ if __name__ == "__main__":
265
+ app()