{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n",
    "\n",
    "import torch\n",
    "import torchaudio\n",
    "from torchaudio.pipelines import SQUIM_OBJECTIVE, SQUIM_SUBJECTIVE\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 360M/360M [00:00<00:00, 564MB/s] \n"
     ]
    }
   ],
   "source": [
    "objective_model = SQUIM_OBJECTIVE.get_model()\n",
    "subjective_model = SQUIM_SUBJECTIVE.get_model()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([0.4115], grad_fn=<SqueezeBackward1>) tensor([1.2090], grad_fn=<SqueezeBackward1>) tensor([-13.6160], grad_fn=<SqueezeBackward1>)\n"
     ]
    }
   ],
   "source": [
    "# load audio\n",
    "x, sr = torchaudio.load(\"/home/christian/audio/reference-audio-wav/02 Dreams.wav\")\n",
    "\n",
    "# crop to 30s\n",
    "x = x[:, :30 * sr]\n",
    "\n",
    "# need to resample to 16kHz\n",
    "if sr != 16000:\n",
    "    x = torchaudio.functional.resample(x, sr, 16000)\n",
    "\n",
    "# convert to mono\n",
    "x = x.mean(dim=0).unsqueeze(0)\n",
    "\n",
    "# run inference\n",
    "stoi_hyp, pesq_hyp, si_sdr_hyp = objective_model(x)\n",
    "\n",
    "print(stoi_hyp, pesq_hyp, si_sdr_hyp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([0.4659], grad_fn=<SqueezeBackward1>) tensor([1.2312], grad_fn=<SqueezeBackward1>) tensor([-14.5185], grad_fn=<SqueezeBackward1>)\n"
     ]
    }
   ],
   "source": [
    "# add some noise and try again\n",
    "\n",
    "y = x + torch.randn_like(x) * 0.5\n",
    "\n",
    "# run inference\n",
    "stoi_hyp, pesq_hyp, si_sdr_hyp = objective_model(y)\n",
    "\n",
    "print(stoi_hyp, pesq_hyp, si_sdr_hyp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/christian/miniconda3/envs/suno_env/lib/python3.10/site-packages/torchaudio/pipelines/_source_separation_pipeline.py:56: 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",
      "  state_dict = torch.load(path)\n"
     ]
    }
   ],
   "source": [
    "from suno_utils.tasks.demucs import (\n",
    "    preload_models as preload_stem_models,\n",
    "    load_model as load_stem_model,\n",
    "    split_vocals,\n",
    "    AUDIO_STEMS,\n",
    ")\n",
    "stem_model = load_stem_model(device=\"cuda\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([4, 2, 1323000])\n",
      "torch.Size([2, 1323000])\n"
     ]
    }
   ],
   "source": [
    "# load audio\n",
    "x, sr = torchaudio.load(\"/home/christian/audio/reference-audio-wav/02 Dreams.wav\")\n",
    "\n",
    "# crop to 30s\n",
    "x = x[:, :30 * sr]\n",
    "\n",
    "# need to resample to 16kHz\n",
    "if sr != 44100:\n",
    "    x = torchaudio.functional.resample(x, sr, 44100)\n",
    "\n",
    "x = x.cuda()\n",
    "\n",
    "# try to split vocals\n",
    "output = stem_model(x.unsqueeze(0)).squeeze(0)\n",
    "print(output.shape)\n",
    "\n",
    "stems = {}\n",
    "for stem_idx, stem_name in enumerate(AUDIO_STEMS):\n",
    "    stems[stem_name] = output[stem_idx].cpu()\n",
    "\n",
    "# compute rms energy for vocals\n",
    "vocals = stems[\"vocals\"]\n",
    "print(vocals.shape)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([0.8487], grad_fn=<SqueezeBackward1>) tensor([2.1148], grad_fn=<SqueezeBackward1>) tensor([10.8712], grad_fn=<SqueezeBackward1>)\n"
     ]
    }
   ],
   "source": [
    "vocals_16k = torchaudio.functional.resample(vocals, 44100, 16000)\n",
    "# now measure the objective metrics\n",
    "stoi_hyp, pesq_hyp, si_sdr_hyp = objective_model(vocals_16k.mean(dim=0).unsqueeze(0))\n",
    "\n",
    "print(stoi_hyp, pesq_hyp, si_sdr_hyp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([0.7870], grad_fn=<SqueezeBackward1>) tensor([1.2957], grad_fn=<SqueezeBackward1>) tensor([8.8079], grad_fn=<SqueezeBackward1>)\n"
     ]
    }
   ],
   "source": [
    "vocals_16k_noise = vocals_16k + torch.randn_like(vocals_16k) * 0.01\n",
    "stoi_hyp, pesq_hyp, si_sdr_hyp = objective_model(vocals_16k_noise.mean(dim=0).unsqueeze(0))\n",
    "\n",
    "print(stoi_hyp, pesq_hyp, si_sdr_hyp)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# test objective model\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "suno_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
