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