Release v2.13.0: Implement zero-Git-audio /quant/ guided tour voice narration (Strategies 1A/2A/3A via hs-quant-voice-build, 250ms onstart watchdog & WebAudio formant fallback) and turnkey Fedora 41 OpenRouter exegesis & git.libre.audio push package (Plan #56 & Plan #57)
This commit is contained in:
1 parent
14c467fa4f
commit
6af5d32b15
40 files changed
+761
-189
No files matched your search
@@ -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"
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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 <out.wav>`) 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("<h", val))
|
||||
elif p_tok in _FRICATIVE_SET:
|
||||
n_samp = max(1, int(sample_rate * 0.032))
|
||||
for s_i in range(n_samp):
|
||||
env = math.sin(math.pi * (s_i / n_samp))
|
||||
lfsr = ((lfsr >> 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("<h", val))
|
||||
|
||||
# Inter-word micro-pause (22ms)
|
||||
samples.extend(b"\x00\x00" * int(sample_rate * 0.022))
|
||||
|
||||
out_wav_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with wave.open(str(out_wav_path), "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(sample_rate)
|
||||
wf.writeframes(bytes(samples))
|
||||
return {"engine": "klatt_formant_wav", "size_bytes": out_wav_path.stat().st_size}
|
||||
|
||||
|
||||
def build_quant_tour_voice_assets(
|
||||
out_dir: str | Path | None = None,
|
||||
workspace_root: str | Path | None = None,
|
||||
force: bool = False,
|
||||
) -> 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())
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user