{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Permutation tests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import re\n",
    "from pathlib import Path\n",
    "\n",
    "#import ipywidgets as widgets\n",
    "#from ipywidgets import Layout, Button, HBox, VBox, Box, Dropdown, Select, Text, Output, IntSlider, Label\n",
    "from IPython.display import display, clear_output, Image, Video\n",
    "import panel as pn\n",
    "\n",
    "\n",
    "#from bokeh.plotting import figure, show, output_notebook\n",
    "#output_notebook()\n",
    "#pn.extension('bokeh')\n",
    "pn.extension()\n",
    "#pn.extension('ipywidgets')\n",
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "outputs_root = Path('images_out')\n",
    "#folder_prefix = 'permutations_limited_palette_2D'\n",
    "#folder_prefix = 'exp_stability_modes'\n",
    "folder_prefix = 'exp_video_basic_stability_modes'\n",
    "folders = list(outputs_root.glob(f'{folder_prefix}_*'))\n",
    "len(folders)\n",
    "\n",
    "def format_val(v):\n",
    "    try:\n",
    "        v = float(v)\n",
    "        if int(v) == v:\n",
    "            v = int(v)\n",
    "    except:\n",
    "        pass\n",
    "    return v\n",
    "\n",
    "def parse_folder_name(folder):\n",
    "    #chunks = folder.name[1+len(folder_prefix):].split('_')\n",
    "    #chunks = folder.name[1+len(folder_prefix):].split('-')\n",
    "    metadata_string = folder.name[1+len(folder_prefix):]\n",
    "    pattern = r\"_?([a-zA-Z_]+)-(True|False|[0-9.]+)\"\n",
    "    matches = re.findall(pattern, metadata_string)\n",
    "    d_ = {k:format_val(v) for k,v in matches}\n",
    "    d_['fpath'] = folder\n",
    "    d_['n_images'] = len(list(folder.glob('*.png')))\n",
    "    return d_\n",
    "\n",
    "#parse_folder_name(folders[0])\n",
    "df_meta = pd.DataFrame([parse_folder_name(f) for f in folders])\n",
    "\n",
    "variant_names = [v for v in df_meta.columns.tolist() if v not in ['fpath']]\n",
    "variant_ranges = {v:df_meta[v].unique() for v in variant_names}\n",
    "[v.sort() for v in variant_ranges.values()]\n",
    "True\n",
    "\n",
    "##########################################\n",
    "\n",
    "# to do: output and display palettes\n",
    "\n",
    "#kargs = {k:widgets.Dropdown(options=v, value=v[0], disabled=False, layout=Layout(width='auto')) for k,v in variant_ranges.items()}\n",
    "#kargs['i'] = widgets.IntSlider(min=1, max=40, step=1, value=1, continuous_update=False, readout=True, readout_format='d')\n",
    "\n",
    "n_imgs_per_group = 20\n",
    "\n",
    "def setting_name_shorthand(setting_name):\n",
    "    return ''.join([tok[0] for tok in setting_name.split('_')])\n",
    "\n",
    "kargs = {k:pn.widgets.DiscreteSlider(name=k, options=list(v), value=v[0]) for k,v in variant_ranges.items()}\n",
    "#kargs['i'] = pn.widgets.IntSlider(name='i', start=1, end=n_imgs_per_group, step=1, value=n_imgs_per_group)\n",
    "kargs['i'] = pn.widgets.Player(interval=300, name='step', start=1, end=n_imgs_per_group, step=1, value=1, loop_policy='reflect')\n",
    "\n",
    "PRELOAD_IMAGES = False\n",
    "from PIL import Image\n",
    "\n",
    "def read_image(fpath):\n",
    "    #return plt.imread(fpath)\n",
    "    #return pn.pane.PNG(fpath, width=700)\n",
    "    with Image.open(fpath) as _img:\n",
    "       img = _img.copy()\n",
    "    return img\n",
    "\n",
    "url_prefix = \"https://raw.githubusercontent.com/dmarx/pytti-settings-test/main/images_out/\"\n",
    "#im_path = im_path.replace('images_out/', url_prefix)\n",
    "\n",
    "image_paths = [str(p) for p in Path('images_out').glob('**/*.png')]\n",
    "#print(len(list(image_paths)))\n",
    "d_image_urls = {im_path:im_path.replace('images_out/', url_prefix) for im_path in image_paths}\n",
    "\n",
    "if PRELOAD_IMAGES:\n",
    "    d_images = {}\n",
    "    for folder in df_meta['fpath']:\n",
    "        for im_path in folder.glob('*.png'):\n",
    "            d_images[str(im_path)] = read_image(im_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "variant_names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "#@widgets.interact(\n",
    "@pn.interact(\n",
    "    **kargs\n",
    ")\n",
    "#@pn.interact\n",
    "def display_images(\n",
    "    palettes,\n",
    "    palette_size,\n",
    "    gamma,\n",
    "    hdr_weight,\n",
    "    smoothing_weight,\n",
    "    palette_normalization_weight,\n",
    "    i,\n",
    "):\n",
    "    folder = df_meta[\n",
    "        (palettes == df_meta['palettes']) &\n",
    "        (palette_size == df_meta['palette_size']) &\n",
    "        (gamma == df_meta['gamma']) &\n",
    "        (hdr_weight == df_meta['hdr_weight']) &\n",
    "        (smoothing_weight == df_meta['smoothing_weight']) &\n",
    "        (palette_normalization_weight == df_meta['palette_normalization_weight'])\n",
    "    ]['fpath'].values[0]\n",
    "    im_path = str(folder / f\"{folder.name}_{i}.png\")\n",
    "    im_url = d_image_urls[im_path]\n",
    "    #return Image(im_path, width=700)\n",
    "    #print(type(im_path))\n",
    "    #im = im_path\n",
    "    #url_prefix = \"https://raw.githubusercontent.com/dmarx/pytti-settings-test/main/images_out/\"\n",
    "    #im_path = im_path.replace('images_out/', url_prefix)\n",
    "    #print(im_path)\n",
    "    #if PRELOAD_IMAGES:\n",
    "    #    im = d_images[im_path]\n",
    "    #else:\n",
    "    #    im = im_path\n",
    "    #return pn.pane.PNG(im, width=700)\n",
    "    #return im\n",
    "    #return pn.pane.PNG(im_url, width=700)\n",
    "    return pn.pane.HTML(f'<img src=\"{im_url}\" width=\"700\">', width=700, height=350, sizing_mode='fixed')\n",
    "\n",
    "# embedding this makes the page nearly a gigabyte in size.\n",
    "# need to use a CDN of something like that.\n",
    "pn.panel(display_images, height=1000).embed(max_opts=n_imgs_per_group, max_states=999999999)\n",
    "#pn.panel(display_images)\n",
    "#display_images "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "\n",
    "#@widgets.interact(\n",
    "@pn.interact(\n",
    "    **kargs\n",
    ")\n",
    "#@pn.interact\n",
    "def display_images(\n",
    "    ref,\n",
    "    dsw,\n",
    "    ssw,\n",
    "    i,\n",
    "):\n",
    "    folder = df_meta[\n",
    "        #(reencode_each_frame == df_meta['ref']) &\n",
    "        #(direct_stabilization_weight == df_meta['dsw']) &\n",
    "        #(semantic_stabilization_weight == df_meta['ssw'])\n",
    "        (ref == df_meta['ref']) &\n",
    "        (dsw == df_meta['dsw']) &\n",
    "        (ssw == df_meta['ssw'])\n",
    "    ]['fpath'].values[0]\n",
    "    im_path = str(folder / f\"{folder.name}_{i}.png\")\n",
    "    #im_url = d_image_urls[im_path]\n",
    "    im_url = im_path\n",
    "    #return Image(im_path, width=700)\n",
    "    #print(type(im_path))\n",
    "    #im = im_path\n",
    "    #url_prefix = \"https://raw.githubusercontent.com/dmarx/pytti-settings-test/main/images_out/\"\n",
    "    #im_path = im_path.replace('images_out/', url_prefix)\n",
    "    #print(im_path)\n",
    "    #if PRELOAD_IMAGES:\n",
    "    #    im = d_images[im_path]\n",
    "    #else:\n",
    "    #    im = im_path\n",
    "    #return pn.pane.PNG(im, width=700)\n",
    "    #return im\n",
    "    #return pn.pane.PNG(im_url, width=700)\n",
    "    return pn.pane.HTML(f'<img src=\"{im_url}\" width=\"700\">', width=700, height=350, sizing_mode='fixed')\n",
    "\n",
    "# embedding this makes the page nearly a gigabyte in size.\n",
    "# need to use a CDN of something like that.\n",
    "pn.panel(display_images, height=1000)#.embed(max_opts=n_imgs_per_group, max_states=999999999)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "3eff1e1332ed0784bebe5613522d192d113df675730803c3b8984f113f4e15fd"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 ('pytti-book-l72HEyWC')",
   "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.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}