{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n",
    "\n",
    "import torch\n",
    "import json\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "from suno_utils.utils.text import read_jsonl\n",
    "from suno_utils.utils.s3 import read_from_s3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.insert(0, \"/home/christian/code/neon/sunoDiff/\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/christian/miniconda3/envs/suno_env2/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading semantic model...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/christian/code/glockenspiel/suno_utils/suno_utils/tasks/mert_25.py:148: 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",
      "  sd = _torch_load_p(checkpoint_filepath)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading codec model...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/christian/code/glockenspiel/suno_utils/suno_utils/tasks/dac_vae_100hz_peaq.py:73: 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",
      "  sd = load_f(checkpoint_filepath)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading diffusion model...\n",
      "loading weights...\n",
      "converting model to precision torch.bfloat16...\n",
      "loading tokenizer...\n",
      "done!\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from suno_utils.audio import Audio\n",
    "from generation import preload_models, generate, _retrieve_models\n",
    "_ = preload_models(\n",
    "    tokenizer_filepath=\"/home/georg/notebooks/gpu_nb/tmp/tokenizer_60k.json\",\n",
    "    semantic_model_filepath=\"/home/georg/notebooks/gpu_nb/tmp/mert_25.pt\",\n",
    "    semantic_clusters_filepath=\"/home/georg/notebooks/gpu_nb/tmp/mert_25_2x4k.npy\",\n",
    "    \n",
    "    #codec_filepath=\"/home/georg/notebooks/gpu_nb/tmp/100hz_vae_peaq_kl_0.005.pth\",\n",
    "    codec_filepath=\"/home/georg/notebooks/gpu_nb/tmp/25hz_vae_peaq_kl_0.005.pth\",\n",
    "    dit_model_filepath=\"s3://suno-data/georg/tmp/2b_prefix_1000k.pt\",\n",
    "    weights_precision=torch.bfloat16,\n",
    "    compile=True,\n",
    ")\n",
    "\n",
    "models = _retrieve_models()\n",
    "model_duration_s = 30\n",
    "if models[\"dit_model\"].ctx_len is not None:\n",
    "    model_duration_s = 6 * 60\n",
    "else:\n",
    "    model_duration_s = models[\"dit_model\"].block_size // models[\"dit_model\"].io_hz\n",
    "duration_s = 2*60 if model_duration_s >= 2*60 else 30"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19448\n"
     ]
    }
   ],
   "source": [
    "metas = read_from_s3(\"s3://suno-data/christian/data/upsample_100hz_v4_t_5_20241018/metas.jsonl\", read_f=read_jsonl)\n",
    "print(len(metas))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 32/32 [00:02<00:00, 15.79it/s]\n",
      "100%|██████████| 32/32 [00:01<00:00, 19.51it/s]\n",
      "100%|██████████| 32/32 [00:01<00:00, 19.52it/s]\n",
      "  1%|          | 1/100 [00:07<12:48,  7.76s/it]"
     ]
    }
   ],
   "source": [
    "peaks = []\n",
    "import random\n",
    "random.shuffle(metas)\n",
    "from tqdm import tqdm\n",
    "for meta in tqdm(metas[:100]):\n",
    "    gen_id = meta[\"id\"]\n",
    "    #s3_filepath = f\"s3://suno-data-uploads/studio/uploads/{gen_id}.npz\"\n",
    "    mp3_filepath = f\"s3://suno-data-uploads/studio/uploads/{gen_id}.mp3\"\n",
    "    #print(s3_filepath)\n",
    "    #data = read_from_s3(s3_filepath, read_f=np.load)\n",
    "    audio = Audio.from_s3(mp3_filepath, n_channels=2).get_slice(0, 30.01)\n",
    "    text_data = read_from_s3(f\"s3://suno-data-uploads/studio/uploads/{gen_id}_hoot.json\")\n",
    "    aligned_lyrics = json.loads(text_data)\n",
    "    seeds = [np.random.randint(0, 2**32-1) for _ in range(3)]\n",
    "\n",
    "    for seed in seeds:\n",
    "        pred_audio = generate(\n",
    "            audio, \n",
    "            aligned_lyrics=aligned_lyrics,\n",
    "            tags=\"pop\",\n",
    "            text_cfg_coef=4.0,\n",
    "            ctx_cfg_coef=1.0,\n",
    "            steps=32,\n",
    "            seed=seed,\n",
    "        )\n",
    "        pred_audio = torch.from_numpy(pred_audio)\n",
    "        #peak = np.max(np.abs(pred_audio.array_float))\n",
    "        #peaks.append(peak)\n",
    "        peaks.append(pred_audio.abs().max())\n",
    "    print(min(peaks), max(peaks))\n",
    "\n",
    "plt.hist(peaks, bins=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "suno_env2",
   "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.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
