{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "#filepath = \"/home/tony/Data/Preference/up_v2_d3/interesting_clips_exp_20250527_diff_ab.pkl\"\n",
    "#filepath = \"/home/tony/Data/Preference/auk/interesting_clips_exp_20250427_diff_ab.pkl\"\n",
    "filepath1 = \"/home/tony/Data/Preference/up_v2_d3/interesting_clips_ahi_d3_20250528.pkl\"\n",
    "df1 = pd.read_pickle(filepath1)\n",
    "\n",
    "filepath2 = \"/home/tony/Data/Preference/up_v2_d3/interesting_clips_diff_v1_20250528.pkl\"\n",
    "df2 = pd.read_pickle(filepath2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.concat([df1, df2])\n",
    "df.head()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from suno_utils.audio import Audio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(df))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# unique model_name\n",
    "unique_model_names = df['model_name'].unique()\n",
    "print(unique_model_names)\n",
    "\n",
    "#count the number of rows for each model_name\n",
    "model_name_counts = df['model_name'].value_counts()\n",
    "print(model_name_counts)\n",
    "\n",
    "# get the first row for each model_name\n",
    "first_row_for_each_model = df.groupby('model_name').first()\n",
    "print(first_row_for_each_model)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "# Get play durations for each unique model\n",
    "play_durations_by_model = {}\n",
    "\n",
    "for model_name in unique_model_names:\n",
    "    model_df = df[df['model_name'] == model_name]\n",
    "    # only do this where preference is true\n",
    "    model_df = model_df[model_df['preference'] == True]\n",
    "    play_durations = model_df['web_total_play_duration_0'].dropna()\n",
    "    play_durations_by_model[model_name] = play_durations\n",
    "\n",
    "# Create histograms for each model\n",
    "fig, axes = plt.subplots(len(unique_model_names), 1, figsize=(5, 3))\n",
    "if len(unique_model_names) == 1:\n",
    "    axes = [axes]\n",
    "\n",
    "# Print summary statistics\n",
    "for model_name in unique_model_names:\n",
    "    play_durations = play_durations_by_model[model_name]\n",
    "    print(f\"\\n{model_name}:\")\n",
    "    print(f\"  Count: {len(play_durations)}\")\n",
    "    print(f\"  Mean: {play_durations.mean():.2f}\")\n",
    "    print(f\"  Median: {play_durations.median():.2f}\")\n",
    "    print(f\"  Std: {play_durations.std():.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from scipy.stats import gaussian_kde\n",
    "\n",
    "plt.figure(figsize=(7, 5))\n",
    "\n",
    "for model_name in unique_model_names:\n",
    "    play_durations = play_durations_by_model[model_name].dropna()\n",
    "\n",
    "    if len(play_durations) == 0:\n",
    "        continue\n",
    "\n",
    "    # Compute KDE\n",
    "    kde = gaussian_kde(play_durations, bw_method=0.5)  # bw_method controls smoothness\n",
    "    x_vals = np.linspace(0, play_durations.quantile(0.99), 1000)  # clip extreme outliers\n",
    "    y_vals = kde(x_vals)\n",
    "\n",
    "    # Plot\n",
    "    plt.plot(x_vals, y_vals, label=model_name)\n",
    "    plt.fill_between(x_vals, y_vals, alpha=0.3)\n",
    "\n",
    "plt.title('Play Duration Distribution by Model')\n",
    "plt.xlabel('Web Total Play Duration (5 days)')\n",
    "plt.ylabel('Density')\n",
    "plt.legend(title='Model Name')\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for model_name in unique_model_names:\n",
    "    model_df = df[df['model_name'] == model_name]\n",
    "    print(f\"\\nModel: {model_name}\")\n",
    "    \n",
    "    for pref_value in [True, False]:\n",
    "        subset = model_df[model_df['preference'] == pref_value]['web_total_play_duration_0'].dropna()\n",
    "        if len(subset) == 0:\n",
    "            print(f\"  Preference = {pref_value}: No data\")\n",
    "            continue\n",
    "        \n",
    "        print(f\"  Preference = {pref_value}\")\n",
    "        print(f\"    Count : {len(subset)}\")\n",
    "        print(f\"    Mean  : {subset.mean():.2f}\")\n",
    "        print(f\"    Median: {subset.median():.2f}\")\n",
    "        print(f\"    Std   : {subset.std():.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "base_s3_path = f\"s3://suno-data-uploads/studio/uploads/\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "idx = 3\n",
    "# ensure that idx is odd, force it if necessary\n",
    "if idx % 2 != 0:\n",
    "    idx += 1\n",
    "\n",
    "print(idx, idx+1)\n",
    "# get the row at idx\n",
    "row_neg = df.iloc[idx]\n",
    "row_pos = df.iloc[idx+1]\n",
    "\n",
    "# get the audio files\n",
    "audio_neg_id = row_neg['id']\n",
    "audio_pos_id = row_pos['id']\n",
    "\n",
    "audio_neg_s3_filepath = f\"{base_s3_path}{audio_neg_id}.mp3\"\n",
    "audio_pos_s3_filepath = f\"{base_s3_path}{audio_pos_id}.mp3\"\n",
    "print(\"neg preference\", row_neg['preference'], \"model\", row_neg['model_name'])\n",
    "print(\"pos preference\", row_pos['preference'], \"model\", row_pos['model_name'])\n",
    "\n",
    "# load the audio files\n",
    "audio_neg = Audio.from_s3(audio_neg_s3_filepath, n_channels=2)\n",
    "audio_pos = Audio.from_s3(audio_pos_s3_filepath, n_channels=2)\n",
    "\n",
    "# play the audio files\n",
    "audio_neg.play()\n",
    "audio_pos.play()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# for each pair of rows, even+odd\n",
    "# collect all the pairs of ids grouped by winning model\n",
    "\n",
    "pairs_by_model = {}\n",
    "\n",
    "# iterate through pairs of rows (even index + odd index)\n",
    "for i in range(0, len(df) - 1, 2):\n",
    "    row_neg = df.iloc[i]\n",
    "    row_pos = df.iloc[i + 1]\n",
    "    \n",
    "    # the negative preference row is the loser, positive is the winner\n",
    "    winning_model = row_pos['model_name']\n",
    "    losing_id = row_neg['id']\n",
    "    winning_id = row_pos['id']\n",
    "    \n",
    "    if winning_model not in pairs_by_model:\n",
    "        pairs_by_model[winning_model] = []\n",
    "    \n",
    "    pairs_by_model[winning_model].append((losing_id, winning_id))\n",
    "\n",
    "# sort by model name and display results\n",
    "for model in sorted(pairs_by_model.keys()):\n",
    "    pairs = pairs_by_model[model]\n",
    "    print(f\"Model '{model}': {len(pairs)} winning pairs\")\n",
    "\n",
    "print(f\"\\nTotal pairs processed: {sum(len(pairs) for pairs in pairs_by_model.values())}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pairs_by_model[\"chirp-ahi-up-1\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "suno_diff",
   "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.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
