{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7b82eb58", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ubuntu/miniconda3/envs/respair/lib/python3.11/site-packages/IPython/core/magics/osm.py:417: UserWarning: This is now an optional IPython functionality, setting dhist requires you to install the `pickleshare` library.\n", " self.shell.db['dhist'] = compress_dhist(dhist)[-100:]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "/home/ubuntu/RINGFORMER\n" ] } ], "source": [ "%cd /home/ubuntu/RINGFORMER\n", "\n", "from __future__ import absolute_import, division, print_function, unicode_literals\n", "\n", "import glob\n", "import os\n", "import argparse\n", "import json\n", "import torch\n", "from scipy.io.wavfile import write\n", "from env import AttrDict\n", "from meldataset import mel_spectrogram, MAX_WAV_VALUE, load_wav\n", "from models import Generator\n", "from stft import TorchSTFT\n", "\n", "from Utils.JDC.model import JDCNet" ] }, { "cell_type": "code", "execution_count": 2, "id": "3ee13ffd", "metadata": {}, "outputs": [], "source": [ "h = None\n", "device = None\n", "\n", "\n", "def load_checkpoint(filepath, device):\n", " assert os.path.isfile(filepath)\n", " print(\"Loading '{}'\".format(filepath))\n", " checkpoint_dict = torch.load(filepath, map_location=device)\n", " print(\"Complete.\")\n", " return checkpoint_dict\n", "\n", "\n", "def get_mel(x):\n", " return mel_spectrogram(x, h.n_fft, h.num_mels, h.sampling_rate, h.hop_size, h.win_size, h.fmin, h.fmax)\n", "\n", "\n", "def scan_checkpoint(cp_dir, prefix):\n", " pattern = os.path.join(cp_dir, prefix + '*')\n", " cp_list = glob.glob(pattern)\n", " if len(cp_list) == 0:\n", " return ''\n", " return sorted(cp_list)[-1]" ] }, { "cell_type": "code", "execution_count": 3, "id": "003b1249", "metadata": {}, "outputs": [], "source": [ "F0_model = JDCNet(num_class=1, seq_len=192)" ] }, { "cell_type": "code", "execution_count": 4, "id": "321eb3b5", "metadata": {}, "outputs": [], "source": [ "cp_path = \"/home/ubuntu/RINGFORMER/cp_ringformer_44.1khz\"" ] }, { "cell_type": "code", "execution_count": 5, "id": "3dcc2764", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'F0_path': '/home/ubuntu/Darya_Speech/Utils/JDC/epoch_00079.pth',\n", " 'resblock': '1',\n", " 'num_gpus': 1,\n", " 'batch_size': 18,\n", " 'learning_rate': 0.0002,\n", " 'adam_b1': 0.8,\n", " 'adam_b2': 0.99,\n", " 'lr_decay': 0.999,\n", " 'seed': 1234,\n", " 'upsample_rates': [16, 8],\n", " 'upsample_kernel_sizes': [32, 16],\n", " 'upsample_initial_channel': 512,\n", " 'resblock_kernel_sizes': [3, 7, 11],\n", " 'resblock_dilation_sizes': [[1, 3, 5], [1, 3, 5], [1, 3, 5]],\n", " 'gen_istft_n_fft': 32,\n", " 'gen_istft_hop_size': 4,\n", " 'segment_size': 65536,\n", " 'num_mels': 128,\n", " 'n_fft': 2048,\n", " 'hop_size': 512,\n", " 'win_size': 2048,\n", " 'sampling_rate': 44100,\n", " 'fmin': 0,\n", " 'fmax': None,\n", " 'fmax_for_loss': None,\n", " 'num_workers': 8,\n", " 'dist_config': {'dist_backend': 'nccl',\n", " 'dist_url': 'tcp://localhost:54321',\n", " 'world_size': 1}}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "with open(cp_path + \"/config.json\") as f:\n", " data = f.read()\n", "\n", "json_config = json.loads(data)\n", "h = AttrDict(json_config)\n", "h" ] }, { "cell_type": "code", "execution_count": 6, "id": "a4c78cb6", "metadata": {}, "outputs": [], "source": [ "# device = torch.device('cuda:{:d}'.format(0))\n", "\n", "device = 'cuda:0'" ] }, { "cell_type": "code", "execution_count": 7, "id": "5a782adb", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ubuntu/miniconda3/envs/respair/lib/python3.11/site-packages/torch/nn/utils/weight_norm.py:143: FutureWarning: `torch.nn.utils.weight_norm` is deprecated in favor of `torch.nn.utils.parametrizations.weight_norm`.\n", " WeightNorm.apply(module, name, dim)\n" ] } ], "source": [ "generator = Generator(h, F0_model).to(device)\n", "stft = TorchSTFT(filter_length=h.gen_istft_n_fft, hop_length=h.gen_istft_hop_size, win_length=h.gen_istft_n_fft).to(device)" ] }, { "cell_type": "code", "execution_count": 8, "id": "6f0a7c64", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading '/home/ubuntu/RINGFORMER/cp_ringformer_44.1khz/g_00017000'\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_3972638/3295719764.py:8: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " checkpoint_dict = torch.load(filepath, map_location=device)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Complete.\n", "Removing weight norm...\n" ] } ], "source": [ "cp_g = scan_checkpoint(cp_path, 'g_')\n", "state_dict_g = load_checkpoint(cp_g, device)\n", "generator.load_state_dict(state_dict_g['generator'])\n", "generator.remove_weight_norm()\n", "_ = generator.eval()" ] }, { "cell_type": "markdown", "id": "a115a967", "metadata": {}, "source": [ "### Resynthesis" ] }, { "cell_type": "code", "execution_count": null, "id": "cbeee500", "metadata": {}, "outputs": [], "source": [ "import torchaudio\n", "from librosa.filters import mel as librosa_mel_fn\n", "from IPython.display import Audio\n", "import librosa\n", "\n", "to_mel = torchaudio.transforms.MelSpectrogram(\n", " n_mels=128, n_fft=2048, win_length=2048, hop_length=512, sample_rate=44100, power=2.5)\n", "mean, std = -4, 4\n", "\n", "def preprocess(wave):\n", " wave_tensor = torch.FloatTensor(wav)\n", " mel_tensor = to_mel(wave_tensor)\n", " mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std\n", " return mel_tensor.to('cuda:0')\n", "\n", "\n", "wav = librosa.load(\"/your.wav\", sr=44100)[0]\n", "\n", "x = preprocess(wav)\n", "print(x.shape)\n", "\n", "n = 1\n", "xxx = torch.load(\"/home/ubuntu/RINGFORMER/gt.pt\").to('cuda:0')[n:n+1,:,:]\n", "with torch.no_grad():\n", "\n", " spec, phase = generator(xxx)\n", " y_g_hat = stft.inverse(spec, phase)\n", " audio = y_g_hat.squeeze()\n", " # audio = audio * MAX_WAV_VALUE\n", " audio = audio.cpu().numpy()\n", "\n", "\n", "print('Synthesized:')\n", "display(Audio(audio, rate=44100))" ] } ], "metadata": { "kernelspec": { "display_name": "respair", "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.11.0" } }, "nbformat": 4, "nbformat_minor": 5 }