-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeak.py
More file actions
executable file
·99 lines (83 loc) · 2.93 KB
/
Copy pathspeak.py
File metadata and controls
executable file
·99 lines (83 loc) · 2.93 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
#!/usr/bin/env python3
import os
import sys
import subprocess
from datetime import datetime
from urllib.request import Request, urlopen
from urllib.error import HTTPError
import json
TTS_API_BASE_URL = os.getenv('TTS_API_BASE_URL', 'https://api.openai.com/v1')
TTS_API_KEY = os.getenv('TTS_API_KEY') or os.getenv('OPENAI_API_KEY')
TTS_MODEL = os.getenv('TTS_MODEL')
TTS_VOICE = os.getenv('TTS_VOICE')
TTS_LANG = os.getenv('TTS_LANG')
TTS_AUDIO_FORMAT = os.getenv('TTS_AUDIO_FORMAT', 'mp3')
TTS_DEBUG = os.getenv('TTS_DEBUG')
def speak(input: str) -> bytes:
model = TTS_MODEL or 'kokoro'
voice = TTS_VOICE or 'af_bella'
format = TTS_AUDIO_FORMAT
lang = TTS_LANG
response_format = format
speed = 1.0
body: dict[str, str | float] = {
'input': input,
'model': model,
'voice': voice,
'format': format,
'response_format': response_format,
'speed': speed,
'lang': lang
}
url = f"{TTS_API_BASE_URL}/audio/speech"
headers = {'Content-Type': 'application/json'}
if TTS_API_KEY:
headers['Authorization'] = f"Bearer {TTS_API_KEY}"
try:
timestamp = datetime.now().timestamp() * 1000
if TTS_DEBUG:
print(f"Generating audio from text: {len(input)} characters...")
req = Request(url, data=json.dumps(body).encode('utf-8'), headers=headers, method='POST')
with urlopen(req) as response:
if response.status != 200:
raise Exception(f"HTTP error with the status: {response.status}")
buffer = response.read()
elapsed = datetime.now().timestamp() * 1000 - timestamp
if TTS_DEBUG:
print(f"Audio generation took {elapsed:.0f} ms.")
return buffer
except HTTPError as e:
if TTS_DEBUG:
print(f"Error: {e}", file=sys.stderr)
raise
except Exception as e:
if TTS_DEBUG:
print(f"Error: {e}", file=sys.stderr)
raise
def main():
args = sys.argv[1:]
input = ' '.join(args)
if not input.strip():
if not sys.stdin.isatty():
input = sys.stdin.read().strip()
if not input.strip():
print('Usage:')
print()
print('./speak.py "How are you?"')
print('echo "Good morning" | ./speak.py')
sys.exit(1)
filename = datetime.now().isoformat()[:16].replace('-', '').replace(':', '').replace('T', '') + f'.{TTS_AUDIO_FORMAT}'
buffer = speak(input)
with open(filename, 'wb') as f:
f.write(buffer)
if TTS_DEBUG:
print(f"Saved {len(buffer)} bytes to {filename}")
try:
speaker = subprocess.Popen(['play', filename])
speaker.wait()
except FileNotFoundError:
print(f"Failed to play audio: 'play' command not found", file=sys.stderr)
except Exception as err:
print(f"Failed to play audio: {err}", file=sys.stderr)
if __name__ == '__main__':
main()