narra 0.0.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.
- narra/__init__.py +3 -0
- narra/__main__.py +8 -0
- narra/cli.py +189 -0
- narra/config.py +231 -0
- narra/core.py +162 -0
- narra/formats.py +99 -0
- narra/script.py +100 -0
- narra/serve.py +50 -0
- narra/serve_page.html +46 -0
- narra/speakers.py +82 -0
- narra/tts/__init__.py +49 -0
- narra/tts/base.py +61 -0
- narra/tts/edge.py +22 -0
- narra/tts/gemini.py +25 -0
- narra/tts/kokoro.py +22 -0
- narra/tts/openai_compat.py +24 -0
- narra/tts/piper.py +23 -0
- narra/writers/__init__.py +43 -0
- narra/writers/base.py +63 -0
- narra/writers/gemini.py +25 -0
- narra/writers/ollama.py +22 -0
- narra/writers/openai_compatible.py +24 -0
- narra-0.0.1.dist-info/METADATA +113 -0
- narra-0.0.1.dist-info/RECORD +27 -0
- narra-0.0.1.dist-info/WHEEL +4 -0
- narra-0.0.1.dist-info/entry_points.txt +2 -0
- narra-0.0.1.dist-info/licenses/LICENSE +21 -0
narra/__init__.py
ADDED
narra/__main__.py
ADDED
narra/cli.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Narra CLI: ``narra "source.pdf" --out episode.mp3``, plus ``narra serve``.
|
|
2
|
+
|
|
3
|
+
The default command routes a bare invocation to ``generate`` so
|
|
4
|
+
``narra "paper.pdf"`` just works, the same shape as limn.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
from typer.core import TyperGroup
|
|
14
|
+
|
|
15
|
+
from narra import __version__
|
|
16
|
+
from narra.config import ConfigurationError, load_config
|
|
17
|
+
from narra.config import save_example_config as _save_example_config
|
|
18
|
+
from narra.core import GenerationError
|
|
19
|
+
from narra.core import generate as _generate
|
|
20
|
+
from narra.formats import format_options
|
|
21
|
+
|
|
22
|
+
console = Console()
|
|
23
|
+
err_console = Console(stderr=True, style="bold red")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DefaultCommandGroup(TyperGroup):
|
|
27
|
+
"""Route bare invocations to ``generate`` so ``narra "a source"`` just works.
|
|
28
|
+
|
|
29
|
+
``narra serve ...`` and ``narra generate ...`` hit their commands normally;
|
|
30
|
+
anything else (a path, or generate's options) is prefixed with ``generate``.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
default_command = "generate"
|
|
34
|
+
_root_tokens = {"-h", "--help", "-V", "--version"}
|
|
35
|
+
|
|
36
|
+
def parse_args(self, ctx: Any, args: list[str]) -> list[str]:
|
|
37
|
+
if args and args[0] not in self.commands and args[0] not in self._root_tokens:
|
|
38
|
+
args = [self.default_command, *args]
|
|
39
|
+
return super().parse_args(ctx, args)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
app = typer.Typer(
|
|
43
|
+
cls=DefaultCommandGroup,
|
|
44
|
+
add_completion=False,
|
|
45
|
+
no_args_is_help=True,
|
|
46
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _version_callback(value: bool) -> None:
|
|
51
|
+
if value:
|
|
52
|
+
console.print(f"narra {__version__}")
|
|
53
|
+
raise typer.Exit()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@app.callback()
|
|
57
|
+
def root(
|
|
58
|
+
version: bool = typer.Option(
|
|
59
|
+
False, "-V", "--version", callback=_version_callback, is_eager=True
|
|
60
|
+
),
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Narra — tell a source document into a multi-speaker podcast episode."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _load(config: str | None) -> dict[str, Any]:
|
|
66
|
+
try:
|
|
67
|
+
return load_config(config)
|
|
68
|
+
except ConfigurationError as e:
|
|
69
|
+
err_console.print(str(e))
|
|
70
|
+
raise typer.Exit(code=1) from e
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _apply_overrides(
|
|
74
|
+
settings: dict[str, Any],
|
|
75
|
+
writer: str | None,
|
|
76
|
+
voice: str | None,
|
|
77
|
+
format: str | None,
|
|
78
|
+
model: str | None,
|
|
79
|
+
base_url: str | None,
|
|
80
|
+
api_key: str | None,
|
|
81
|
+
) -> dict[str, Any]:
|
|
82
|
+
"""Overlay CLI flags on top of the loaded config (flags win)."""
|
|
83
|
+
if writer:
|
|
84
|
+
settings["writer"] = writer
|
|
85
|
+
if voice:
|
|
86
|
+
settings["voice"] = voice
|
|
87
|
+
if format:
|
|
88
|
+
settings["format"] = format
|
|
89
|
+
if model:
|
|
90
|
+
settings["model"] = model
|
|
91
|
+
if base_url or api_key:
|
|
92
|
+
active = str(settings.get("writer") or "gemini")
|
|
93
|
+
block = settings.setdefault("writers", {}).setdefault(active, {})
|
|
94
|
+
if base_url:
|
|
95
|
+
block["base_url"] = base_url
|
|
96
|
+
if api_key:
|
|
97
|
+
block["api_key"] = api_key
|
|
98
|
+
return settings
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@app.command()
|
|
102
|
+
def init_config(
|
|
103
|
+
path: str = typer.Argument("narra.yaml", help="Where to write the example config."),
|
|
104
|
+
force: bool = typer.Option(False, "--force", "-f", help="Overwrite if it exists."),
|
|
105
|
+
) -> None:
|
|
106
|
+
"""Write an example ``narra.yaml`` you can edit."""
|
|
107
|
+
from pathlib import Path
|
|
108
|
+
|
|
109
|
+
target = Path(path)
|
|
110
|
+
if force and target.exists():
|
|
111
|
+
target.unlink()
|
|
112
|
+
try:
|
|
113
|
+
written = _save_example_config(str(target))
|
|
114
|
+
except ConfigurationError as e:
|
|
115
|
+
err_console.print(str(e))
|
|
116
|
+
raise typer.Exit(code=1) from e
|
|
117
|
+
console.print(f"Wrote example config to {written}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@app.command()
|
|
121
|
+
def formats() -> None:
|
|
122
|
+
"""List the built-in script formats."""
|
|
123
|
+
for option in format_options():
|
|
124
|
+
console.print(f"{option['key']:<12} {option['label']}")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@app.command()
|
|
128
|
+
def generate(
|
|
129
|
+
source: str = typer.Argument(..., help="Path to a .pdf or .txt source file."),
|
|
130
|
+
out: str | None = typer.Option(None, "--out", "-o", help="Output audio file."),
|
|
131
|
+
out_dir: str | None = typer.Option(
|
|
132
|
+
None, "--out-dir", help="Directory for auto-named output."
|
|
133
|
+
),
|
|
134
|
+
format: str | None = typer.Option(None, "--format", "-f", help="Script format."),
|
|
135
|
+
writer: str | None = typer.Option(None, "--writer", "-w", help="Script writer."),
|
|
136
|
+
voice: str | None = typer.Option(None, "--voice", help="Voice provider."),
|
|
137
|
+
model: str | None = typer.Option(None, "--model", "-m", help="Writer model."),
|
|
138
|
+
base_url: str | None = typer.Option(None, "--base-url", help="Writer base URL."),
|
|
139
|
+
api_key: str | None = typer.Option(None, "--api-key", help="Writer API key."),
|
|
140
|
+
config: str | None = typer.Option(None, "--config", "-c", help="Config file."),
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Generate a podcast episode from a source file."""
|
|
143
|
+
settings = _apply_overrides(
|
|
144
|
+
_load(config), writer, voice, format, model, base_url, api_key
|
|
145
|
+
)
|
|
146
|
+
try:
|
|
147
|
+
episode = _generate(source, settings, format=format, writer=writer)
|
|
148
|
+
except GenerationError as e:
|
|
149
|
+
err_console.print(str(e))
|
|
150
|
+
raise typer.Exit(code=1) from e
|
|
151
|
+
|
|
152
|
+
from narra.core import save_episode
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
audio, sidecar = save_episode(episode, out=out, out_dir=out_dir)
|
|
156
|
+
except GenerationError as e:
|
|
157
|
+
err_console.print(str(e))
|
|
158
|
+
raise typer.Exit(code=1) from e
|
|
159
|
+
console.print(f"Saved {audio}")
|
|
160
|
+
console.print(f"Wrote {sidecar}")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@app.command()
|
|
164
|
+
def serve(
|
|
165
|
+
host: str | None = typer.Option(None, "--host", help="Bind host."),
|
|
166
|
+
port: int | None = typer.Option(None, "--port", "-p", help="Bind port."),
|
|
167
|
+
config: str | None = typer.Option(None, "--config", "-c", help="Config file."),
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Run the local web UI (needs the [serve] extra)."""
|
|
170
|
+
settings = _load(config)
|
|
171
|
+
serve_cfg = settings.get("serve") or {}
|
|
172
|
+
bind_host = host or str(serve_cfg.get("host") or "127.0.0.1")
|
|
173
|
+
bind_port = int(port or serve_cfg.get("port") or 5372)
|
|
174
|
+
try:
|
|
175
|
+
from narra.serve import create_app
|
|
176
|
+
except ImportError as e:
|
|
177
|
+
err_console.print(
|
|
178
|
+
"The web UI needs the [serve] extra. Install with:\n"
|
|
179
|
+
' pip install "narra[serve]"'
|
|
180
|
+
)
|
|
181
|
+
raise typer.Exit(code=1) from e
|
|
182
|
+
|
|
183
|
+
import uvicorn
|
|
184
|
+
|
|
185
|
+
uvicorn.run(create_app(settings), host=bind_host, port=bind_port)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
if __name__ == "__main__":
|
|
189
|
+
app()
|
narra/config.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Layered configuration for Narra.
|
|
2
|
+
|
|
3
|
+
Layers, later wins:
|
|
4
|
+
|
|
5
|
+
1. Built-in defaults
|
|
6
|
+
2. ``~/.narra.yaml`` — your providers + keys, set once
|
|
7
|
+
3. ``./narra.yaml`` — per-directory overrides (or an explicit ``--config`` path)
|
|
8
|
+
4. CLI flags — applied by the CLI on top of the loaded config
|
|
9
|
+
|
|
10
|
+
Secrets are referenced as ``${VAR}`` and expanded from the environment, so no
|
|
11
|
+
plaintext keys need to live in config files.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import yaml
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConfigurationError(Exception):
|
|
26
|
+
"""Raised when configuration is invalid or missing."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
DEFAULT_CONFIG: dict[str, Any] = {
|
|
30
|
+
"writer": "gemini",
|
|
31
|
+
"voice": "edge",
|
|
32
|
+
"format": "deep-dive",
|
|
33
|
+
"model": None,
|
|
34
|
+
"voice_model": None,
|
|
35
|
+
"timeout": 300,
|
|
36
|
+
"writers": {},
|
|
37
|
+
"voices": {},
|
|
38
|
+
"speakers": [],
|
|
39
|
+
"serve": {
|
|
40
|
+
"host": "127.0.0.1",
|
|
41
|
+
"port": 5372,
|
|
42
|
+
"password": None,
|
|
43
|
+
"out_dir": "~/Podcasts/Narra",
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_ENV_VAR_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def expand_env_vars(value: Any) -> Any:
|
|
51
|
+
"""Recursively expand ``${VAR}`` references in configuration values."""
|
|
52
|
+
if isinstance(value, str):
|
|
53
|
+
return _ENV_VAR_RE.sub(lambda m: os.getenv(m.group(1), ""), value)
|
|
54
|
+
if isinstance(value, dict):
|
|
55
|
+
return {k: expand_env_vars(v) for k, v in value.items()}
|
|
56
|
+
if isinstance(value, list):
|
|
57
|
+
return [expand_env_vars(item) for item in value]
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _first_existing(*candidates: Path) -> Path | None:
|
|
62
|
+
for path in candidates:
|
|
63
|
+
if path.exists():
|
|
64
|
+
return path
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_home_config() -> Path | None:
|
|
69
|
+
"""The user-level config (~/.narra.yaml) — providers + keys, set once."""
|
|
70
|
+
return _first_existing(
|
|
71
|
+
Path.home() / ".narra.yaml",
|
|
72
|
+
Path.home() / ".narra.yml",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_project_config() -> Path | None:
|
|
77
|
+
"""The directory-level config (./narra.yaml)."""
|
|
78
|
+
return _first_existing(
|
|
79
|
+
Path("./narra.yaml"),
|
|
80
|
+
Path("./narra.yml"),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _read_config_file(config_file: Path) -> dict[str, Any] | None:
|
|
85
|
+
try:
|
|
86
|
+
with open(config_file, encoding="utf-8") as f:
|
|
87
|
+
data = yaml.safe_load(f)
|
|
88
|
+
except yaml.YAMLError as e:
|
|
89
|
+
raise ConfigurationError(f"Invalid YAML in {config_file}: {e}") from e
|
|
90
|
+
except OSError as e:
|
|
91
|
+
raise ConfigurationError(f"Error reading {config_file}: {e}") from e
|
|
92
|
+
if data is None:
|
|
93
|
+
return None
|
|
94
|
+
if not isinstance(data, dict):
|
|
95
|
+
raise ConfigurationError(
|
|
96
|
+
f"Config file {config_file} must contain a YAML mapping"
|
|
97
|
+
)
|
|
98
|
+
return data
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def merge_configs(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
102
|
+
"""Deep-merge two config dicts (override wins)."""
|
|
103
|
+
result = base.copy()
|
|
104
|
+
for key, value in override.items():
|
|
105
|
+
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
106
|
+
result[key] = merge_configs(result[key], value)
|
|
107
|
+
else:
|
|
108
|
+
result[key] = value
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def load_config(config_path: str | None = None) -> dict[str, Any]:
|
|
113
|
+
"""Load configuration by layering defaults, home, and project files.
|
|
114
|
+
|
|
115
|
+
An explicit ``config_path`` replaces the auto-discovered ./narra.yaml but
|
|
116
|
+
still sits on top of ~/.narra.yaml.
|
|
117
|
+
"""
|
|
118
|
+
config = copy.deepcopy(DEFAULT_CONFIG)
|
|
119
|
+
|
|
120
|
+
sources: list[Path] = []
|
|
121
|
+
if home_config := find_home_config():
|
|
122
|
+
sources.append(home_config)
|
|
123
|
+
if config_path:
|
|
124
|
+
explicit = Path(config_path)
|
|
125
|
+
if not explicit.exists():
|
|
126
|
+
raise ConfigurationError(f"Configuration file not found: {config_path}")
|
|
127
|
+
sources.append(explicit)
|
|
128
|
+
elif project_config := find_project_config():
|
|
129
|
+
sources.append(project_config)
|
|
130
|
+
|
|
131
|
+
for source in sources:
|
|
132
|
+
file_config = _read_config_file(source)
|
|
133
|
+
if file_config:
|
|
134
|
+
config = merge_configs(config, file_config)
|
|
135
|
+
|
|
136
|
+
return expand_env_vars(config)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def writer_settings(config: dict[str, Any], writer: str | None = None) -> dict[str, Any]:
|
|
140
|
+
"""Effective settings for one writer, merged from the top level and its block."""
|
|
141
|
+
name = writer or str(config.get("writer") or "gemini")
|
|
142
|
+
settings = {k: v for k, v in config.items() if k not in ("writers", "voices", "speakers")}
|
|
143
|
+
override = (config.get("writers") or {}).get(name)
|
|
144
|
+
if isinstance(override, dict):
|
|
145
|
+
settings = merge_configs(settings, override)
|
|
146
|
+
settings["writer"] = name
|
|
147
|
+
return settings
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def voice_settings(config: dict[str, Any], voice: str | None = None) -> dict[str, Any]:
|
|
151
|
+
"""Effective settings for one voice provider, merged from its block."""
|
|
152
|
+
name = voice or str(config.get("voice") or "edge")
|
|
153
|
+
settings: dict[str, Any] = {}
|
|
154
|
+
override = (config.get("voices") or {}).get(name)
|
|
155
|
+
if isinstance(override, dict):
|
|
156
|
+
settings = merge_configs(settings, override)
|
|
157
|
+
settings["voice"] = name
|
|
158
|
+
return settings
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
EXAMPLE_CONFIG = """\
|
|
162
|
+
# Narra configuration
|
|
163
|
+
#
|
|
164
|
+
# Layered, later wins:
|
|
165
|
+
# 1. built-in defaults
|
|
166
|
+
# 2. ~/.narra.yaml (personal: providers, API keys — set once)
|
|
167
|
+
# 3. ./narra.yaml (per-directory overrides; or pass --config FILE)
|
|
168
|
+
# 4. CLI flags (e.g. --writer, --voice, --format)
|
|
169
|
+
#
|
|
170
|
+
# Secrets: reference environment variables as ${VAR} — no plaintext keys.
|
|
171
|
+
|
|
172
|
+
writer: gemini # gemini | openai-compatible | ollama
|
|
173
|
+
voice: edge # edge | openai-compatible | gemini | piper | kokoro
|
|
174
|
+
format: deep-dive # deep-dive | brief | critique | debate | <custom>
|
|
175
|
+
|
|
176
|
+
writers:
|
|
177
|
+
gemini:
|
|
178
|
+
model: gemini-3.5-flash
|
|
179
|
+
# api_key: "${GEMINI_API_KEY}" # defaults to the env var anyway
|
|
180
|
+
|
|
181
|
+
openai-compatible: # LocalAI, LM Studio, llama.cpp, OpenRouter, OpenAI
|
|
182
|
+
base_url: https://api.openai.com/v1
|
|
183
|
+
model: gpt-4o-mini
|
|
184
|
+
# api_key: "${OPENAI_API_KEY}" # optional for local servers
|
|
185
|
+
|
|
186
|
+
ollama: # local, no key
|
|
187
|
+
base_url: http://127.0.0.1:11434
|
|
188
|
+
model: qwen3.5:4b
|
|
189
|
+
|
|
190
|
+
voices:
|
|
191
|
+
edge: {} # free, no key; default
|
|
192
|
+
|
|
193
|
+
openai-compatible: # OpenAI standard /v1/audio/speech
|
|
194
|
+
base_url: https://api.openai.com/v1
|
|
195
|
+
model: gpt-4o-mini-tts
|
|
196
|
+
# api_key: "${OPENAI_API_KEY}"
|
|
197
|
+
|
|
198
|
+
gemini: # native TTS
|
|
199
|
+
model: gemini-3.8-flash-tts
|
|
200
|
+
# api_key: "${GEMINI_API_KEY}"
|
|
201
|
+
|
|
202
|
+
piper: # local CPU
|
|
203
|
+
voice: en_GB-alan-low
|
|
204
|
+
|
|
205
|
+
kokoro: # local CPU
|
|
206
|
+
voice: bm_george
|
|
207
|
+
|
|
208
|
+
# 1–N speakers. Each may point at a different voice provider.
|
|
209
|
+
speakers:
|
|
210
|
+
- name: Alex
|
|
211
|
+
persona: Storyteller who sees the big picture.
|
|
212
|
+
voice: { provider: edge, voice_id: en-US-AndrewNeural }
|
|
213
|
+
- name: Sam
|
|
214
|
+
persona: Curious skeptic who asks sharp follow-ups.
|
|
215
|
+
voice: { provider: edge, voice_id: en-US-AvaNeural }
|
|
216
|
+
|
|
217
|
+
serve:
|
|
218
|
+
host: 127.0.0.1
|
|
219
|
+
port: 5372 # "NARR" on a phone keypad
|
|
220
|
+
# password: "${NARRA_SERVE_PASSWORD}"
|
|
221
|
+
out_dir: ~/Podcasts/Narra
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def save_example_config(path: str = "narra.yaml") -> Path:
|
|
226
|
+
"""Write an example configuration file and return its path."""
|
|
227
|
+
target = Path(path)
|
|
228
|
+
if target.exists():
|
|
229
|
+
raise ConfigurationError(f"Refusing to overwrite existing {target}")
|
|
230
|
+
target.write_text(EXAMPLE_CONFIG, encoding="utf-8")
|
|
231
|
+
return target
|
narra/core.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Core: turn a source document into a podcast episode on disk.
|
|
2
|
+
|
|
3
|
+
``generate`` is a skeleton in 0.0.1: it reads the source, resolves the format
|
|
4
|
+
and speakers, and then hands off to a writer + voice, which raise "not
|
|
5
|
+
implemented yet" until M1/M3. The save + JSON sidecar helpers are real.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from narra.formats import format_prompt, get_format
|
|
19
|
+
from narra.script import clean_lines, read_source, script_text
|
|
20
|
+
from narra.speakers import resolve_speakers
|
|
21
|
+
from narra.writers.base import DialogueLine, WriterError
|
|
22
|
+
|
|
23
|
+
_AUDIO_SUFFIXES = {".mp3", ".wav", ".flac", ".ogg", ".m4a"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Episode:
|
|
28
|
+
"""One finished episode: audio plus the inputs that produced it."""
|
|
29
|
+
|
|
30
|
+
lines: list[DialogueLine]
|
|
31
|
+
audio: bytes
|
|
32
|
+
source: str
|
|
33
|
+
source_path: str
|
|
34
|
+
format: str
|
|
35
|
+
writer: str
|
|
36
|
+
voices: list[dict[str, Any]] = field(default_factory=list)
|
|
37
|
+
created: str = ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class GenerationError(Exception):
|
|
41
|
+
"""Raised when an episode cannot be generated."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def generate(
|
|
45
|
+
source_path: str,
|
|
46
|
+
settings: dict[str, Any],
|
|
47
|
+
*,
|
|
48
|
+
format: str | None = None,
|
|
49
|
+
writer: str | None = None,
|
|
50
|
+
) -> Episode:
|
|
51
|
+
"""Generate one episode from a source file.
|
|
52
|
+
|
|
53
|
+
Skeleton: reads the source and resolves everything, then calls the writer
|
|
54
|
+
(which raises a clear "not implemented yet" error until M1). Voicing and
|
|
55
|
+
stitching land in M1/M3.
|
|
56
|
+
"""
|
|
57
|
+
chosen_format = format or str(settings.get("format") or "deep-dive")
|
|
58
|
+
fmt = get_format(chosen_format)
|
|
59
|
+
chosen_writer = writer or str(settings.get("writer") or "gemini")
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
text = read_source(source_path)
|
|
63
|
+
except Exception as e:
|
|
64
|
+
raise GenerationError(str(e)) from e
|
|
65
|
+
|
|
66
|
+
from narra.script import outline_to_dialogue
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
lines = outline_to_dialogue(text, format_prompt(fmt.key), chosen_writer, settings)
|
|
70
|
+
except WriterError as e:
|
|
71
|
+
raise GenerationError(str(e)) from e
|
|
72
|
+
|
|
73
|
+
return Episode(
|
|
74
|
+
lines=clean_lines(lines),
|
|
75
|
+
audio=b"",
|
|
76
|
+
source=text,
|
|
77
|
+
source_path=source_path,
|
|
78
|
+
format=fmt.key,
|
|
79
|
+
writer=chosen_writer,
|
|
80
|
+
voices=[s.voice_ref() for s in resolve_speakers(settings.get("speakers"))],
|
|
81
|
+
created=datetime.now(timezone.utc).isoformat(),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def slugify(text: str, max_length: int = 48) -> str:
|
|
86
|
+
"""Filesystem-safe slug for a default output name."""
|
|
87
|
+
slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
|
88
|
+
slug = slug[:max_length].rstrip("-")
|
|
89
|
+
return slug or "episode"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def unique_path(path: Path) -> Path:
|
|
93
|
+
"""Avoid clobbering existing files by appending -2, -3, ..."""
|
|
94
|
+
if not path.exists():
|
|
95
|
+
return path
|
|
96
|
+
for i in range(2, 1000):
|
|
97
|
+
candidate = path.with_name(f"{path.stem}-{i}{path.suffix}")
|
|
98
|
+
if not candidate.exists():
|
|
99
|
+
return candidate
|
|
100
|
+
raise FileExistsError(f"Could not find a free filename near {path}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def source_hash(text: str) -> str:
|
|
104
|
+
"""Short content hash for reproducibility sidecars."""
|
|
105
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def metadata_for(episode: Episode) -> dict[str, Any]:
|
|
109
|
+
"""Reproducibility sidecar for one saved episode."""
|
|
110
|
+
return {
|
|
111
|
+
"format": episode.format,
|
|
112
|
+
"writer": episode.writer,
|
|
113
|
+
"voices": episode.voices,
|
|
114
|
+
"source_path": episode.source_path,
|
|
115
|
+
"source_hash": source_hash(episode.source),
|
|
116
|
+
"source_chars": len(episode.source),
|
|
117
|
+
"lines": len(episode.lines),
|
|
118
|
+
"transcript": script_text(episode.lines),
|
|
119
|
+
"created": episode.created or datetime.now(timezone.utc).isoformat(),
|
|
120
|
+
"app": "narra",
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def write_metadata(audio_path: Path, metadata: dict[str, Any]) -> Path:
|
|
125
|
+
"""Write a ``<episode>.json`` sidecar next to the audio; return its path."""
|
|
126
|
+
sidecar = audio_path.with_suffix(audio_path.suffix + ".json")
|
|
127
|
+
sidecar.write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
|
|
128
|
+
return sidecar
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def save_episode(
|
|
132
|
+
episode: Episode,
|
|
133
|
+
out: str | None = None,
|
|
134
|
+
out_dir: str | Path | None = None,
|
|
135
|
+
) -> tuple[Path, Path]:
|
|
136
|
+
"""Write one episode and its sidecar; return ``(audio, metadata)``.
|
|
137
|
+
|
|
138
|
+
``out`` is an exact file. Without it, the episode is named from the source
|
|
139
|
+
stem and format and written into ``out_dir`` (the current directory by
|
|
140
|
+
default). Existing files are never overwritten.
|
|
141
|
+
"""
|
|
142
|
+
if not episode.audio:
|
|
143
|
+
raise GenerationError(
|
|
144
|
+
"Episode has no audio yet — voicing is not implemented in the "
|
|
145
|
+
"0.0.1 skeleton. See SPEC.md §10 M1."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if out:
|
|
149
|
+
target = Path(out).expanduser()
|
|
150
|
+
if target.parent != Path("."):
|
|
151
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
152
|
+
if not target.suffix:
|
|
153
|
+
target = target.with_suffix(".mp3")
|
|
154
|
+
else:
|
|
155
|
+
base_dir = Path(out_dir).expanduser() if out_dir else Path(".")
|
|
156
|
+
base_dir.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
stem = slugify(f"{Path(episode.source_path).stem} {episode.format}")
|
|
158
|
+
target = unique_path(base_dir / f"{stem}.mp3")
|
|
159
|
+
|
|
160
|
+
target.write_bytes(episode.audio)
|
|
161
|
+
sidecar = write_metadata(target, metadata_for(episode))
|
|
162
|
+
return target, sidecar
|
narra/formats.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Format registry: a name -> the prompt fragment that shapes a script.
|
|
2
|
+
|
|
3
|
+
A format is either a shipped preset or a custom briefing (free text). The
|
|
4
|
+
writer rules are appended to every format so a cold open, concrete facts, and
|
|
5
|
+
no stage directions are enforced consistently.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Format:
|
|
15
|
+
"""One script format: a key, a label, and the prompt fragment."""
|
|
16
|
+
|
|
17
|
+
key: str
|
|
18
|
+
label: str
|
|
19
|
+
instruction: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
FORMATS: dict[str, Format] = {
|
|
23
|
+
"deep-dive": Format(
|
|
24
|
+
key="deep-dive",
|
|
25
|
+
label="Deep dive",
|
|
26
|
+
instruction=(
|
|
27
|
+
"Write an 18-24 line lively two-host Deep Dive between Alex (storyteller "
|
|
28
|
+
"who sees the big picture) and Sam (curious skeptic who asks sharp "
|
|
29
|
+
"follow-ups and translates jargon). Mix longer explanations with short "
|
|
30
|
+
"3-6 word reactions. Connect non-obvious dots in the source."
|
|
31
|
+
),
|
|
32
|
+
),
|
|
33
|
+
"brief": Format(
|
|
34
|
+
key="brief",
|
|
35
|
+
label="Brief",
|
|
36
|
+
instruction=(
|
|
37
|
+
"Write a tight, single-host Brief delivered ONLY by Alex (6-8 short "
|
|
38
|
+
"lines, under 90 seconds spoken). Every single line MUST have speaker "
|
|
39
|
+
"set to 'Alex'. Lead with the core headline, hit the 3 sharpest facts, "
|
|
40
|
+
"and close with one clear takeaway."
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
"critique": Format(
|
|
44
|
+
key="critique",
|
|
45
|
+
label="Critique",
|
|
46
|
+
instruction=(
|
|
47
|
+
"Write a 16-20 line constructive Critique between Alex and Sam acting as "
|
|
48
|
+
"candid domain reviewers. Highlight what is genuinely strong, then "
|
|
49
|
+
"directly dissect gaps, risks, missing evidence, or areas that could be "
|
|
50
|
+
"tightened."
|
|
51
|
+
),
|
|
52
|
+
),
|
|
53
|
+
"debate": Format(
|
|
54
|
+
key="debate",
|
|
55
|
+
label="Debate",
|
|
56
|
+
instruction=(
|
|
57
|
+
"Write an 18-22 line structured Debate. Alex argues the optimistic/pro "
|
|
58
|
+
"case from the source; Sam plays the tough skeptic highlighting "
|
|
59
|
+
"trade-offs, blind spots, and counterarguments. Do not let them agree "
|
|
60
|
+
"prematurely."
|
|
61
|
+
),
|
|
62
|
+
),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
#: Appended to every format so the writer follows the same rules.
|
|
66
|
+
WRITER_RULES = (
|
|
67
|
+
"Rules:\n"
|
|
68
|
+
"- Start with a cold open (NO \"Welcome back to the show\" or generic greetings).\n"
|
|
69
|
+
"- Cite concrete facts, numbers, or names from the source text.\n"
|
|
70
|
+
"- Avoid AI clichés (\"delve into\", \"game-changer\", \"tapestry\", "
|
|
71
|
+
"\"at the end of the day\").\n"
|
|
72
|
+
"- Keep lines conversational with no stage directions or sound effects."
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_format(name: str | None) -> Format:
|
|
77
|
+
"""Resolve a format by key, or treat the text itself as a custom briefing.
|
|
78
|
+
|
|
79
|
+
An unknown key is not an error: it is used verbatim as a custom briefing so
|
|
80
|
+
users can pass their own episode profile without editing config.
|
|
81
|
+
"""
|
|
82
|
+
key = (name or "deep-dive").strip()
|
|
83
|
+
if key in FORMATS:
|
|
84
|
+
return FORMATS[key]
|
|
85
|
+
lowered = key.lower()
|
|
86
|
+
if lowered in FORMATS:
|
|
87
|
+
return FORMATS[lowered]
|
|
88
|
+
return Format(key=key, label=key[:32], instruction=key)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def format_options() -> list[dict[str, str]]:
|
|
92
|
+
"""Format choices for the CLI help and web UI."""
|
|
93
|
+
return [{"key": f.key, "label": f.label} for f in FORMATS.values()]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def format_prompt(name: str | None) -> str:
|
|
97
|
+
"""The full prompt fragment for a format: instruction plus shared rules."""
|
|
98
|
+
fmt = get_format(name)
|
|
99
|
+
return f"{fmt.instruction}\n\n{WRITER_RULES}"
|