Full Code of suno-ai/bark for AI

main f4f32d4cd480 cached
289 files
131.3 KB
54.8k tokens
59 symbols
1 requests
Download .txt
Repository: suno-ai/bark
Branch: main
Commit: f4f32d4cd480
Files: 289
Total size: 131.3 KB

Directory structure:
gitextract_qrs7w3px/

├── .gitignore
├── LICENSE
├── README.md
├── bark/
│   ├── __init__.py
│   ├── __main__.py
│   ├── api.py
│   ├── assets/
│   │   └── prompts/
│   │       ├── announcer.npz
│   │       ├── de_speaker_0.npz
│   │       ├── de_speaker_1.npz
│   │       ├── de_speaker_2.npz
│   │       ├── de_speaker_3.npz
│   │       ├── de_speaker_4.npz
│   │       ├── de_speaker_5.npz
│   │       ├── de_speaker_6.npz
│   │       ├── de_speaker_7.npz
│   │       ├── de_speaker_8.npz
│   │       ├── de_speaker_9.npz
│   │       ├── en_speaker_0.npz
│   │       ├── en_speaker_1.npz
│   │       ├── en_speaker_2.npz
│   │       ├── en_speaker_3.npz
│   │       ├── en_speaker_4.npz
│   │       ├── en_speaker_5.npz
│   │       ├── en_speaker_6.npz
│   │       ├── en_speaker_7.npz
│   │       ├── en_speaker_8.npz
│   │       ├── en_speaker_9.npz
│   │       ├── es_speaker_0.npz
│   │       ├── es_speaker_1.npz
│   │       ├── es_speaker_2.npz
│   │       ├── es_speaker_3.npz
│   │       ├── es_speaker_4.npz
│   │       ├── es_speaker_5.npz
│   │       ├── es_speaker_6.npz
│   │       ├── es_speaker_7.npz
│   │       ├── es_speaker_8.npz
│   │       ├── es_speaker_9.npz
│   │       ├── fr_speaker_0.npz
│   │       ├── fr_speaker_1.npz
│   │       ├── fr_speaker_2.npz
│   │       ├── fr_speaker_3.npz
│   │       ├── fr_speaker_4.npz
│   │       ├── fr_speaker_5.npz
│   │       ├── fr_speaker_6.npz
│   │       ├── fr_speaker_7.npz
│   │       ├── fr_speaker_8.npz
│   │       ├── fr_speaker_9.npz
│   │       ├── hi_speaker_0.npz
│   │       ├── hi_speaker_1.npz
│   │       ├── hi_speaker_2.npz
│   │       ├── hi_speaker_3.npz
│   │       ├── hi_speaker_4.npz
│   │       ├── hi_speaker_5.npz
│   │       ├── hi_speaker_6.npz
│   │       ├── hi_speaker_7.npz
│   │       ├── hi_speaker_8.npz
│   │       ├── hi_speaker_9.npz
│   │       ├── it_speaker_0.npz
│   │       ├── it_speaker_1.npz
│   │       ├── it_speaker_2.npz
│   │       ├── it_speaker_3.npz
│   │       ├── it_speaker_4.npz
│   │       ├── it_speaker_5.npz
│   │       ├── it_speaker_6.npz
│   │       ├── it_speaker_7.npz
│   │       ├── it_speaker_8.npz
│   │       ├── it_speaker_9.npz
│   │       ├── ja_speaker_0.npz
│   │       ├── ja_speaker_1.npz
│   │       ├── ja_speaker_2.npz
│   │       ├── ja_speaker_3.npz
│   │       ├── ja_speaker_4.npz
│   │       ├── ja_speaker_5.npz
│   │       ├── ja_speaker_6.npz
│   │       ├── ja_speaker_7.npz
│   │       ├── ja_speaker_8.npz
│   │       ├── ja_speaker_9.npz
│   │       ├── ko_speaker_0.npz
│   │       ├── ko_speaker_1.npz
│   │       ├── ko_speaker_2.npz
│   │       ├── ko_speaker_3.npz
│   │       ├── ko_speaker_4.npz
│   │       ├── ko_speaker_5.npz
│   │       ├── ko_speaker_6.npz
│   │       ├── ko_speaker_7.npz
│   │       ├── ko_speaker_8.npz
│   │       ├── ko_speaker_9.npz
│   │       ├── pl_speaker_0.npz
│   │       ├── pl_speaker_1.npz
│   │       ├── pl_speaker_2.npz
│   │       ├── pl_speaker_3.npz
│   │       ├── pl_speaker_4.npz
│   │       ├── pl_speaker_5.npz
│   │       ├── pl_speaker_6.npz
│   │       ├── pl_speaker_7.npz
│   │       ├── pl_speaker_8.npz
│   │       ├── pl_speaker_9.npz
│   │       ├── pt_speaker_0.npz
│   │       ├── pt_speaker_1.npz
│   │       ├── pt_speaker_2.npz
│   │       ├── pt_speaker_3.npz
│   │       ├── pt_speaker_4.npz
│   │       ├── pt_speaker_5.npz
│   │       ├── pt_speaker_6.npz
│   │       ├── pt_speaker_7.npz
│   │       ├── pt_speaker_8.npz
│   │       ├── pt_speaker_9.npz
│   │       ├── readme.md
│   │       ├── ru_speaker_0.npz
│   │       ├── ru_speaker_1.npz
│   │       ├── ru_speaker_2.npz
│   │       ├── ru_speaker_3.npz
│   │       ├── ru_speaker_4.npz
│   │       ├── ru_speaker_5.npz
│   │       ├── ru_speaker_6.npz
│   │       ├── ru_speaker_7.npz
│   │       ├── ru_speaker_8.npz
│   │       ├── ru_speaker_9.npz
│   │       ├── speaker_0.npz
│   │       ├── speaker_1.npz
│   │       ├── speaker_2.npz
│   │       ├── speaker_3.npz
│   │       ├── speaker_4.npz
│   │       ├── speaker_5.npz
│   │       ├── speaker_6.npz
│   │       ├── speaker_7.npz
│   │       ├── speaker_8.npz
│   │       ├── speaker_9.npz
│   │       ├── tr_speaker_0.npz
│   │       ├── tr_speaker_1.npz
│   │       ├── tr_speaker_2.npz
│   │       ├── tr_speaker_3.npz
│   │       ├── tr_speaker_4.npz
│   │       ├── tr_speaker_5.npz
│   │       ├── tr_speaker_6.npz
│   │       ├── tr_speaker_7.npz
│   │       ├── tr_speaker_8.npz
│   │       ├── tr_speaker_9.npz
│   │       ├── v2/
│   │       │   ├── de_speaker_0.npz
│   │       │   ├── de_speaker_1.npz
│   │       │   ├── de_speaker_2.npz
│   │       │   ├── de_speaker_3.npz
│   │       │   ├── de_speaker_4.npz
│   │       │   ├── de_speaker_5.npz
│   │       │   ├── de_speaker_6.npz
│   │       │   ├── de_speaker_7.npz
│   │       │   ├── de_speaker_8.npz
│   │       │   ├── de_speaker_9.npz
│   │       │   ├── en_speaker_0.npz
│   │       │   ├── en_speaker_1.npz
│   │       │   ├── en_speaker_2.npz
│   │       │   ├── en_speaker_3.npz
│   │       │   ├── en_speaker_4.npz
│   │       │   ├── en_speaker_5.npz
│   │       │   ├── en_speaker_6.npz
│   │       │   ├── en_speaker_7.npz
│   │       │   ├── en_speaker_8.npz
│   │       │   ├── en_speaker_9.npz
│   │       │   ├── es_speaker_0.npz
│   │       │   ├── es_speaker_1.npz
│   │       │   ├── es_speaker_2.npz
│   │       │   ├── es_speaker_3.npz
│   │       │   ├── es_speaker_4.npz
│   │       │   ├── es_speaker_5.npz
│   │       │   ├── es_speaker_6.npz
│   │       │   ├── es_speaker_7.npz
│   │       │   ├── es_speaker_8.npz
│   │       │   ├── es_speaker_9.npz
│   │       │   ├── fr_speaker_0.npz
│   │       │   ├── fr_speaker_1.npz
│   │       │   ├── fr_speaker_2.npz
│   │       │   ├── fr_speaker_3.npz
│   │       │   ├── fr_speaker_4.npz
│   │       │   ├── fr_speaker_5.npz
│   │       │   ├── fr_speaker_6.npz
│   │       │   ├── fr_speaker_7.npz
│   │       │   ├── fr_speaker_8.npz
│   │       │   ├── fr_speaker_9.npz
│   │       │   ├── hi_speaker_0.npz
│   │       │   ├── hi_speaker_1.npz
│   │       │   ├── hi_speaker_2.npz
│   │       │   ├── hi_speaker_3.npz
│   │       │   ├── hi_speaker_4.npz
│   │       │   ├── hi_speaker_5.npz
│   │       │   ├── hi_speaker_6.npz
│   │       │   ├── hi_speaker_7.npz
│   │       │   ├── hi_speaker_8.npz
│   │       │   ├── hi_speaker_9.npz
│   │       │   ├── it_speaker_0.npz
│   │       │   ├── it_speaker_1.npz
│   │       │   ├── it_speaker_2.npz
│   │       │   ├── it_speaker_3.npz
│   │       │   ├── it_speaker_4.npz
│   │       │   ├── it_speaker_5.npz
│   │       │   ├── it_speaker_6.npz
│   │       │   ├── it_speaker_7.npz
│   │       │   ├── it_speaker_8.npz
│   │       │   ├── it_speaker_9.npz
│   │       │   ├── ja_speaker_0.npz
│   │       │   ├── ja_speaker_1.npz
│   │       │   ├── ja_speaker_2.npz
│   │       │   ├── ja_speaker_3.npz
│   │       │   ├── ja_speaker_4.npz
│   │       │   ├── ja_speaker_5.npz
│   │       │   ├── ja_speaker_6.npz
│   │       │   ├── ja_speaker_7.npz
│   │       │   ├── ja_speaker_8.npz
│   │       │   ├── ja_speaker_9.npz
│   │       │   ├── ko_speaker_0.npz
│   │       │   ├── ko_speaker_1.npz
│   │       │   ├── ko_speaker_2.npz
│   │       │   ├── ko_speaker_3.npz
│   │       │   ├── ko_speaker_4.npz
│   │       │   ├── ko_speaker_5.npz
│   │       │   ├── ko_speaker_6.npz
│   │       │   ├── ko_speaker_7.npz
│   │       │   ├── ko_speaker_8.npz
│   │       │   ├── ko_speaker_9.npz
│   │       │   ├── pl_speaker_0.npz
│   │       │   ├── pl_speaker_1.npz
│   │       │   ├── pl_speaker_2.npz
│   │       │   ├── pl_speaker_3.npz
│   │       │   ├── pl_speaker_4.npz
│   │       │   ├── pl_speaker_5.npz
│   │       │   ├── pl_speaker_6.npz
│   │       │   ├── pl_speaker_7.npz
│   │       │   ├── pl_speaker_8.npz
│   │       │   ├── pl_speaker_9.npz
│   │       │   ├── pt_speaker_0.npz
│   │       │   ├── pt_speaker_1.npz
│   │       │   ├── pt_speaker_2.npz
│   │       │   ├── pt_speaker_3.npz
│   │       │   ├── pt_speaker_4.npz
│   │       │   ├── pt_speaker_5.npz
│   │       │   ├── pt_speaker_6.npz
│   │       │   ├── pt_speaker_7.npz
│   │       │   ├── pt_speaker_8.npz
│   │       │   ├── pt_speaker_9.npz
│   │       │   ├── ru_speaker_0.npz
│   │       │   ├── ru_speaker_1.npz
│   │       │   ├── ru_speaker_2.npz
│   │       │   ├── ru_speaker_3.npz
│   │       │   ├── ru_speaker_4.npz
│   │       │   ├── ru_speaker_5.npz
│   │       │   ├── ru_speaker_6.npz
│   │       │   ├── ru_speaker_7.npz
│   │       │   ├── ru_speaker_8.npz
│   │       │   ├── ru_speaker_9.npz
│   │       │   ├── tr_speaker_0.npz
│   │       │   ├── tr_speaker_1.npz
│   │       │   ├── tr_speaker_2.npz
│   │       │   ├── tr_speaker_3.npz
│   │       │   ├── tr_speaker_4.npz
│   │       │   ├── tr_speaker_5.npz
│   │       │   ├── tr_speaker_6.npz
│   │       │   ├── tr_speaker_7.npz
│   │       │   ├── tr_speaker_8.npz
│   │       │   ├── tr_speaker_9.npz
│   │       │   ├── zh_speaker_0.npz
│   │       │   ├── zh_speaker_1.npz
│   │       │   ├── zh_speaker_2.npz
│   │       │   ├── zh_speaker_3.npz
│   │       │   ├── zh_speaker_4.npz
│   │       │   ├── zh_speaker_5.npz
│   │       │   ├── zh_speaker_6.npz
│   │       │   ├── zh_speaker_7.npz
│   │       │   ├── zh_speaker_8.npz
│   │       │   └── zh_speaker_9.npz
│   │       ├── zh_speaker_0.npz
│   │       ├── zh_speaker_1.npz
│   │       ├── zh_speaker_2.npz
│   │       ├── zh_speaker_3.npz
│   │       ├── zh_speaker_4.npz
│   │       ├── zh_speaker_5.npz
│   │       ├── zh_speaker_6.npz
│   │       ├── zh_speaker_7.npz
│   │       ├── zh_speaker_8.npz
│   │       └── zh_speaker_9.npz
│   ├── cli.py
│   ├── generation.py
│   ├── model.py
│   └── model_fine.py
├── model-card.md
├── notebooks/
│   ├── fake_classifier.ipynb
│   ├── long_form_generation.ipynb
│   ├── memory_profiling_bark.ipynb
│   └── use_small_models_on_cpu.ipynb
├── pyproject.toml
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
__pycache__/
suno_bark.egg-info/


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) Suno, Inc

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
> Notice: Bark is Suno's open-source text-to-speech+ model. If you are looking for our text-to-music models, please visit us on our [web page](https://suno.ai) and join our community on [Discord](https://suno.ai/discord). 

     
# 🐶 Bark

[![](https://dcbadge.vercel.app/api/server/J2B2vsjKuE?style=flat&compact=True)](https://suno.ai/discord)
[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/FM.svg?style=social&label=@suno_ai_)](https://twitter.com/suno_ai_)

> 🔗 [Examples](https://suno.ai/examples/bark-v0) • [Suno Studio Waitlist](https://suno-ai.typeform.com/suno-studio) • [Updates](#-updates) • [How to Use](#-usage-in-python) • [Installation](#-installation) • [FAQ](#-faq)

[//]: <br> (vertical spaces around image)
<br>
<p align="center">
<img src="https://user-images.githubusercontent.com/5068315/235310676-a4b3b511-90ec-4edf-8153-7ccf14905d73.png" width="500"></img>
</p>
<br>

Bark is a transformer-based text-to-audio model created by [Suno](https://suno.ai). Bark can generate highly realistic, multilingual speech as well as other audio - including music, background noise and simple sound effects. The model can also produce nonverbal communications like laughing, sighing and crying. To support the research community, we are providing access to pretrained model checkpoints, which are ready for inference and available for commercial use.

## ⚠ Disclaimer
Bark was developed for research purposes. It is not a conventional text-to-speech model but instead a fully generative text-to-audio model, which can deviate in unexpected ways from provided prompts. Suno does not take responsibility for any output generated. Use at your own risk, and please act responsibly.

## 📖 Quick Index
* [🚀 Updates](#-updates)
* [💻 Installation](#-installation)
* [🐍 Usage](#-usage-in-python)
* [🌀 Live Examples](https://suno.ai/examples/bark-v0)
* [❓ FAQ](#-faq)

## 🎧 Demos  

[![Open in Spaces](https://img.shields.io/badge/🤗-Open%20in%20Spaces-blue.svg)](https://huggingface.co/spaces/suno/bark)
[![Open on Replicate](https://img.shields.io/badge/®️-Open%20on%20Replicate-blue.svg)](https://replicate.com/suno-ai/bark)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1eJfA2XUa-mXwdMy7DoYKVYHI1iTd9Vkt?usp=sharing)

## 🚀 Updates

**2023.05.01**
- ©️ Bark is now licensed under the MIT License, meaning it's now available for commercial use!  
- ⚡ 2x speed-up on GPU. 10x speed-up on CPU. We also added an option for a smaller version of Bark, which offers additional speed-up with the trade-off of slightly lower quality. 
- 📕 [Long-form generation](notebooks/long_form_generation.ipynb), voice consistency enhancements and other examples are now documented in a new [notebooks](./notebooks) section.
- 👥 We created a [voice prompt library](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c). We hope this resource helps you find useful prompts for your use cases! You can also join us on [Discord](https://suno.ai/discord), where the community actively shares useful prompts in the **#audio-prompts** channel.  
- 💬 Growing community support and access to new features here: 

     [![](https://dcbadge.vercel.app/api/server/J2B2vsjKuE)](https://suno.ai/discord)

- 💾 You can now use Bark with GPUs that have low VRAM (<4GB).

**2023.04.20**
- 🐶 Bark release!

## 🐍 Usage in Python

<details open>
  <summary><h3>🪑 Basics</h3></summary>

```python
from bark import SAMPLE_RATE, generate_audio, preload_models
from scipy.io.wavfile import write as write_wav
from IPython.display import Audio

# download and load all models
preload_models()

# generate audio from text
text_prompt = """
     Hello, my name is Suno. And, uh — and I like pizza. [laughs] 
     But I also have other interests such as playing tic tac toe.
"""
audio_array = generate_audio(text_prompt)

# save audio to disk
write_wav("bark_generation.wav", SAMPLE_RATE, audio_array)
  
# play text in notebook
Audio(audio_array, rate=SAMPLE_RATE)
```
     
[pizza1.webm](https://user-images.githubusercontent.com/34592747/cfa98e54-721c-4b9c-b962-688e09db684f.webm)

</details>

<details open>
  <summary><h3>🌎 Foreign Language</h3></summary>
<br>
Bark supports various languages out-of-the-box and automatically determines language from input text. When prompted with code-switched text, Bark will attempt to employ the native accent for the respective languages. English quality is best for the time being, and we expect other languages to further improve with scaling. 
<br>
<br>

```python

text_prompt = """
    추석은 내가 가장 좋아하는 명절이다. 나는 며칠 동안 휴식을 취하고 친구 및 가족과 시간을 보낼 수 있습니다.
"""
audio_array = generate_audio(text_prompt)
```
[suno_korean.webm](https://user-images.githubusercontent.com/32879321/235313033-dc4477b9-2da0-4b94-9c8b-a8c2d8f5bb5e.webm)
  
*Note: since Bark recognizes languages automatically from input text, it is possible to use, for example, a german history prompt with english text. This usually leads to english audio with a german accent.*
```python
text_prompt = """
    Der Dreißigjährige Krieg (1618-1648) war ein verheerender Konflikt, der Europa stark geprägt hat.
    This is a beginning of the history. If you want to hear more, please continue.
"""
audio_array = generate_audio(text_prompt)
```
[suno_german_accent.webm](https://user-images.githubusercontent.com/34592747/3f96ab3e-02ec-49cb-97a6-cf5af0b3524a.webm)


     

</details>

<details open>
  <summary><h3>🎶 Music</h3></summary>
Bark can generate all types of audio, and, in principle, doesn't see a difference between speech and music. Sometimes Bark chooses to generate text as music, but you can help it out by adding music notes around your lyrics.
<br>
<br>

```python
text_prompt = """
    ♪ In the jungle, the mighty jungle, the lion barks tonight ♪
"""
audio_array = generate_audio(text_prompt)
```
[lion.webm](https://user-images.githubusercontent.com/5068315/230684766-97f5ea23-ad99-473c-924b-66b6fab24289.webm)
</details>

<details open>
<summary><h3>🎤 Voice Presets</h3></summary>
  
Bark supports 100+ speaker presets across [supported languages](#supported-languages). You can browse the library of supported voice presets [HERE](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c), or in the [code](bark/assets/prompts). The community also often shares presets in [Discord](https://discord.gg/J2B2vsjKuE).

> Bark tries to match the tone, pitch, emotion and prosody of a given preset, but does not currently support custom voice cloning. The model also attempts to preserve music, ambient noise, etc.

```python
text_prompt = """
    I have a silky smooth voice, and today I will tell you about 
    the exercise regimen of the common sloth.
"""
audio_array = generate_audio(text_prompt, history_prompt="v2/en_speaker_1")
```

[sloth.webm](https://user-images.githubusercontent.com/5068315/230684883-a344c619-a560-4ff5-8b99-b4463a34487b.webm)
</details>

### 📃 Generating Longer Audio
  
By default, `generate_audio` works well with around 13 seconds of spoken text. For an example of how to do long-form generation, see 👉 **[Notebook](notebooks/long_form_generation.ipynb)** 👈

<details>
<summary>Click to toggle example long-form generations (from the example notebook)</summary>

[dialog.webm](https://user-images.githubusercontent.com/2565833/235463539-f57608da-e4cb-4062-8771-148e29512b01.webm)

[longform_advanced.webm](https://user-images.githubusercontent.com/2565833/235463547-1c0d8744-269b-43fe-9630-897ea5731652.webm)

[longform_basic.webm](https://user-images.githubusercontent.com/2565833/235463559-87efe9f8-a2db-4d59-b764-57db83f95270.webm)

</details>


## Command line
```commandline
python -m bark --text "Hello, my name is Suno." --output_filename "example.wav"
```

## 💻 Installation
*‼️ CAUTION ‼️ Do NOT use `pip install bark`. It installs a different package, which is not managed by Suno.*
```bash
pip install git+https://github.com/suno-ai/bark.git
```

or

```bash
git clone https://github.com/suno-ai/bark
cd bark && pip install . 
```


## 🤗 Transformers Usage

Bark is available in the 🤗 Transformers library from version 4.31.0 onwards, requiring minimal dependencies 
and additional packages. Steps to get started:

1. First install the 🤗 [Transformers library](https://github.com/huggingface/transformers) from main:

```
pip install git+https://github.com/huggingface/transformers.git
```

2. Run the following Python code to generate speech samples:

```py
from transformers import AutoProcessor, BarkModel

processor = AutoProcessor.from_pretrained("suno/bark")
model = BarkModel.from_pretrained("suno/bark")

voice_preset = "v2/en_speaker_6"

inputs = processor("Hello, my dog is cute", voice_preset=voice_preset)

audio_array = model.generate(**inputs)
audio_array = audio_array.cpu().numpy().squeeze()
```

3. Listen to the audio samples either in an ipynb notebook:

```py
from IPython.display import Audio

sample_rate = model.generation_config.sample_rate
Audio(audio_array, rate=sample_rate)
```

Or save them as a `.wav` file using a third-party library, e.g. `scipy`:

```py
import scipy

sample_rate = model.generation_config.sample_rate
scipy.io.wavfile.write("bark_out.wav", rate=sample_rate, data=audio_array)
```

For more details on using the Bark model for inference using the 🤗 Transformers library, refer to the 
[Bark docs](https://huggingface.co/docs/transformers/main/en/model_doc/bark) or the hands-on 
[Google Colab](https://colab.research.google.com/drive/1dWWkZzvu7L9Bunq9zvD-W02RFUXoW-Pd?usp=sharing).


## 🛠️ Hardware and Inference Speed

Bark has been tested and works on both CPU and GPU (`pytorch 2.0+`, CUDA 11.7 and CUDA 12.0).

On enterprise GPUs and PyTorch nightly, Bark can generate audio in roughly real-time. On older GPUs, default colab, or CPU, inference time might be significantly slower. For older GPUs or CPU you might want to consider using smaller models. Details can be found in out tutorial sections here.

The full version of Bark requires around 12GB of VRAM to hold everything on GPU at the same time. 
To use a smaller version of the models, which should fit into 8GB VRAM, set the environment flag `SUNO_USE_SMALL_MODELS=True`.

If you don't have hardware available or if you want to play with bigger versions of our models, you can also sign up for early access to our model playground [here](https://suno-ai.typeform.com/suno-studio).

## ⚙️ Details

Bark is fully generative text-to-audio model devolved for research and demo purposes. It follows a GPT style architecture similar to [AudioLM](https://arxiv.org/abs/2209.03143) and [Vall-E](https://arxiv.org/abs/2301.02111) and a quantized Audio representation from [EnCodec](https://github.com/facebookresearch/encodec). It is not a conventional TTS model, but instead a fully generative text-to-audio model capable of deviating in unexpected ways from any given script. Different to previous approaches, the input text prompt is converted directly to audio without the intermediate use of phonemes. It can therefore generalize to arbitrary instructions beyond speech such as music lyrics, sound effects or other non-speech sounds.

Below is a list of some known non-speech sounds, but we are finding more every day. Please let us know if you find patterns that work particularly well on [Discord](https://suno.ai/discord)!

- `[laughter]`
- `[laughs]`
- `[sighs]`
- `[music]`
- `[gasps]`
- `[clears throat]`
- `—` or `...` for hesitations
- `♪` for song lyrics
- CAPITALIZATION for emphasis of a word
- `[MAN]` and `[WOMAN]` to bias Bark toward male and female speakers, respectively

### Supported Languages

| Language | Status |
| --- | :---: |
| English (en) | ✅ |
| German (de) | ✅ |
| Spanish (es) | ✅ |
| French (fr) | ✅ |
| Hindi (hi) | ✅ |
| Italian (it) | ✅ |
| Japanese (ja) | ✅ |
| Korean (ko) | ✅ |
| Polish (pl) | ✅ |
| Portuguese (pt) | ✅ |
| Russian (ru) | ✅ |
| Turkish (tr) | ✅ |
| Chinese, simplified (zh) | ✅ |

Requests for future language support [here](https://github.com/suno-ai/bark/discussions/111) or in the **#forums** channel on [Discord](https://suno.ai/discord). 

## 🙏 Appreciation

- [nanoGPT](https://github.com/karpathy/nanoGPT) for a dead-simple and blazing fast implementation of GPT-style models
- [EnCodec](https://github.com/facebookresearch/encodec) for a state-of-the-art implementation of a fantastic audio codec
- [AudioLM](https://github.com/lucidrains/audiolm-pytorch) for related training and inference code
- [Vall-E](https://arxiv.org/abs/2301.02111), [AudioLM](https://arxiv.org/abs/2209.03143) and many other ground-breaking papers that enabled the development of Bark

## © License

Bark is licensed under the MIT License. 

## 📱 Community

- [Twitter](https://twitter.com/suno_ai_)
- [Discord](https://suno.ai/discord)

## 🎧 Suno Studio (Early Access)

We’re developing a playground for our models, including Bark. 

If you are interested, you can sign up for early access [here](https://suno-ai.typeform.com/suno-studio).

## ❓ FAQ

#### How do I specify where models are downloaded and cached?
* Bark uses Hugging Face to download and store models. You can see find more info [here](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfhome). 


#### Bark's generations sometimes differ from my prompts. What's happening?
* Bark is a GPT-style model. As such, it may take some creative liberties in its generations, resulting in higher-variance model outputs than traditional text-to-speech approaches.

#### What voices are supported by Bark?  
* Bark supports 100+ speaker presets across [supported languages](#supported-languages). You can browse the library of speaker presets [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c). The community also shares presets in [Discord](https://suno.ai/discord). Bark also supports generating unique random voices that fit the input text. Bark does not currently support custom voice cloning.

#### Why is the output limited to ~13-14 seconds?
* Bark is a GPT-style model, and its architecture/context window is optimized to output generations with roughly this length.

#### How much VRAM do I need?
* The full version of Bark requires around 12Gb of memory to hold everything on GPU at the same time. However, even smaller cards down to ~2Gb work with some additional settings. Simply add the following code snippet before your generation: 

```python
import os
os.environ["SUNO_OFFLOAD_CPU"] = "True"
os.environ["SUNO_USE_SMALL_MODELS"] = "True"
```

#### My generated audio sounds like a 1980s phone call. What's happening?
* Bark generates audio from scratch. It is not meant to create only high-fidelity, studio-quality speech. Rather, outputs could be anything from perfect speech to multiple people arguing at a baseball game recorded with bad microphones.


================================================
FILE: bark/__init__.py
================================================
from .api import generate_audio, text_to_semantic, semantic_to_waveform, save_as_prompt
from .generation import SAMPLE_RATE, preload_models


================================================
FILE: bark/__main__.py
================================================
from .cli import cli

cli()


================================================
FILE: bark/api.py
================================================
from typing import Dict, Optional, Union

import numpy as np

from .generation import codec_decode, generate_coarse, generate_fine, generate_text_semantic


def text_to_semantic(
    text: str,
    history_prompt: Optional[Union[Dict, str]] = None,
    temp: float = 0.7,
    silent: bool = False,
):
    """Generate semantic array from text.

    Args:
        text: text to be turned into audio
        history_prompt: history choice for audio cloning
        temp: generation temperature (1.0 more diverse, 0.0 more conservative)
        silent: disable progress bar

    Returns:
        numpy semantic array to be fed into `semantic_to_waveform`
    """
    x_semantic = generate_text_semantic(
        text,
        history_prompt=history_prompt,
        temp=temp,
        silent=silent,
        use_kv_caching=True
    )
    return x_semantic


def semantic_to_waveform(
    semantic_tokens: np.ndarray,
    history_prompt: Optional[Union[Dict, str]] = None,
    temp: float = 0.7,
    silent: bool = False,
    output_full: bool = False,
):
    """Generate audio array from semantic input.

    Args:
        semantic_tokens: semantic token output from `text_to_semantic`
        history_prompt: history choice for audio cloning
        temp: generation temperature (1.0 more diverse, 0.0 more conservative)
        silent: disable progress bar
        output_full: return full generation to be used as a history prompt

    Returns:
        numpy audio array at sample frequency 24khz
    """
    coarse_tokens = generate_coarse(
        semantic_tokens,
        history_prompt=history_prompt,
        temp=temp,
        silent=silent,
        use_kv_caching=True
    )
    fine_tokens = generate_fine(
        coarse_tokens,
        history_prompt=history_prompt,
        temp=0.5,
    )
    audio_arr = codec_decode(fine_tokens)
    if output_full:
        full_generation = {
            "semantic_prompt": semantic_tokens,
            "coarse_prompt": coarse_tokens,
            "fine_prompt": fine_tokens,
        }
        return full_generation, audio_arr
    return audio_arr


def save_as_prompt(filepath, full_generation):
    assert(filepath.endswith(".npz"))
    assert(isinstance(full_generation, dict))
    assert("semantic_prompt" in full_generation)
    assert("coarse_prompt" in full_generation)
    assert("fine_prompt" in full_generation)
    np.savez(filepath, **full_generation)


def generate_audio(
    text: str,
    history_prompt: Optional[Union[Dict, str]] = None,
    text_temp: float = 0.7,
    waveform_temp: float = 0.7,
    silent: bool = False,
    output_full: bool = False,
):
    """Generate audio array from input text.

    Args:
        text: text to be turned into audio
        history_prompt: history choice for audio cloning
        text_temp: generation temperature (1.0 more diverse, 0.0 more conservative)
        waveform_temp: generation temperature (1.0 more diverse, 0.0 more conservative)
        silent: disable progress bar
        output_full: return full generation to be used as a history prompt

    Returns:
        numpy audio array at sample frequency 24khz
    """
    semantic_tokens = text_to_semantic(
        text,
        history_prompt=history_prompt,
        temp=text_temp,
        silent=silent,
    )
    out = semantic_to_waveform(
        semantic_tokens,
        history_prompt=history_prompt,
        temp=waveform_temp,
        silent=silent,
        output_full=output_full,
    )
    if output_full:
        full_generation, audio_arr = out
        return full_generation, audio_arr
    else:
        audio_arr = out
    return audio_arr


================================================
FILE: bark/assets/prompts/readme.md
================================================
# Example Prompts Data

## Version Two
The `v2` prompts are better engineered to follow text with a consistent voice.
To use them, simply include `v2` in the prompt. For example
```python
from bark import generate_audio
text_prompt = "madam I'm adam"
audio_array = generate_audio(text_prompt, history_prompt="v2/en_speaker_1")
```

## Prompt Format
The provided data is in the .npz format, which is a file format used in Python for storing arrays and data. The data contains three arrays: semantic_prompt, coarse_prompt, and fine_prompt.

```semantic_prompt```

The semantic_prompt array contains a sequence of token IDs generated by the BERT tokenizer from Hugging Face. These tokens encode the text input and are used as an input to generate the audio output. The shape of this array is (n,), where n is the number of tokens in the input text.

```coarse_prompt```

The coarse_prompt array is an intermediate output of the text-to-speech pipeline, and contains token IDs generated by the first two codebooks of the EnCodec Codec from Facebook. This step converts the semantic tokens into a different representation that is better suited for the subsequent step. The shape of this array is (2, m), where m is the number of tokens after conversion by the EnCodec Codec.

```fine_prompt```

The fine_prompt array is a further processed output of the pipeline, and contains 8 codebooks from the EnCodec Codec. These codebooks represent the final stage of tokenization, and the resulting tokens are used to generate the audio output. The shape of this array is (8, p), where p is the number of tokens after further processing by the EnCodec Codec.

Overall, these arrays represent different stages of a text-to-speech pipeline that converts text input into synthesized audio output. The semantic_prompt array represents the input text, while coarse_prompt and fine_prompt represent intermediate and final stages of tokenization, respectively.





================================================
FILE: bark/cli.py
================================================
import argparse
from typing import Dict, Optional, Union
import os

from scipy.io.wavfile import write as write_wav
from .api import generate_audio
from .generation import SAMPLE_RATE


def cli():
    """Commandline interface."""
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("--text", type=str, help="text to be turned into audio")
    parser.add_argument(
        "--output_filename",
        type=str,
        default="bark_generation.wav",
        help="output audio file name",
    )
    parser.add_argument("--output_dir", type=str, default=".", help="directory to save the outputs")
    parser.add_argument(
        "--history_prompt",
        type=str,
        default=None,
        help="history choice for audio cloning, be path to the .npz file.",
    )
    parser.add_argument(
        "--text_temp",
        default=0.7,
        type=float,
        help="generation temperature (1.0 more diverse, 0.0 more conservative)",
    )
    parser.add_argument(
        "--waveform_temp",
        default=0.7,
        type=float,
        help="generation temperature (1.0 more diverse, 0.0 more conservative)",
    )
    parser.add_argument("--silent", default=False, type=bool, help="disable progress bar")
    parser.add_argument(
        "--output_full",
        default=False,
        type=bool,
        help="return full generation to be used as a history prompt",
    )

    args = vars(parser.parse_args())
    input_text: str = args.get("text")
    output_filename: str = args.get("output_filename")
    output_dir: str = args.get("output_dir")
    history_prompt: str = args.get("history_prompt")
    text_temp: float = args.get("text_temp")
    waveform_temp: float = args.get("waveform_temp")
    silent: bool = args.get("silent")
    output_full: bool = args.get("output_full")

    try:
        os.makedirs(output_dir, exist_ok=True)
        generated_audio = generate_audio(
            input_text,
            history_prompt=history_prompt,
            text_temp=text_temp,
            waveform_temp=waveform_temp,
            silent=silent,
            output_full=output_full,
        )
        output_file_path = os.path.join(output_dir, output_filename)
        write_wav(output_file_path, SAMPLE_RATE, generated_audio)
        print(f"Done! Output audio file is saved at: '{output_file_path}'")
    except Exception as e:
        print(f"Oops, an error occurred: {e}")


================================================
FILE: bark/generation.py
================================================
import contextlib
import gc
import os
import re

from encodec import EncodecModel
import funcy
import logging
import numpy as np
from scipy.special import softmax
import torch
import torch.nn.functional as F
import tqdm
from transformers import BertTokenizer
from huggingface_hub import hf_hub_download

from .model import GPTConfig, GPT
from .model_fine import FineGPT, FineGPTConfig

if (
    torch.cuda.is_available() and
    hasattr(torch.cuda, "amp") and
    hasattr(torch.cuda.amp, "autocast") and
    hasattr(torch.cuda, "is_bf16_supported") and
    torch.cuda.is_bf16_supported()
):
    autocast = funcy.partial(torch.cuda.amp.autocast, dtype=torch.bfloat16)
else:
    @contextlib.contextmanager
    def autocast():
        yield


# hold models in global scope to lazy load
global models
models = {}

global models_devices
models_devices = {}


CONTEXT_WINDOW_SIZE = 1024

SEMANTIC_RATE_HZ = 49.9
SEMANTIC_VOCAB_SIZE = 10_000

CODEBOOK_SIZE = 1024
N_COARSE_CODEBOOKS = 2
N_FINE_CODEBOOKS = 8
COARSE_RATE_HZ = 75

SAMPLE_RATE = 24_000


SUPPORTED_LANGS = [
    ("English", "en"),
    ("German", "de"),
    ("Spanish", "es"),
    ("French", "fr"),
    ("Hindi", "hi"),
    ("Italian", "it"),
    ("Japanese", "ja"),
    ("Korean", "ko"),
    ("Polish", "pl"),
    ("Portuguese", "pt"),
    ("Russian", "ru"),
    ("Turkish", "tr"),
    ("Chinese", "zh"),
]

ALLOWED_PROMPTS = {"announcer"}
for _, lang in SUPPORTED_LANGS:
    for prefix in ("", f"v2{os.path.sep}"):
        for n in range(10):
            ALLOWED_PROMPTS.add(f"{prefix}{lang}_speaker_{n}")


logger = logging.getLogger(__name__)


CUR_PATH = os.path.dirname(os.path.abspath(__file__))


default_cache_dir = os.path.join(os.path.expanduser("~"), ".cache")
CACHE_DIR = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0")


def _cast_bool_env_var(s):
    return s.lower() in ('true', '1', 't')


USE_SMALL_MODELS = _cast_bool_env_var(os.environ.get("SUNO_USE_SMALL_MODELS", "False"))
GLOBAL_ENABLE_MPS = _cast_bool_env_var(os.environ.get("SUNO_ENABLE_MPS", "False"))
OFFLOAD_CPU = _cast_bool_env_var(os.environ.get("SUNO_OFFLOAD_CPU", "False"))


REMOTE_MODEL_PATHS = {
    "text_small": {
        "repo_id": "suno/bark",
        "file_name": "text.pt",
    },
    "coarse_small": {
        "repo_id": "suno/bark",
        "file_name": "coarse.pt",
    },
    "fine_small": {
        "repo_id": "suno/bark",
        "file_name": "fine.pt",
    },
    "text": {
        "repo_id": "suno/bark",
        "file_name": "text_2.pt",
    },
    "coarse": {
        "repo_id": "suno/bark",
        "file_name": "coarse_2.pt",
    },
    "fine": {
        "repo_id": "suno/bark",
        "file_name": "fine_2.pt",
    },
}


if not hasattr(torch.nn.functional, 'scaled_dot_product_attention') and torch.cuda.is_available():
    logger.warning(
        "torch version does not support flash attention. You will get faster" +
        " inference speed by upgrade torch to newest nightly version."
    )


def _grab_best_device(use_gpu=True):
    if torch.cuda.device_count() > 0 and use_gpu:
        device = "cuda"
    elif torch.backends.mps.is_available() and use_gpu and GLOBAL_ENABLE_MPS:
        device = "mps"
    else:
        device = "cpu"
    return device


def _get_ckpt_path(model_type, use_small=False):
    key = model_type
    if use_small or USE_SMALL_MODELS:
        key += "_small"
    return os.path.join(CACHE_DIR, REMOTE_MODEL_PATHS[key]["file_name"])


def _download(from_hf_path, file_name):
    os.makedirs(CACHE_DIR, exist_ok=True)
    hf_hub_download(repo_id=from_hf_path, filename=file_name, local_dir=CACHE_DIR)


class InferenceContext:
    def __init__(self, benchmark=False):
        # we can't expect inputs to be the same length, so disable benchmarking by default
        self._chosen_cudnn_benchmark = benchmark
        self._cudnn_benchmark = None

    def __enter__(self):
        self._cudnn_benchmark = torch.backends.cudnn.benchmark
        torch.backends.cudnn.benchmark = self._chosen_cudnn_benchmark

    def __exit__(self, exc_type, exc_value, exc_traceback):
        torch.backends.cudnn.benchmark = self._cudnn_benchmark


if torch.cuda.is_available():
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True


@contextlib.contextmanager
def _inference_mode():
    with InferenceContext(), torch.inference_mode(), torch.no_grad(), autocast():
        yield


def _clear_cuda_cache():
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
        torch.cuda.synchronize()


def clean_models(model_key=None):
    global models
    model_keys = [model_key] if model_key is not None else list(models.keys())
    for k in model_keys:
        if k in models:
            del models[k]
    _clear_cuda_cache()
    gc.collect()


def _load_model(ckpt_path, device, use_small=False, model_type="text"):
    if model_type == "text":
        ConfigClass = GPTConfig
        ModelClass = GPT
    elif model_type == "coarse":
        ConfigClass = GPTConfig
        ModelClass = GPT
    elif model_type == "fine":
        ConfigClass = FineGPTConfig
        ModelClass = FineGPT
    else:
        raise NotImplementedError()
    model_key = f"{model_type}_small" if use_small or USE_SMALL_MODELS else model_type
    model_info = REMOTE_MODEL_PATHS[model_key]
    if not os.path.exists(ckpt_path):
        logger.info(f"{model_type} model not found, downloading into `{CACHE_DIR}`.")
        _download(model_info["repo_id"], model_info["file_name"])
    checkpoint = torch.load(ckpt_path, map_location=device)
    # this is a hack
    model_args = checkpoint["model_args"]
    if "input_vocab_size" not in model_args:
        model_args["input_vocab_size"] = model_args["vocab_size"]
        model_args["output_vocab_size"] = model_args["vocab_size"]
        del model_args["vocab_size"]
    gptconf = ConfigClass(**checkpoint["model_args"])
    model = ModelClass(gptconf)
    state_dict = checkpoint["model"]
    # fixup checkpoint
    unwanted_prefix = "_orig_mod."
    for k, v in list(state_dict.items()):
        if k.startswith(unwanted_prefix):
            state_dict[k[len(unwanted_prefix) :]] = state_dict.pop(k)
    extra_keys = set(state_dict.keys()) - set(model.state_dict().keys())
    extra_keys = set([k for k in extra_keys if not k.endswith(".attn.bias")])
    missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())
    missing_keys = set([k for k in missing_keys if not k.endswith(".attn.bias")])
    if len(extra_keys) != 0:
        raise ValueError(f"extra keys found: {extra_keys}")
    if len(missing_keys) != 0:
        raise ValueError(f"missing keys: {missing_keys}")
    model.load_state_dict(state_dict, strict=False)
    n_params = model.get_num_params()
    val_loss = checkpoint["best_val_loss"].item()
    logger.info(f"model loaded: {round(n_params/1e6,1)}M params, {round(val_loss,3)} loss")
    model.eval()
    model.to(device)
    del checkpoint, state_dict
    _clear_cuda_cache()
    if model_type == "text":
        tokenizer = BertTokenizer.from_pretrained("bert-base-multilingual-cased")
        return {
            "model": model,
            "tokenizer": tokenizer,
        }
    return model


def _load_codec_model(device):
    model = EncodecModel.encodec_model_24khz()
    model.set_target_bandwidth(6.0)
    model.eval()
    model.to(device)
    _clear_cuda_cache()
    return model


def load_model(use_gpu=True, use_small=False, force_reload=False, model_type="text"):
    _load_model_f = funcy.partial(_load_model, model_type=model_type, use_small=use_small)
    if model_type not in ("text", "coarse", "fine"):
        raise NotImplementedError()
    global models
    global models_devices
    device = _grab_best_device(use_gpu=use_gpu)
    model_key = f"{model_type}"
    if OFFLOAD_CPU:
        models_devices[model_key] = device
        device = "cpu"
    if model_key not in models or force_reload:
        ckpt_path = _get_ckpt_path(model_type, use_small=use_small)
        clean_models(model_key=model_key)
        model = _load_model_f(ckpt_path, device)
        models[model_key] = model
    if model_type == "text":
        models[model_key]["model"].to(device)
    else:
        models[model_key].to(device)
    return models[model_key]


def load_codec_model(use_gpu=True, force_reload=False):
    global models
    global models_devices
    device = _grab_best_device(use_gpu=use_gpu)
    if device == "mps":
        # encodec doesn't support mps
        device = "cpu"
    model_key = "codec"
    if OFFLOAD_CPU:
        models_devices[model_key] = device
        device = "cpu"
    if model_key not in models or force_reload:
        clean_models(model_key=model_key)
        model = _load_codec_model(device)
        models[model_key] = model
    models[model_key].to(device)
    return models[model_key]


def preload_models(
    text_use_gpu=True,
    text_use_small=False,
    coarse_use_gpu=True,
    coarse_use_small=False,
    fine_use_gpu=True,
    fine_use_small=False,
    codec_use_gpu=True,
    force_reload=False,
):
    """Load all the necessary models for the pipeline."""
    if _grab_best_device() == "cpu" and (
        text_use_gpu or coarse_use_gpu or fine_use_gpu or codec_use_gpu
    ):
        logger.warning("No GPU being used. Careful, inference might be very slow!")
    _ = load_model(
        model_type="text", use_gpu=text_use_gpu, use_small=text_use_small, force_reload=force_reload
    )
    _ = load_model(
        model_type="coarse",
        use_gpu=coarse_use_gpu,
        use_small=coarse_use_small,
        force_reload=force_reload,
    )
    _ = load_model(
        model_type="fine", use_gpu=fine_use_gpu, use_small=fine_use_small, force_reload=force_reload
    )
    _ = load_codec_model(use_gpu=codec_use_gpu, force_reload=force_reload)


####
# Generation Functionality
####


def _tokenize(tokenizer, text):
    return tokenizer.encode(text, add_special_tokens=False)


def _detokenize(tokenizer, enc_text):
    return tokenizer.decode(enc_text)


def _normalize_whitespace(text):
    return re.sub(r"\s+", " ", text).strip()


TEXT_ENCODING_OFFSET = 10_048
SEMANTIC_PAD_TOKEN = 10_000
TEXT_PAD_TOKEN = 129_595
SEMANTIC_INFER_TOKEN = 129_599


def _load_history_prompt(history_prompt_input):
    if isinstance(history_prompt_input, str) and history_prompt_input.endswith(".npz"):
        history_prompt = np.load(history_prompt_input)
    elif isinstance(history_prompt_input, str):
        # make sure this works on non-ubuntu
        history_prompt_input = os.path.join(*history_prompt_input.split("/"))
        if history_prompt_input not in ALLOWED_PROMPTS:
            raise ValueError("history prompt not found")
        history_prompt = np.load(
            os.path.join(CUR_PATH, "assets", "prompts", f"{history_prompt_input}.npz")
        )
    elif isinstance(history_prompt_input, dict):
        assert("semantic_prompt" in history_prompt_input)
        assert("coarse_prompt" in history_prompt_input)
        assert("fine_prompt" in history_prompt_input)
        history_prompt = history_prompt_input
    else:
        raise ValueError("history prompt format unrecognized")
    return history_prompt


def generate_text_semantic(
    text,
    history_prompt=None,
    temp=0.7,
    top_k=None,
    top_p=None,
    silent=False,
    min_eos_p=0.2,
    max_gen_duration_s=None,
    allow_early_stop=True,
    use_kv_caching=False,
):
    """Generate semantic tokens from text."""
    assert isinstance(text, str)
    text = _normalize_whitespace(text)
    assert len(text.strip()) > 0
    if history_prompt is not None:
        history_prompt = _load_history_prompt(history_prompt)
        semantic_history = history_prompt["semantic_prompt"]
        assert (
            isinstance(semantic_history, np.ndarray)
            and len(semantic_history.shape) == 1
            and len(semantic_history) > 0
            and semantic_history.min() >= 0
            and semantic_history.max() <= SEMANTIC_VOCAB_SIZE - 1
        )
    else:
        semantic_history = None
    # load models if not yet exist
    global models
    global models_devices
    if "text" not in models:
        preload_models()
    model_container = models["text"]
    model = model_container["model"]
    tokenizer = model_container["tokenizer"]
    encoded_text = np.array(_tokenize(tokenizer, text)) + TEXT_ENCODING_OFFSET
    if OFFLOAD_CPU:
        model.to(models_devices["text"])
    device = next(model.parameters()).device
    if len(encoded_text) > 256:
        p = round((len(encoded_text) - 256) / len(encoded_text) * 100, 1)
        logger.warning(f"warning, text too long, lopping of last {p}%")
        encoded_text = encoded_text[:256]
    encoded_text = np.pad(
        encoded_text,
        (0, 256 - len(encoded_text)),
        constant_values=TEXT_PAD_TOKEN,
        mode="constant",
    )
    if semantic_history is not None:
        semantic_history = semantic_history.astype(np.int64)
        # lop off if history is too long, pad if needed
        semantic_history = semantic_history[-256:]
        semantic_history = np.pad(
            semantic_history,
            (0, 256 - len(semantic_history)),
            constant_values=SEMANTIC_PAD_TOKEN,
            mode="constant",
        )
    else:
        semantic_history = np.array([SEMANTIC_PAD_TOKEN] * 256)
    x = torch.from_numpy(
        np.hstack([
            encoded_text, semantic_history, np.array([SEMANTIC_INFER_TOKEN])
        ]).astype(np.int64)
    )[None]
    assert x.shape[1] == 256 + 256 + 1
    with _inference_mode():
        x = x.to(device)
        n_tot_steps = 768
        # custom tqdm updates since we don't know when eos will occur
        pbar = tqdm.tqdm(disable=silent, total=n_tot_steps)
        pbar_state = 0
        tot_generated_duration_s = 0
        kv_cache = None
        for n in range(n_tot_steps):
            if use_kv_caching and kv_cache is not None:
                x_input = x[:, [-1]]
            else:
                x_input = x
            logits, kv_cache = model(
                x_input, merge_context=True, use_cache=use_kv_caching, past_kv=kv_cache
            )
            relevant_logits = logits[0, 0, :SEMANTIC_VOCAB_SIZE]
            if allow_early_stop:
                relevant_logits = torch.hstack(
                    (relevant_logits, logits[0, 0, [SEMANTIC_PAD_TOKEN]])  # eos
                )
            if top_p is not None:
                # faster to convert to numpy
                original_device = relevant_logits.device
                relevant_logits = relevant_logits.detach().cpu().type(torch.float32).numpy()
                sorted_indices = np.argsort(relevant_logits)[::-1]
                sorted_logits = relevant_logits[sorted_indices]
                cumulative_probs = np.cumsum(softmax(sorted_logits))
                sorted_indices_to_remove = cumulative_probs > top_p
                sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].copy()
                sorted_indices_to_remove[0] = False
                relevant_logits[sorted_indices[sorted_indices_to_remove]] = -np.inf
                relevant_logits = torch.from_numpy(relevant_logits)
                relevant_logits = relevant_logits.to(original_device)
            if top_k is not None:
                v, _ = torch.topk(relevant_logits, min(top_k, relevant_logits.size(-1)))
                relevant_logits[relevant_logits < v[-1]] = -float("Inf")
            probs = F.softmax(relevant_logits / temp, dim=-1)
            item_next = torch.multinomial(probs, num_samples=1).to(torch.int32)
            if allow_early_stop and (
                item_next == SEMANTIC_VOCAB_SIZE
                or (min_eos_p is not None and probs[-1] >= min_eos_p)
            ):
                # eos found, so break
                pbar.update(n - pbar_state)
                break
            x = torch.cat((x, item_next[None]), dim=1)
            tot_generated_duration_s += 1 / SEMANTIC_RATE_HZ
            if max_gen_duration_s is not None and tot_generated_duration_s > max_gen_duration_s:
                pbar.update(n - pbar_state)
                break
            if n == n_tot_steps - 1:
                pbar.update(n - pbar_state)
                break
            del logits, relevant_logits, probs, item_next

            if n > pbar_state:
                if n > pbar.total:
                    pbar.total = n
                pbar.update(n - pbar_state)
            pbar_state = n
        pbar.total = n
        pbar.refresh()
        pbar.close()
        out = x.detach().cpu().numpy().squeeze()[256 + 256 + 1 :]
    if OFFLOAD_CPU:
        model.to("cpu")
    assert all(0 <= out) and all(out < SEMANTIC_VOCAB_SIZE)
    _clear_cuda_cache()
    return out


def _flatten_codebooks(arr, offset_size=CODEBOOK_SIZE):
    assert len(arr.shape) == 2
    arr = arr.copy()
    if offset_size is not None:
        for n in range(1, arr.shape[0]):
            arr[n, :] += offset_size * n
    flat_arr = arr.ravel("F")
    return flat_arr


COARSE_SEMANTIC_PAD_TOKEN = 12_048
COARSE_INFER_TOKEN = 12_050


def generate_coarse(
    x_semantic,
    history_prompt=None,
    temp=0.7,
    top_k=None,
    top_p=None,
    silent=False,
    max_coarse_history=630,  # min 60 (faster), max 630 (more context)
    sliding_window_len=60,
    use_kv_caching=False,
):
    """Generate coarse audio codes from semantic tokens."""
    assert (
        isinstance(x_semantic, np.ndarray)
        and len(x_semantic.shape) == 1
        and len(x_semantic) > 0
        and x_semantic.min() >= 0
        and x_semantic.max() <= SEMANTIC_VOCAB_SIZE - 1
    )
    assert 60 <= max_coarse_history <= 630
    assert max_coarse_history + sliding_window_len <= 1024 - 256
    semantic_to_coarse_ratio = COARSE_RATE_HZ / SEMANTIC_RATE_HZ * N_COARSE_CODEBOOKS
    max_semantic_history = int(np.floor(max_coarse_history / semantic_to_coarse_ratio))
    if history_prompt is not None:
        history_prompt = _load_history_prompt(history_prompt)
        x_semantic_history = history_prompt["semantic_prompt"]
        x_coarse_history = history_prompt["coarse_prompt"]
        assert (
            isinstance(x_semantic_history, np.ndarray)
            and len(x_semantic_history.shape) == 1
            and len(x_semantic_history) > 0
            and x_semantic_history.min() >= 0
            and x_semantic_history.max() <= SEMANTIC_VOCAB_SIZE - 1
            and isinstance(x_coarse_history, np.ndarray)
            and len(x_coarse_history.shape) == 2
            and x_coarse_history.shape[0] == N_COARSE_CODEBOOKS
            and x_coarse_history.shape[-1] >= 0
            and x_coarse_history.min() >= 0
            and x_coarse_history.max() <= CODEBOOK_SIZE - 1
            and (
                round(x_coarse_history.shape[-1] / len(x_semantic_history), 1)
                == round(semantic_to_coarse_ratio / N_COARSE_CODEBOOKS, 1)
            )
        )
        x_coarse_history = _flatten_codebooks(x_coarse_history) + SEMANTIC_VOCAB_SIZE
        # trim histories correctly
        n_semantic_hist_provided = np.min(
            [
                max_semantic_history,
                len(x_semantic_history) - len(x_semantic_history) % 2,
                int(np.floor(len(x_coarse_history) / semantic_to_coarse_ratio)),
            ]
        )
        n_coarse_hist_provided = int(round(n_semantic_hist_provided * semantic_to_coarse_ratio))
        x_semantic_history = x_semantic_history[-n_semantic_hist_provided:].astype(np.int32)
        x_coarse_history = x_coarse_history[-n_coarse_hist_provided:].astype(np.int32)
        # TODO: bit of a hack for time alignment (sounds better)
        x_coarse_history = x_coarse_history[:-2]
    else:
        x_semantic_history = np.array([], dtype=np.int32)
        x_coarse_history = np.array([], dtype=np.int32)
    # load models if not yet exist
    global models
    global models_devices
    if "coarse" not in models:
        preload_models()
    model = models["coarse"]
    if OFFLOAD_CPU:
        model.to(models_devices["coarse"])
    device = next(model.parameters()).device
    # start loop
    n_steps = int(
        round(
            np.floor(len(x_semantic) * semantic_to_coarse_ratio / N_COARSE_CODEBOOKS)
            * N_COARSE_CODEBOOKS
        )
    )
    assert n_steps > 0 and n_steps % N_COARSE_CODEBOOKS == 0
    x_semantic = np.hstack([x_semantic_history, x_semantic]).astype(np.int32)
    x_coarse = x_coarse_history.astype(np.int32)
    base_semantic_idx = len(x_semantic_history)
    with _inference_mode():
        x_semantic_in = torch.from_numpy(x_semantic)[None].to(device)
        x_coarse_in = torch.from_numpy(x_coarse)[None].to(device)
        n_window_steps = int(np.ceil(n_steps / sliding_window_len))
        n_step = 0
        for _ in tqdm.tqdm(range(n_window_steps), total=n_window_steps, disable=silent):
            semantic_idx = base_semantic_idx + int(round(n_step / semantic_to_coarse_ratio))
            # pad from right side
            x_in = x_semantic_in[:, np.max([0, semantic_idx - max_semantic_history]) :]
            x_in = x_in[:, :256]
            x_in = F.pad(
                x_in,
                (0, 256 - x_in.shape[-1]),
                "constant",
                COARSE_SEMANTIC_PAD_TOKEN,
            )
            x_in = torch.hstack(
                [
                    x_in,
                    torch.tensor([COARSE_INFER_TOKEN])[None].to(device),
                    x_coarse_in[:, -max_coarse_history:],
                ]
            )
            kv_cache = None
            for _ in range(sliding_window_len):
                if n_step >= n_steps:
                    continue
                is_major_step = n_step % N_COARSE_CODEBOOKS == 0

                if use_kv_caching and kv_cache is not None:
                    x_input = x_in[:, [-1]]
                else:
                    x_input = x_in

                logits, kv_cache = model(x_input, use_cache=use_kv_caching, past_kv=kv_cache)
                logit_start_idx = (
                    SEMANTIC_VOCAB_SIZE + (1 - int(is_major_step)) * CODEBOOK_SIZE
                )
                logit_end_idx = (
                    SEMANTIC_VOCAB_SIZE + (2 - int(is_major_step)) * CODEBOOK_SIZE
                )
                relevant_logits = logits[0, 0, logit_start_idx:logit_end_idx]
                if top_p is not None:
                    # faster to convert to numpy
                    original_device = relevant_logits.device
                    relevant_logits = relevant_logits.detach().cpu().type(torch.float32).numpy()
                    sorted_indices = np.argsort(relevant_logits)[::-1]
                    sorted_logits = relevant_logits[sorted_indices]
                    cumulative_probs = np.cumsum(softmax(sorted_logits))
                    sorted_indices_to_remove = cumulative_probs > top_p
                    sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].copy()
                    sorted_indices_to_remove[0] = False
                    relevant_logits[sorted_indices[sorted_indices_to_remove]] = -np.inf
                    relevant_logits = torch.from_numpy(relevant_logits)
                    relevant_logits = relevant_logits.to(original_device)
                if top_k is not None:
                    v, _ = torch.topk(relevant_logits, min(top_k, relevant_logits.size(-1)))
                    relevant_logits[relevant_logits < v[-1]] = -float("Inf")
                probs = F.softmax(relevant_logits / temp, dim=-1)
                item_next = torch.multinomial(probs, num_samples=1).to(torch.int32)
                item_next += logit_start_idx
                x_coarse_in = torch.cat((x_coarse_in, item_next[None]), dim=1)
                x_in = torch.cat((x_in, item_next[None]), dim=1)
                del logits, relevant_logits, probs, item_next
                n_step += 1
            del x_in
        del x_semantic_in
    if OFFLOAD_CPU:
        model.to("cpu")
    gen_coarse_arr = x_coarse_in.detach().cpu().numpy().squeeze()[len(x_coarse_history) :]
    del x_coarse_in
    assert len(gen_coarse_arr) == n_steps
    gen_coarse_audio_arr = gen_coarse_arr.reshape(-1, N_COARSE_CODEBOOKS).T - SEMANTIC_VOCAB_SIZE
    for n in range(1, N_COARSE_CODEBOOKS):
        gen_coarse_audio_arr[n, :] -= n * CODEBOOK_SIZE
    _clear_cuda_cache()
    return gen_coarse_audio_arr


def generate_fine(
    x_coarse_gen,
    history_prompt=None,
    temp=0.5,
    silent=True,
):
    """Generate full audio codes from coarse audio codes."""
    assert (
        isinstance(x_coarse_gen, np.ndarray)
        and len(x_coarse_gen.shape) == 2
        and 1 <= x_coarse_gen.shape[0] <= N_FINE_CODEBOOKS - 1
        and x_coarse_gen.shape[1] > 0
        and x_coarse_gen.min() >= 0
        and x_coarse_gen.max() <= CODEBOOK_SIZE - 1
    )
    if history_prompt is not None:
        history_prompt = _load_history_prompt(history_prompt)
        x_fine_history = history_prompt["fine_prompt"]
        assert (
            isinstance(x_fine_history, np.ndarray)
            and len(x_fine_history.shape) == 2
            and x_fine_history.shape[0] == N_FINE_CODEBOOKS
            and x_fine_history.shape[1] >= 0
            and x_fine_history.min() >= 0
            and x_fine_history.max() <= CODEBOOK_SIZE - 1
        )
    else:
        x_fine_history = None
    n_coarse = x_coarse_gen.shape[0]
    # load models if not yet exist
    global models
    global models_devices
    if "fine" not in models:
        preload_models()
    model = models["fine"]
    if OFFLOAD_CPU:
        model.to(models_devices["fine"])
    device = next(model.parameters()).device
    # make input arr
    in_arr = np.vstack(
        [
            x_coarse_gen,
            np.zeros((N_FINE_CODEBOOKS - n_coarse, x_coarse_gen.shape[1]))
            + CODEBOOK_SIZE,  # padding
        ]
    ).astype(np.int32)
    # prepend history if available (max 512)
    if x_fine_history is not None:
        x_fine_history = x_fine_history.astype(np.int32)
        in_arr = np.hstack(
            [
                x_fine_history[:, -512:].astype(np.int32),
                in_arr,
            ]
        )
        n_history = x_fine_history[:, -512:].shape[1]
    else:
        n_history = 0
    n_remove_from_end = 0
    # need to pad if too short (since non-causal model)
    if in_arr.shape[1] < 1024:
        n_remove_from_end = 1024 - in_arr.shape[1]
        in_arr = np.hstack(
            [
                in_arr,
                np.zeros((N_FINE_CODEBOOKS, n_remove_from_end), dtype=np.int32) + CODEBOOK_SIZE,
            ]
        )
    # we can be lazy about fractional loop and just keep overwriting codebooks
    n_loops = np.max([0, int(np.ceil((x_coarse_gen.shape[1] - (1024 - n_history)) / 512))]) + 1
    with _inference_mode():
        in_arr = torch.tensor(in_arr.T).to(device)
        for n in tqdm.tqdm(range(n_loops), disable=silent):
            start_idx = np.min([n * 512, in_arr.shape[0] - 1024])
            start_fill_idx = np.min([n_history + n * 512, in_arr.shape[0] - 512])
            rel_start_fill_idx = start_fill_idx - start_idx
            in_buffer = in_arr[start_idx : start_idx + 1024, :][None]
            for nn in range(n_coarse, N_FINE_CODEBOOKS):
                logits = model(nn, in_buffer)
                if temp is None:
                    relevant_logits = logits[0, rel_start_fill_idx:, :CODEBOOK_SIZE]
                    codebook_preds = torch.argmax(relevant_logits, -1)
                else:
                    relevant_logits = logits[0, :, :CODEBOOK_SIZE] / temp
                    probs = F.softmax(relevant_logits, dim=-1)
                    codebook_preds = torch.multinomial(
                        probs[rel_start_fill_idx:1024], num_samples=1
                    ).reshape(-1)
                codebook_preds = codebook_preds.to(torch.int32)
                in_buffer[0, rel_start_fill_idx:, nn] = codebook_preds
                del logits, codebook_preds
            # transfer over info into model_in and convert to numpy
            for nn in range(n_coarse, N_FINE_CODEBOOKS):
                in_arr[
                    start_fill_idx : start_fill_idx + (1024 - rel_start_fill_idx), nn
                ] = in_buffer[0, rel_start_fill_idx:, nn]
            del in_buffer
        gen_fine_arr = in_arr.detach().cpu().numpy().squeeze().T
        del in_arr
    if OFFLOAD_CPU:
        model.to("cpu")
    gen_fine_arr = gen_fine_arr[:, n_history:]
    if n_remove_from_end > 0:
        gen_fine_arr = gen_fine_arr[:, :-n_remove_from_end]
    assert gen_fine_arr.shape[-1] == x_coarse_gen.shape[-1]
    _clear_cuda_cache()
    return gen_fine_arr


def codec_decode(fine_tokens):
    """Turn quantized audio codes into audio array using encodec."""
    # load models if not yet exist
    global models
    global models_devices
    if "codec" not in models:
        preload_models()
    model = models["codec"]
    if OFFLOAD_CPU:
        model.to(models_devices["codec"])
    device = next(model.parameters()).device
    arr = torch.from_numpy(fine_tokens)[None]
    arr = arr.to(device)
    arr = arr.transpose(0, 1)
    emb = model.quantizer.decode(arr)
    out = model.decoder(emb)
    audio_arr = out.detach().cpu().numpy().squeeze()
    del arr, emb, out
    if OFFLOAD_CPU:
        model.to("cpu")
    return audio_arr


================================================
FILE: bark/model.py
================================================
"""
Much of this code is adapted from Andrej Karpathy's NanoGPT
(https://github.com/karpathy/nanoGPT)
"""
import math
from dataclasses import dataclass

import torch
import torch.nn as nn
from torch.nn import functional as F

class LayerNorm(nn.Module):
    """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """

    def __init__(self, ndim, bias):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(ndim))
        self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None

    def forward(self, input):
        return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)

class CausalSelfAttention(nn.Module):

    def __init__(self, config):
        super().__init__()
        assert config.n_embd % config.n_head == 0
        # key, query, value projections for all heads, but in a batch
        self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
        # output projection
        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
        # regularization
        self.attn_dropout = nn.Dropout(config.dropout)
        self.resid_dropout = nn.Dropout(config.dropout)
        self.n_head = config.n_head
        self.n_embd = config.n_embd
        self.dropout = config.dropout
        # flash attention make GPU go brrrrr but support is only in PyTorch nightly and still a bit scary
        self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
        if not self.flash:
            # print("WARNING: using slow attention. Flash Attention atm needs PyTorch nightly and dropout=0.0")
            # causal mask to ensure that attention is only applied to the left in the input sequence
            self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
                                        .view(1, 1, config.block_size, config.block_size))

    def forward(self, x, past_kv=None, use_cache=False):
        B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)

        # calculate query, key, values for all heads in batch and move head forward to be the batch dim
        q, k ,v  = self.c_attn(x).split(self.n_embd, dim=2)
        k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)

        if past_kv is not None:
            past_key = past_kv[0]
            past_value = past_kv[1]
            k = torch.cat((past_key, k), dim=-2)
            v = torch.cat((past_value, v), dim=-2)

        FULL_T = k.shape[-2]

        if use_cache is True:
            present = (k, v)
        else:
            present = None

        # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
        if self.flash:
            # efficient attention using Flash Attention CUDA kernels
            if past_kv is not None:
                # When `past_kv` is provided, we're doing incremental decoding and `q.shape[2] == 1`: q only contains
                # the query for the last token. scaled_dot_product_attention interprets this as the first token in the
                # sequence, so if is_causal=True it will mask out all attention from it. This is not what we want, so 
                # to work around this we set is_causal=False.
                is_causal = False
            else:
                is_causal = True

            y = torch.nn.functional.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout, is_causal=is_causal)
        else:
            # manual implementation of attention
            att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
            att = att.masked_fill(self.bias[:,:,FULL_T-T:FULL_T,:FULL_T] == 0, float('-inf'))
            att = F.softmax(att, dim=-1)
            att = self.attn_dropout(att)
            y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
        y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side

        # output projection
        y = self.resid_dropout(self.c_proj(y))
        return (y, present)

class MLP(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.c_fc    = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
        self.c_proj  = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
        self.dropout = nn.Dropout(config.dropout)
        self.gelu = nn.GELU()

    def forward(self, x):
        x = self.c_fc(x)
        x = self.gelu(x)
        x = self.c_proj(x)
        x = self.dropout(x)
        return x

class Block(nn.Module):

    def __init__(self, config, layer_idx):
        super().__init__()
        self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
        self.attn = CausalSelfAttention(config)
        self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
        self.mlp = MLP(config)
        self.layer_idx = layer_idx

    def forward(self, x, past_kv=None, use_cache=False):
        attn_output, prev_kvs = self.attn(self.ln_1(x), past_kv=past_kv, use_cache=use_cache)
        x = x + attn_output
        x = x + self.mlp(self.ln_2(x))
        return (x, prev_kvs)

@dataclass
class GPTConfig:
    block_size: int = 1024
    input_vocab_size: int = 10_048
    output_vocab_size: int = 10_048
    n_layer: int = 12
    n_head: int = 12
    n_embd: int = 768
    dropout: float = 0.0
    bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster

class GPT(nn.Module):

    def __init__(self, config):
        super().__init__()
        assert config.input_vocab_size is not None
        assert config.output_vocab_size is not None
        assert config.block_size is not None
        self.config = config

        self.transformer = nn.ModuleDict(dict(
            wte = nn.Embedding(config.input_vocab_size, config.n_embd),
            wpe = nn.Embedding(config.block_size, config.n_embd),
            drop = nn.Dropout(config.dropout),
            h = nn.ModuleList([Block(config, idx) for idx in range(config.n_layer)]),
            ln_f = LayerNorm(config.n_embd, bias=config.bias),
        ))
        self.lm_head = nn.Linear(config.n_embd, config.output_vocab_size, bias=False)

    def get_num_params(self, non_embedding=True):
        """
        Return the number of parameters in the model.
        For non-embedding count (default), the position embeddings get subtracted.
        The token embeddings would too, except due to the parameter sharing these
        params are actually used as weights in the final layer, so we include them.
        """
        n_params = sum(p.numel() for p in self.parameters())
        if non_embedding:
            n_params -= self.transformer.wte.weight.numel()
            n_params -= self.transformer.wpe.weight.numel()
        return n_params

    def forward(self, idx, merge_context=False, past_kv=None, position_ids=None, use_cache=False):
        device = idx.device
        b, t = idx.size()
        if past_kv is not None:
            assert t == 1
            tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
        else:
            if merge_context:
                assert(idx.shape[1] >= 256+256+1)
                t = idx.shape[1] - 256
            else:
                assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"

            # forward the GPT model itself
            if merge_context:
                tok_emb = torch.cat([
                    self.transformer.wte(idx[:,:256]) + self.transformer.wte(idx[:,256:256+256]),
                    self.transformer.wte(idx[:,256+256:])
                ], dim=1)
            else:
                tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)

        if past_kv is None:
            past_length = 0
            past_kv = tuple([None] * len(self.transformer.h))
        else:
            past_length = past_kv[0][0].size(-2)

        if position_ids is None:
            position_ids = torch.arange(past_length, t + past_length, dtype=torch.long, device=device)
            position_ids = position_ids.unsqueeze(0) # shape (1, t)
            assert position_ids.shape == (1, t)

        pos_emb = self.transformer.wpe(position_ids) # position embeddings of shape (1, t, n_embd)

        x = self.transformer.drop(tok_emb + pos_emb)

        new_kv = () if use_cache else None

        for i, (block, past_layer_kv) in enumerate(zip(self.transformer.h, past_kv)):
            x, kv = block(x, past_kv=past_layer_kv, use_cache=use_cache)

            if use_cache:
                new_kv = new_kv + (kv,)

        x = self.transformer.ln_f(x)

        # inference-time mini-optimization: only forward the lm_head on the very last position
        logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim

        return (logits, new_kv)


================================================
FILE: bark/model_fine.py
================================================
"""
Much of this code is adapted from Andrej Karpathy's NanoGPT
(https://github.com/karpathy/nanoGPT)
"""
from dataclasses import dataclass
import math

import torch
import torch.nn as nn
from torch.nn import functional as F

from .model import GPT, GPTConfig, MLP


class NonCausalSelfAttention(nn.Module):
    def __init__(self, config):
        super().__init__()
        assert config.n_embd % config.n_head == 0
        # key, query, value projections for all heads, but in a batch
        self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
        # output projection
        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
        # regularization
        self.attn_dropout = nn.Dropout(config.dropout)
        self.resid_dropout = nn.Dropout(config.dropout)
        self.n_head = config.n_head
        self.n_embd = config.n_embd
        self.dropout = config.dropout
        # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
        self.flash = (
            hasattr(torch.nn.functional, "scaled_dot_product_attention")
        )

    def forward(self, x):
        B, T, C = x.size()  # batch size, sequence length, embedding dimensionality (n_embd)

        # calculate query, key, values for all heads in batch and move head forward to be the batch dim
        q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
        k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)  # (B, nh, T, hs)
        q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)  # (B, nh, T, hs)
        v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)  # (B, nh, T, hs)

        # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
        if self.flash:
            # efficient attention using Flash Attention CUDA kernels
            y = torch.nn.functional.scaled_dot_product_attention(
                q, k, v, attn_mask=None, dropout_p=self.dropout, is_causal=False
            )
        else:
            # manual implementation of attention
            att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
            att = F.softmax(att, dim=-1)
            att = self.attn_dropout(att)
            y = att @ v  # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
        y = (
            y.transpose(1, 2).contiguous().view(B, T, C)
        )  # re-assemble all head outputs side by side

        # output projection
        y = self.resid_dropout(self.c_proj(y))
        return y


class FineBlock(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.ln_1 = nn.LayerNorm(config.n_embd)
        self.attn = NonCausalSelfAttention(config)
        self.ln_2 = nn.LayerNorm(config.n_embd)
        self.mlp = MLP(config)

    def forward(self, x):
        x = x + self.attn(self.ln_1(x))
        x = x + self.mlp(self.ln_2(x))
        return x


class FineGPT(GPT):
    def __init__(self, config):
        super().__init__(config)
        del self.lm_head
        self.config = config
        self.n_codes_total = config.n_codes_total
        self.transformer = nn.ModuleDict(
            dict(
                wtes=nn.ModuleList(
                    [
                        nn.Embedding(config.input_vocab_size, config.n_embd)
                        for _ in range(config.n_codes_total)
                    ]
                ),
                wpe=nn.Embedding(config.block_size, config.n_embd),
                drop=nn.Dropout(config.dropout),
                h=nn.ModuleList([FineBlock(config) for _ in range(config.n_layer)]),
                ln_f=nn.LayerNorm(config.n_embd),
            )
        )
        self.lm_heads = nn.ModuleList(
            [
                nn.Linear(config.n_embd, config.output_vocab_size, bias=False)
                for _ in range(config.n_codes_given, self.n_codes_total)
            ]
        )
        for i in range(self.n_codes_total - config.n_codes_given):
            self.transformer.wtes[i + 1].weight = self.lm_heads[i].weight

    def forward(self, pred_idx, idx):
        device = idx.device
        b, t, codes = idx.size()
        assert (
            t <= self.config.block_size
        ), f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
        assert pred_idx > 0, "cannot predict 0th codebook"
        assert codes == self.n_codes_total, (b, t, codes)
        pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0)  # shape (1, t)

        # forward the GPT model itself
        tok_embs = [
            wte(idx[:, :, i]).unsqueeze(-1) for i, wte in enumerate(self.transformer.wtes)
        ]  # token embeddings of shape (b, t, n_embd)
        tok_emb = torch.cat(tok_embs, dim=-1)
        pos_emb = self.transformer.wpe(pos)  # position embeddings of shape (1, t, n_embd)
        x = tok_emb[:, :, :, : pred_idx + 1].sum(dim=-1)
        x = self.transformer.drop(x + pos_emb)
        for block in self.transformer.h:
            x = block(x)
        x = self.transformer.ln_f(x)
        logits = self.lm_heads[pred_idx - self.config.n_codes_given](x)
        return logits

    def get_num_params(self, non_embedding=True):
        """
        Return the number of parameters in the model.
        For non-embedding count (default), the position embeddings get subtracted.
        The token embeddings would too, except due to the parameter sharing these
        params are actually used as weights in the final layer, so we include them.
        """
        n_params = sum(p.numel() for p in self.parameters())
        if non_embedding:
            for wte in self.transformer.wtes:
                n_params -= wte.weight.numel()
            n_params -= self.transformer.wpe.weight.numel()
        return n_params


@dataclass
class FineGPTConfig(GPTConfig):
    n_codes_total: int = 8
    n_codes_given: int = 1


================================================
FILE: model-card.md
================================================
# Model Card: Bark

This is the official codebase for running the text to audio model, from Suno.ai.

The following is additional information about the models released here. 

## Model Details

Bark is a series of three transformer models that turn text into audio.
### Text to semantic tokens
 - Input: text, tokenized with [BERT tokenizer from Hugging Face](https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertTokenizer)
 - Output: semantic tokens that encode the audio to be generated

### Semantic to coarse tokens
 - Input: semantic tokens
 - Output: tokens from the first two codebooks of the [EnCodec Codec](https://github.com/facebookresearch/encodec) from facebook

### Coarse to fine tokens
 - Input: the first two codebooks from EnCodec
 - Output: 8 codebooks from EnCodec

### Architecture
|           Model           | Parameters | Attention  | Output Vocab size |  
|:-------------------------:|:----------:|------------|:-----------------:|
|  Text to semantic tokens  |    80 M    | Causal     |       10,000      |
| Semantic to coarse tokens |    80 M    | Causal     |     2x 1,024      |
|   Coarse to fine tokens   |    80 M    | Non-causal |     6x 1,024      |


### Release date
April 2023

## Broader Implications
We anticipate that this model's text to audio capabilities can be used to improve accessbility tools in a variety of languages. 
Straightforward improvements will allow models to run faster than realtime, rendering them useful for applications such as virtual assistants. 
 
While we hope that this release will enable users to express their creativity and build applications that are a force
for good, we acknowledge that any text to audio model has the potential for dual use. While it is not straightforward
to voice clone known people with Bark, they can still be used for nefarious purposes. To further reduce the chances of unintended use of Bark, 
we also release a simple classifier to detect Bark-generated audio with high accuracy (see notebooks section of the main repository). 


================================================
FILE: notebooks/fake_classifier.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e330c1de",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torchaudio\n",
    "from transformers import HubertModel\n",
    "from sklearn.metrics import PrecisionRecallDisplay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ac3dd88",
   "metadata": {},
   "outputs": [],
   "source": [
    "# use hubert from HF for feature embedding\n",
    "model = HubertModel.from_pretrained(\"facebook/hubert-base-ls960\")\n",
    "arr, sr = torchaudio.load(\"my_audio.wav\")\n",
    "if sr != 16_000:\n",
    "    arr = torchaudio.functional.resample(arr, sr, 16_000)\n",
    "# use intermediate layer\n",
    "hidden_state = model(arr[None], output_hidden_states=True).hidden_states[6]\n",
    "# take mean over time\n",
    "feats = hidden_state.detach().cpu().numpy().squeeze().mean(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03a602e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load sk-learn classifier from here: https://dl.suno-models.io/bark/models/v0/classifier.pkl\n",
    "with open(\"classifier.pkl\", \"rb\") as f:\n",
    "    clf = pickle.load(f)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e423794",
   "metadata": {},
   "source": [
    "### Precision-recall curve on test set"
   ]
  },
  {
   "attachments": {
    "image.png": {
     "image/png": "iVBORw0KGgoAAAANSUhEUgAAAjcAAAHFCAIAAACB+E92AAAMPmlDQ1BJQ0MgUHJvZmlsZQAASImVVwdYU8kWnltSIbQAAlJCb4JIDSAlhBZAercRkgChxBgIKnZkUcG1oGIBG7oqothpdsTOotj7YkFFWRcLduVNCui6r3xvvm/u/PefM/85c+7MvXcAUD/OFYtzUQ0A8kQFktiQAEZySiqD9BTggAyogAKMuLx8MSs6OgLAMtj+vby7DhBZe8VBpvXP/v9aNPmCfB4ASDTE6fx8Xh7EBwDAq3liSQEARBlv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sp37TpxjWivZ9yCULZWaf5lquwiIgAhcIYDl9NCNxdkomUUFC+XM+NjUFUTWGbaAf9vWLp68RpVU6soT0iECIiACqZzAsHv/f3yPDUecKDCqOtYrlZglep25JSCsEb8EQNMtIiACIhCxBFjHfe2gxn8MuLNv0wqmkY3fWsT3VcnVYKlUcpFXuSIgAiIQpgRYEhCHwGZVi5j68fXvoVMXkquuUqnkIq9yRUAERCCsCbCu0vbXmrFwe/LWUiqVvPxVugiIgAiIgD8CUil/dHRNBERABEQgeQnIxy95+at0ERABEQhrAgdOXpmRajb651L5sjapUuiFu/7fpSLJKi1bKslQqyAREAERSMEEth0+8/4v25O+AVKppGeuEkVABEQgxRCY0qFW/XL52K2RGl/m/5L80IhfkiNXgSIgAiKQcgjcXqEg/+0+dja5qixbKrnIq1wREAEREIHABKRSgRkphQiIgAiIQHIRkEolF3mVKwIiIAIiEJiAVCowI6UQAREQARFILgJSqeQir3JFQAREQAQCE5BKBWakFCIgAiKQyglc3cv3X+ejYx+YuCSJV56VSqXy356aLwIiIAKBCbCdh0n02/Zjv249EviG4KWQSgWPpXISAREQgQglUChnprfbVDeNS+I95qVSEfqbUrNEQAREIKgEWlYvWq9s3qBm6SozqZQrTEokAiIgAiKQLASkUsmCXYWKgAiIgAi4IiCVcoVJiURABERABJKFgFQqWbCrUBEQAREQAVcEpFKuMCmRCIiACIhAshCQSiULdhUqAiIgAiLgioBUyhUmJRIBERABEUgWAlKpZMGuQkVABERABFwRkEq5wqREIiACIiACyUJAKpUs2FWoCIiACIiAKwJSKVeYlEgEREAERCBZCEilkgW7ChUBERABEXBFQCrlCpMSiYAIiIAIJAsBqVSyYFehIiACIiACrghIpVxhUiIREAEREIFkIRBylRo/fnypUqUyZcpUs2bNxYsX+2zkuHHjKlasmDlz5muvvfbDDz/0mUaRIiACIiACqZBAupC2efr06d27d0eo6tWrN2nSpCZNmqxbt6548eLOQidMmNCnT5933333hhtuWL58+eOPP547d+7mzZs70ygsAiIgAiKQOgmE1pYaO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UCk/eZ05c2bRokV+EuiSCIiACIhAJBH4pfftBbJnTOIWJVyl8KFg2b0krq6KEwEREAERSC4CRXNl7tesYhKXnnCVSuKKqjgREAEREIFUSCCAjx9E8uTJ45MLa5n7jFekCIiACIiACASLQGCVunDhwlNPPXXdddd5FIlr36BBgzwidSoCIiACIiACQSQQWKWqV6/OV73t27f3KHX16tVSKQ8mOhUBERABEQgugcDzUs2aNWPJCe9SGQls166dd7xiREAEREAERCBYBALbUn379vVZGAbW+++/7/OSIkVABERABEQgKAQC21JBKUaZiIAIiIAIiEACCEilEgBNt4iACIiACCQRAalUEoFWMSIgAiIgAgkgIJVKADTdIgIiIAIikEQEpFJJBFrFiIAIiIAIJICAVCoB0HSLCIiACIhAEhGIh0o99thj/fr1s/XCQ50Ye6qACIiACIiACASdQODvpWyR27Zti42Ntad79uzZtWuXPVVABERABERABIJOIB4q9eOPPzqL/+CDD5ynCouACIiACIhA0AnEY8Qv6GUrQxEQAREQARHwTyCALfXVV1/5v79Fixb+E+iqCIiACIiACCSYQACVatWqlZ+s06RJo12m/PDRJREQAREQgUQSCKBSTneJRJak20VABERABEQgvgTiPS91/vz5+Jah9CIgAiIgAiKQMAJuVYqRvVdeeaVo0aLZsmXbunUrhfXv33/y5MkJK1V3iYAIiIAIiIAbAm5VasiQIVOnTn399dczZMhg8mWP+ffee89NGUojAiIgAiIgAgkj4FalPvzww3feeadt27ZRUVGmpKpVq27YsCFhpeouERABERABEXBDwK1KsdJE2bJlnTniWBEdHe2MUVgEREAEREAEgkvArUpVrlx58eLFzrI///zzGjVqOGMUFgEREAEREIHgEgjgiW4LGzhw4KOPPopFhQk1c+bMjRs3MgY4e/Zsm0ABERABERABEQg6Abe2VPPmzadPnz5nzhy+5B0wYMD69eu//vrrO++8M+gVUoYiIAIiIAIiYAm4taW4ofHVw96pgAiIgAiIgAiEmkA8VIqqrFixAisKc6pixYo1a9YMdeWUvwiIgAiIQCon4Faldu/e/dBDD/3yyy+5cuUC2fHjx+vWrfvJJ58UK1YslRNU80VABERABEJHwO28FNvy4neOIXX06kHg8uXLnTp1Cl3NlLMIiIAIiIAIuFUp3NAnTJhw7bXXGmQExowZ4+GbLpoiIAIiIAKRTeBC9JUd25dsOTJt2c6kaalblSpevLjHN7yXLl1iWb+kqaVKEQEREAERCAcCS7cdMdXoO2vNoVMXkqBKblWKFfyeffZZvCcY6KNaBLp16/bmm28mQRVVhAiIgAiIQJgQ6HZHOVuT89ExNhy6QBqjOnEVkDt3bjz6zNUzZ85gP6VLd8XhwgSyZs3KLFVc94Yu/uTJkzlz5jxx4kSOHDlCV4pyFgEREAER8EmgQv+556NjF7/QoFieLD4TuI8M2J8H8PF766233BemlCIgAiIgAiIQXAIBVKp9+/bBLU+5iYAIiIAIiIB7AgFUyjujc+fOOd0oNObmjUgxIiACIiACwSLg1nuCSalnnnmmQIEC7NXLZJU9glUP5SMCIiACIiAC3gTcqtQLL7ywYMGC8ePHZ8yYkS16Bw0aVKRIEZZF985RMSIgAiIgAiIQLAJuR/xYAR1Nuu2221iEon79+uyIWKJEiY8//pjde4NVFeUjAiIgAiIgAh4E3NpSeJyXKlWKm5mIMt7nN99886JFizyy06kIiIAIiIAIBJGAW5UqXbr09u3bKbhSpUqfffYZAawrs/JsEGujrERABERABETAScCtSnXs2HH16tXc2adPHzM71aNHj169ejnzUlgEREAEREAEgkvArUqhSV27dqXsBg0abNiwgT07Vq1axSJJAWuDpDFUmClTJvajimt1Wua3qlWrliVLlsKFCyOHR478/zpRATNXAhEQAREQgcgm4FalnBRYefbee+9FV5yRPsNsQt+9e/d+/fr9/vvv+Fw0adJk586dHil//vnndu3asQnIX3/99fnnn//222+dO3f2SKNTERABERCB1EkggI/f6NGj/XMxBlZcaUaOHIn8GNVhsaVvv/2W7T+GDRvmTL906dKSJUuafLC6nnzySVa2dSZQWAREQAREINUSCKBSo0aN8oOGhWj9qNTFixdXrlzZu3dvm0OjRo2WLFliT02APX8xtubMmYOldfDgwS+++KJZs2YeaTi9cPUw8axO6J1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AsBYtQ4e+H34T3foYhragyFwEREAERCB8C89cdMJV56cu1Ia2VW5VKly7d3XffjWsfu2+wN/yOHTvwpChTpkxIK6fMRUAEREAEwpPAoBaVTcXOR8eEtIbx8J4w9WBqiqWSjh07hlCx0nlIK6fMRUAEREAEwpNA+7olbyiZp+noxaGunltbinqwERS2VNOmTdlWY9SoUa1atVq7NrSGXqgbr/xFQAREQATCnIBbW+qhhx76+uuvMaQeeOCBn376yXszwzBvp6onAiIgAiKQEgm4VSmWnMB7grE+JqhSYjtVZxEQAREQgZRIwK3kTJs2LSU2T3UWAREQARFI0QQCqNTo0aOfeOKJTJkyEfDZTjaA9xmvSBEQAREQARFIPIEAKoWXRNu2bVEpAt6FMQwolfLGohgREAEREIFgEQigUtu2bTMl2UCwClY+IiACIiACIhCQgFtP9MGDB+OJ7szu3LlzRDpjFBYBERABERCB4BJwq1KDBg06ffq0s2xEi0hnjMIiIAIiIAIiEFwCblXq8uXLzEI5y169enWePP+/XaMzXmEREAEREAERCBaBAPNSFJM7d270iaN8+fL8awqOiYnBtOrSpUuw6qF8REAEREAERMCbQGCVYm1ZDKnHHnuM8b2cOXOaLDJkyFCyZMk6dep456gYERABERABEQgWgcAq1b59eworVaoUqyKlT58+WAUrHxEQAREQAREISCCASp08eTJHjhzkUqNGDZz6ODxyNFc9InUqAiIgAiIgAkEhEEClmJRi/0N26c2VK5edlDIFG38KJqiCUg9lIgIiIAIiIALeBAKo1IIFC4wj348//uh9s2JEQAREQAREIKQEAqjUrbfeaoq3gZDWRpmLgAiIgAiIgJOA2++l5s2b9/PPP5s7x40bV7169Ycffpgde515KSwCIiACIiACwSXgVqV69eqFJwVlr1mzpmfPnuzYu3XrVgLBrY1yEwEREAEREAEngQAjfjYpq81WqlSJ0xkzZjRv3nzo0KGrVq1Cq2wCBURABERABEQg6ATc2lJ8xmtWm/3+++8bNWpEPfCqMNZV0OukDEVABERABETAEHBrS918882M79WrV2/58uVsLc/NmzZtuuaaa8RRBERABERABEJHwK0tNXbs2HTp0n3xxRcTJkwoWrQoFZo7d+5dd90VupopZxEQAREQARFwa0sVL1589uzZTl4+d+91JlBYBERABERABBJJwK1KUQzLTHz55Zfr169nEYqKFSu2bNkyKioqkcXrdhEQAREQARHwQ8CtSm3evBmPvj179lx77bWsjcSkVLFixb755psyZcr4yV2XREAEREAERCAxBNzOS3Xt2hVB2rVrFw7ov//++86dO1klncjElK17RUAEREAERMA/Abe21MKFC5cuXWo3582bN+9rr72Gy5//3HVVBERABERABBJDwK0tlTFjxlOnTjlLYq9ePqJyxigsAiIgAiIgAsEl4Fal7r777ieeeGLZsmVMSnFgV7GdfIsWLYJbG+UmAiIgAiIgAk4CblVq9OjRzEuxhXymqwdjfWXLln377bedeSksAiIgAiIgAsEl4HZeil0Q//vf/+Lphyc6thRr+qFSwa2KchMBERABERABDwKBVSo2NnbEiBF8KRUdHd2wYcMBAwZgTXnkolMREAEREAERCAWBwCN+w4cP7927d9asWQsXLjxy5Eh5n4fiMShPERABERABnwQCq9TUqVPHjBnz3XffMeKHRfXhhx8y4uczL0WKgAiIgAiIQHAJBFapHTt24OBnSm3cuDEStXfv3uBWQrmJgAiIgAiIgE8CgVXq4sWLmTNnNjezgh/fSF24cMFnXooUAREQAREQgeASCOw9QXn9+/fPkiWLKRjRGjJkSM6cOc0pM1XBrZByEwEREAEREAFLILBK3XLLLRs3brQ31K1bd+vWreYU08rGKyACIiACIiACQScQWKV++umnoJeqDEVABERABETADYHA81JuclEaERABERABEQgFgQAqxcLnZ86c8VMwK/uxy5SfBLokAiIgAiIgAgkmEECl1q1bV6JEiaeeemru3LmHDh0yxVy6dOnPP/8cP348c1Rt2rTJkSNHgovXjSIgAiIgAiLgh0AAleIb3gULFrBIUtu2bQsVKoQbevbs2dnFo0aNGlOmTOnQocOGDRvq16/vpwDEjP0SWVSpZs2aixcv9k5JJnhhOI/KlSt7J1OMCIiACIhAKiQQ2HuiatWqkyZNmjhxIvbT9u3bz507ly9fvurVq/NvQF7Tp0/v3r07QsU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C/qFonLKUwREQAREIJUTcKtSt99+e7du3fbu3Wt4sVZsjx497rjjjlSOT80XAREQAREIKQG3KjV27NhTp07xSW+ZMmXKli1bqlQpTseMGRPSyilzERABERCBVE7A7bwU2+OyzAQbRG3YsAEfP+alGjZsmMrZqfkiIAIiIAKhJuBWpUw97rx6hLpOyl8EREAEREAEDIEAKjV69OgnnngiU6ZMBHwikzO6TyyKFAEREAERCAqBACo1atSotm3bolIEvMtjEQqplDcWxYiACIiACASLQACV2rZtmynJBoJVsPIRAREQAREQgYAE3Pr4OTOKiYn5448/WIHCGamwCIiACIiACASdgFuV6t69++TJkykeibrllluuv/56vP5Y1i/oFVKGIiACIiACImAJuFWpL774olq1atz29ddfb9++HX90dKtfv342IwVEQAREQAREIOgE3KrU4cOHCxUqRPFz5sx54IEHypcv36lTpzVr1gS9QspQBERABERABCwBtyrFXvLr1q1juI9lZ833vGfPno2KirIZKSACIiACIiACQScQwMfPltexY8cHH3ywcOHCeJ/zaS/xy5Ytq1Chgk2ggAiIgAiIgAgEnYBblXr55ZerVKmya9cuhvsyZsxIPTCkevfuHfQKKUMREAEREAERsATcqhQ33H///fY2Au3bt3eeKiwCIiACIiACQScQQKW0QlLQiStDERABERAB9wQCqJRWSHKPUilFQAREQASCTiCAStmFkWwg6DVQhiIgAiIgAiIQFwG3nuhx3a94ERABERABEQgdAbcqhevEa6+95qzHG2+8gb+fM0ZhERABERABEQguAbcqtXDhwmbNmjnLvuuuuxYtWuSMUVgEREAEREAEgkvArUqdPn06Q4YMzrLTp09/8uRJZ4zCIiACIiACIhBcAm5Vik96p0+f7iz7008/rVSpkjNGYREQAREQAREILoEAPn62sP79+993331btmy5/fbbifzhhx8++eSTzz//3CZQQAREQAREQASCTsCtSrVo0eLLL78cOnQoW3hkzpy5atWq33///a233hr0CilDERABERABEbAE3KoUN+A94eFAYXNRQAREQAREQARCQcDtvBRlHz9+/L333uvbt+/Ro0c5XbVq1Z49e0JRJ+UpAiIgAiIgAoaAW1vqzz//ZFupnDlzslFv586d8+TJM2vWrB07dnz44YdCKQIiIAIiIAIhIuDWlurZs2eHDh3+/vvvTJkymao0adJE30uF6KkoWxEQAREQAUPArUr99ttvTz75pJNa0aJF9+/f74xRWAREQAREQASCS8CtSmFCeXzDu3Hjxvz58we3NspNBERABERABJwE3KpUy5YtBw8eHB0dzc1sKr9z50426uULKmdeCouACIiACIhAcAm4Vak333zz0KFDBQoUOHfuHJ9JlS1bNnv27EOGDAlubZSbCIiACIiACDgJuPXxy5Ejx88//7xgwQIc0GNjY6+//npc/pwZKSwCIiACIiACQSfgSqUuXbrEvNQff/zB8khmhaSg10MZioAIiIAIiIA3AVcjfunSpStRokRMTIz3/YoRAREQAREQgdARcKVSFP/SSy/16dPHrDoRutooZxEQAREQARFwEnA14scNo0eP3rx5c5EiRTCqsmbNarNgmsqGFRABERABERCB4BJwq1J4ouOAHtyylZsIiIAIiIAI+CfgVqVefvll/xnpqgiIgAiIgAgEnUDgeamzZ8/++9//Zj0kPpZ6+OGHDx8+HPRKKEMREAEREAER8EkgsEoNHDhw6tSp7CzVpk2b+fPnP/XUUz4zUqQIiIAIiIAIBJ1A4BG/mTNnTp48GYmi7EceeaRevXq4pEdFRQW9KspQBERABERABDwIBLaldu3aVb9+fXPbjTfeyLdTe/fu9chFpyIgAiIgAiIQCgKBVQrLKUOGDLZsVIqlKOypAiIgAiIgAiIQOgKBVery5cvsf3jvP8f58+e7dOnyz9m9AWs2fvz4UqVKscBSzZo1Fy9e7DP9hQsX+vXrx5dYGTNmLFOmzJQpU3wmU6QIiIAIiEBqIxB4Xqp9+/ZOKExNOU/9h6dPn969e3eEitmsSZMmsb3vunXrihcv7nHXgw8+eODAAWa/WGr94MGDstU8+OhUBERABFItgTSYSqFrfO3atVk9fcKECaaIihUrtmrVatiwYc4S582bh2vG1q1b8+TJ44z3E2Y/xpw5c544cYKV2v0k0yUREAEREIHQEVi392TT0YsLZM+4vF/DBJcSsD8PPOKX4LIvXry4cuXKRo0a2RwIL1myxJ6awFdffVWrVq3XX3+dT7LKly///PPPs4WVRxqdioAIiIAIpE4CgUf8EsyF73/xvChYsKDNgfD+/fvtqQlgRbFzFRNXs2bN4pann36aNW29p6aYu+Iwt3jsbe+RoU5FQAREQAQihkAIbSnDyLn6H6OLzlOTgD0Vifz4449xc2/atOnIkSP5iNjbnGKckFE+cxQrVixiHoAaIgIiIAIi4IdACFUqX758fPzrNJ7wjHCaVqZahQsXZqwP+TGnzF0hZrt37/aoNPuGMBFlDj7h8riqUxEQAREQgYgkEEKV4isrvM9ZVMmCI1y3bl17agK4//GZ8OnTp83ppk2b0qZNe80113gkw0kdXwl7eFzVqQiIgAiIQEQSCKFKwatnz57vvfcek0zr16/v0aPHzp07+daKeAyjdu3aGaCsYJs3b96OHTvipL5o0aJevXo99thjmTNnjkjcapQIiIAIiEC8CITQe4J6tG7d+siRI4MHD963b1+VKlXmzJnDp7vEc4pimYpmy5YNG+vZZ5/F0w+54tupV199NV5tUGIREAEREIFIJRDa76VCRC2gf32IylW2IiACIiAClkCK/17KtkQBERABERABEUgYgdDOSyWsTrpLBERABERABAwBqZR+CSIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNRMBERABEZBK6TcgAiIgAiIQvgSkUuH7bFQzERABERABqZR+AyIgAiIgAuFLQCoVvs9GNR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nDHOMC3FfmJPd4bv0GlziX2oUUrc5HAydCb2E4YDY4yPPPIIaZAfppcY1rPply5d6gyzeTzKRNup2MGDB+vXr2+vBjHADBnTjZUrVw5insoqpROQ90RKf4KptP58UURfhq8E7X/55Zf5gAmnA4YB16xZwwQJU1bE46SA3x2fyjLbj4yhGb/++ivxmFDM7jAeiF8D3+4Ya8w9R0bqUAhvc8ojBxzlGYpkWJKxr//+97/IKlLEqCCWE9VesWIFw4xUgxFLpzaYTHCEIxnyefjwYe/qMaODgyJaRTLG5cwtnGLkoTpoD1NleAkys8UAo0etnKdwMFYdfhxMp+3fv995lcpT4Y0bN+J0h81HblxlrI+C8NCj5pTy22+/DR8+fM6cOc4bCTOEiLPl8uXLPeLNKeQ5eD+g7QTWrVtnk1F59C8uI9gmUyB1EeBdT4cIhD8Bp3OBqS2jW9gc9PWcEq5evTqn5rta+lCTho7+vvvuw7zA9c54ohNP98qAIV0hBtDYsWOd0/huvCfIAW3gsx5TBLnRZRjvCRNj/8ULAB8/aoVY4oCA4x+X6JTROQa18FCn07eOG84Gog0UYTpr8vd2eWDQkkIxxWxZBHAIRD/QKnIuXbo0E3U4IzgTEHZmhV8JqsZ4HRYYvubc63TfQGW7dOkCOpDiRo9YmqwYFaRcBBKjh3ZhkuIqwiWn94RhQlnmFo9/PXpYmNsEAEEU7akCIgCBNPzP40ejUxEQAf8EsB5YzofhKWwj/yl11T0BnBVRXzTPzLS5v1EpI5uA5qUi+/mqdSEhgNM2sziMazk/ZgpJSakpU3wvMcgkUanpmbtqq2wpV5iUSAREQAREIFkIaLwiWbCrUBEQAREQAVcEpFKuMCmRCIiACIhAshCQSiULdhUqAiIgAiLgioBUyhUmJRIBERABEUgWAlKpZMGuQkVABERABFwRkEq5wqREIiACIiACyUJAKpUs2FWoCIiACIiAKwJSKVeYlEgEREAERCBZCEilkgW7ChUBERABEXBF4P8AuRwuVEedncgAAAAASUVORK5CYII="
    }
   },
   "cell_type": "markdown",
   "id": "e1486424",
   "metadata": {},
   "source": [
    "![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "668856bf",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c87326bd",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "decdbf09",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.8.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}


================================================
FILE: notebooks/long_form_generation.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "39ea4bed",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
    "\n",
    "\n",
    "from IPython.display import Audio\n",
    "import nltk  # we'll use this to split into sentences\n",
    "import numpy as np\n",
    "\n",
    "from bark.generation import (\n",
    "    generate_text_semantic,\n",
    "    preload_models,\n",
    ")\n",
    "from bark.api import semantic_to_waveform\n",
    "from bark import generate_audio, SAMPLE_RATE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "776964b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "preload_models()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d03f4d2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "74a025a4",
   "metadata": {},
   "source": [
    "# Simple Long-Form Generation\n",
    "We split longer text into sentences using `nltk` and generate the sentences one by one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "57b06e2a",
   "metadata": {},
   "outputs": [],
   "source": [
    "script = \"\"\"\n",
    "Hey, have you heard about this new text-to-audio model called \"Bark\"? \n",
    "Apparently, it's the most realistic and natural-sounding text-to-audio model \n",
    "out there right now. People are saying it sounds just like a real person speaking. \n",
    "I think it uses advanced machine learning algorithms to analyze and understand the \n",
    "nuances of human speech, and then replicates those nuances in its own speech output. \n",
    "It's pretty impressive, and I bet it could be used for things like audiobooks or podcasts. \n",
    "In fact, I heard that some publishers are already starting to use Bark to create audiobooks. \n",
    "It would be like having your own personal voiceover artist. I really think Bark is going to \n",
    "be a game-changer in the world of text-to-audio technology.\n",
    "\"\"\".replace(\"\\n\", \" \").strip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "f747f804",
   "metadata": {},
   "outputs": [],
   "source": [
    "sentences = nltk.sent_tokenize(script)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "17400a9b",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:02<00:00, 43.03it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 17/17 [00:06<00:00,  2.45it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 22.73it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 33/33 [00:13<00:00,  2.52it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 66.30it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 11/11 [00:04<00:00,  2.46it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 20.99it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 35/35 [00:14<00:00,  2.46it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 25.63it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 29/29 [00:11<00:00,  2.50it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 23.90it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 30/30 [00:12<00:00,  2.46it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 53.24it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 14/14 [00:05<00:00,  2.51it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 50.63it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 15/15 [00:05<00:00,  2.57it/s]\n"
     ]
    }
   ],
   "source": [
    "SPEAKER = \"v2/en_speaker_6\"\n",
    "silence = np.zeros(int(0.25 * SAMPLE_RATE))  # quarter second of silence\n",
    "\n",
    "pieces = []\n",
    "for sentence in sentences:\n",
    "    audio_array = generate_audio(sentence, history_prompt=SPEAKER)\n",
    "    pieces += [audio_array, silence.copy()]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04cf77f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "Audio(np.concatenate(pieces), rate=SAMPLE_RATE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac2d4625",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "6d13249b",
   "metadata": {},
   "source": [
    "# $ \\\\ $"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdfc8bf5",
   "metadata": {},
   "source": [
    "# Advanced Long-Form Generation\n",
    "Somtimes Bark will hallucinate a little extra audio at the end of the prompt.\n",
    "We can solve this issue by lowering the threshold for bark to stop generating text. \n",
    "We use the `min_eos_p` kwarg in `generate_text_semantic`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "62807fd0",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:02<00:00, 38.05it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 18/18 [00:07<00:00,  2.46it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 32.28it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 21/21 [00:08<00:00,  2.54it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 55.78it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 14/14 [00:05<00:00,  2.57it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:06<00:00, 14.73it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 35/35 [00:14<00:00,  2.47it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:02<00:00, 40.29it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 18/18 [00:07<00:00,  2.56it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 32.92it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 20/20 [00:08<00:00,  2.47it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 68.87it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 12/12 [00:04<00:00,  2.62it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:02<00:00, 47.64it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 15/15 [00:06<00:00,  2.46it/s]\n"
     ]
    }
   ],
   "source": [
    "GEN_TEMP = 0.6\n",
    "SPEAKER = \"v2/en_speaker_6\"\n",
    "silence = np.zeros(int(0.25 * SAMPLE_RATE))  # quarter second of silence\n",
    "\n",
    "pieces = []\n",
    "for sentence in sentences:\n",
    "    semantic_tokens = generate_text_semantic(\n",
    "        sentence,\n",
    "        history_prompt=SPEAKER,\n",
    "        temp=GEN_TEMP,\n",
    "        min_eos_p=0.05,  # this controls how likely the generation is to end\n",
    "    )\n",
    "\n",
    "    audio_array = semantic_to_waveform(semantic_tokens, history_prompt=SPEAKER,)\n",
    "    pieces += [audio_array, silence.copy()]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "133fec46",
   "metadata": {},
   "outputs": [],
   "source": [
    "Audio(np.concatenate(pieces), rate=SAMPLE_RATE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6eee9f5a",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "be8e125e",
   "metadata": {},
   "source": [
    "# $ \\\\ $"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03a16c1b",
   "metadata": {},
   "source": [
    "# Make a Long-Form Dialog with Bark"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06c5eff8",
   "metadata": {},
   "source": [
    "### Step 1: Format a script and speaker lookup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "5238b297",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Samantha: Hey, have you heard about this new text-to-audio model called \"Bark\"?',\n",
       " \"John: No, I haven't. What's so special about it?\",\n",
       " \"Samantha: Well, apparently it's the most realistic and natural-sounding text-to-audio model out there right now. People are saying it sounds just like a real person speaking.\",\n",
       " 'John: Wow, that sounds amazing. How does it work?',\n",
       " 'Samantha: I think it uses advanced machine learning algorithms to analyze and understand the nuances of human speech, and then replicates those nuances in its own speech output.',\n",
       " \"John: That's pretty impressive. Do you think it could be used for things like audiobooks or podcasts?\",\n",
       " 'Samantha: Definitely! In fact, I heard that some publishers are already starting to use Bark to create audiobooks. And I bet it would be great for podcasts too.',\n",
       " 'John: I can imagine. It would be like having your own personal voiceover artist.',\n",
       " 'Samantha: Exactly! I think Bark is going to be a game-changer in the world of text-to-audio technology.']"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "speaker_lookup = {\"Samantha\": \"v2/en_speaker_9\", \"John\": \"v2/en_speaker_2\"}\n",
    "\n",
    "# Script generated by chat GPT\n",
    "script = \"\"\"\n",
    "Samantha: Hey, have you heard about this new text-to-audio model called \"Bark\"?\n",
    "\n",
    "John: No, I haven't. What's so special about it?\n",
    "\n",
    "Samantha: Well, apparently it's the most realistic and natural-sounding text-to-audio model out there right now. People are saying it sounds just like a real person speaking.\n",
    "\n",
    "John: Wow, that sounds amazing. How does it work?\n",
    "\n",
    "Samantha: I think it uses advanced machine learning algorithms to analyze and understand the nuances of human speech, and then replicates those nuances in its own speech output.\n",
    "\n",
    "John: That's pretty impressive. Do you think it could be used for things like audiobooks or podcasts?\n",
    "\n",
    "Samantha: Definitely! In fact, I heard that some publishers are already starting to use Bark to create audiobooks. And I bet it would be great for podcasts too.\n",
    "\n",
    "John: I can imagine. It would be like having your own personal voiceover artist.\n",
    "\n",
    "Samantha: Exactly! I think Bark is going to be a game-changer in the world of text-to-audio technology.\"\"\"\n",
    "script = script.strip().split(\"\\n\")\n",
    "script = [s.strip() for s in script if s]\n",
    "script"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee547efd",
   "metadata": {},
   "source": [
    "### Step 2: Generate the audio for every speaker turn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "203e5081",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:02<00:00, 34.03it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 22/22 [00:08<00:00,  2.55it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 71.58it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 11/11 [00:04<00:00,  2.65it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 22.75it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 33/33 [00:13<00:00,  2.53it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 70.76it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 11/11 [00:04<00:00,  2.63it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 20.46it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 36/36 [00:14<00:00,  2.47it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 20.18it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 37/37 [00:14<00:00,  2.51it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:04<00:00, 23.04it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 32/32 [00:12<00:00,  2.48it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 54.64it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 14/14 [00:05<00:00,  2.58it/s]\n",
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 31.71it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 24/24 [00:09<00:00,  2.56it/s]\n"
     ]
    }
   ],
   "source": [
    "pieces = []\n",
    "silence = np.zeros(int(0.5*SAMPLE_RATE))\n",
    "for line in script:\n",
    "    speaker, text = line.split(\": \")\n",
    "    audio_array = generate_audio(text, history_prompt=speaker_lookup[speaker], )\n",
    "    pieces += [audio_array, silence.copy()]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c54bada",
   "metadata": {},
   "source": [
    "### Step 3: Concatenate all of the audio and play it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27a56842",
   "metadata": {},
   "outputs": [],
   "source": [
    "Audio(np.concatenate(pieces), rate=SAMPLE_RATE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1bc5877",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}


================================================
FILE: notebooks/memory_profiling_bark.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "90641144",
   "metadata": {},
   "source": [
    "# Bark Memory Profiling\n",
    "Bark has two ways to reduce GPU memory: \n",
    " - Small models: a smaller version of the model. This can be set by using the environment variable `SUNO_USE_SMALL_MODELS`\n",
    " - offloading models to CPU: Holding only one model at a time on the GPU, and shuttling the models to the CPU in between generations. \n",
    "\n",
    "# $ \\\\ $\n",
    "## First, we'll use the most memory efficient configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "39ea4bed",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
    "os.environ[\"SUNO_USE_SMALL_MODELS\"] = \"1\"\n",
    "os.environ[\"SUNO_OFFLOAD_CPU\"] = \"1\"\n",
    "\n",
    "from bark.generation import (\n",
    "    generate_text_semantic,\n",
    "    preload_models,\n",
    ")\n",
    "from bark import generate_audio, SAMPLE_RATE\n",
    "\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "66b0c006",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 62.17it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████████| 10/10 [00:03<00:00,  2.74it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max memory usage = 2396MB\n"
     ]
    }
   ],
   "source": [
    "torch.cuda.reset_peak_memory_stats()\n",
    "preload_models()\n",
    "audio_array = generate_audio(\"madam I'm adam\", history_prompt=\"v2/en_speaker_5\")\n",
    "max_utilization = torch.cuda.max_memory_allocated()\n",
    "print(f\"max memory usage = {max_utilization / 1024 / 1024:.0f}MB\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9922dd2d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdbe578e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "213d1b5b",
   "metadata": {},
   "source": [
    "# Memory Profiling:\n",
    "We can profile the memory consumption of 4 scenarios\n",
    " - Small models, offloading to CPU\n",
    " - Large models, offloading to CPU\n",
    " - Small models, not offloading to CPU\n",
    " - Large models, not offloading to CPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "417d5e9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from bark.generation import (\n",
    "    generate_text_semantic,\n",
    "    preload_models,\n",
    "    models,\n",
    ")\n",
    "import bark.generation\n",
    "\n",
    "from bark.api import semantic_to_waveform\n",
    "from bark import generate_audio, SAMPLE_RATE\n",
    "\n",
    "import torch\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cd83b45d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Small models True, offloading to CPU: True\n",
      "\tmax memory usage = 967MB, time 4s\n",
      "\n",
      "Small models False, offloading to CPU: True\n",
      "\tmax memory usage = 2407MB, time 8s\n",
      "\n",
      "Small models True, offloading to CPU: False\n",
      "\tmax memory usage = 2970MB, time 3s\n",
      "\n",
      "Small models False, offloading to CPU: False\n",
      "\tmax memory usage = 7824MB, time 6s\n",
      "\n"
     ]
    }
   ],
   "source": [
    "global models\n",
    "\n",
    "for offload_models in (True, False):\n",
    "    # this setattr is needed to do on the fly\n",
    "    # the easier way to do this is with `os.environ[\"SUNO_OFFLOAD_CPU\"] = \"1\"`\n",
    "    setattr(bark.generation, \"OFFLOAD_CPU\", offload_models)\n",
    "    for use_small_models in (True, False):\n",
    "        models = {}\n",
    "        torch.cuda.empty_cache()\n",
    "        torch.cuda.reset_peak_memory_stats()\n",
    "        preload_models(\n",
    "            text_use_small=use_small_models,\n",
    "            coarse_use_small=use_small_models,\n",
    "            fine_use_small=use_small_models,\n",
    "            force_reload=True,\n",
    "        )\n",
    "        t0 = time.time()\n",
    "        audio_array = generate_audio(\"madam I'm adam\", history_prompt=\"v2/en_speaker_5\", silent=True)\n",
    "        dur = time.time() - t0\n",
    "        max_utilization = torch.cuda.max_memory_allocated()\n",
    "        print(f\"Small models {use_small_models}, offloading to CPU: {offload_models}\")\n",
    "        print(f\"\\tmax memory usage = {max_utilization / 1024 / 1024:.0f}MB, time {dur:.0f}s\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bfe5fa06",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}


================================================
FILE: notebooks/use_small_models_on_cpu.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6a682b61",
   "metadata": {},
   "source": [
    "# Benchmarking small models on CPU\n",
    " - We can enable small models with the `SUNO_USE_SMALL_MODELS` environment variable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9500dd93",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n",
    "os.environ[\"SUNO_USE_SMALL_MODELS\"] = \"1\"\n",
    "\n",
    "from IPython.display import Audio\n",
    "import numpy as np\n",
    "\n",
    "from bark import generate_audio, preload_models, SAMPLE_RATE\n",
    "\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4e3454b6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No GPU being used. Careful, inference might be very slow!\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 5.52 s, sys: 2.34 s, total: 7.86 s\n",
      "Wall time: 4.33 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "preload_models()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f6024e5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████| 100/100 [00:10<00:00,  9.89it/s]\n",
      "100%|██████████████████████████████████████████████████████████| 15/15 [00:43<00:00,  2.90s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "took 62s to generate 6s of audio\n"
     ]
    }
   ],
   "source": [
    "t0 = time.time()\n",
    "text = \"In the light of the moon, a little egg lay on a leaf\"\n",
    "audio_array = generate_audio(text)\n",
    "generation_duration_s = time.time() - t0\n",
    "audio_duration_s = audio_array.shape[0] / SAMPLE_RATE\n",
    "\n",
    "print(f\"took {generation_duration_s:.0f}s to generate {audio_duration_s:.0f}s of audio\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2dcce86c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.cpu_count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3046eddb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}


================================================
FILE: pyproject.toml
================================================
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "suno-bark"
version = "0.0.1a"
description = "Bark text to audio model"
readme = "README.md"
requires-python = ">=3.8"
authors =  [
    {name = "Suno Inc", email = "hello@suno.ai"},
]
# Apache 2.0
license = {file = "LICENSE"}

dependencies = [
    "boto3",
    "encodec",
    "funcy",
    "huggingface-hub>=0.14.1",
    "numpy",
    "scipy",
    "tokenizers",
    "torch",
    "tqdm",
    "transformers",
]

[project.urls]
source = "https://github.com/suno-ai/bark"

[project.optional-dependencies]
dev = [
    "bandit",
    "black",
    "codecov",
    "flake8",
    "hypothesis>=6.14,<7",
    "isort>=5.0.0,<6",
    "jupyter",
    "mypy",
    "nbconvert",
    "nbformat",
    "pydocstyle",
    "pylint",
    "pytest",
    "pytest-cov",
]

[tool.setuptools]
packages = ["bark"]

[tool.setuptools.package-data]
bark = ["assets/prompts/*.npz", "assets/prompts/v2/*.npz"]


[tool.black]
line-length = 100


================================================
FILE: setup.py
================================================
from setuptools import setup

setup()
Download .txt
gitextract_qrs7w3px/

├── .gitignore
├── LICENSE
├── README.md
├── bark/
│   ├── __init__.py
│   ├── __main__.py
│   ├── api.py
│   ├── assets/
│   │   └── prompts/
│   │       ├── announcer.npz
│   │       ├── de_speaker_0.npz
│   │       ├── de_speaker_1.npz
│   │       ├── de_speaker_2.npz
│   │       ├── de_speaker_3.npz
│   │       ├── de_speaker_4.npz
│   │       ├── de_speaker_5.npz
│   │       ├── de_speaker_6.npz
│   │       ├── de_speaker_7.npz
│   │       ├── de_speaker_8.npz
│   │       ├── de_speaker_9.npz
│   │       ├── en_speaker_0.npz
│   │       ├── en_speaker_1.npz
│   │       ├── en_speaker_2.npz
│   │       ├── en_speaker_3.npz
│   │       ├── en_speaker_4.npz
│   │       ├── en_speaker_5.npz
│   │       ├── en_speaker_6.npz
│   │       ├── en_speaker_7.npz
│   │       ├── en_speaker_8.npz
│   │       ├── en_speaker_9.npz
│   │       ├── es_speaker_0.npz
│   │       ├── es_speaker_1.npz
│   │       ├── es_speaker_2.npz
│   │       ├── es_speaker_3.npz
│   │       ├── es_speaker_4.npz
│   │       ├── es_speaker_5.npz
│   │       ├── es_speaker_6.npz
│   │       ├── es_speaker_7.npz
│   │       ├── es_speaker_8.npz
│   │       ├── es_speaker_9.npz
│   │       ├── fr_speaker_0.npz
│   │       ├── fr_speaker_1.npz
│   │       ├── fr_speaker_2.npz
│   │       ├── fr_speaker_3.npz
│   │       ├── fr_speaker_4.npz
│   │       ├── fr_speaker_5.npz
│   │       ├── fr_speaker_6.npz
│   │       ├── fr_speaker_7.npz
│   │       ├── fr_speaker_8.npz
│   │       ├── fr_speaker_9.npz
│   │       ├── hi_speaker_0.npz
│   │       ├── hi_speaker_1.npz
│   │       ├── hi_speaker_2.npz
│   │       ├── hi_speaker_3.npz
│   │       ├── hi_speaker_4.npz
│   │       ├── hi_speaker_5.npz
│   │       ├── hi_speaker_6.npz
│   │       ├── hi_speaker_7.npz
│   │       ├── hi_speaker_8.npz
│   │       ├── hi_speaker_9.npz
│   │       ├── it_speaker_0.npz
│   │       ├── it_speaker_1.npz
│   │       ├── it_speaker_2.npz
│   │       ├── it_speaker_3.npz
│   │       ├── it_speaker_4.npz
│   │       ├── it_speaker_5.npz
│   │       ├── it_speaker_6.npz
│   │       ├── it_speaker_7.npz
│   │       ├── it_speaker_8.npz
│   │       ├── it_speaker_9.npz
│   │       ├── ja_speaker_0.npz
│   │       ├── ja_speaker_1.npz
│   │       ├── ja_speaker_2.npz
│   │       ├── ja_speaker_3.npz
│   │       ├── ja_speaker_4.npz
│   │       ├── ja_speaker_5.npz
│   │       ├── ja_speaker_6.npz
│   │       ├── ja_speaker_7.npz
│   │       ├── ja_speaker_8.npz
│   │       ├── ja_speaker_9.npz
│   │       ├── ko_speaker_0.npz
│   │       ├── ko_speaker_1.npz
│   │       ├── ko_speaker_2.npz
│   │       ├── ko_speaker_3.npz
│   │       ├── ko_speaker_4.npz
│   │       ├── ko_speaker_5.npz
│   │       ├── ko_speaker_6.npz
│   │       ├── ko_speaker_7.npz
│   │       ├── ko_speaker_8.npz
│   │       ├── ko_speaker_9.npz
│   │       ├── pl_speaker_0.npz
│   │       ├── pl_speaker_1.npz
│   │       ├── pl_speaker_2.npz
│   │       ├── pl_speaker_3.npz
│   │       ├── pl_speaker_4.npz
│   │       ├── pl_speaker_5.npz
│   │       ├── pl_speaker_6.npz
│   │       ├── pl_speaker_7.npz
│   │       ├── pl_speaker_8.npz
│   │       ├── pl_speaker_9.npz
│   │       ├── pt_speaker_0.npz
│   │       ├── pt_speaker_1.npz
│   │       ├── pt_speaker_2.npz
│   │       ├── pt_speaker_3.npz
│   │       ├── pt_speaker_4.npz
│   │       ├── pt_speaker_5.npz
│   │       ├── pt_speaker_6.npz
│   │       ├── pt_speaker_7.npz
│   │       ├── pt_speaker_8.npz
│   │       ├── pt_speaker_9.npz
│   │       ├── readme.md
│   │       ├── ru_speaker_0.npz
│   │       ├── ru_speaker_1.npz
│   │       ├── ru_speaker_2.npz
│   │       ├── ru_speaker_3.npz
│   │       ├── ru_speaker_4.npz
│   │       ├── ru_speaker_5.npz
│   │       ├── ru_speaker_6.npz
│   │       ├── ru_speaker_7.npz
│   │       ├── ru_speaker_8.npz
│   │       ├── ru_speaker_9.npz
│   │       ├── speaker_0.npz
│   │       ├── speaker_1.npz
│   │       ├── speaker_2.npz
│   │       ├── speaker_3.npz
│   │       ├── speaker_4.npz
│   │       ├── speaker_5.npz
│   │       ├── speaker_6.npz
│   │       ├── speaker_7.npz
│   │       ├── speaker_8.npz
│   │       ├── speaker_9.npz
│   │       ├── tr_speaker_0.npz
│   │       ├── tr_speaker_1.npz
│   │       ├── tr_speaker_2.npz
│   │       ├── tr_speaker_3.npz
│   │       ├── tr_speaker_4.npz
│   │       ├── tr_speaker_5.npz
│   │       ├── tr_speaker_6.npz
│   │       ├── tr_speaker_7.npz
│   │       ├── tr_speaker_8.npz
│   │       ├── tr_speaker_9.npz
│   │       ├── v2/
│   │       │   ├── de_speaker_0.npz
│   │       │   ├── de_speaker_1.npz
│   │       │   ├── de_speaker_2.npz
│   │       │   ├── de_speaker_3.npz
│   │       │   ├── de_speaker_4.npz
│   │       │   ├── de_speaker_5.npz
│   │       │   ├── de_speaker_6.npz
│   │       │   ├── de_speaker_7.npz
│   │       │   ├── de_speaker_8.npz
│   │       │   ├── de_speaker_9.npz
│   │       │   ├── en_speaker_0.npz
│   │       │   ├── en_speaker_1.npz
│   │       │   ├── en_speaker_2.npz
│   │       │   ├── en_speaker_3.npz
│   │       │   ├── en_speaker_4.npz
│   │       │   ├── en_speaker_5.npz
│   │       │   ├── en_speaker_6.npz
│   │       │   ├── en_speaker_7.npz
│   │       │   ├── en_speaker_8.npz
│   │       │   ├── en_speaker_9.npz
│   │       │   ├── es_speaker_0.npz
│   │       │   ├── es_speaker_1.npz
│   │       │   ├── es_speaker_2.npz
│   │       │   ├── es_speaker_3.npz
│   │       │   ├── es_speaker_4.npz
│   │       │   ├── es_speaker_5.npz
│   │       │   ├── es_speaker_6.npz
│   │       │   ├── es_speaker_7.npz
│   │       │   ├── es_speaker_8.npz
│   │       │   ├── es_speaker_9.npz
│   │       │   ├── fr_speaker_0.npz
│   │       │   ├── fr_speaker_1.npz
│   │       │   ├── fr_speaker_2.npz
│   │       │   ├── fr_speaker_3.npz
│   │       │   ├── fr_speaker_4.npz
│   │       │   ├── fr_speaker_5.npz
│   │       │   ├── fr_speaker_6.npz
│   │       │   ├── fr_speaker_7.npz
│   │       │   ├── fr_speaker_8.npz
│   │       │   ├── fr_speaker_9.npz
│   │       │   ├── hi_speaker_0.npz
│   │       │   ├── hi_speaker_1.npz
│   │       │   ├── hi_speaker_2.npz
│   │       │   ├── hi_speaker_3.npz
│   │       │   ├── hi_speaker_4.npz
│   │       │   ├── hi_speaker_5.npz
│   │       │   ├── hi_speaker_6.npz
│   │       │   ├── hi_speaker_7.npz
│   │       │   ├── hi_speaker_8.npz
│   │       │   ├── hi_speaker_9.npz
│   │       │   ├── it_speaker_0.npz
│   │       │   ├── it_speaker_1.npz
│   │       │   ├── it_speaker_2.npz
│   │       │   ├── it_speaker_3.npz
│   │       │   ├── it_speaker_4.npz
│   │       │   ├── it_speaker_5.npz
│   │       │   ├── it_speaker_6.npz
│   │       │   ├── it_speaker_7.npz
│   │       │   ├── it_speaker_8.npz
│   │       │   ├── it_speaker_9.npz
│   │       │   ├── ja_speaker_0.npz
│   │       │   ├── ja_speaker_1.npz
│   │       │   ├── ja_speaker_2.npz
│   │       │   ├── ja_speaker_3.npz
│   │       │   ├── ja_speaker_4.npz
│   │       │   ├── ja_speaker_5.npz
│   │       │   ├── ja_speaker_6.npz
│   │       │   ├── ja_speaker_7.npz
│   │       │   ├── ja_speaker_8.npz
│   │       │   ├── ja_speaker_9.npz
│   │       │   ├── ko_speaker_0.npz
│   │       │   ├── ko_speaker_1.npz
│   │       │   ├── ko_speaker_2.npz
│   │       │   ├── ko_speaker_3.npz
│   │       │   ├── ko_speaker_4.npz
│   │       │   ├── ko_speaker_5.npz
│   │       │   ├── ko_speaker_6.npz
│   │       │   ├── ko_speaker_7.npz
│   │       │   ├── ko_speaker_8.npz
│   │       │   ├── ko_speaker_9.npz
│   │       │   ├── pl_speaker_0.npz
│   │       │   ├── pl_speaker_1.npz
│   │       │   ├── pl_speaker_2.npz
│   │       │   ├── pl_speaker_3.npz
│   │       │   ├── pl_speaker_4.npz
│   │       │   ├── pl_speaker_5.npz
│   │       │   ├── pl_speaker_6.npz
│   │       │   ├── pl_speaker_7.npz
│   │       │   ├── pl_speaker_8.npz
│   │       │   ├── pl_speaker_9.npz
│   │       │   ├── pt_speaker_0.npz
│   │       │   ├── pt_speaker_1.npz
│   │       │   ├── pt_speaker_2.npz
│   │       │   ├── pt_speaker_3.npz
│   │       │   ├── pt_speaker_4.npz
│   │       │   ├── pt_speaker_5.npz
│   │       │   ├── pt_speaker_6.npz
│   │       │   ├── pt_speaker_7.npz
│   │       │   ├── pt_speaker_8.npz
│   │       │   ├── pt_speaker_9.npz
│   │       │   ├── ru_speaker_0.npz
│   │       │   ├── ru_speaker_1.npz
│   │       │   ├── ru_speaker_2.npz
│   │       │   ├── ru_speaker_3.npz
│   │       │   ├── ru_speaker_4.npz
│   │       │   ├── ru_speaker_5.npz
│   │       │   ├── ru_speaker_6.npz
│   │       │   ├── ru_speaker_7.npz
│   │       │   ├── ru_speaker_8.npz
│   │       │   ├── ru_speaker_9.npz
│   │       │   ├── tr_speaker_0.npz
│   │       │   ├── tr_speaker_1.npz
│   │       │   ├── tr_speaker_2.npz
│   │       │   ├── tr_speaker_3.npz
│   │       │   ├── tr_speaker_4.npz
│   │       │   ├── tr_speaker_5.npz
│   │       │   ├── tr_speaker_6.npz
│   │       │   ├── tr_speaker_7.npz
│   │       │   ├── tr_speaker_8.npz
│   │       │   ├── tr_speaker_9.npz
│   │       │   ├── zh_speaker_0.npz
│   │       │   ├── zh_speaker_1.npz
│   │       │   ├── zh_speaker_2.npz
│   │       │   ├── zh_speaker_3.npz
│   │       │   ├── zh_speaker_4.npz
│   │       │   ├── zh_speaker_5.npz
│   │       │   ├── zh_speaker_6.npz
│   │       │   ├── zh_speaker_7.npz
│   │       │   ├── zh_speaker_8.npz
│   │       │   └── zh_speaker_9.npz
│   │       ├── zh_speaker_0.npz
│   │       ├── zh_speaker_1.npz
│   │       ├── zh_speaker_2.npz
│   │       ├── zh_speaker_3.npz
│   │       ├── zh_speaker_4.npz
│   │       ├── zh_speaker_5.npz
│   │       ├── zh_speaker_6.npz
│   │       ├── zh_speaker_7.npz
│   │       ├── zh_speaker_8.npz
│   │       └── zh_speaker_9.npz
│   ├── cli.py
│   ├── generation.py
│   ├── model.py
│   └── model_fine.py
├── model-card.md
├── notebooks/
│   ├── fake_classifier.ipynb
│   ├── long_form_generation.ipynb
│   ├── memory_profiling_bark.ipynb
│   └── use_small_models_on_cpu.ipynb
├── pyproject.toml
└── setup.py
Download .txt
SYMBOL INDEX (59 symbols across 5 files)

FILE: bark/api.py
  function text_to_semantic (line 8) | def text_to_semantic(
  function semantic_to_waveform (line 35) | def semantic_to_waveform(
  function save_as_prompt (line 77) | def save_as_prompt(filepath, full_generation):
  function generate_audio (line 86) | def generate_audio(

FILE: bark/cli.py
  function cli (line 10) | def cli():

FILE: bark/generation.py
  function autocast (line 30) | def autocast():
  function _cast_bool_env_var (line 88) | def _cast_bool_env_var(s):
  function _grab_best_device (line 132) | def _grab_best_device(use_gpu=True):
  function _get_ckpt_path (line 142) | def _get_ckpt_path(model_type, use_small=False):
  function _download (line 149) | def _download(from_hf_path, file_name):
  class InferenceContext (line 154) | class InferenceContext:
    method __init__ (line 155) | def __init__(self, benchmark=False):
    method __enter__ (line 160) | def __enter__(self):
    method __exit__ (line 164) | def __exit__(self, exc_type, exc_value, exc_traceback):
  function _inference_mode (line 174) | def _inference_mode():
  function _clear_cuda_cache (line 179) | def _clear_cuda_cache():
  function clean_models (line 185) | def clean_models(model_key=None):
  function _load_model (line 195) | def _load_model(ckpt_path, device, use_small=False, model_type="text"):
  function _load_codec_model (line 252) | def _load_codec_model(device):
  function load_model (line 261) | def load_model(use_gpu=True, use_small=False, force_reload=False, model_...
  function load_codec_model (line 284) | def load_codec_model(use_gpu=True, force_reload=False):
  function preload_models (line 303) | def preload_models(
  function _tokenize (line 338) | def _tokenize(tokenizer, text):
  function _detokenize (line 342) | def _detokenize(tokenizer, enc_text):
  function _normalize_whitespace (line 346) | def _normalize_whitespace(text):
  function _load_history_prompt (line 356) | def _load_history_prompt(history_prompt_input):
  function generate_text_semantic (line 377) | def generate_text_semantic(
  function _flatten_codebooks (line 517) | def _flatten_codebooks(arr, offset_size=CODEBOOK_SIZE):
  function generate_coarse (line 531) | def generate_coarse(
  function generate_fine (line 691) | def generate_fine(
  function codec_decode (line 800) | def codec_decode(fine_tokens):

FILE: bark/model.py
  class LayerNorm (line 12) | class LayerNorm(nn.Module):
    method __init__ (line 15) | def __init__(self, ndim, bias):
    method forward (line 20) | def forward(self, input):
  class CausalSelfAttention (line 23) | class CausalSelfAttention(nn.Module):
    method __init__ (line 25) | def __init__(self, config):
    method forward (line 46) | def forward(self, x, past_kv=None, use_cache=False):
  class MLP (line 94) | class MLP(nn.Module):
    method __init__ (line 96) | def __init__(self, config):
    method forward (line 103) | def forward(self, x):
  class Block (line 110) | class Block(nn.Module):
    method __init__ (line 112) | def __init__(self, config, layer_idx):
    method forward (line 120) | def forward(self, x, past_kv=None, use_cache=False):
  class GPTConfig (line 127) | class GPTConfig:
  class GPT (line 137) | class GPT(nn.Module):
    method __init__ (line 139) | def __init__(self, config):
    method get_num_params (line 155) | def get_num_params(self, non_embedding=True):
    method forward (line 168) | def forward(self, idx, merge_context=False, past_kv=None, position_ids...

FILE: bark/model_fine.py
  class NonCausalSelfAttention (line 15) | class NonCausalSelfAttention(nn.Module):
    method __init__ (line 16) | def __init__(self, config):
    method forward (line 34) | def forward(self, x):
  class FineBlock (line 64) | class FineBlock(nn.Module):
    method __init__ (line 65) | def __init__(self, config):
    method forward (line 72) | def forward(self, x):
  class FineGPT (line 78) | class FineGPT(GPT):
    method __init__ (line 79) | def __init__(self, config):
    method forward (line 107) | def forward(self, pred_idx, idx):
    method get_num_params (line 131) | def get_num_params(self, non_embedding=True):
  class FineGPTConfig (line 147) | class FineGPTConfig(GPTConfig):
Condensed preview — 289 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (141K chars).
[
  {
    "path": ".gitignore",
    "chars": 33,
    "preview": "__pycache__/\nsuno_bark.egg-info/\n"
  },
  {
    "path": "LICENSE",
    "chars": 1061,
    "preview": "MIT License\n\nCopyright (c) Suno, Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof th"
  },
  {
    "path": "README.md",
    "chars": 14943,
    "preview": "> Notice: Bark is Suno's open-source text-to-speech+ model. If you are looking for our text-to-music models, please visi"
  },
  {
    "path": "bark/__init__.py",
    "chars": 140,
    "preview": "from .api import generate_audio, text_to_semantic, semantic_to_waveform, save_as_prompt\nfrom .generation import SAMPLE_R"
  },
  {
    "path": "bark/__main__.py",
    "chars": 28,
    "preview": "from .cli import cli\n\ncli()\n"
  },
  {
    "path": "bark/api.py",
    "chars": 3626,
    "preview": "from typing import Dict, Optional, Union\n\nimport numpy as np\n\nfrom .generation import codec_decode, generate_coarse, gen"
  },
  {
    "path": "bark/assets/prompts/readme.md",
    "chars": 1943,
    "preview": "# Example Prompts Data\n\n## Version Two\nThe `v2` prompts are better engineered to follow text with a consistent voice.\nTo"
  },
  {
    "path": "bark/cli.py",
    "chars": 2464,
    "preview": "import argparse\nfrom typing import Dict, Optional, Union\nimport os\n\nfrom scipy.io.wavfile import write as write_wav\nfrom"
  },
  {
    "path": "bark/generation.py",
    "chars": 29404,
    "preview": "import contextlib\nimport gc\nimport os\nimport re\n\nfrom encodec import EncodecModel\nimport funcy\nimport logging\nimport num"
  },
  {
    "path": "bark/model.py",
    "chars": 9139,
    "preview": "\"\"\"\nMuch of this code is adapted from Andrej Karpathy's NanoGPT\n(https://github.com/karpathy/nanoGPT)\n\"\"\"\nimport math\nfr"
  },
  {
    "path": "bark/model_fine.py",
    "chars": 5908,
    "preview": "\"\"\"\nMuch of this code is adapted from Andrej Karpathy's NanoGPT\n(https://github.com/karpathy/nanoGPT)\n\"\"\"\nfrom dataclass"
  },
  {
    "path": "model-card.md",
    "chars": 2050,
    "preview": "# Model Card: Bark\n\nThis is the official codebase for running the text to audio model, from Suno.ai.\n\nThe following is a"
  },
  {
    "path": "notebooks/fake_classifier.ipynb",
    "chars": 38246,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e330c1de\",\n   \"metadata\": {},\n   \"output"
  },
  {
    "path": "notebooks/long_form_generation.ipynb",
    "chars": 15830,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"39ea4bed\",\n   \"metadata\": {},\n   \"outputs\":"
  },
  {
    "path": "notebooks/memory_profiling_bark.ipynb",
    "chars": 5583,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"90641144\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Bark Memory "
  },
  {
    "path": "notebooks/use_small_models_on_cpu.ipynb",
    "chars": 3051,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"6a682b61\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Benchmarking"
  },
  {
    "path": "pyproject.toml",
    "chars": 1001,
    "preview": "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"suno-bark\"\nversion ="
  },
  {
    "path": "setup.py",
    "chars": 38,
    "preview": "from setuptools import setup\n\nsetup()\n"
  }
]

// ... and 271 more files (download for full content)

About this extraction

This page contains the full source code of the suno-ai/bark GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 289 files (131.3 KB), approximately 54.8k tokens, and a symbol index with 59 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!