File size: 20,535 Bytes
90ca2ad |
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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import Audio\n",
"from scipy.io.wavfile import write as write_wav\n",
"\n",
"from bark.api import generate_audio\n",
"from bark.generation import SAMPLE_RATE, preload_models, codec_decode, generate_coarse, generate_fine, generate_text_semantic"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"semantic_path = \"semantic_output/pytorch_model.bin\" # set to None if you don't want to use finetuned semantic\n",
"coarse_path = \"coarse_output/pytorch_model.bin\" # set to None if you don't want to use finetuned coarse\n",
"fine_path = \"fine_output/pytorch_model.bin\" # set to None if you don't want to use finetuned fine\n",
"use_rvc = True # Set to False to use bark without RVC\n",
"rvc_name = 'mi-test'\n",
"rvc_path = f\"Retrieval-based-Voice-Conversion-WebUI/weights/{rvc_name}.pth\"\n",
"index_path = f\"Retrieval-based-Voice-Conversion-WebUI/logs/{rvc_name}/added_IVF256_Flat_nprobe_1_{rvc_name}_v2.index\"\n",
"device=\"cuda:0\"\n",
"is_half=True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"preload_models(\n",
" text_use_gpu=True,\n",
" text_use_small=False,\n",
" text_model_path=semantic_path,\n",
" coarse_use_gpu=True,\n",
" coarse_use_small=False,\n",
" coarse_model_path=coarse_path,\n",
" fine_use_gpu=True,\n",
" fine_use_small=False,\n",
" fine_model_path=fine_path,\n",
" codec_use_gpu=True,\n",
" force_reload=False,\n",
" path=\"models\"\n",
")\n",
"\n",
"if use_rvc:\n",
" from rvc_infer import get_vc, vc_single\n",
" get_vc(rvc_path, device, is_half)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# simple generation\n",
"text_prompt = \"I am Joe Biden... and this is the finetuned semantic, coarse and fine model! A lot better than the original!\"\n",
"filepath = \"output/audio.wav\" # change this to your desired output path\n",
"audio_array = generate_audio(text_prompt, history_prompt=None, text_temp=0.7, waveform_temp=0.7)\n",
"write_wav(filepath, SAMPLE_RATE, audio_array)\n",
"\n",
"if use_rvc:\n",
" index_rate = 0.75\n",
" f0up_key = -6\n",
" filter_radius = 3\n",
" rms_mix_rate = 0.25\n",
" protect = 0.33\n",
" resample_sr = SAMPLE_RATE\n",
" f0method = \"harvest\" #harvest or pm\n",
" try:\n",
" audio_array = vc_single(0,filepath,f0up_key,None,f0method,index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" except:\n",
" audio_array = vc_single(0,filepath,f0up_key,None,'pm',index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" write_wav(filepath, SAMPLE_RATE, audio_array)\n",
"\n",
"Audio(audio_array, rate=SAMPLE_RATE)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def generate_with_settings(text_prompt, semantic_temp=0.7, semantic_top_k=50, semantic_top_p=0.95, coarse_temp=0.7, coarse_top_k=50, coarse_top_p=0.95, fine_temp=0.5, voice_name=None, use_semantic_history_prompt=True, use_coarse_history_prompt=True, use_fine_history_prompt=True, output_full=False):\n",
" # generation with more control\n",
" x_semantic = generate_text_semantic(\n",
" text_prompt,\n",
" history_prompt=voice_name if use_semantic_history_prompt else None,\n",
" temp=semantic_temp,\n",
" top_k=semantic_top_k,\n",
" top_p=semantic_top_p,\n",
" )\n",
"\n",
" x_coarse_gen = generate_coarse(\n",
" x_semantic,\n",
" history_prompt=voice_name if use_coarse_history_prompt else None,\n",
" temp=coarse_temp,\n",
" top_k=coarse_top_k,\n",
" top_p=coarse_top_p,\n",
" )\n",
" x_fine_gen = generate_fine(\n",
" x_coarse_gen,\n",
" history_prompt=voice_name if use_fine_history_prompt else None,\n",
" temp=fine_temp,\n",
" )\n",
"\n",
" if output_full:\n",
" full_generation = {\n",
" 'semantic_prompt': x_semantic,\n",
" 'coarse_prompt': x_coarse_gen,\n",
" 'fine_prompt': x_fine_gen,\n",
" }\n",
" return full_generation, codec_decode(x_fine_gen)\n",
" return codec_decode(x_fine_gen)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text_prompt = \"I am Joe Biden... and this is the finetuned semantic, coarse and fine model! A lot better than the original!\"\n",
"filepath = \"output/audio.wav\" # change this to your desired output path\n",
"\n",
"audio_array = generate_with_settings(\n",
" text_prompt,\n",
" semantic_temp=0.7,\n",
" semantic_top_k=50,\n",
" semantic_top_p=0.99,\n",
" coarse_temp=0.7,\n",
" coarse_top_k=50,\n",
" coarse_top_p=0.95,\n",
" fine_temp=0.5,\n",
" voice_name=\"datasets/joe_biden_state_of_union/tokens/257.npz\",\n",
" use_semantic_history_prompt=False,\n",
" use_coarse_history_prompt=True,\n",
" use_fine_history_prompt=True,\n",
" output_full=False\n",
")\n",
"\n",
"write_wav(filepath, SAMPLE_RATE, audio_array)\n",
"\n",
"if use_rvc:\n",
" index_rate = 0.75\n",
" f0up_key = -6\n",
" filter_radius = 3\n",
" rms_mix_rate = 0.25\n",
" protect = 0.33\n",
" resample_sr = SAMPLE_RATE\n",
" f0method = \"harvest\" #harvest or pm\n",
" try:\n",
" audio_array = vc_single(0,filepath,f0up_key,None,f0method,index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" except:\n",
" audio_array = vc_single(0,filepath,f0up_key,None,'pm',index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" write_wav(filepath, SAMPLE_RATE, audio_array)\n",
"\n",
"Audio(audio_array, rate=SAMPLE_RATE)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"def split_and_recombine_text(text, desired_length=100, max_length=150):\n",
" # from https://github.com/neonbjb/tortoise-tts\n",
" \"\"\"Split text it into chunks of a desired length trying to keep sentences intact.\"\"\"\n",
" # normalize text, remove redundant whitespace and convert non-ascii quotes to ascii\n",
" text = re.sub(r\"\\n\\n+\", \"\\n\", text)\n",
" text = re.sub(r\"\\s+\", \" \", text)\n",
" text = re.sub(r\"[“”]\", '\"', text)\n",
"\n",
" rv = []\n",
" in_quote = False\n",
" current = \"\"\n",
" split_pos = []\n",
" pos = -1\n",
" end_pos = len(text) - 1\n",
"\n",
" def seek(delta):\n",
" nonlocal pos, in_quote, current\n",
" is_neg = delta < 0\n",
" for _ in range(abs(delta)):\n",
" if is_neg:\n",
" pos -= 1\n",
" current = current[:-1]\n",
" else:\n",
" pos += 1\n",
" current += text[pos]\n",
" if text[pos] == '\"':\n",
" in_quote = not in_quote\n",
" return text[pos]\n",
"\n",
" def peek(delta):\n",
" p = pos + delta\n",
" return text[p] if p < end_pos and p >= 0 else \"\"\n",
"\n",
" def commit():\n",
" nonlocal rv, current, split_pos\n",
" rv.append(current)\n",
" current = \"\"\n",
" split_pos = []\n",
"\n",
" while pos < end_pos:\n",
" c = seek(1)\n",
" # do we need to force a split?\n",
" if len(current) >= max_length:\n",
" if len(split_pos) > 0 and len(current) > (desired_length / 2):\n",
" # we have at least one sentence and we are over half the desired length, seek back to the last split\n",
" d = pos - split_pos[-1]\n",
" seek(-d)\n",
" else:\n",
" # no full sentences, seek back until we are not in the middle of a word and split there\n",
" while c not in \"!?.\\n \" and pos > 0 and len(current) > desired_length:\n",
" c = seek(-1)\n",
" commit()\n",
" # check for sentence boundaries\n",
" elif not in_quote and (c in \"!?\\n\" or (c == \".\" and peek(1) in \"\\n \")):\n",
" # seek forward if we have consecutive boundary markers but still within the max length\n",
" while (\n",
" pos < len(text) - 1 and len(current) < max_length and peek(1) in \"!?.\"\n",
" ):\n",
" c = seek(1)\n",
" split_pos.append(pos)\n",
" if len(current) >= desired_length:\n",
" commit()\n",
" # treat end of quote as a boundary if its followed by a space or newline\n",
" elif in_quote and peek(1) == '\"' and peek(2) in \"\\n \":\n",
" seek(2)\n",
" split_pos.append(pos)\n",
" rv.append(current)\n",
"\n",
" # clean up, remove lines with only whitespace or punctuation\n",
" rv = [s.strip() for s in rv]\n",
" rv = [s for s in rv if len(s) > 0 and not re.match(r\"^[\\s\\.,;:!?]*$\", s)]\n",
"\n",
" return rv\n",
"\n",
"def generate_with_settings(text_prompt, semantic_temp=0.7, semantic_top_k=50, semantic_top_p=0.95, coarse_temp=0.7, coarse_top_k=50, coarse_top_p=0.95, fine_temp=0.5, voice_name=None, use_semantic_history_prompt=True, use_coarse_history_prompt=True, use_fine_history_prompt=True, output_full=False):\n",
" # generation with more control\n",
" x_semantic = generate_text_semantic(\n",
" text_prompt,\n",
" history_prompt=voice_name if use_semantic_history_prompt else None,\n",
" temp=semantic_temp,\n",
" top_k=semantic_top_k,\n",
" top_p=semantic_top_p,\n",
" )\n",
"\n",
" x_coarse_gen = generate_coarse(\n",
" x_semantic,\n",
" history_prompt=voice_name if use_coarse_history_prompt else None,\n",
" temp=coarse_temp,\n",
" top_k=coarse_top_k,\n",
" top_p=coarse_top_p,\n",
" )\n",
" x_fine_gen = generate_fine(\n",
" x_coarse_gen,\n",
" history_prompt=voice_name if use_fine_history_prompt else None,\n",
" temp=fine_temp,\n",
" )\n",
"\n",
" if output_full:\n",
" full_generation = {\n",
" 'semantic_prompt': x_semantic,\n",
" 'coarse_prompt': x_coarse_gen,\n",
" 'fine_prompt': x_fine_gen,\n",
" }\n",
" return full_generation, codec_decode(x_fine_gen)\n",
" return codec_decode(x_fine_gen)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text = \"\"\"The Uncharted Land of Discovery: A Journey Through Time and Space\n",
"[clears throat]\n",
"Chapter 1: The Dawn of Curiosity\n",
"[takes breath]\n",
"Since the dawn of humankind, our species has been driven by a powerful force: curiosity. It is an innate, unquenchable desire to explore, understand, and unravel the mysteries of the world around us. This primal urge has led us on countless adventures, pushing us to the farthest reaches of our planet and beyond.\n",
"\n",
"Early humans, huddled around a flickering fire, gazed up at the night sky and wondered what those twinkling lights were. They had no idea that their curiosity would eventually propel us into the vast, uncharted realm of space. As time progressed, our ancestors began to explore their surroundings, venturing beyond their caves and settlements, driven by the need to discover what lay beyond the horizon.\n",
"\n",
"hapter 2: The Age of Exploration\n",
"\n",
"The Age of Exploration marked a turning point in human history, as brave souls took to the seas in search of new lands, wealth, and knowledge. Pioneers like Christopher Columbus, Vasco da Gama, and Ferdinand Magellan set sail on perilous voyages, pushing the boundaries of what was known and understood.\n",
"[clears throat]\n",
"These intrepid explorers discovered new continents, mapped out previously unknown territories, and encountered diverse cultures. They also established trade routes, allowing for the exchange of goods, ideas, and innovations between distant societies. The Age of Exploration was not without its dark moments, however, as conquest, colonization, and exploitation often went hand in hand with discovery.\n",
"[clears throat]\n",
"Chapter 3: The Scientific Revolution\n",
"[laughs]\n",
"The Scientific Revolution was a period of profound change, as humanity began to question long-held beliefs and seek empirical evidence. Pioneers like Galileo Galilei, Isaac Newton, and Johannes Kepler sought to understand the natural world through observation, experimentation, and reason.\n",
"[sighs]\n",
"Their discoveries laid the foundation for modern science, transforming the way we view the universe and our place within it. New technologies, such as the telescope and the microscope, allowed us to peer deeper into the cosmos and the microscopic world, further expanding our understanding of reality.\n",
"[gasps]\n",
"Chapter 4: The Information Age\n",
"\n",
"The Information Age, sometimes referred to as the Digital Age, has revolutionized the way we communicate, learn, and access knowledge. With the advent of the internet and personal computers, information that was once reserved for the privileged few is now available to the masses.\n",
"...\n",
"This democratization of knowledge has led to an explosion of innovation, as ideas and information are shared across borders and cultures at lightning speed. The Information Age has also brought new challenges, as the rapid pace of technological advancements threatens to outpace our ability to adapt and raises questions about the ethical implications of our increasingly interconnected world.\n",
"[laughter]\n",
"Chapter 5: The Final Frontier\n",
"[clears throat]\n",
"As our knowledge of the universe expands, so too does our desire to explore the cosmos. Space exploration has come a long way since the first successful satellite, Sputnik, was launched in 1957. We have landed humans on the moon, sent probes to the far reaches of our solar system, and even glimpsed distant galaxies through powerful telescopes.\n",
"\n",
"The future of space exploration is filled with possibilities, from establishing colonies on Mars to the search for extraterrestrial life. As we venture further into the unknown, we continue to be driven by the same curiosity that has propelled us throughout history, always seeking to uncover the secrets of the universe and our place within it.\n",
"...\n",
"In conclusion, the human journey is one of discovery, driven by our innate curiosity and desire to understand the world around us. From the dawn of our species to the present day, we have continued to explore, learn, and adapt, pushing the boundaries of what is known and possible. As we continue to unravel the mysteries of the cosmos, our spirit.\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Chunk the text into smaller pieces then combine the generated audio\n",
"from time import time\n",
"from tqdm.auto import tqdm\n",
"from IPython.display import Audio\n",
"from scipy.io.wavfile import write as write_wav\n",
"import os\n",
"import numpy as np\n",
"\n",
"# generation settings\n",
"voice_name = \"datasets/joe_biden_state_of_union/tokens/257.npz\"\n",
"out_filepath = 'audio/audio.wav'\n",
"\n",
"semantic_temp = 0.7\n",
"semantic_top_k = 100\n",
"semantic_top_p = 0.99\n",
"\n",
"coarse_temp = 0.7\n",
"coarse_top_k = 100\n",
"coarse_top_p = 0.95\n",
"\n",
"fine_temp = 0.7\n",
"\n",
"use_semantic_history_prompt = True\n",
"use_coarse_history_prompt = True\n",
"use_fine_history_prompt = True\n",
"\n",
"use_last_generation_as_history = False\n",
"\n",
"if use_rvc:\n",
" index_rate = 0.75\n",
" f0up_key = -6\n",
" filter_radius = 3\n",
" rms_mix_rate = 0.25\n",
" protect = 0.33\n",
" resample_sr = SAMPLE_RATE\n",
" f0method = \"harvest\" #harvest or pm\n",
"\n",
"texts = split_and_recombine_text(text)\n",
"\n",
"all_parts = []\n",
"for i, text in tqdm(enumerate(texts), total=len(texts)):\n",
" full_generation, audio_array = generate_with_settings(\n",
" text,\n",
" semantic_temp=semantic_temp,\n",
" semantic_top_k=semantic_top_k,\n",
" semantic_top_p=semantic_top_p,\n",
" coarse_temp=coarse_temp,\n",
" coarse_top_k=coarse_top_k,\n",
" coarse_top_p=coarse_top_p,\n",
" fine_temp=fine_temp,\n",
" voice_name=voice_name,\n",
" use_semantic_history_prompt=use_semantic_history_prompt,\n",
" use_coarse_history_prompt=use_coarse_history_prompt,\n",
" use_fine_history_prompt=use_fine_history_prompt,\n",
" output_full=True\n",
" )\n",
" if use_last_generation_as_history:\n",
" # save to npz\n",
" os.makedirs('_temp', exist_ok=True)\n",
" np.savez_compressed(\n",
" '_temp/history.npz',\n",
" semantic_prompt=full_generation['semantic_prompt'],\n",
" coarse_prompt=full_generation['coarse_prompt'],\n",
" fine_prompt=full_generation['fine_prompt'],\n",
" )\n",
" voice_name = '_temp/history.npz'\n",
" write_wav(out_filepath.replace('.wav', f'_{i}') + '.wav', SAMPLE_RATE, audio_array)\n",
"\n",
" if use_rvc:\n",
" try:\n",
" audio_array = vc_single(0,out_filepath.replace('.wav', f'_{i}') + '.wav',f0up_key,None,f0method,index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" except:\n",
" audio_array = vc_single(0,out_filepath.replace('.wav', f'_{i}') + '.wav',f0up_key,None,'pm',index_path,index_rate, filter_radius=filter_radius, resample_sr=resample_sr, rms_mix_rate=rms_mix_rate, protect=protect)\n",
" write_wav(out_filepath.replace('.wav', f'_{i}') + '.wav', SAMPLE_RATE, audio_array)\n",
" all_parts.append(audio_array)\n",
"\n",
"audio_array = np.concatenate(all_parts, axis=-1)\n",
"\n",
"# save audio\n",
"write_wav(out_filepath, SAMPLE_RATE, audio_array)\n",
"\n",
"# play audio\n",
"Audio(audio_array, rate=SAMPLE_RATE)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
|