Spaces:
Runtime error
Runtime error
Update speech_edit.py
Browse files- speech_edit.py +255 -181
speech_edit.py
CHANGED
@@ -1,183 +1,257 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import torch
|
4 |
-
|
5 |
-
import
|
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 |
-
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# coding: utfβ8
|
3 |
+
"""
|
4 |
+
CosyVoice gRPC backβend β updated to mirror the FastAPI logic
|
5 |
+
* loads CosyVoice2 with TRT / FP16 first (falls back to CosyVoice)
|
6 |
+
* inference_zero_shot β adds stream=False + speed
|
7 |
+
* inference_instruct β keeps original βspeakerβIDβ path
|
8 |
+
* inference_instruct2 β new: promptβaudio + speed (no speakerβID)
|
9 |
+
"""
|
10 |
+
|
11 |
+
import io, os, tempfile, requests, soundfile as sf, torchaudio
|
12 |
+
import sys
|
13 |
+
from concurrent import futures
|
14 |
+
import argparse
|
15 |
+
import logging
|
16 |
+
import grpc
|
17 |
+
import numpy as np
|
18 |
import torch
|
19 |
+
|
20 |
+
import cosyvoice_pb2
|
21 |
+
import cosyvoice_pb2_grpc
|
22 |
+
|
23 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
24 |
+
# setβup
|
25 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
26 |
+
logging.getLogger("matplotlib").setLevel(logging.WARNING)
|
27 |
+
logging.basicConfig(level=logging.INFO,
|
28 |
+
format="%(asctime)s %(levelname)s %(message)s")
|
29 |
+
|
30 |
+
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
|
31 |
+
sys.path.extend([
|
32 |
+
f"{ROOT_DIR}/../../..",
|
33 |
+
f"{ROOT_DIR}/../../../third_party/Matcha-TTS",
|
34 |
+
])
|
35 |
+
|
36 |
+
from cosyvoice.cli.cosyvoice import CosyVoice2 # noqa: E402
|
37 |
+
|
38 |
+
|
39 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
40 |
+
# helpers
|
41 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
42 |
+
def _bytes_to_tensor(wav_bytes: bytes) -> torch.Tensor:
|
43 |
+
"""
|
44 |
+
Convert int16 littleβendian PCM bytes β torch.FloatTensor in range [β1,1]
|
45 |
+
"""
|
46 |
+
speech = torch.from_numpy(
|
47 |
+
np.frombuffer(wav_bytes, dtype=np.int16)
|
48 |
+
).unsqueeze(0).float() / (2 ** 15)
|
49 |
+
return speech # [1,β―T]
|
50 |
+
|
51 |
+
|
52 |
+
def _yield_audio(model_output):
|
53 |
+
"""
|
54 |
+
Generator that converts CosyVoice output β protobuf Response messages.
|
55 |
+
"""
|
56 |
+
for seg in model_output:
|
57 |
+
pcm16 = (seg["tts_speech"].numpy() * (2 ** 15)).astype(np.int16)
|
58 |
+
resp = cosyvoice_pb2.Response(tts_audio=pcm16.tobytes())
|
59 |
+
yield resp
|
60 |
+
|
61 |
+
|
62 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
63 |
+
# gRPC service
|
64 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
65 |
+
class CosyVoiceServiceImpl(cosyvoice_pb2_grpc.CosyVoiceServicer):
|
66 |
+
def __init__(self, args):
|
67 |
+
# try CosyVoice2 first (preferred runtime: TRT / FP16)
|
68 |
+
try:
|
69 |
+
self.cosyvoice = CosyVoice2(args.model_dir,
|
70 |
+
load_jit=False,
|
71 |
+
load_trt=True,
|
72 |
+
fp16=True)
|
73 |
+
logging.info("Loaded CosyVoice2 (TRT / FP16).")
|
74 |
+
except Exception:
|
75 |
+
raise TypeError("No valid CosyVoice model found!")
|
76 |
+
|
77 |
+
# ---------------------------------------------------------------------
|
78 |
+
# single biβdi streaming RPC
|
79 |
+
# ---------------------------------------------------------------------
|
80 |
+
def Inference(self, request, context):
|
81 |
+
"""Route to the correct model call based on the oneof field present."""
|
82 |
+
# 1. Supervised fineβtuning
|
83 |
+
if request.HasField("sft_request"):
|
84 |
+
logging.info("Received SFT inference request")
|
85 |
+
mo = self.cosyvoice.inference_sft(
|
86 |
+
request.sft_request.tts_text,
|
87 |
+
request.sft_request.spk_id
|
88 |
+
)
|
89 |
+
yield from _yield_audio(mo)
|
90 |
+
return
|
91 |
+
|
92 |
+
# 2. Zeroβshot speaker cloning (bytes OR S3 URL)
|
93 |
+
if request.HasField("zero_shot_request"):
|
94 |
+
logging.info("Received zeroβshot inference request")
|
95 |
+
zr = request.zero_shot_request
|
96 |
+
tmp_path = None # initialise so we can delete later
|
97 |
+
|
98 |
+
try:
|
99 |
+
# βββββ determine payload type ββββββββββββββββββββββββββββββββββββββ
|
100 |
+
if zr.prompt_audio.startswith(b'http'):
|
101 |
+
# ββ remote URL ββ ---------------------------------------------
|
102 |
+
url = zr.prompt_audio.decode('utfβ8')
|
103 |
+
logging.info("Downloading prompt audio from %s", url)
|
104 |
+
resp = requests.get(url, timeout=10)
|
105 |
+
resp.raise_for_status()
|
106 |
+
|
107 |
+
# save to a temp file
|
108 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
109 |
+
f.write(resp.content)
|
110 |
+
tmp_path = f.name
|
111 |
+
|
112 |
+
# load, monoβise, resample β tensor [1,β―T]
|
113 |
+
wav, sr = sf.read(tmp_path, dtype="float32")
|
114 |
+
if wav.ndim > 1:
|
115 |
+
wav = wav.mean(axis=1)
|
116 |
+
if sr != 16_000:
|
117 |
+
wav = torchaudio.functional.resample(
|
118 |
+
torch.from_numpy(wav).unsqueeze(0), sr, 16_000
|
119 |
+
)[0].numpy()
|
120 |
+
prompt = torch.from_numpy(wav).unsqueeze(0)
|
121 |
+
|
122 |
+
else:
|
123 |
+
# ββ legacy raw PCM bytes ββ -----------------------------------
|
124 |
+
prompt = _bytes_to_tensor(zr.prompt_audio)
|
125 |
+
|
126 |
+
# βββββ call the model ββββββββββββββββββββββββββββββββββββββββββββββ
|
127 |
+
speed = getattr(zr, "speed", 1.0)
|
128 |
+
mo = self.cosyvoice.inference_zero_shot(
|
129 |
+
zr.tts_text,
|
130 |
+
zr.prompt_text,
|
131 |
+
prompt,
|
132 |
+
stream=False,
|
133 |
+
speed=speed,
|
134 |
+
)
|
135 |
+
|
136 |
+
finally:
|
137 |
+
# clean up any temporary file we created
|
138 |
+
if tmp_path and os.path.exists(tmp_path):
|
139 |
+
try:
|
140 |
+
os.remove(tmp_path)
|
141 |
+
except Exception as e:
|
142 |
+
logging.warning("Could not remove temp file %s: %s", tmp_path, e)
|
143 |
+
|
144 |
+
yield from _yield_audio(mo)
|
145 |
+
return
|
146 |
+
|
147 |
+
# 3. Crossβlingual
|
148 |
+
if request.HasField("cross_lingual_request"):
|
149 |
+
logging.info("Received crossβlingual inference request")
|
150 |
+
cr = request.cross_lingual_request
|
151 |
+
prompt = _bytes_to_tensor(cr.prompt_audio)
|
152 |
+
mo = self.cosyvoice.inference_cross_lingual(
|
153 |
+
cr.tts_text,
|
154 |
+
prompt
|
155 |
+
)
|
156 |
+
yield from _yield_audio(mo)
|
157 |
+
return
|
158 |
+
|
159 |
+
# 4. InstructionβTTS (two flavours)
|
160 |
+
if request.HasField("instruct_request"):
|
161 |
+
ir = request.instruct_request
|
162 |
+
|
163 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
164 |
+
# 4βa) instructβ2 (has prompt_audio β bytes OR S3 URL)
|
165 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
166 |
+
if ir.HasField("prompt_audio"):
|
167 |
+
logging.info("Received instructβ2 inference request")
|
168 |
+
|
169 |
+
tmp_path = None
|
170 |
+
try:
|
171 |
+
if ir.prompt_audio.startswith(b'http'):
|
172 |
+
# treat as URL, download then load
|
173 |
+
url = ir.prompt_audio.decode('utfβ8')
|
174 |
+
logging.info("Downloading prompt audio from %s", url)
|
175 |
+
resp = requests.get(url, timeout=10)
|
176 |
+
resp.raise_for_status()
|
177 |
+
|
178 |
+
with tempfile.NamedTemporaryFile(delete=False,
|
179 |
+
suffix=".wav") as f:
|
180 |
+
f.write(resp.content)
|
181 |
+
tmp_path = f.name
|
182 |
+
|
183 |
+
wav, sr = sf.read(tmp_path, dtype='float32')
|
184 |
+
if wav.ndim > 1:
|
185 |
+
wav = wav.mean(axis=1)
|
186 |
+
if sr != 16_000:
|
187 |
+
wav = torchaudio.functional.resample(
|
188 |
+
torch.from_numpy(wav).unsqueeze(0), sr, 16_000
|
189 |
+
)[0].numpy()
|
190 |
+
prompt = torch.from_numpy(wav).unsqueeze(0)
|
191 |
+
|
192 |
+
else:
|
193 |
+
# legacy rawβbytes payload
|
194 |
+
prompt = _bytes_to_tensor(ir.prompt_audio)
|
195 |
+
|
196 |
+
speed = getattr(ir, "speed", 1.0)
|
197 |
+
mo = self.cosyvoice.inference_instruct2(
|
198 |
+
ir.tts_text,
|
199 |
+
ir.instruct_text,
|
200 |
+
prompt,
|
201 |
+
stream=False,
|
202 |
+
speed=speed
|
203 |
+
)
|
204 |
+
|
205 |
+
finally:
|
206 |
+
if tmp_path and os.path.exists(tmp_path):
|
207 |
+
try:
|
208 |
+
os.remove(tmp_path)
|
209 |
+
except Exception as e:
|
210 |
+
logging.warning("Could not remove temp file %s: %s",
|
211 |
+
tmp_path, e)
|
212 |
+
|
213 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
214 |
+
# 4βb) classic instruct (speakerβID, no prompt audio)
|
215 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
216 |
+
else:
|
217 |
+
logging.info("Received instruct inference request")
|
218 |
+
mo = self.cosyvoice.inference_instruct(
|
219 |
+
ir.tts_text,
|
220 |
+
ir.spk_id,
|
221 |
+
ir.instruct_text
|
222 |
+
)
|
223 |
+
|
224 |
+
yield from _yield_audio(mo)
|
225 |
+
return
|
226 |
+
|
227 |
+
# unknown request type
|
228 |
+
context.abort(grpc.StatusCode.INVALID_ARGUMENT,
|
229 |
+
"Unsupported request type in oneof field.")
|
230 |
+
|
231 |
+
|
232 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
233 |
+
# entryβpoint
|
234 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
235 |
+
def serve(args):
|
236 |
+
server = grpc.server(
|
237 |
+
futures.ThreadPoolExecutor(max_workers=args.max_conc),
|
238 |
+
maximum_concurrent_rpcs=args.max_conc
|
239 |
+
)
|
240 |
+
cosyvoice_pb2_grpc.add_CosyVoiceServicer_to_server(
|
241 |
+
CosyVoiceServiceImpl(args), server
|
242 |
)
|
243 |
+
server.add_insecure_port(f"0.0.0.0:{args.port}")
|
244 |
+
server.start()
|
245 |
+
logging.info("CosyVoice gRPC server listening on 0.0.0.0:%d", args.port)
|
246 |
+
server.wait_for_termination()
|
247 |
+
|
248 |
+
|
249 |
+
if __name__ == "__main__":
|
250 |
+
parser = argparse.ArgumentParser()
|
251 |
+
parser.add_argument("--port", type=int, default=8000)
|
252 |
+
parser.add_argument("--max_conc", type=int, default=4,
|
253 |
+
help="maximum concurrent requests / threads")
|
254 |
+
parser.add_argument("--model_dir", type=str,
|
255 |
+
default="pretrained_models/CosyVoice2-0.5B",
|
256 |
+
help="local path or ModelScope repo id")
|
257 |
+
serve(parser.parse_args())
|