awdeck 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
awdeck/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """awdeck - Aither World Deck. A slides outline becomes a narrated video."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ from .narrate import FALLBACK, PLANE, NarrationPath, probe_plane, synthesize
6
+ from .render import render, render_frame
7
+
8
+ __all__ = [
9
+ "FALLBACK",
10
+ "PLANE",
11
+ "NarrationPath",
12
+ "probe_plane",
13
+ "render",
14
+ "render_frame",
15
+ "synthesize",
16
+ ]
awdeck/_doctor.py ADDED
@@ -0,0 +1,198 @@
1
+ """Stack-aware `doctor` for awdeck.
2
+
3
+ GENERATED BY gen_aw_doctor.py -- DO NOT EDIT.
4
+ Regenerate it with the generator named above; a hand-edit here is reverted by
5
+ the next run and fails the parity gate.
6
+
7
+ Why a doctor exists at all: the aw* bricks are designed to COMPOSE, so the
8
+ interesting failures live BETWEEN them. "awdeck is installed" is not the useful
9
+ fact -- "awdeck is installed and the thing it pairs with is not" is. This reports
10
+ the whole stack, not just itself.
11
+
12
+ stdlib only, on purpose: a diagnostic that cannot run because a dependency is
13
+ missing is worthless precisely when you need it.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import os
19
+ import shutil
20
+ import sys
21
+
22
+ #: Frozen from the Aither World registry at generation time. A shipped
23
+ #: package cannot read the registry, and a doctor that guessed at the family
24
+ #: would go stale in silence. Regenerate to update.
25
+ SELF = 'awdeck'
26
+ FAMILY = [
27
+ 'awask', 'awavatar', 'awbac', 'awbrain', 'awbrowse', 'awcams', 'awclassify', 'awdecide',
28
+ 'awdelphi', 'awdit', 'awembed', 'awevolve', 'awfind', 'awflow', 'awfocus', 'awgit', 'awgraph',
29
+ 'awgym', 'awiam', 'awkno', 'awm', 'awmail', 'awmine', 'awnboard', 'awnest', 'awnet', 'awplay',
30
+ 'awpool', 'awpredict', 'awprism', 'awprove', 'awreason', 'awrecover', 'awrecurse', 'awrelay',
31
+ 'awrena', 'awrepl', 'awreport', 'awresearch', 'awrise', 'awrouter', 'awrtifact', 'awrun',
32
+ 'awscope', 'awscreen', 'awseal', 'awsettings', 'awshare', 'awsprite', 'awstorage', 'awsuite',
33
+ 'awswarm', 'awtax', 'awtoll', 'awtunnel', 'awvision', 'awvoice', 'awwall', 'gawbbonet',
34
+ ]
35
+ PAIRS_WITH = ['adk', 'awrtifact', 'awvoice']
36
+
37
+ #: This brick's OWN config, read out of its source at generation time.
38
+ #: ENV_REQUIRED is `os.environ["X"]` -- absent, that is a KeyError the moment
39
+ #: the line runs. ENV_OPTIONAL is `os.getenv("X")`, which returns None and lets
40
+ #: the caller cope. Only this brick's namespace is listed: reporting the
41
+ #: platform-wide vars it also touches would be noise, and a doctor that floods
42
+ #: gets ignored.
43
+ ENV_REQUIRED = ['AWDECK_FONT_DIR']
44
+ ENV_OPTIONAL = []
45
+
46
+
47
+ def _installed(mod: str) -> "str | None":
48
+ """Version if importable, else None. Never raises -- a broken sibling must
49
+ not take the diagnostic down with it."""
50
+ try:
51
+ if importlib.util.find_spec(mod) is None:
52
+ return None
53
+ except (ImportError, ValueError):
54
+ return None
55
+ try:
56
+ from importlib.metadata import PackageNotFoundError, version
57
+ try:
58
+ return version(mod)
59
+ except PackageNotFoundError:
60
+ return "installed"
61
+ except Exception:
62
+ return "installed"
63
+
64
+
65
+ def report(out=None) -> int:
66
+ """Print the stack picture. 0 = this brick and its pairs are present."""
67
+ out = out or sys.stdout
68
+ print(f"{SELF} doctor", file=out)
69
+
70
+ mine = _installed(SELF)
71
+ print(f" self {SELF} {mine or 'NOT IMPORTABLE'}", file=out)
72
+ shim = shutil.which(SELF)
73
+ print(f" command {shim or 'not on PATH'}", file=out)
74
+
75
+ # The stack. Siblings this brick pairs with are called out separately,
76
+ # because a missing pair is a REASON, while a missing unrelated brick is
77
+ # just a fact about your machine.
78
+ missing_pairs, present = [], []
79
+ for name in FAMILY:
80
+ v = _installed(name)
81
+ if v:
82
+ present.append(name)
83
+ elif name in PAIRS_WITH:
84
+ missing_pairs.append(name)
85
+ print(f" stack {len(present)}/{len(FAMILY)} aw* packages installed",
86
+ file=out)
87
+ if present:
88
+ print(f" {' '.join(sorted(present))}", file=out)
89
+
90
+ missing_req = [v for v in ENV_REQUIRED if not os.environ.get(v)]
91
+ if ENV_REQUIRED or ENV_OPTIONAL:
92
+ have = sum(1 for v in ENV_REQUIRED + ENV_OPTIONAL if os.environ.get(v))
93
+ total = len(ENV_REQUIRED) + len(ENV_OPTIONAL)
94
+ print(f" config {have}/{total} of this brick's own vars set", file=out)
95
+ if missing_req:
96
+ # Not a preference. os.environ[...] raises the moment it runs.
97
+ print(f" MISSING REQUIRED: {' '.join(missing_req)}", file=out)
98
+
99
+ local = _local_checks()
100
+ for line in local:
101
+ print(f" {line}", file=out)
102
+ problems, unjudged = _local_verdict()
103
+
104
+ if mine is None:
105
+ print(f"\nverdict: {SELF} itself is not importable. Reinstall it before "
106
+ f"anything else here means much.", file=out)
107
+ return 1
108
+ if missing_req:
109
+ print(f"\nverdict: {SELF} is missing required config "
110
+ f"({', '.join(missing_req)}). Those are read with os.environ[...], "
111
+ f"so the code path that needs them raises rather than degrades.",
112
+ file=out)
113
+ return 1
114
+ # A measured NO outranks a missing optional pair: awrise printed
115
+ # "nothing wakes run-due" and still exited 0 because the missing-pairs
116
+ # branch returned first (measured 2026-09-20).
117
+ if problems:
118
+ for p in problems:
119
+ print(f"\nverdict: {p}", file=out)
120
+ return 1
121
+ if unjudged:
122
+ for u in unjudged:
123
+ print(f"\nverdict: UNJUDGED -- could not judge: {u}", file=out)
124
+ return 2
125
+ if missing_pairs:
126
+ print(f"\nverdict: {SELF} works, but pairs with "
127
+ f"{', '.join(sorted(missing_pairs))} which "
128
+ f"{'is' if len(missing_pairs) == 1 else 'are'} not installed. "
129
+ f"That is a capability you are missing, not an error.", file=out)
130
+ return 0
131
+ print(f"\nverdict: {SELF} and everything it pairs with are present.", file=out)
132
+ return 0
133
+
134
+
135
+ def _local_verdict() -> tuple:
136
+ """The brick's OWN verdict, folded into the exit code.
137
+
138
+ Without this the local lines are DECORATION. Measured 2026-09-20: awrise
139
+ printed "hostclock NOT INSTALLED -- nothing wakes run-due" and "last tick
140
+ never", then exited 0 -- teaching an operator that a doctor exit code
141
+ carries no information. A brick opts in with `_doctor_local_verdict()`
142
+ returning (problems, unjudged); a brick without one is unaffected.
143
+ """
144
+ try:
145
+ mod = importlib.import_module(f"{SELF}.doctor_local")
146
+ problems, unjudged = mod._doctor_local_verdict()
147
+ except Exception: # noqa: BLE001
148
+ return [], []
149
+ return list(problems or []), list(unjudged or [])
150
+
151
+
152
+ def _local_checks() -> "list[str]":
153
+ """Per-brick checks, if this package defines them.
154
+
155
+ Kept as a HOOK rather than generated guesses: the generator knows the family
156
+ from the registry, but it does not know what awdeck needs at runtime, and a
157
+ doctor that invented config requirements would be confidently wrong. A
158
+ package supplies `_doctor_local()` returning display lines; absent, the
159
+ stack picture above still stands on its own.
160
+ """
161
+ try:
162
+ mod = importlib.import_module(f"{SELF}.doctor_local")
163
+ except Exception:
164
+ return []
165
+ try:
166
+ return list(mod._doctor_local())
167
+ except Exception as exc: # noqa: BLE001
168
+ return [f"local checks raised {type(exc).__name__}: {exc}"]
169
+
170
+
171
+ def main(argv: "list[str] | None" = None) -> int:
172
+ # --self-test delegates to a SIBLING module when one exists.
173
+ #
174
+ # This file is generated and a fresh run replaces it, so a self-test
175
+ # written HERE is deleted by the next regeneration. awdelphi learned that
176
+ # the expensive way: 125 lines exercising four real failure paths --
177
+ # convergence, roster anonymization, resume, gateway-down -- lived in this
178
+ # file and were destroyed by a routine regeneration, silently, leaving a
179
+ # --self-test flag that reported PASS while asserting nothing.
180
+ #
181
+ # So the seam is a separate module the generator never writes. A package
182
+ # with real machinery to prove puts it in _selftest.py; everything else
183
+ # keeps the honest answer below rather than a self-test that only ever
184
+ # passes.
185
+ argv = list(argv if argv is not None else __import__("sys").argv[1:])
186
+ if "--self-test" in argv:
187
+ try:
188
+ from . import _selftest as _st
189
+ except Exception:
190
+ print("no _selftest module: this doctor reports the stack, and has",
191
+ "no machinery of its own to prove")
192
+ return 0
193
+ return int(_st.run())
194
+ return report()
195
+
196
+
197
+ if __name__ == "__main__":
198
+ raise SystemExit(main())
awdeck/cli.py ADDED
@@ -0,0 +1,144 @@
1
+ """awdeck — Aither World Deck. Turn a slides outline into a narrated video."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .narrate import probe_plane, tts_url
11
+ from .render import render
12
+
13
+
14
+ def _self_test() -> int:
15
+ """Exit 0 only when each guard is PROVEN to still fire. Never 0 on silence."""
16
+ import tempfile
17
+
18
+ from . import narrate as _n
19
+
20
+ failures: list[str] = []
21
+ real_probe, real_url, real_plane = _n.probe_plane, _n.tts_url, _n._synthesize_plane
22
+ try:
23
+ with tempfile.TemporaryDirectory() as td:
24
+ out = Path(td) / "a.mp3"
25
+
26
+ # arm 1 — plane reachable, synthesis fails: must RAISE, not degrade.
27
+ _n.tts_url = lambda env=None: "http://voice/synthesize"
28
+ _n.probe_plane = lambda url, timeout=4.0: True
29
+
30
+ def _boom(text, o, v):
31
+ raise RuntimeError("stream closed")
32
+
33
+ _n._synthesize_plane = _boom
34
+ try:
35
+ _n.synthesize("x", out, allow_fallback=False)
36
+ except RuntimeError as exc:
37
+ if "Refusing to silently downgrade" not in str(exc):
38
+ failures.append(f"arm 1: wrong error: {exc}")
39
+ else:
40
+ failures.append("arm 1: a silent downgrade was ALLOWED")
41
+
42
+ # arm 2 — plane unreachable, fallback not allowed: must RAISE.
43
+ _n.tts_url = lambda env=None: None
44
+ _n.probe_plane = lambda url, timeout=4.0: False
45
+ refused = False
46
+ try:
47
+ _n.synthesize("x", out, allow_fallback=False)
48
+ except RuntimeError:
49
+ refused = True # correct: no plane and no permission
50
+ if not refused:
51
+ failures.append("arm 2: rendered with no plane and no permission")
52
+
53
+ # arm 3 — a downgrade taken on purpose is recorded, not hidden.
54
+ n = _n.NarrationPath(_n.FALLBACK, "sapi", "windows-sapi", plane_reachable=True)
55
+ if not n.is_silent_downgrade:
56
+ failures.append("arm 3: is_silent_downgrade did not flag the defect")
57
+
58
+ # arm 4 — a substituted voice is visible.
59
+ sub = _n.NarrationPath(_n.PLANE, "onyx", "p", True, voice_served="en-GB-SoniaNeural")
60
+ if not sub.voice_substituted:
61
+ failures.append("arm 4: voice substitution was not detected")
62
+ finally:
63
+ _n.probe_plane, _n.tts_url, _n._synthesize_plane = real_probe, real_url, real_plane
64
+
65
+ if failures:
66
+ for f in failures:
67
+ print(f"SELF-TEST FAIL: {f}", file=sys.stderr)
68
+ return 1
69
+ print("awdeck self-test OK: 4 arms, the fail-closed guards still fire")
70
+ return 0
71
+
72
+
73
+ def main(argv: list[str] | None = None) -> int:
74
+ # GENERATED repo-state intercept (gen_aw_doctor.py) -- do not edit
75
+ try:
76
+ from awgit import state as _aw_state
77
+ except Exception:
78
+ _aw_state = None
79
+ if _aw_state is not None:
80
+ _sv = locals().get("argv")
81
+ if _aw_state.cli_banner(_sv if _sv is not None else __import__("sys").argv[1:]):
82
+ return 0
83
+ ap = argparse.ArgumentParser(prog="awdeck", description=__doc__)
84
+ # The family contract is `awXXX --self-test` (34 of the bricks do this), so
85
+ # the FLAG has to work, not only the subcommand. `required=True` on the
86
+ # subparsers made the bare flag exit 2 with "the following arguments are
87
+ # required: cmd" — which reads as a broken CLI, not as a passing self-test.
88
+ ap.add_argument("--self-test", action="store_true", help=argparse.SUPPRESS)
89
+ sub = ap.add_subparsers(dest="cmd")
90
+
91
+ r = sub.add_parser("render", help="slides.json -> narrated mp4 + manifest")
92
+ r.add_argument("slides", type=Path)
93
+ r.add_argument("--out", type=Path, required=True)
94
+ r.add_argument("--voice", default="onyx")
95
+ r.add_argument(
96
+ "--allow-fallback",
97
+ action="store_true",
98
+ help="permit a degraded local voice; the manifest records that it happened",
99
+ )
100
+
101
+ sub.add_parser("doctor", help="is the voice plane reachable?")
102
+ sub.add_parser("self-test", help="prove the fail-closed guard still fires")
103
+ args = ap.parse_args(argv)
104
+
105
+ if getattr(args, "self_test", False) or args.cmd == "self-test":
106
+ return _self_test()
107
+
108
+ if args.cmd is None:
109
+ ap.print_help(sys.stderr)
110
+ return 2
111
+
112
+ if args.cmd == "doctor":
113
+ url = tts_url()
114
+ ok = probe_plane(url)
115
+ print(f"AWVOICE_TTS_URL = {url or '(unset)'}")
116
+ print(f"plane reachable = {ok}")
117
+ return 0 if ok else 1
118
+
119
+ try:
120
+ manifest = render(
121
+ args.slides,
122
+ args.out,
123
+ voice=args.voice,
124
+ allow_fallback=args.allow_fallback,
125
+ )
126
+ except RuntimeError as exc:
127
+ print(f"awdeck: {exc}", file=sys.stderr)
128
+ return 1
129
+
130
+ print(json.dumps(manifest, indent=2))
131
+ n = manifest["narration"]
132
+ if n.get("path") == "local-fallback" and n.get("plane_reachable"):
133
+ print("\nWARNING: degraded voice while the plane was up (MNP003)", file=sys.stderr)
134
+ return 1
135
+ if n.get("voice_served") and n["voice_served"] != n.get("voice"):
136
+ print(
137
+ f"\nNOTE: asked for {n['voice']!r}, served {n['voice_served']!r}",
138
+ file=sys.stderr,
139
+ )
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ sys.exit(main())
awdeck/narrate.py ADDED
@@ -0,0 +1,193 @@
1
+ """Narration with a PREFERRED plane and an honest fallback.
2
+
3
+ The whole point of this module is the thing that went wrong on 2026-09-19: a
4
+ session hit one long-job transport failure, concluded "the fleet is down", and
5
+ silently narrated a video with a 2010-era Windows SAPI voice while the voice
6
+ plane was healthy the entire time. Nothing recorded that choice, so nothing
7
+ could catch it.
8
+
9
+ So: every synthesis records WHICH path produced it and whether the plane was
10
+ reachable at the time. `check_media_narration_plane.py` fails the build when a
11
+ fallback was taken while the plane answered.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import urllib.error
21
+ import urllib.request
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+
26
+ PLANE = "plane"
27
+ FALLBACK = "local-fallback"
28
+
29
+ DEFAULT_PROBE_TIMEOUT = 4.0
30
+
31
+
32
+ @dataclass
33
+ class NarrationPath:
34
+ """How a narration track was produced, and what was true when it was."""
35
+
36
+ path: str
37
+ voice: str
38
+ provider: str
39
+ plane_reachable: bool
40
+ voice_served: str = ""
41
+ checked_at: str = field(
42
+ default_factory=lambda: datetime.now(timezone.utc).isoformat()
43
+ )
44
+ detail: str = ""
45
+
46
+ @property
47
+ def is_silent_downgrade(self) -> bool:
48
+ """A fallback taken while the plane was answering. The defect."""
49
+ return self.path == FALLBACK and self.plane_reachable
50
+
51
+ @property
52
+ def voice_substituted(self) -> bool:
53
+ """Asked for one voice, got another, and nothing said so."""
54
+ return bool(self.voice_served) and self.voice_served != self.voice
55
+
56
+ def as_dict(self) -> dict:
57
+ return {
58
+ "path": self.path,
59
+ "voice": self.voice,
60
+ "voice_served": self.voice_served,
61
+ "provider": self.provider,
62
+ "plane_reachable": self.plane_reachable,
63
+ "checked_at": self.checked_at,
64
+ "detail": self.detail,
65
+ }
66
+
67
+
68
+ def tts_url(environment: dict[str, str] | None = None) -> str | None:
69
+ env = environment if environment is not None else os.environ
70
+ return env.get("AWVOICE_TTS_URL") or None
71
+
72
+
73
+ def probe_plane(url: str | None, timeout: float = DEFAULT_PROBE_TIMEOUT) -> bool:
74
+ """Is the voice plane answering RIGHT NOW?
75
+
76
+ Deliberately cheap and deliberately separate from synthesis: the failure we
77
+ are guarding against is concluding "unreachable" from an unrelated error.
78
+ """
79
+ if not url:
80
+ return False
81
+ try:
82
+ req = urllib.request.Request(url, method="OPTIONS")
83
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
84
+ return resp.status < 500
85
+ except urllib.error.HTTPError as exc:
86
+ # A 4xx means something answered. That is reachable.
87
+ return exc.code < 500
88
+ except Exception:
89
+ return False
90
+
91
+
92
+ def _synthesize_plane(text: str, out: Path, voice: str, url: str | None = None) -> str:
93
+ """POST to the voice plane, write bytes, return the voice it ACTUALLY served.
94
+
95
+ `return_base64` matters: the service otherwise answers with a path inside its
96
+ own container, and the caller shares no filesystem with it. Bytes travel,
97
+ paths do not.
98
+
99
+ The returned voice is not decoration. Measured 2026-09-19: `/voice/synthesize`
100
+ declares a `voice` parameter and serves `en-GB-SoniaNeural` whatever you ask
101
+ for, so the only way to know what you got is to read it back.
102
+ """
103
+ import base64 # noqa: PLC0415
104
+ import json # noqa: PLC0415
105
+
106
+ url = url or tts_url()
107
+ payload = json.dumps({
108
+ "text": text,
109
+ "voice": voice,
110
+ "format": "mp3",
111
+ "return_base64": True,
112
+ }).encode("utf-8")
113
+ req = urllib.request.Request(
114
+ url, data=payload, headers={"Content-Type": "application/json"}, method="POST"
115
+ )
116
+ with urllib.request.urlopen(req, timeout=120) as resp:
117
+ body = json.loads(resp.read().decode("utf-8"))
118
+ if not body.get("success"):
119
+ raise RuntimeError(f"voice plane refused: {body.get('error')!r}")
120
+ b64 = body.get("audio_base64")
121
+ if not b64:
122
+ raise RuntimeError(
123
+ "voice plane returned no audio_base64 — it answered with a path "
124
+ f"({body.get('audio_path')!r}) this process cannot read"
125
+ )
126
+ out.write_bytes(base64.b64decode(b64))
127
+ return body.get("voice") or voice
128
+
129
+
130
+ def _synthesize_local(text: str, out: Path, voice: str) -> None:
131
+ """Windows SAPI. The last resort, never the default."""
132
+ if sys.platform != "win32":
133
+ raise RuntimeError("no local TTS fallback on this platform")
134
+ script = (
135
+ "Add-Type -AssemblyName System.Speech; "
136
+ "$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
137
+ f"$s.SetOutputToWaveFile('{out}'); "
138
+ "$s.Speak([Console]::In.ReadToEnd()); "
139
+ "$s.Dispose()"
140
+ )
141
+ subprocess.run(
142
+ ["powershell", "-NoProfile", "-Command", script],
143
+ input=text.encode("utf-8"),
144
+ check=True,
145
+ )
146
+
147
+
148
+ def synthesize(
149
+ text: str,
150
+ out: Path,
151
+ voice: str = "onyx",
152
+ *,
153
+ allow_fallback: bool = False,
154
+ environment: dict[str, str] | None = None,
155
+ ) -> NarrationPath:
156
+ """Speak `text` into `out`, preferring the plane.
157
+
158
+ `allow_fallback` is OFF by default on purpose. A caller that wants the
159
+ degraded voice has to say so, and the manifest records that it happened.
160
+ """
161
+ url = tts_url(environment)
162
+ reachable = probe_plane(url)
163
+
164
+ if reachable:
165
+ try:
166
+ served = _synthesize_plane(text, out, voice, url)
167
+ return NarrationPath(PLANE, voice, f"awvoice:{url}", True, voice_served=served)
168
+ except Exception as exc: # plane answered the probe then failed the call
169
+ if not allow_fallback:
170
+ raise RuntimeError(
171
+ f"voice plane reachable at {url} but synthesis failed: {exc}. "
172
+ "Refusing to silently downgrade; pass allow_fallback=True to override."
173
+ ) from exc
174
+ _synthesize_local(text, out, voice)
175
+ return NarrationPath(
176
+ FALLBACK, voice, "windows-sapi", True,
177
+ detail=f"plane reachable but synthesis raised: {exc}",
178
+ )
179
+
180
+ if not allow_fallback:
181
+ raise RuntimeError(
182
+ f"voice plane unreachable (AWVOICE_TTS_URL={url!r}) and fallback not allowed. "
183
+ "Fix the plane, or pass allow_fallback=True and accept a recorded downgrade."
184
+ )
185
+ _synthesize_local(text, out, voice)
186
+ return NarrationPath(
187
+ FALLBACK, voice, "windows-sapi", False,
188
+ detail="plane did not answer the probe",
189
+ )
190
+
191
+
192
+ def have_ffmpeg() -> bool:
193
+ return shutil.which("ffmpeg") is not None
awdeck/render.py ADDED
@@ -0,0 +1,265 @@
1
+ """Slides JSON -> frames -> narrated mp4, with a manifest that records the truth.
2
+
3
+ The manifest (`<name>.deck.json`) is the point. A rendered video looks identical
4
+ whether it was narrated by the voice plane or by a 2010-era speech synthesiser,
5
+ so the artifact alone cannot be audited. The sidecar can.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import subprocess
13
+ import wave
14
+ from datetime import datetime, timezone
15
+ from functools import lru_cache
16
+ from pathlib import Path
17
+
18
+ from PIL import Image, ImageDraw, ImageFont
19
+
20
+ from .narrate import FALLBACK, PLANE, NarrationPath, have_ffmpeg, synthesize
21
+
22
+ W, H = 1920, 1080
23
+ BG = (13, 17, 23)
24
+ FG = (230, 237, 243)
25
+ DIM = (139, 148, 158)
26
+ ACCENT = (79, 142, 247)
27
+
28
+ # Fonts are resolved across platforms, not pinned to one. The first version
29
+ # hardcoded C:/Windows/Fonts and the frame tests skipped on non-win32, so a
30
+ # brick advertised as pip-installable would have raised OSError on the first
31
+ # slide for every Linux and macOS user, with CI structurally unable to see it.
32
+ _FONT_DIRS = (
33
+ (Path(os.environ["AWDECK_FONT_DIR"]),)
34
+ if os.environ.get("AWDECK_FONT_DIR")
35
+ else (
36
+ Path("C:/Windows/Fonts"),
37
+ Path("/usr/share/fonts"),
38
+ Path("/usr/local/share/fonts"),
39
+ Path.home() / ".fonts",
40
+ Path("/Library/Fonts"),
41
+ Path("/System/Library/Fonts"),
42
+ )
43
+ )
44
+ _FONT_CANDIDATES = {
45
+ "bold": ["segoeuib.ttf", "DejaVuSans-Bold.ttf", "LiberationSans-Bold.ttf", "Arial Bold.ttf"],
46
+ "body": ["segoeui.ttf", "DejaVuSans.ttf", "LiberationSans-Regular.ttf", "Arial.ttf"],
47
+ "italic": [
48
+ "segoeuii.ttf",
49
+ "DejaVuSans-Oblique.ttf",
50
+ "LiberationSans-Italic.ttf",
51
+ "Arial Italic.ttf",
52
+ ],
53
+ }
54
+
55
+
56
+ @lru_cache(maxsize=None)
57
+ def _font_path(kind: str) -> str:
58
+ for name in _FONT_CANDIDATES[kind]:
59
+ for d in _FONT_DIRS:
60
+ hit = d / name
61
+ if hit.exists():
62
+ return str(hit)
63
+ # Linux nests fonts (…/truetype/dejavu/DejaVuSans.ttf)
64
+ if d.is_dir():
65
+ found = next(iter(sorted(d.rglob(name))), None)
66
+ if found is not None:
67
+ return str(found)
68
+ raise RuntimeError(
69
+ f"awdeck: no {kind} font found. Tried {_FONT_CANDIDATES[kind]} under "
70
+ f"{[str(d) for d in _FONT_DIRS]}. Set AWDECK_FONT_DIR to a directory "
71
+ "containing a TrueType face."
72
+ )
73
+
74
+
75
+ def _font(kind: str, size: int) -> ImageFont.FreeTypeFont:
76
+ return ImageFont.truetype(_font_path(kind), size)
77
+
78
+
79
+ def _wrap(draw, text: str, fnt, max_w: int) -> list[str]:
80
+ lines: list[str] = []
81
+ cur = ""
82
+ for word in text.split():
83
+ trial = f"{cur} {word}".strip()
84
+ if draw.textlength(trial, font=fnt) <= max_w:
85
+ cur = trial
86
+ else:
87
+ if cur:
88
+ lines.append(cur)
89
+ cur = word
90
+ if cur:
91
+ lines.append(cur)
92
+ return lines
93
+
94
+
95
+ def _draw_title(d, slide) -> None:
96
+ fnt = _font("bold", 86)
97
+ lines = _wrap(d, slide["title"], fnt, W - 320)
98
+ y = H // 2 - (len(lines) * 104) // 2 - 40
99
+ for ln in lines:
100
+ d.text(((W - d.textlength(ln, font=fnt)) / 2, y), ln, font=fnt, fill=FG)
101
+ y += 104
102
+ d.rectangle([W // 2 - 90, y + 26, W // 2 + 90, y + 32], fill=ACCENT)
103
+ if slide.get("subtitle"):
104
+ sf = _font("body", 40)
105
+ for ln in _wrap(d, slide["subtitle"], sf, W - 480):
106
+ d.text(((W - d.textlength(ln, font=sf)) / 2, y + 78), ln, font=sf, fill=DIM)
107
+ y += 54
108
+
109
+
110
+ def _draw_bullets(d, slide) -> None:
111
+ tf = _font("bold", 64)
112
+ x0, y = 150, 150
113
+ for ln in _wrap(d, slide["title"], tf, W - 300):
114
+ d.text((x0, y), ln, font=tf, fill=FG)
115
+ y += 78
116
+ d.rectangle([x0, y + 16, x0 + 130, y + 23], fill=ACCENT)
117
+ y += 92
118
+
119
+ bullets = slide.get("bullets", [])
120
+ bf = _font("body", 44 if len(bullets) <= 5 else 40)
121
+ gap = 96 if len(bullets) <= 5 else 84
122
+ for b in bullets:
123
+ d.ellipse([x0 + 6, y + 20, x0 + 24, y + 38], fill=ACCENT)
124
+ for i, ln in enumerate(_wrap(d, b, bf, W - 420)):
125
+ d.text((x0 + 56, y), ln, font=bf, fill=FG if i == 0 else DIM)
126
+ y += 56
127
+ y += gap - 56
128
+
129
+
130
+ def _draw_quote(d, slide) -> None:
131
+ d.rectangle([150, 300, 162, H - 300], fill=ACCENT)
132
+ qf = _font("italic", 62)
133
+ lines = _wrap(d, slide["quote"], qf, W - 480)
134
+ y = H // 2 - (len(lines) * 84) // 2 - 30
135
+ for ln in lines:
136
+ d.text((220, y), ln, font=qf, fill=FG)
137
+ y += 84
138
+ d.text((220, y + 40), slide.get("title", ""), font=_font("body", 36), fill=DIM)
139
+
140
+
141
+ _LAYOUTS = {"title": _draw_title, "quote": _draw_quote, "bullets": _draw_bullets}
142
+
143
+
144
+ def render_frame(slide: dict, path: Path) -> None:
145
+ img = Image.new("RGB", (W, H), BG)
146
+ draw = ImageDraw.Draw(img)
147
+ _LAYOUTS.get(slide.get("layout", "bullets"), _draw_bullets)(draw, slide)
148
+ img.save(path)
149
+
150
+
151
+ def _audio_seconds(path: Path) -> float:
152
+ if path.suffix.lower() == ".wav":
153
+ with wave.open(str(path), "rb") as w:
154
+ return w.getnframes() / float(w.getframerate())
155
+ out = subprocess.run(
156
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",
157
+ "-of", "default=nw=1:nk=1", str(path)],
158
+ capture_output=True, text=True, encoding="utf-8", check=True,
159
+ )
160
+ return float(out.stdout.strip())
161
+
162
+
163
+ def _concat_line(p: Path) -> str:
164
+ """One ffmpeg concat-demuxer entry, with a literal quote escaped.
165
+
166
+ The demuxer ends a single-quoted token at the first `'`, so a path
167
+ containing one (`/out/dave's talk/`) silently truncates into a different
168
+ filename. The escape is: close, emit an escaped quote, reopen.
169
+ """
170
+ escaped = p.as_posix().replace("'", "'\\''")
171
+ return f"file '{escaped}'\n"
172
+
173
+
174
+ def aggregate(tracks: list[NarrationPath]) -> dict:
175
+ """Collapse per-slide narration into ONE honest verdict for the whole deck.
176
+
177
+ Worst-case wins. A deck is only `plane` if EVERY slide was narrated by the
178
+ plane: recording just the last slide's path would let slide 3 degrade while
179
+ slide 15 succeeded, and the manifest would say `plane` with the gate green —
180
+ a hole in the exact guarantee this file exists to provide.
181
+ """
182
+ if not tracks:
183
+ return {}
184
+ degraded = [t for t in tracks if t.path == FALLBACK]
185
+ worst = degraded[0] if degraded else tracks[0]
186
+ served = sorted({t.voice_served for t in tracks if t.voice_served})
187
+
188
+ out = worst.as_dict()
189
+ out["path"] = FALLBACK if degraded else PLANE
190
+ # reachable = was the plane up at ANY point? If it was, every fallback here
191
+ # is a silent downgrade and MNP003 must fire.
192
+ out["plane_reachable"] = any(t.plane_reachable for t in tracks)
193
+ out["voices_served"] = served
194
+ out["voice_served"] = served[0] if len(served) == 1 else ",".join(served)
195
+ out["slides_narrated"] = len(tracks)
196
+ out["slides_degraded"] = len(degraded)
197
+ return out
198
+
199
+
200
+ def render(
201
+ slides_path: Path,
202
+ out_path: Path,
203
+ *,
204
+ voice: str = "onyx",
205
+ allow_fallback: bool = False,
206
+ workdir: Path | None = None,
207
+ ) -> dict:
208
+ """Render the deck. Returns the manifest dict (also written beside the mp4)."""
209
+ if not have_ffmpeg():
210
+ raise RuntimeError("ffmpeg not found on PATH")
211
+
212
+ slides = json.loads(slides_path.read_text(encoding="utf-8"))
213
+ work = workdir or out_path.parent / f".{out_path.stem}-work"
214
+ work.mkdir(parents=True, exist_ok=True)
215
+
216
+ clips: list[Path] = []
217
+ tracks: list[NarrationPath] = []
218
+
219
+ for i, slide in enumerate(slides):
220
+ png = work / f"s{i:02d}.png"
221
+ audio = work / f"s{i:02d}.mp3"
222
+ clip = work / f"s{i:02d}.mp4"
223
+
224
+ render_frame(slide, png)
225
+ tracks.append(
226
+ synthesize(
227
+ slide.get("notes", slide.get("title", "")),
228
+ audio,
229
+ voice=voice,
230
+ allow_fallback=allow_fallback,
231
+ )
232
+ )
233
+ dur = _audio_seconds(audio) + 0.7
234
+
235
+ subprocess.run(
236
+ ["ffmpeg", "-y", "-loglevel", "error",
237
+ "-loop", "1", "-i", str(png), "-i", str(audio),
238
+ "-c:v", "libx264", "-tune", "stillimage", "-pix_fmt", "yuv420p",
239
+ "-r", "30", "-t", f"{dur:.2f}",
240
+ "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2",
241
+ str(clip)],
242
+ check=True,
243
+ )
244
+ clips.append(clip)
245
+
246
+ listing = work / "concat.txt"
247
+ listing.write_text("".join(f"file '{c.as_posix()}'\n" for c in clips), encoding="utf-8")
248
+ subprocess.run(
249
+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0",
250
+ "-i", str(listing), "-c", "copy", str(out_path)],
251
+ check=True,
252
+ )
253
+
254
+ manifest = {
255
+ "tool": "awdeck",
256
+ "deck": out_path.stem,
257
+ "rendered_at": datetime.now(timezone.utc).isoformat(),
258
+ "slides": len(slides),
259
+ "duration_s": round(_audio_seconds(out_path), 2),
260
+ "narration": aggregate(tracks),
261
+ }
262
+ out_path.with_suffix(".deck.json").write_text(
263
+ json.dumps(manifest, indent=2), encoding="utf-8"
264
+ )
265
+ return manifest
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: awdeck
3
+ Version: 0.1.1
4
+ Summary: Aither World Deck - turn a slides outline into a narrated video, and record which voice actually spoke it.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/Aitherium
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pillow>=10.0
11
+ Dynamic: license-file
12
+
13
+ # awdeck — Aither World Deck
14
+
15
+ Turn a JSON outline into a narrated MP4, and read back which voice actually spoke it.
16
+
17
+ ```bash
18
+ export AWVOICE_TTS_URL=http://127.0.0.1:8084/voice/synthesize
19
+ awdeck doctor # is the plane reachable?
20
+ awdeck render slides.json --out talk.mp4 --voice onyx
21
+ ```
22
+
23
+ ## Why the manifest exists
24
+
25
+ A rendered video looks identical whether a neural voice plane narrated it or a
26
+ 2010-era desktop speech synthesiser did. The artifact cannot be audited by looking
27
+ at it, so `awdeck` writes a sidecar that can be:
28
+
29
+ ```json
30
+ {
31
+ "deck": "talk",
32
+ "slides": 15,
33
+ "duration_s": 507.92,
34
+ "narration": {
35
+ "path": "plane",
36
+ "voice": "onyx",
37
+ "voice_served": "en-GB-SoniaNeural",
38
+ "voices_served": ["en-GB-SoniaNeural"],
39
+ "provider": "awvoice:http://127.0.0.1:8084/voice/synthesize",
40
+ "plane_reachable": true,
41
+ "slides_narrated": 15,
42
+ "slides_degraded": 0
43
+ }
44
+ }
45
+ ```
46
+
47
+ Three fields carry the weight:
48
+
49
+ - **`path`** — `plane` or `local-fallback`, and it is **worst-case across the whole
50
+ deck**, not the last slide. One degraded slide out of fifteen makes the deck
51
+ `local-fallback`. A fallback taken while `plane_reachable` is true is a silent
52
+ downgrade, and `check_media_narration_plane.py` (MNP003) fails the build on it.
53
+ - **`slides_degraded`** — how many slides took the degraded path. `0` is the only
54
+ number that means what you hope it means.
55
+ - **`voice_served`** / **`voices_served`** — what the service actually produced, read
56
+ back from its own response rather than assumed from the request.
57
+
58
+ ## Fail-closed by default
59
+
60
+ `awdeck` will **not** narrate off-plane unless you ask:
61
+
62
+ ```
63
+ $ awdeck render slides.json --out x.mp4
64
+ awdeck: voice plane unreachable (AWVOICE_TTS_URL=None) and fallback not allowed.
65
+ Fix the plane, or pass allow_fallback=True and accept a recorded downgrade.
66
+ ```
67
+
68
+ That default exists because of a measured incident (2026-09-19): one long-job
69
+ transport failure was read as "the fleet is down", a six-minute video was narrated
70
+ by Windows SAPI while the voice plane was healthy the whole time, and the only
71
+ thing that caught it was a human listening to it.
72
+
73
+ ## Known defect in the voice plane
74
+
75
+ `/voice/synthesize` accepts a `voice` parameter and, as measured on 2026-09-19,
76
+ serves `en-GB-SoniaNeural` regardless — all six advertised names and three real
77
+ edge voice names returned the same speaker. `awdeck` cannot fix that, so it
78
+ records it: `voice_served` will differ from `voice`, and the CLI prints a NOTE.
79
+
80
+ ## Slides format
81
+
82
+ A JSON array. Three layouts; `notes` is the narration script for that slide.
83
+
84
+ ```json
85
+ [
86
+ {"layout": "title", "title": "...", "subtitle": "...", "notes": "..."},
87
+ {"layout": "bullets", "title": "...", "bullets": ["..."], "notes": "..."},
88
+ {"layout": "quote", "title": "...", "quote": "...", "notes": "..."}
89
+ ]
90
+ ```
91
+
92
+ ## Requires
93
+
94
+ `ffmpeg` and `ffprobe` on PATH, Pillow, and a voice-shaped HTTP service at
95
+ `AWVOICE_TTS_URL` accepting `{text, voice, format, return_base64}`.
96
+
97
+ Pairs with [`awvoice`](../awvoice) (the speech brick this speaks through), `awsh`,
98
+ `awdk`, `mediaforge` and `awrtifact`.
@@ -0,0 +1,11 @@
1
+ awdeck/__init__.py,sha256=r4mtQPO1bb0sZXFhksn0atFRIr6xLiOhp9j8zB0SpN8,355
2
+ awdeck/_doctor.py,sha256=iMKW8oEMQ9n-VHj0PK78BeFIvXYU6Lvmvha9LLDQVMU,8332
3
+ awdeck/cli.py,sha256=9xmOhOK2vmbBZ1VLBmCzxYSxfMBU15EmAPKylxGwB0Y,5353
4
+ awdeck/narrate.py,sha256=Pw_zUX2zTsWOnsevE5MrK7vIqnX86XWtPQ2mE6hhTp0,6688
5
+ awdeck/render.py,sha256=EMQfd9EczKrQ672XAkyfSjXDJoHtpvJ2jtG5PDRQTkg,9024
6
+ awdeck-0.1.1.dist-info/licenses/LICENSE,sha256=ldw_nqPlJKJOi8Gy4T9kCAVjZCbs1dbal6DtX3mIVgc,1066
7
+ awdeck-0.1.1.dist-info/METADATA,sha256=mqzSdK-wg46ARdPt2L-EVnD1YIuIgBUSWT7Up_Gri2k,3501
8
+ awdeck-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ awdeck-0.1.1.dist-info/entry_points.txt,sha256=uwp0AqNVkbbrpLpgyLphc4b5L0ddsAT8gBVnVA4y4FU,43
10
+ awdeck-0.1.1.dist-info/top_level.txt,sha256=hyO9PGlTik6RAD0J4su-8aNa28rFTwKPc_XdlyrlxXY,7
11
+ awdeck-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ awdeck = awdeck.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aitherium
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ awdeck