File size: 10,123 Bytes
94fb728
 
 
 
 
 
2098fed
 
 
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
 
 
 
 
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
 
 
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
 
 
 
 
 
94fb728
 
 
2098fed
 
 
94fb728
 
 
2098fed
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
 
 
 
 
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
 
94fb728
2098fed
 
94fb728
 
2098fed
 
 
 
 
 
 
 
 
 
 
 
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
94fb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2098fed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
{
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "## Prerequisites"
      ],
      "metadata": {
        "id": "w4LtdMb23tZ4"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JgJLBIh3fm-W"
      },
      "source": [
        "### Install Dependencies"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EodUpreufqD-"
      },
      "outputs": [],
      "source": [
        "!nvidia-smi"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bOn11huvfuXc"
      },
      "outputs": [],
      "source": [
        "!pip install --upgrade --quiet pip\n",
        "!pip install --quiet git+https://github.com/huggingface/transformers.git"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install typing-extensions==4.5.0\n",
        "!pip install python-multipart\n",
        "!pip install kaleido\n",
        "!pip install notebook>=6.5.5\n",
        "!pip install click>=8.0\n",
        "!pip install fastapi\n",
        "!pip install \"uvicorn[standard]\"\n",
        "!pip install pyngrok"
      ],
      "metadata": {
        "id": "Nl0CQxwHCrFd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ROxnljVbf6_o"
      },
      "source": [
        "### Load the models"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ToxW1gbLf6tr"
      },
      "outputs": [],
      "source": [
        "from transformers import MusicgenForConditionalGeneration, MusicgenProcessor, set_seed\n",
        "\n",
        "model = MusicgenForConditionalGeneration.from_pretrained(\"facebook/musicgen-small\")\n",
        "processor = MusicgenProcessor.from_pretrained(\"facebook/musicgen-small\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "omP9Hg1ajUKM"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from IPython.display import Audio\n",
        "\n",
        "sampling_rate = model.config.audio_encoder.sampling_rate\n",
        "device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n",
        "model.to(device)\n",
        "None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "852jZKSqiKoT"
      },
      "source": [
        "## Music Generation functionality"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### Model Class"
      ],
      "metadata": {
        "id": "8nydshMdxKab"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import typing\n",
        "\n",
        "class AudioPalette:\n",
        "    def __init__(self):\n",
        "        pass\n",
        "\n",
        "    def set_prompt(self, caption: str | typing.List[str]):\n",
        "        self.caption = caption\n",
        "\n",
        "    def generate(self):\n",
        "        if isinstance(self.caption, str):\n",
        "            return self.generate_single(max_new_tokens=1024)\n",
        "        else:\n",
        "            return self.generate_multiple()\n",
        "\n",
        "    def generate_single(self, prompt=None, max_new_tokens=512):\n",
        "        if not prompt:\n",
        "            prompt = self.caption\n",
        "        inputs = processor(\n",
        "            text=[prompt],\n",
        "            padding=True,\n",
        "            return_tensors=\"pt\",\n",
        "            sampling_rate=sampling_rate\n",
        "        )\n",
        "\n",
        "        audio_values = model.generate(**inputs.to(device), do_sample=True, guidance_scale=3, max_new_tokens=max_new_tokens)\n",
        "        return audio_values\n",
        "\n",
        "    def generate_audio_with_melody_conditioning(self, prompt, melody, max_new_tokens=256):\n",
        "        inputs = processor(\n",
        "            text=[prompt],\n",
        "            audio=melody[0, 0].cpu().numpy(),\n",
        "            padding=True,\n",
        "            return_tensors=\"pt\",\n",
        "            sampling_rate=sampling_rate\n",
        "        )\n",
        "\n",
        "        # set_seed(1)\n",
        "        audio_values = model.generate(**inputs.to(device), do_sample=True, guidance_scale=3, max_new_tokens=max_new_tokens)\n",
        "        return audio_values\n",
        "\n",
        "    def generate_multiple(self):\n",
        "        for idx, prompt in enumerate(self.caption):\n",
        "            if idx == 0:\n",
        "                audio = self.generate_single(prompt, 256)\n",
        "            else:\n",
        "                audio = self.generate_audio_with_melody_conditioning(prompt, audio)\n",
        "        return audio"
      ],
      "metadata": {
        "id": "4V49E7xpxNPu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "audiopalette = AudioPalette()"
      ],
      "metadata": {
        "id": "qW65Q68o-R7f"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "P3OmxnaBA9E-"
      },
      "source": [
        "#### API Creation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Dxlw3ODsTtuB"
      },
      "outputs": [],
      "source": [
        "from fastapi import FastAPI\n",
        "from pydantic import BaseModel, Field\n",
        "from fastapi.middleware.cors import CORSMiddleware\n",
        "\n",
        "app = FastAPI()\n",
        "\n",
        "app.add_middleware(\n",
        "    CORSMiddleware,\n",
        "    allow_origins=['*'],\n",
        "    allow_credentials=True,\n",
        "    allow_methods=['*'],\n",
        "    allow_headers=['*'],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import typing\n",
        "import numpy as np\n",
        "\n",
        "class Prompt(BaseModel):\n",
        "    caption: str | typing.List[str]\n",
        "\n",
        "class FileData(BaseModel):\n",
        "    file_path: str\n",
        "\n",
        "# class Melody(BaseModel):\n",
        "#     audio: np.ndarray\n",
        "\n",
        "#     class Config:\n",
        "#         arbitrary_types_allowed = True"
      ],
      "metadata": {
        "id": "iYUH3-GpfbN8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PTQCdon0A9FA"
      },
      "outputs": [],
      "source": [
        "import tempfile\n",
        "import scipy\n",
        "\n",
        "from fastapi.responses import FileResponse\n",
        "\n",
        "@app.get('/')\n",
        "async def root():\n",
        "    return {\"message\": \"Hello World\"}\n",
        "\n",
        "@app.post('/download')\n",
        "async def download(file_data: FileData):\n",
        "    file_path = file_data.file_path\n",
        "    return FileResponse(file_path)\n",
        "\n",
        "@app.post('/generate')\n",
        "async def gen_music(prompt: Prompt):\n",
        "    audiopalette.set_prompt(prompt.caption)\n",
        "    audio = audiopalette.generate()\n",
        "\n",
        "    file_path = None\n",
        "    with tempfile.NamedTemporaryFile(delete=False) as f:\n",
        "        scipy.io.wavfile.write(f, rate=sampling_rate, data=audio[0, 0].cpu().numpy())\n",
        "        file_path = f.name\n",
        "\n",
        "    if not file_path:\n",
        "        return {\"error\": \"There has been an error\"}\n",
        "    return {\"file_path\": f\"{file_path}\"}\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ALpNtVpHA9FA"
      },
      "source": [
        "#### Run the API"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w3eG8rfRA9FB"
      },
      "outputs": [],
      "source": [
        "from getpass import getpass\n",
        "\n",
        "import nest_asyncio\n",
        "import uvicorn\n",
        "from pyngrok import ngrok"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "ngrok_auth_token = getpass(prompt=\"Enter ngrok auth token: \")\n",
        "ngrok.set_auth_token(ngrok_auth_token)"
      ],
      "metadata": {
        "id": "QFDDncCJEs4f"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yOhMLxA5A9FB"
      },
      "outputs": [],
      "source": [
        "ngrok_tunnel = ngrok.connect(8000)\n",
        "print(\"Public URL:\", ngrok_tunnel.public_url)\n",
        "nest_asyncio.apply()\n",
        "uvicorn.run(app, port=8000)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "606pRql4A9FC"
      },
      "source": [
        "#### Kill ngrok Connection"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "k7Tbq8w-A9FC"
      },
      "outputs": [],
      "source": [
        "ngrok.kill()"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [
        "w4LtdMb23tZ4"
      ],
      "gpuType": "T4",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.10"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}