feat(news-aq): implement daily 00:00 GMT current-events pipeline, TZ handling, Nov 2 dossier, and RHEL packaging

This commit is contained in:
Hermes Agent committed 2026-11-02 21:21:53 +00:00
1 parent ed3b3a2b60
commit 9861367f34
34 files changed
+10736 -121

No files matched your search

View File
File mode changed.
+570
View File
@@ -0,0 +1,570 @@
#!/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))
"""
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
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",
) -> 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.
- 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)"
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") -> dict[str, str]:
"""Run a single Node script invoking `ingglish` on all input strings."""
if not strings:
return {}
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]
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-aq-archive")
parser.add_argument("--workdir", default="/workspace")
parser.add_argument("--out", default=None, help="Optional file path to also save JSON output.")
args = parser.parse_args()
now_utc = datetime.datetime.now(datetime.timezone.utc)
date_info = resolve_target_dates(now_utc, explicit_date=args.date, mode=args.mode)
# 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)
strings_to_translate = list(
{h["headline"] for h in all_headlines} | {c["eng"] for c in 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)
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),
"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,
"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
if __name__ == "__main__":
raise SystemExit(main())