File size: 2,033 Bytes
0566d70
1
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: image_classifier"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy tensorflow requests "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/imagenet_labels.json https://github.com/gradio-app/gradio/raw/main/demo/image_classifier/files/imagenet_labels.json"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import requests\n", "import tensorflow as tf  # type: ignore\n", "\n", "import gradio as gr\n", "# get_image() returns the file path to sample images included with Gradio\n", "from gradio.media import get_image\n", "\n", "inception_net = tf.keras.applications.MobileNetV2()  # load the model\n", "\n", "# Download human-readable labels for ImageNet.\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "def classify_image(inp):\n", "    inp = inp.reshape((-1, 224, 224, 3))\n", "    inp = tf.keras.applications.mobilenet_v2.preprocess_input(inp)\n", "    prediction = inception_net.predict(inp).flatten()\n", "    return {labels[i]: float(prediction[i]) for i in range(1000)}\n", "\n", "image = gr.Image()\n", "label = gr.Label(num_top_classes=3)\n", "\n", "demo = gr.Interface(\n", "    fn=classify_image,\n", "    inputs=image,\n", "    outputs=label,\n", "    examples=[\n", "        get_image(\"cheetah1.jpg\"),\n", "        get_image(\"lion.jpg\")\n", "        ],\n", "    api_name=\"predict\"\n", "    )\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}