-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreed.py
More file actions
executable file
Β·1148 lines (977 loc) Β· 37.6 KB
/
reed.py
File metadata and controls
executable file
Β·1148 lines (977 loc) Β· 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""reed - A CLI that reads text aloud using piper-tts."""
import argparse
import os
import platform
import shutil
import signal
import subprocess
from subprocess import CompletedProcess
import sys
import tempfile
import threading
import time
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from enum import Enum, auto
from html.parser import HTMLParser
from dataclasses import dataclass, field
from pathlib import Path
from collections.abc import Callable, Iterator, Sequence
from typing import TYPE_CHECKING, TextIO
if TYPE_CHECKING:
from prompt_toolkit import PromptSession
try:
from pypdf import PdfReader
except ImportError: # pragma: no cover - validated in runtime error path
PdfReader = None # type: ignore[assignment,misc]
from rich.console import Console
from rich.markup import escape
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
console = Console()
DEFAULT_SILENCE = 0.6
class ReedError(Exception):
pass
class PlaybackState(Enum):
"""Enum representing the current playback state."""
IDLE = auto()
PLAYING = auto()
PAUSED = auto()
STOPPED = auto()
class PlaybackController:
"""Non-blocking playback controller for managing TTS audio playback.
Runs piper TTS and audio player in a background thread, allowing
pause/resume/stop controls without blocking the interactive prompt.
"""
def __init__(self, print_fn: Callable[..., None] = console.print) -> None:
self._current_proc: subprocess.Popen | None = None
self._piper_proc: subprocess.Popen | None = None
self._playback_thread: threading.Thread | None = None
self._state = PlaybackState.IDLE
self._current_text = ""
self._config: ReedConfig | None = None
self._lock = threading.Lock()
self._print_fn = print_fn
self._stop_event = threading.Event()
def play(self, text: str, config: ReedConfig) -> None:
"""Start playback of text in a background thread.
If already playing, stops current playback before starting new one.
"""
with self._lock:
if self._state == PlaybackState.PLAYING:
self._stop_locked()
self._current_text = text
self._config = config
self._state = PlaybackState.PLAYING
self._stop_event.clear()
self._playback_thread = threading.Thread(
target=self._playback_worker, args=(text, config), daemon=True
)
self._playback_thread.start()
def _playback_worker(self, text: str, config: ReedConfig) -> None:
"""Background worker that generates and plays audio.
Runs piper to generate WAV, then plays it with the system audio player.
Uses Popen for both to enable pause/resume/stop controls.
"""
play_cmd = _default_play_cmd()
tmp_path = None
try:
# Generate WAV with piper
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
tmp_path = tmp.name
piper_cmd = build_piper_cmd(
config.model,
config.speed,
config.volume,
config.silence,
Path(tmp_path),
)
self._piper_proc = subprocess.Popen(
piper_cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
piper_stdout, piper_stderr = self._piper_proc.communicate(
input=text.encode("utf-8")
)
if self._stop_event.is_set() or self._piper_proc.returncode != 0:
self._print_fn("\n[bold red]β Piper error[/bold red]")
return
# Play WAV with audio player
self._current_proc = subprocess.Popen([*play_cmd, tmp_path])
# Wait for playback to complete or be interrupted
self._current_proc.wait()
if self._stop_event.is_set():
self._state = PlaybackState.STOPPED
self._print_fn("[bold red]βΉ Stopped[/bold red]")
else:
self._print_fn("[bold green]β Done[/bold green]")
except Exception as e:
self._print_fn(f"[bold red]Playback error: {e}[/bold red]")
finally:
# Cleanup temp file
if tmp_path and os.path.exists(tmp_path):
try:
os.unlink(tmp_path)
except OSError:
pass
# Reset state if not stopped
with self._lock:
if self._state not in (PlaybackState.STOPPED, PlaybackState.PAUSED):
self._state = PlaybackState.IDLE
self._current_proc = None
self._piper_proc = None
def pause(self) -> bool:
"""Pause playback. Returns True if successful.
On Unix: sends SIGSTOP to player process.
On Windows: not supported, returns False.
"""
with self._lock:
if self._state != PlaybackState.PLAYING or self._current_proc is None:
return False
if os.name == "posix":
sigstop = getattr(signal, "SIGSTOP", None)
if sigstop is None:
return False
self._current_proc.send_signal(sigstop)
self._state = PlaybackState.PAUSED
self._print_fn("\n[bold yellow]βΈ Paused[/bold yellow]")
return True
return False
def resume(self) -> bool:
"""Resume paused playback. Returns True if successful.
On Unix: sends SIGCONT to player process.
On Windows: not supported, returns False.
"""
with self._lock:
if self._state != PlaybackState.PAUSED or self._current_proc is None:
return False
if os.name == "posix":
sigcont = getattr(signal, "SIGCONT", None)
if sigcont is None:
return False
self._current_proc.send_signal(sigcont)
self._state = PlaybackState.PLAYING
self._print_fn("\n[bold green]βΆ Playing...[/bold green]")
return True
return False
def stop(self) -> bool:
"""Stop playback. Returns True if was playing/paused."""
with self._lock:
return self._stop_locked()
def _stop_locked(self) -> bool:
"""Internal stop implementation - must be called with lock held."""
if self._state == PlaybackState.IDLE:
return False
self._stop_event.set()
if self._current_proc:
try:
self._current_proc.terminate()
self._current_proc.wait(timeout=2)
except subprocess.TimeoutExpired, ProcessLookupError:
try:
self._current_proc.kill()
except ProcessLookupError:
pass
if self._piper_proc and self._piper_proc.poll() is None:
try:
self._piper_proc.terminate()
except ProcessLookupError:
pass
self._state = PlaybackState.IDLE
self._current_proc = None
self._piper_proc = None
return True
def is_playing(self) -> bool:
"""Check if currently playing."""
with self._lock:
return self._state == PlaybackState.PLAYING
def wait(self) -> None:
"""Block until playback completes (for non-interactive mode)."""
if self._playback_thread:
self._playback_thread.join()
def get_current_text(self) -> str:
"""Get the currently playing text (for replay)."""
return self._current_text
def _data_dir() -> Path:
system = platform.system()
if system == "Windows":
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
else:
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
d = base / "reed"
d.mkdir(parents=True, exist_ok=True)
return d
DEFAULT_MODEL_NAME = "en_US-kristin-medium"
def _default_model() -> Path:
return _data_dir() / f"{DEFAULT_MODEL_NAME}.onnx"
def _model_url(name: str) -> tuple[str, str]:
parts = name.split("-")
lang_code = parts[0]
quality = parts[-1]
voice_name = "_".join(parts[1:-1])
family = lang_code[:2]
base = (
f"https://huggingface.co/rhasspy/piper-voices/resolve/main/"
f"{family}/{lang_code}/{voice_name}/{quality}/{name}"
)
return (f"{base}.onnx", f"{base}.onnx.json")
def _download_file(
url: str, dest: Path, print_fn: Callable[..., None] = console.print
) -> None:
print_fn(f"[bold cyan]β¬ Downloading[/bold cyan] {escape(dest.name)}β¦")
urllib.request.urlretrieve(url, dest)
print_fn(f"[bold green]β Saved[/bold green] {escape(str(dest))}")
@dataclass(frozen=True)
class ReedConfig:
model: Path = field(default_factory=_default_model)
speed: float = 1.0
volume: float = 1.0
silence: float = DEFAULT_SILENCE
output: Path | None = None
def ensure_model(
config: ReedConfig, print_fn: Callable[..., None] = console.print
) -> None:
if config.model.exists():
return
if config.model.parent != _data_dir():
raise ReedError(f"Model not found: {config.model}")
name = config.model.stem
onnx_url, json_url = _model_url(name)
_download_file(onnx_url, config.model, print_fn)
_download_file(json_url, config.model.with_suffix(".onnx.json"), print_fn)
QUIT_WORDS = ("/quit", "/exit")
BANNER_MARKUP = """π [bold]reed[/bold] - Interactive Mode
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
[dim]Type or paste text and press Enter to hear it.[/dim]
[dim]Drag and drop PDF/EPUB files or type [bold]/load <path>[/bold] to read files.[/dim]
[dim]Type [bold]/quit[/bold] or [bold]/exit[/bold] to stop. Ctrl-D for EOF.[/dim]
[dim]Available commands: [bold]/help[/bold], [bold]/clear[/bold], [bold]/replay[/bold], [bold]/load[/bold][/dim]"""
COMMANDS = {
"/quit": "Exit interactive mode",
"/exit": "Exit interactive mode (sync)",
"/help": "Show this help",
"/clear": "Clear screen",
"/replay": "Replay last text",
"/load <path>": "Load and read a PDF or EPUB file",
}
def _default_play_cmd() -> list[str]:
system = platform.system()
if system == "Darwin":
return ["afplay"]
if system == "Linux":
for cmd, args in [
("paplay", []),
("aplay", []),
("ffplay", ["-nodisp", "-autoexit"]),
]:
if shutil.which(cmd):
return [cmd, *args]
if system == "Windows":
if shutil.which("powershell"):
return [
"powershell",
"-NoProfile",
"-NonInteractive",
"-c",
"(New-Object System.Media.SoundPlayer $args[0]).PlaySync()",
]
if shutil.which("ffplay"):
return ["ffplay", "-nodisp", "-autoexit", "-hide_banner"]
raise ReedError("No supported audio player found")
def _default_clipboard_cmd() -> list[str]:
system = platform.system()
if system == "Darwin":
return ["pbpaste"]
if system == "Linux":
for cmd, args in [
("wl-paste", []),
("xclip", ["-selection", "clipboard", "-o"]),
("xsel", ["--clipboard", "--output"]),
]:
if shutil.which(cmd):
return [cmd, *args]
if system == "Windows":
return ["powershell", "-Command", "Get-Clipboard"]
raise ReedError("No supported clipboard tool found")
def get_text(
args: argparse.Namespace,
stdin: TextIO,
run: Callable[..., CompletedProcess] = subprocess.run,
) -> str:
if args.clipboard:
clipboard_cmd = _default_clipboard_cmd()
result = run(clipboard_cmd, capture_output=True, text=True)
if result.returncode != 0:
raise ReedError("Failed to read clipboard")
return result.stdout.strip()
if args.file:
file_path = Path(args.file)
if args.pages:
raise ReedError("--pages can only be used with PDF or EPUB files")
return file_path.read_text()
if not stdin.isatty():
return stdin.read().strip()
if args.text:
return " ".join(args.text)
raise ReedError("No input provided. Use --help for usage.")
def _parse_range_selection(
selection_str: str, total: int, label: str = "page"
) -> list[int]:
selection = selection_str.strip()
if not selection:
raise ReedError("Invalid page selection")
selected: list[int] = []
seen: set[int] = set()
for part in selection.split(","):
token = part.strip()
if not token:
raise ReedError("Invalid page selection")
if "-" in token:
bounds = token.split("-", 1)
if len(bounds) != 2 or not bounds[0].isdigit() or not bounds[1].isdigit():
raise ReedError("Invalid page selection")
start = int(bounds[0])
end = int(bounds[1])
if start < 1 or end < 1 or end < start:
raise ReedError("Invalid page selection")
pages: Sequence[int] = range(start, end + 1)
else:
if not token.isdigit():
raise ReedError("Invalid page selection")
page = int(token)
if page < 1:
raise ReedError("Invalid page selection")
pages = [page]
for page in pages:
if page > total:
raise ReedError(
f"{label.title()} {page} is out of range (total: {total})"
)
index = page - 1
if index not in seen:
seen.add(index)
selected.append(index)
if not selected:
raise ReedError("Invalid page selection")
return selected
def _iter_pdf_pages(
path: Path, page_selection: str | None
) -> Iterator[tuple[int, int, str]]:
"""Yield ``(page_number, total_pages, text)`` for each selected PDF page."""
if PdfReader is None:
raise ReedError("PDF support requires pypdf. Reinstall reed with dependencies.")
try:
reader = PdfReader(str(path))
except Exception as e: # pragma: no cover - depends on third-party parser internals
raise ReedError(f"Failed to read PDF: {e}")
total_pages = len(reader.pages)
if total_pages == 0:
raise ReedError("PDF has no pages")
if page_selection:
page_indices: Sequence[int] = _parse_range_selection(
page_selection, total_pages
)
else:
page_indices = range(total_pages)
found_any = False
for index in page_indices:
page_text = reader.pages[index].extract_text() or ""
page_text = page_text.strip()
if page_text:
found_any = True
yield (index + 1, total_pages, page_text)
if not found_any:
raise ReedError("No extractable text found in PDF")
_BLOCK_TAGS = frozenset(
{
"p",
"div",
"br",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"li",
"tr",
"blockquote",
"section",
"article",
}
)
class _HTMLTextExtractor(HTMLParser):
"""Extract plain text from HTML, stripping all tags."""
def __init__(self) -> None:
super().__init__()
self._parts: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag.lower() in _BLOCK_TAGS:
self._parts.append("\n")
def handle_data(self, data: str) -> None:
self._parts.append(data)
def get_text(self) -> str:
raw = "".join(self._parts)
lines = raw.split("\n")
paragraphs = [" ".join(line.split()) for line in lines]
return "\n".join(paragraphs).strip()
def _strip_html(html_bytes: bytes) -> str:
extractor = _HTMLTextExtractor()
extractor.feed(html_bytes.decode("utf-8", errors="replace"))
return extractor.get_text()
def _load_epub_spine(path: Path) -> list[tuple[str, zipfile.ZipFile]]:
"""Parse EPUB spine and return ``(href, zip_file)`` pairs in reading order.
Only reads the OPF manifest (lightweight), does NOT decompress chapter content.
Each item is a tuple of ``(internal_path, ZipFile)`` so callers can lazily
read individual chapters with ``zf.read(href)``.
"""
try:
zf = zipfile.ZipFile(str(path), "r")
except Exception as e:
raise ReedError(f"Failed to open EPUB: {e}")
try:
container_xml = zf.read("META-INF/container.xml")
except KeyError:
zf.close()
raise ReedError("Invalid EPUB: missing META-INF/container.xml")
container = ET.fromstring(container_xml)
ns = {"c": "urn:oasis:names:tc:opendocument:xmlns:container"}
rootfile_el = container.find(".//c:rootfile", ns)
if rootfile_el is None:
zf.close()
raise ReedError("Invalid EPUB: no rootfile in container.xml")
opf_path = rootfile_el.get("full-path", "")
try:
opf_xml = zf.read(opf_path)
except KeyError:
zf.close()
raise ReedError(f"Invalid EPUB: missing {opf_path}")
opf = ET.fromstring(opf_xml)
opf_ns = opf.tag.split("}")[0] + "}" if "}" in opf.tag else ""
opf_dir = opf_path.rsplit("/", 1)[0] + "/" if "/" in opf_path else ""
manifest: dict[str, str] = {}
for item in opf.findall(f".//{opf_ns}manifest/{opf_ns}item"):
item_id = item.get("id", "")
href = item.get("href", "")
media = item.get("media-type", "")
props = item.get("properties", "")
if media == "application/xhtml+xml" and "nav" not in props:
manifest[item_id] = opf_dir + href
spine_hrefs: list[tuple[str, zipfile.ZipFile]] = []
for itemref in opf.findall(f".//{opf_ns}spine/{opf_ns}itemref"):
idref = itemref.get("idref", "")
if idref in manifest:
spine_hrefs.append((manifest[idref], zf))
if not spine_hrefs:
zf.close()
raise ReedError("No chapters found in EPUB")
return spine_hrefs
def _read_epub_chapter(chapter: tuple[str, zipfile.ZipFile]) -> str:
"""Read and strip HTML from a single EPUB chapter. Lightweight β only decompresses one file."""
href, zf = chapter
try:
raw = zf.read(href)
except KeyError:
return ""
return _strip_html(raw).strip()
def _split_paragraphs(text: str) -> list[str]:
"""Split text into paragraph-sized chunks for incremental TTS.
Each non-blank line becomes a separate chunk that is spoken individually
so playback starts quickly.
"""
return [line.strip() for line in text.splitlines() if line.strip()]
def _iter_epub_chapters(
path: Path, chapter_selection: str | None
) -> Iterator[tuple[int, int, str]]:
"""Yield ``(chapter_number, total_chapters, text)`` for each selected EPUB chapter."""
chapters = _load_epub_spine(path)
total_chapters = len(chapters)
if chapter_selection:
chapter_indices: Sequence[int] = _parse_range_selection(
chapter_selection, total_chapters, label="chapter"
)
else:
chapter_indices = range(total_chapters)
try:
for index in chapter_indices:
text = _read_epub_chapter(chapters[index])
yield (index + 1, total_chapters, text)
finally:
if chapters:
chapters[0][1].close()
def build_piper_cmd(
model: Path,
speed: float,
volume: float,
silence: float,
output: Path | None = None,
) -> list[str]:
cmd = [
sys.executable,
"-m",
"piper",
"--model",
str(model),
"--length-scale",
str(speed),
"--volume",
str(volume),
"--sentence-silence",
str(silence),
]
if output:
cmd += ["--output-file", str(output)]
return cmd
def print_generation_progress(print_fn: Callable[..., None] = console.print) -> None:
print_fn("[bold cyan]β Generating speech...[/bold cyan]")
def print_playback_progress(print_fn: Callable[..., None] = console.print) -> None:
print_fn("[bold green]βΆ Playing...[/bold green]")
def print_saved_message(
output: Path, print_fn: Callable[..., None] = console.print
) -> None:
panel = Panel.fit(
f"[bold green]β Successfully saved[/bold green]\n\n"
f"[dim]File:[/dim] [cyan]{escape(str(output))}[/cyan]",
title="[bold]Output Saved[/bold]",
border_style="green",
)
print_fn(panel)
def print_error(message: str, print_fn: Callable[..., None] = console.print) -> None:
panel = Panel.fit(
f"[bold red]{escape(message)}[/bold red]",
title="[bold]Error[/bold]",
border_style="red",
)
print_fn(panel)
def print_banner(print_fn: Callable[..., None] = console.print) -> None:
print_fn(Text.from_markup(BANNER_MARKUP))
def print_help(print_fn: Callable[..., None] = console.print) -> None:
text = Text.from_markup("\n[bold]Available Commands:[/bold]\n")
for cmd, desc in COMMANDS.items():
text.append("\n")
text.append(cmd, style="cyan")
text.append(f" - {desc}")
panel = Panel(text, title="Commands", border_style="cyan")
print_fn(panel)
def speak_text(
text: str,
config: ReedConfig,
run: Callable[..., CompletedProcess] = subprocess.run,
print_fn: Callable[..., None] = console.print,
play_cmd: list[str] | None = None,
controller: PlaybackController | None = None,
) -> None:
"""Speak text aloud.
Args:
text: Text to speak.
config: Reed configuration.
run: subprocess runner (for testing).
print_fn: Function for printing messages.
play_cmd: Audio player command (optional, auto-detected if None).
controller: PlaybackController for non-blocking playback (optional).
If provided, playback is non-blocking. If None, blocks.
"""
if config.output:
# File output mode - always blocking
print_generation_progress(print_fn)
start = time.time()
piper_cmd = build_piper_cmd(
config.model, config.speed, config.volume, config.silence, config.output
)
proc = run(piper_cmd, input=text, text=True, capture_output=True)
elapsed = time.time() - start
if proc.returncode != 0:
raise ReedError(f"piper error: {proc.stderr}")
print_fn(f"\n[bold green]β Done in {elapsed:.1f}s[/bold green]")
print_saved_message(config.output, print_fn)
elif controller is not None:
# Non-blocking mode with controller
print_generation_progress(print_fn)
controller.play(text, config)
else:
# Legacy blocking mode
print_generation_progress(print_fn)
start = time.time()
with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
piper_cmd = build_piper_cmd(
config.model,
config.speed,
config.volume,
config.silence,
Path(tmp.name),
)
proc = run(piper_cmd, input=text, text=True, capture_output=True)
if proc.returncode != 0:
raise ReedError(f"piper error: {proc.stderr}")
print_fn(
f"\n[bold green]β Generated in {time.time() - start:.1f}s[/bold green]"
)
print_playback_progress(print_fn)
resolved_play_cmd = play_cmd or _default_play_cmd()
result = run([*resolved_play_cmd, tmp.name])
if result.returncode != 0:
raise ReedError("playback error")
print_fn("[bold green]β Done[/bold green]")
def _make_prompt_session(
prompt: str,
quit_words: tuple[str, ...],
) -> "PromptSession[str]":
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.history import InMemoryHistory
history = InMemoryHistory()
for cmd in quit_words:
history.append_string(cmd)
return PromptSession(
message=prompt,
history=history,
auto_suggest=AutoSuggestFromHistory(),
)
def interactive_loop(
speak_line: Callable[[str], None],
prompt: str = "> ",
quit_words: tuple[str, ...] = QUIT_WORDS,
print_fn: Callable[..., None] = console.print,
prompt_fn: Callable[[], str] | None = None,
clear_fn: Callable[..., None] = console.clear,
controller: PlaybackController | None = None,
) -> int:
quit_set = {w.lower() for w in quit_words}
help_cmd = "/help"
clear_cmd = "/clear"
replay_cmd = "/replay"
load_cmd = "/load"
print_banner(print_fn)
if prompt_fn is None:
session = _make_prompt_session(prompt, quit_words)
prompt_fn = session.prompt
last_text = ""
def _path_candidates(path_text: str) -> list[str]:
stripped = path_text.strip("\"'")
normalized = stripped.replace("\\ ", " ")
if normalized == stripped:
return [normalized]
return [normalized, stripped]
def _try_detect_file_path(input_text: str) -> str | None:
"""Try to detect if input is a file path. Returns cleaned path or None."""
for candidate in _path_candidates(input_text):
if not candidate.lower().endswith((".pdf", ".epub")):
continue
if Path(candidate).exists():
return candidate
return None
def _read_file_path(file_path_str: str) -> None:
"""Load and read a PDF or EPUB file."""
file_path: Path | None = None
for candidate in _path_candidates(file_path_str):
candidate_path = Path(candidate)
if candidate_path.exists():
file_path = candidate_path
break
if file_path is None:
print_fn(f"[bold red]File not found:[/bold red] {file_path_str}\n")
return
suffix = file_path.suffix.lower()
if suffix not in (".pdf", ".epub"):
print_fn(
f"[bold red]Unsupported file type:[/bold red] {suffix} (use .pdf or .epub)\n"
)
return
try:
if suffix == ".pdf":
for page_num, total, page_text in _iter_pdf_pages(file_path, None):
print_fn(f"\n[bold cyan]π Page {page_num}/{total}[/bold cyan]")
speak_line(page_text)
# Wait for current speech to complete before next page
if controller is not None:
controller.wait()
elif suffix == ".epub":
for ch_num, total, ch_text in _iter_epub_chapters(file_path, None):
print_fn(f"\n[bold cyan]π Chapter {ch_num}/{total}[/bold cyan]")
speak_line(ch_text)
# Wait for current speech to complete before next chapter
if controller is not None:
controller.wait()
except ReedError as e:
print_error(str(e), print_fn)
print_fn("")
try:
while True:
try:
text = prompt_fn()
except EOFError:
return 0
text = text.strip()
if not text:
continue
cmd = text.lower()
if cmd in quit_set:
return 0
elif cmd == help_cmd:
print_help(print_fn)
print_fn("")
continue
elif cmd == clear_cmd:
clear_fn()
print_banner(print_fn)
continue
elif cmd == replay_cmd:
if controller is not None:
# Replay using controller's stored text
replay_text = controller.get_current_text()
if replay_text:
speak_line(replay_text)
print_fn("")
else:
print_fn("[bold yellow]No text to replay.[/bold yellow]\n")
elif last_text:
speak_line(last_text)
print_fn("")
else:
print_fn("[bold yellow]No text to replay.[/bold yellow]\n")
continue
elif cmd.startswith(load_cmd + " "):
# Handle /load <path>
parts = text.split(maxsplit=1)
if len(parts) < 2:
print_fn(
f"[bold yellow]Usage:[/bold yellow] {parts[0]} <file-path>\n"
)
continue
file_path_str = parts[1]
_read_file_path(file_path_str)
continue
detected_path = _try_detect_file_path(text)
if detected_path:
_read_file_path(detected_path)
continue
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
if not lines:
continue
last_text = "\n".join(lines)
speak_line(last_text)
print_fn("")
except KeyboardInterrupt:
return 0
def _should_enter_interactive(args: argparse.Namespace, stdin: TextIO | None) -> bool:
if args.text or args.file or args.clipboard or args.pages:
return False
if stdin is not None and hasattr(stdin, "isatty") and stdin.isatty():
return True
return False
def main(
argv: list[str] | None = None,
run: Callable[..., CompletedProcess] = subprocess.run,
interactive_loop_fn: Callable[..., int] | None = None,
stdin: TextIO | None = None,
print_fn: Callable[..., None] = console.print,
) -> int:
if stdin is None:
stdin = sys.stdin
parser = argparse.ArgumentParser(
prog="reed",
description="Read text aloud using piper-tts",
)
parser.add_argument("text", nargs="*", help="Text to read aloud")
parser.add_argument("-f", "--file", help="Read text from a file")
parser.add_argument(
"--pages",
default=None,
help="PDF pages to read (1-based), e.g. 1,3-5",
)
parser.add_argument(
"-c", "--clipboard", action="store_true", help="Read text from clipboard"
)
parser.add_argument(
"-m", "--model", default=None, help="Voice name or path to voice model"
)
parser.add_argument(
"-s",
"--speed",
type=float,
default=1.0,
help="Speech speed (default: 1.0, lower=slower)",
)
parser.add_argument(
"-v",
"--volume",
type=float,
default=1.0,
help="Volume multiplier (default: 1.0)",
)
parser.add_argument(
"-o", "--output", type=Path, help="Save to WAV file instead of playing"
)
parser.add_argument(
"--silence",
type=float,
default=DEFAULT_SILENCE,
help="Seconds of silence between sentences",
)
args = parser.parse_args(argv)
if args.pages:
if not args.file:
print_error("--pages requires --file <PDF or EPUB>", print_fn)
return 1
if Path(args.file).suffix.lower() not in (".pdf", ".epub"):
print_error("--pages can only be used with PDF or EPUB files", print_fn)
return 1
# Resolve model: None β default, short name β data dir path
if args.model is None:
model_path = _default_model()
else:
model_path = Path(args.model)
if not model_path.exists() and "/" not in args.model and "\\" not in args.model:
name = args.model
if not name.endswith(".onnx"):
name += ".onnx"
model_path = _data_dir() / name
# ββ reed voices ββββββββββββββββββββββββββββββββββββββββββββββ
if args.text == ["voices"]:
data = _data_dir()
models = sorted(data.glob("*.onnx"))
if not models:
print_fn("[dim]No voices installed.[/dim]")
print_fn(
f"[dim]Download one with:[/dim] reed download {DEFAULT_MODEL_NAME}"
)
return 0
table = Table(title="Installed Voices")
table.add_column("Name", style="cyan")
table.add_column("Size (MB)", justify="right")