#!/usr/bin/env python3
"""
Generate synchronized Markdown (.md), ReportLab PDF (.pdf), and TierMaker-style S+ to F PNG (.png)
tier lists from all bidirectional AQ evaluations in an archive directory.
"""
import argparse
import glob
import os
import re
from xml.sax.saxutils import escape
def aq(s: str) -> int:
return sum(
(ord(c) - 48 if "0" <= c <= "9" else ord(c) - 87 if "a" <= c <= "z" else 0)
for c in s.lower()
)
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def collect_evaluations(archive_dir: str):
if not os.path.exists(archive_dir) and os.path.exists("/workspace/ingglish-aq-archive"):
archive_dir = "/workspace/ingglish-aq-archive"
eval_paths = sorted(glob.glob(os.path.join(archive_dir, "[34]*-eval-*-bidirectional.md")))
rows = []
for p in eval_paths:
with open(p, "r", encoding="utf-8") as f:
text = f.read()
eval_file = os.path.basename(p)
eval_num = re.match(r"^(\d+)-", eval_file).group(1)
title_m = re.search(r"^#\s+Bidirectional AQ Evaluation[^:]*:\s*(.+)$", text, re.M)
dossier_m = re.search(r"\*\*Source Dossier:\*\*\s*`([^`]+)`", text)
score_m = re.search(
r"\*\*Composite Fitness Score \(Option 4 Curve\):\*\*\s*\*\*(\d+)\s*/\s*100\s*—\s*(Class [SAB])[^*]*\*\*\s*\*\(Uncurved Raw Score:\s*(\d+)\s*/\s*100\)\*",
text,
)
dims = [
int(x)
for x in re.findall(r"\|\s*\*\*[1-5]\.[^*]+\*\*\s*\|\s*\*\*(\d+)\s*/\s*20\*\*", text)
]
dossier_file = os.path.basename(dossier_m.group(1)) if dossier_m else ""
dossier_num = re.match(r"^(\d+)-", dossier_file).group(1) if dossier_file else ""
dp = os.path.join(archive_dir, dossier_file)
with open(dp, "r", encoding="utf-8") as df:
dt = df.read()
eqs = re.findall(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`', dt)
iso_w = tot_w = p_ing = pad_cnt = iso_cl = 0
deltas = []
for ing, eng, _, _ in eqs:
if "seekrat" in ing or "hidan" in ing:
pad_cnt += 1
ec = re.sub(r"[^\w\s-]", "", eng)
ic = re.sub(r"[^\w\s-]", "", ing)
d = aq(ic) - aq(ec)
deltas.append(d)
if d == 0:
iso_cl += 1
ew, iw = ec.split(), ic.split()
if len(ew) == len(iw):
for w1, w2 in zip(ew, iw):
tot_w += 1
if aq(w1) == aq(w2):
iso_w += 1
if is_prime(aq(w2)):
p_ing += 1
ledger_rows = re.findall(
r"^\|\s*\*\*([^*]+)\*\*\s*\|\s*`[^`]+`\s*\|\s*[^|]+\|\s*([^|]+)\|\s*`[^`]+`\s*\|\s*([^|]+)\|",
text,
re.M,
)
lock1 = f"{ledger_rows[0][0].strip()}: {ledger_rows[0][1].strip()}" if len(ledger_rows) > 0 else ""
lock2 = f"{ledger_rows[1][0].strip()}: {ledger_rows[1][1].strip()}" if len(ledger_rows) > 1 else ""
lock1 = re.sub(r"`", "", lock1)[:42]
lock2 = re.sub(r"`", "", lock2)[:42]
short_title = title_m.group(1).strip() if title_m else eval_file
for pref in [
"John Carpenter's ", "Paul W. S. Anderson's ", "Alex Garland's ",
"David Cronenberg's ", "Jonathan Glazer's ", "Richard Stanley's ",
"Clive Barker's ", "Kostanski & Gillespie's ", "Andrzej Zulawski's ",
]:
if short_title.startswith(pref):
short_title = short_title[len(pref):]
if len(short_title) > 30:
short_title = re.sub(r"\s*\([^)]*\)$", "", short_title)
if len(short_title) > 30:
short_title = short_title[:28].rstrip() + ".."
rows.append(
{
"eval_file": eval_file,
"eval_num": eval_num,
"dossier_file": dossier_file,
"dossier_num": dossier_num,
"title": short_title,
"curve_score": int(score_m.group(1)),
"raw_score": int(score_m.group(3)),
"dims": dims,
"n_eq": len(eqs),
"iso_w_pct": 100.0 * iso_w / max(1, tot_w),
"prime_ing_pct": 100.0 * p_ing / max(1, tot_w),
"mean_delta": sum(abs(x) for x in deltas) / max(1, len(deltas)),
"pad_pct": 100.0 * pad_cnt / max(1, len(eqs)),
"iso_cl": iso_cl,
"lock1": lock1,
"lock2": lock2,
}
)
rows.sort(key=lambda x: (-x["curve_score"], -x["iso_cl"], x["mean_delta"], -x["iso_w_pct"]))
for idx, r in enumerate(rows, 1):
r["rank"] = f"#{idx}"
sc = r["curve_score"]
if sc >= 95:
r["tier_Band"] = "S+"
elif sc >= 90:
r["tier_Band"] = "S"
elif sc >= 81:
r["tier_Band"] = "A"
elif sc >= 72:
r["tier_Band"] = "B"
elif sc >= 66:
r["tier_Band"] = "C"
elif sc >= 60:
r["tier_Band"] = "D"
else:
r["tier_Band"] = "F"
return rows
def render_md_and_pdf(rows, out_md: str, out_pdf: str):
tot_eqs = sum(r["n_eq"] for r in rows)
lines = [
f"# Master Bidirectional AQ Evaluation Tier List (All {len(rows)} Dossiers)",
"",
"- **Active Grading Standard:** Option #4 — Hybrid Numogrammatic Curve (`Class S >= 90`, `Class A >= 81 [3⁴]`, `Class B >= 72`, `C/D/F < 72`)",
f"- **Total Corpus Audited:** {len(rows)} Dossiers, {len(rows)} Bidirectional Evaluations, **{tot_eqs} verified cross-scale equations** (`333`, `666`, `777`)",
"- **Tie-Breaking Protocol:** Within identical composite scores, entries are ordered by (1) Full-Clause Repdigit Isometry count (`Δ = 0` at `333/666/777`), then (2) lowest Mean Clause Drift (`Mean |Δ|`), then (3) highest Isometric Word %.",
"",
"---",
"",
"## 1. Master Quantitative Leaderboard (S+ to F)",
"",
"| Rank | Tier | Option #4 Score (Raw) | D1 / D2 / D3 / D4 / D5 | Evaluation Record | Source Dossier | N_eq | Iso Word % | Prime Word % (Ing) | Mean Abs(Δ) | Padding % (`seekrat`/`hidan`) |",
"| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |",
]
for r in rows:
d_str = " / ".join(str(x) for x in r["dims"])
lines.append(
f"| **{r['rank']}** | **Class {r['tier_Band']}** | **{r['curve_score']} / 100** *({r['raw_score']})* | `{d_str}` | `{r['eval_file']}` | `{r['dossier_file']}` | {r['n_eq']} | {r['iso_w_pct']:.1f}% | {r['prime_ing_pct']:.1f}% | {r['mean_delta']:.1f} | {r['pad_pct']:.1f}% |"
)
lines.extend(
[
"",
"---",
"",
"## 2. Unpopulated Lower Tiers (`C / D / F` Diagnostic Thresholds)",
"",
"- **Tier C (`66 – 71 pts`, Mint Green `#7FFF7F` — High-Padding Band):** `0 Dossiers`. Reserved for dossiers with `>60%` generic `seekrat/hidan` padding and zero compensating `Δ = 0` full-clause or consecutive-prime rarity locks.",
"- **Tier D (`60 – 65 pts`, Sky Blue `#7FBFFF` — Marginal Band):** `0 Dossiers`. Reserved for dossiers with `0` independent domain-native equivalence classes, `<10%` prime word density, and `Mean |Δ| > 50`.",
f"- **Tier F (`< 60 pts`, Violet `#BF7FFF` — Discard Band):** `0 Dossiers`. Rejected by Post-Write Arithmetic Audit (`{tot_eqs} / {tot_eqs}` archive equations verified exact with `0` sum mismatches).",
]
)
if out_md:
with open(out_md, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
if out_pdf and out_md and os.path.exists(out_md):
try:
from reportlab.lib.pagesizes import letter
except ImportError:
import subprocess, sys
subprocess.run(
[sys.executable, "-m", "pip", "install", "--root-user-action=ignore", "--cache-dir", "/tmp/.pip", "reportlab", "pypdf", "pdfplumber"],
check=True,
stdout=subprocess.DEVNULL,
)
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, HRFlowable
def fmt_inline(text):
text = escape(text)
text = text.replace("Δ", 'D')
text = text.replace("μ", 'm')
text = text.replace("σ", 's')
text = text.replace("π", 'p')
text = (
text.replace("⁴", "4")
.replace("⁵", "5")
.replace("⁶", "6")
.replace("⁷", "7")
)
code_spans = []
def _save_code(m):
idx = len(code_spans)
code_spans.append(f'{m.group(1)}')
return f"\x00CODE{idx}\x00"
text = re.sub(r"`([^`]+)`", _save_code, text)
text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)
text = re.sub(r"\*([^*]+)\*", r"\1", text)
for idx, span in enumerate(code_spans):
text = text.replace(f"\x00CODE{idx}\x00", span)
return text
def add_page_number(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 9)
canvas.setFillColor(colors.HexColor("#555555"))
canvas.drawRightString(letter[0] - 54, 36, f"Page {doc.page}")
canvas.restoreState()
with open(out_md, "r", encoding="utf-8") as f:
md_lines = f.read().splitlines()
doc = SimpleDocTemplate(out_pdf, pagesize=letter, leftMargin=54, rightMargin=54, topMargin=54, bottomMargin=54)
styles = getSampleStyleSheet()
h1 = ParagraphStyle("H1", parent=styles["Heading1"], fontName="Helvetica-Bold", fontSize=15, leading=19, spaceAfter=8)
h2 = ParagraphStyle("H2", parent=styles["Heading2"], fontName="Helvetica-Bold", fontSize=12.5, leading=16, spaceBefore=10, spaceAfter=6)
h3 = ParagraphStyle("H3", parent=styles["Heading3"], fontName="Helvetica-Bold", fontSize=10.5, leading=14, spaceBefore=8, spaceAfter=4)
body = ParagraphStyle("Body", parent=styles["Normal"], fontName="Helvetica", fontSize=9.5, leading=13.5, spaceAfter=5)
bullet = ParagraphStyle("Bullet", parent=body, leftIndent=14, firstLineIndent=-8, spaceAfter=4)
story, headers, in_table, in_code = [], [], False, False
for line in md_lines:
s = line.strip()
if s.startswith("```"):
in_code = not in_code
continue
if in_code or not s:
if not s:
in_table, headers = False, []
continue
if s == "---":
story.extend([Spacer(1, 4), HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#cccccc")), Spacer(1, 4)])
continue
if s.startswith("|") and s.endswith("|"):
cells = [c.strip() for c in re.split(r'(?60% generic 'seekrat/hidan' padding and zero Full-Clause (Δ=0) or Consecutive-Prime Rarity Bonuses.",
),
(
"D",
"60 – 65 pts",
"MARGINAL",
"#7FBFFF",
"0 Dossiers in Tier D (60 – 65 pts — Marginal / Unanchored Scaffolding Band)",
"Threshold for dossiers with 0 independent domain-native equivalence locks, <10% prime word density, and Mean |Δ| > 50.",
),
(
"F",
"< 60 pts",
"DISCARD",
"#BF7FFF",
"0 Dossiers in Tier F (< 60 pts — Non-Deterministic / Arithmetic Failure / Discard)",
"Rejected by Post-Write Arithmetic Audit (100% of archive equations verified exact with 0 sum mismatches).",
),
]
tier_defs = [tuple(t) for t in custom_tier_defs] if custom_tier_defs else default_tier_defs
W = 1960
MARGIN_X = 28
HEADER_H = 118
FOOTER_H = 64
LABEL_W = 210
ROW_GAP = 8
CARD_W = 546
CARD_H = 156
CARD_GAP_X = 14
CARD_GAP_Y = 14
ROW_PAD_Y = 14
ROW_PAD_X = 16
grouped = {t[0]: [] for t in tier_defs}
for r in rows:
grouped[r["tier_Band"]].append(r)
tier_heights = []
for t in tier_defs:
cards = grouped[t[0]]
if not cards:
tier_heights.append(104)
else:
rc = (len(cards) + 2) // 3
tier_heights.append(ROW_PAD_Y * 2 + rc * CARD_H + (rc - 1) * CARD_GAP_Y)
H = HEADER_H + sum(tier_heights) + ROW_GAP * (len(tier_defs) - 1) + FOOTER_H
img = Image.new("RGB", (W, H), "#121316")
draw = ImageDraw.Draw(img)
tot_eqs = sum(r["n_eq"] for r in rows)
draw.rectangle([0, 0, W, HEADER_H - 8], fill="#18191D")
draw.line([(0, HEADER_H - 8), (W, HEADER_H - 8)], fill="#333640", width=2)
draw.text(
(MARGIN_X, 22),
header_title,
fill="#F5F6F8",
font=f_title,
)
sub_str = (
header_subtitle
if header_subtitle
else f"All {len(rows)} Dossiers ({tot_eqs} Verified Equations) | Graded on Option #4: Hybrid Numogrammatic Curve (Class S >= 90, Class A >= 81 [3⁴], Class B >= 72, C/D/F < 72)"
)
draw.text(
(MARGIN_X, 68),
sub_str,
fill="#A5AAB5",
font=f_subtitle,
)
def draw_centered(box, text, font, fill):
x0, y0, x1, y1 = box
bbox = draw.textbbox((0, 0), text, font=font)
tw, th_b = bbox[2] - bbox[0], bbox[3] - bbox[1]
tx = x0 + (x1 - x0 - tw) / 2 - bbox[0]
ty = y0 + (y1 - y0 - th_b) / 2 - bbox[1]
draw.text((tx, ty), text, fill=fill, font=font)
cur_y = HEADER_H
for (label, rng, desc, bg, empty_t, empty_d), th in zip(tier_defs, tier_heights):
x0, x1 = MARGIN_X, W - MARGIN_X
y0, y1 = cur_y, cur_y + th
draw.rectangle([x0, y0, x1, y1], fill="#1E2026", outline="#090A0C", width=3)
lx0, ly0, lx1, ly1 = x0 + 3, y0 + 3, x0 + LABEL_W, y1 - 3
draw.rectangle([lx0, ly0, lx1, ly1], fill=bg)
draw.line([(lx1, ly0), (lx1, ly1)], fill="#090A0C", width=4)
mid_y = (ly0 + ly1) / 2
draw_centered((lx0, mid_y - 42, lx1, mid_y + 2), label, f_tier_big, "#111111")
draw_centered((lx0, mid_y + 10, lx1, mid_y + 26), rng, f_tier_sub, "#1A1A1A")
draw_centered((lx0, mid_y + 27, lx1, mid_y + 43), desc, f_tier_sub, "#2A2A2A")
rx0, ry0 = lx1 + ROW_PAD_X, y0 + ROW_PAD_Y
cards = grouped[label]
if not cards:
ex0, ey0, ex1, ey1 = rx0, y0 + 16, x1 - ROW_PAD_X, y1 - 16
draw.rounded_rectangle([ex0, ey0, ex1, ey1], radius=8, fill="#16181D", outline="#2C303A", width=2)
draw.rounded_rectangle([ex0, ey0, ex0 + 8, ey1], radius=4, fill=bg)
draw.text((ex0 + 24, ey0 + 14), empty_t, fill="#C8CDD8", font=f_empty_bold)
draw.text((ex0 + 24, ey0 + 42), empty_d, fill="#7F8594", font=f_empty)
else:
for idx, c in enumerate(cards):
col, row = idx % 3, idx // 3
cx0 = rx0 + col * (CARD_W + CARD_GAP_X)
cy0 = ry0 + row * (CARD_H + CARD_GAP_Y)
cx1, cy1 = cx0 + CARD_W, cy0 + CARD_H
draw.rounded_rectangle([cx0, cy0, cx1, cy1], radius=8, fill="#262932", outline="#383C4A", width=2)
draw.rounded_rectangle([cx0, cy0, cx1, cy0 + 6], radius=4, fill=bg)
draw.rounded_rectangle([cx0 + 12, cy0 + 14, cx0 + 60, cy0 + 40], radius=5, fill="#15171C", outline=bg, width=1)
draw_centered((cx0 + 12, cy0 + 14, cx0 + 60, cy0 + 40), c["rank"], f_card_rank, bg)
score_txt = c.get("score_badge_text") or f"{c['curve_score']}/100 (Raw {c['raw_score']})"
sb_w = 158
draw.rounded_rectangle([cx1 - sb_w - 12, cy0 + 14, cx1 - 12, cy0 + 40], radius=5, fill="#15171C", outline="#454A59", width=1)
draw_centered((cx1 - sb_w - 12, cy0 + 14, cx1 - 12, cy0 + 40), score_txt, f_card_rank, "#F0F2F5")
codes = c.get("badge_code") or f"Eval {c['eval_num']} • Dossier {c['dossier_num']}"
draw.text((cx0 + 70, cy0 + 19), codes[:22], fill="#9DA3B4", font=f_card_dossier)
draw.text((cx0 + 14, cy0 + 47), c["title"], fill="#FFFFFF", font=f_card_title)
draw.line([(cx0 + 14, cy0 + 74), (cx1 - 14, cy0 + 74)], fill="#363A47", width=1)
draw.text((cx0 + 14, cy0 + 80), "• " + c["lock1"], fill="#FFD97D", font=f_card_lock)
draw.text((cx0 + 14, cy0 + 99), "• " + c["lock2"], fill="#A8E6CF", font=f_card_lock)
stats = c.get("stat_bar_text") or f"IsoW: {c['iso_w_pct']:.1f}% | PrimeW: {c['prime_ing_pct']:.1f}% | Mean|Δ|: {c['mean_delta']:.1f} | Pad: {c['pad_pct']:.1f}%"
draw.rounded_rectangle([cx0 + 10, cy1 - 32, cx1 - 10, cy1 - 8], radius=4, fill="#1A1C23")
draw.text((cx0 + 16, cy1 - 28), stats, fill="#CED3E0", font=f_card_stat)
cur_y += th + ROW_GAP
fy = H - FOOTER_H + 16
foot_str = (
footer_text
if footer_text
else "Rubric Dimensions (20 pts each): D1 = CMUdict Purity & Mean Clause Drift | D2 = Independent Domain-Native Collision Density | D3 = Repdigit & Prime Word Architecture (+Rarity Bonus) | D4 = Epistemological Fit | D5 = Anti-Padding Rate"
)
draw.text(
(MARGIN_X, fy),
foot_str,
fill="#8C92A4",
font=f_footer,
)
if write_atomic:
tmp_png = out_png + ".tmp"
img.save(tmp_png, "PNG", optimize=True)
os.replace(tmp_png, out_png)
else:
img.save(out_png, "PNG", optimize=True)
def main():
import json
ap = argparse.ArgumentParser()
ap.add_argument("--archive-dir", default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive")
ap.add_argument("--rows-json", default=None, help="Optional pre-computed cohort JSON (e.g. Assemblage Builds from technocapital-singularity-zoology).")
ap.add_argument("--header-title", default="INGGLISH AQ ARCHIVE — MASTER BIDIRECTIONAL EVALUATION TIER LIST (S+ TO F)")
ap.add_argument("--header-subtitle", default=None)
ap.add_argument("--footer-text", default=None)
ap.add_argument("--skip-md", action="store_true", help="When --rows-json already generated custom Markdown, only compile PDF and PNG.")
ap.add_argument("--out-md", default="/workspace/ingglish-hyperdope-gematria/dossier-bidirectional-eval-tier-list.md")
ap.add_argument("--out-pdf", default="/workspace/ingglish-hyperdope-gematria/dossier-bidirectional-eval-tier-list.pdf")
ap.add_argument("--out-png", default="/workspace/ingglish-hyperdope-gematria/dossier-bidirectional-eval-tier-list.png")
args = ap.parse_args()
if args.rows_json:
with open(args.rows_json, "r", encoding="utf-8") as f:
data = json.load(f)
rows = data["rows"] if isinstance(data, dict) and "rows" in data else data
custom_tier_defs = data.get("tier_defs") if isinstance(data, dict) else None
if not args.skip_md:
render_md_and_pdf(rows, args.out_md, args.out_pdf)
elif args.out_pdf and args.out_md and os.path.exists(args.out_md):
# Compile PDF from existing custom Markdown via build_wire_report_pdf.py
import subprocess, sys
build_script = os.path.join(os.path.dirname(__file__), "build_wire_report_pdf.py")
subprocess.run(
[sys.executable, build_script, "--md", args.out_md, "--pdf", args.out_pdf, "--title", args.header_title],
check=True,
)
render_png(
rows,
args.out_png,
header_title=args.header_title,
header_subtitle=args.header_subtitle,
footer_text=args.footer_text,
custom_tier_defs=custom_tier_defs,
)
else:
rows = collect_evaluations(args.archive_dir)
render_md_and_pdf(rows, args.out_md, args.out_pdf)
render_png(rows, args.out_png)
print(f"Ranked {len(rows)} evaluations -> {args.out_md}, {args.out_pdf}, {args.out_png}")
if __name__ == "__main__":
main()