Turn a Jupyter Notebook into a Web App | DevsDay.ru

IT-блоги Turn a Jupyter Notebook into a Web App

dev.to 4 мая 2021 г.

Let’s say you’re a data scientist, and you’ve been asked to solve a problem. Of course, what you really want is to build an interactive tool, so your colleagues can solve the problem themselves!

In this tutorial, I'll show you how to take a machine-learning model in a Jupyter notebook, and turn it into a web application using the Anvil Uplink.

Here's what we'll do:

  1. Set up a Jupyter notebook
  2. Connect it to an Anvil app
  3. Make a user interface

Setting up the Jupyter Notebook

We'll start with a pre-existing Jupyter Notebook containing a classification model that distinguishes between cats and dogs. You give it an image and it scores it as ‘cat’ or ‘dog’.

(Thanks to Uysim Ty for sharing it on Kaggle.)

Connecting to the Uplink

We'll use the Anvil Uplink to connect a Jupyter Notebook to Anvil. It’s a library you can pip install on your computer or wherever your Notebook is running.

It allows you to:

  • call functions in your Jupyter Notebook from your Anvil app
  • call functions in your Anvil app from your Juypter Notebook - store data in your Anvil app from your Jupyter Notebook
  • use the Anvil server library inside your Jupyter Notebook

It works for any Python process - this happens to be a Jupyter Notebook, but it could be an ordinary Python script, a Flask app, even the Python REPL!

To connect our notebook, we'll first need to enable the Uplink in the Anvil IDE.


This gives us a key that we can then use in our code.


We then need to pip install the Uplink library on the machine the Jupyter Notebook is running on:

pip install anvil-uplink

By adding the following lines to our Jupyter notebook, we can connect it to our Anvil app:

import anvil.server


Now we can do anything in our Jupyter Notebook that we can do in an Anvil Server Module - call Anvil server functions, store data in Data Tables, and define server functions to be called from other parts of the app.

Loading an image into the Notebook

We'll load an image into the Jupyter Notebook by making an anvil.server.callable function in the Jupyter Notebook. It will classify the input image as either a cat or a dog.

import anvil.media

def classify_image(file):
   with anvil.media.TempFile(file) as filename:
      img = load_img(filename)

We’re passing the image in as an Anvil Media object, which we then write to a temporary file.

The load_img function loads the file into Pillow, a Python imaging library.

Then we can do a bit of post-processing of the image to get it into a format that the model likes:

    # Inside the classify_image function

    img = img.resize((128, 128), resample=PIL.Image.BICUBIC)
    arr = img_to_array(img)
    arr = np.expand_dims(arr, axis=0)
    arr /= 255

Then we can just pass it into our model and return the result:

    # Inside the classify_image function

    score = model.predict(arr)
    return ('dog' if score < 0.5 else 'cat', float(score))

Building a User Interface

We can drag-and-drop components to create a User Interface. It consists of a FileLoader to upload the images, an Image to display them, and a Label to display the classification.


Making the UI call the Notebook

Now we need to write some Python code that runs in the browser so the app responds when an image is loaded in.

We can define an event handler that triggers when the FileLoader gets a new file:

  def file_loader_1_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader."""
    result, score = anvil.server.call('classify_image', file)

    self.result_lbl.text = "%s (%0.2f)" % (result, score)
    self.image_1.source = file

The first line calls the classify_image function in the Jupyter Notebook, passing in the image file.

Then we display the result (cat or dog) and the score (0 to 1; completely dog or completely cat).

We also put the image file into the Image component so that the user can see their cat or dog (or other cat-or-dog-like image) and decide if they agree with the result.


Your app is already published at a private URL, but we can give it a public URL. You can check out this finished app at https://cat-or-dog.anvil.app.

Check out the whole tutorial:

Источник: dev.to

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

python datascience

Читайте также

[Перевод] Запуск домашнего веб-сервера без статического IP с помощью Python

Разработка habr.com 13 мая 2021 г. 3:55
Приветствую жителей Хабра! Задался тут вопросом, как можно обойтись без статического IP для экспериментов в домашних условиях. Наткнулся на вот эту статью. Если вы хотите развернуть свой вебсервер с доступом извне, а платить провайдеру за статическ...... читать далее
Python Разработка на Raspberry Pi python raspberry pi gmail api google domains веб-сервер

How to build an air quality monitor using Raspberry Pi Zero W

Разработка dev.to 13 мая 2021 г. 2:32
Hi, it's Takuya. Knowing the air quality is useful to keep yourself productive because the bad air quality would affect your brain performance more than you'd think. So, I built a room air quality monitor that displays the temperature, humidity, CO2...... читать далее
raspberrypi diy iot

Разработка dev.to 12 мая 2021 г. 21:55

So you want to write a CLI utility in Python. The goal is to be able to write: $ ./say_something.py -w "hello, world" hello, world And then to get your script running. This isn't so hard and you've probably done it already, but have you thou...... читать далее

python tutorial learning

Разработка dev.to 12 мая 2021 г. 21:11

There are several problems in computer science that are very hard. One of them is naming things. So it should no surprise when names make little sense. One of the "bad" names is "Infrastructure as Code". I think it misleads more than it reflects the...... читать далее

cloud terraform programming devops

Разработка habr.com 12 мая 2021 г. 20:28

Квалификацию надо иногда повышать, и вообще учиться для мозгов полезно. А потому пошел я недавно на курсы - поизучать Python и всякие его фреймворки. На днях вот до Django добрался. И тут мы в ходе обучения коллективно выловили не то чтобы баг, но ди...... читать далее

Python encodings python3 sqlite json windows 10

Разработка dev.to 12 мая 2021 г. 18:09

How to calculate the distance between the objects in the image with Python. Today I want to show you how to calculate the distance between the objects in the image. We will write an awesome algorithm that you can modify and extend to your needs...... читать далее

python tutorial showdev computervision

Разработка dev.to 12 мая 2021 г. 17:40

Learning data science and machine learning is very much important now a days to get a sustainable survival in the hot jobs of 2021. Getting knowledge is a key to get on a right path. Here, i am sharing a list of machine learning algorithms to get st...... читать далее

machinelearning python programming datascience

Популярные темы

новости (402) javascript (401) ux (381) design (349) headline (303) python (295) devops (255) ubuntu (240) tutorial (226) ux-design (225) programming (216) security (211) новость (204) web dev (196) webdev (180) working in tech (153) seo (152) дайджесты вакансий от new.hr (150) статьи (144) ui (135) testing roundup (122) software testing (121) css (118) react (117) user-experience (116) java (114) дизайн (102) google (100) beginners (99) product-design (94) игровые проекты (90) ui-design (88) productivity (86) design-thinking (85) php (84) technology (83) primary (81) движки и конструкторы игр (80) прочее (80) job hunting (78) cloud (77) api5 (76) технологии (76) windows 10 (74) бизнес (73) docker (72) laravel (71) bash programming (69) debian (68) android (68) uncategorized (68) tutorials (68) hardware (67) news (60) мероприятия (60) linux mint (59) обучение (58) linux (57) kubernetes (57) networking (56) работа (56) ios (55) games (54) art (54) инструкции (53) machine learning (53) angular (52) español (51) aws (51) api (51) html (51) ux-research (50) git (50) node (50) linux commands (50) case-study (50) covid-19 (50) apple (50) разработчики (50) web design and applications (50) обзоры (49) cybersecurity (49) data (49) chrome (48) engineering (48) турбо-страницы (47) typescript (47) job skills (47) inspiration (47) web (46) dotnet (45) home page stories (45) publication (45) mobile (44) powershell (44) c++ (43) tools (43) навыки алисы (43) testing (42) codenewbie (42)