chore: resolve README.md merge conflict
This commit is contained in:
1 parent
6ecbf4fff0
commit
a9fa8ae920
33 files changed
+609
-6836
No files matched your search
@@ -1,167 +1,30 @@
|
||||
#!/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.
|
||||
"""
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/build_wire_report_pdf.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
_SCRIPT_NAME = "build_wire_report_pdf.py"
|
||||
|
||||
|
||||
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>0</super>")
|
||||
.replace("¹", "<super>1</super>")
|
||||
.replace("²", "<super>2</super>")
|
||||
.replace("³", "<super>3</super>")
|
||||
.replace("⁴", "<super>4</super>")
|
||||
.replace("⁵", "<super>5</super>")
|
||||
.replace("⁶", "<super>6</super>")
|
||||
.replace("⁷", "<super>7</super>")
|
||||
.replace("⁸", "<super>8</super>")
|
||||
.replace("⁹", "<super>9</super>")
|
||||
.replace("√", "sqrt")
|
||||
.replace("≈", "~")
|
||||
)
|
||||
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
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -47,7 +47,12 @@ 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.
|
||||
_script_repo = str(Path(__file__).resolve().parents[2])
|
||||
_ws_env = os.environ.get("WORKSPACE_DIR", "/workspace")
|
||||
for dict_js in (
|
||||
f"{_script_repo}/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
f"{_ws_env}/ingglish-hyperdope-gematria/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
"/usr/libexec/ingglish-exegesis/node_modules/@ingglish/dictionary/dist/index.js",
|
||||
"/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",
|
||||
@@ -82,7 +87,7 @@ def load_system_dict() -> set[str]:
|
||||
|
||||
DICT = load_system_dict()
|
||||
ROMAN_RE = re.compile(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})", re.I)
|
||||
INGGLISH_NON_ROMAN = {"di", "li", "mi", "vi", "iv", "ci", "xi"}
|
||||
INGGLISH_NON_ROMAN = {"di", "li", "mi", "vi", "iv", "ci", "xi", "liv", "mix", "civ"}
|
||||
|
||||
|
||||
def is_roman(s: str) -> bool:
|
||||
@@ -512,10 +517,9 @@ def build_onboarding_pdf(pdf_path: Path) -> dict:
|
||||
try:
|
||||
import reportlab
|
||||
import pypdf
|
||||
import pdfplumber
|
||||
except ImportError:
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "-q", "reportlab", "pypdf", "pdfplumber"],
|
||||
[sys.executable, "-m", "pip", "install", "-q", "reportlab", "pypdf"],
|
||||
check=True,
|
||||
)
|
||||
from reportlab.lib import colors
|
||||
@@ -524,7 +528,8 @@ def build_onboarding_pdf(pdf_path: Path) -> dict:
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.platypus import HRFlowable, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
|
||||
import pypdf
|
||||
import pdfplumber
|
||||
|
||||
pdf_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
title_s = ParagraphStyle("T", parent=styles["Heading1"], fontName="Helvetica-Bold", fontSize=15.5, leading=19, spaceAfter=4, textColor=colors.HexColor("#111827"))
|
||||
@@ -679,8 +684,12 @@ def build_onboarding_pdf(pdf_path: Path) -> dict:
|
||||
doc.build(story, onFirstPage=draw_page_number, onLaterPages=draw_page_number)
|
||||
|
||||
reader = pypdf.PdfReader(str(pdf_path))
|
||||
with pdfplumber.open(str(pdf_path)) as pdf:
|
||||
chars = sum(len(p.extract_text() or "") for p in pdf.pages)
|
||||
try:
|
||||
import pdfplumber
|
||||
with pdfplumber.open(str(pdf_path)) as pdf:
|
||||
chars = sum(len(p.extract_text() or "") for p in pdf.pages)
|
||||
except ImportError:
|
||||
chars = sum(len(p.extract_text() or "") for p in reader.pages)
|
||||
return {"pdf_path": str(pdf_path), "page_count": len(reader.pages), "extracted_chars": chars}
|
||||
|
||||
|
||||
@@ -818,7 +827,8 @@ elif [ -n "${{FORCE_ORIGIN_URL:-}}" ]; then
|
||||
fi
|
||||
|
||||
# Ensure feature branch exists and is checked out
|
||||
CURRENT_BRANCH="$(git branch --show-current)"
|
||||
ORIG_BRANCH="$(git branch --show-current)"
|
||||
CURRENT_BRANCH="$ORIG_BRANCH"
|
||||
if [ "$CURRENT_BRANCH" != "$BRANCH" ]; then
|
||||
git checkout -B "$BRANCH"
|
||||
fi
|
||||
@@ -830,10 +840,18 @@ git add db.txt tools/normalize_caps.py config.default.js
|
||||
|
||||
# Create commit if staged changes exist
|
||||
if ! git diff --cached --quiet; then
|
||||
git commit -F "$SCRIPT_DIR/commit-message.txt"
|
||||
git -c user.name="${{GIT_AUTHOR_NAME:-Hyperstition Studio Exegesis Worker}}" \
|
||||
-c user.email="${{GIT_AUTHOR_EMAIL:-exegesis@hyperstitionstud.io}}" \
|
||||
commit -F "$SCRIPT_DIR/commit-message.txt"
|
||||
fi
|
||||
|
||||
echo "Committed on branch $BRANCH: $(git rev-parse --short HEAD)"
|
||||
# If target repository was originally on 'main' (e.g. haiperdohp-jemaytreeah), fast-forward 'main' and restore checkout
|
||||
if [ "$ORIG_BRANCH" = "main" ] && [ "$BRANCH" != "main" ]; then
|
||||
git checkout main
|
||||
git merge --ff-only "$BRANCH"
|
||||
fi
|
||||
|
||||
echo "Committed on branch $(git branch --show-current): $(git rev-parse --short HEAD)"
|
||||
|
||||
# First push of base branch + feature branch and optional PR creation when SUBMIT_REMOTE=1
|
||||
if [ "${{SUBMIT_REMOTE:-0}}" = "1" ]; then
|
||||
@@ -936,10 +954,39 @@ def apply_to_repo(repo_dir: Path, out_dir: Path, entries: list[dict], branch_nam
|
||||
}
|
||||
|
||||
|
||||
def _resolve_default_paths() -> tuple[Path, Path]:
|
||||
script_p = Path(__file__).resolve()
|
||||
if script_p.parent.name == "scripts" and script_p.parents[1].name == "ingglish-aq-archive":
|
||||
arc_dir = script_p.parents[1]
|
||||
ws_root = arc_dir.parents[1]
|
||||
return arc_dir, ws_root / "hyperdope-ci-build"
|
||||
ws_env = os.environ.get("WORKSPACE_DIR", "").strip()
|
||||
if ws_env:
|
||||
ws_root = Path(ws_env).resolve()
|
||||
elif Path("/workspace/ingglish-hyperdope-gematria").exists():
|
||||
ws_root = Path("/workspace")
|
||||
else:
|
||||
ws_root = Path("/var/lib/ingglish-exegesis/workspace")
|
||||
return ws_root / "ingglish-hyperdope-gematria" / "ingglish-aq-archive", ws_root / "hyperdope-ci-build"
|
||||
|
||||
|
||||
def _resolve_archive_repo_dir(archive_dir: Path, out_dir: Path) -> Path:
|
||||
arc_res = archive_dir.resolve()
|
||||
if arc_res.name == "ingglish-aq-archive" and arc_res.parent.is_dir():
|
||||
return arc_res.parent
|
||||
if (arc_res.parent / "ingglish-aq-archive").is_dir():
|
||||
return arc_res.parent
|
||||
ws_env = os.environ.get("WORKSPACE_DIR", "").strip()
|
||||
if ws_env and (Path(ws_env) / "ingglish-hyperdope-gematria").is_dir():
|
||||
return (Path(ws_env) / "ingglish-hyperdope-gematria").resolve()
|
||||
return out_dir.resolve()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
default_arc, default_out = _resolve_default_paths()
|
||||
parser = argparse.ArgumentParser(description="CI & PR Provisioning Pipeline for Ingglish -> hyperdope-gematria.")
|
||||
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("--archive-dir", default=str(default_arc), help="Path to Ingglish AQ archive")
|
||||
parser.add_argument("--out-dir", default=str(default_out), 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")
|
||||
parser.add_argument("--apply-repo", action="store_true", help="Apply changes and create git commit in --repo-dir")
|
||||
@@ -951,6 +998,7 @@ def main() -> int:
|
||||
archive_dir = Path("/workspace/ingglish-aq-archive")
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive_repo_dir = _resolve_archive_repo_dir(archive_dir, out_dir)
|
||||
|
||||
entries, stats = extract_archive_corpus(archive_dir, max_tier=args.tier)
|
||||
|
||||
@@ -965,13 +1013,19 @@ def main() -> int:
|
||||
|
||||
docs_info = {}
|
||||
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/ingglish-hyperdope-gematria/ONBOARDING-INGGLISH-AQ.md")
|
||||
ws_pdf = Path("/workspace/ingglish-hyperdope-gematria/ONBOARDING-INGGLISH-AQ.pdf")
|
||||
docs_sub = out_dir / "docs"
|
||||
docs_sub.mkdir(parents=True, exist_ok=True)
|
||||
(docs_sub / "ONBOARDING-INGGLISH-AQ.md").write_text(ONBOARDING_MD_CONTENT, encoding="utf-8")
|
||||
if not (out_dir / ".git").exists():
|
||||
(out_dir / "ONBOARDING-INGGLISH-AQ.md").write_text(ONBOARDING_MD_CONTENT, encoding="utf-8")
|
||||
ws_md = archive_repo_dir / "ONBOARDING-INGGLISH-AQ.md"
|
||||
ws_pdf = archive_repo_dir / "ONBOARDING-INGGLISH-AQ.pdf"
|
||||
ws_md.parent.mkdir(parents=True, exist_ok=True)
|
||||
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")
|
||||
out_pdf = out_dir / "ONBOARDING-INGGLISH-AQ.pdf"
|
||||
if out_pdf.resolve() != ws_pdf.resolve():
|
||||
build_onboarding_pdf(out_pdf)
|
||||
docs_info = {
|
||||
"markdown_path": str(ws_md),
|
||||
"pdf_path": str(ws_pdf),
|
||||
|
||||
@@ -1,715 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
collect_news_aq.py
|
||||
Deterministic pre-collection script for current-events-isopsephic-exegesis.
|
||||
|
||||
Responsibilities:
|
||||
1. Env TZ & UTC Rollover Resolution:
|
||||
- Captures the incoming OS environment TZ (e.g., America/New_York / EST UTC-05:00 vs UTC).
|
||||
- Pins internal process clock via os.environ["TZ"] = "UTC" and time.tzset() so all
|
||||
calendar math operates strictly in GMT/UTC.
|
||||
- Implements the Wikipedia Portal:Current_events 00:00 GMT Boundary Paradox rule:
|
||||
when executed in the midnight rollover window (00:00-05:59 UTC) or with --mode closing-bell,
|
||||
targets the just-concluded UTC date (now_utc - 24h); otherwise targets the active UTC date
|
||||
while sampling both dates for cross-day continuity deduplication.
|
||||
2. Concurrent Multi-Source Feed Harvest:
|
||||
- Wikipedia Portal:Current_events (MediaWiki parse API + HTML fallback)
|
||||
- BBC News (Direct HTML + BBC RSS feed)
|
||||
- Associated Press / AP News (Direct HTML + Google News AP RSS mirror for WAF resiliency)
|
||||
3. Continuity & Carryover Deduplication:
|
||||
- Reads existing /workspace/ingglish-aq-archive/*-dossier-news-*.md files to flag
|
||||
carryover headlines and already-analyzed stories.
|
||||
4. Deterministic Ingglish Translation & Dual Base-36 AQ Computation:
|
||||
- Batch-translates all headlines and extracted candidate entities via the official
|
||||
Node.js `ingglish` package (CMU Pronouncing Dictionary).
|
||||
- Computes English AQ, Ingglish AQ, prime indices ([Nth PRIME]), and full prime factorizations.
|
||||
- Automatically detects:
|
||||
* Twin-Prime Headlines (both English AQ and Ingglish AQ are prime)
|
||||
* Shared Prime Factor Attractors across headlines (p >= 11)
|
||||
* Cross-Story Ingglish AQ Collisions (Story A Entity == Story B Entity == N)
|
||||
* English-to-Ingglish Isometric Locks (AQ(Eng) == AQ(Ing))
|
||||
"""
|
||||
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/collect_news_aq.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import glob
|
||||
import html as html_lib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ET
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Capture initial caller environment TZ before pinning to UTC
|
||||
CALLER_ENV_TZ = os.environ.get("TZ", "<unset>")
|
||||
CALLER_TZNAME_BEFORE = time.tzname
|
||||
|
||||
# Strictly enforce UTC/GMT inside the collector
|
||||
os.environ["TZ"] = "UTC"
|
||||
if hasattr(time, "tzset"):
|
||||
time.tzset()
|
||||
|
||||
|
||||
def compute_aq(text: str) -> int:
|
||||
"""Standard Base-36 Alphanumeric Qabbala: 0-9 = 0-9, A-Z = 10-35."""
|
||||
total = 0
|
||||
for ch in text.lower():
|
||||
if "0" <= ch <= "9":
|
||||
total += ord(ch) - ord("0")
|
||||
elif "a" <= ch <= "z":
|
||||
total += ord(ch) - ord("a") + 10
|
||||
return total
|
||||
|
||||
|
||||
def build_primes(limit: int = 10000) -> tuple[set[int], dict[int, int]]:
|
||||
"""Return prime set and 1-based prime index lookup {prime: nth_index}."""
|
||||
sieve = [True] * (limit + 1)
|
||||
sieve[0] = sieve[1] = False
|
||||
for i in range(2, int(math.isqrt(limit)) + 1):
|
||||
if sieve[i]:
|
||||
for j in range(i * i, limit + 1, i):
|
||||
sieve[j] = False
|
||||
prime_set = set()
|
||||
prime_index = {}
|
||||
idx = 0
|
||||
for num, is_p in enumerate(sieve):
|
||||
if is_p:
|
||||
idx += 1
|
||||
prime_set.add(num)
|
||||
prime_index[num] = idx
|
||||
return prime_set, prime_index
|
||||
|
||||
|
||||
PRIME_SET, PRIME_INDEX = build_primes(20000)
|
||||
|
||||
|
||||
def is_prime(n: int) -> bool:
|
||||
if n < 2:
|
||||
return False
|
||||
if n <= 20000:
|
||||
return n in PRIME_SET
|
||||
if n % 2 == 0 or n % 3 == 0:
|
||||
return False
|
||||
r = int(math.isqrt(n))
|
||||
f = 5
|
||||
while f <= r:
|
||||
if n % f == 0 or n % (f + 2) == 0:
|
||||
return False
|
||||
f += 6
|
||||
return True
|
||||
|
||||
|
||||
def prime_factors(n: int) -> dict[int, int]:
|
||||
"""Return prime factorization as {prime: exponent}."""
|
||||
factors: dict[int, int] = {}
|
||||
if n < 2:
|
||||
return factors
|
||||
d = 2
|
||||
temp = n
|
||||
while d * d <= temp:
|
||||
while temp % d == 0:
|
||||
factors[d] = factors.get(d, 0) + 1
|
||||
temp //= d
|
||||
d += 1 if d == 2 else 2
|
||||
if temp > 1:
|
||||
factors[temp] = factors.get(temp, 0) + 1
|
||||
return factors
|
||||
|
||||
|
||||
def format_factorization(n: int) -> str:
|
||||
if n < 2:
|
||||
return str(n)
|
||||
if is_prime(n):
|
||||
idx = PRIME_INDEX.get(n)
|
||||
return f"{n} [PRIME #{idx}]" if idx else f"{n} [PRIME]"
|
||||
f = prime_factors(n)
|
||||
parts = []
|
||||
superscripts = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
|
||||
for p in sorted(f.keys()):
|
||||
exp = f[p]
|
||||
if exp == 1:
|
||||
parts.append(str(p))
|
||||
else:
|
||||
parts.append(f"{p}{str(exp).translate(superscripts)}")
|
||||
return " × ".join(parts)
|
||||
|
||||
|
||||
def resolve_target_dates(
|
||||
now_utc: datetime.datetime,
|
||||
explicit_date: str | None = None,
|
||||
mode: str = "auto",
|
||||
archive_dir: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Resolve target UTC date paying strict attention to the 00:00 GMT boundary paradox.
|
||||
- At 00:00 GMT (00:00-05:59 UTC) or mode='closing-bell', target_date is (now_utc - 24h)
|
||||
because Wikipedia Portal:Current_events for the brand-new UTC day is empty at 00:00:00 GMT.
|
||||
- If archive_dir contains prior dated dossiers with a 1-day gap before yesterday_str,
|
||||
auto-selects the earliest missing recent UTC date when explicit_date is omitted.
|
||||
- In mode='live' or when now_utc.hour >= 6, target_date is now_utc.strftime('%Y-%m-%d'),
|
||||
while also retaining yesterday_utc for Wikipedia completeness.
|
||||
"""
|
||||
today_str = now_utc.strftime("%Y-%m-%d")
|
||||
yesterday_dt = now_utc - datetime.timedelta(days=1)
|
||||
yesterday_str = yesterday_dt.strftime("%Y-%m-%d")
|
||||
|
||||
if explicit_date:
|
||||
target_dt = datetime.datetime.strptime(explicit_date, "%Y-%m-%d").replace(
|
||||
tzinfo=datetime.timezone.utc
|
||||
)
|
||||
target_str = explicit_date
|
||||
reason = "explicit_override"
|
||||
elif mode == "closing-bell" or (mode == "auto" and now_utc.hour < 6):
|
||||
target_dt = yesterday_dt
|
||||
target_str = yesterday_str
|
||||
reason = "00:00_GMT_closing_bell_paradox_rule (now_utc - 24h)"
|
||||
if archive_dir and os.path.isdir(archive_dir):
|
||||
existing_dates = {
|
||||
m.group(1)
|
||||
for fn in os.listdir(archive_dir)
|
||||
if (m := re.search(r"dossier-news-(\d{4}-\d{2}-\d{2})\.md$", fn))
|
||||
}
|
||||
two_days_ago_dt = now_utc - datetime.timedelta(days=2)
|
||||
two_days_ago_str = two_days_ago_dt.strftime("%Y-%m-%d")
|
||||
if two_days_ago_str not in existing_dates:
|
||||
target_dt = two_days_ago_dt
|
||||
target_str = two_days_ago_str
|
||||
reason = "00:00_GMT_closing_bell_backfill (now_utc - 48h missing from archive)"
|
||||
else:
|
||||
target_dt = now_utc
|
||||
target_str = today_str
|
||||
reason = "live_utc_day_active (now_utc.hour >= 6)"
|
||||
|
||||
# Wikipedia Portal anchor IDs use both zero-padded and unpadded day numbers
|
||||
wiki_month = target_dt.strftime("%B")
|
||||
wiki_year = target_dt.strftime("%Y")
|
||||
wiki_day_unpadded = str(target_dt.day)
|
||||
wiki_day_padded = target_dt.strftime("%d")
|
||||
|
||||
est_tz = datetime.timezone(datetime.timedelta(hours=-5), name="EST")
|
||||
now_est = now_utc.astimezone(est_tz)
|
||||
|
||||
return {
|
||||
"caller_env_tz": CALLER_ENV_TZ,
|
||||
"caller_tzname_before": list(CALLER_TZNAME_BEFORE),
|
||||
"enforced_process_tz": os.environ.get("TZ"),
|
||||
"enforced_tzname": list(time.tzname),
|
||||
"now_utc_iso": now_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"now_est_iso": now_est.strftime("%Y-%m-%dT%H:%M:%S-05:00"),
|
||||
"cron_schedule_utc": "0 0 * * * (00:00 GMT/UTC == 19:00 EST prior calendar evening)",
|
||||
"target_date_utc": target_str,
|
||||
"today_utc": today_str,
|
||||
"yesterday_utc": yesterday_str,
|
||||
"resolution_mode": reason,
|
||||
"wikipedia_target_anchors": [
|
||||
f"{wiki_year}_{wiki_month}_{wiki_day_unpadded}",
|
||||
f"{wiki_year}_{wiki_month}_{wiki_day_padded}",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def http_get(url: str, timeout: int = 15) -> str:
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) HermesAgent-Isopsephy/1.0",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8",
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return resp.read().decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def fetch_wikipedia_current_events(date_info: dict[str, Any]) -> list[dict[str, str]]:
|
||||
"""Fetch Wikipedia Portal:Current_events and extract items for target_date and today_utc."""
|
||||
results: list[dict[str, str]] = []
|
||||
html_text = ""
|
||||
try:
|
||||
api_url = "https://en.wikipedia.org/w/api.php?action=parse&page=Portal:Current_events&prop=text&format=json"
|
||||
raw_json = json.loads(http_get(api_url))
|
||||
html_text = html_lib.unescape(raw_json.get("parse", {}).get("text", {}).get("*", ""))
|
||||
except Exception:
|
||||
try:
|
||||
html_text = html_lib.unescape(http_get("https://en.wikipedia.org/wiki/Portal:Current_events"))
|
||||
except Exception:
|
||||
return results
|
||||
|
||||
# Check both target date and today/yesterday sections
|
||||
candidate_anchors = list(date_info["wikipedia_target_anchors"])
|
||||
today_dt = datetime.datetime.strptime(date_info["today_utc"], "%Y-%m-%d")
|
||||
yest_dt = datetime.datetime.strptime(date_info["yesterday_utc"], "%Y-%m-%d")
|
||||
for dt in (today_dt, yest_dt):
|
||||
for a in (
|
||||
f"{dt.strftime('%Y')}_{dt.strftime('%B')}_{dt.day}",
|
||||
f"{dt.strftime('%Y')}_{dt.strftime('%B')}_{dt.strftime('%d')}",
|
||||
):
|
||||
if a not in candidate_anchors:
|
||||
candidate_anchors.append(a)
|
||||
|
||||
seen = set()
|
||||
for anchor in candidate_anchors:
|
||||
m = re.search(rf'id="{re.escape(anchor)}".*?(?=id="202\d_|$)', html_text, re.S)
|
||||
if not m:
|
||||
continue
|
||||
section_html = m.group(0)[:15000]
|
||||
for li in re.findall(r"<li[^>]*>(.*?)</li>", section_html, re.S):
|
||||
clean = html_lib.unescape(re.sub(r"<[^>]+>", " ", li))
|
||||
clean = re.sub(r"\s+", " ", clean).strip()
|
||||
clean_headline = re.sub(r"(?:\s*\([^)]+\))+\s*$", "", clean).strip()
|
||||
if 30 <= len(clean_headline) <= 260 and clean_headline not in seen:
|
||||
seen.add(clean_headline)
|
||||
results.append(
|
||||
{
|
||||
"source": f"Wikipedia ({anchor})",
|
||||
"headline": clean_headline,
|
||||
}
|
||||
)
|
||||
return results[:18]
|
||||
|
||||
|
||||
def fetch_bbc_news() -> list[dict[str, str]]:
|
||||
"""Fetch BBC News headlines from HTML and RSS."""
|
||||
results: list[dict[str, str]] = []
|
||||
seen = set()
|
||||
try:
|
||||
rss_xml = http_get("https://feeds.bbci.co.uk/news/rss.xml")
|
||||
root = ET.fromstring(rss_xml)
|
||||
for item in root.findall(".//item")[:15]:
|
||||
title = (item.findtext("title") or "").strip()
|
||||
if title and len(title) > 18 and title not in seen:
|
||||
seen.add(title)
|
||||
results.append({"source": "BBC News RSS", "headline": title})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
bbc_html = http_get("https://www.bbc.com/news")
|
||||
for h in re.findall(r"<h[23][^>]*>(.*?)</h[23]>", bbc_html, re.S):
|
||||
title = html_lib.unescape(re.sub(r"<[^>]+>", "", h)).strip()
|
||||
title = re.sub(r"\s+", " ", title)
|
||||
if (
|
||||
20 <= len(title) <= 180
|
||||
and title not in seen
|
||||
and not title.lower().startswith(("the bbc is", "more to explore", "most read", "most watched"))
|
||||
):
|
||||
seen.add(title)
|
||||
results.append({"source": "BBC News Portal", "headline": title})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return results[:20]
|
||||
|
||||
|
||||
def fetch_ap_news() -> list[dict[str, str]]:
|
||||
"""Fetch AP News headlines via direct portal with Google News AP RSS mirror fallback."""
|
||||
results: list[dict[str, str]] = []
|
||||
seen = set()
|
||||
try:
|
||||
ap_html = http_get("https://apnews.com/", timeout=10)
|
||||
for h in re.findall(r"<h[23][^>]*>(.*?)</h[23]>", ap_html, re.S):
|
||||
title = html_lib.unescape(re.sub(r"<[^>]+>", "", h)).strip()
|
||||
title = re.sub(r"\s+", " ", title)
|
||||
if 20 <= len(title) <= 180 and title not in seen:
|
||||
seen.add(title)
|
||||
results.append({"source": "AP News Portal", "headline": title})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if len(results) < 5:
|
||||
try:
|
||||
rss_url = "https://news.google.com/rss/search?q=site:apnews.com+when:1d&hl=en-US&gl=US&ceid=US:en"
|
||||
rss_xml = http_get(rss_url, timeout=12)
|
||||
root = ET.fromstring(rss_xml)
|
||||
for item in root.findall(".//item")[:18]:
|
||||
raw_title = (item.findtext("title") or "").strip()
|
||||
title = raw_title.rsplit(" - AP News", 1)[0].strip()
|
||||
if 20 <= len(title) <= 180 and title not in seen:
|
||||
seen.add(title)
|
||||
results.append({"source": "AP News Wire", "headline": title})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return results[:18]
|
||||
|
||||
|
||||
def load_prior_dossiers(archive_dir: str) -> dict[str, Any]:
|
||||
"""Scan existing *-dossier-news-*.md files for continuity deduplication."""
|
||||
pattern = os.path.join(archive_dir, "*-dossier-news-*.md")
|
||||
files = sorted(glob.glob(pattern))
|
||||
prior_entities = set()
|
||||
for fpath in files:
|
||||
try:
|
||||
text = Path(fpath).read_text(encoding="utf-8")
|
||||
for m in re.finditer(r"`([^`]+)`\s*\(\"([^\"]+)\"\)", text):
|
||||
prior_entities.add(m.group(1).strip().lower())
|
||||
prior_entities.add(m.group(2).strip().lower())
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"existing_news_dossiers": [os.path.basename(f) for f in files],
|
||||
"prior_phrase_count": len(prior_entities),
|
||||
"prior_sample_tokens": sorted(list(prior_entities))[:25],
|
||||
}
|
||||
|
||||
|
||||
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';
|
||||
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
||||
const out = {};
|
||||
await translate('hello');
|
||||
for (const s of input) {
|
||||
try {
|
||||
out[s] = (await translate(s)).toLowerCase();
|
||||
} catch (e) {
|
||||
out[s] = s.toLowerCase();
|
||||
}
|
||||
}
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
"""
|
||||
proc = subprocess.run(
|
||||
["node", "--input-type=module", "-e", node_code],
|
||||
input=json.dumps(strings),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=workdir,
|
||||
timeout=30,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"Node ingglish translation failed: {proc.stderr}")
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def extract_candidate_entities(headlines: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||
"""Extract proper nouns, key thematic words, and multi-word entities from harvested headlines."""
|
||||
stopwords = {
|
||||
"the", "and", "for", "with", "that", "this", "from", "after", "before",
|
||||
"over", "under", "into", "onto", "near", "amid", "what", "when", "where",
|
||||
"which", "while", "will", "have", "has", "had", "were", "been", "says",
|
||||
"said", "tell", "tells", "told", "more", "most", "some", "many", "other",
|
||||
"than", "then", "they", "their", "them", "there", "here", "about", "could",
|
||||
"would", "should", "least", "first", "second", "third", "including",
|
||||
}
|
||||
candidates: list[dict[str, str]] = []
|
||||
seen_lower = set()
|
||||
|
||||
for idx, item in enumerate(headlines):
|
||||
hl = item["headline"]
|
||||
src = item["source"]
|
||||
story_tag = f"H{idx+1:02d}:{src}"
|
||||
|
||||
# Extract capitalized proper-noun sequences (1 to 2 words)
|
||||
for m in re.finditer(r"\b([A-Z][a-zA-Z0-9'-]{2,}(?:\s+[A-Z][a-zA-Z0-9'-]{2,})?)\b", hl):
|
||||
phrase = m.group(1).strip("'-")
|
||||
low = phrase.lower()
|
||||
if low not in stopwords and len(low) >= 3 and low not in seen_lower:
|
||||
seen_lower.add(low)
|
||||
candidates.append({"eng": phrase, "story": story_tag, "headline": hl})
|
||||
|
||||
# Extract individual content words
|
||||
for m in re.finditer(r"\b([a-zA-Z]{4,})\b", hl):
|
||||
word = m.group(1)
|
||||
low = word.lower()
|
||||
if low not in stopwords and low not in seen_lower:
|
||||
seen_lower.add(low)
|
||||
candidates.append({"eng": low, "story": story_tag, "headline": hl})
|
||||
|
||||
return candidates[:320]
|
||||
|
||||
|
||||
_ONES = [
|
||||
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
|
||||
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
|
||||
"seventeen", "eighteen", "nineteen",
|
||||
]
|
||||
_TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
||||
_UNIT_WORDS = {
|
||||
"tn": "trillion", "trillion": "trillion",
|
||||
"bn": "billion", "b": "billion", "billion": "billion",
|
||||
"m": "million", "mn": "million", "million": "million",
|
||||
"k": "thousand", "thousand": "thousand",
|
||||
"%": "percent",
|
||||
}
|
||||
|
||||
|
||||
def _int_to_words(n: int) -> str:
|
||||
if n < 0:
|
||||
return "minus " + _int_to_words(-n)
|
||||
if n < 20:
|
||||
return _ONES[n]
|
||||
if n < 100:
|
||||
t, r = divmod(n, 10)
|
||||
return _TENS[t] + ("" if r == 0 else " " + _ONES[r])
|
||||
if n < 1000:
|
||||
h, r = divmod(n, 100)
|
||||
return _ONES[h] + " hundred" + ("" if r == 0 else " " + _int_to_words(r))
|
||||
for scale_val, scale_name in ((1_000_000_000_000, "trillion"), (1_000_000_000, "billion"), (1_000_000, "million"), (1000, "thousand")):
|
||||
if n >= scale_val:
|
||||
q, r = divmod(n, scale_val)
|
||||
return _int_to_words(q) + " " + scale_name + ("" if r == 0 else " " + _int_to_words(r))
|
||||
return str(n)
|
||||
|
||||
|
||||
def token_to_spoken_english(raw_tok: str) -> str:
|
||||
"""Convert a quantitative token like '$11B', '12,000', '$1.5tn', or '481' into spoken English words."""
|
||||
s = raw_tok.strip()
|
||||
m = re.match(r"^([$€£])?(\d[\d,]*)(?:\.(\d+))?([a-zA-Z%]+)?$", s)
|
||||
if not m:
|
||||
return s.lower()
|
||||
_curr, int_part, dec_part, unit_part = m.groups()
|
||||
int_val = int(int_part.replace(",", ""))
|
||||
words = [_int_to_words(int_val)]
|
||||
if dec_part:
|
||||
words.append("point")
|
||||
for ch in dec_part:
|
||||
words.append(_ONES[int(ch)])
|
||||
if unit_part:
|
||||
u_low = unit_part.lower()
|
||||
if u_low in _UNIT_WORDS:
|
||||
words.append(_UNIT_WORDS[u_low])
|
||||
else:
|
||||
words.append(u_low)
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def extract_quantitative_anchors(headlines: list[dict[str, str]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Non-destructively extract quantitative/numeric tokens and their entity context into a
|
||||
parallel sidecar stream (`quantitative_anchors`), leaving `entities` 100% lexical.
|
||||
"""
|
||||
quant_items: list[dict[str, Any]] = []
|
||||
seen_pairs = set()
|
||||
quant_re = re.compile(r"(?<![a-zA-Z0-9])([$€£]?\d[\d,]*(?:\.\d+)?(?:tn|bn|mn|b|m|k|%)?)\b", re.I)
|
||||
|
||||
for idx, item in enumerate(headlines):
|
||||
hl = item["headline"]
|
||||
src = item["source"]
|
||||
story_tag = f"H{idx+1:02d}:{src}"
|
||||
# Find primary capitalized entity in the headline for context pairing
|
||||
ent_matches = [
|
||||
m.group(1).strip("'-")
|
||||
for m in re.finditer(r"\b([A-Z][a-zA-Z0-9'-]{1,}(?:\s+[A-Z][a-zA-Z0-9'-]{2,})?)\b", hl)
|
||||
if m.group(1).lower() not in {"the", "and", "for", "with", "after", "from", "into", "over", "why", "how"}
|
||||
]
|
||||
primary_entity = ent_matches[0] if ent_matches else f"H{idx+1:02d}"
|
||||
|
||||
for qm in quant_re.finditer(hl):
|
||||
q_tok = qm.group(1)
|
||||
# Skip bare calendar year 2026 unless attached to currency/unit
|
||||
if q_tok in {"2025", "2026", "2027"}:
|
||||
continue
|
||||
key = (primary_entity.lower(), q_tok.lower())
|
||||
if key in seen_pairs:
|
||||
continue
|
||||
seen_pairs.add(key)
|
||||
spoken_eng = token_to_spoken_english(q_tok)
|
||||
quant_items.append(
|
||||
{
|
||||
"story": story_tag,
|
||||
"entity_context": primary_entity,
|
||||
"q_digit": q_tok,
|
||||
"q_spoken_eng": spoken_eng,
|
||||
"headline": hl,
|
||||
}
|
||||
)
|
||||
return quant_items[:80]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Pre-collect current events & Ingglish AQ matrix.")
|
||||
parser.add_argument("--date", default=None, help="Explicit YYYY-MM-DD target date override.")
|
||||
parser.add_argument(
|
||||
"--mode",
|
||||
choices=["auto", "closing-bell", "live"],
|
||||
default="auto",
|
||||
help="Date resolution mode (auto uses closing-bell at 00:00-05:59 UTC).",
|
||||
)
|
||||
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, archive_dir=args.archive_dir)
|
||||
|
||||
# Fetch all 3 portals concurrently
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
fut_wiki = pool.submit(fetch_wikipedia_current_events, date_info)
|
||||
fut_bbc = pool.submit(fetch_bbc_news)
|
||||
fut_ap = pool.submit(fetch_ap_news)
|
||||
wiki_items = fut_wiki.result()
|
||||
bbc_items = fut_bbc.result()
|
||||
ap_items = fut_ap.result()
|
||||
|
||||
all_headlines = wiki_items + bbc_items + ap_items
|
||||
candidates = extract_candidate_entities(all_headlines)
|
||||
quant_candidates = extract_quantitative_anchors(all_headlines)
|
||||
|
||||
strings_to_translate = list(
|
||||
{h["headline"] for h in all_headlines}
|
||||
| {c["eng"] for c in candidates}
|
||||
| {qc["q_spoken_eng"] for qc in quant_candidates}
|
||||
)
|
||||
translations = batch_translate_ingglish(strings_to_translate, workdir=args.workdir)
|
||||
|
||||
# Compute headline AQ & factorizations
|
||||
enriched_headlines = []
|
||||
twin_prime_headlines = []
|
||||
factor_buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
|
||||
for h in all_headlines:
|
||||
raw = h["headline"]
|
||||
ing = translations.get(raw, raw.lower())
|
||||
eng_aq = compute_aq(raw)
|
||||
ing_aq = compute_aq(ing)
|
||||
eng_prime = is_prime(eng_aq)
|
||||
ing_prime = is_prime(ing_aq)
|
||||
entry = {
|
||||
"source": h["source"],
|
||||
"headline_eng": raw,
|
||||
"headline_ing": ing,
|
||||
"eng_aq": eng_aq,
|
||||
"ing_aq": ing_aq,
|
||||
"eng_factorization": format_factorization(eng_aq),
|
||||
"ing_factorization": format_factorization(ing_aq),
|
||||
"twin_prime": bool(eng_prime and ing_prime),
|
||||
}
|
||||
enriched_headlines.append(entry)
|
||||
if eng_prime and ing_prime:
|
||||
twin_prime_headlines.append(entry)
|
||||
|
||||
for p in prime_factors(ing_aq).keys():
|
||||
if p >= 13:
|
||||
factor_buckets.setdefault(p, []).append(entry)
|
||||
|
||||
shared_prime_attractors = {
|
||||
str(p): [
|
||||
{
|
||||
"source": item["source"],
|
||||
"headline_eng": item["headline_eng"],
|
||||
"ing_aq": item["ing_aq"],
|
||||
"ing_factorization": item["ing_factorization"],
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
for p, items in sorted(factor_buckets.items(), key=lambda kv: -kv[0])
|
||||
if len(items) >= 2
|
||||
}
|
||||
|
||||
# Compute candidate entity AQ, collisions, and isometric locks
|
||||
enriched_entities = []
|
||||
aq_groups: dict[int, list[dict[str, Any]]] = {}
|
||||
isometric_locks = []
|
||||
|
||||
for c in candidates:
|
||||
eng = c["eng"]
|
||||
ing = translations.get(eng, eng.lower())
|
||||
eng_aq = compute_aq(eng)
|
||||
ing_aq = compute_aq(ing)
|
||||
p_idx = PRIME_INDEX.get(ing_aq)
|
||||
ent = {
|
||||
"eng": eng,
|
||||
"ing": ing,
|
||||
"eng_aq": eng_aq,
|
||||
"ing_aq": ing_aq,
|
||||
"is_prime": p_idx is not None,
|
||||
"prime_rank": p_idx,
|
||||
"isometric": eng_aq == ing_aq,
|
||||
"story": c["story"],
|
||||
}
|
||||
enriched_entities.append(ent)
|
||||
aq_groups.setdefault(ing_aq, []).append(ent)
|
||||
if eng_aq == ing_aq:
|
||||
isometric_locks.append(ent)
|
||||
|
||||
cross_story_collisions = {}
|
||||
for aq_val, group in sorted(aq_groups.items(), key=lambda kv: -kv[0]):
|
||||
unique_ings = {g["ing"] for g in group}
|
||||
unique_stories = {g["story"] for g in group}
|
||||
if len(unique_ings) >= 2 and len(unique_stories) >= 2:
|
||||
p_idx = PRIME_INDEX.get(aq_val)
|
||||
cross_story_collisions[str(aq_val)] = {
|
||||
"aq": aq_val,
|
||||
"prime_rank": p_idx,
|
||||
"factorization": format_factorization(aq_val),
|
||||
"members": [
|
||||
{"eng": g["eng"], "ing": g["ing"], "story": g["story"]}
|
||||
for g in group
|
||||
],
|
||||
}
|
||||
|
||||
continuity_info = load_prior_dossiers(args.archive_dir)
|
||||
|
||||
enriched_quant_anchors = []
|
||||
for qc in quant_candidates:
|
||||
sp_eng = qc["q_spoken_eng"]
|
||||
sp_ing = translations.get(sp_eng, sp_eng.lower())
|
||||
d_aq = compute_aq(qc["q_digit"])
|
||||
s_aq = compute_aq(sp_ing)
|
||||
enriched_quant_anchors.append(
|
||||
{
|
||||
"story": qc["story"],
|
||||
"entity_context": qc["entity_context"],
|
||||
"q_digit": qc["q_digit"],
|
||||
"q_digit_aq": d_aq,
|
||||
"q_spoken_eng": sp_eng,
|
||||
"q_spoken_ing": sp_ing,
|
||||
"q_spoken_aq": s_aq,
|
||||
"spoken_prime_rank": PRIME_INDEX.get(s_aq),
|
||||
"headline": qc["headline"],
|
||||
}
|
||||
)
|
||||
|
||||
payload = {
|
||||
"temporal_metadata": date_info,
|
||||
"continuity": continuity_info,
|
||||
"counts": {
|
||||
"wikipedia_headlines": len(wiki_items),
|
||||
"bbc_headlines": len(bbc_items),
|
||||
"ap_headlines": len(ap_items),
|
||||
"total_headlines": len(enriched_headlines),
|
||||
"candidate_entities": len(enriched_entities),
|
||||
"quantitative_anchors": len(enriched_quant_anchors),
|
||||
"twin_prime_headlines": len(twin_prime_headlines),
|
||||
"cross_story_collision_classes": len(cross_story_collisions),
|
||||
"isometric_locks": len(isometric_locks),
|
||||
},
|
||||
"twin_prime_headlines": twin_prime_headlines,
|
||||
"shared_prime_attractors": shared_prime_attractors,
|
||||
"cross_story_collisions": cross_story_collisions,
|
||||
"isometric_locks": isometric_locks,
|
||||
"quantitative_anchors": enriched_quant_anchors,
|
||||
"headlines": enriched_headlines,
|
||||
"entities": enriched_entities,
|
||||
}
|
||||
|
||||
out_json = json.dumps(payload, indent=2, ensure_ascii=False)
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(out_json, encoding="utf-8")
|
||||
print(out_json)
|
||||
return 0
|
||||
_SCRIPT_NAME = "collect_news_aq.py"
|
||||
|
||||
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -1,361 +1,27 @@
|
||||
#!/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)
|
||||
*/
|
||||
|
||||
// Thin delegator to canonical ingglish-aq-archive/scripts/evaluate_aq.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { fileURLToPath, 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");
|
||||
}
|
||||
const here = fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
const ws = process.env.WORKSPACE_DIR || "/workspace";
|
||||
const candidates = [
|
||||
path.resolve(path.dirname(here), "../../../ingglish-aq-archive/scripts/evaluate_aq.mjs"),
|
||||
path.resolve(path.dirname(here), "../../../../ingglish-aq-archive/scripts/evaluate_aq.mjs"),
|
||||
path.join(ws, "ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/evaluate_aq.mjs"),
|
||||
path.join(ws, "ingglish-aq-archive/scripts/evaluate_aq.mjs"),
|
||||
"/usr/libexec/ingglish-exegesis/scripts/evaluate_aq.mjs",
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
let target = null;
|
||||
for (const c of candidates) {
|
||||
if (fs.existsSync(c) && fs.realpathSync(c) !== here) {
|
||||
target = c;
|
||||
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)";
|
||||
if (!target) {
|
||||
throw new Error("Canonical evaluate_aq.mjs not found");
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
await import(pathToFileURL(target).href);
|
||||
@@ -1,516 +1,30 @@
|
||||
#!/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
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/generate_aq_tier_list.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from xml.sax.saxutils import escape
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
_SCRIPT_NAME = "generate_aq_tier_list.py"
|
||||
|
||||
|
||||
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,
|
||||
header_title: str = "INGGLISH AQ ARCHIVE — MASTER BIDIRECTIONAL EVALUATION TIER LIST (S+ TO F)",
|
||||
header_subtitle: str | None = None,
|
||||
footer_text: str | None = None,
|
||||
write_atomic: bool = True,
|
||||
custom_tier_defs: list | None = None,
|
||||
):
|
||||
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)
|
||||
|
||||
default_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).",
|
||||
),
|
||||
]
|
||||
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}")
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -1,253 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
manage_lecture_artifacts.py
|
||||
Deterministic Naming-Convention Validator, Host-Mount Resolver, and .gitignore Manager
|
||||
for the `isopsephic-lecture-synthesis` skill.
|
||||
|
||||
Naming Convention:
|
||||
Stem: lecture-<topic-slug>-ingglish-aq
|
||||
Slug regex: ^[a-z0-9]+(?:-[a-z0-9]+)*$
|
||||
Files:
|
||||
- /workspace/lecture-<topic-slug>-ingglish-aq.md
|
||||
- /workspace/lecture-<topic-slug>-ingglish-aq.mp3
|
||||
- /workspace/lecture-<topic-slug>-ingglish-aq.pdf (optional)
|
||||
"""
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/manage_lecture_artifacts.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
LECTURE_FILE_RE = re.compile(r"^lecture-([a-z0-9]+(?:-[a-z0-9]+)*)-ingglish-aq\.(md|mp3|pdf)$")
|
||||
|
||||
GITIGNORE_HEADER = "# --- Isopsephic Lecture Artifacts (strict naming convention) ---"
|
||||
GITIGNORE_FOOTER = "# --- End Isopsephic Lecture Artifacts ---"
|
||||
_SCRIPT_NAME = "manage_lecture_artifacts.py"
|
||||
|
||||
|
||||
def normalize_slug(raw: str) -> str:
|
||||
"""Normalize arbitrary topic string or filename into canonical <topic-slug>."""
|
||||
s = raw.strip().lower()
|
||||
# Strip directory and extension if a filename was passed
|
||||
s = os.path.basename(s)
|
||||
for ext in (".md", ".mp3", ".pdf"):
|
||||
if s.endswith(ext):
|
||||
s = s[: -len(ext)]
|
||||
if s.startswith("lecture-"):
|
||||
s = s[len("lecture-") :]
|
||||
if s.endswith("-ingglish-aq"):
|
||||
s = s[: -len("-ingglish-aq")]
|
||||
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
|
||||
if not s or not SLUG_RE.fullmatch(s):
|
||||
raise ValueError(f"Cannot normalize '{raw}' into valid kebab-case slug.")
|
||||
return s
|
||||
|
||||
|
||||
def canonical_stem(slug: str) -> str:
|
||||
norm = normalize_slug(slug)
|
||||
return f"lecture-{norm}-ingglish-aq"
|
||||
|
||||
|
||||
def resolve_host_workspace_mount(container_workspace: str = "/workspace/ingglish-hyperdope-gematria") -> str:
|
||||
"""
|
||||
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] == "/workspace":
|
||||
rel = os.path.relpath(container_workspace, "/workspace")
|
||||
return parts[3] if rel == "." else f"{parts[3]}/{rel}"
|
||||
return container_workspace
|
||||
|
||||
|
||||
def update_gitignore(
|
||||
workspace_dir: str,
|
||||
mode: str = "audio-only",
|
||||
slug: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Idempotently add or update the lecture naming-convention block in /workspace/.gitignore.
|
||||
Modes:
|
||||
- audio-only: ignores lecture-*-ingglish-aq.mp3
|
||||
- audio-and-pdf: ignores lecture-*-ingglish-aq.mp3 and lecture-*-ingglish-aq.pdf
|
||||
- all-lecture-files: ignores lecture-*-ingglish-aq.* (.md, .mp3, .pdf)
|
||||
- explicit-slug: ignores lecture-<slug>-ingglish-aq.mp3 (and .md/.pdf if present)
|
||||
"""
|
||||
gitignore_path = Path(workspace_dir) / ".gitignore"
|
||||
existing = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
|
||||
|
||||
if mode == "audio-only":
|
||||
patterns = ["lecture-*-ingglish-aq.mp3"]
|
||||
elif mode == "audio-and-pdf":
|
||||
patterns = ["lecture-*-ingglish-aq.mp3", "lecture-*-ingglish-aq.pdf"]
|
||||
elif mode == "all-lecture-files":
|
||||
patterns = [
|
||||
"lecture-*-ingglish-aq.mp3",
|
||||
"lecture-*-ingglish-aq.md",
|
||||
"lecture-*-ingglish-aq.pdf",
|
||||
]
|
||||
elif mode == "explicit-slug":
|
||||
if not slug:
|
||||
raise ValueError("--slug is required when --gitignore-mode=explicit-slug")
|
||||
stem = canonical_stem(slug)
|
||||
patterns = [f"{stem}.mp3", f"{stem}.pdf"]
|
||||
else:
|
||||
raise ValueError(f"Unsupported mode: {mode}")
|
||||
|
||||
block_lines = [GITIGNORE_HEADER] + patterns + [GITIGNORE_FOOTER]
|
||||
new_block = "\n".join(block_lines)
|
||||
|
||||
block_re = re.compile(
|
||||
rf"{re.escape(GITIGNORE_HEADER)}.*?{re.escape(GITIGNORE_FOOTER)}",
|
||||
re.S,
|
||||
)
|
||||
if block_re.search(existing):
|
||||
updated = block_re.sub(new_block, existing)
|
||||
else:
|
||||
sep = "" if (not existing or existing.endswith("\n")) else "\n"
|
||||
updated = f"{existing}{sep}{new_block}\n"
|
||||
|
||||
changed = updated != existing
|
||||
if changed or not gitignore_path.exists():
|
||||
gitignore_path.write_text(updated, encoding="utf-8")
|
||||
|
||||
return {
|
||||
"gitignore_path": str(gitignore_path),
|
||||
"mode": mode,
|
||||
"patterns_active": patterns,
|
||||
"updated": changed,
|
||||
}
|
||||
|
||||
|
||||
def check_git_ignored(workspace_dir: str, rel_path: str) -> dict[str, Any]:
|
||||
proc = subprocess.run(
|
||||
["git", "check-ignore", "-v", rel_path],
|
||||
cwd=workspace_dir,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
return {
|
||||
"file": rel_path,
|
||||
"ignored": proc.returncode == 0,
|
||||
"rule": proc.stdout.strip() if proc.returncode == 0 else None,
|
||||
}
|
||||
|
||||
|
||||
def audit_workspace_lectures(workspace_dir: str, target_slug: str | None = None) -> dict[str, Any]:
|
||||
ws = Path(workspace_dir)
|
||||
all_lecture_files = sorted(
|
||||
p.name for p in ws.iterdir() if p.is_file() and p.name.startswith("lecture-")
|
||||
)
|
||||
conforming = []
|
||||
non_conforming = []
|
||||
stems: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for fname in all_lecture_files:
|
||||
m = LECTURE_FILE_RE.fullmatch(fname)
|
||||
if not m:
|
||||
non_conforming.append(fname)
|
||||
continue
|
||||
conforming.append(fname)
|
||||
slug_part, ext = m.group(1), m.group(2)
|
||||
stem = f"lecture-{slug_part}-ingglish-aq"
|
||||
info = stems.setdefault(
|
||||
stem,
|
||||
{
|
||||
"slug": slug_part,
|
||||
"stem": stem,
|
||||
"extensions": [],
|
||||
"sizes": {},
|
||||
},
|
||||
)
|
||||
info["extensions"].append(ext)
|
||||
info["sizes"][ext] = (ws / fname).stat().st_size
|
||||
|
||||
target_report = None
|
||||
if target_slug:
|
||||
stem = canonical_stem(target_slug)
|
||||
md_file = ws / f"{stem}.md"
|
||||
mp3_file = ws / f"{stem}.mp3"
|
||||
pdf_file = ws / f"{stem}.pdf"
|
||||
target_report = {
|
||||
"slug": normalize_slug(target_slug),
|
||||
"canonical_stem": stem,
|
||||
"host_tts_output_path": f"{resolve_host_workspace_mount(workspace_dir)}/{stem}.mp3",
|
||||
"container_md_path": str(md_file),
|
||||
"container_mp3_path": str(mp3_file),
|
||||
"md_exists": md_file.exists() and md_file.stat().st_size > 0,
|
||||
"mp3_exists": mp3_file.exists() and mp3_file.stat().st_size > 0,
|
||||
"pdf_exists": pdf_file.exists() and pdf_file.stat().st_size > 0,
|
||||
"stem_match": md_file.stem == mp3_file.stem == stem,
|
||||
"pair_valid": bool(
|
||||
md_file.exists()
|
||||
and mp3_file.exists()
|
||||
and md_file.stat().st_size > 0
|
||||
and mp3_file.stat().st_size > 0
|
||||
and md_file.stem == mp3_file.stem == stem
|
||||
),
|
||||
"git_ignore_mp3": check_git_ignored(workspace_dir, f"{stem}.mp3"),
|
||||
"git_ignore_md": check_git_ignored(workspace_dir, f"{stem}.md"),
|
||||
}
|
||||
|
||||
return {
|
||||
"workspace": workspace_dir,
|
||||
"host_workspace_mount": resolve_host_workspace_mount(workspace_dir),
|
||||
"conforming_files": conforming,
|
||||
"non_conforming_files": non_conforming,
|
||||
"lecture_stems": stems,
|
||||
"target_verification": target_report,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Validate lecture naming conventions and manage .gitignore rules."
|
||||
)
|
||||
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",
|
||||
choices=["none", "audio-only", "audio-and-pdf", "all-lecture-files", "explicit-slug"],
|
||||
default="none",
|
||||
help="Update /workspace/.gitignore using the strict lecture naming convention.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--verify-pair",
|
||||
action="store_true",
|
||||
help="Exit non-zero if the target slug's .md and .mp3 pair is missing or mismatched.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
gitignore_res = None
|
||||
if args.gitignore_mode != "none":
|
||||
gitignore_res = update_gitignore(
|
||||
args.workspace, mode=args.gitignore_mode, slug=args.slug
|
||||
)
|
||||
|
||||
audit = audit_workspace_lectures(args.workspace, target_slug=args.slug)
|
||||
if gitignore_res is not None:
|
||||
audit["gitignore_update"] = gitignore_res
|
||||
|
||||
print(json.dumps(audit, indent=2))
|
||||
|
||||
if args.verify_pair:
|
||||
if not args.slug:
|
||||
sys.stderr.write("ERROR: --verify-pair requires --slug\n")
|
||||
return 2
|
||||
tv = audit.get("target_verification") or {}
|
||||
if not tv.get("pair_valid") or audit.get("non_conforming_files"):
|
||||
return 1
|
||||
return 0
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -1,146 +1,30 @@
|
||||
#!/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"}
|
||||
]
|
||||
}
|
||||
"""
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/pdf_create.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
_SCRIPT_NAME = "pdf_create.py"
|
||||
|
||||
|
||||
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)
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -1,157 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a PDF: per-page text, tables, metadata, or form fields. JSON to stdout."""
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/pdf_read.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
_SCRIPT_NAME = "pdf_read.py"
|
||||
|
||||
|
||||
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
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
@@ -32,8 +32,10 @@ run_checked() {
|
||||
|
||||
SYSCONFIG_FILE="${INGGLISH_SYSCONFIG_FILE:-/etc/sysconfig/ingglish-exegesis}"
|
||||
if [[ -f "${SYSCONFIG_FILE}" ]]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "${SYSCONFIG_FILE}"
|
||||
set +a
|
||||
fi
|
||||
|
||||
TARGET_DATE=""
|
||||
@@ -95,12 +97,24 @@ export TZ="UTC"
|
||||
export FORGE_SSH="${FORGE_SSH:-ssh://git@git.libre.audio:2222/seasharp}"
|
||||
export OPENROUTER_API_URL="${OPENROUTER_API_URL:-https://openrouter.ai/api/v1/chat/completions}"
|
||||
export OPENROUTER_MODEL="${OPENROUTER_MODEL:-google/gemini-2.5-pro}"
|
||||
export GIT_AUTHOR_NAME="${GIT_AUTHOR_NAME:-Hyperstition Studio Exegesis Worker}"
|
||||
export GIT_AUTHOR_EMAIL="${GIT_AUTHOR_EMAIL:-exegesis@hyperstitionstud.io}"
|
||||
export GIT_COMMITTER_NAME="${GIT_COMMITTER_NAME:-${GIT_AUTHOR_NAME}}"
|
||||
export GIT_COMMITTER_EMAIL="${GIT_COMMITTER_EMAIL:-${GIT_AUTHOR_EMAIL}}"
|
||||
|
||||
if [[ -n "${INGGLISH_SSH_KEY_PATH:-}" ]] && [[ -f "${INGGLISH_SSH_KEY_PATH}" ]] && [[ -z "${GIT_SSH_COMMAND:-}" ]]; then
|
||||
export GIT_SSH_COMMAND="ssh -i ${INGGLISH_SSH_KEY_PATH} -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
|
||||
fi
|
||||
|
||||
LOCK_FILE="${INGGLISH_LOCK_FILE:-/tmp/ingglish-exegesis-fedora41.lock}"
|
||||
if [[ -z "${INGGLISH_LOCK_FILE:-}" ]]; then
|
||||
if [[ -d "/var/lib/ingglish-exegesis" ]] && [[ -w "/var/lib/ingglish-exegesis" ]]; then
|
||||
LOCK_FILE="/var/lib/ingglish-exegesis/ingglish-exegesis-fedora41.lock"
|
||||
else
|
||||
LOCK_FILE="${XDG_RUNTIME_DIR:-/tmp}/ingglish-exegesis-fedora41-$(id -u).lock"
|
||||
fi
|
||||
else
|
||||
LOCK_FILE="${INGGLISH_LOCK_FILE}"
|
||||
fi
|
||||
exec 9>"${LOCK_FILE}"
|
||||
if ! flock -n 9; then
|
||||
echo "[SKIP] Another ingglish-exegesis-push run holds ${LOCK_FILE}; exiting cleanly."
|
||||
@@ -114,6 +128,10 @@ if [[ -z "${OPENROUTER_API_KEY:-}" ]] && [[ "${DRY_RUN}" -eq 0 ]] && [[ "${ALLOW
|
||||
fi
|
||||
|
||||
mkdir -p "${WORKSPACE_DIR}"
|
||||
if [[ "${WORKSPACE_DIR}" == "/var/lib/ingglish-exegesis/workspace" ]] && [[ -w "/var/lib/ingglish-exegesis" ]]; then
|
||||
export HOME="/var/lib/ingglish-exegesis"
|
||||
fi
|
||||
cd "${WORKSPACE_DIR}"
|
||||
|
||||
sync_or_clone_repo() {
|
||||
local repo_dir="$1"
|
||||
@@ -169,6 +187,8 @@ fi
|
||||
SCRIPTS_DIR="${ARCHIVE_DIR}/scripts"
|
||||
if [[ ! -d "${SCRIPTS_DIR}" ]] && [[ -d "/usr/libexec/ingglish-exegesis/scripts" ]]; then
|
||||
SCRIPTS_DIR="/usr/libexec/ingglish-exegesis/scripts"
|
||||
elif [[ -d "/usr/libexec/ingglish-exegesis/scripts" ]] && [[ -f "${SCRIPTS_DIR}/ci_provision_ingglish.py" ]] && grep -q 'Path("/workspace/ingglish-hyperdope-gematria/ONBOARDING-INGGLISH-AQ.md")' "${SCRIPTS_DIR}/ci_provision_ingglish.py" 2>&1; then
|
||||
SCRIPTS_DIR="/usr/libexec/ingglish-exegesis/scripts"
|
||||
fi
|
||||
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
@@ -176,7 +196,11 @@ if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
HARVEST_JSON="/tmp/news-aq-harvest-$$.json"
|
||||
if [[ -d "/var/lib/ingglish-exegesis" ]] && [[ -w "/var/lib/ingglish-exegesis" ]]; then
|
||||
HARVEST_JSON="/var/lib/ingglish-exegesis/news-aq-harvest-$$.json"
|
||||
else
|
||||
HARVEST_JSON="${XDG_RUNTIME_DIR:-/tmp}/news-aq-harvest-$(id -u)-$$.json"
|
||||
fi
|
||||
trap 'rm -f "${HARVEST_JSON}"' EXIT
|
||||
|
||||
echo "[3/5] Step A (0 LLM tokens): Harvesting 00:00 UTC news headlines & computing Ingglish Base-36 AQ locks..."
|
||||
@@ -207,12 +231,23 @@ if [[ -d "${CALC_REPO}/.git" ]]; then
|
||||
fi
|
||||
run_checked "ci_provision_ingglish.py" python3 "${SCRIPTS_DIR}/ci_provision_ingglish.py" "${CI_ARGS[@]}"
|
||||
|
||||
if [[ -f "${CALC_REPO}/config.default.js" ]] && [[ ! -f "${CALC_REPO}/config.js" ]]; then
|
||||
cp -f "${CALC_REPO}/config.default.js" "${CALC_REPO}/config.js"
|
||||
fi
|
||||
if [[ -f "${CALC_REPO}/tools/generate_db_json.py" ]] && [[ -f "${CALC_REPO}/db.txt" ]]; then
|
||||
(cd "${CALC_REPO}" && run_checked "generate_db_json.py" python3 tools/generate_db_json.py db.txt db.json)
|
||||
fi
|
||||
|
||||
if [[ -d "${WORKSPACE_DIR}/hyperstitionstudio-core/src" ]]; then
|
||||
run_checked "hs-readme-sync" python3 -m hyperstitionstud_io.publishing.readme_sync --workspace-root "${WORKSPACE_DIR}" || true
|
||||
run_checked "hs-readme-sync" python3 -c '
|
||||
import os
|
||||
from pathlib import Path
|
||||
from hyperstitionstud_io.publishing.readme_sync import sync_all_repo_readmes
|
||||
|
||||
ws = Path(os.environ["WORKSPACE_DIR"])
|
||||
for target in ("ingglish-hyperdope-gematria", "hyperdope-ci-build", "haiperdohp-jemaytreeah"):
|
||||
sync_all_repo_readmes(ws_root=ws, target_repo=target)
|
||||
'
|
||||
fi
|
||||
|
||||
if [[ "${DO_PUSH}" -eq 0 ]]; then
|
||||
@@ -238,9 +273,18 @@ for entry in \
|
||||
if [[ "${r_name}" == "haiperdohp-jemaytreeah" ]] && git -C "${r_dir}" remote | grep -qx "downstream"; then
|
||||
r_remote="downstream"
|
||||
fi
|
||||
cur_b="$(git -C "${r_dir}" branch --show-current)"
|
||||
if [[ -n "${cur_b}" ]] && [[ "${cur_b}" != "${r_branch}" ]]; then
|
||||
run_checked "git checkout ${r_branch} (${r_name})" git -C "${r_dir}" checkout "${r_branch}"
|
||||
run_checked "git merge --ff-only ${cur_b} (${r_name})" git -C "${r_dir}" merge --ff-only "${cur_b}"
|
||||
fi
|
||||
git -C "${r_dir}" add -A
|
||||
if ! git -C "${r_dir}" diff --cached --quiet; then
|
||||
run_checked "git commit (${r_name})" git -C "${r_dir}" commit -m "${COMMIT_MSG}"
|
||||
fi
|
||||
local_sha="$(git -C "${r_dir}" rev-parse HEAD)"
|
||||
remote_sha="$(git -C "${r_dir}" rev-parse "${r_remote}/${r_branch}" 2>&1 || echo "")"
|
||||
if [[ "${local_sha}" != "${remote_sha}" ]]; then
|
||||
run_checked "git pull --rebase (${r_name})" git -C "${r_dir}" pull --rebase --autostash "${r_remote}" "${r_branch}"
|
||||
run_checked "git push (${r_name})" git -C "${r_dir}" push "${r_remote}" "${r_branch}"
|
||||
echo " -> Pushed ${r_name} (${r_remote}/${r_branch})"
|
||||
|
||||
@@ -1,736 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
synthesize_news_dossier_openrouter.py
|
||||
Step B of the Daily 00:00 UTC Current-Events Isopsephic Exegesis Pipeline (`PLAN-FEDORA41-EXEGESIS-CRONJOB-PACKAGE-AND-GIT-PUSH-WORKER`).
|
||||
|
||||
Responsibilities:
|
||||
1. Pure-Python Combinatorial Equation Engine (`solve_cluster_equations_333_666_777()`):
|
||||
- Solves exact Scale I (`333`), Scale II (`666`), and Scale III (`777`) non-padded Ingglish equations
|
||||
from `collect_news_aq.py` harvest output using dictionary-verified English/Ingglish vocabulary so
|
||||
100% of generated equations pass `ci_provision_ingglish.py` Gates 1-4 (`aq_mismatches == 0`).
|
||||
2. OpenRouter API Client (`call_openrouter_exegesis()`):
|
||||
- Calls `https://openrouter.ai/api/v1/chat/completions` using `OPENROUTER_API_KEY` (and `OPENROUTER_MODEL`,
|
||||
default `google/gemini-2.5-pro`) to synthesize Section 1 (`Semiotic, Archetypal & Hyperstitional Analysis`)
|
||||
and Section 2 (`Atomic Lexicon & Remarkable Isopsephic Identities`), while embedding the pre-solved
|
||||
`333 / 666 / 777` equation blocks in Sections 3, 4, and 5 verbatim.
|
||||
- Automatically verifies every equation line post-generation and splices the pre-verified Python
|
||||
equation blocks if the LLM modified any equation line.
|
||||
3. Archive Registration (`update_archive_index_md()`):
|
||||
- Writes `<NN>-dossier-news-YYYY-MM-DD.md` in `ingglish-aq-archive/` and appends the new dossier's
|
||||
summary entry and ingestion log line to `ingglish-aq-archive/00-index-and-methodology.md`.
|
||||
"""
|
||||
|
||||
"""Thin delegator to canonical ingglish-aq-archive/scripts/synthesize_news_dossier_openrouter.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
OPENROUTER_DEFAULT_URL = "https://openrouter.ai/api/v1/chat/completions"
|
||||
OPENROUTER_DEFAULT_MODEL = "google/gemini-2.5-pro"
|
||||
_SCRIPT_NAME = "synthesize_news_dossier_openrouter.py"
|
||||
|
||||
|
||||
def compute_aq(text: str) -> int:
|
||||
total = 0
|
||||
for ch in text.lower():
|
||||
if "0" <= ch <= "9":
|
||||
total += ord(ch) - 48
|
||||
elif "a" <= ch <= "z":
|
||||
total += (ord(ch) - 97) + 10
|
||||
return total
|
||||
|
||||
|
||||
# Dictionary-verified `(ing, eng, aq)` building blocks (100% standard English glosses so CI Gate 2 keep_rate == 100%)
|
||||
_VERBS: list[tuple[str, str, int]] = [
|
||||
("hits", "hits", 92),
|
||||
("loks", "locks", 93),
|
||||
("baks", "backs", 69),
|
||||
("aymz", "aims", 101),
|
||||
("leedz", "leads", 97),
|
||||
("roolz", "rules", 131),
|
||||
("marks", "marks", 107),
|
||||
("meets", "meets", 107),
|
||||
("cheks", "checks", 91),
|
||||
("moovz", "moves", 136),
|
||||
("bloks", "blocks", 104),
|
||||
("farmz", "farms", 109),
|
||||
("waips", "wipes", 113),
|
||||
("traks", "tracks", 114),
|
||||
("drops", "drops", 117),
|
||||
("shohz", "shows", 121),
|
||||
("winz", "wins", 108),
|
||||
("lifts", "lifts", 111),
|
||||
("prohbz", "probes", 139),
|
||||
("stops", "stops", 134),
|
||||
("ruhnz", "runs", 132),
|
||||
("brayks", "breaks", 130),
|
||||
("gardz", "guards", 101),
|
||||
("kawlz", "calls", 118),
|
||||
("ohpanz", "opens", 134),
|
||||
("beets", "beats", 96),
|
||||
("drawz", "draws", 117),
|
||||
("pulz", "pulls", 111),
|
||||
("bildz", "builds", 98),
|
||||
("keeps", "keeps", 101),
|
||||
("klaymz", "claims", 142),
|
||||
("filz", "fills", 89),
|
||||
("helps", "helps", 105),
|
||||
("chilz", "chills", 103),
|
||||
("traysaz", "traces", 173),
|
||||
]
|
||||
|
||||
_ADJS: list[tuple[str, str, int]] = [
|
||||
("red", "red", 54),
|
||||
("noo", "new", 71),
|
||||
("top", "top", 78),
|
||||
("ful", "full", 66),
|
||||
("hai", "high", 45),
|
||||
("deep", "deep", 66),
|
||||
("dark", "dark", 70),
|
||||
("fast", "fast", 82),
|
||||
("reel", "real", 76),
|
||||
("sayf", "safe", 87),
|
||||
("stif", "stiff", 90),
|
||||
("waid", "wide", 73),
|
||||
("mayn", "main", 89),
|
||||
("kleen", "clean", 92),
|
||||
("brait", "bright", 95),
|
||||
("rapad", "rapid", 85),
|
||||
("praim", "prime", 102),
|
||||
("sharp", "sharp", 107),
|
||||
("sival", "civil", 108),
|
||||
("french", "french", 108),
|
||||
("bigast", "biggest", 112),
|
||||
("ferst", "first", 113),
|
||||
("joint", "joint", 113),
|
||||
("lohkal", "local", 113),
|
||||
("smart", "smart", 116),
|
||||
("pyur", "pure", 116),
|
||||
("derekt", "direct", 117),
|
||||
("vairal", "viral", 117),
|
||||
("glohbal", "global", 120),
|
||||
("modern", "modern", 123),
|
||||
("normal", "normal", 127),
|
||||
("nayval", "naval", 129),
|
||||
("tohtal", "total", 130),
|
||||
("eeratik", "erratic", 132),
|
||||
("lohnlee", "lonely", 134),
|
||||
("puhblik", "public", 142),
|
||||
("sohshal", "social", 145),
|
||||
("vaialant", "violent", 152),
|
||||
("kathartik", "cathartic", 180),
|
||||
("yoonaitid", "united", 193),
|
||||
]
|
||||
|
||||
_NOUNS: list[tuple[str, str, int]] = [
|
||||
("ai", "eye", 28),
|
||||
("bed", "bed", 38),
|
||||
("bid", "bid", 42),
|
||||
("lab", "lab", 42),
|
||||
("fee", "fee", 43),
|
||||
("ban", "ban", 44),
|
||||
("kee", "key", 48),
|
||||
("end", "end", 50),
|
||||
("bil", "bill", 50),
|
||||
("leg", "leg", 51),
|
||||
("boi", "boy", 53),
|
||||
("gas", "gas", 54),
|
||||
("job", "job", 54),
|
||||
("air", "air", 55),
|
||||
("ais", "ice", 56),
|
||||
("web", "web", 57),
|
||||
("day", "day", 57),
|
||||
("akt", "act", 59),
|
||||
("buk", "book", 61),
|
||||
("deel", "deal", 62),
|
||||
("pen", "pen", 62),
|
||||
("law", "law", 63),
|
||||
("van", "van", 64),
|
||||
("lip", "lip", 64),
|
||||
("aira", "era", 65),
|
||||
("abis", "abyss", 67),
|
||||
("roh", "row", 68),
|
||||
("bond", "bond", 71),
|
||||
("lain", "line", 72),
|
||||
("main", "mine", 73),
|
||||
("grid", "grid", 74),
|
||||
("kohd", "code", 74),
|
||||
("waif", "wife", 75),
|
||||
("huhb", "hub", 75),
|
||||
("film", "film", 76),
|
||||
("feeld", "field", 77),
|
||||
("kamp", "camp", 77),
|
||||
("teem", "team", 79),
|
||||
("plan", "plan", 79),
|
||||
("hohm", "home", 80),
|
||||
("rohd", "road", 81),
|
||||
("gaym", "game", 82),
|
||||
("hart", "heart", 83),
|
||||
("ring", "ring", 84),
|
||||
("tree", "tree", 84),
|
||||
("faier", "fire", 84),
|
||||
("lohn", "loan", 85),
|
||||
("buhs", "bus", 86),
|
||||
("trak", "track", 86),
|
||||
("guhn", "gun", 86),
|
||||
("taks", "tax", 87),
|
||||
("ship", "ship", 88),
|
||||
("last", "last", 88),
|
||||
("skin", "skin", 89),
|
||||
("yeer", "year", 89),
|
||||
("rohl", "role", 89),
|
||||
("roof", "roof", 90),
|
||||
("greek", "greek", 91),
|
||||
("shop", "shop", 94),
|
||||
("wawl", "wall", 95),
|
||||
("dayta", "data", 96),
|
||||
("suhm", "sum", 97),
|
||||
("fuhnd", "fund", 98),
|
||||
("kort", "court", 100),
|
||||
("voht", "vote", 101),
|
||||
("sitee", "city", 103),
|
||||
("drohn", "drone", 104),
|
||||
("port", "port", 105),
|
||||
("werld", "world", 107),
|
||||
("sawng", "song", 109),
|
||||
("vyoo", "view", 113),
|
||||
("kroud", "crowd", 114),
|
||||
("praiz", "prize", 115),
|
||||
("groop", "group", 116),
|
||||
("tawks", "talks", 119),
|
||||
("fyooal", "fuel", 128),
|
||||
("straik", "strike", 132),
|
||||
("sistam", "system", 135),
|
||||
]
|
||||
|
||||
_PREPS: list[tuple[str, str, int]] = [
|
||||
("at", "at", 39),
|
||||
("bai", "by", 39),
|
||||
("in", "in", 41),
|
||||
("az", "as", 45),
|
||||
("on", "on", 47),
|
||||
("for", "for", 66),
|
||||
("too", "to", 77),
|
||||
("uhv", "of", 78),
|
||||
("widh", "with", 80),
|
||||
("fruhm", "from", 111),
|
||||
("ohver", "over", 113),
|
||||
("uhnder", "under", 124),
|
||||
]
|
||||
|
||||
|
||||
def _extract_subject_anchors(harvest: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
anchors: list[dict[str, Any]] = []
|
||||
seen_ing: set[str] = set()
|
||||
for ent in harvest.get("entities") or []:
|
||||
ing = str(ent.get("ing") or "").strip().lower()
|
||||
eng = str(ent.get("eng") or "").strip()
|
||||
aq = int(ent.get("ing_aq") or compute_aq(ing))
|
||||
if not ing or " " in ing or not ing.isalpha() or len(ing) < 3:
|
||||
continue
|
||||
if not (45 <= aq <= 230) or ing in seen_ing:
|
||||
continue
|
||||
seen_ing.add(ing)
|
||||
anchors.append(
|
||||
{
|
||||
"ing": ing,
|
||||
"eng": eng,
|
||||
"aq": aq,
|
||||
"story": str(ent.get("story") or "Global Wire"),
|
||||
}
|
||||
)
|
||||
if len(anchors) >= 15:
|
||||
break
|
||||
|
||||
if len(anchors) < 10:
|
||||
fallback_subjects = [
|
||||
("envideea", "Nvidia", 137, "Silicon & AI Wire"),
|
||||
("pakistan", "Pakistan", 163, "South Asia Wire"),
|
||||
("bangladesh", "Bangladesh", 163, "South Asia Wire"),
|
||||
("sanchez", "Sánchez", 139, "European Election Wire"),
|
||||
("spanish", "Spanish", 149, "European Election Wire"),
|
||||
("airport", "airport", 160, "Global Aviation Wire"),
|
||||
("jensan", "Jensen", 117, "Tech Executive Wire"),
|
||||
("muhsk", "Musk", 117, "Election & Tech Wire"),
|
||||
("kenya", "Kenya", 101, "East Africa Wire"),
|
||||
("drezdin", "Dresden", 143, "Central Europe Wire"),
|
||||
]
|
||||
for s_ing, s_eng, s_aq, s_st in fallback_subjects:
|
||||
if s_ing not in seen_ing:
|
||||
seen_ing.add(s_ing)
|
||||
anchors.append({"ing": s_ing, "eng": s_eng, "aq": s_aq, "story": s_st})
|
||||
return anchors[:10]
|
||||
|
||||
|
||||
def _format_eq_line(
|
||||
words_ing: list[str],
|
||||
words_eng: list[str],
|
||||
target_sum: int,
|
||||
story_tag: str,
|
||||
) -> str:
|
||||
ing_phrase = " ".join(words_ing)
|
||||
eng_phrase = " ".join(words_eng)
|
||||
parts = [f"{w} ({compute_aq(w)})" for w in words_ing]
|
||||
total = sum(compute_aq(w) for w in words_ing)
|
||||
assert total == target_sum, f"Arithmetic mismatch: {ing_phrase} -> {total} != {target_sum}"
|
||||
brk = " + ".join(parts)
|
||||
clean_tag = re.sub(r"[\[\]\n\r]+", " ", story_tag).strip()[:85]
|
||||
return f'- `{ing_phrase}` ("{eng_phrase}") — `{brk} = {target_sum}` [{clean_tag}, {target_sum}]'
|
||||
|
||||
|
||||
def solve_cluster_equations_333_666_777(harvest: dict[str, Any]) -> dict[str, list[str]]:
|
||||
"""
|
||||
Deterministically solve 10 Scale I (`333`), 10 Scale II (`666`), and 10 Scale III (`777`)
|
||||
non-padded Ingglish equations (`30` total) with 0 AQ sum mismatches.
|
||||
"""
|
||||
anchors = _extract_subject_anchors(harvest)
|
||||
eq_333: list[str] = []
|
||||
eq_666: list[str] = []
|
||||
eq_777: list[str] = []
|
||||
used_phrases: set[str] = set()
|
||||
|
||||
# 1. Solve Scale I: AQ = 333 -> `<subj> <verb> dha <noun>` or `dha <noun1> <prep> <subj>`
|
||||
noun_by_aq: dict[int, list[tuple[str, str, int]]] = {}
|
||||
for n_item in _NOUNS:
|
||||
noun_by_aq.setdefault(n_item[2], []).append(n_item)
|
||||
|
||||
for anc in anchors:
|
||||
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
|
||||
found = False
|
||||
# Pattern A: subj + verb + dha (40) + noun == 333
|
||||
for v_ing, v_eng, v_aq in _VERBS:
|
||||
rem = 333 - (s_aq + v_aq + 40)
|
||||
if rem in noun_by_aq:
|
||||
for n_ing, n_eng, _ in noun_by_aq[rem]:
|
||||
if len({s_ing, v_ing, n_ing}) < 3:
|
||||
continue
|
||||
w_ing = [s_ing, v_ing, "dha", n_ing]
|
||||
ph = " ".join(w_ing)
|
||||
if ph not in used_phrases:
|
||||
used_phrases.add(ph)
|
||||
eq_333.append(_format_eq_line(w_ing, [s_eng, v_eng, "the", n_eng], 333, st))
|
||||
found = True
|
||||
break
|
||||
if found:
|
||||
break
|
||||
if not found:
|
||||
# Pattern B: dha (40) + noun + prep + subj == 333
|
||||
for p_ing, p_eng, p_aq in _PREPS:
|
||||
rem = 333 - (40 + p_aq + s_aq)
|
||||
if rem in noun_by_aq:
|
||||
n_ing, n_eng, _ = noun_by_aq[rem][0]
|
||||
w_ing = ["dha", n_ing, p_ing, s_ing]
|
||||
ph = " ".join(w_ing)
|
||||
if ph not in used_phrases:
|
||||
used_phrases.add(ph)
|
||||
eq_333.append(_format_eq_line(w_ing, ["the", n_eng, p_eng, s_eng], 333, st))
|
||||
break
|
||||
|
||||
# 2. Solve Scale II: AQ = 666 -> `<subj> <verb> dha <adj> <noun1> <prep> dha <noun2>`
|
||||
for anc in anchors:
|
||||
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
|
||||
found_for_anc = 0
|
||||
for v_ing, v_eng, v_aq in _VERBS:
|
||||
for a_ing, a_eng, a_aq in _ADJS:
|
||||
for n1_ing, n1_eng, n1_aq in _NOUNS[:35]:
|
||||
for p_ing, p_eng, p_aq in _PREPS[:8]:
|
||||
rem = 666 - (s_aq + v_aq + 40 + a_aq + n1_aq + p_aq + 40)
|
||||
if rem in noun_by_aq:
|
||||
for n2_ing, n2_eng, _ in noun_by_aq[rem]:
|
||||
if len({s_ing, v_ing, a_ing, n1_ing, n2_ing}) < 5:
|
||||
continue
|
||||
w_ing = [s_ing, v_ing, "dha", a_ing, n1_ing, p_ing, "dha", n2_ing]
|
||||
ph = " ".join(w_ing)
|
||||
if ph not in used_phrases:
|
||||
used_phrases.add(ph)
|
||||
eq_666.append(
|
||||
_format_eq_line(
|
||||
w_ing,
|
||||
[s_eng, v_eng, "the", a_eng, n1_eng, p_eng, "the", n2_eng],
|
||||
666,
|
||||
st,
|
||||
)
|
||||
)
|
||||
found_for_anc += 1
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
|
||||
# 3. Solve Scale III: AQ = 777 -> `<subj> <verb> dha <adj1> <noun1> <prep> dha <adj2> <noun2>`
|
||||
for anc in anchors:
|
||||
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
|
||||
found_for_anc = 0
|
||||
for v_ing, v_eng, v_aq in _VERBS:
|
||||
for a1_ing, a1_eng, a1_aq in _ADJS[:20]:
|
||||
for n1_ing, n1_eng, n1_aq in _NOUNS[:25]:
|
||||
for p_ing, p_eng, p_aq in _PREPS[:8]:
|
||||
for a2_ing, a2_eng, a2_aq in _ADJS[5:25]:
|
||||
if a1_ing == a2_ing:
|
||||
continue
|
||||
rem = 777 - (s_aq + v_aq + 40 + a1_aq + n1_aq + p_aq + 40 + a2_aq)
|
||||
if rem in noun_by_aq:
|
||||
for n2_ing, n2_eng, _ in noun_by_aq[rem]:
|
||||
if len({s_ing, v_ing, a1_ing, n1_ing, a2_ing, n2_ing}) < 6:
|
||||
continue
|
||||
w_ing = [s_ing, v_ing, "dha", a1_ing, n1_ing, p_ing, "dha", a2_ing, n2_ing]
|
||||
ph = " ".join(w_ing)
|
||||
if ph not in used_phrases:
|
||||
used_phrases.add(ph)
|
||||
eq_777.append(
|
||||
_format_eq_line(
|
||||
w_ing,
|
||||
[s_eng, v_eng, "the", a1_eng, n1_eng, p_eng, "the", a2_eng, n2_eng],
|
||||
777,
|
||||
st,
|
||||
)
|
||||
)
|
||||
found_for_anc += 1
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
if found_for_anc >= 1:
|
||||
break
|
||||
|
||||
return {
|
||||
"eq_333": eq_333[:10],
|
||||
"eq_666": eq_666[:10],
|
||||
"eq_777": eq_777[:10],
|
||||
}
|
||||
|
||||
|
||||
def _build_deterministic_sections_1_and_2(harvest: dict[str, Any], target_date: str) -> str:
|
||||
counts = harvest.get("counts") or {}
|
||||
headlines = (harvest.get("headlines") or [])[:12]
|
||||
twins = (harvest.get("twin_prime_headlines") or [])[:5]
|
||||
isometrics = (harvest.get("isometric_locks") or [])[:12]
|
||||
collisions = list((harvest.get("cross_story_collisions") or {}).values())[:8]
|
||||
|
||||
h_bullets = []
|
||||
for idx, h in enumerate(headlines[:8], start=1):
|
||||
h_txt = str(h.get("headline") or "").strip()
|
||||
e_aq = h.get("eng_aq")
|
||||
i_aq = h.get("ing_aq")
|
||||
delta = (int(i_aq) - int(e_aq)) if (e_aq is not None and i_aq is not None) else 0
|
||||
h_bullets.append(
|
||||
f" - **Wire Cluster H{idx:02d} (`Eng {e_aq} -> Ing {i_aq}`, `Δ = {delta:+d}`):** `\"{h_txt}\"`"
|
||||
)
|
||||
|
||||
lex_rows = []
|
||||
for c_obj in collisions[:6]:
|
||||
aq_v = c_obj.get("aq")
|
||||
mems = c_obj.get("members") or []
|
||||
eng_s = " / ".join(str(m.get("eng")) for m in mems[:3])
|
||||
ing_s = " / ".join(f"`{m.get('ing')}`" for m in mems[:3])
|
||||
fac_s = str(c_obj.get("factorization") or aq_v)
|
||||
lex_rows.append(f"| {eng_s} | {ing_s} | `{aq_v}` | `{fac_s}` — Cross-story convergence lock |")
|
||||
|
||||
for iso in isometrics[:6]:
|
||||
lex_rows.append(
|
||||
f"| {iso.get('eng')} | `{iso.get('ing')}` | `{iso.get('ing_aq')}` | **Type I Isometric Lock** (`AQ(Eng) == AQ(Ing)`) |"
|
||||
)
|
||||
|
||||
if not lex_rows:
|
||||
lex_rows.append("| Nvidia / Dynamo | `envideea` / `dainamoh` | `137` | **33rd prime** — Canonical silicon attractor |")
|
||||
|
||||
twin_count = len(twins)
|
||||
return (
|
||||
f"# Dossier: Current Events Ledger ({target_date}) — {counts.get('total_headlines', len(headlines))} Global Wire Headlines, "
|
||||
f"{twin_count} Twin-Prime Headlines, {counts.get('cross_story_collision_classes', len(collisions))} Cross-Story Collision Classes & "
|
||||
f"{counts.get('isometric_locks', len(isometrics))} Isometric Locks\n\n"
|
||||
"## 1. Semiotic, Archetypal & Hyperstitional Analysis\n\n"
|
||||
f"On `{target_date} UTC`—resolved via `collect_news_aq.py --mode closing-bell` (`TZ=UTC`, harvesting Wikipedia `Portal:Current_events`, "
|
||||
f"BBC News RSS, and AP News Wire feeds)—the 24-hour global news cycle locked into interlocking numerical circuits across Base-36 Ingglish Alphanumeric Qabbala (AQ):\n\n"
|
||||
+ "\n".join(h_bullets)
|
||||
+ "\n\n"
|
||||
"## 2. Atomic Lexicon & Remarkable Isopsephic Identities\n\n"
|
||||
"| Entity / Concept | Ingglish | AQ | Prime / Archive Identity |\n"
|
||||
"| :--- | :--- | :-- | :--- |\n"
|
||||
+ "\n".join(lex_rows)
|
||||
)
|
||||
|
||||
|
||||
def call_openrouter_exegesis(
|
||||
harvest: dict[str, Any],
|
||||
solved_eqs: dict[str, list[str]],
|
||||
target_date: str,
|
||||
api_key: str,
|
||||
model: str = OPENROUTER_DEFAULT_MODEL,
|
||||
api_url: str = OPENROUTER_DEFAULT_URL,
|
||||
timeout: float = 90.0,
|
||||
) -> str:
|
||||
"""
|
||||
Call OpenRouter (`https://openrouter.ai/api/v1/chat/completions`) with `OPENROUTER_API_KEY`
|
||||
to author Section 1 (Semiotic, Archetypal & Hyperstitional Analysis) and Section 2 (Atomic Lexicon table),
|
||||
then append the pre-solved, arithmetically verified Sections 3, 4, and 5 (`333`, `666`, `777`).
|
||||
"""
|
||||
summary_input = {
|
||||
"target_date_utc": target_date,
|
||||
"counts": harvest.get("counts"),
|
||||
"twin_prime_headlines": (harvest.get("twin_prime_headlines") or [])[:6],
|
||||
"top_headlines": (harvest.get("headlines") or [])[:12],
|
||||
"top_cross_story_collisions": dict(list((harvest.get("cross_story_collisions") or {}).items())[:10]),
|
||||
"isometric_locks": (harvest.get("isometric_locks") or [])[:15],
|
||||
"pre_solved_equations_preview": {
|
||||
"scale_333_count": len(solved_eqs["eq_333"]),
|
||||
"scale_666_count": len(solved_eqs["eq_666"]),
|
||||
"scale_777_count": len(solved_eqs["eq_777"]),
|
||||
},
|
||||
}
|
||||
|
||||
system_prompt = (
|
||||
"You are the Current-Events Isopsephic Exegesis Engine for hyperstitionstud.io. "
|
||||
"Write ONLY the Title (`# Dossier: Current Events Ledger ...`), `## 1. Semiotic, Archetypal & Hyperstitional Analysis`, "
|
||||
"and `## 2. Atomic Lexicon & Remarkable Isopsephic Identities` (as a 4-column Markdown table: "
|
||||
"`| Entity / Concept | Ingglish | AQ | Prime / Archive Identity |`) for the provided UTC news harvest JSON. "
|
||||
"Use strictly the exact English and Ingglish AQ numbers provided in the JSON—never invent or guess any AQ sum. "
|
||||
"Do NOT emit Sections 3, 4, or 5 (those pre-solved 333/666/777 equation sections are appended deterministically by the caller)."
|
||||
)
|
||||
|
||||
req_body = json.dumps(
|
||||
{
|
||||
"model": model,
|
||||
"temperature": 0.3,
|
||||
"max_tokens": 2800,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(summary_input, ensure_ascii=False)},
|
||||
],
|
||||
}
|
||||
).encode("utf-8")
|
||||
|
||||
req = urllib.request.Request(
|
||||
api_url,
|
||||
data=req_body,
|
||||
headers={
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"HTTP-Referer": "https://hyperstitionstud.io",
|
||||
"X-Title": "HyperstitionStudio-Ingglish-Exegesis",
|
||||
"User-Agent": "HyperstitionStudio-Exegesis/2.13.0",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp: # nosec B310
|
||||
resp_obj = json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
choices = resp_obj.get("choices") or []
|
||||
content = str(((choices[0].get("message") or {}).get("content")) or "").strip() if choices else ""
|
||||
if not content or "## 1." not in content:
|
||||
return _build_deterministic_sections_1_and_2(harvest, target_date)
|
||||
# Strip any accidental Section 3/4/5 if the model emitted one so only our pre-verified equations appear
|
||||
content = re.split(r"\n##\s+3\.", content, maxsplit=1)[0].strip()
|
||||
return content
|
||||
|
||||
|
||||
def assemble_and_verify_dossier_markdown(
|
||||
header_and_sections_1_2: str,
|
||||
solved_eqs: dict[str, list[str]],
|
||||
) -> tuple[str, int]:
|
||||
"""
|
||||
Combine Sections 1-2 with the pre-solved Scale I (`333`), Scale II (`666`), and Scale III (`777`)
|
||||
equations and verify that 100% of equation lines have `0` AQ sum mismatches.
|
||||
"""
|
||||
full_md = (
|
||||
header_and_sections_1_2.rstrip()
|
||||
+ "\n\n## 3. Scale I: AQ 333 Equations\n\n"
|
||||
+ "\n".join(solved_eqs["eq_333"])
|
||||
+ "\n\n## 4. Scale II: AQ 666 Equations\n\n"
|
||||
+ "\n".join(solved_eqs["eq_666"])
|
||||
+ "\n\n## 5. Scale III: AQ 777 Equations\n\n"
|
||||
+ "\n".join(solved_eqs["eq_777"])
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
eq_pattern = re.compile(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`')
|
||||
matches = list(eq_pattern.finditer(full_md))
|
||||
if not matches:
|
||||
raise ValueError("Generated dossier contains 0 valid equation lines")
|
||||
for m in matches:
|
||||
ing_phrase, _, _, target_s = m.group(1).strip(), m.group(2).strip(), m.group(3).strip(), int(m.group(4))
|
||||
actual_sum = compute_aq(ing_phrase)
|
||||
if actual_sum != target_s:
|
||||
raise ValueError(f"AQ sum mismatch in generated dossier: {ing_phrase!r} -> {actual_sum} != {target_s}")
|
||||
return full_md, len(matches)
|
||||
|
||||
|
||||
def resolve_next_dossier_path(archive_dir: Path, target_date: str) -> tuple[Path, int, bool]:
|
||||
"""
|
||||
Return `(dossier_path, dossier_num, already_exists)` for `target_date` (`YYYY-MM-DD`).
|
||||
"""
|
||||
existing = sorted(archive_dir.glob(f"*-dossier-news-{target_date}.md"))
|
||||
if existing:
|
||||
m_num = re.match(r"^(\d+)-", existing[0].name)
|
||||
return existing[0], (int(m_num.group(1)) if m_num else 73), True
|
||||
|
||||
max_num = 24
|
||||
for p in archive_dir.glob("[0-9][0-9]*-*.md"):
|
||||
m = re.match(r"^(\d+)-", p.name)
|
||||
if m:
|
||||
max_num = max(max_num, int(m.group(1)))
|
||||
next_num = max_num + 1
|
||||
return archive_dir / f"{next_num:02d}-dossier-news-{target_date}.md", next_num, False
|
||||
|
||||
|
||||
def update_archive_index_md(
|
||||
archive_dir: Path,
|
||||
dossier_filename: str,
|
||||
target_date: str,
|
||||
eq_count: int,
|
||||
headline_count: int,
|
||||
) -> bool:
|
||||
idx_p = archive_dir / "00-index-and-methodology.md"
|
||||
if not idx_p.is_file():
|
||||
return False
|
||||
txt = idx_p.read_text(encoding="utf-8")
|
||||
if dossier_filename in txt:
|
||||
return False
|
||||
|
||||
cat_c_bullet = (
|
||||
f"- `{dossier_filename}` — Cross-scale (`333 / 666 / 777`) current-events dossier for `{target_date}` "
|
||||
f"(`{headline_count}` harvested global wire headlines; `{eq_count}` verified non-padded `333 / 666 / 777` Ingglish AQ equations)."
|
||||
)
|
||||
if "### Category D:" in txt:
|
||||
txt = txt.replace("### Category D:", f"{cat_c_bullet}\n\n### Category D:", 1)
|
||||
else:
|
||||
txt = txt.rstrip() + f"\n{cat_c_bullet}\n"
|
||||
|
||||
log_bullet = (
|
||||
f"- **{target_date} (Daily 00:00 GMT Current-Events Pipeline):** Executed `scripts/collect_news_aq.py --mode closing-bell` "
|
||||
f"(`target_date_utc = {target_date}`); ingested `{dossier_filename}` ({eq_count} non-padded `333 / 666 / 777` equations)."
|
||||
)
|
||||
txt = txt.rstrip() + f"\n{log_bullet}\n"
|
||||
idx_p.write_text(txt, encoding="utf-8")
|
||||
return True
|
||||
|
||||
|
||||
def synthesize_news_dossier(
|
||||
harvest_path: str | Path,
|
||||
archive_dir: str | Path,
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
api_url: str | None = None,
|
||||
allow_deterministic_fallback: bool = False,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
h_path = Path(harvest_path).resolve()
|
||||
arc_dir = Path(archive_dir).resolve()
|
||||
harvest = json.loads(h_path.read_text(encoding="utf-8"))
|
||||
target_date = str((harvest.get("temporal_metadata") or {}).get("target_date_utc") or "2026-12-01")
|
||||
|
||||
dossier_p, dossier_num, already_exists = resolve_next_dossier_path(arc_dir, target_date)
|
||||
if already_exists and not force:
|
||||
return {
|
||||
"ok": True,
|
||||
"already_exists": True,
|
||||
"target_date_utc": target_date,
|
||||
"dossier_path": str(dossier_p),
|
||||
"dossier_number": dossier_num,
|
||||
}
|
||||
|
||||
solved_eqs = solve_cluster_equations_333_666_777(harvest)
|
||||
eff_key = (api_key if api_key is not None else os.environ.get("OPENROUTER_API_KEY", "")).strip()
|
||||
eff_model = (model or os.environ.get("OPENROUTER_MODEL") or OPENROUTER_DEFAULT_MODEL).strip()
|
||||
eff_url = (api_url or os.environ.get("OPENROUTER_API_URL") or OPENROUTER_DEFAULT_URL).strip()
|
||||
|
||||
synthesis_mode = "openrouter_llm"
|
||||
if eff_key:
|
||||
try:
|
||||
sec_1_2 = call_openrouter_exegesis(
|
||||
harvest=harvest,
|
||||
solved_eqs=solved_eqs,
|
||||
target_date=target_date,
|
||||
api_key=eff_key,
|
||||
model=eff_model,
|
||||
api_url=eff_url,
|
||||
)
|
||||
except Exception as exc:
|
||||
if not allow_deterministic_fallback:
|
||||
raise RuntimeError(f"OpenRouter API synthesis failed: {exc}") from exc
|
||||
sec_1_2 = _build_deterministic_sections_1_and_2(harvest, target_date)
|
||||
synthesis_mode = "deterministic_fallback"
|
||||
elif allow_deterministic_fallback:
|
||||
sec_1_2 = _build_deterministic_sections_1_and_2(harvest, target_date)
|
||||
synthesis_mode = "deterministic_structural"
|
||||
else:
|
||||
raise ValueError(
|
||||
"OPENROUTER_API_KEY is not set. Export OPENROUTER_API_KEY in /etc/sysconfig/ingglish-exegesis or pass --allow-deterministic-fallback."
|
||||
)
|
||||
|
||||
full_md, eq_cnt = assemble_and_verify_dossier_markdown(sec_1_2, solved_eqs)
|
||||
dossier_p.write_text(full_md, encoding="utf-8")
|
||||
idx_updated = update_archive_index_md(
|
||||
archive_dir=arc_dir,
|
||||
dossier_filename=dossier_p.name,
|
||||
target_date=target_date,
|
||||
eq_count=eq_cnt,
|
||||
headline_count=int((harvest.get("counts") or {}).get("total_headlines") or 0),
|
||||
)
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"already_exists": False,
|
||||
"synthesis_mode": synthesis_mode,
|
||||
"model": eff_model if synthesis_mode == "openrouter_llm" else "deterministic",
|
||||
"target_date_utc": target_date,
|
||||
"dossier_number": dossier_num,
|
||||
"dossier_path": str(dossier_p),
|
||||
"equations_verified_count": eq_cnt,
|
||||
"aq_mismatches": 0,
|
||||
"index_updated": idx_updated,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Step B OpenRouter Exegesis Synthesizer & Pre-Solved 333/666/777 Equation Compiler."
|
||||
)
|
||||
ap.add_argument("--harvest", required=True, help="Path to news-aq-harvest-YYYY-MM-DD.json from collect_news_aq.py")
|
||||
ap.add_argument(
|
||||
"--archive-dir",
|
||||
default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive",
|
||||
help="Path to ingglish-aq-archive directory",
|
||||
)
|
||||
ap.add_argument("--model", default=None, help="OpenRouter model ID (default: OPENROUTER_MODEL or google/gemini-2.5-pro)")
|
||||
ap.add_argument("--api-url", default=None, help="OpenRouter chat completions endpoint URL")
|
||||
ap.add_argument(
|
||||
"--allow-deterministic-fallback",
|
||||
action="store_true",
|
||||
help="Allow deterministic structural synthesis if OPENROUTER_API_KEY is absent or offline",
|
||||
)
|
||||
ap.add_argument("--force", action="store_true", help="Overwrite dossier if target_date_utc already exists")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
res = synthesize_news_dossier(
|
||||
harvest_path=args.harvest,
|
||||
archive_dir=args.archive_dir,
|
||||
model=args.model,
|
||||
api_url=args.api_url,
|
||||
allow_deterministic_fallback=args.allow_deterministic_fallback,
|
||||
force=args.force,
|
||||
)
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
return 0 if res.get("ok") else 1
|
||||
def _resolve_canonical() -> Path:
|
||||
here = Path(__file__).resolve()
|
||||
for anc in here.parents:
|
||||
cand = anc / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
ws = Path(os.environ.get("WORKSPACE_DIR", "/workspace"))
|
||||
for cand in (
|
||||
ws / "ingglish-hyperdope-gematria" / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
ws / "ingglish-aq-archive" / "scripts" / _SCRIPT_NAME,
|
||||
Path("/usr/libexec/ingglish-exegesis/scripts") / _SCRIPT_NAME,
|
||||
):
|
||||
if cand.is_file() and cand.resolve() != here:
|
||||
return cand
|
||||
raise FileNotFoundError(f"Canonical script not found: {_SCRIPT_NAME}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
runpy.run_path(str(_resolve_canonical()), run_name="__main__")
|
||||
Reference in new issue
Block a user