chore(repo): finalize 3-repo separation, sync 8 AQ skills/scripts, and add Eval 47
- Remove legacy tracked hyperdope-ci-build/* files (moved to sibling repo /workspace/hyperdope-ci-build). - Remove duplicate root news dossiers (25, 46) and duplicate archive PDF compendium per Archive File Hygiene Rule. - Add evaluate_aq.mjs, generate_aq_tier_list.py, build_wire_report_pdf.py, pdf_create.py, and pdf_read.py to ingglish-aq-archive/scripts/. - Synchronize all 8 scripts and 8 creative Ingglish AQ skills into packaging/bundle/ and rebuild .tar.gz / .tar.xz bundles. - Update reconstruct_option4_curve.py and option-4-curve-migration-manifest.json paths to /workspace/ingglish-hyperdope-gematria/. - Add 47-eval-news-2026-11-02-bidirectional (.md + .pdf) and update master 17-dossier tier list (.md, .pdf, .png). - Track Series I-V repeat lecture transcripts, genealogy compendium, repdigit compendium, and wire report artifacts.
This commit is contained in:
1 parent
c8ff9a63fd
commit
44c48bb12a
83 files changed
+6209
-3247
No files matched your search
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
build_wire_report_pdf.py
|
||||
Deterministic ReportLab PDF compiler & ASCII/mechanism verifier for `isopsephic-wire-report-synthesis`.
|
||||
Safely masks inline backtick code spans before applying bold/italic tags and verifies the resulting PDF
|
||||
via pypdf and pdfplumber.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
|
||||
def fmt_inline_safe(text: str) -> str:
|
||||
text = escape(text)
|
||||
text = text.replace("Δ", '<font name="Symbol">D</font>')
|
||||
text = text.replace("δ", '<font name="Symbol">d</font>')
|
||||
text = text.replace("μ", '<font name="Symbol">m</font>')
|
||||
text = text.replace("σ", '<font name="Symbol">s</font>')
|
||||
text = text.replace("π", '<font name="Symbol">p</font>')
|
||||
text = (
|
||||
text.replace("⁴", "<super>4</super>")
|
||||
.replace("⁵", "<super>5</super>")
|
||||
.replace("⁶", "<super>6</super>")
|
||||
.replace("⁷", "<super>7</super>")
|
||||
)
|
||||
code_spans: list[str] = []
|
||||
|
||||
def save_code(m: re.Match) -> str:
|
||||
idx = len(code_spans)
|
||||
code_spans.append(f'<font name="Courier">{m.group(1)}</font>')
|
||||
return f"\x00CODE{idx}\x00"
|
||||
|
||||
text = re.sub(r"`([^`]+)`", save_code, text)
|
||||
text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
|
||||
text = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", text)
|
||||
for idx, span in enumerate(code_spans):
|
||||
text = text.replace(f"\x00CODE{idx}\x00", span)
|
||||
return text
|
||||
|
||||
|
||||
def build_pdf(md_path: str, pdf_path: str, title: str) -> dict:
|
||||
try:
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
||||
from reportlab.platypus import HRFlowable, Paragraph, SimpleDocTemplate, Spacer
|
||||
from pypdf import PdfReader
|
||||
import pdfplumber
|
||||
except ImportError:
|
||||
import subprocess
|
||||
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 import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
||||
from reportlab.platypus import HRFlowable, Paragraph, SimpleDocTemplate, Spacer
|
||||
from pypdf import PdfReader
|
||||
import pdfplumber
|
||||
|
||||
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()
|
||||
|
||||
lines = Path(md_path).read_text(encoding="utf-8").splitlines()
|
||||
|
||||
doc = SimpleDocTemplate(
|
||||
pdf_path,
|
||||
pagesize=letter,
|
||||
leftMargin=54,
|
||||
rightMargin=54,
|
||||
topMargin=54,
|
||||
bottomMargin=54,
|
||||
title=title,
|
||||
author="Hermes Agent",
|
||||
)
|
||||
styles = getSampleStyleSheet()
|
||||
h1 = ParagraphStyle("H1", parent=styles["Heading1"], fontName="Helvetica-Bold", fontSize=15, leading=19, spaceAfter=8, textColor=colors.HexColor("#111111"))
|
||||
h2 = ParagraphStyle("H2", parent=styles["Heading2"], fontName="Helvetica-Bold", fontSize=12.5, leading=16, spaceBefore=10, spaceAfter=6, textColor=colors.HexColor("#1a1a1a"))
|
||||
h3 = ParagraphStyle("H3", parent=styles["Heading3"], fontName="Helvetica-Bold", fontSize=10.5, leading=14, spaceBefore=8, spaceAfter=4, textColor=colors.HexColor("#222222"))
|
||||
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)
|
||||
subbullet = ParagraphStyle("SubBullet", parent=body, leftIndent=28, firstLineIndent=-8, spaceAfter=3)
|
||||
|
||||
story, headers, in_table = [], [], False
|
||||
for line in lines:
|
||||
s = line.strip()
|
||||
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("|"):
|
||||
cols = [c.strip() for c in re.split(r'(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)', s)[1:-1]]
|
||||
if all(re.fullmatch(r":?-+:?", c) for c in cols):
|
||||
in_table = True
|
||||
continue
|
||||
if not in_table and not headers:
|
||||
headers = cols
|
||||
continue
|
||||
parts = [f"**{re.sub(r'\\*\\*([^*]+)\\*\\*', r'\\1', h)}:** {v}" for h, v in zip(headers, cols)]
|
||||
story.append(Paragraph("• " + fmt_inline_safe(" | ".join(parts)), bullet))
|
||||
continue
|
||||
in_table, headers = False, []
|
||||
if s.startswith("# "):
|
||||
story.append(Paragraph(fmt_inline_safe(s[2:]), h1))
|
||||
elif s.startswith("## "):
|
||||
story.append(Paragraph(fmt_inline_safe(s[3:]), h2))
|
||||
elif s.startswith("### "):
|
||||
story.append(Paragraph(fmt_inline_safe(s[4:]), h3))
|
||||
elif line.startswith(" - ") or line.startswith(" - ") or line.startswith(" - "):
|
||||
story.append(Paragraph("◦ " + fmt_inline_safe(s[2:]), subbullet))
|
||||
elif re.match(r"^\s+\d+\.\s+", line):
|
||||
story.append(Paragraph(fmt_inline_safe(s), subbullet))
|
||||
elif s.startswith("- "):
|
||||
story.append(Paragraph("• " + fmt_inline_safe(s[2:]), bullet))
|
||||
elif re.match(r"^\d+\.\s+", s):
|
||||
story.append(Paragraph(fmt_inline_safe(s), bullet))
|
||||
else:
|
||||
story.append(Paragraph(fmt_inline_safe(s), body))
|
||||
|
||||
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
|
||||
|
||||
reader = PdfReader(pdf_path)
|
||||
with pdfplumber.open(pdf_path) as pdf:
|
||||
chars = sum(len(p.extract_text() or "") for p in pdf.pages)
|
||||
return {
|
||||
"md_path": md_path,
|
||||
"pdf_path": pdf_path,
|
||||
"page_count": len(reader.pages),
|
||||
"extracted_chars": chars,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Compile wire report Markdown to verified PDF.")
|
||||
ap.add_argument("--md", required=True, help="Input Markdown file path")
|
||||
ap.add_argument("--pdf", required=True, help="Output PDF file path")
|
||||
ap.add_argument("--title", default="Isopsephic Wire Report", help="PDF document title")
|
||||
args = ap.parse_args()
|
||||
|
||||
res = build_pdf(args.md, args.pdf, args.title)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0 if res["page_count"] >= 1 and res["extracted_chars"] > 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Regular → Executable
+53
-31
@@ -47,29 +47,36 @@ def load_system_dict() -> set[str]:
|
||||
continue
|
||||
# Fallback when container /usr/share/dict/words is absent: load the 126,051 English words
|
||||
# from the installed @ingglish/dictionary CMU Pronouncing Dictionary package.
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
[
|
||||
"node",
|
||||
"-e",
|
||||
'import("/workspace/node_modules/@ingglish/dictionary/dist/index.js").then(async m => {'
|
||||
"await m.loadDictionary();"
|
||||
"console.log(Object.keys(m.getDictionary()).join('\\n'));"
|
||||
"});",
|
||||
],
|
||||
text=True,
|
||||
timeout=15,
|
||||
)
|
||||
words = {w.strip().lower() for w in out.splitlines() if w.strip() and w.strip().isalpha()}
|
||||
if words:
|
||||
try:
|
||||
os.makedirs("/usr/share/dict", exist_ok=True)
|
||||
Path("/usr/share/dict/words").write_text("\n".join(sorted(words)) + "\n", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return words
|
||||
except Exception:
|
||||
pass
|
||||
for dict_js in (
|
||||
"/workspace/ingglish-hyperdope-gematria/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
"/workspace/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
"/opt/ingglish-exegesis/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
):
|
||||
if not os.path.exists(dict_js):
|
||||
continue
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
[
|
||||
"node",
|
||||
"-e",
|
||||
f'import("{dict_js}").then(async m => {{'
|
||||
"await m.loadDictionary();"
|
||||
"console.log(Object.keys(m.getDictionary()).join('\\n'));"
|
||||
"});",
|
||||
],
|
||||
text=True,
|
||||
timeout=15,
|
||||
)
|
||||
words = {w.strip().lower() for w in out.splitlines() if w.strip() and w.strip().isalpha()}
|
||||
if words:
|
||||
try:
|
||||
os.makedirs("/usr/share/dict", exist_ok=True)
|
||||
Path("/usr/share/dict/words").write_text("\n".join(sorted(words)) + "\n", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return words
|
||||
except Exception:
|
||||
continue
|
||||
return set()
|
||||
|
||||
|
||||
@@ -788,10 +795,11 @@ Standard English spelling (`Gen 0`) carries historical silent-letter "ghost mass
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${{BASH_SOURCE[0]}}")" && pwd)"
|
||||
REPO_DIR="${{1:-/workspace/hyperdope-gematria}}"
|
||||
REPO_DIR="${{1:-/workspace/hyperdope-ci-build}}"
|
||||
BRANCH="{branch_name}"
|
||||
BASE_BRANCH="{base_branch}"
|
||||
UPSTREAM_REPO="{upstream_repo}"
|
||||
ORIGIN_URL="${{ORIGIN_URL:-ssh://git@git.libre.audio:2222/seasharp/ingglish-hyperdope-gematria.git}}"
|
||||
|
||||
if [ ! -d "$REPO_DIR/.git" ]; then
|
||||
echo "Error: Target git repository not found at $REPO_DIR" >&2
|
||||
@@ -800,6 +808,15 @@ fi
|
||||
|
||||
cd "$REPO_DIR"
|
||||
|
||||
# Configure 'origin' remote if not yet registered
|
||||
if ! git remote get-url origin >/dev/null 2>&1; then
|
||||
git remote add origin "$ORIGIN_URL"
|
||||
echo "Configured remote 'origin' -> $ORIGIN_URL"
|
||||
elif [ -n "${{FORCE_ORIGIN_URL:-}}" ]; then
|
||||
git remote set-url origin "$FORCE_ORIGIN_URL"
|
||||
echo "Updated remote 'origin' -> $FORCE_ORIGIN_URL"
|
||||
fi
|
||||
|
||||
# Ensure feature branch exists and is checked out
|
||||
CURRENT_BRANCH="$(git branch --show-current)"
|
||||
if [ "$CURRENT_BRANCH" != "$BRANCH" ]; then
|
||||
@@ -818,8 +835,11 @@ fi
|
||||
|
||||
echo "Committed on branch $BRANCH: $(git rev-parse --short HEAD)"
|
||||
|
||||
# Submit PR if push/remote credentials are configured
|
||||
# First push of base branch + feature branch and optional PR creation when SUBMIT_REMOTE=1
|
||||
if [ "${{SUBMIT_REMOTE:-0}}" = "1" ]; then
|
||||
if git show-ref --verify --quiet "refs/heads/$BASE_BRANCH"; then
|
||||
git push -u origin "$BASE_BRANCH" || true
|
||||
fi
|
||||
git push -u origin "$BRANCH"
|
||||
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
|
||||
gh pr create \\
|
||||
@@ -835,11 +855,11 @@ if [ "${{SUBMIT_REMOTE:-0}}" = "1" ]; then
|
||||
"https://api.github.com/repos/$UPSTREAM_REPO/pulls" \\
|
||||
-d @"$SCRIPT_DIR/pr-payload.json"
|
||||
else
|
||||
echo "Error: Neither 'gh auth' nor GITHUB_TOKEN is active for remote PR creation." >&2
|
||||
exit 2
|
||||
echo "Remote branch '$BRANCH' pushed to origin. Set gh auth or GITHUB_TOKEN to also open a GitHub PR."
|
||||
fi
|
||||
else
|
||||
echo "Local commit ready. Set SUBMIT_REMOTE=1 to push and open the GitHub PR."
|
||||
echo "Local commit ready on '$BRANCH' (origin: $(git remote get-url origin))."
|
||||
echo "For first push: git -C $REPO_DIR push -u origin $BASE_BRANCH $BRANCH (or SUBMIT_REMOTE=1 $0 $REPO_DIR)"
|
||||
fi
|
||||
"""
|
||||
submit_sh_path = out_dir / "submit-pr.sh"
|
||||
@@ -918,7 +938,7 @@ def apply_to_repo(repo_dir: Path, out_dir: Path, entries: list[dict], branch_nam
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="CI & PR Provisioning Pipeline for Ingglish -> hyperdope-gematria.")
|
||||
parser.add_argument("--archive-dir", default="/workspace/ingglish-aq-archive", help="Path to Ingglish AQ archive")
|
||||
parser.add_argument("--archive-dir", default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive", help="Path to Ingglish AQ archive")
|
||||
parser.add_argument("--out-dir", default="/workspace/hyperdope-ci-build", help="Directory for CI & PR build artifacts")
|
||||
parser.add_argument("--repo-dir", default="", help="Optional path to local hyperdope-gematria git clone")
|
||||
parser.add_argument("--tier", type=int, default=2, choices=[1, 2], help="1 = Lexicon only, 2 = Lexicon + 333/666/777/Numogram equations")
|
||||
@@ -927,6 +947,8 @@ def main() -> int:
|
||||
args = parser.parse_args()
|
||||
|
||||
archive_dir = Path(args.archive_dir)
|
||||
if not archive_dir.exists() and Path("/workspace/ingglish-aq-archive").exists():
|
||||
archive_dir = Path("/workspace/ingglish-aq-archive")
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -945,8 +967,8 @@ def main() -> int:
|
||||
if args.generate_docs:
|
||||
md_out = out_dir / "ONBOARDING-INGGLISH-AQ.md"
|
||||
md_out.write_text(ONBOARDING_MD_CONTENT, encoding="utf-8")
|
||||
ws_md = Path("/workspace/ONBOARDING-INGGLISH-AQ.md")
|
||||
ws_pdf = Path("/workspace/ONBOARDING-INGGLISH-AQ.pdf")
|
||||
ws_md = Path("/workspace/ingglish-hyperdope-gematria/ONBOARDING-INGGLISH-AQ.md")
|
||||
ws_pdf = Path("/workspace/ingglish-hyperdope-gematria/ONBOARDING-INGGLISH-AQ.pdf")
|
||||
ws_md.write_text(ONBOARDING_MD_CONTENT, encoding="utf-8")
|
||||
pdf_meta = build_onboarding_pdf(ws_pdf)
|
||||
build_onboarding_pdf(out_dir / "ONBOARDING-INGGLISH-AQ.pdf")
|
||||
|
||||
@@ -346,10 +346,15 @@ def load_prior_dossiers(archive_dir: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def batch_translate_ingglish(strings: list[str], workdir: str = "/workspace") -> dict[str, str]:
|
||||
def batch_translate_ingglish(strings: list[str], workdir: str = "/workspace/ingglish-hyperdope-gematria") -> dict[str, str]:
|
||||
"""Run a single Node script invoking `ingglish` on all input strings."""
|
||||
if not strings:
|
||||
return {}
|
||||
if not os.path.exists(os.path.join(workdir, "node_modules")):
|
||||
for candidate_wd in ("/workspace/ingglish-hyperdope-gematria", "/workspace", "/opt/ingglish-exegesis"):
|
||||
if os.path.exists(os.path.join(candidate_wd, "node_modules")):
|
||||
workdir = candidate_wd
|
||||
break
|
||||
node_code = """
|
||||
import { translate } from 'ingglish';
|
||||
import fs from 'fs';
|
||||
@@ -424,11 +429,13 @@ def main() -> int:
|
||||
default="auto",
|
||||
help="Date resolution mode (auto uses closing-bell at 00:00-05:59 UTC).",
|
||||
)
|
||||
parser.add_argument("--archive-dir", default="/workspace/ingglish-aq-archive")
|
||||
parser.add_argument("--workdir", default="/workspace")
|
||||
parser.add_argument("--archive-dir", default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive")
|
||||
parser.add_argument("--workdir", default="/workspace/ingglish-hyperdope-gematria")
|
||||
parser.add_argument("--out", default=None, help="Optional file path to also save JSON output.")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.exists(args.archive_dir) and os.path.exists("/workspace/ingglish-aq-archive"):
|
||||
args.archive_dir = "/workspace/ingglish-aq-archive"
|
||||
now_utc = datetime.datetime.now(datetime.timezone.utc)
|
||||
date_info = resolve_target_dates(now_utc, explicit_date=args.date, mode=args.mode)
|
||||
|
||||
|
||||
Executable
+361
@@ -0,0 +1,361 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* evaluate_aq.mjs
|
||||
* Deterministic Bidirectional English / Ingglish Alphanumeric Qabbala (AQ) Evaluator.
|
||||
* Supports:
|
||||
* Mode A (AND): --eng "<phrase>" --ing "<phrase>"
|
||||
* Mode B (XOR Eng): --eng "<phrase>" (generates Ingglish via CMUdict + archive lexicon)
|
||||
* Mode C (XOR Ing): --ing "<phrase>" (reconstructs English via archive lexicon + reverseTranslate + homophone forks)
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
async function loadIngglishModule() {
|
||||
const candidates = [
|
||||
"/workspace/ingglish-hyperdope-gematria/node_modules/ingglish/dist/index.js",
|
||||
"/workspace/node_modules/ingglish/dist/index.js",
|
||||
"/opt/ingglish-exegesis/node_modules/ingglish/dist/index.js",
|
||||
];
|
||||
for (const p of candidates) {
|
||||
if (fs.existsSync(p)) {
|
||||
return await import(pathToFileURL(p).href);
|
||||
}
|
||||
}
|
||||
return await import("ingglish");
|
||||
}
|
||||
|
||||
function computeAQ(text) {
|
||||
let total = 0;
|
||||
for (const ch of String(text).toLowerCase()) {
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code >= 48 && code <= 57) {
|
||||
total += code - 48;
|
||||
} else if (code >= 97 && code <= 122) {
|
||||
total += code - 97 + 10;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function buildPrimes(limit = 20000) {
|
||||
const sieve = new Uint8Array(limit + 1);
|
||||
sieve.fill(1);
|
||||
sieve[0] = 0;
|
||||
sieve[1] = 0;
|
||||
for (let i = 2; i * i <= limit; i++) {
|
||||
if (sieve[i]) {
|
||||
for (let j = i * i; j <= limit; j += i) sieve[j] = 0;
|
||||
}
|
||||
}
|
||||
const primeRank = new Map();
|
||||
let rank = 0;
|
||||
for (let n = 2; n <= limit; n++) {
|
||||
if (sieve[n]) {
|
||||
rank += 1;
|
||||
primeRank.set(n, rank);
|
||||
}
|
||||
}
|
||||
return primeRank;
|
||||
}
|
||||
|
||||
const PRIME_RANK = buildPrimes(20000);
|
||||
|
||||
function factorize(n) {
|
||||
if (n < 2) return String(n);
|
||||
if (PRIME_RANK.has(n)) {
|
||||
return `${n} [PRIME #${PRIME_RANK.get(n)}]`;
|
||||
}
|
||||
let temp = n;
|
||||
const factors = [];
|
||||
for (let d = 2; d * d <= temp; d += d === 2 ? 1 : 2) {
|
||||
let count = 0;
|
||||
while (temp % d === 0) {
|
||||
count += 1;
|
||||
temp = Math.floor(temp / d);
|
||||
}
|
||||
if (count > 0) {
|
||||
factors.push(count === 1 ? `${d}` : `${d}^${count}`);
|
||||
}
|
||||
}
|
||||
if (temp > 1) factors.push(`${temp}`);
|
||||
return `${n} (${factors.join(" × ")})`;
|
||||
}
|
||||
|
||||
const HOMOPHONE_FORKS = new Map([
|
||||
["ai", ["I", "eye", "AI"]],
|
||||
["nait", ["night", "knight"]],
|
||||
["rait", ["write", "right", "rite"]],
|
||||
["raits", ["writes", "rights", "rites"]],
|
||||
["see", ["sea", "see"]],
|
||||
["too", ["to", "too", "two"]],
|
||||
["suhn", ["sun", "son"]],
|
||||
["noo", ["new", "knew"]],
|
||||
["hart", ["heart", "hart"]],
|
||||
["seer", ["seer", "sear"]],
|
||||
["werd", ["word", "whirred"]],
|
||||
]);
|
||||
|
||||
const PROPER_NOUN_OVERRIDES_ENG_TO_ING = new Map([
|
||||
["typhon", "taifan"],
|
||||
["apophis", "apawfis"],
|
||||
["joshua", "joshooa"],
|
||||
["ramey", "raymee"],
|
||||
["outpost", "outpohst"],
|
||||
["childs", "chaildz"],
|
||||
["macready", "makreedee"],
|
||||
]);
|
||||
|
||||
function loadArchiveLexicon() {
|
||||
const engToIng = new Map(PROPER_NOUN_OVERRIDES_ENG_TO_ING);
|
||||
const ingToEng = new Map([
|
||||
["dha", "the"],
|
||||
["uhv", "of"],
|
||||
["spairal", "spiral"],
|
||||
["flaymethroher", "flamethrower"],
|
||||
["outpohst", "outpost"],
|
||||
["chaildz", "childs"],
|
||||
["ayleean", "alien"],
|
||||
["wiskee", "whiskey"],
|
||||
["aiern", "iron"],
|
||||
["deeman", "demon"],
|
||||
["gohst", "ghost"],
|
||||
["gohsts", "ghosts"],
|
||||
["spaider", "spider"],
|
||||
["hed", "head"],
|
||||
["taifan", "typhon"],
|
||||
["apawfis", "apophis"],
|
||||
["joshooa", "joshua"],
|
||||
["raymee", "ramey"],
|
||||
]);
|
||||
|
||||
const lexPaths = [
|
||||
"/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/01-ingglish-aq-lexicon.md",
|
||||
"/workspace/ingglish-aq-archive/01-ingglish-aq-lexicon.md",
|
||||
];
|
||||
for (const lp of lexPaths) {
|
||||
if (!fs.existsSync(lp)) continue;
|
||||
const text = fs.readFileSync(lp, "utf8");
|
||||
const bulletRe = /^-\s*`([^`]+)`\s*\("([^"]+)"\)\s*=\s*(\d+)/gm;
|
||||
let m;
|
||||
while ((m = bulletRe.exec(text)) !== null) {
|
||||
const ing = m[1].trim().toLowerCase();
|
||||
const eng = m[2].trim().toLowerCase();
|
||||
if (!ingToEng.has(ing)) ingToEng.set(ing, eng);
|
||||
if (!engToIng.has(eng)) engToIng.set(eng, ing);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return { engToIng, ingToEng };
|
||||
}
|
||||
|
||||
function classifyIsometry(engWord, ingWord, engAq, ingAq) {
|
||||
if (engAq !== ingAq) return null;
|
||||
const eClean = engWord.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
const iClean = ingWord.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
if (eClean === iClean) return "Type I (Invariant)";
|
||||
const eSorted = eClean.split("").sort().join("");
|
||||
const iSorted = iClean.split("").sort().join("");
|
||||
if (eSorted === iSorted) return "Type II (Anagram)";
|
||||
return "Type III (Compensatory Split)";
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { eng: null, ing: null, jsonOnly: false };
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === "--eng" && i + 1 < argv.length) {
|
||||
args.eng = argv[++i];
|
||||
} else if (a === "--ing" && i + 1 < argv.length) {
|
||||
args.ing = argv[++i];
|
||||
} else if (a === "--json") {
|
||||
args.jsonOnly = true;
|
||||
} else if (a === "-h" || a === "--help") {
|
||||
console.log(
|
||||
"Usage: node evaluate_aq.mjs [--eng \"<english phrase>\"] [--ing \"<ingglish phrase>\"] [--json]"
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
if (!args.eng && !args.ing) {
|
||||
console.error("Error: supply --eng, --ing, or both.");
|
||||
process.exit(1);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv);
|
||||
const ingglish = await loadIngglishModule();
|
||||
const { engToIng, ingToEng } = loadArchiveLexicon();
|
||||
|
||||
let mode = "AND (Bidirectional Present)";
|
||||
let engPhrase = args.eng ? args.eng.trim() : "";
|
||||
let ingPhrase = args.ing ? args.ing.trim() : "";
|
||||
|
||||
if (engPhrase && !ingPhrase) {
|
||||
mode = "XOR (English -> Ingglish)";
|
||||
const rawTokens = engPhrase.split(/\s+/);
|
||||
const outTokens = [];
|
||||
for (const tok of rawTokens) {
|
||||
const clean = tok.toLowerCase().replace(/[^a-z0-9'-]/g, "");
|
||||
if (PROPER_NOUN_OVERRIDES_ENG_TO_ING.has(clean)) {
|
||||
outTokens.push(PROPER_NOUN_OVERRIDES_ENG_TO_ING.get(clean));
|
||||
} else {
|
||||
const tr = await ingglish.translate(tok);
|
||||
outTokens.push(tr.toLowerCase());
|
||||
}
|
||||
}
|
||||
ingPhrase = outTokens.join(" ");
|
||||
} else if (!engPhrase && ingPhrase) {
|
||||
mode = "XOR (Ingglish -> English)";
|
||||
const rawTokens = ingPhrase.split(/\s+/);
|
||||
const outTokens = [];
|
||||
for (const tok of rawTokens) {
|
||||
const clean = tok.toLowerCase().replace(/[^a-z0-9'-]/g, "");
|
||||
if (ingToEng.has(clean)) {
|
||||
outTokens.push(ingToEng.get(clean));
|
||||
} else if (typeof ingglish.reverseTranslate === "function") {
|
||||
const rev = await ingglish.reverseTranslate(clean);
|
||||
outTokens.push((rev || clean).toLowerCase());
|
||||
} else {
|
||||
outTokens.push(clean);
|
||||
}
|
||||
}
|
||||
engPhrase = outTokens.join(" ");
|
||||
}
|
||||
|
||||
const engWords = engPhrase.split(/\s+/).filter(Boolean);
|
||||
const ingWords = ingPhrase.split(/\s+/).filter(Boolean);
|
||||
|
||||
const engAq = computeAQ(engPhrase);
|
||||
const ingAq = computeAQ(ingPhrase);
|
||||
const netDelta = ingAq - engAq;
|
||||
|
||||
const tokenComparison = [];
|
||||
const homophoneForksFound = [];
|
||||
let isoWordCount = 0;
|
||||
let primeIngWordCount = 0;
|
||||
let paddingWordCount = 0;
|
||||
|
||||
const maxLen = Math.max(engWords.length, ingWords.length);
|
||||
for (let i = 0; i < maxLen; i++) {
|
||||
const ew = engWords[i] || "";
|
||||
const iw = ingWords[i] || "";
|
||||
const eVal = computeAQ(ew);
|
||||
const iVal = computeAQ(iw);
|
||||
const dVal = iVal - eVal;
|
||||
const isoType = ew && iw ? classifyIsometry(ew, iw, eVal, iVal) : null;
|
||||
if (isoType) isoWordCount += 1;
|
||||
if (PRIME_RANK.has(iVal)) primeIngWordCount += 1;
|
||||
const iwClean = iw.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
if (iwClean === "seekrat" || iwClean === "hidan") paddingWordCount += 1;
|
||||
if (HOMOPHONE_FORKS.has(iwClean)) {
|
||||
const branches = HOMOPHONE_FORKS.get(iwClean).map((b) => ({
|
||||
eng: b,
|
||||
eng_aq: computeAQ(b),
|
||||
eng_prime_rank: PRIME_RANK.get(computeAQ(b)) || null,
|
||||
}));
|
||||
homophoneForksFound.push({ ing: iwClean, ing_aq: iVal, branches });
|
||||
}
|
||||
tokenComparison.push({
|
||||
eng_token: ew,
|
||||
eng_aq: eVal,
|
||||
eng_prime_rank: PRIME_RANK.get(eVal) || null,
|
||||
ing_token: iw,
|
||||
ing_aq: iVal,
|
||||
ing_prime_rank: PRIME_RANK.get(iVal) || null,
|
||||
delta: dVal,
|
||||
isometry: isoType,
|
||||
});
|
||||
}
|
||||
|
||||
const isoRatePct = Number(((100 * isoWordCount) / Math.max(1, maxLen)).toFixed(1));
|
||||
const primeIngRatePct = Number(((100 * primeIngWordCount) / Math.max(1, maxLen)).toFixed(1));
|
||||
const paddingRatePct = Number(((100 * paddingWordCount) / Math.max(1, maxLen)).toFixed(1));
|
||||
|
||||
// Compute 5-dimension rubric score
|
||||
const absDelta = Math.abs(netDelta);
|
||||
let d1 = absDelta === 0 ? 20 : absDelta <= 35 ? 19 : absDelta <= 50 ? 18 : 17;
|
||||
if (isoWordCount > 0 && d1 < 20) d1 = Math.min(20, d1 + 1);
|
||||
|
||||
const repdigits = new Set([111, 222, 333, 444, 555, 666, 777, 888, 999]);
|
||||
const syzygies = new Set([81, 108, 216, 495]);
|
||||
const twinPrimeClause = PRIME_RANK.has(engAq) && PRIME_RANK.has(ingAq);
|
||||
const exact37Step = absDelta > 0 && absDelta % 37 === 0;
|
||||
|
||||
let d2 = homophoneForksFound.length > 0 || isoWordCount >= 2 ? 19 : 18;
|
||||
let d3 = 17;
|
||||
if (repdigits.has(ingAq) || repdigits.has(engAq)) d3 += 2;
|
||||
if (twinPrimeClause || exact37Step || syzygies.has(ingAq)) d3 += 1;
|
||||
if (primeIngRatePct >= 18) d3 += 1;
|
||||
d3 = Math.min(20, d3);
|
||||
|
||||
let d4 = 18 + (homophoneForksFound.length > 0 || ingWords.includes("dha") ? 1 : 0);
|
||||
d4 = Math.min(20, d4);
|
||||
|
||||
let d5 = paddingRatePct === 0 ? 19 : paddingRatePct < 15 ? 18 : paddingRatePct <= 30 ? 16 : 14;
|
||||
if (netDelta === 0 && repdigits.has(ingAq)) d5 = 20;
|
||||
|
||||
const totalScore = d1 + d2 + d3 + d4 + d5;
|
||||
const tier =
|
||||
totalScore >= 95
|
||||
? "Class S+ (Apex Lock)"
|
||||
: totalScore >= 90
|
||||
? "Class S (Canonical Lock)"
|
||||
: totalScore >= 81
|
||||
? "Class A (Structural Entry)"
|
||||
: totalScore >= 72
|
||||
? "Class B (Modular Entry)"
|
||||
: "Class C/D/F";
|
||||
|
||||
const payload = {
|
||||
mode,
|
||||
english: {
|
||||
phrase: engPhrase,
|
||||
aq: engAq,
|
||||
factorization: factorize(engAq),
|
||||
is_prime: PRIME_RANK.has(engAq),
|
||||
prime_rank: PRIME_RANK.get(engAq) || null,
|
||||
breakdown: tokenComparison.map((t) => `${t.eng_token} (${t.eng_aq})`).join(" + ") + ` = ${engAq}`,
|
||||
},
|
||||
ingglish: {
|
||||
phrase: ingPhrase,
|
||||
aq: ingAq,
|
||||
factorization: factorize(ingAq),
|
||||
is_prime: PRIME_RANK.has(ingAq),
|
||||
prime_rank: PRIME_RANK.get(ingAq) || null,
|
||||
breakdown: tokenComparison.map((t) => `${t.ing_token} (${t.ing_aq})`).join(" + ") + ` = ${ingAq}`,
|
||||
},
|
||||
drift: {
|
||||
net_delta: netDelta,
|
||||
abs_delta: absDelta,
|
||||
quantized_37_step: exact37Step,
|
||||
full_clause_isometry: netDelta === 0,
|
||||
twin_prime_clause: twinPrimeClause,
|
||||
isometric_word_count: isoWordCount,
|
||||
isometric_word_rate_pct: isoRatePct,
|
||||
prime_ing_word_rate_pct: primeIngRatePct,
|
||||
padding_rate_pct: paddingRatePct,
|
||||
},
|
||||
tokens: tokenComparison,
|
||||
homophone_forks: homophoneForksFound,
|
||||
rubric: {
|
||||
D1_determinism_and_drift: d1,
|
||||
D2_collision_density: d2,
|
||||
D3_repdigit_and_prime_arch: d3,
|
||||
D4_epistemological_fit: d4,
|
||||
D5_syntactic_anti_padding: d5,
|
||||
composite_score: totalScore,
|
||||
classification: tier,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(JSON.stringify(payload, null, 2));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
+462
@@ -0,0 +1,462 @@
|
||||
#!/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("Δ", '<font name="Symbol">D</font>')
|
||||
text = text.replace("μ", '<font name="Symbol">m</font>')
|
||||
text = text.replace("σ", '<font name="Symbol">s</font>')
|
||||
text = text.replace("π", '<font name="Symbol">p</font>')
|
||||
text = (
|
||||
text.replace("⁴", "<super>4</super>")
|
||||
.replace("⁵", "<super>5</super>")
|
||||
.replace("⁶", "<super>6</super>")
|
||||
.replace("⁷", "<super>7</super>")
|
||||
)
|
||||
code_spans = []
|
||||
|
||||
def _save_code(m):
|
||||
idx = len(code_spans)
|
||||
code_spans.append(f'<font name="Courier">{m.group(1)}</font>')
|
||||
return f"\x00CODE{idx}\x00"
|
||||
|
||||
text = re.sub(r"`([^`]+)`", _save_code, text)
|
||||
text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
|
||||
text = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", 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'(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)', s)[1:-1]]
|
||||
if all(re.match(r"^:?-+:?$", c) for c in cells):
|
||||
in_table = True
|
||||
continue
|
||||
if not in_table and not headers:
|
||||
headers = cells
|
||||
continue
|
||||
parts = [f"**{re.sub(r'\\*\\*([^*]+)\\*\\*', r'\\1', h)}:** {v}" for h, v in zip(headers, cells)]
|
||||
story.append(Paragraph("• " + fmt_inline(" | ".join(parts)), bullet))
|
||||
continue
|
||||
in_table, headers = False, []
|
||||
if s.startswith("# "):
|
||||
story.append(Paragraph(fmt_inline(s[2:]), h1))
|
||||
elif s.startswith("## "):
|
||||
story.append(Paragraph(fmt_inline(s[3:]), h2))
|
||||
elif s.startswith("### "):
|
||||
story.append(Paragraph(fmt_inline(s[4:]), h3))
|
||||
elif s.startswith("- ") or re.match(r"^\d+\.\s+", s):
|
||||
story.append(Paragraph("• " + fmt_inline(re.sub(r"^(-\s+|\d+\.\s+)", "", s)), bullet))
|
||||
else:
|
||||
story.append(Paragraph(fmt_inline(s), body))
|
||||
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
|
||||
|
||||
|
||||
def render_png(rows, out_png: str):
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
FONT_BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
|
||||
FONT_REG = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
|
||||
FONT_MONO = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"
|
||||
FONT_MONO_REG = "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf"
|
||||
|
||||
f_title = ImageFont.truetype(FONT_BOLD, 34)
|
||||
f_subtitle = ImageFont.truetype(FONT_REG, 18)
|
||||
f_tier_big = ImageFont.truetype(FONT_BOLD, 50)
|
||||
f_tier_sub = ImageFont.truetype(FONT_BOLD, 13)
|
||||
f_card_rank = ImageFont.truetype(FONT_BOLD, 16)
|
||||
f_card_title = ImageFont.truetype(FONT_BOLD, 19)
|
||||
f_card_dossier = ImageFont.truetype(FONT_MONO_REG, 13)
|
||||
f_card_lock = ImageFont.truetype(FONT_MONO, 13)
|
||||
f_card_stat = ImageFont.truetype(FONT_REG, 13)
|
||||
f_empty = ImageFont.truetype(FONT_REG, 18)
|
||||
f_empty_bold = ImageFont.truetype(FONT_BOLD, 18)
|
||||
f_footer = ImageFont.truetype(FONT_REG, 15)
|
||||
|
||||
tier_defs = [
|
||||
("S+", "95 – 100 pts", "APEX LOCK", "#FF4D4D", "0 Dossiers in Tier S+", ""),
|
||||
("S", "90 – 94 pts", "CANONICAL", "#FF7F7F", "0 Dossiers in Tier S", ""),
|
||||
("A", "81 – 89 pts [3⁴]", "STRUCTURAL", "#FFBF7F", "0 Dossiers in Tier A", ""),
|
||||
("B", "72 – 80 pts [8×9]", "MODULAR SWAP", "#FFFF7F", "0 Dossiers in Tier B", ""),
|
||||
(
|
||||
"C",
|
||||
"66 – 71 pts",
|
||||
"HIGH-PADDING",
|
||||
"#7FFF7F",
|
||||
"0 Dossiers in Tier C (66 – 71 pts — High-Padding / Low-Collision Band)",
|
||||
"Threshold for dossiers with >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).",
|
||||
),
|
||||
]
|
||||
|
||||
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),
|
||||
"INGGLISH AQ ARCHIVE — MASTER BIDIRECTIONAL EVALUATION TIER LIST (S+ TO F)",
|
||||
fill="#F5F6F8",
|
||||
font=f_title,
|
||||
)
|
||||
draw.text(
|
||||
(MARGIN_X, 68),
|
||||
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)",
|
||||
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 = 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 = f"Eval {c['eval_num']} • Dossier {c['dossier_num']}"
|
||||
draw.text((cx0 + 70, cy0 + 19), codes, 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 = 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
|
||||
draw.text(
|
||||
(MARGIN_X, fy),
|
||||
"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",
|
||||
fill="#8C92A4",
|
||||
font=f_footer,
|
||||
)
|
||||
img.save(out_png, "PNG", optimize=True)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--archive-dir", default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive")
|
||||
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()
|
||||
|
||||
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()
|
||||
@@ -54,17 +54,18 @@ def canonical_stem(slug: str) -> str:
|
||||
return f"lecture-{norm}-ingglish-aq"
|
||||
|
||||
|
||||
def resolve_host_workspace_mount(container_workspace: str = "/workspace") -> str:
|
||||
def resolve_host_workspace_mount(container_workspace: str = "/workspace/ingglish-hyperdope-gematria") -> str:
|
||||
"""
|
||||
Resolve the host filesystem path backing /workspace from /proc/self/mountinfo
|
||||
so host-executed tools like text_to_speech(output_path=...) write directly into /workspace.
|
||||
Resolve the host filesystem path backing container_workspace from /proc/self/mountinfo
|
||||
so host-executed tools like text_to_speech(output_path=...) write directly into the target repo.
|
||||
"""
|
||||
mountinfo = Path("/proc/self/mountinfo")
|
||||
if mountinfo.exists():
|
||||
for line in mountinfo.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 5 and parts[4] == container_workspace:
|
||||
return parts[3]
|
||||
if len(parts) >= 5 and parts[4] == "/workspace":
|
||||
rel = os.path.relpath(container_workspace, "/workspace")
|
||||
return parts[3] if rel == "." else f"{parts[3]}/{rel}"
|
||||
return container_workspace
|
||||
|
||||
|
||||
@@ -211,7 +212,7 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Validate lecture naming conventions and manage .gitignore rules."
|
||||
)
|
||||
parser.add_argument("--workspace", default="/workspace")
|
||||
parser.add_argument("--workspace", default="/workspace/ingglish-hyperdope-gematria")
|
||||
parser.add_argument("--slug", default=None, help="Topic slug to normalize/verify.")
|
||||
parser.add_argument(
|
||||
"--gitignore-mode",
|
||||
|
||||
Executable
+146
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create a PDF from a JSON spec using reportlab platypus.
|
||||
|
||||
Spec format (UTF-8 JSON):
|
||||
{
|
||||
"title": "Example Report",
|
||||
"author": "example-author",
|
||||
"page_size": "A4", // or "letter" (default: A4)
|
||||
"page_numbers": true, // default true
|
||||
"elements": [
|
||||
{"type": "heading", "text": "Section 1", "level": 1},
|
||||
{"type": "paragraph", "text": "Body text..."},
|
||||
{"type": "table", "rows": [["H1", "H2"], ["a", "b"]], "header": true},
|
||||
{"type": "image", "path": "chart.png", "width": 400},
|
||||
{"type": "pagebreak"}
|
||||
]
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def _reconfigure_stdio() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def build_pdf(spec: dict, out_path: str) -> int:
|
||||
try:
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import A4, letter
|
||||
from reportlab.lib.styles import getSampleStyleSheet
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.platypus import (
|
||||
Image,
|
||||
PageBreak,
|
||||
Paragraph,
|
||||
SimpleDocTemplate,
|
||||
Spacer,
|
||||
Table,
|
||||
TableStyle,
|
||||
)
|
||||
except ImportError:
|
||||
import subprocess
|
||||
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 import colors
|
||||
from reportlab.lib.pagesizes import A4, letter
|
||||
from reportlab.lib.styles import getSampleStyleSheet
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.platypus import (
|
||||
Image,
|
||||
PageBreak,
|
||||
Paragraph,
|
||||
SimpleDocTemplate,
|
||||
Spacer,
|
||||
Table,
|
||||
TableStyle,
|
||||
)
|
||||
|
||||
page_size = letter if str(spec.get("page_size", "A4")).lower() == "letter" else A4
|
||||
styles = getSampleStyleSheet()
|
||||
story = []
|
||||
for el in spec.get("elements", []):
|
||||
etype = el.get("type")
|
||||
if etype == "heading":
|
||||
level = min(max(int(el.get("level", 1)), 1), 3)
|
||||
story.append(Paragraph(el.get("text", ""), styles[f"Heading{level}"]))
|
||||
elif etype == "paragraph":
|
||||
story.append(Paragraph(el.get("text", ""), styles["BodyText"]))
|
||||
story.append(Spacer(1, 6))
|
||||
elif etype == "table":
|
||||
rows = el.get("rows", [])
|
||||
if not rows:
|
||||
continue
|
||||
table = Table(rows, repeatRows=1 if el.get("header", True) else 0)
|
||||
style = [
|
||||
("GRID", (0, 0), (-1, -1), 0.5, colors.grey),
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
]
|
||||
if el.get("header", True):
|
||||
style += [
|
||||
("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
|
||||
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
||||
]
|
||||
table.setStyle(TableStyle(style))
|
||||
story.append(table)
|
||||
story.append(Spacer(1, 10))
|
||||
elif etype == "image":
|
||||
kwargs = {}
|
||||
if el.get("width"):
|
||||
kwargs["width"] = float(el["width"])
|
||||
if el.get("height"):
|
||||
kwargs["height"] = float(el["height"])
|
||||
img = Image(el["path"], **kwargs)
|
||||
if "width" in kwargs and "height" not in kwargs:
|
||||
ratio = img.imageHeight / img.imageWidth
|
||||
img.drawWidth = kwargs["width"]
|
||||
img.drawHeight = kwargs["width"] * ratio
|
||||
story.append(img)
|
||||
story.append(Spacer(1, 10))
|
||||
elif etype == "pagebreak":
|
||||
story.append(PageBreak())
|
||||
else:
|
||||
print(f"Warning: unknown element type {etype!r}, skipped", file=sys.stderr)
|
||||
|
||||
def draw_page_number(canvas, doc):
|
||||
if spec.get("page_numbers", True):
|
||||
canvas.saveState()
|
||||
canvas.setFont("Helvetica", 9)
|
||||
canvas.drawCentredString(page_size[0] / 2.0, 0.5 * inch, f"Page {doc.page}")
|
||||
canvas.restoreState()
|
||||
|
||||
doc = SimpleDocTemplate(
|
||||
out_path,
|
||||
pagesize=page_size,
|
||||
title=spec.get("title", ""),
|
||||
author=spec.get("author", ""),
|
||||
)
|
||||
doc.build(story, onFirstPage=draw_page_number, onLaterPages=draw_page_number)
|
||||
print(json.dumps({"output": out_path, "elements": len(spec.get("elements", []))}))
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_reconfigure_stdio()
|
||||
parser = argparse.ArgumentParser(description="Create a PDF from a JSON spec (reportlab).")
|
||||
parser.add_argument("spec", help="Path to UTF-8 JSON spec file")
|
||||
parser.add_argument("-o", "--output", required=True, help="Output PDF path")
|
||||
args = parser.parse_args()
|
||||
with open(args.spec, encoding="utf-8") as fh:
|
||||
spec = json.load(fh)
|
||||
return build_pdf(spec, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+157
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a PDF: per-page text, tables, metadata, or form fields. JSON to stdout."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _reconfigure_stdio() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _need(module: str, package: str):
|
||||
try:
|
||||
return __import__(module)
|
||||
except ImportError:
|
||||
import subprocess
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--root-user-action=ignore", "--cache-dir", "/tmp/.pip", package],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
return __import__(module)
|
||||
|
||||
|
||||
def read_text(path: str, password: str | None) -> dict:
|
||||
pdfplumber = _need("pdfplumber", "pdfplumber")
|
||||
pages = []
|
||||
with pdfplumber.open(path, password=password) as pdf:
|
||||
for page in pdf.pages:
|
||||
pages.append(page.extract_text() or "")
|
||||
return {"page_count": len(pages), "pages": pages}
|
||||
|
||||
|
||||
def read_tables(path: str, password: str | None, csv_dir: str | None) -> dict:
|
||||
pdfplumber = _need("pdfplumber", "pdfplumber")
|
||||
result = []
|
||||
written = []
|
||||
with pdfplumber.open(path, password=password) as pdf:
|
||||
for pageno, page in enumerate(pdf.pages, start=1):
|
||||
for tidx, table in enumerate(page.extract_tables()):
|
||||
result.append({"page": pageno, "index": tidx, "rows": table})
|
||||
if csv_dir:
|
||||
os.makedirs(csv_dir, exist_ok=True)
|
||||
csv_path = os.path.join(csv_dir, f"page{pageno}_table{tidx}.csv")
|
||||
with open(csv_path, "w", encoding="utf-8", newline="") as fh:
|
||||
csv.writer(fh).writerows([[c if c is not None else "" for c in row] for row in table])
|
||||
written.append(csv_path)
|
||||
out = {"table_count": len(result), "tables": result}
|
||||
if csv_dir:
|
||||
out["csv_files"] = written
|
||||
return out
|
||||
|
||||
|
||||
def read_meta(path: str, password: str | None) -> dict:
|
||||
pypdf = _need("pypdf", "pypdf")
|
||||
reader = pypdf.PdfReader(path)
|
||||
encrypted = reader.is_encrypted
|
||||
if encrypted:
|
||||
if password is None or not reader.decrypt(password):
|
||||
return {"encrypted": True, "note": "Provide --password to read metadata of an encrypted file."}
|
||||
meta = {}
|
||||
if reader.metadata:
|
||||
for key, value in reader.metadata.items():
|
||||
meta[str(key).lstrip("/")] = str(value)
|
||||
pages = []
|
||||
for idx, page in enumerate(reader.pages, start=1):
|
||||
box = page.mediabox
|
||||
pages.append({
|
||||
"page": idx,
|
||||
"width": float(box.width),
|
||||
"height": float(box.height),
|
||||
"rotation": int(page.get("/Rotate", 0)),
|
||||
})
|
||||
likely_scanned = []
|
||||
try:
|
||||
pdfplumber = _need("pdfplumber", "pdfplumber")
|
||||
with pdfplumber.open(path, password=password) as pdf:
|
||||
for pageno, page in enumerate(pdf.pages, start=1):
|
||||
text = (page.extract_text() or "").strip()
|
||||
if not text and page.images:
|
||||
likely_scanned.append(pageno)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
print(f"Warning: scanned-page check failed: {exc}", file=sys.stderr)
|
||||
out = {
|
||||
"encrypted": encrypted,
|
||||
"page_count": len(reader.pages),
|
||||
"metadata": meta,
|
||||
"pages": pages,
|
||||
"likely_scanned_pages": likely_scanned,
|
||||
}
|
||||
if likely_scanned:
|
||||
out["note"] = ("Image-only pages detected: no text layer to extract. "
|
||||
"Use the references/ocr-extraction.md in this skill for OCR.")
|
||||
return out
|
||||
|
||||
|
||||
FIELD_TYPES = {"/Tx": "text", "/Btn": "button", "/Ch": "choice", "/Sig": "signature"}
|
||||
|
||||
|
||||
def read_fields(path: str, password: str | None) -> dict:
|
||||
pypdf = _need("pypdf", "pypdf")
|
||||
reader = pypdf.PdfReader(path)
|
||||
if reader.is_encrypted:
|
||||
if password is None or not reader.decrypt(password):
|
||||
print("File is encrypted; pass --password.", file=sys.stderr)
|
||||
raise SystemExit(3)
|
||||
fields = reader.get_fields() or {}
|
||||
out = {}
|
||||
for name, field in fields.items():
|
||||
ftype = FIELD_TYPES.get(str(field.get("/FT")), str(field.get("/FT")))
|
||||
value = field.get("/V")
|
||||
states = field.get("/_States_")
|
||||
entry = {"type": ftype, "value": None if value is None else str(value)}
|
||||
if states:
|
||||
entry["options"] = [str(s) for s in states]
|
||||
out[name] = entry
|
||||
return {"field_count": len(out), "fields": out}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_reconfigure_stdio()
|
||||
parser = argparse.ArgumentParser(description="Extract text, tables, metadata, or form fields from a PDF.")
|
||||
parser.add_argument("pdf", help="Input PDF path")
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument("--text", action="store_true", help="Per-page text as JSON")
|
||||
mode.add_argument("--tables", action="store_true", help="Tables as JSON (optionally CSV via --csv-dir)")
|
||||
mode.add_argument("--meta", action="store_true", help="Metadata, page sizes, encrypted/scanned flags")
|
||||
mode.add_argument("--fields", action="store_true", help="AcroForm fields with types and values")
|
||||
parser.add_argument("--csv-dir", help="Also write each table as a CSV file into this directory")
|
||||
parser.add_argument("--password", help="Password for encrypted PDFs")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.text:
|
||||
result = read_text(args.pdf, args.password)
|
||||
elif args.tables:
|
||||
result = read_tables(args.pdf, args.password, args.csv_dir)
|
||||
elif args.meta:
|
||||
result = read_meta(args.pdf, args.password)
|
||||
else:
|
||||
result = read_fields(args.pdf, args.password)
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user