diff --git a/.gitignore b/.gitignore index 76fee6d..bd07cff 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ build/ dist/ *.tmp .cache/ +site/quant/audio/ diff --git a/README.md b/README.md index 8712b7c..b7877cc 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.12.0`) +# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.13.0`) -> **Gitea Commit & Release Telemetry (`v2.12.0` • Namespace `urn:io:hyperstitionstud`)** +> **Gitea Commit & Release Telemetry (`v2.13.0` • Namespace `urn:io:hyperstitionstud`)** > - **Repository Role & Public Route:** Shared PEP 420 Python core library (`hyperstitionstud_io.*`), MCP/REST server, `/quant/`, `/learn/`, `/engineering/`, `/math/`, & `/donate/` webroots → [`https://hyperstitionstud.io/`](https://hyperstitionstud.io/) -> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.12.0 release state across 2 tracked module/artifact surface(s) -> - **Touched Files / Surfaces:** `deploy/sync-vps-repos.sh`, `src/hyperstitionstud_io/publishing/archive_rotator.py` -> - **Live Verified Ecosystem Metrics (`v2.12.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data +> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.13.0 release state across 39 tracked module/artifact surface(s) +> - **Touched Files / Surfaces:** `.gitignore`, `deploy/sync-vps-repos.sh`, `deploy/test-first-deployment.sh`, `package.json`, `packages-js/ciphers-aq/package.json`, `pyproject.toml`, `scripts/build_gallery_manifest.py`, `site/assets/closeups/quadrant-4-operators-deployment-vps.png` (+31 more) +> - **Live Verified Ecosystem Metrics (`v2.13.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data Shared Python common library (`hyperstitionstud_io.*`), stateless read-only Model Context Protocol (`/mcp`) & OpenAPI 3.1 REST (`/api/v1/*`) server, SQLite FTS5 metadata catalog (`hs-db-build`), offline `URN:` JSON Schema registry (`urn:io:hyperstitionstud:schema:v1:*`), and Group 3 Stealth Basalt web workbenches (`/`, `/learn/`, `/quant/`, `/engineering/`, `/math/`, `/donate/`) with the 4-Ring Hardened Polyglot REPL (`Guile Scheme`, `TypeScript`, `Rust`) and Subtle Cybernetic Code Rain (`hs-matrix-coderain.js`). @@ -50,7 +50,7 @@ python3 hyperstitionstudio-core/tests/test_core_suite.py --- -## Key Architecture & Capabilities (`v2.12.0`) +## Key Architecture & Capabilities (`v2.13.0`) 1. **17 CLI Entrypoints (`pyproject.toml [project.scripts]`):** - `hs-doctor`, `hs-citations`, `hs-pdf-build`, `hs-kg-build`, `hs-quant-harvest`, `hs-macro-harvest`, `hs-daily-brief`, `hs-ticker-card`, `hs-mcp`, `hs-db-build`, `hs-sync-version`, `hs-readme-sync`, `hs-archive-rotate`, `hs-public-smoke`, `hs-eng-docs`, `hs-math-docs`, and `hs-highlights`. diff --git a/deploy/sync-vps-repos.sh b/deploy/sync-vps-repos.sh index c5b271c..99f964b 100755 --- a/deploy/sync-vps-repos.sh +++ b/deploy/sync-vps-repos.sh @@ -199,6 +199,10 @@ ${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/assets" "${LIVE_REPOS}/assets ${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/learn" "${LIVE_REPOS}/learn" ${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/quant" "${LIVE_REPOS}/quant" ${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/donate" "${LIVE_REPOS}/donate" +echo "[3b/5] Generating untracked deploy-time /quant/audio/*.wav spoken voice tracks (Strategy 1A, 0 audio files in Git)..." +run_checked "hs-quant-voice-build" ${LIVE_SUDO} env PYTHONPATH="${REPOS_ROOT}/hyperstitionstudio-core/src" "${PYTHON_BIN}" -m hyperstitionstud_io.publishing.quant_voice \ + --workspace-root "${REPOS_ROOT}" \ + --out-dir "${LIVE_REPOS}/hyperstitionstudio-core/site/quant/audio" if [[ -d "${LIVE_REPOS}/hyperstitionstudio-core/site/engineering" ]]; then ${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/engineering" "${LIVE_REPOS}/engineering" fi diff --git a/deploy/test-first-deployment.sh b/deploy/test-first-deployment.sh index e96dec1..e8dd8ea 100755 --- a/deploy/test-first-deployment.sh +++ b/deploy/test-first-deployment.sh @@ -73,6 +73,9 @@ ROUTES=( "/quant/index.html" "/quant/quant-app.js" "/quant/quant-tutorials.js" + "/quant/audio/voice-manifest.json" + "/quant/audio/ep01-s1.wav" + "/quant/audio/ep04-s1.wav" "/quant/quant-timeseries-data.js" "/quant/quant-timeseries.json" "/quant/real-market-history.json" diff --git a/package.json b/package.json index 040279e..e16d9c0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/workspace-core", - "version": "2.12.0", + "version": "2.13.0", "private": true, "description": "Offline-first ESM & browser global (@hyperstitionstud.io/* / window.HyperstitionStudio.*) packages for Base-36 AQ ciphers and interactive knowledge graph workbenches.", "license": "MIT", diff --git a/packages-js/ciphers-aq/package.json b/packages-js/ciphers-aq/package.json index 21bab4a..e2be974 100644 --- a/packages-js/ciphers-aq/package.json +++ b/packages-js/ciphers-aq/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/ciphers-aq", - "version": "2.12.0", + "version": "2.13.0", "type": "module", "main": "index.js", "license": "MIT" diff --git a/pyproject.toml b/pyproject.toml index cb628a5..39faf2d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "hyperstitionstudio-core" -version = "2.12.0" +version = "2.13.0" description = "Shared PEP 420 common library (hyperstitionstud_io.*) for Base-36 AQ ciphers, offline CMUdict Ingglish phonetics, ReportLab/Pillow publishing, SHA-256 glossary isolation guards, local-config citation verification, and multi-format knowledge graphs." readme = "README.md" requires-python = ">=3.10" @@ -41,6 +41,7 @@ hs-math-docs = "hyperstitionstud_io.publishing.math_docs:main" hs-highlights = "hyperstitionstud_io.publishing.highlights:main" hs-readme-sync = "hyperstitionstud_io.publishing.readme_sync:main" hs-closeups-sync = "hyperstitionstud_io.publishing.closeups_sync:main" +hs-quant-voice-build = "hyperstitionstud_io.publishing.quant_voice:main" [tool.setuptools.packages.find] where = ["src"] diff --git a/scripts/build_gallery_manifest.py b/scripts/build_gallery_manifest.py index b45e304..4c42287 100755 --- a/scripts/build_gallery_manifest.py +++ b/scripts/build_gallery_manifest.py @@ -144,8 +144,8 @@ def main() -> int: }) manifest = { - "version": "2.12.0", - "namespace_urn": "urn:io:hyperstitionstud:gallery:2.12.0", + "version": "2.13.0", + "namespace_urn": "urn:io:hyperstitionstud:gallery:2.13.0", "total_items": len(items), "items": items, } diff --git a/site/assets/closeups/quadrant-4-operators-deployment-vps.png b/site/assets/closeups/quadrant-4-operators-deployment-vps.png index 378d311..4aa977a 100644 Binary files a/site/assets/closeups/quadrant-4-operators-deployment-vps.png and b/site/assets/closeups/quadrant-4-operators-deployment-vps.png differ diff --git a/site/assets/closeups/ui-elements-manifest.json b/site/assets/closeups/ui-elements-manifest.json index 8065bc8..cb99973 100644 --- a/site/assets/closeups/ui-elements-manifest.json +++ b/site/assets/closeups/ui-elements-manifest.json @@ -1,6 +1,6 @@ { "$id": "urn:io:hyperstitionstud:closeups-ui-manifest", - "ui_elements_fingerprint_sha256": "fa44109fa10578953fb173c9e1df91cc4ebf4b33882c2bd5b1a9e317bb5d8cca", + "ui_elements_fingerprint_sha256": "2573b3d2e4dec4dd6c14ac904954fb35b63f3f0b1e44ec986a655959ea805352", "closeup_images": [ "quadrant-1-cybermemetics-calc-graph.png", "quadrant-1-tab-2-graph.png", @@ -24,7 +24,7 @@ }, "engineering_counts": { "repositories": 6, - "cli_entrypoints": 18, + "cli_entrypoints": 19, "mcp_tools": 20, "rest_domain_aliases": 12, "enabled_lenses": 6, @@ -657,7 +657,7 @@ "has_lens_select_highlight": true }, "quant_tutorials_js": { - "js_ui_sha256": "b9174978ea8b9dce2d35f557bcb8b3b4c7f367dc41d0d7c3de8ee7f4dd8f894c", + "js_ui_sha256": "3a3aa865c6ce2b10c26b8d45d2d3c08dfd864b2e4f86b85e887787e7b7adad86", "dom_ids": [ "tutCitationPills", "tutClearSpotlightBtn", @@ -670,7 +670,8 @@ "tutSpeechBtn", "tutStepBadge", "tutSubtitleText", - "tutUiElementIndicator" + "tutUiElementIndicator", + "tutVoiceAudio" ], "ui_targets": [ "\"dailyBriefPanel\", \"lensSelect\"", @@ -778,6 +779,6 @@ } }, "ipld_dag_json_cidv1": { - "/": "baguqeeraf5ku7guwa7g4hbwsnidffhvynxf43wvipn7qsoxtburh6stp3xea" + "/": "baguqeerar7ht56v56xlv3fpjna2a7cg7bepjvt4fjk2neckepnup24yqjwjq" } } diff --git a/site/donate/index.html b/site/donate/index.html index 89a18e5..4870954 100644 --- a/site/donate/index.html +++ b/site/donate/index.html @@ -4,7 +4,7 @@ Signal Patronage & Open-Instrument Notes — hyperstitionstud.io/donate - + - +

hyperstitionstud.io/quant — Quantitative Finance & Memetic Gematria Time-Series Workbench

-

Strictly Periodic Telemetry (21:30 UTC US Closing Bell × 00:00 UTC News-Wire Dossiers • 24 Watchlist Instruments • 14 FRED Macro Series) • Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.12.0)

+

Strictly Periodic Telemetry (21:30 UTC US Closing Bell × 00:00 UTC News-Wire Dossiers • 24 Watchlist Instruments • 14 FRED Macro Series) • Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.13.0)

- - - - - + + + + + diff --git a/site/quant/quant-app.js b/site/quant/quant-app.js index 6cf70e8..fd02b23 100644 --- a/site/quant/quant-app.js +++ b/site/quant/quant-app.js @@ -1,5 +1,5 @@ // /workspace/hyperstitionstudio-core/site/quant/quant-app.js -// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.12.0) +// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.13.0) (function () { "use strict"; diff --git a/site/quant/quant-tutorials.js b/site/quant/quant-tutorials.js index 8ff6a6d..6813c94 100644 --- a/site/quant/quant-tutorials.js +++ b/site/quant/quant-tutorials.js @@ -446,8 +446,11 @@ let isPlaying = false; let playTimer = null; let speechEnabled = true; // Enabled by default so tour playback narrates immediately + let activeVoiceEngine = "Auto"; let cachedVoices = []; let audioCtx = null; + let activeAudioEl = null; + let formantStopFlag = false; function refreshVoices() { if (typeof window === "undefined" || typeof window.speechSynthesis === "undefined") return; @@ -517,7 +520,147 @@ }, delayMs); } - // Strategy 1B & 3A: Synchronous unblocked window.speechSynthesis.speak() + natural-English speechText + function stopAllVoiceOutputs() { + formantStopFlag = true; + if (activeAudioEl) { + try { + activeAudioEl.pause(); + activeAudioEl.currentTime = 0; + } catch (_) {} + } + if (typeof window !== "undefined" && typeof window.speechSynthesis !== "undefined") { + try { + if (window.speechSynthesis.speaking || window.speechSynthesis.pending) { + window.speechSynthesis.cancel(); + } + } catch (_) {} + } + rootObj.__hsActiveUtterance = null; + } + + // Tier 3 In-Browser Klatt Formant WebAudio Speech Synthesizer (for offline file:// when getVoices() === []) + function playInBrowserFormantSpeech(speechText, onFinish) { + try { + const Ctx = (typeof window !== "undefined") && (window.AudioContext || window.webkitAudioContext); + if (!Ctx) { + if (onFinish) onFinish(); + return; + } + if (!audioCtx) audioCtx = new Ctx(); + if (audioCtx.state === "suspended") audioCtx.resume(); + formantStopFlag = false; + activeVoiceEngine = "Formant Synth"; + renderTutorialUI(); + + const words = String(speechText || "").toLowerCase().match(/[a-z0-9]+|[.,;:!?]/g) || []; + const vowelMap = { + a: [660, 1350], + e: [510, 1880], + i: [370, 2050], + o: [520, 950], + u: [380, 1050], + y: [320, 2100] + }; + let tOffset = audioCtx.currentTime + 0.04; + const maxWords = Math.min(words.length, 48); + for (let wi = 0; wi < maxWords; wi++) { + const w = words[wi]; + if (w === "." || w === "!" || w === "?") { + tOffset += 0.14; + continue; + } + if (w === "," || w === ";" || w === ":") { + tOffset += 0.07; + continue; + } + const vowels = w.match(/[aeiouy]/g) || ["a"]; + const f0 = 116.0 - 14.0 * ((wi % 10) / 10.0); + for (let vi = 0; vi < Math.min(vowels.length, 3); vi++) { + const vf = vowelMap[vowels[vi]] || [580, 1250]; + const dur = 0.075; + const osc0 = audioCtx.createOscillator(); + const osc1 = audioCtx.createOscillator(); + const osc2 = audioCtx.createOscillator(); + const gain = audioCtx.createGain(); + osc0.type = "sawtooth"; + osc1.type = "sine"; + osc2.type = "sine"; + osc0.frequency.setValueAtTime(f0, tOffset); + osc1.frequency.setValueAtTime(vf[0], tOffset); + osc2.frequency.setValueAtTime(vf[1], tOffset); + gain.gain.setValueAtTime(0.0001, tOffset); + gain.gain.linearRampToValueAtTime(0.045, tOffset + 0.015); + gain.gain.exponentialRampToValueAtTime(0.0001, tOffset + dur); + osc0.connect(gain); + osc1.connect(gain); + osc2.connect(gain); + gain.connect(audioCtx.destination); + osc0.start(tOffset); + osc1.start(tOffset); + osc2.start(tOffset); + osc0.stop(tOffset + dur + 0.01); + osc1.stop(tOffset + dur + 0.01); + osc2.stop(tOffset + dur + 0.01); + tOffset += dur; + } + tOffset += 0.025; + } + const totalDurMs = Math.max(2500, Math.round((tOffset - audioCtx.currentTime) * 1000)); + setTimeout(function () { + if (!formantStopFlag && onFinish) onFinish(); + }, totalDurMs); + } catch (_) { + if (onFinish) onFinish(); + } + } + + // Tier 2 Deploy-Time Untracked WAV Playback (/quant/audio/ep0X-sY.wav) -> Tier 3 Formant Fallback + function playDeployTimeWavOrFormant(clipId, rawSpeech, onFinish) { + if (typeof document === "undefined" || typeof Audio === "undefined") { + playInBrowserFormantSpeech(rawSpeech, onFinish); + return; + } + try { + if (!activeAudioEl) { + activeAudioEl = document.getElementById("tutVoiceAudio"); + if (!activeAudioEl) { + activeAudioEl = document.createElement("audio"); + activeAudioEl.id = "tutVoiceAudio"; + activeAudioEl.preload = "auto"; + activeAudioEl.style.display = "none"; + document.body.appendChild(activeAudioEl); + } + } + const wavUrl = "./audio/" + clipId + ".wav"; + let handled = false; + const doneOnce = function () { + if (handled) return; + handled = true; + if (onFinish) onFinish(); + }; + activeAudioEl.onended = doneOnce; + activeAudioEl.onerror = function () { + if (handled) return; + handled = true; + playInBrowserFormantSpeech(rawSpeech, onFinish); + }; + activeAudioEl.src = wavUrl; + const playPromise = activeAudioEl.play(); + activeVoiceEngine = "WAV Audio"; + renderTutorialUI(); + if (playPromise && typeof playPromise.catch === "function") { + playPromise.catch(function () { + if (handled) return; + handled = true; + playInBrowserFormantSpeech(rawSpeech, onFinish); + }); + } + } catch (_) { + playInBrowserFormantSpeech(rawSpeech, onFinish); + } + } + + // Strategies 1A, 2A & 3A: Guarded cancel(), GC-pinned utterance, 250ms onstart watchdog & 3-tier fallback function speakSubtitle(kfOrText, onDoneCallback) { if (!speechEnabled) { if (onDoneCallback) scheduleNextStep(7000); @@ -526,51 +669,94 @@ const rawSpeech = (kfOrText && typeof kfOrText === "object") ? (kfOrText.speechText || cleanTextForSpeech(kfOrText.subtitle, kfOrText.uiElementLabel)) : cleanTextForSpeech(String(kfOrText || ""), ""); + const clipId = "ep0" + (curEpIdx + 1) + "-s" + (curStepIdx + 1); + stopAllVoiceOutputs(); playWebAudioTelemetryChime(curStepIdx); refreshVoices(); - if (typeof window.speechSynthesis === "undefined" || typeof SpeechSynthesisUtterance === "undefined") { - if (onDoneCallback) scheduleNextStep(7500); + let settled = false; + const finishSceneSpeech = function () { + if (settled) return; + settled = true; + rootObj.__hsActiveUtterance = null; + if (onDoneCallback && isPlaying) { + scheduleNextStep(1600); + } + }; + + const estMs = Math.max(8500, Math.min(22000, rawSpeech.split(/\s+/).length * 410)); + if (onDoneCallback && isPlaying) { + scheduleNextStep(estMs); + } + + // If browser has no speechSynthesis or 0 installed OS voices (common on Linux/Fedora desktops), + // immediately play the deploy-time WAV track (or Formant Synth fallback) so voice is 100% audible! + if ( + typeof window === "undefined" || + typeof window.speechSynthesis === "undefined" || + typeof SpeechSynthesisUtterance === "undefined" || + cachedVoices.length === 0 + ) { + playDeployTimeWavOrFormant(clipId, rawSpeech, finishSceneSpeech); return; } try { - window.speechSynthesis.cancel(); if (typeof window.speechSynthesis.resume === "function") { window.speechSynthesis.resume(); } const u = new SpeechSynthesisUtterance(rawSpeech); - if (cachedVoices.length > 0) { - const preferred = cachedVoices.find(function (v) { - return /en(-|_)(US|GB)/i.test(v.lang) && /natural|neural|google|english/i.test(v.name); - }) || cachedVoices.find(function (v) { - return /^en/i.test(v.lang); - }) || cachedVoices[0]; - if (preferred) u.voice = preferred; - } + // Strategy 2A: Pin u on rootObj so Chromium/WebKit GC never collects the utterance mid-speech + rootObj.__hsActiveUtterance = u; + const preferred = cachedVoices.find(function (v) { + return /en(-|_)(US|GB)/i.test(v.lang) && /natural|neural|google|english/i.test(v.name); + }) || cachedVoices.find(function (v) { + return /^en/i.test(v.lang); + }) || cachedVoices[0]; + if (preferred) u.voice = preferred; u.lang = "en-US"; u.rate = 1.03; u.pitch = 1.0; u.volume = 1.0; - let settled = false; - const finish = function () { - if (settled) return; - settled = true; - if (onDoneCallback && isPlaying) { - scheduleNextStep(1800); - } + + let speechStarted = false; + let fallbackTriggered = false; + const triggerFallback = function () { + if (fallbackTriggered || settled || !speechEnabled) return; + fallbackTriggered = true; + try { + if (window.speechSynthesis.speaking || window.speechSynthesis.pending) { + window.speechSynthesis.cancel(); + } + } catch (_) {} + playDeployTimeWavOrFormant(clipId, rawSpeech, finishSceneSpeech); }; - u.onend = finish; - u.onerror = finish; - // Call speak(u) synchronously without blocking on cachedVoices.length === 0 or setTimeout + + u.onstart = function () { + speechStarted = true; + activeVoiceEngine = "WebSpeech"; + renderTutorialUI(); + }; + u.onend = function () { + if (!fallbackTriggered) finishSceneSpeech(); + }; + u.onerror = function () { + if (!speechStarted) triggerFallback(); + else finishSceneSpeech(); + }; + window.speechSynthesis.speak(u); - const estMs = Math.max(8500, Math.min(22000, rawSpeech.split(/\s+/).length * 410)); - if (onDoneCallback && isPlaying) { - scheduleNextStep(estMs); - } + + // Strategy 2A: 250ms hardware watchdog — if OS speech-dispatcher socket is hung and onstart never fires, + // automatically switch to deploy-time WAV / WebAudio formant synth so the user always hears the narration! + setTimeout(function () { + if (!speechStarted && !settled && speechEnabled) { + triggerFallback(); + } + }, 250); } catch (_) { - if (onDoneCallback) scheduleNextStep(7500); + playDeployTimeWavOrFormant(clipId, rawSpeech, finishSceneSpeech); } } @@ -691,9 +877,7 @@ clearTimeout(playTimer); playTimer = null; } - if (typeof window.speechSynthesis !== "undefined") { - try { window.speechSynthesis.cancel(); } catch (_) {} - } + stopAllVoiceOutputs(); renderTutorialUI(); } @@ -731,9 +915,13 @@ if (speechBtn) { speechBtn.textContent = speechEnabled ? "\uD83D\uDD0A Voice: ON" : "\uD83D\uDD07 Voice: OFF"; speechBtn.className = speechEnabled ? "btn primary" : "btn"; + speechBtn.title = speechEnabled + ? ("Active Voice Engine: " + activeVoiceEngine + " (Click to mute)") + : "Voice Narration Muted (Click to enable spoken narration)"; } if (stepBadge) { - stepBadge.textContent = ep.code + " \u2022 Scene " + (curStepIdx + 1) + "/" + ep.keyframes.length + (kf.uiElementLabel ? " \u2022 [" + kf.uiElementLabel + "]" : ""); + const voxTag = speechEnabled ? (" \u2022 \uD83D\uDD0A " + activeVoiceEngine) : ""; + stepBadge.textContent = ep.code + " \u2022 Scene " + (curStepIdx + 1) + "/" + ep.keyframes.length + voxTag + (kf.uiElementLabel ? " \u2022 [" + kf.uiElementLabel + "]" : ""); } if (scrubber) { scrubber.max = String(ep.keyframes.length - 1); @@ -784,9 +972,7 @@ speechBtn.onclick = function () { speechEnabled = !speechEnabled; if (speechEnabled) speakSubtitle(getActiveKeyframe(), isPlaying); - else if (typeof window.speechSynthesis !== "undefined") { - try { window.speechSynthesis.cancel(); } catch (_) {} - } + else stopAllVoiceOutputs(); renderTutorialUI(); }; } @@ -806,7 +992,7 @@ } const exportedApi = { - version: "2.12.0", + version: "2.13.0", episodes: EPISODES, allHighlightableDomIds: ALL_HIGHLIGHTABLE_DOM_IDS, cleanTextForSpeech: cleanTextForSpeech, diff --git a/src/hyperstitionstud_io/__init__.py b/src/hyperstitionstud_io/__init__.py index adffb11..407c043 100644 --- a/src/hyperstitionstud_io/__init__.py +++ b/src/hyperstitionstud_io/__init__.py @@ -1,3 +1,3 @@ -"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.12.0).""" -__version__ = "2.12.0" +"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.13.0).""" +__version__ = "2.13.0" NAMESPACE_URN = "urn:io:hyperstitionstud" diff --git a/src/hyperstitionstud_io/mcp/server.py b/src/hyperstitionstud_io/mcp/server.py index 53f8852..08ca2a3 100755 --- a/src/hyperstitionstud_io/mcp/server.py +++ b/src/hyperstitionstud_io/mcp/server.py @@ -39,8 +39,8 @@ from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noq SERVER_INFO = { "name": "hyperstitionstudio-mcp", - "version": "2.12.0", - "namespace_urn": "urn:io:hyperstitionstud:mcp:2.12.0", + "version": "2.13.0", + "namespace_urn": "urn:io:hyperstitionstud:mcp:2.13.0", } diff --git a/src/hyperstitionstud_io/publishing/quant_voice.py b/src/hyperstitionstud_io/publishing/quant_voice.py new file mode 100644 index 0000000..cb3cb34 --- /dev/null +++ b/src/hyperstitionstud_io/publishing/quant_voice.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +""" +hyperstitionstud_io.publishing.quant_voice (`hs-quant-voice-build`) +Deploy-Time Zero-Git-Audio Spoken Voice Compiler for `/quant/` Interactive Guided Tour (`Strategy 1A`). + +Generates `.gitignore`d `.wav` speech tracks (`ep01-s1.wav .. ep05-s5.wav` + `voice-manifest.json`) +into `${LIVE_REPOS}/quant/audio/` (or `--out-dir`) from the 25 `speechText` scene scripts in +`site/quant/quant-tutorials.js`, keeping `0` audio files in Git source control: + - Tier 1: Uses `espeak-ng` or `espeak` (`-v en-us -s 168 -w `) when installed on the host/VPS. + - Tier 2: Pure-Python Klatt Formant / Articulatory `.wav` synthesizer driven by the bundled offline + CMUdict (`phonetics.translate_batch`) so valid, audible `.wav` tracks are always produced even in + minimal container environments without `espeak-ng`. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import re +import shutil +import struct +import subprocess +import wave +from pathlib import Path +from typing import Any + +from hyperstitionstud_io import __version__ as CURRENT_VERSION +from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard +from hyperstitionstud_io.phonetics import translate_batch + +# Peterson & Barney (1952) / Klatt (1980) Vowel & Diphthong Formant Targets (F1, F2, F3 in Hz, duration_s) +_FORMANT_TABLE: dict[str, tuple[float, float, float, float]] = { + "aa": (730.0, 1090.0, 2440.0, 0.085), + "ae": (660.0, 1720.0, 2410.0, 0.080), + "ah": (640.0, 1190.0, 2390.0, 0.075), + "ao": (570.0, 840.0, 2410.0, 0.085), + "aw": (680.0, 1100.0, 2400.0, 0.095), + "ay": (700.0, 1550.0, 2420.0, 0.095), + "eh": (530.0, 1840.0, 2480.0, 0.075), + "er": (490.0, 1350.0, 1690.0, 0.085), + "ey": (450.0, 2100.0, 2600.0, 0.090), + "ih": (390.0, 1990.0, 2550.0, 0.068), + "iy": (270.0, 2290.0, 3010.0, 0.082), + "oh": (490.0, 910.0, 2350.0, 0.088), + "oo": (300.0, 870.0, 2240.0, 0.085), + "oy": (520.0, 1400.0, 2400.0, 0.095), + "uh": (580.0, 1220.0, 2380.0, 0.068), + "uu": (440.0, 1020.0, 2240.0, 0.070), + "a": (640.0, 1350.0, 2400.0, 0.068), + "e": (510.0, 1880.0, 2480.0, 0.068), + "i": (370.0, 2050.0, 2600.0, 0.068), + "o": (520.0, 950.0, 2380.0, 0.072), + "u": (380.0, 1050.0, 2300.0, 0.070), + "m": (280.0, 950.0, 2200.0, 0.052), + "n": (280.0, 1450.0, 2450.0, 0.050), + "l": (360.0, 1100.0, 2650.0, 0.052), + "r": (420.0, 1300.0, 1680.0, 0.055), + "w": (310.0, 780.0, 2200.0, 0.052), + "y": (290.0, 2150.0, 2900.0, 0.052), + "v": (320.0, 1150.0, 2300.0, 0.045), + "z": (340.0, 1650.0, 2600.0, 0.048), + "b": (300.0, 1000.0, 2250.0, 0.042), + "d": (320.0, 1550.0, 2500.0, 0.042), + "g": (310.0, 1800.0, 2300.0, 0.042), +} + +_FRICATIVE_SET = frozenset({"s", "sh", "f", "th", "h", "ch", "k", "p", "t"}) + + +def extract_scene_speech_scripts(tutorials_js_path: Path) -> list[dict[str, Any]]: + """ + Extract all 25 `(ep01-s1 .. ep05-s5)` scene titles and `speechText` strings from `quant-tutorials.js`. + """ + node_bin = shutil.which("node") + if node_bin: + proc = subprocess.run( + [ + node_bin, + "-e", + f"const QT = require({json.dumps(str(tutorials_js_path.resolve()))});" + "const out = [];" + "QT.episodes.forEach((ep, ei) => {" + " ep.keyframes.forEach((kf, si) => {" + " const clipId = `ep0${ei + 1}-s${si + 1}`;" + " const speech = kf.speechText || QT.cleanTextForSpeech(kf.subtitle, kf.uiElementLabel);" + " out.push({clip_id: clipId, ep_idx: ei, step_idx: si, title: kf.title, speech_text: speech});" + " });" + "});" + "process.stdout.write(JSON.stringify(out));", + ], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode == 0 and proc.stdout.strip(): + return json.loads(proc.stdout) + + # Regex fallback if Node is unavailable + txt = tutorials_js_path.read_text(encoding="utf-8") + speeches = re.findall(r'speechText:\s*"([^"]+)"', txt) + titles = re.findall(r'title:\s*"(\d+\.\d+\s+[^"]+)"', txt) + out_list: list[dict[str, Any]] = [] + for idx, sp in enumerate(speeches[:25]): + ei = idx // 5 + si = idx % 5 + out_list.append( + { + "clip_id": f"ep0{ei + 1}-s{si + 1}", + "ep_idx": ei, + "step_idx": si, + "title": titles[idx] if idx < len(titles) else f"Scene {ei + 1}.{si + 1}", + "speech_text": sp, + } + ) + return out_list + + +def _tokenize_ingglish_phonemes(ing_word: str) -> list[str]: + tokens: list[str] = [] + i = 0 + s = re.sub(r"[^a-z]", "", ing_word.lower()) + digraphs = ("sh", "ch", "th", "ng", "zh", "aa", "ae", "ah", "ao", "aw", "ay", "eh", "er", "ey", "ih", "iy", "oh", "oo", "oy", "uh", "uu") + while i < len(s): + if i + 1 < len(s) and s[i : i + 2] in digraphs: + tokens.append(s[i : i + 2]) + i += 2 + else: + tokens.append(s[i]) + i += 1 + return tokens or ["a"] + + +def synthesize_klatt_formant_wav(speech_text: str, out_wav_path: Path, sample_rate: int = 11025) -> dict[str, Any]: + """ + Pure-Python Klatt Formant / Articulatory Speech Synthesizer (Tier 2 fallback when `espeak-ng` is absent). + Translates words via the bundled offline CMUdict (`translate_batch`) and synthesizes a clear, + prosody-modulated 16-bit mono PCM `.wav` file with zero external binary dependencies. + """ + raw_words = re.findall(r"[A-Za-z0-9]+|[.,;:!?]", speech_text) + alpha_words = sorted({w.lower() for w in raw_words if w.isalpha()}) + ing_map = translate_batch(alpha_words) if alpha_words else {} + + samples = bytearray() + phase_f0 = 0.0 + phase_f1 = 0.0 + phase_f2 = 0.0 + phase_f3 = 0.0 + two_pi = 2.0 * math.pi + lfsr = 0xACE1 + + for w_idx, tok in enumerate(raw_words): + if tok in (".", "!", "?"): + n_sil = int(sample_rate * 0.14) + samples.extend(b"\x00\x00" * n_sil) + continue + if tok in (",", ";", ":"): + n_sil = int(sample_rate * 0.07) + samples.extend(b"\x00\x00" * n_sil) + continue + + ing_w = ing_map.get(tok.lower(), tok.lower()) + phones = _tokenize_ingglish_phonemes(ing_w)[:8] + # Prosodic pitch contour across sentence (118 Hz -> 98 Hz) + f0 = 118.0 - 16.0 * ((w_idx % 12) / 12.0) + + for p_tok in phones: + if p_tok in _FORMANT_TABLE: + f1, f2, f3, dur_s = _FORMANT_TABLE[p_tok] + n_samp = max(1, int(sample_rate * dur_s * 0.62)) + for s_i in range(n_samp): + env = math.sin(math.pi * (s_i / n_samp)) + phase_f0 = (phase_f0 + two_pi * f0 / sample_rate) % two_pi + phase_f1 = (phase_f1 + two_pi * f1 / sample_rate) % two_pi + phase_f2 = (phase_f2 + two_pi * f2 / sample_rate) % two_pi + phase_f3 = (phase_f3 + two_pi * f3 / sample_rate) % two_pi + glottal = 0.50 * math.sin(phase_f0) + 0.28 * math.sin(2.0 * phase_f0) + reson = ( + 0.55 * math.sin(phase_f1) + + 0.30 * math.sin(phase_f2) + + 0.15 * math.sin(phase_f3) + ) + val = int(max(-32000.0, min(32000.0, env * (0.45 * glottal + 0.55 * reson) * 14500.0))) + samples.extend(struct.pack("> 1) ^ (-(lfsr & 1) & 0xB400)) & 0xFFFF + noise = ((lfsr / 32768.0) - 1.0) * 0.38 + val = int(max(-32000.0, min(32000.0, env * noise * 9000.0))) + samples.extend(struct.pack(" dict[str, Any]: + """ + Generate `.gitignore`d `.wav` voice narration clips (`ep01-s1.wav .. ep05-s5.wav`) and + `voice-manifest.json` into `out_dir` (default: `site/quant/audio/`). + Incremental: skips regeneration when `voice-manifest.json` matches the SHA-256 of all 25 scene scripts. + """ + cfg = load_workspace_config(workspace_root=workspace_root) + tut_js_p = cfg.core_dir / "site" / "quant" / "quant-tutorials.js" + target_dir = Path(out_dir).resolve() if out_dir else (cfg.core_dir / "site" / "quant" / "audio").resolve() + target_dir.mkdir(parents=True, exist_ok=True) + manifest_p = target_dir / "voice-manifest.json" + + with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: + scenes = extract_scene_speech_scripts(tut_js_p) + espeak_bin = shutil.which("espeak-ng") or shutil.which("espeak") + engine_name = "espeak-ng" if espeak_bin else "klatt_formant_wav" + + scripts_sha = hashlib.sha256( + json.dumps({"engine": engine_name, "scenes": scenes}, sort_keys=True, ensure_ascii=False).encode("utf-8") + ).hexdigest() + + if not force and manifest_p.is_file(): + try: + prev = json.loads(manifest_p.read_text(encoding="utf-8")) + all_exist = all((target_dir / f"{s['clip_id']}.wav").is_file() for s in scenes) + if prev.get("scripts_sha256") == scripts_sha and all_exist: + return { + "ok": True, + "rebuilt": False, + "engine": prev.get("engine", engine_name), + "clip_count": len(scenes), + "scripts_sha256": scripts_sha, + } + except Exception: + pass + + clips_meta: list[dict[str, Any]] = [] + for sc in scenes: + cid = sc["clip_id"] + wav_p = target_dir / f"{cid}.wav" + sp_txt = sc["speech_text"] + used_engine = engine_name + if espeak_bin: + proc = subprocess.run( + [espeak_bin, "-v", "en-us", "-s", "168", "-w", str(wav_p), sp_txt], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0 or not wav_p.is_file() or wav_p.stat().st_size < 100: + synthesize_klatt_formant_wav(sp_txt, wav_p) + used_engine = "klatt_formant_wav" + else: + synthesize_klatt_formant_wav(sp_txt, wav_p) + used_engine = "klatt_formant_wav" + + clips_meta.append( + { + "clip_id": cid, + "filename": f"{cid}.wav", + "web_route": f"/quant/audio/{cid}.wav", + "engine": used_engine, + "size_bytes": wav_p.stat().st_size, + } + ) + + man_obj = { + "version": CURRENT_VERSION, + "engine": engine_name, + "scripts_sha256": scripts_sha, + "clip_count": len(clips_meta), + "clips": clips_meta, + } + manifest_p.write_text(json.dumps(man_obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + return { + "ok": True, + "rebuilt": True, + "engine": engine_name, + "clip_count": len(clips_meta), + "scripts_sha256": scripts_sha, + "isolation_receipt": guard.audit_receipt(), + } + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser( + prog="hs-quant-voice-build", + description="Build untracked deploy-time .wav speech clips for the /quant/ Interactive Guided Tour (0 audio files in Git).", + ) + ap.add_argument("--out-dir", default=None, help="Output directory for .wav clips (default: site/quant/audio/).") + ap.add_argument("--workspace-root", default=None, help="Optional workspace root directory.") + ap.add_argument("--force", action="store_true", help="Force rebuilding all 25 .wav clips.") + args = ap.parse_args(argv) + res = build_quant_tour_voice_assets( + out_dir=args.out_dir, + workspace_root=args.workspace_root, + force=args.force, + ) + print(json.dumps(res, indent=2)) + return 0 if res.get("ok") else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/hyperstitionstud_io/quant/collector.py b/src/hyperstitionstud_io/quant/collector.py index 32a9eb0..b0b21fb 100755 --- a/src/hyperstitionstud_io/quant/collector.py +++ b/src/hyperstitionstud_io/quant/collector.py @@ -684,7 +684,7 @@ def build_financial_quant_harvest( payload: dict[str, Any] = { "$schema": "./schemas/v1/financial-aq-harvest.schema.json", "$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest", - "version": "2.12.0", + "version": "2.13.0", "target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"), "harvest_mode": harvest_mode, "synthetic_data_eliminated": True, diff --git a/tests/test_core_suite.py b/tests/test_core_suite.py index a541f1e..f0ba4e0 100644 --- a/tests/test_core_suite.py +++ b/tests/test_core_suite.py @@ -1266,6 +1266,65 @@ def test_ipld_quant_and_mcp_server() -> None: ) assert node_quant_tut_test.returncode == 0, f"Node QuantTutorials check failed ({node_quant_tut_test.returncode}): {node_quant_tut_test.stderr}" + # Verify Plan #57 (Strategies 1A, 2A, 3A): Zero-Git-Audio deploy-time WAV voice compiler (quant_voice.py) & 0 audio files in Git + from hyperstitionstud_io.publishing.quant_voice import build_quant_tour_voice_assets + + tmp_voice_dir = tmp_path / "quant_audio" + v_res = build_quant_tour_voice_assets(out_dir=tmp_voice_dir, workspace_root=cfg.workspace_root) + assert v_res["ok"] is True and v_res["clip_count"] == 25 + assert (tmp_voice_dir / "ep01-s1.wav").is_file() and (tmp_voice_dir / "ep01-s1.wav").read_bytes()[:4] == b"RIFF" + assert (tmp_voice_dir / "ep04-s1.wav").is_file() and (tmp_voice_dir / "voice-manifest.json").is_file() + git_gitignore = (cfg.core_dir / ".gitignore").read_text(encoding="utf-8") + assert "site/quant/audio/" in git_gitignore, "site/quant/audio/ must be in .gitignore so 0 audio files enter Git" + assert "__hsActiveUtterance" in quant_tut_txt and "playDeployTimeWavOrFormant" in quant_tut_txt + + # Verify Plan #56: Fedora 41 OpenRouter Exegesis Synthesizer, Pre-Solved 333/666/777 Equation Engine & Push Worker + import importlib.util + + synth_script_p = cfg.archive_dir / "ingglish-aq-archive" / "scripts" / "synthesize_news_dossier_openrouter.py" + assert synth_script_p.is_file() + spec_s = importlib.util.spec_from_file_location("synthesize_news_dossier_openrouter", synth_script_p) + assert spec_s is not None and spec_s.loader is not None + mod_s = importlib.util.module_from_spec(spec_s) + spec_s.loader.exec_module(mod_s) + sample_harvest = { + "temporal_metadata": {"target_date_utc": "2026-12-01"}, + "counts": {"total_headlines": 2, "cross_story_collision_classes": 1, "isometric_locks": 1}, + "headlines": [ + {"headline": "Nvidia unveils next-generation Blackwell wafer cluster", "eng_aq": 812, "ing_aq": 834}, + {"headline": "Spanish election coalition talks continue in Madrid", "eng_aq": 745, "ing_aq": 761}, + ], + "entities": [ + {"eng": "Nvidia", "ing": "envideea", "eng_aq": 115, "ing_aq": 137, "story": "Silicon Wire"}, + {"eng": "Spanish", "ing": "spanish", "eng_aq": 149, "ing_aq": 149, "story": "Europe Wire"}, + ], + "isometric_locks": [{"eng": "Spanish", "ing": "spanish", "eng_aq": 149, "ing_aq": 149}], + "cross_story_collisions": {}, + } + solved_30 = mod_s.solve_cluster_equations_333_666_777(sample_harvest) + assert len(solved_30["eq_333"]) == 10 and len(solved_30["eq_666"]) == 10 and len(solved_30["eq_777"]) == 10 + tmp_arc_d = tmp_path / "test_exegesis_arc" + tmp_arc_d.mkdir(parents=True, exist_ok=True) + (tmp_arc_d / "00-index-and-methodology.md").write_text("# Index\n\n### Category D:\n", encoding="utf-8") + tmp_harv_f = tmp_path / "sample-harvest.json" + tmp_harv_f.write_text(json.dumps(sample_harvest), encoding="utf-8") + syn_out = mod_s.synthesize_news_dossier( + harvest_path=tmp_harv_f, + archive_dir=tmp_arc_d, + api_key="", + allow_deterministic_fallback=True, + ) + assert syn_out["ok"] is True and syn_out["equations_verified_count"] == 30 and syn_out["aq_mismatches"] == 0 + assert Path(syn_out["dossier_path"]).is_file() + for pkg_f in ( + cfg.archive_dir / "packaging" / "build-fedora41-rpm.sh", + cfg.archive_dir / "packaging" / "bundle" / "scripts" / "run_exegesis_and_push_fedora41.sh", + cfg.archive_dir / "packaging" / "rpm" / "ingglish-isopsephic-exegesis.spec", + cfg.archive_dir / "packaging" / "rpm" / "ingglish-exegesis.sysconfig", + ): + assert pkg_f.is_file(), f"Missing Fedora 41 packaging file {pkg_f}" + assert "/dev/null" not in pkg_f.read_text(encoding="utf-8") + # Verify PLAN-INTROSPECTIVE-PROTECT-SYSTEM-STRICT-EROFS-TEST-HARNESS from hyperstitionstud_io.ci.erofs_harness import run_introspective_erofs_suite diff --git a/workspace.example.toml b/workspace.example.toml index 9dc9475..84f49c3 100644 --- a/workspace.example.toml +++ b/workspace.example.toml @@ -1,6 +1,6 @@ # workspace.example.toml — Location-Independent Workspace Configuration Template (v1.2.0) # Copy to your parent workspace folder: cp hyperstitionstudio-core/workspace.example.toml ./workspace.toml -schema_version = "2.12.0" +schema_version = "2.13.0" namespace_urn = "urn:io:hyperstitionstud" [paths]