-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_subprocess.py
More file actions
78 lines (70 loc) · 1.92 KB
/
Copy pathpython_subprocess.py
File metadata and controls
78 lines (70 loc) · 1.92 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
from __future__ import annotations
import argparse
import json
import subprocess
from pathlib import Path
def synthesize(
text: str,
output: Path,
*,
voice: str = "Ryan",
language: str = "en",
style: str | None = None,
utter_command: str = "utter",
) -> Path:
"""Generate a WAV through the globally installed Utter CLI."""
output = output.expanduser().resolve(strict=False)
output.parent.mkdir(parents=True, exist_ok=True)
command = [
utter_command,
"speak",
"--stdin",
"--voice",
voice,
"--language",
language,
"--output",
str(output),
"--json",
]
if style:
command.extend(["--style", style])
result = subprocess.run(
command,
input=text,
text=True,
capture_output=True,
check=False,
)
try:
payload = json.loads(result.stdout)
except json.JSONDecodeError as error:
raise RuntimeError(
f"Utter returned invalid JSON: {result.stdout!r}\n{result.stderr.strip()}"
) from error
if result.returncode != 0:
failure = payload.get("error", {})
raise RuntimeError(
f"Utter failed ({failure.get('code')}): {failure.get('message')}\n"
f"{result.stderr.strip()}"
)
return Path(payload["output"])
def main() -> int:
parser = argparse.ArgumentParser(description="Generate speech through Utter.")
parser.add_argument("text")
parser.add_argument("output", type=Path)
parser.add_argument("--voice", default="Ryan")
parser.add_argument("--language", default="en")
parser.add_argument("--style")
args = parser.parse_args()
output = synthesize(
args.text,
args.output,
voice=args.voice,
language=args.language,
style=args.style,
)
print(output)
return 0
if __name__ == "__main__":
raise SystemExit(main())