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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/steinhaug/bark-infinity/blob/main/notebooks/Bark_Infinity_Long_Form_Audio_Colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Connect and check GPU and runtime\n",
        "from psutil import virtual_memory\n",
        "gpu_info = !nvidia-smi\n",
        "gpu_info = '\\n'.join(gpu_info)\n",
        "ram_gb = virtual_memory().total / 1e9\n",
        "if gpu_info.find('failed') >= 0:\n",
        "    print('Not connected to a GPU', end=\"\")\n",
        "elif gpu_info.find('not found') >= 0:\n",
        "    print('Not connected to a GPU', end=\"\")\n",
        "else:\n",
        "    print('GPU Connected', end=\"\")\n",
        "print(', your runtime has {:.1f} gigabytes of available RAM\\n'.format(ram_gb))\n"
      ],
      "metadata": {
        "cellView": "form",
        "id": "ogUYjFfhcxTG"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HJQ4TI0_Qowr"
      },
      "source": [
        "## Setup Notebook, Install dependencies\n",
        "<small>Run both cells to install system and needed functions.  \n",
        "_If Colab for some reason crashes re-run cell 0.2 before contining._</small>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "r8wG_tIaOV0Q",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "#@title 0.1 - Install system\n",
        "from IPython.display import clear_output\n",
        "!git clone https://github.com/JonathanFly/bark.git\n",
        "%cd bark\n",
        "!pip install -r old_setup_files/requirements-pip.txt\n",
        "!pip install encodec rich-argparse\n",
        "!pip install librosa pydub devtools\n",
        "\n",
        "#clear_output()\n",
        "#print('Cell completed.')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jKTvqvVkOwXM",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        " #@title 0.2 - Setup required functions and helpers\n",
        "import os\n",
        "import time\n",
        "from bark_infinity import config\n",
        "import numpy as np\n",
        "\n",
        "logger = config.logger\n",
        "logger.setLevel(\"WARNING\")\n",
        "\n",
        "from bark_infinity import generation\n",
        "from bark_infinity import api\n",
        "\n",
        "import rich\n",
        "from rich import print\n",
        "from rich import pretty\n",
        "from rich.pretty import pprint\n",
        "from rich import inspect\n",
        "\n",
        "import librosa\n",
        "from pydub import AudioSegment\n",
        "import ipywidgets as widgets\n",
        "from IPython.display import display, Audio\n",
        "from io import BytesIO\n",
        "\n",
        "# None of this code, just fiddlign with Colab stuff\n",
        "# Just to save Colab with outputs and float32 wavs are GIGANTO\n",
        "# actually this doesn't work, the iPython widget converts it back to float32? or I messed up\n",
        "\n",
        "def display_audio_int16_but(audio_arr_segments, file_name, sample_rate=generation.SAMPLE_RATE,  width='200px'):\n",
        "    file_name_label = widgets.Label(value=f\"Playing: {file_name}\")\n",
        "    file_name_label.layout.width = width\n",
        "    audio_data_int16 = audio_arr_segments\n",
        "    if isinstance(audio_data_int16, list):\n",
        "        audio_data_int16 = np.concatenate(audio_data_int16)\n",
        "\n",
        "    #audio_data_int16 = np.int16(audio_data_int16 * np.iinfo(np.int16).max)\n",
        "\n",
        "\n",
        "    audio_widget = Audio(audio_data_int16, rate=sample_rate)\n",
        "    display(file_name_label, audio_widget)\n",
        "\n",
        "\n",
        "def on_button_click(button):\n",
        "    audio_data, sample_rate = librosa.load(button.wav_path, sr=None)\n",
        "    file_name = os.path.basename(button.wav_path)\n",
        "    display_audio_int16_but(audio_data,file_name, sample_rate)\n",
        "\n",
        "def display_wav_files(directory, matchType=\".wav\"):\n",
        "    subdirs, wav_files = [], []\n",
        "\n",
        "    for item in os.listdir(directory):\n",
        "        item_path = os.path.join(directory, item)\n",
        "\n",
        "        if os.path.isfile(item_path) and item_path.endswith(matchType):\n",
        "            wav_files.append(item_path)\n",
        "        elif os.path.isdir(item_path):\n",
        "            subdirs.append(item_path)\n",
        "\n",
        "    wav_files.sort(key=lambda x: os.path.basename(x))\n",
        "\n",
        "    for wav_file in wav_files:\n",
        "\n",
        "        filename = os.path.basename(wav_file)\n",
        "        print(f\" {filename}\")\n",
        "        display( Audio(filename=wav_file, rate=generation.SAMPLE_RATE) )\n",
        "        #button = widgets.Button(description=f\"Play {filename}\")\n",
        "        #button.wav_path = wav_file\n",
        "        #button.on_click(on_button_click)\n",
        "        #display(button)\n",
        "\n",
        "    for subdir in sorted(subdirs):\n",
        "        print(f\"<{subdir}>\")\n",
        "        display_wav_files(subdir, matchType)\n",
        "\n",
        "def display_mp4_files(directory):\n",
        "    return display_wav_files(directory, '.mp4')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 1.0 - Gradio App"
      ],
      "metadata": {
        "id": "VbIE0Bv8jxtN"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@markdown Run the WebUI with all features.<br>\n",
        "#@markdown When loaded click the second link to launch WebUI in another window.\n",
        "!python bark_webui.py --share"
      ],
      "metadata": {
        "cellView": "form",
        "id": "BQfEqnxMpUk1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OTRtNy1xT1sI"
      },
      "source": [
        "## 2.0 - Manual generation\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LKLe_gYkQ59l"
      },
      "source": [
        "### 2.1 - Choose Bark Models and set Text and Other Generation Options\n",
        "\n",
        "Required for 3.0 and 4.0"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Time to complete cell: ca. 3min\n",
        "generation.OFFLOAD_CPU = False # On your home system set to True probably, but Colab GPU should have plenty of memory for all three models\n",
        "generation.preload_models() # Optional, will lazy load if not preloaded. First time run in New Colab has to download models"
      ],
      "metadata": {
        "id": "QLa2jPOUjSyd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nTzF9iamO1Tm"
      },
      "outputs": [],
      "source": [
        "text = \"\"\"\n",
        "Hey, have you heard about this new text-to-audio model called \"Bark\"?\n",
        "It's like rain on your wedding day. It's a free ride when you've already paid. It's the good advice that you just didn't take.\n",
        "And who would've thought? It figures.\n",
        "\n",
        "Well, life has a funny way of sneaking up on you. When you think everything's okay and everything's going right.\n",
        "And life has a funny way of helping you out. When you think everything's gone wrong.\n",
        "And everything blows up in your face.\n",
        "\n",
        "It's a traffic jam when you're already late. A \"No smoking\" sign on your cigarette break.\n",
        "It's like ten thousand spoons when all you need is a knife. It's meeting the man of my dreams.\n",
        "And then meeting his beautiful wife.\n",
        "\n",
        "And isn't it ironic? Don't you think? A little too ironic.\n",
        "And yeah, I really do think.\n",
        "\"\"\"\n",
        "\n",
        "# For split set split_character_goal_length and split_character_max_length\n",
        "kwargs = {}\n",
        "\n",
        "kwargs = config.load_all_defaults()\n",
        "kwargs['text_prompt'] = text\n",
        "kwargs['hoarder_mode'] = True\n",
        "kwargs[\"output_dir\"] = 'bark_samples'\n",
        "kwargs[\"history_prompt\"] = None\n",
        "# kwargs[\"single_starting_seed\"] = None #\n",
        "# If you set seed you might want manually call generation.set_seed(-1) after to disable deterministic generation settings\n",
        "# I'm not cleaning up after this paramater at the moment and I'm not sure on other side effects\n",
        "kwargs[\"stable_mode_interval\"] = 1 # 0 for continous, 2,3,4 for mixed\n",
        "kwargs[\"split_character_goal_length\"] = 90\n",
        "kwargs[\"split_character_max_length\"] = 130\n",
        "# kwargs[\"output_iterations\"] = 1\n",
        "kwargs[\"add_silence_between_segments\"] = .025 # See: https://github.com/suno-ai/bark/blob/main/notebooks/long_form_generation.ipynb but not great for songs or stable_mode_interval 0\n",
        "kwargs[\"semantic_min_eos_p\"] = 0.05 # 0.20 is default, lower means more likely to stotp\n",
        "\n",
        "\n",
        "# not sure on overall effect so far from these, but for example:\n",
        "kwargs[\"semantic_top_k\"] = 50\n",
        "kwargs[\"semantic_top_p\"] = 0.95"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 3.0 First Attempt"
      ],
      "metadata": {
        "id": "uuqkchecXnbm"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 3.2 Before we run, let's double check out settings"
      ],
      "metadata": {
        "id": "6ANm93mHZIa6"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6SPmYLSoQBBp"
      },
      "outputs": [],
      "source": [
        "kwargs[\"dry_run\"] = True # Check how the text is being split, don't actually run the model.\n",
        "full_generation_segments, audio_arr_segments, final_filename_will_be, _ = api.generate_audio_long(**kwargs)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IEFQgcemX7Ih"
      },
      "outputs": [],
      "source": [
        "# that's the output we expect to see, we didn't generate audio yet\n",
        "# these text segments look a little small small so let's try this instead\n",
        "kwargs[\"split_character_goal_length\"] = 110\n",
        "kwargs[\"split_character_max_length\"] = 175\n",
        "\n",
        "full_generation_segments, audio_arr_segments, final_filename_will_be, _ = api.generate_audio_long(**kwargs)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 3.2 Run Bark"
      ],
      "metadata": {
        "id": "iPwaLVKCZNaN"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gnvv0zEZY7vP"
      },
      "outputs": [],
      "source": [
        "# These segement sizes look better so now so set dry_run to False to run for real\n",
        "# Because we set hoarder_mode we can see the wav files for each segment in the Colab File Manager\n",
        "\n",
        "kwargs[\"dry_run\"] = False\n",
        "full_generation_segments, audio_arr_segments, final_filename_will_be, _ = api.generate_audio_long(**kwargs)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 3.3 Save and list files + playbutton"
      ],
      "metadata": {
        "id": "pGeaoAZ6Y9yX"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Qqyw-Uk1axiC"
      },
      "outputs": [],
      "source": [
        "print(f\"Final audiofile: {final_filename_will_be}\")\n",
        "# (we see many wav because we set hoarder_mode, but one file will be the final product\n",
        "# set hoarder_mode=False if you just want the file wav and aren't in explore mode\n",
        "\n",
        "# or play here\n",
        "Audio(np.concatenate(audio_arr_segments), rate=generation.SAMPLE_RATE)\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# because we set hoarder mode we also saved each segement as its own seperate sample with wav\n",
        "\n",
        "!find \"bark_samples/\" -name \"*.npz\"\n",
        "\n",
        "display_mp4_files(\"bark_samples/\")"
      ],
      "metadata": {
        "id": "yqORA8ajXMrk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 4.0 Second Attempt. Can we do better?"
      ],
      "metadata": {
        "id": "psbR-0mxW4Dn"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 4.1 settings"
      ],
      "metadata": {
        "id": "g8vPUGahb0Ar"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# we used stable_mode_interval = 1, so the history_prompt does not evolve between segments\n",
        "# even still the voices that are saved for each segment are one-generation different than the original history prompt\n",
        "# this means they are a *little* bit different, and we may prefer one of them over the original\n",
        "# for example maybe segment 2 was a little more clear, or had a particular emotion, we could use that segment's version as the speaker\n",
        "# in the particular run I'm doing now, that segment ended with a little bit an interesting accent. I'm curious if I can bring that out more.\n",
        "\n",
        "# (should probably rename the file to something sensible though)\n",
        "\n",
        "kwargs[\"history_prompt\"] = \"/content/bark/bark_samples/Hey_have_you_he-23-0714-0743-27-SPK-random/002_Its_the_good_ad-23-0714-0744-51-SPK-random.mp4.npz\""
      ],
      "metadata": {
        "id": "WQvyiM2sW5xC"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 4.2 generate"
      ],
      "metadata": {
        "id": "t95ZGI6kcNBq"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "kwargs[\"text_prompt\"] = f\"I'm speaker number two. I'm the best speaker. Also I'm a free spirit. Let me evolve my voice with every step. Here's my version.\"\n",
        "kwargs[\"text_prompt\"] += text\n",
        "kwargs[\"stable_mode_interval\"] = 0\n",
        "kwargs[\"output_dir\"] = \"speaker_2_test\"\n",
        "kwargs[\"add_silence_between_segments\"] = 0.0 # No silence, fully merge clips\n",
        "\n",
        "kwargs[\"semantic_min_eos_p\"] = 0.20 # Back to default, let Bark umm and ahh a bit\n",
        "full_generation_segments, audio_arr_segments, final_filename_will_be, _ = api.generate_audio_long(**kwargs)\n"
      ],
      "metadata": {
        "id": "btp4V86BfAT1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 4.3 Save and list files + playbutton"
      ],
      "metadata": {
        "id": "GrXY5zfscCwi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"Final audiofile: {final_filename_will_be}\")\n",
        "Audio(np.concatenate(audio_arr_segments), rate=generation.SAMPLE_RATE)"
      ],
      "metadata": {
        "id": "9fthW9oGw-5g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# this clip probably got really weird after a full segments, fully feedbacking into itself. So kwargs[\"stable_mode_interval\"] = 3 might be a good compromise\n",
        "\n",
        "display_mp4_files(\"speaker_2_test\")"
      ],
      "metadata": {
        "id": "Rlv4CQrfthY8"
      },
      "execution_count": null,
      "outputs": []
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [
        "HJQ4TI0_Qowr",
        "FHlxNCt3QwIr",
        "uuqkchecXnbm"
      ],
      "provenance": [],
      "machine_shape": "hm",
      "gpuType": "T4",
      "include_colab_link": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}