secure-contain-protect / src /generate_report.py
ozefe's picture
Upload folder using huggingface_hub
d341341 verified
Raw
History Blame Contribute Delete
38 kB
#!/usr/bin/env python
# Matplotlib ships only partial type stubs, so strict checking is pure noise here.
# pyright: basic
"""Generate the SCP dataset's statistics showcase: charts (PNG) + tables + conclusions.
Reads the DuckDB database, writes chart images to `<images>/` and a single Markdown
report (`STATISTICS.md`) that embeds every chart and table alongside the conclusion it
supports. Re-running overwrites the outputs.
Usage (run from the src/ directory, like scp_dataset.py):
python generate_report.py
python generate_report.py --db ../data/scp_dataset.duckdb --images ../images \
--report ../STATISTICS.md
"""
from __future__ import annotations
import argparse
import itertools
import logging
from pathlib import Path
from typing import TYPE_CHECKING
import duckdb
import matplotlib as mpl
import numpy as np
mpl.use("Agg") # headless: render to files, never a window.
import matplotlib.pyplot as plt
if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.figure import Figure
DEFAULT_DB = "../data/scp_dataset.duckdb"
DEFAULT_IMAGES = "../images"
DEFAULT_REPORT = "../STATISTICS.md"
CAPTION = "SCP Wiki content pages · 2008–2026 · n = 19,438 · via Crom"
# Placeholder/institutional credit names to drop from author stats.
_PLACEHOLDERS = "('Anonymous', 'Unknown Author', 'Staff', 'Site News Team')"
# Shared TEMP views (registered in main()): `credits` is one row per attribution credit;
# `page_authors` applies the all-authors rule — AUTHOR credits where present, else the
# page's submitter/poster — so co-authors count and every page is attributed.
_VIEWS_SQL = f"""
CREATE TEMP VIEW credits AS
SELECT p.url, p.rating, p.title, p.created_at,
p.created_by_display_name AS poster,
a.type AS role, a.user_display_name AS name
FROM pages p,
unnest(from_json(p.attributions,
'[{{"type":"VARCHAR","user_display_name":"VARCHAR","date":"VARCHAR","order":"INTEGER"}}]'
)) AS t(a);
CREATE TEMP VIEW page_authors AS
WITH ac AS (
SELECT DISTINCT url, name AS author FROM credits
WHERE role = 'AUTHOR' AND name NOT IN {_PLACEHOLDERS}
)
SELECT url, author FROM ac
UNION
SELECT p.url, p.created_by_display_name FROM pages p
WHERE p.created_by_display_name IS NOT NULL
AND p.created_by_display_name NOT IN {_PLACEHOLDERS}
AND p.url NOT IN (SELECT url FROM ac);
"""
# Palette.
INK, SUBINK, MUTED, GRID = "#222222", "#555555", "#9a9a9a", "#ececec"
ACCENT, ACCENT2 = "#a01722", "#2f6f9f"
SERIES = [ACCENT, ACCENT2, "#c98a2b", "#4f8a5b", "#7a5195", "#5a5a5a", "#d45087"]
# Tags that describe structure/meta rather than content themes; excluded from "themes".
_NON_THEME = (
"scp",
"tale",
"hub",
"goi-format",
"essay",
"supplement",
"admin",
"guide",
"collaboration",
"contest",
"interview",
"poetry",
"artwork",
"co-authored",
"featured",
"rewrite",
"safe",
"euclid",
"keter",
"thaumiel",
"neutralized",
"explained",
"apollyon",
"archon",
"esoteric-class",
"pending",
"decommissioned",
)
logger = logging.getLogger("generate_report")
# --- Style + small helpers ------------------------------------------------------------
def setup_style() -> None:
"""Apply a clean, consistent matplotlib look."""
plt.rcParams.update(
{
"savefig.dpi": 150,
"figure.facecolor": "white",
"axes.facecolor": "white",
"axes.edgecolor": "#cccccc",
"axes.linewidth": 0.8,
"axes.titlesize": 14,
"axes.titleweight": "bold",
"axes.titlecolor": INK,
"axes.labelcolor": SUBINK,
"axes.grid": True,
"axes.axisbelow": True,
"grid.color": GRID,
"grid.linewidth": 0.9,
"xtick.color": SUBINK,
"ytick.color": SUBINK,
"text.color": INK,
"font.size": 11,
"legend.frameon": False,
}
)
def _style_axes(ax: Axes, title: str) -> None:
"""Despine, left-align the title, and add the dataset caption."""
for side in ("top", "right"):
ax.spines[side].set_visible(False)
ax.set_title(title, loc="left", pad=12)
ax.figure.text(0.005, 0.005, CAPTION, fontsize=7.5, color=MUTED, ha="left")
def _save(fig: Figure, images_dir: Path, name: str) -> str:
"""Write a figure and return its repo-relative path for Markdown embedding."""
fig.savefig(images_dir / f"{name}.png", bbox_inches="tight")
plt.close(fig)
return f"images/{name}.png"
def _section(title: str, body: str, takeaway: str) -> str:
"""Assemble one Markdown section: heading, body (image or table), conclusion."""
return f"## {title}\n\n{body}\n\n**Takeaway.** {takeaway}\n"
def _img(title: str, path: str, takeaway: str) -> str:
return _section(title, f"![{title}]({path})", takeaway)
def _md_table(headers: list[str], rows: list[list[str]]) -> str:
"""Render a Markdown table; cell pipes are escaped so titles can't break columns."""
def row(cells: list[str]) -> str:
return "| " + " | ".join(c.replace("|", r"\|") for c in cells) + " |"
rule = "| " + " | ".join("---" for _ in headers) + " |"
return "\n".join([row(headers), rule, *(row(r) for r in rows)])
# --- Charts ---------------------------------------------------------------------------
def chart_pages_per_year(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Stacked bar of pages created per year, split SCP / Tale / Other."""
rows = con.execute("""
WITH typed AS (
SELECT p.url, year(p.created_at) AS yr,
max(t.tag = 'scp')::int AS is_scp,
max(t.tag = 'tale')::int AS is_tale
FROM pages p LEFT JOIN page_tags t ON t.page_url = p.url
GROUP BY p.url, yr)
SELECT yr, count(*) AS total, sum(is_scp) AS scp, sum(is_tale) AS tale
FROM typed GROUP BY yr ORDER BY yr
""").fetchall()
years = [r[0] for r in rows]
scp = np.array([r[2] for r in rows])
tale = np.array([r[3] for r in rows])
other = np.array([r[1] for r in rows]) - scp - tale
fig, ax = plt.subplots(figsize=(10, 5.2))
ax.bar(years, scp, label="SCP", color=ACCENT)
ax.bar(years, tale, bottom=scp, label="Tale", color=ACCENT2)
ax.bar(years, other, bottom=scp + tale, label="Other", color="#c9b79c")
ax.set_ylabel("pages created")
ax.legend(loc="upper left")
ax.margins(x=0.01)
ax.set_xticks(range(min(years), max(years) + 1, 2))
_style_axes(ax, "Content created per year")
peak = years[int(np.argmax(scp + tale + other))]
total = int((scp + tale + other).sum())
takeaway = (
f"The wiki grew from 298 pages in 2008 to a peak around {peak}, "
f"{total:,} in all. SCPs are the backbone but tales now make up roughly a "
"third of yearly output; 2026 is a partial year."
)
return _img(
"Content created per year",
_save(fig, images, "pages_per_year"),
takeaway,
)
def chart_object_classes(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Bar of object-class counts."""
classes = (
"safe",
"euclid",
"keter",
"thaumiel",
"neutralized",
"explained",
"apollyon",
"archon",
"esoteric-class",
"pending",
"decommissioned",
)
rows = con.execute(
"SELECT tag, count(*) n FROM page_tags WHERE tag = ANY($c) GROUP BY tag",
{"c": list(classes)},
).fetchall()
counts = dict(rows)
labels = [c for c in classes if c in counts]
values = [counts[c] for c in labels]
order = np.argsort(values)
labels = [labels[i] for i in order]
values = [values[i] for i in order]
fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.barh(labels, values, color=ACCENT)
ax.bar_label(bars, padding=4, fmt="{:,.0f}", color=SUBINK, fontsize=9)
ax.set_xlabel("pages")
ax.margins(x=0.12)
_style_axes(ax, "Object classes")
takeaway = (
f"Euclid ('anomalous but containable') is the plurality at {counts['euclid']:,}, "
f"just ahead of Safe ({counts['safe']:,}); Keter is a distant third. The catch-all "
"'esoteric-class' has overtaken every named class except the big three."
)
return _img(
"Object classes",
_save(fig, images, "object_classes"),
takeaway,
)
def _theme_tags(con: duckdb.DuckDBPyConnection, limit: int) -> list[tuple[str, int]]:
"""Top content-theme tags (excluding meta, structural, and class tags)."""
return con.execute(
r"""
SELECT tag, count(*) n FROM page_tags
WHERE tag NOT LIKE '\_%' ESCAPE '\' AND tag NOT LIKE 'crom:%'
AND NOT (tag = ANY($x))
GROUP BY tag ORDER BY n DESC LIMIT $k
""",
{"x": list(_NON_THEME), "k": limit},
).fetchall()
def chart_top_themes(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Horizontal bar of the most common theme tags."""
rows = _theme_tags(con, 15)
labels = [r[0] for r in rows][::-1]
values = [r[1] for r in rows][::-1]
fig, ax = plt.subplots(figsize=(9, 6))
bars = ax.barh(labels, values, color=ACCENT2)
ax.bar_label(bars, padding=4, fmt="{:,.0f}", color=SUBINK, fontsize=9)
ax.set_xlabel("pages tagged")
ax.margins(x=0.12)
_style_axes(ax, "Most common themes")
takeaway = (
f"Entity descriptors dominate — '{rows[0][0]}', '{rows[1][0]}' and '{rows[2][0]}' "
"lead — followed by genre tags like horror and mind-affecting. Comedy ranks "
"surprisingly high, a reminder the wiki is not all grimdark."
)
return _img(
"Most common themes",
_save(fig, images, "top_themes"),
takeaway,
)
def chart_rating_distribution(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Histogram of ratings on a symlog x-axis (covers negatives and the long tail)."""
ratings = np.array(
[
r[0]
for r in con.execute(
"SELECT rating FROM pages WHERE rating IS NOT NULL"
).fetchall()
]
)
bins = np.concatenate(
[[-200, -50, -10, 0], np.logspace(np.log10(10), np.log10(11000), 45)]
)
fig, ax = plt.subplots(figsize=(10, 5))
ax.hist(ratings, bins=bins.tolist(), color=ACCENT, edgecolor="white", linewidth=0.3)
ax.set_xscale("symlog", linthresh=10)
ax.set_yscale("log")
ax.set_xlabel("rating (net votes, symlog)")
ax.set_ylabel("pages (log)")
median = float(np.median(ratings))
ax.axvline(median, color=INK, linestyle="--", linewidth=1)
ax.text(
median * 1.1,
ax.get_ylim()[1] * 0.5,
f"median {median:.0f}",
color=INK,
fontsize=9,
)
_style_axes(ax, "Rating distribution")
neg = int((ratings < 0).sum())
takeaway = (
f"Ratings are extremely right-skewed: a median of {median:.0f} against a maximum of "
f"{ratings.max():,.0f} (SCP-173). Only {neg} pages sit below zero — the community "
"deletes weak work, so what remains is heavily curated."
)
return _img(
"Rating distribution",
_save(fig, images, "rating_distribution"),
takeaway,
)
def chart_length_distribution(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Histogram of article (source) length on a log x-axis."""
lengths = np.array(
[
r[0]
for r in con.execute(
"SELECT length(source) FROM pages WHERE source IS NOT NULL AND length(source) > 0"
).fetchall()
]
)
bins = np.logspace(np.log10(lengths.min()), np.log10(lengths.max()), 50)
fig, ax = plt.subplots(figsize=(10, 5))
ax.hist(
lengths, bins=bins.tolist(), color="#4f8a5b", edgecolor="white", linewidth=0.3
)
ax.set_xscale("log")
ax.set_xlabel("source length (characters, log)")
ax.set_ylabel("pages")
median = float(np.median(lengths))
ax.axvline(median, color=INK, linestyle="--", linewidth=1)
ax.text(
median * 1.1,
ax.get_ylim()[1] * 0.9,
f"median {median:,.0f} chars",
color=INK,
fontsize=9,
)
_style_axes(ax, "Article length")
takeaway = (
f"Article length is roughly log-normal around a median of {median:,.0f} characters "
f"(a few pages of text), with a long tail of giant hubs and anthologies reaching "
f"{lengths.max():,.0f} characters."
)
return _img(
"Article length",
_save(fig, images, "length_distribution"),
takeaway,
)
def chart_author_pareto(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Lorenz curve of how unequally pages are distributed across authors."""
counts = np.array(
sorted(
r[0]
for r in con.execute(
"SELECT count(*) FROM page_authors GROUP BY author"
).fetchall()
)
)
cum = np.cumsum(counts) / counts.sum()
frac_authors = np.arange(1, len(counts) + 1) / len(counts)
desc = counts[::-1]
top2 = desc[: max(1, len(desc) // 50)].sum() / counts.sum()
solo = int((counts == 1).sum())
fig, ax = plt.subplots(figsize=(7.5, 6.5))
ax.plot(
[0, 1],
[0, 1],
color=MUTED,
linestyle="--",
linewidth=1,
label="perfect equality",
)
ax.plot(frac_authors, cum, color=ACCENT, linewidth=2.2, label="actual")
ax.fill_between(frac_authors, cum, frac_authors, color=ACCENT, alpha=0.08)
ax.set_xlabel("share of authors (least to most prolific)")
ax.set_ylabel("share of pages")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend(loc="upper left")
_style_axes(ax, "Authorship is a power law")
takeaway = (
"Counting every credited author (not just whoever posted the page), contribution is "
f"steeply unequal: the most prolific 2% hold {top2:.0%} of all author credits, while "
f"{solo:,} authors have a single credit. A small core sustains the wiki."
)
return _img(
"Authorship is a power law",
_save(fig, images, "author_pareto"),
takeaway,
)
def chart_rating_vs_length(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Scatter of rating vs article length, with the (flat) trend."""
rows = con.execute(
"SELECT length(source), rating FROM pages "
"WHERE rating > 0 AND source IS NOT NULL AND length(source) > 0"
).fetchall()
length = np.array([r[0] for r in rows])
rating = np.array([r[1] for r in rows])
r = float(np.corrcoef(length, rating)[0, 1])
fig, ax = plt.subplots(figsize=(9, 6))
ax.scatter(length, rating, s=6, alpha=0.18, color=ACCENT, edgecolors="none")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("source length (characters, log)")
ax.set_ylabel("rating (log, positive-rated pages)")
# Median rating per length-decile, to show the flat relationship clearly.
edges = np.logspace(np.log10(length.min()), np.log10(length.max()), 11)
centers, meds = [], []
for lo, hi in itertools.pairwise(edges):
sel = (length >= lo) & (length < hi)
if sel.any():
centers.append((lo * hi) ** 0.5)
meds.append(np.median(rating[sel]))
ax.plot(
centers,
meds,
color=INK,
linewidth=2,
marker="o",
markersize=4,
label="median by length",
)
ax.legend(loc="upper left")
_style_axes(ax, "Does length buy quality? No.")
takeaway = (
f"Rating and article length are essentially uncorrelated (r = {r:.02f}). The median "
"rating is flat across the whole length range — a longer article is not a "
"better-rated one. Concept and execution, not word count, drive a page's score."
)
return _img(
"Does length buy quality? No.",
_save(fig, images, "rating_vs_length"),
takeaway,
)
def chart_rating_by_year(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Line chart of mean and median rating per creation year."""
rows = con.execute("""
SELECT year(created_at) yr, round(avg(rating), 1), median(rating)
FROM pages WHERE rating IS NOT NULL GROUP BY yr ORDER BY yr
""").fetchall()
years = [r[0] for r in rows]
mean = [r[1] for r in rows]
med = [r[2] for r in rows]
fig, ax = plt.subplots(figsize=(10, 5.2))
ax.plot(
years,
mean,
color=ACCENT,
linewidth=2.2,
marker="o",
markersize=4,
label="mean",
)
ax.plot(
years,
med,
color=ACCENT2,
linewidth=2.2,
marker="s",
markersize=4,
label="median",
)
ax.set_ylabel("rating")
ax.legend(loc="upper right")
ax.margins(x=0.02)
ax.set_xticks(range(min(years), max(years) + 1, 2))
_style_axes(ax, "Ratings fall with each cohort")
takeaway = (
f"Average rating slides from {mean[0]:.0f} in 2008 to {mean[-1]:.0f} in 2026. This is "
"mostly an age effect — older pages have had years to accumulate up-votes — rather "
"than proof that newer writing is worse; the median falls far more gently than the mean."
)
return _img(
"Ratings fall with each cohort",
_save(fig, images, "rating_by_year"),
takeaway,
)
def chart_rating_by_class(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Bar of average rating by object class."""
rows = con.execute("""
SELECT t.tag, round(avg(p.rating), 1) ar, count(*) n
FROM page_tags t JOIN pages p ON p.url = t.page_url
WHERE t.tag IN ('safe','euclid','keter','thaumiel','neutralized','explained','apollyon','archon')
GROUP BY t.tag ORDER BY ar
""").fetchall()
labels = [r[0] for r in rows]
avg = [r[1] for r in rows]
colors = [ACCENT if a >= avg[len(avg) // 2] else ACCENT2 for a in avg]
fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.barh(labels, avg, color=colors)
ax.bar_label(bars, padding=4, fmt="{:.0f}", color=SUBINK, fontsize=9)
ax.set_xlabel("mean rating")
ax.margins(x=0.12)
_style_axes(ax, "Danger sells")
best = max(rows, key=lambda x: x[1])
takeaway = (
f"The more dangerous the classification, the higher the average score: Apollyon "
f"({best[1]:.0f}) and Keter top the table, while Safe and Neutralized trail. Readers "
"reward existential threat over the mundane."
)
return _img(
"Danger sells",
_save(fig, images, "rating_by_class"),
takeaway,
)
def chart_prolific_vs_acclaimed(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Bubble scatter of authors: output vs acclaim, sized by total rating."""
rows = con.execute("""
SELECT pa.author, count(*) n, avg(p.rating) ar, sum(p.rating) total
FROM page_authors pa JOIN pages p ON p.url = pa.url
WHERE p.rating IS NOT NULL
GROUP BY pa.author HAVING count(*) >= 10
""").fetchall()
n = np.array([r[1] for r in rows])
ar = np.array([r[2] for r in rows])
total = np.array([r[3] for r in rows])
fig, ax = plt.subplots(figsize=(10, 6.5))
ax.scatter(
n,
ar,
s=np.clip(total / 200, 8, 600),
alpha=0.45,
color=ACCENT,
edgecolors="white",
linewidth=0.4,
)
ax.set_xscale("log")
ax.set_xlabel("pages written (log)")
ax.set_ylabel("mean rating")
# Label a few notable authors: most prolific and most acclaimed.
notable = (
set(np.argsort(n)[-4:]) | set(np.argsort(ar)[-4:]) | set(np.argsort(total)[-4:])
)
for i in notable:
ax.annotate(
rows[i][0],
(float(n[i]), float(ar[i])),
fontsize=8.5,
color=INK,
xytext=(5, 4),
textcoords="offset points",
)
_style_axes(ax, "Prolific vs. acclaimed authors")
takeaway = (
"Counting every credited author (co-authors included), output and acclaim remain "
"different games: the most prolific cluster at modest average ratings, while the "
"highest-rated are comparatively selective — bubble size (total score) shows a few "
"writers manage both volume and quality."
)
return _img(
"Prolific vs. acclaimed authors",
_save(fig, images, "prolific_vs_acclaimed"),
takeaway,
)
def chart_coauthorship_over_time(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Line: share of pages with two or more credited authors, by year."""
rows = con.execute(f"""
WITH ac AS (
SELECT url, count(DISTINCT name) AS k FROM credits
WHERE role = 'AUTHOR' AND name NOT IN {_PLACEHOLDERS}
GROUP BY url
)
SELECT year(p.created_at) AS yr, count(*) AS total,
count(*) FILTER (WHERE coalesce(ac.k, 0) >= 2) AS co
FROM pages p LEFT JOIN ac ON ac.url = p.url
GROUP BY yr ORDER BY yr
""").fetchall()
years = [r[0] for r in rows]
pct = [100.0 * r[2] / r[1] for r in rows]
fig, ax = plt.subplots(figsize=(10, 5.2))
ax.plot(years, pct, color=ACCENT, linewidth=2.4, marker="o", markersize=4)
ax.fill_between(years, pct, color=ACCENT, alpha=0.08)
ax.set_ylabel("% of pages with ≥2 credited authors")
ax.set_ylim(0, max(pct) * 1.15)
ax.set_xticks(range(min(years), max(years) + 1, 2))
_style_axes(ax, "Co-authorship over time")
peak = max(pct)
takeaway = (
f"Co-authorship has climbed from near zero to about {peak:.0f}% of pages in recent years "
"— modern SCP is increasingly a team effort (2026 is a partial year). Early collaboration "
"is undercounted: the attribution metadata recording co-authors is a later convention."
)
return _img(
"Co-authorship over time",
_save(fig, images, "coauthorship_over_time"),
takeaway,
)
def chart_rating_by_team(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Bar: median rating by number of credited authors."""
rows = con.execute("""
WITH per_page AS (
SELECT pa.url, any_value(p.rating) AS rating, count(*) AS n
FROM page_authors pa JOIN pages p ON p.url = pa.url
WHERE p.rating IS NOT NULL GROUP BY pa.url
),
bucketed AS (SELECT rating, least(n, 4) AS team FROM per_page)
SELECT team, count(*) AS pages, median(rating) AS med
FROM bucketed GROUP BY team ORDER BY team
""").fetchall()
names = {1: "1 (solo)", 2: "2", 3: "3", 4: "4+"}
labels = [names[r[0]] for r in rows]
med = [r[2] for r in rows]
counts = [r[1] for r in rows]
fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.bar(labels, med, color=ACCENT, width=0.62)
ax.bar_label(bars, fmt="{:.0f}", padding=3, color=SUBINK, fontsize=10)
for i, c in enumerate(counts):
ax.text(i, max(med) * 0.04, f"n={c:,}", ha="center", color="white", fontsize=8)
ax.set_ylabel("median rating")
ax.set_xlabel("number of credited authors")
_style_axes(ax, "Bigger teams, higher ratings")
takeaway = (
f"Median rating rises with team size — from {med[0]:.0f} for solo pages to {med[-1]:.0f} "
"for the largest teams. Collaboration correlates with a warmer reception, though the "
"most ambitious projects also tend to attract co-authors."
)
return _img(
"Bigger teams, higher ratings",
_save(fig, images, "rating_by_team"),
takeaway,
)
def chart_collaboration_network(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Circular network of co-authorship among the most-connected authors."""
edges = con.execute("""
WITH a AS (SELECT url, author FROM page_authors)
SELECT x.author, y.author, count(*) AS w
FROM a x JOIN a y ON x.url = y.url AND x.author < y.author
GROUP BY x.author, y.author
""").fetchall()
pages = dict(
con.execute(
"SELECT author, count(*) FROM page_authors GROUP BY author"
).fetchall()
)
# Rank authors by *recurring* collaboration (≥2 shared pages) so the named hub matches the
# drawn edges; one-off links from mass-collaboration pages would otherwise dominate.
recurring = [(a, b, w) for a, b, w in edges if w >= 2]
degree: dict[str, int] = {}
for a1, a2, w in recurring:
degree[a1] = degree.get(a1, 0) + w
degree[a2] = degree.get(a2, 0) + w
top = [
a for a, _ in sorted(degree.items(), key=lambda kv: kv[1], reverse=True)[:26]
]
rank = set(top)
sub = [(a, b, w) for a, b, w in recurring if a in rank and b in rank]
angles = np.linspace(0, 2 * np.pi, len(top), endpoint=False)
xy = {
a: (float(np.cos(t)), float(np.sin(t)))
for a, t in zip(top, angles, strict=True)
}
maxw = max(e[2] for e in sub)
fig, ax = plt.subplots(figsize=(9.5, 9.5))
for a, b, w in sub:
(x1, y1), (x2, y2) = xy[a], xy[b]
ax.plot(
[x1, x2],
[y1, y2],
color=ACCENT,
solid_capstyle="round",
zorder=1,
alpha=min(0.75, 0.10 + 0.65 * w / maxw),
linewidth=0.4 + 3.0 * w / maxw,
)
sizes = [float(np.clip(pages.get(a, 1) * 2.0, 30, 600)) for a in top]
ax.scatter(
[xy[a][0] for a in top],
[xy[a][1] for a in top],
s=sizes,
color=INK,
edgecolors="white",
linewidth=0.6,
zorder=2,
)
for a, t in zip(top, angles, strict=True):
deg = float(np.degrees(t))
flip = 90 < deg < 270
ax.text(
1.06 * np.cos(t),
1.06 * np.sin(t),
a,
fontsize=7.5,
color=INK,
ha="right" if flip else "left",
va="center",
rotation=deg + 180 if flip else deg,
rotation_mode="anchor",
)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("How authors collaborate", loc="left", pad=12)
ax.figure.text(0.005, 0.005, CAPTION, fontsize=7.5, color=MUTED, ha="left")
takeaway = (
f"Co-authorship forms tight clusters around a few hubs — {top[0]} is the most connected. "
"Node size is total pages, edge weight is shared pages; the modern wiki is a densely "
"woven collaborative network, not a crowd of soloists."
)
return _img(
"How authors collaborate",
_save(fig, images, "collaboration_network"),
takeaway,
)
def chart_tag_cooccurrence(con: duckdb.DuckDBPyConnection, images: Path) -> str:
"""Heatmap of Jaccard association between the top theme tags."""
tags = [t for t, _ in _theme_tags(con, 14)]
pairs = con.execute(
"""
SELECT a.tag, b.tag, count(*) FROM page_tags a JOIN page_tags b ON a.page_url = b.page_url
WHERE a.tag = ANY($t) AND b.tag = ANY($t) GROUP BY a.tag, b.tag
""",
{"t": tags},
).fetchall()
idx = {t: i for i, t in enumerate(tags)}
inter = np.zeros((len(tags), len(tags)))
for a, b, c in pairs:
inter[idx[a], idx[b]] = c
freq = np.diag(inter).copy()
jac = inter / (freq[:, None] + freq[None, :] - inter)
np.fill_diagonal(jac, np.nan)
fig, ax = plt.subplots(figsize=(8.5, 7.5))
im = ax.imshow(jac, cmap="rocket_r" if "rocket_r" in plt.colormaps() else "magma_r")
ax.set_xticks(range(len(tags)), tags, rotation=45, ha="right", fontsize=9)
ax.set_yticks(range(len(tags)), tags, fontsize=9)
ax.grid(visible=False)
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="Jaccard similarity")
ax.set_title("How themes cluster", loc="left", pad=12)
ax.figure.text(0.005, 0.005, CAPTION, fontsize=7.5, color=MUTED, ha="left")
iu = np.triu_indices(len(tags), k=1)
bi, bj = iu[0][np.nanargmax(jac[iu])], iu[1][np.nanargmax(jac[iu])]
takeaway = (
f"Themes form clear clusters. The strongest pairing is '{tags[bi]}' + '{tags[bj]}': "
"entity descriptors (humanoid / sapient / alive) co-occur tightly, forming a "
"'monster' cluster distinct from the genre tags."
)
return _img(
"How themes cluster",
_save(fig, images, "tag_cooccurrence"),
takeaway,
)
# --- Tables ---------------------------------------------------------------------------
def table_per_year(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table: one row per year with headline figures."""
rows = con.execute("""
WITH t AS (
SELECT p.url, year(p.created_at) yr, p.rating, p.title,
max(tg.tag = 'scp')::int s, max(tg.tag = 'tale')::int tl
FROM pages p LEFT JOIN page_tags tg ON tg.page_url = p.url
GROUP BY p.url, yr, p.rating, p.title)
SELECT yr, count(*), sum(s), sum(tl), round(avg(rating)),
arg_max(title, rating) AS top
FROM t GROUP BY yr ORDER BY yr
""").fetchall()
auth = dict(
con.execute(
"SELECT year(created_at), count(DISTINCT created_by_wikidot_id) FROM pages GROUP BY 1"
).fetchall()
)
table = _md_table(
["Year", "Pages", "SCPs", "Tales", "Authors", "Avg rating", "Top-rated page"],
[
[
str(r[0]),
f"{r[1]:,}",
f"{r[2]:,}",
f"{r[3]:,}",
f"{auth[r[0]]:,}",
f"{r[4]:.0f}",
r[5],
]
for r in rows
],
)
takeaway = (
"Output and contributor counts climb together — more authors, more pages — while "
"average rating declines with each younger cohort (an age effect, not a quality one)."
)
return _section("Per-year summary", table, takeaway)
def table_top_pages(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table of the 15 highest-rated pages."""
rows = con.execute("""
SELECT title, rating, vote_count, comment_count, created_by_display_name, year(created_at)
FROM pages ORDER BY rating DESC LIMIT 15
""").fetchall()
table = _md_table(
["#", "Title", "Rating", "Votes", "Comments", "Author", "Year"],
[
[
str(i),
r[0],
f"{r[1]:,.0f}",
f"{r[2]:,}",
f"{r[3]:,}",
r[4] or "—",
str(r[5]),
]
for i, r in enumerate(rows, 1)
],
)
takeaway = (
"The canon is front-loaded with early classics — SCP-173, SCP-049, SCP-682 — that "
"have compounded votes for over a decade, alongside a few modern breakouts like SCP-5000."
)
return _section("Top 15 highest-rated pages", table, takeaway)
def table_top_authors(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table of the 15 most-credited authors (all-authors rule)."""
rows = con.execute("""
WITH team AS (SELECT url, count(*) AS n FROM page_authors GROUP BY url)
SELECT pa.author, count(*) AS pages, round(avg(p.rating)) AS ar,
round(sum(p.rating)) AS tot,
round(100.0 * count(*) FILTER (WHERE team.n >= 2) / count(*)) AS collab,
arg_max(p.title, p.rating) AS best
FROM page_authors pa
JOIN pages p ON p.url = pa.url
JOIN team ON team.url = pa.url
WHERE p.rating IS NOT NULL
GROUP BY pa.author ORDER BY pages DESC LIMIT 15
""").fetchall()
table = _md_table(
[
"#",
"Author",
"Pages",
"Avg rating",
"Total rating",
"Co-authored",
"Best-rated work",
],
[
[
str(i),
r[0],
f"{r[1]:,}",
f"{r[2]:.0f}",
f"{r[3]:,.0f}",
f"{r[4]:.0f}%",
r[5],
]
for i, r in enumerate(rows, 1)
],
)
takeaway = (
"The most prolific authors are not the highest-scoring on average — volume and acclaim "
"rarely coincide — but their cumulative totals show how much of the wiki rests on a few "
"dozen people. The co-authored share shows how collaboratively each writer works."
)
return _section("Top 15 authors (all credited authors)", table, takeaway)
def table_coauthor_duos(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table of the most frequent co-author pairs."""
rows = con.execute("""
WITH a AS (SELECT url, author FROM page_authors)
SELECT x.author, y.author, count(*) AS n, round(avg(p.rating)) AS ar
FROM a x JOIN a y ON x.url = y.url AND x.author < y.author
JOIN pages p ON p.url = x.url
WHERE p.rating IS NOT NULL
GROUP BY x.author, y.author ORDER BY n DESC LIMIT 12
""").fetchall()
table = _md_table(
["#", "Author A", "Author B", "Shared pages", "Avg rating"],
[
[str(i), r[0], r[1], f"{r[2]:,}", f"{r[3]:.0f}"]
for i, r in enumerate(rows, 1)
],
)
takeaway = (
"The wiki's tightest writing partnerships — recurring duos that have co-authored many "
"pages together, several rating well above the site median."
)
return _section("Top co-author duos", table, takeaway)
def table_most_collaborative(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table of authors with the most distinct co-authors."""
rows = con.execute("""
WITH a AS (SELECT url, author FROM page_authors)
SELECT x.author, count(DISTINCT y.author) AS partners, count(DISTINCT x.url) AS pages
FROM a x JOIN a y ON x.url = y.url AND x.author <> y.author
GROUP BY x.author ORDER BY partners DESC LIMIT 15
""").fetchall()
table = _md_table(
["#", "Author", "Distinct co-authors", "Co-authored pages"],
[[str(i), r[0], f"{r[1]:,}", f"{r[2]:,}"] for i, r in enumerate(rows, 1)],
)
takeaway = (
"The community's connectors — authors who have written with the widest circle of "
"collaborators, knitting otherwise separate clusters together."
)
return _section("Most collaborative authors", table, takeaway)
def table_top_rewriters(con: duckdb.DuckDBPyConnection) -> str:
"""Markdown table of authors credited with the most rewrites."""
rows = con.execute(f"""
SELECT name, count(*) AS n, round(avg(rating)) AS ar
FROM credits WHERE role = 'REWRITE' AND name NOT IN {_PLACEHOLDERS}
GROUP BY name ORDER BY n DESC LIMIT 12
""").fetchall()
table = _md_table(
["#", "Rewriter", "Pages rewritten", "Avg rating"],
[[str(i), r[0], f"{r[1]:,}", f"{r[2]:.0f}"] for i, r in enumerate(rows, 1)],
)
takeaway = (
"The canon's caretakers: a small group does most of the rewriting that keeps the early, "
"heavily-trafficked articles current."
)
return _section("Top rewriters", table, takeaway)
# --- Orchestration --------------------------------------------------------------------
_CHARTS = (
chart_pages_per_year,
chart_object_classes,
chart_top_themes,
chart_rating_distribution,
chart_length_distribution,
chart_author_pareto,
chart_rating_vs_length,
chart_rating_by_year,
chart_rating_by_class,
chart_prolific_vs_acclaimed,
chart_coauthorship_over_time,
chart_rating_by_team,
chart_tag_cooccurrence,
chart_collaboration_network,
)
_TABLES = (
table_per_year,
table_top_pages,
table_top_authors,
table_coauthor_duos,
table_most_collaborative,
table_top_rewriters,
)
def main(argv: list[str] | None = None) -> int:
"""Generate every chart and table and write the Markdown report."""
parser = argparse.ArgumentParser(
description="Generate the SCP dataset statistics showcase.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--db", default=DEFAULT_DB, help="DuckDB database path")
parser.add_argument(
"--images",
default=DEFAULT_IMAGES,
help="Image output directory",
)
parser.add_argument("--report", default=DEFAULT_REPORT, help="Markdown report path")
args = parser.parse_args(argv)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(message)s",
datefmt="%H:%M:%S",
)
images = Path(args.images)
images.mkdir(parents=True, exist_ok=True)
setup_style()
con = duckdb.connect(args.db, read_only=True)
con.execute(_VIEWS_SQL) # register the `credits` and `page_authors` views
sections: list[str] = []
try:
for fn in _CHARTS:
logger.info("chart %s", fn.__name__)
sections.append(fn(con, images))
for tfn in _TABLES:
logger.info("table %s", tfn.__name__)
sections.append(tfn(con))
finally:
con.close()
report = Path(args.report)
header = (
"# The SCP Foundation Wiki in Numbers\n\n"
f"_{CAPTION}._\n\n"
"A statistical tour of every content page (SCPs, tales, hubs, GOI formats and more) "
"on the English SCP Wiki, built from the Crom API. Each figure below is followed by "
"the conclusion it supports.\n"
)
report.write_text(header + "\n" + "\n".join(sections), encoding="utf-8")
logger.info("Wrote %s and %d images to %s/", report, len(_CHARTS), images)
return 0
if __name__ == "__main__":
raise SystemExit(main())