{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Implementación-del-modelo-como-una-Web-App\" data-toc-modified-id=\"Implementación-del-modelo-como-una-Web-App-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Implementación del modelo como una Web App</a></span></li></ul></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Implementación del modelo como una Web App"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-06T22:40:31.231371Z",
     "start_time": "2022-02-06T22:40:25.856446Z"
    }
   },
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import PIL\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-01-24T14:01:13.298437Z",
     "start_time": "2022-01-24T14:01:13.293451Z"
    }
   },
   "source": [
    "En primer lugar, creamos la función sobre la que envolveremos la interfaz de Gradio. Para ello, cargamos el modelo:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-06T22:40:32.997510Z",
     "start_time": "2022-02-06T22:40:31.232369Z"
    }
   },
   "outputs": [],
   "source": [
    "model = tf.keras.models.load_model('model.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-06T22:40:33.013563Z",
     "start_time": "2022-02-06T22:40:32.998484Z"
    }
   },
   "outputs": [],
   "source": [
    "class_name_list = ['Edible', 'Inedible', 'Poisonous']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-06T22:40:33.028866Z",
     "start_time": "2022-02-06T22:40:33.014537Z"
    }
   },
   "outputs": [],
   "source": [
    "def predict_image(img):\n",
    "    # Reescalamos la imagen en 4 dimensiones\n",
    "    img_4d = img.reshape(-1,224,224,3)\n",
    "    # Predicción del modelo\n",
    "    prediction = model.predict(img_4d)[0]\n",
    "    # Diccionario con todas las clases y las probabilidades correspondientes\n",
    "    return {class_name_list[i]: float(prediction[i]) for i in range(3)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-06T22:40:36.372549Z",
     "start_time": "2022-02-06T22:40:33.029834Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Usuario\\anaconda3\\envs\\python38gpu\\lib\\site-packages\\gradio\\interface.py:272: UserWarning: 'darkpeach' theme name is deprecated, using dark-peach instead.\n",
      "  warnings.warn(\n",
      "C:\\Users\\Usuario\\anaconda3\\envs\\python38gpu\\lib\\site-packages\\gradio\\interface.py:338: UserWarning: The `allow_flagging` parameter in `Interface` nowtakes a string value ('auto', 'manual', or 'never'), not a boolean. Setting parameter to: 'never'.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7860/\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"900\"\n",
       "            height=\"500\"\n",
       "            src=\"http://127.0.0.1:7860/\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x1875520e790>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "(<fastapi.applications.FastAPI at 0x1873512db50>,\n",
       " 'http://127.0.0.1:7860/',\n",
       " None)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "image = gr.inputs.Image(shape=(224,224))\n",
    "label = gr.outputs.Label(num_top_classes=3)\n",
    "title = 'Mushroom Edibility Classifier'\n",
    "description = 'Get the edibility classification for the input mushroom image'\n",
    "examples=[['app_interface/Boletus edulis 15 wf.jpg'],\n",
    "          ['app_interface/Cantharelluscibarius5 mw.jpg'],\n",
    "          ['app_interface/Agaricus augustus 2 wf.jpg'],\n",
    "          ['app_interface/Coprinellus micaceus 8 wf.jpg'],\n",
    "          ['app_interface/Clavulinopsis fusiformis 2 fp.jpg'],\n",
    "          ['app_interface/Amanita torrendii 8 fp.jpg'],\n",
    "          ['app_interface/Russula sanguinea 5 fp.jpg'],\n",
    "          ['app_interface/Caloceraviscosa1 mw.jpg'],\n",
    "          ['app_interface/Amanita muscaria 1 wf.jpg'],\n",
    "          ['app_interface/Amanita pantherina 11 wf.jpg'],\n",
    "          ['app_interface/Lactarius torminosus 6 fp.jpg'],\n",
    "          ['app_interface/Amanitaphalloides1 mw.jpg']]\n",
    "thumbnail = 'app_interface/thumbnail.png'\n",
    "article = '''\n",
    "<!DOCTYPE html>\n",
    "<html>\n",
    "<body>\n",
    "<p>The Mushroom Edibility Classifier is an MVP for CNN multiclass classification model.<br>\n",
    "It has been trained after gathering <b>5500 mushroom images</b> through Web Scraping techniques from the following web sites:</p>\n",
    "<br>\n",
    "<p>\n",
    "<a href=\"https://www.mushroom.world/\">- Mushroom World</a><br>\n",
    "<a href=\"https://www.wildfooduk.com/mushroom-guide/\">- Wild Food UK</a> <br>\n",
    "<a href=\"https://www.fungipedia.org/hongos\">- Fungipedia</a><\n",
    "</p>\n",
    "<br>\n",
    "<p style=\"color:Orange;\">Note: <i>model created solely and exclusively for academic purposes. The results provided by the model should never be considered definitive as the accuracy of the model is not guaranteed.</i></p>\n",
    "\n",
    "<br>\n",
    "<p><b>MODEL METRICS:</b></p>  \n",
    "<table>\n",
    "  <tr>\n",
    "    <th> </th>\n",
    "    <th>precision</th>\n",
    "    <th>recall</th>\n",
    "    <th>f1-score</th>\n",
    "    <th>support</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Edible</th>\n",
    "    <th>0.61</th>\n",
    "    <th>0.70</th>\n",
    "    <th>0.65</th>\n",
    "    <th>481</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Inedible</th>\n",
    "    <th>0.67</th>\n",
    "    <th>0.69</th>\n",
    "    <th>0.68</th>\n",
    "    <th>439</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Poisonous</th>\n",
    "    <th>0.52</th>\n",
    "    <th>0.28</th>\n",
    "    <th>0.36</th>\n",
    "    <th>192</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "  <th></th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Global Accuracy</th>\n",
    "    <th></th>\n",
    "    <th></th>\n",
    "    <th>0.63</th>\n",
    "    <th>1112</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Macro Average</th>\n",
    "    <th>0.60</th>\n",
    "    <th>0.56</th>\n",
    "    <th>0.57</th>\n",
    "    <th>1112</th>\n",
    "  </tr>\n",
    "  <tr>\n",
    "    <th>Weighted Average</th>\n",
    "    <th>0.62</th>\n",
    "    <th>0.63</th>\n",
    "    <th>0.61</th>\n",
    "    <th>1112</th>\n",
    "  </tr>\n",
    "</table>\n",
    "<br>\n",
    "<p><i>Author: Íñigo Sarralde Alzórriz</i></p> \n",
    "</body>\n",
    "</html>\n",
    "'''\n",
    "\n",
    "iface = gr.Interface(fn=predict_image, \n",
    "                     inputs=image, \n",
    "                     outputs=label,\n",
    "                     interpretation='default',\n",
    "                     title = title,\n",
    "                     description = description,\n",
    "                     theme = 'darkpeach',\n",
    "                     examples = examples,\n",
    "                     thumbnail = thumbnail,\n",
    "                     article = article,\n",
    "                     allow_flagging = False,\n",
    "                     allow_screenshot = False,                     \n",
    "                    )\n",
    "iface.launch()"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [
    "eRTY-COfOwwD",
    "ip1P14xN-uSX",
    "VaNHXO2N_Hv-",
    "mhPpAK2bMyQZ",
    "rEI-mXrkU4ku"
   ],
   "name": "PrevioTFM3.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.8.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": true,
   "toc_position": {
    "height": "877px",
    "left": "70px",
    "top": "111.125px",
    "width": "316.771px"
   },
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}