{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
" # CoMoGan\n",
"Notebook to test our model after training."
]
},
{
"cell_type": "code",
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-24T11:36:37.046598Z",
"start_time": "2024-08-24T11:36:35.526168Z"
}
},
"source": [
"import ipywidgets as widgets\n",
"import pytorch_lightning as pl\n",
"import pathlib\n",
"import torch\n",
"import yaml\n",
"import os\n",
"\n",
"from math import pi\n",
"from PIL import Image\n",
"from munch import Munch\n",
"from threading import Timer\n",
"from IPython.display import clear_output\n",
"from torchvision.transforms import ToPILImage\n",
"\n",
"from data import create_dataset\n",
"from torchvision.transforms import ToTensor\n",
"from data.base_dataset import get_transform\n",
"from networks import find_model_using_name, create_model"
],
"outputs": [],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load the model with a checkpoint\n",
"Choose the directory that contains the checkpoint that you want."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import pathlib\n",
"\n",
"# Load names of directories inside /logs\n",
"p = pathlib.Path('./logs')\n",
"\n",
"# Use x.name to get the directory name instead of splitting the path\n",
"list_run_id = [x.name for x in p.iterdir() if x.is_dir()]\n",
"\n",
"import ipywidgets as widgets\n",
"from IPython.display import display, clear_output\n",
"import os\n",
"\n",
"w_run = widgets.Dropdown(options=list_run_id,\n",
" description='Select RUN_ID',\n",
" disabled=False,\n",
" style=dict(description_width='initial'))\n",
"\n",
"\n",
"w_check = None\n",
"root_dir = None\n",
"\n",
"def on_value_change_check(change):\n",
" global w_check, w_run, root_dir\n",
" \n",
" clear_output(wait=True)\n",
" \n",
" root_dir = os.path.join('logs', w_run.value, 'tensorboard', 'default', 'version_0')\n",
" p = pathlib.Path(root_dir + '/checkpoints')\n",
" \n",
" # Load a list of checkpoints, use the last one by default\n",
" list_checkpoint = [x.name for x in p.iterdir() if 'iter' in x.name]\n",
" list_checkpoint.sort(reverse=True, key=lambda x: int(x.split('_')[1].split('.pth')[0]))\n",
" \n",
" w_check = widgets.Dropdown(options=list_checkpoint,\n",
" description='Select checkpoint',\n",
" disabled=False,\n",
" style=dict(description_width='initial'))\n",
" display(widgets.HBox([w_run, w_check]))\n",
"\n",
"on_value_change_check({'new': w_run.value})\n",
"w_run.observe(on_value_change_check, names='value')\n"
],
"execution_count": 2,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-24T11:36:39.368141Z",
"start_time": "2024-08-24T11:36:37.080571Z"
}
},
"source": [
"RUN_ID = w_run.value\n",
"CHECKPOINT = w_check.value\n",
"\n",
"# Load parameters\n",
"with open(os.path.join(root_dir, 'hparams.yaml')) as cfg_file:\n",
" opt = Munch(yaml.safe_load(cfg_file))\n",
"\n",
"opt.no_flip = True\n",
"# Load parameters to the model, load the checkpoint\n",
"model = create_model(opt)\n",
"model = model.load_from_checkpoint((os.path.join(root_dir, 'checkpoints/', CHECKPOINT)))\n",
"# Transfer the model to the GPU\n",
"model.to('cpu');"
],
"outputs": [],
"execution_count": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load the validation dataset"
]
},
{
"cell_type": "code",
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-24T11:36:39.383167Z",
"start_time": "2024-08-24T11:36:39.370142Z"
}
},
"source": [
"import pathlib\n",
"from PIL import Image\n",
"\n",
"# Set opt.dataroot to the imgs_test directory\n",
"opt.dataroot = 'imgs_test/'\n",
"\n",
"# Load paths of all files contained in /imgs_test\n",
"p = pathlib.Path(opt.dataroot)\n",
"dataset_paths = [str(x.relative_to(opt.dataroot)) for x in p.iterdir()]\n",
"dataset_paths.sort()\n",
"\n",
"sequence_name = {}\n",
"# Make a dict with each sequence name as a key and\n",
"# a list of paths to the images of the sequence as a value\n",
"for file in dataset_paths:\n",
" # Keep only the sequence part contained in the name of the image\n",
" strip_name = file.split('_')[0]\n",
" \n",
" if strip_name not in sequence_name:\n",
" sequence_name[strip_name] = [file]\n",
" else:\n",
" sequence_name[strip_name].append(file)\n"
],
"outputs": [],
"execution_count": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Select a sequence, an image and the moment of the day\n",
"Select the sequence on which you want to work before choosing which image should be used.
\n",
"Select the moment of the day, by choosing the angle of the sun $\\phi$ between [0,2$\\pi$],\n",
"which maps to a sun elevation ∈ [+30◦,−40◦]\n",
"
pip install imageio imageio-ffmpeg"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import Video\n",
"import numpy as np\n",
"import imageio\n",
"\n",
"w_button = widgets.Button(description='Start', tooltip='Start the inference of a sequence',\n",
" icon='play')\n",
"\n",
"phi_opt = ['Variable phi'] + [str(round(f, 2)) for f in np.arange(0, pi*2, 0.01)]\n",
"w_vid_time = widgets.SelectionSlider(options=phi_opt, value=phi_opt[0], description='Select time : ')\n",
"\n",
"w_vid_seq = drop_list()\n",
"\n",
"w_button_seq = widgets.VBox([widgets.HBox([w_vid_seq, w_vid_time]), w_button])\n",
"display(w_button_seq)\n",
"\n",
"def get_video(bt):\n",
" global sequence_name, w_vid_seq, w_vid_time, w_button_seq\n",
" \n",
" clear_output(wait=True)\n",
" display(w_button_seq)\n",
" seq_size = len(sequence_name[w_vid_seq.value])\n",
" # Display progress bar\n",
" w_prog = widgets.IntProgress(value=0, min=0, max=seq_size, description='Loading:')\n",
" display(w_prog)\n",
" # Create a videos directory to save our video\n",
" save_name = str(pathlib.Path('.').absolute()) + '/videos/'\n",
" os.makedirs(save_name, exist_ok=True)\n",
" # If variable phi\n",
" if w_vid_time.value == 'Variable phi':\n",
" # Write our video in the project folder\n",
" save_name += 'comogan_{}_phi_{}.mp4'.format(w_vid_seq.value.replace('segment-', 'seg_'),\n",
" 'variable')\n",
" else:\n",
" save_name += 'comogan_{}_phi_{}.mp4'.format(w_vid_seq.value.replace('segment-', 'seg_'),\n",
" w_vid_time.value.replace('.', '_'))\n",
" writer = imageio.get_writer(save_name, fps=10)\n",
" # Loop on the images contained in the sequence\n",
" for i in range(seq_size):\n",
" if w_vid_time.value == 'Variable phi':\n",
" # Inference of the i image in sequence_name[key]\n",
" phi_var = 2*pi/seq_size * i\n",
" my_img = inference(w_vid_seq, i, torch.tensor(phi_var), False)\n",
" else:\n",
" my_img = inference(w_vid_seq, i, torch.tensor(float(w_vid_time.value)), False)\n",
" writer.append_data(np.array(my_img))\n",
" # Progress bar\n",
" w_prog.value += 1\n",
" \n",
" writer.close()\n",
" display(Video(save_name, embed=True))\n",
"\n",
"w_button.on_click(get_video)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}