talkaty 1.2.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.
talkaty/__about__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
talkaty/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """talkaty — terminal-native TTS voiceover tool."""
2
+
3
+ from .__about__ import __version__
4
+
5
+ __all__ = ["__version__"]
talkaty/audio.py ADDED
@@ -0,0 +1,70 @@
1
+ """Audio output: write MP3/WAV, compute duration, write SRT/VTT subtitles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class AudioResult:
10
+ path: str
11
+ duration_seconds: float
12
+ voice_used: str
13
+ backend_used: str
14
+
15
+
16
+ def write_audio(path: str, data: bytes, fmt: str = "mp3") -> str:
17
+ """Write raw audio bytes to `path`. Returns the path written."""
18
+ with open(path, "wb") as fh:
19
+ fh.write(data)
20
+ return path
21
+
22
+
23
+ def estimate_duration_ms(segments: list, words_per_minute: int = 150) -> int:
24
+ """Rough duration estimate from segment text (fallback when backend doesn't report)."""
25
+ total_chars = sum(len(seg.text) for seg in segments)
26
+ # ~5 chars per word average
27
+ words = total_chars / 5.0
28
+ minutes = words / words_per_minute
29
+ return int(minutes * 60 * 1000)
30
+
31
+
32
+ def write_srt(path: str, segments: list, start_ms: int = 0) -> str:
33
+ """Write an SRT subtitle file from segments with start/end ms."""
34
+ offset = start_ms
35
+ with open(path, "w", encoding="utf-8") as fh:
36
+ for i, seg in enumerate(segments, 1):
37
+ start = offset + (seg.start_ms or 0)
38
+ end = offset + (seg.end_ms or start + 2000)
39
+ fh.write(f"{i}\n")
40
+ fh.write(f"{_fmt_ts(start)} --> {_fmt_ts(end)}\n")
41
+ fh.write(f"{seg.text}\n\n")
42
+ return path
43
+
44
+
45
+ def write_vtt(path: str, segments: list, start_ms: int = 0) -> str:
46
+ """Write a VTT subtitle file."""
47
+ offset = start_ms
48
+ with open(path, "w", encoding="utf-8") as fh:
49
+ fh.write("WEBVTT\n\n")
50
+ for i, seg in enumerate(segments, 1):
51
+ start = offset + (seg.start_ms or 0)
52
+ end = offset + (seg.end_ms or start + 2000)
53
+ fh.write(f"{i}\n")
54
+ fh.write(f"{_fmt_vtt_ts(start)} --> {_fmt_vtt_ts(end)}\n")
55
+ fh.write(f"{seg.text}\n\n")
56
+ return path
57
+
58
+
59
+ def _fmt_ts(ms: int) -> str:
60
+ total = ms // 1000
61
+ h, rem = divmod(total, 3600)
62
+ m, s = divmod(rem, 60)
63
+ return f"{h:02d}:{m:02d}:{s:02d},{ms % 1000:03d}"
64
+
65
+
66
+ def _fmt_vtt_ts(ms: int) -> str:
67
+ total = ms // 1000
68
+ h, rem = divmod(total, 3600)
69
+ m, s = divmod(rem, 60)
70
+ return f"{h:02d}:{m:02d}:{s:02d}.{ms % 1000:03d}"
@@ -0,0 +1,33 @@
1
+ """Abstract base class for TTS backends."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class VoiceInfo:
9
+ id: str
10
+ name: str
11
+ accent: str
12
+ gender: str
13
+ backend: str
14
+
15
+
16
+ class TTSBackend(ABC):
17
+ """A TTS backend turns text + voice controls into audio bytes."""
18
+
19
+ name: str
20
+
21
+ @abstractmethod
22
+ async def synthesize(
23
+ self,
24
+ text: str,
25
+ voice: str,
26
+ pitch: float | str = 0.0,
27
+ speed: float = 1.0,
28
+ ) -> bytes:
29
+ """Synthesize `text` with `voice`, returning audio bytes (MP3)."""
30
+
31
+ @abstractmethod
32
+ def list_voices(self) -> list[VoiceInfo]:
33
+ """List available voices for this backend."""
@@ -0,0 +1,54 @@
1
+ """edge-tts backend — Microsoft Edge TTS, free, 400+ voices, many accents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from talkaty.backends.base import TTSBackend, VoiceInfo
6
+
7
+
8
+ class EdgeTTS(TTSBackend):
9
+ name = "edge-tts"
10
+
11
+ async def synthesize(
12
+ self,
13
+ text: str,
14
+ voice: str,
15
+ pitch: float | str = 0.0,
16
+ speed: float = 1.0,
17
+ ) -> bytes:
18
+ import edge_tts
19
+
20
+ pitch_str = pitch if isinstance(pitch, str) else f"{pitch:+.0f}Hz"
21
+ communicate = edge_tts.Communicate(
22
+ text,
23
+ voice,
24
+ pitch=pitch_str,
25
+ rate=f"{(speed - 1) * 100:+.0f}%",
26
+ )
27
+ chunks: list[bytes] = []
28
+ async for chunk in communicate.stream():
29
+ if chunk["type"] == "audio":
30
+ chunks.append(chunk["data"])
31
+ return b"".join(chunks)
32
+
33
+ def list_voices(self) -> list[VoiceInfo]:
34
+ import edge_tts
35
+
36
+ voices = []
37
+ # edge-tts.list_voices() is async
38
+ import asyncio
39
+
40
+ async def _fetch():
41
+ return await edge_tts.list_voices()
42
+
43
+ raw = asyncio.run(_fetch())
44
+ for v in raw:
45
+ voices.append(
46
+ VoiceInfo(
47
+ id=v["ShortName"],
48
+ name=v.get("FriendlyName", v["ShortName"]),
49
+ accent=v.get("Locale", "")[:2].upper(),
50
+ gender=v.get("Gender", "unknown"),
51
+ backend="edge-tts",
52
+ )
53
+ )
54
+ return voices
@@ -0,0 +1,54 @@
1
+ """kittenTTS backend — small, local, offline TTS fallback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from talkaty.backends.base import TTSBackend, VoiceInfo
6
+
7
+
8
+ class KittenTTS(TTSBackend):
9
+ name = "kittentts"
10
+
11
+ def __init__(self) -> None:
12
+ try:
13
+ import kittentts # type: ignore
14
+
15
+ self._model = kittentts.KittenTTS()
16
+ except ImportError as exc: # pragma: no cover - optional dep
17
+ raise ImportError(
18
+ "kittentts is not installed. `pip install talkaty[kittentts]`"
19
+ ) from exc
20
+
21
+ async def synthesize(
22
+ self,
23
+ text: str,
24
+ voice: str,
25
+ pitch: float | str = 0.0,
26
+ speed: float = 1.0,
27
+ ) -> bytes:
28
+ import io
29
+
30
+ import soundfile as sf # type: ignore
31
+
32
+ audio = self._model.generate(text, voice=voice, speed=speed)
33
+ buf = io.BytesIO()
34
+ sf.write(buf, audio, 24000, format="WAV")
35
+ return buf.getvalue()
36
+
37
+ def list_voices(self) -> list[VoiceInfo]:
38
+ # kittenTTS exposes a small fixed voice set
39
+ return [
40
+ VoiceInfo(
41
+ id="expr-voice-2-f",
42
+ name="Expressive Female",
43
+ accent="US",
44
+ gender="female",
45
+ backend="kittentts",
46
+ ),
47
+ VoiceInfo(
48
+ id="expr-voice-2-m",
49
+ name="Expressive Male",
50
+ accent="US",
51
+ gender="male",
52
+ backend="kittentts",
53
+ ),
54
+ ]
@@ -0,0 +1,60 @@
1
+ """Piper TTS backend — local, offline TTS using .onnx voice models.
2
+
3
+ Each Piper model is a single voice. Provide the model path via --model.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import io
9
+ import wave
10
+
11
+ from talkaty.backends.base import TTSBackend, VoiceInfo
12
+
13
+
14
+ class PiperTTS(TTSBackend):
15
+ name = "piper"
16
+
17
+ def __init__(self, model_path: str, config_path: str | None = None) -> None:
18
+ try:
19
+ from piper_tts import PiperVoice # type: ignore
20
+ except ImportError as exc: # pragma: no cover - optional dep
21
+ raise ImportError("piper-tts is not installed. `pip install talkaty[piper]`") from exc
22
+
23
+ self.model_path = model_path
24
+ self.config_path = config_path
25
+ self._voice = PiperVoice.load(model_path, config_path)
26
+
27
+ async def synthesize(
28
+ self,
29
+ text: str,
30
+ voice: str,
31
+ pitch: float | str = 0.0,
32
+ speed: float = 1.0,
33
+ ) -> bytes:
34
+ """Synthesize `text` using the loaded Piper model.
35
+
36
+ Piper does not support per-call pitch/speed adjustment; those
37
+ controls are silently ignored for this backend.
38
+ """
39
+
40
+ buf = io.BytesIO()
41
+ sample_rate = int(self._voice.config.sample_rate)
42
+ with wave.open(buf, "wb") as wf:
43
+ wf.setnchannels(1)
44
+ wf.setsampwidth(2)
45
+ wf.setframerate(sample_rate)
46
+ for audio_bytes in self._voice.synthesize_stream_raw(text):
47
+ wf.writeframes(audio_bytes)
48
+ buf.seek(0)
49
+ return buf.getvalue()
50
+
51
+ def list_voices(self) -> list[VoiceInfo]:
52
+ return [
53
+ VoiceInfo(
54
+ id=self.model_path,
55
+ name=self.model_path,
56
+ accent="",
57
+ gender="unknown",
58
+ backend="piper",
59
+ )
60
+ ]
talkaty/cli.py ADDED
@@ -0,0 +1,197 @@
1
+ """talkaty CLI — Typer + Rich terminal interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.table import Table
12
+
13
+ from .pipeline import run
14
+ from .voices import list_personas
15
+
16
+ app = typer.Typer(
17
+ name="talkaty",
18
+ help="Generate voiceover audio from script.md using open-source TTS.",
19
+ )
20
+ console = Console()
21
+
22
+
23
+ @app.command()
24
+ def generate(
25
+ script: Path = typer.Argument(..., help="Path to script.md"),
26
+ brief: Path | None = typer.Option(None, "--brief", help="Optional brief/description file"),
27
+ voice: str | None = typer.Option(
28
+ None,
29
+ "--voice",
30
+ "-v",
31
+ help="Persona name (alpha male, smooth female, warm narrator, energetic, calm, nigerian narrator). If omitted, accent or default voice is used.",
32
+ ),
33
+ accent: str | None = typer.Option(
34
+ None,
35
+ "--accent",
36
+ "-a",
37
+ help="Accent hint (US, UK, AU, NG). If omitted, brief hint or default voice is used.",
38
+ ),
39
+ backend: str = typer.Option(
40
+ "edge-tts", "--backend", "-b", help="TTS backend: edge-tts or kittentts or piper"
41
+ ),
42
+ model: Path | None = typer.Option(
43
+ None, "--model", "-m", help="Piper .onnx voice model path (piper backend only)"
44
+ ),
45
+ pitch: float = typer.Option(0.0, "--pitch", help="Pitch shift in semitones"),
46
+ speed: float = typer.Option(1.0, "--speed", help="Speed multiplier (0.5–2.0)"),
47
+ output: Path | None = typer.Option(None, "--output", "-o", help="Output audio path"),
48
+ subtitles: bool = typer.Option(False, "--subtitles", help="Also emit .srt subtitle file"),
49
+ ) -> None:
50
+ """Generate voiceover audio from a script.md."""
51
+ opts = {
52
+ "script_path": str(script),
53
+ "brief_path": str(brief) if brief else None,
54
+ "voice": voice,
55
+ "accent": accent,
56
+ "backend": backend,
57
+ "pitch": pitch,
58
+ "speed": speed,
59
+ "output_path": str(output) if output else None,
60
+ "subtitles": subtitles,
61
+ "model_path": str(model) if model else None,
62
+ }
63
+ result = asyncio.run(
64
+ run(__import__("talkaty.pipeline", fromlist=["GenerateOptions"]).GenerateOptions(**opts))
65
+ )
66
+ console.print(f"[green]✓[/green] Voiceover written to {result.path}")
67
+ console.print(
68
+ f" voice: {result.voice_used} backend: {result.backend_used} duration: {result.duration_seconds:.1f}s"
69
+ )
70
+
71
+
72
+ @app.command()
73
+ def voices(
74
+ backend: str = typer.Option("edge-tts", "--backend", "-b", help="Filter by backend"),
75
+ ) -> None:
76
+ """List available voices/personas."""
77
+ table = Table(title="talkaty voices")
78
+ table.add_column("Persona", style="cyan")
79
+ table.add_column("Voice ID", style="magenta")
80
+ table.add_column("Accent", style="green")
81
+ table.add_column("Gender", style="yellow")
82
+ table.add_column("Description")
83
+ for p in list_personas():
84
+ if backend and p.backend != backend:
85
+ continue
86
+ table.add_row(p.id, p.voice_id(backend), p.accent, p.gender, p.description)
87
+ console.print(table)
88
+
89
+
90
+ @app.command()
91
+ def personas() -> None:
92
+ """Alias for `talkaty voices`."""
93
+ voices()
94
+
95
+
96
+ @app.command()
97
+ def preview(
98
+ text: str = typer.Argument(..., help="Short text to preview"),
99
+ voice: str = typer.Option("smooth female", "--voice", "-v", help="Persona name"),
100
+ backend: str = typer.Option("edge-tts", "--backend", "-b", help="TTS backend"),
101
+ ) -> None:
102
+ """Preview a short sample with a voice."""
103
+ from tempfile import NamedTemporaryFile
104
+
105
+ from .pipeline import GenerateOptions
106
+ from .pipeline import run as _run
107
+
108
+ with NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as fh:
109
+ fh.write(text)
110
+ tmp = fh.name
111
+
112
+ try:
113
+ result = asyncio.run(
114
+ _run(
115
+ GenerateOptions(
116
+ script_path=tmp,
117
+ voice=voice,
118
+ backend=backend,
119
+ )
120
+ )
121
+ )
122
+ console.print(f"[green]✓[/green] Preview: {result.path}")
123
+ os.unlink(tmp)
124
+ finally:
125
+ if os.path.exists(tmp):
126
+ os.unlink(tmp)
127
+
128
+
129
+ @app.command()
130
+ def batch(
131
+ scripts_dir: Path = typer.Argument(..., help="Directory of *.md scripts"),
132
+ output_dir: Path = typer.Argument(..., help="Directory for output audio"),
133
+ voice: str = typer.Option("smooth female", "--voice", "-v", help="Persona name"),
134
+ accent: str = typer.Option("US", "--accent", "-a", help="Accent hint"),
135
+ backend: str = typer.Option("edge-tts", "--backend", "-b", help="TTS backend"),
136
+ model: Path | None = typer.Option(
137
+ None, "--model", "-m", help="Piper .onnx voice model path (piper backend only)"
138
+ ),
139
+ pitch: float = typer.Option(0.0, "--pitch", help="Pitch shift in semitones"),
140
+ speed: float = typer.Option(1.0, "--speed", help="Speed multiplier"),
141
+ subtitles: bool = typer.Option(False, "--subtitles", help="Also emit .srt files"),
142
+ jobs: int = typer.Option(4, "--jobs", "-j", help="Number of parallel batch jobs"),
143
+ ) -> None:
144
+ """Generate voiceovers for all *.md in a directory (in parallel)."""
145
+ scripts_dir = scripts_dir.resolve()
146
+ output_dir = output_dir.resolve()
147
+ output_dir.mkdir(parents=True, exist_ok=True)
148
+
149
+ scripts = sorted(scripts_dir.glob("*.md"))
150
+ if not scripts:
151
+ console.print(f"[yellow]No *.md files found in {scripts_dir}[/yellow]")
152
+ return
153
+
154
+ from concurrent.futures import ThreadPoolExecutor, as_completed
155
+
156
+ from .pipeline import GenerateOptions
157
+ from .pipeline import run as _run
158
+
159
+ def _generate_one(script: Path) -> tuple[Path, str | None]:
160
+ out = output_dir / (script.stem + ".mp3")
161
+ try:
162
+ asyncio.run(
163
+ _run(
164
+ GenerateOptions(
165
+ script_path=str(script),
166
+ voice=voice,
167
+ accent=accent,
168
+ backend=backend,
169
+ pitch=pitch,
170
+ speed=speed,
171
+ output_path=str(out),
172
+ subtitles=subtitles,
173
+ model_path=str(model) if model else None,
174
+ )
175
+ )
176
+ )
177
+ return script, None
178
+ except Exception as exc: # noqa: BLE001
179
+ return script, str(exc)
180
+
181
+ max_workers = max(1, min(jobs, len(scripts)))
182
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
183
+ futures = {pool.submit(_generate_one, s): s for s in scripts}
184
+ for future in as_completed(futures):
185
+ script, err = future.result()
186
+ if err:
187
+ console.print(f"[red]✗[/red] {script.name}: {err}")
188
+ else:
189
+ console.print(f"[green]✓[/green] {script.name} → {script.stem}.mp3")
190
+
191
+
192
+ def main() -> None:
193
+ app()
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
talkaty/config.py ADDED
@@ -0,0 +1,22 @@
1
+ """talkaty configuration — pydantic settings with TALKATY_* env overrides."""
2
+
3
+ from functools import lru_cache
4
+
5
+ from pydantic import Field
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+
9
+ class Settings(BaseSettings):
10
+ model_config = SettingsConfigDict(env_file=".env", env_prefix="TALKATY_", extra="ignore")
11
+
12
+ default_backend: str = Field(default="edge-tts")
13
+ default_voice: str = Field(default="smooth female")
14
+ default_accent: str = Field(default="US")
15
+ default_pitch: float = Field(default=0.0)
16
+ default_speed: float = Field(default=1.0)
17
+ output_dir: str = Field(default=".")
18
+
19
+
20
+ @lru_cache
21
+ def get_settings() -> Settings:
22
+ return Settings()