返回 F5-TTS
socket_server.py
根目录 / src / f5_tts / socket_server.py
1 import argparse
2 import gc
3 import logging
4 import queue
5 import socket
6 import struct
7 import threading
8 import traceback
9 import wave
10 from importlib.resources import files
11
12 import numpy as np
13 import torch
14 import torchaudio
15 from huggingface_hub import hf_hub_download
16 from hydra.utils import get_class
17 from omegaconf import OmegaConf
18
19 from f5_tts.device_utils import get_default_device
20 from f5_tts.infer.utils_infer import (
21 chunk_text,
22 infer_batch_process,
23 load_model,
24 load_vocoder,
25 preprocess_ref_audio_text,
26 )
27
28
29 logging.basicConfig(level=logging.INFO)
30 logger = logging.getLogger(__name__)
31
32
33 class AudioFileWriterThread(threading.Thread):
34 """Threaded file writer to avoid blocking the TTS streaming process."""
35
36 def __init__(self, output_file, sampling_rate):
37 super().__init__()
38 self.output_file = output_file
39 self.sampling_rate = sampling_rate
40 self.queue = queue.Queue()
41 self.stop_event = threading.Event()
42 self.audio_data = []
43
44 def run(self):
45 """Process queued audio data and write it to a file."""
46 logger.info("AudioFileWriterThread started.")
47 with wave.open(self.output_file, "wb") as wf:
48 wf.setnchannels(1)
49 wf.setsampwidth(2)
50 wf.setframerate(self.sampling_rate)
51
52 while not self.stop_event.is_set() or not self.queue.empty():
53 try:
54 chunk = self.queue.get(timeout=0.1)
55 if chunk is not None:
56 chunk = np.int16(chunk * 32767)
57 self.audio_data.append(chunk)
58 wf.writeframes(chunk.tobytes())
59 except queue.Empty:
60 continue
61
62 def add_chunk(self, chunk):
63 """Add a new chunk to the queue."""
64 self.queue.put(chunk)
65
66 def stop(self):
67 """Stop writing and ensure all queued data is written."""
68 self.stop_event.set()
69 self.join()
70 logger.info("Audio writing completed.")
71
72
73 class TTSStreamingProcessor:
74 def __init__(self, model, ckpt_file, vocab_file, ref_audio, ref_text, device=None, dtype=torch.float32):
75 self.device = device or get_default_device()
76 model_cfg = OmegaConf.load(str(files("f5_tts").joinpath(f"configs/{model}.yaml")))
77 self.model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
78 self.model_arc = model_cfg.model.arch
79 self.mel_spec_type = model_cfg.model.mel_spec.mel_spec_type
80 self.sampling_rate = model_cfg.model.mel_spec.target_sample_rate
81
82 self.model = self.load_ema_model(ckpt_file, vocab_file, dtype)
83 self.vocoder = self.load_vocoder_model()
84
85 self.update_reference(ref_audio, ref_text)
86 self._warm_up()
87 self.file_writer_thread = None
88 self.first_package = True
89
90 def load_ema_model(self, ckpt_file, vocab_file, dtype):
91 return load_model(
92 self.model_cls,
93 self.model_arc,
94 ckpt_path=ckpt_file,
95 mel_spec_type=self.mel_spec_type,
96 vocab_file=vocab_file,
97 ode_method="euler",
98 use_ema=True,
99 device=self.device,
100 ).to(self.device, dtype=dtype)
101
102 def load_vocoder_model(self):
103 return load_vocoder(vocoder_name=self.mel_spec_type, is_local=False, local_path=None, device=self.device)
104
105 def update_reference(self, ref_audio, ref_text):
106 self.ref_audio, self.ref_text = preprocess_ref_audio_text(ref_audio, ref_text)
107 self.audio, self.sr = torchaudio.load(self.ref_audio)
108
109 ref_audio_duration = self.audio.shape[-1] / self.sr
110 ref_text_byte_len = len(self.ref_text.encode("utf-8"))
111 self.max_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration))
112 self.few_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration) / 2)
113 self.min_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration) / 4)
114
115 def _warm_up(self):
116 logger.info("Warming up the model...")
117 gen_text = "Warm-up text for the model."
118 for _ in infer_batch_process(
119 (self.audio, self.sr),
120 self.ref_text,
121 [gen_text],
122 self.model,
123 self.vocoder,
124 progress=None,
125 device=self.device,
126 streaming=True,
127 ):
128 pass
129 logger.info("Warm-up completed.")
130
131 def generate_stream(self, text, conn):
132 text_batches = chunk_text(text, max_chars=self.max_chars)
133 if self.first_package:
134 text_batches = chunk_text(text_batches[0], max_chars=self.few_chars) + text_batches[1:]
135 text_batches = chunk_text(text_batches[0], max_chars=self.min_chars) + text_batches[1:]
136 self.first_package = False
137
138 audio_stream = infer_batch_process(
139 (self.audio, self.sr),
140 self.ref_text,
141 text_batches,
142 self.model,
143 self.vocoder,
144 progress=None,
145 device=self.device,
146 streaming=True,
147 chunk_size=2048,
148 )
149
150 # Reset the file writer thread
151 if self.file_writer_thread is not None:
152 self.file_writer_thread.stop()
153 self.file_writer_thread = AudioFileWriterThread("output.wav", self.sampling_rate)
154 self.file_writer_thread.start()
155
156 for audio_chunk, _ in audio_stream:
157 if len(audio_chunk) > 0:
158 logger.info(f"Generated audio chunk of size: {len(audio_chunk)}")
159
160 # Send audio chunk via socket
161 conn.sendall(struct.pack(f"{len(audio_chunk)}f", *audio_chunk))
162
163 # Write to file asynchronously
164 self.file_writer_thread.add_chunk(audio_chunk)
165
166 logger.info("Finished sending audio stream.")
167 conn.sendall(b"END") # Send end signal
168
169 # Ensure all audio data is written before exiting
170 self.file_writer_thread.stop()
171
172
173 def handle_client(conn, processor):
174 try:
175 with conn:
176 conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
177 while True:
178 data = conn.recv(1024)
179 if not data:
180 processor.first_package = True
181 break
182 data_str = data.decode("utf-8").strip()
183 logger.info(f"Received text: {data_str}")
184
185 try:
186 processor.generate_stream(data_str, conn)
187 except Exception as inner_e:
188 logger.error(f"Error during processing: {inner_e}")
189 traceback.print_exc()
190 break
191 except Exception as e:
192 logger.error(f"Error handling client: {e}")
193 traceback.print_exc()
194
195
196 def start_server(host, port, processor):
197 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
198 s.bind((host, port))
199 s.listen()
200 logger.info(f"Server started on {host}:{port}")
201 while True:
202 conn, addr = s.accept()
203 logger.info(f"Connected by {addr}")
204 handle_client(conn, processor)
205
206
207 if __name__ == "__main__":
208 parser = argparse.ArgumentParser()
209
210 parser.add_argument("--host", default="0.0.0.0")
211 parser.add_argument("--port", default=9998)
212
213 parser.add_argument(
214 "--model",
215 default="F5TTS_v1_Base",
216 help="The model name, e.g. F5TTS_v1_Base",
217 )
218 parser.add_argument(
219 "--ckpt_file",
220 default=str(hf_hub_download(repo_id="SWivid/F5-TTS", filename="F5TTS_v1_Base/model_1250000.safetensors")),
221 help="Path to the model checkpoint file",
222 )
223 parser.add_argument(
224 "--vocab_file",
225 default="",
226 help="Path to the vocab file if customized",
227 )
228
229 parser.add_argument(
230 "--ref_audio",
231 default=str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav")),
232 help="Reference audio to provide model with speaker characteristics",
233 )
234 parser.add_argument(
235 "--ref_text",
236 default="",
237 help="Reference audio subtitle, leave empty to auto-transcribe",
238 )
239
240 parser.add_argument("--device", default=None, help="Device to run the model on")
241 parser.add_argument("--dtype", default=torch.float32, help="Data type to use for model inference")
242
243 args = parser.parse_args()
244
245 try:
246 # Initialize the processor with the model and vocoder
247 processor = TTSStreamingProcessor(
248 model=args.model,
249 ckpt_file=args.ckpt_file,
250 vocab_file=args.vocab_file,
251 ref_audio=args.ref_audio,
252 ref_text=args.ref_text,
253 device=args.device,
254 dtype=args.dtype,
255 )
256
257 # Start the server
258 start_server(args.host, args.port, processor)
259
260 except KeyboardInterrupt:
261 gc.collect()
262
262 lines PYTHON