Rise
The Vieneo Province
Loading...
Searching...
No Matches
erin.py
Go to the documentation of this file.
1"""Local, reference-conditioned Erin text-to-speech using Chatterbox Nano."""
2import argparse
3import json
4import os
5import random
6import threading
7import time
8from pathlib import Path
9
10ROOT = Path(__file__).resolve().parent
11MODEL = ROOT / 'models' / 'nano'
12MODEL_REVISION = '71ccd1d0081b430592cea481f4307e764e07bc64'
13MODEL_FILES = ['added_tokens.json', 'merges.txt', 's3gen_meanflow.safetensors',
14 'special_tokens_map.json', 't3_nano_v1.safetensors',
15 'tokenizer_config.json', 've.safetensors', 'vocab.json']
16for key, value in {
17 'HF_HOME': str(ROOT / 'cache' / 'huggingface'),
18 'TORCH_HOME': str(ROOT / 'cache' / 'torch'),
19 'NUMBA_CACHE_DIR': str(ROOT / 'cache' / 'numba'),
20 'GRADIO_TEMP_DIR': str(ROOT / 'cache' / 'gradio'),
21 'HF_HUB_DISABLE_TELEMETRY': '1',
22 'HF_HUB_DISABLE_XET': '1',
23 'GRADIO_ANALYTICS_ENABLED': 'False',
24 'DO_NOT_TRACK': '1',
25}.items():
26 os.environ[key] = value
27
28PROFILES = json.loads((ROOT / 'profiles.json').read_text(encoding='utf-8'))
29_model = None
30_lock = threading.Lock()
31
32
34 global _model
35 if _model is None:
36 import torch
37 from chatterbox.tts_turbo import ChatterboxTurboTTS
38 torch.set_num_threads(min(8, os.cpu_count() or 4))
39 torch.set_num_interop_threads(1)
40 print('Loading Erin on CPU...', flush=True)
41 _model = ChatterboxTurboTTS.from_local(MODEL, device='cpu', nano=True)
42 return _model
43
44
45def condition_path(profile):
46 return ROOT / 'voices' / (profile.replace(' ', '_') + '.pt')
47
48
49def setup():
50 from huggingface_hub import snapshot_download
51 MODEL.mkdir(parents=True, exist_ok=True)
52 if not all((MODEL / filename).is_file() for filename in MODEL_FILES):
53 snapshot_download('ResembleAI/chatterbox-nano', revision=MODEL_REVISION, local_dir=MODEL,
54 allow_patterns=MODEL_FILES, max_workers=3)
55 model = load_model()
56 (ROOT / 'voices').mkdir(exist_ok=True)
57 from erin_profile import build_voice_profile
58 build_voice_profile(ROOT, model)
59 print('Erin voice profile saved.', flush=True)
60
61
62def synthesize(text, profile='Erin', seed=42, output=None, sample_rate=24000):
63 import numpy as np
64 import soundfile as sf
65 import torch
66 from chatterbox.tts_turbo import Conditionals
67 from scipy.signal import resample_poly
68 from math import gcd
69 text = text.strip()
70 if not text:
71 raise ValueError('Enter the words you want Erin to say.')
72 if len(text) > 600:
73 raise ValueError('Use at most 600 characters per generation; short phrases work best.')
74 if profile not in PROFILES:
75 raise ValueError('Unknown Erin profile.')
76 if not condition_path(profile).is_file():
77 raise RuntimeError('Erin setup is incomplete: the voice profile is missing.')
78 with _lock:
79 started = time.perf_counter()
80 model = load_model()
81 random.seed(int(seed))
82 np.random.seed(int(seed) % (2**32))
83 torch.manual_seed(int(seed))
84 model.conds = Conditionals.load(condition_path(profile), map_location='cpu').to('cpu')
85 with torch.inference_mode():
86 result = model.generate(text, temperature=0.7).squeeze().cpu().numpy()
87 rate = model.sr
88 if sample_rate != rate:
89 factor = gcd(rate, sample_rate)
90 result = resample_poly(result, sample_rate//factor, rate//factor)
91 rate = sample_rate
92 peak = float(np.max(np.abs(result)))
93 if peak > 0.98:
94 result *= 0.98 / peak
95 if output is None:
96 output = ROOT / 'generated' / f'Erin_{time.strftime("%Y%m%d_%H%M%S")}_{time.time_ns()%1000000:06d}.wav'
97 output = Path(output).resolve()
98 output.parent.mkdir(parents=True, exist_ok=True)
99 sf.write(output, result, rate, subtype='PCM_16')
100 metadata = dict(voice=profile, text=text, seed=int(seed), model='ResembleAI/chatterbox-nano',
101 sample_rate=rate, seconds=round(len(result)/rate, 3),
102 generation_seconds=round(time.perf_counter()-started, 2),
103 synthetic=True)
104 output.with_suffix('.json').write_text(json.dumps(metadata, indent=2), encoding='utf-8')
105 return str(output), metadata
106
107
108def gui(open_browser=True):
109 print('Starting the Erin interface...', flush=True)
110 # Initialize PyTorch and the model on the main thread before Gradio workers.
111 load_model()
112 import gradio as gr
113 print('Erin will be available at http://127.0.0.1:7861', flush=True)
114 def generate(text, seed, rate):
115 try:
116 path, info = synthesize(text, 'Erin', seed, sample_rate=int(rate))
117 return path, f"Saved {Path(path).name} | {info['seconds']:.1f}s audio | {info['generation_seconds']:.1f}s processing"
118 except Exception as exc:
119 raise gr.Error(str(exc)) from exc
120 with gr.Blocks(title='Erin — Local Voice') as app:
121 gr.Markdown('# Erin\nCreate speech locally using your Erin recordings.')
122 text = gr.Textbox(label='What should Erin say?', lines=4, max_lines=8,
123 value='Good morning, Jason. This is Erin. All systems are online and ready.')
124 with gr.Row():
125 rate = gr.Dropdown(choices=[24000, 22050], value=22050, label='WAV sample rate')
126 seed = gr.Number(value=42, precision=0, minimum=0, maximum=4294967295, label='Variation seed')
127 gr.Markdown('**Erin** combines all 145 original recordings from Unused/Erin and VMU/E-10.\n\nUse a short phrase or a few sentences. Change the seed to try another delivery.')
128 button = gr.Button('Generate speech', variant='primary')
129 audio = gr.Audio(label='Generated Erin speech', type='filepath', format='wav')
130 status = gr.Textbox(label='Saved file', interactive=False)
131 button.click(generate, inputs=[text, seed, rate], outputs=[audio, status], concurrency_limit=1)
132 gr.Markdown('Files are saved in the **generated** folder as mono 16-bit WAV. This is synthetic speech. The model’s built-in watermark is retained.')
133 app.launch(server_name='127.0.0.1', server_port=7861, share=False, inbrowser=open_browser,
134 allowed_paths=[str(ROOT / 'generated')], show_error=True, quiet=True)
135
136
137if __name__ == '__main__':
138 parser = argparse.ArgumentParser(description=__doc__)
139 parser.add_argument('--setup', action='store_true')
140 parser.add_argument('--no-browser', action='store_true')
141 parser.add_argument('--text')
142 parser.add_argument('--profile', choices=list(PROFILES), default='Erin')
143 parser.add_argument('--seed', type=int, default=42)
144 parser.add_argument('--output', type=Path)
145 parser.add_argument('--sample-rate', type=int, choices=[22050, 24000], default=22050)
146 args = parser.parse_args()
147 if args.setup:
148 setup()
149 else:
150 os.environ['HF_HUB_OFFLINE'] = '1'
151 os.environ['TRANSFORMERS_OFFLINE'] = '1'
152 if args.text:
153 path, info = synthesize(args.text, args.profile, args.seed, args.output, args.sample_rate)
154 print(json.dumps(dict(file=path, **info), indent=2), flush=True)
155 else:
156 gui(open_browser=not args.no_browser)
gui(open_browser=True)
Definition erin.py:108
setup()
Definition erin.py:49
synthesize(text, profile='Erin', seed=42, output=None, sample_rate=24000)
Definition erin.py:62
int
Definition erin.py:143
condition_path(profile)
Definition erin.py:45
load_model()
Definition erin.py:33