File size: 1,770 Bytes
176faa1
1
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: image_classification\n", "### Simple image classification in Pytorch with Gradio's Image input and Label output.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchvision"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/image_classification/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "import requests\n", "from torchvision import transforms\n", "\n", "model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval()\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "def predict(inp):\n", "  inp = transforms.ToTensor()(inp).unsqueeze(0)\n", "  with torch.no_grad():\n", "    prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)\n", "    confidences = {labels[i]: float(prediction[i]) for i in range(1000)}    \n", "  return confidences\n", "\n", "demo = gr.Interface(fn=predict, \n", "             inputs=gr.Image(type=\"pil\"),\n", "             outputs=gr.Label(num_top_classes=3),\n", "             examples=[[\"cheetah.jpg\"]],\n", "             )\n", "             \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}