{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pkl_filepath = \"/home/tony/Data/Preference/up_v1/interesting_clips_up_u_1_20241201_full.pkl\"\n",
    "df = pd.read_pickle(pkl_filepath)\n",
    "print(len(df))\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# lets do an audio-quality reward model first with no conditioning\n",
    "# in this case we just grab the mp3 one for the positive and for the negative \n",
    "# in our metas we will have the ids of the positive and the negative \n",
    "metas = []\n",
    "for idx in range(0, len(df), 2):\n",
    "    # get the two rows\n",
    "    row1 = df.iloc[idx]\n",
    "    row2 = df.iloc[idx + 1]\n",
    "    # get the text and tags\n",
    "\n",
    "    id1 = row1[\"id_x\"]\n",
    "    id2 = row2[\"id_x\"]\n",
    "    metas.append({\n",
    "        \"positive_id\": id1,\n",
    "        \"negative_id\": id2,\n",
    "    })\n",
    "\n",
    "print(len(metas))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from suno_utils.utils.text import read_jsonl, write_jsonl\n",
    "# write metas to jsonl \n",
    "metas_filepath = \"/app/suno/christian/data/reward_model/remaster_v1/metas.jsonl\"\n",
    "write_jsonl(metas, metas_filepath)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# iterate and get list of s3 paths, then we will download with multiprocessing\n",
    "s3_ids = df[\"id_x\"].tolist()\n",
    "print(len(s3_ids))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# first download audios in parallel to local from s3\n",
    "base_dir = \"/app/suno/christian/data/reward_model/remaster_v1\"\n",
    "out_dir = \"audio\"\n",
    "os.makedirs(os.path.join(base_dir, out_dir), exist_ok=True)\n",
    "\n",
    "def download_npz(song_id):\n",
    "    npz_filepath = f\"s3://suno-data-uploads/studio/uploads/{song_id}.npz\"\n",
    "    out_filepath = os.path.join(base_dir, out_dir, f\"{song_id}.npz\")\n",
    "    # surpress output\n",
    "    if not os.path.exists(out_filepath):\n",
    "        os.system(f\"aws s3 cp {npz_filepath} {out_filepath} > /dev/null 2>&1\")\n",
    "\n",
    "def download_mp3(song_id):\n",
    "    mp3_filepath = f\"s3://suno-data-uploads/studio/uploads/{song_id}.mp3\"\n",
    "    out_filepath = os.path.join(base_dir, out_dir, f\"{song_id}.mp3\")\n",
    "    if not os.path.exists(out_filepath):\n",
    "        os.system(f\"aws s3 cp {mp3_filepath} {out_filepath} > /dev/null 2>&1\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# use joblib for parallel downloads with progress bar\n",
    "from joblib import Parallel, delayed\n",
    "from tqdm import tqdm\n",
    "\n",
    "results = Parallel(n_jobs=96, backend=\"loky\")(\n",
    "    delayed(download_mp3)(song_id) for song_id in tqdm(s3_ids, desc=\"Downloading mp3 files\")\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we need to load the metas and clean them up if we don't have the mp3s\n",
    "from suno_utils.utils.text import read_jsonl, write_jsonl\n",
    "from tqdm import tqdm\n",
    "import torchaudio\n",
    "\n",
    "# first download audios in parallel to local from s3\n",
    "metas_filepath = \"/app/suno/christian/data/reward_model/remaster_v1/metas.jsonl\"\n",
    "base_dir = \"/app/suno/christian/data/reward_model/remaster_v1\"\n",
    "out_dir = \"audio\"\n",
    "\n",
    "metas = read_jsonl(metas_filepath)\n",
    "print(f\"Total metas: {len(metas)}\")\n",
    "\n",
    "new_metas = []\n",
    "for meta in tqdm(metas, desc=\"Cleaning metas\"):\n",
    "    # check if the positive and negative mp3s exist\n",
    "    positive_mp3_path = os.path.join(base_dir, out_dir, f\"{meta['positive_id']}.mp3\")\n",
    "    negative_mp3_path = os.path.join(base_dir, out_dir, f\"{meta['negative_id']}.mp3\")\n",
    "\n",
    "    # try to open the mp3s with torchaudio \n",
    "    try:\n",
    "        pos, sr = torchaudio.load(positive_mp3_path)\n",
    "        neg, sr = torchaudio.load(negative_mp3_path)\n",
    "        new_metas.append(meta)\n",
    "    except Exception as e:\n",
    "        print(f\"Error loading mp3s for {meta['positive_id']} and {meta['negative_id']}: {e}\")\n",
    "\n",
    "\n",
    "print(f\"Total metas after cleaning: {len(new_metas)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# write the new metas to a new file\n",
    "write_jsonl(metas, metas_filepath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we need to load the metas and clean them up if we don't have the mp3s\n",
    "from suno_utils.utils.text import read_jsonl, write_jsonl\n",
    "from tqdm import tqdm\n",
    "import torchaudio\n",
    "from joblib import Parallel, delayed\n",
    "\n",
    "# first download audios in parallel to local from s3\n",
    "metas_filepath = \"/app/suno/christian/data/reward_model/remaster_v1/metas.jsonl\"\n",
    "base_dir = \"/app/suno/christian/data/reward_model/remaster_v1\"\n",
    "out_dir = \"audio\"\n",
    "\n",
    "metas = read_jsonl(metas_filepath)\n",
    "print(f\"Total metas: {len(metas)}\")\n",
    "\n",
    "def check_meta(meta):\n",
    "    # check if the positive and negative mp3s exist\n",
    "    positive_mp3_path = os.path.join(base_dir, out_dir, f\"{meta['positive_id']}.mp3\")\n",
    "    negative_mp3_path = os.path.join(base_dir, out_dir, f\"{meta['negative_id']}.mp3\")\n",
    "\n",
    "    # try to open the mp3s with torchaudio\n",
    "    try:\n",
    "        pos, sr = torchaudio.load(positive_mp3_path)\n",
    "        neg, sr = torchaudio.load(negative_mp3_path)\n",
    "        return meta\n",
    "    except Exception as e:\n",
    "        print(f\"Error loading mp3s for {meta['positive_id']} and {meta['negative_id']}: {e}\")\n",
    "        return None\n",
    "\n",
    "# Process metas in parallel\n",
    "results = Parallel(n_jobs=96, backend=\"loky\")(\n",
    "    delayed(check_meta)(meta) for meta in tqdm(metas, desc=\"Cleaning metas\")\n",
    ")\n",
    "\n",
    "# Filter out None results\n",
    "new_metas = [meta for meta in results if meta is not None]\n",
    "\n",
    "print(f\"Total metas after cleaning: {len(new_metas)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# write the new metas to a new file\n",
    "write_jsonl(new_metas, metas_filepath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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
}
