|
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"]) |
|
|
|
|
|
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): |
|
|
|
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": |
|
|
|
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"] < 1.05: |
|
|
|
continue |
|
elif qscores["engagement"] > 50: |
|
|
|
continue |
|
elif qscores["compound"] < 0.05: |
|
|
|
continue |
|
elif qscores["richness"] < 0.01 or qscores["richness"] > 0.95: |
|
|
|
|
|
|
|
continue |
|
elif qscores["diversity"] < 0.05 or qscores["diversity"] > 5: |
|
|
|
|
|
continue |
|
reddits.append(stats_data) |
|
elif mode == "media": |
|
|
|
|
|
|
|
|
|
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: |
|
|
|
continue |
|
elif qscores["engagement"] > 50: |
|
|
|
continue |
|
elif qscores["compound"] < 0.05: |
|
|
|
continue |
|
elif image_bias_richness < 0.15 or image_bias_richness > 0.95: |
|
|
|
|
|
|
|
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() |
|
|