Spaces:
Running
on
A10G
Running
on
A10G
File size: 7,220 Bytes
b2eb230 |
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 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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
import argparse
import base64
import wave
import ormsgpack
import pyaudio
import requests
from pydub import AudioSegment
from pydub.playback import play
from tools.file import audio_to_bytes, read_ref_text
from tools.schema import ServeReferenceAudio, ServeTTSRequest
def parse_args():
parser = argparse.ArgumentParser(
description="Send a WAV file and text to a server and receive synthesized audio.",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--url",
"-u",
type=str,
default="http://127.0.0.1:8080/v1/tts",
help="URL of the server",
)
parser.add_argument(
"--text", "-t", type=str, required=True, help="Text to be synthesized"
)
parser.add_argument(
"--reference_id",
"-id",
type=str,
default=None,
help="ID of the reference model to be used for the speech\n(Local: name of folder containing audios and files)",
)
parser.add_argument(
"--reference_audio",
"-ra",
type=str,
nargs="+",
default=None,
help="Path to the audio file",
)
parser.add_argument(
"--reference_text",
"-rt",
type=str,
nargs="+",
default=None,
help="Reference text for voice synthesis",
)
parser.add_argument(
"--output",
"-o",
type=str,
default="generated_audio",
help="Output audio file name",
)
parser.add_argument(
"--play",
type=bool,
default=True,
help="Whether to play audio after receiving data",
)
parser.add_argument("--normalize", type=bool, default=True)
parser.add_argument(
"--format", type=str, choices=["wav", "mp3", "flac"], default="wav"
)
parser.add_argument(
"--mp3_bitrate", type=int, choices=[64, 128, 192], default=64, help="kHz"
)
parser.add_argument("--opus_bitrate", type=int, default=-1000)
parser.add_argument(
"--latency",
type=str,
default="normal",
choices=["normal", "balanced"],
help="Used in api.fish.audio/v1/tts",
)
parser.add_argument(
"--max_new_tokens",
type=int,
default=0,
help="Maximum new tokens to generate. \n0 means no limit.",
)
parser.add_argument(
"--chunk_length", type=int, default=200, help="Chunk length for synthesis"
)
parser.add_argument(
"--top_p", type=float, default=0.7, help="Top-p sampling for synthesis"
)
parser.add_argument(
"--repetition_penalty",
type=float,
default=1.2,
help="Repetition penalty for synthesis",
)
parser.add_argument(
"--temperature", type=float, default=0.7, help="Temperature for sampling"
)
parser.add_argument(
"--streaming", type=bool, default=False, help="Enable streaming response"
)
parser.add_argument(
"--channels", type=int, default=1, help="Number of audio channels"
)
parser.add_argument("--rate", type=int, default=44100, help="Sample rate for audio")
parser.add_argument(
"--use_memory_cache",
type=str,
default="never",
choices=["on-demand", "never"],
help="Cache encoded references codes in memory.\n"
"If `on-demand`, the server will use cached encodings\n "
"instead of encoding reference audio again.",
)
parser.add_argument(
"--seed",
type=int,
default=None,
help="`None` means randomized inference, otherwise deterministic.\n"
"It can't be used for fixing a timbre.",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
idstr: str | None = args.reference_id
# priority: ref_id > [{text, audio},...]
if idstr is None:
ref_audios = args.reference_audio
ref_texts = args.reference_text
if ref_audios is None:
byte_audios = []
else:
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in ref_audios]
if ref_texts is None:
ref_texts = []
else:
ref_texts = [read_ref_text(ref_text) for ref_text in ref_texts]
else:
byte_audios = []
ref_texts = []
pass # in api.py
data = {
"text": args.text,
"references": [
ServeReferenceAudio(audio=ref_audio, text=ref_text)
for ref_text, ref_audio in zip(ref_texts, byte_audios)
],
"reference_id": idstr,
"normalize": args.normalize,
"format": args.format,
"mp3_bitrate": args.mp3_bitrate,
"opus_bitrate": args.opus_bitrate,
"max_new_tokens": args.max_new_tokens,
"chunk_length": args.chunk_length,
"top_p": args.top_p,
"repetition_penalty": args.repetition_penalty,
"temperature": args.temperature,
"streaming": args.streaming,
"use_memory_cache": args.use_memory_cache,
"seed": args.seed,
}
pydantic_data = ServeTTSRequest(**data)
response = requests.post(
args.url,
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
stream=args.streaming,
headers={
"authorization": "Bearer YOUR_API_KEY",
"content-type": "application/msgpack",
},
)
if response.status_code == 200:
if args.streaming:
p = pyaudio.PyAudio()
audio_format = pyaudio.paInt16 # Assuming 16-bit PCM format
stream = p.open(
format=audio_format, channels=args.channels, rate=args.rate, output=True
)
wf = wave.open(f"{args.output}.wav", "wb")
wf.setnchannels(args.channels)
wf.setsampwidth(p.get_sample_size(audio_format))
wf.setframerate(args.rate)
stream_stopped_flag = False
try:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
stream.write(chunk)
wf.writeframesraw(chunk)
else:
if not stream_stopped_flag:
stream.stop_stream()
stream_stopped_flag = True
finally:
stream.close()
p.terminate()
wf.close()
else:
audio_content = response.content
audio_path = f"{args.output}.{args.format}"
with open(audio_path, "wb") as audio_file:
audio_file.write(audio_content)
audio = AudioSegment.from_file(audio_path, format=args.format)
if args.play:
play(audio)
print(f"Audio has been saved to '{audio_path}'.")
else:
print(f"Request failed with status code {response.status_code}")
print(response.json())
|