{
 "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.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": [
    "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": [
    "# `[laughter]`\n",
    "# - `[laughs]`\n",
    "# - `[sighs]`\n",
    "# - `[music]`\n",
    "# - `[gasps]`\n",
    "# - `[clears throat]`\n",
    "# - `—` or `...` for hesitations\n",
    "# - `♪` for song lyrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download and load all models\n",
    "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": [
    "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 = 'en_speaker_0'\n",
    "out_filepath = 'audio/audio.wav'\n",
    "\n",
    "semantic_temp = 0.7\n",
    "semantic_top_k = 50\n",
    "semantic_top_p = 0.95\n",
    "\n",
    "coarse_temp = 0.7\n",
    "coarse_top_k = 50\n",
    "coarse_top_p = 0.95\n",
    "\n",
    "fine_temp = 0.5\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 = True\n",
    "\n",
    "if use_rvc:\n",
    "    index_rate = 0.75\n",
    "    f0up_key = -10\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)"
   ]
  }
 ],
 "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
}
