Google collab to html

Putting a web front-end on a Google Colab notebook

Let’s say you’re a data scientist, and you’ve been asked to classify iris flowers based on their measurements (using the famous iris dataset). You’ve written some code in a Colab notebook that solves the problem; however, what you really want is to build an interactive tool, so people can classify the flowers themselves!

In this short tutorial, we are going to build an interactive tool for people to classify iris flowers by connecting a web app to a Colab notebook. The web app will collect the iris measurements from the user, send the data to our Colab notebook, where it will be classified, and then send the classification back to our web app to display to the user.

Читайте также:  Как создать multipartfile java

For this tutorial you will need to know basic Python and have an understanding of how to use Google Colab notebooks.

Step 1 — Create your Anvil app

Creating web apps with Anvil is simple. No need to wrestle with HTML, CSS, JavaScript or PHP. We can do everything in Python.

Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.

Location of the Create App button

First, name the app. Click on the name at the top of the screen and give it a name.

Rename your app by clicking on the title

Step 2 — Design your page

To classify the species of iris a flower comes from, we need to collect several measurements, so let’s design the user interface for entering that data.

We construct the UI by dragging-and-dropping components from the Toolbox. Let’s start by dropping a Card Card iconinto our form – this will be a neat container for the other components. Then let’s add a Label Label iconand a TextBox TextBox iconinto the card component:

Next we will set up the Label and TextBox components to collect enter the sepal length.

Select the Label we just added and, in the properties panel on the right, change the text to ‘Sepal length: ‘ and align the text to the right.

Then select the TextBox we added and change the name to sepal_length , change the placeholder text to ‘(cm)’ and align the text to the centre.

Repeat this process adding labels and text boxes for the other parameters we need: sepal width, petal length and petal width. This will capture all the information we need to classify each iris flower.

Button icon

Next, let’s add a Button to run the classifier. Name it categorise_button and change the text to ‘Categorise’. Clicking this button will trigger a Python function to send the iris measurements to our Colab notebook. (We’ll set that up in a moment.)

Finally, let’s add a Label where we’ll display our results. Put it below the button, call it species_label , centre the text and untick the visible tick box in the properties panel so it doesn’t appear immediately. In step 3 we will create an event handler function that makes the label visible, and uses it to display data returned from our Colab notebook.

Our app should now look like this:

The finished Google Colab app UI

In the next step we will add some code to control what happens when a user pushes the Categorise button.

Step 3 — Add a button click event

We want our categorise_button to do something when it’s clicked, so let’s add a click event.

With the button selected, go to the bottom of the properties panel. Then click the blue button with two arrows in it next to the click event box. This will open our code view and create a function called categorise_button_click() . From now on, every time the button is clicked by a user, this function will be called.

We want to call a function in our Google Colab notebook, and pass it the measurements the user has entered into our web app. When the notebook returns our answer, we’ll display it as text on the species_label :

To do this we add the following:

def categorise_button_click(self, **event_args): """This method is called when the button is clicked""" # Call the google colab function and pass it the iris measurements iris_category = anvil.server.call('predict_iris', self.sepal_length.text, self.sepal_width.text, self.petal_length.text, self.petal_width.text) # If a category is returned set our species if iris_category: self.species_label.visible = True self.species_label.text = "The species is " + iris_category.capitalize()

Now we have a basic UI and functionality, let’s connect our app to the code in our Google Colab notebook.

From the Anvil editor, let’s enable the Uplink. This gives us everything we need to connect our web app to our Colab notebook. Select the blue ‘+’ button in the Sidebar Menu to open the list of available services. Then add the Uplink and click ‘Enable Server Uplink’:

This will then give us an Uplink key we can use in our Google Colab notebook, to connect to this app.

Now let’s install the Uplink in our Colab environment, and connect our script using the key we just created.

In the next few steps, we will be connecting a Colab notebook to the web app we have built. For simplicity, I’ve created a notebook that already handles the iris classification for us. Make a copy of the following notebook to follow along:

In the example Google Colab notebook, I’ve written code that builds and trains a very simple classification model using scikit-learn’s built-in iris dataset and the k-nearest neighbors algorithm. How this works is beyond the scope of this tutorial, but Towards Data Science has a useful article if you’re looking for more information.

The first thing we need to do is install the anvil-uplink library in our Colab environment. Let’s add !pip install anvil-uplink to the top of our notebook.

The ! operator tells our notebook that this line is a command line script and not Python code.

Step 6 — Connecting our Script

Now that the Uplink library will be installed when we start our notebook, we can connect our notebook in the same way as any other Uplink script.

Start by importing the anvil.server module:

Then connect to the Uplink:

anvil.server.connect("your-uplink-key")

Replace “your-uplink-key” with the Uplink key from your app.

That’s it! When we run our notebook, it will now connect to our web app via the Uplink. Next, let’s create a function we can call from our Anvil app.

Step 7 — Creating a callable function

With a classification model built and trained, we can create a function that takes our iris data and returns the name of the iris species. Let’s create a predict_iris function and add @anvil.server.callable so it is available to call from our app.

@anvil.server.callable def predict_iris(sepal_length, sepal_width, petal_length, petal_width): classification = knn.predict([[sepal_length, sepal_width, petal_length, petal_width]]) return iris.target_names[classification][0]

Finally at the end of our notebook we will call the wait_forever() function. This keeps our notebook running and allows our app to call functions indefinitely.

Run the notebook. You should see output like this:

Connecting to wss://anvil.works/uplink Anvil websocket open Authenticated OK

Step 8 — Publishing your app

Now we have our app and script connected, all we have to do is publish our app for our colleagues to use.

Click the ‘Publish’ button at the top right of the editor, then select ‘Publish this app’ and use the public URL provided or enter your own.

That’s it, our notebook is now connected to our Anvil app and anyone with access to your web app can now interact with code in your Google Colab notebook.

Our app has one final problem, Colab notebooks shut down after a certain amount of time. This means our model won’t be available 24 ⁄7 and our app will stop working. To solve this we need to export the model from our Colab notebook and deploy it somewhere else.

Step 9 — Deploying your model

There are two ways to deploy our model and keep it available for our Anvil app to use.

Firstly, we can host the model on our own computer and connect our app to the model using the Anvil Uplink. Here’s a full tutorial which shows you exactly how to do this for free:

The second solution is to deploy our model online with Anvil. This is the simplest way to deploy both our app and model — hosting the model online requires a paid account. Let me quickly show you how it works.

Downloading your model

We’ll start by going back into our Colab notebook. At the end of the cell that builds and trains the iris classification model, we’ll import the joblib library and the files module from google.colab.

. knn = KNeighborsClassifier(n_neighbors=10) knn.fit(X,y) import joblib from google.colab import files model = joblib.dump(knn, "knn.skmodel")[0] files.download(model)

Uploading the model to our app

Now, back in the Anvil editor, let’s add the Data Files service. Select the blue ‘+’ button in the Sidebar Menu and add Data Files.

Adding the Data Files service

Next, we can upload our model as a file by clicking the ‘Upload’ button and selecting the model we downloaded earlier.

An image showing where the 'Upload' button is

Here’s a Gif of the full process for uploading your model:

Configuring your server environment

With our model uploaded, we need to configure our app’s server environment to include all the packages we need to use the model.

Settings Icon

We’ll start by selecting settings icon from the Sidebar Menu and opening ‘Python versions’.

Opening the settings menu

Then, in the Python version dropdown, select ‘Python 3.10’. Under ‘Base packages’, choose the ‘Machine Learning’ base image. This includes all of the packages we’ll need to run the model.

Changing the Python version to 'Python 3.10' and editing the requirements.txt

With our server environment configured, it’s time to start using our model.

Using your hosted model

app icon

Create a Server Module by selecting the App Browser in the Sidebar Menu and clicking ‘+ Add Server Module’.

Adding a server module

At the top of our server module, let’s import the joblib library we need to load our model and import load_iris from sklearn’s built-in iris dataset.

import joblib from sklearn.datasets import load_iris iris = load_iris()

The same as we did in our Colab notebook, let’s define the predict_iris function that takes the flower measurements.

@anvil.server.callable def predict_iris(sepal_length, sepal_width, petal_length, petal_width):

Inside the predict_iris function, we’ll reconstruct our model using joblib.load() . We will get the path to the model file on disk using data_files[‘knn.skmodel’] . Lastly, we’ll get the classification using the same code we used in our Colab notebook.

@anvil.server.callable def predict_iris(sepal_length, sepal_width, petal_length, petal_width): # Reconstruct our model model = joblib.load(data_files['knn.skmodel']) # Get the classification of the iris classification = model.predict([[sepal_length, sepal_width, petal_length, petal_width]]) return iris.target_names[classification][0]

And that’s it! If we go to our app’s URL now and enter some iris measurements, our app will use our Machine Learning model that’s deployed online with Anvil.

I’ve added some images to improve the final app. To do this I simply added an image component to the app and set its source based on the returned iris classification.

Clone the App

For those of you who want to see the source code for this app:

New to Anvil?

If you’re new here, welcome! Anvil is a platform for building full-stack web apps with nothing but Python. No need to wrestle with JS, HTML, CSS, Python, SQL and all their frameworks – just build it all in Python.

Yes – Python that runs in the browser. Python that runs on the server. Python that builds your UI. A drag-and-drop UI editor. We even have a built-in Python database, in case you don’t have your own.

Why not have a play with the app builder? It’s free! Click here to get started:

Share this

  • Anvil Tutorials Get started
  • Developer Docs Start reading
  • Anvil Learning Centre Learn more

Источник

Как конвертировать записную книжку Google Colab (.ipynb) в HTML

Часто нам нужно поделиться пояснениями кода и рисунками, записанными в блокноте Google colab Jupyter (файлы .py или .ipynb), с нашими друзьями / коллегами / начальниками. Самый простой способ — сохранить их в виде файлов PDF. Однако файлы PDF не могут загружать большие цифры или пояснения по уценке.

Альтернативный способ — поделиться ими в виде файлов .html, поскольку это просто — достаточно одного щелчка мышки, чтобы открыть записную книжку, без установки Python или среды colab.

Ниже приведены пошаговые инструкции по экспорту записной книжки Google colab Jupyter в виде HTML-файла.

1. Загрузите записную книжку Colab. В правом верхнем углу нажмите Файл → Загрузить → Загрузить .ipynb.

2. Повторно загрузите загруженный .ipynb в хранилище сеанса.

У вас будет файл .ipynb в хранилище сеанса (помечено синей стрелкой).

3. Запустите приведенный ниже сценарий и нажмите «Обновить» в разделе «Файлы». Вы увидите свою записную книжку как .html (помечено синей стрелкой).

%%shell jupyter nbconvert --to html /Your notebook path/file.ipynb

4. Щелкните три точки рядом с файлом .html и загрузите. Ваш файл готов к публикации!

Не стесняйтесь комментировать / спрашивать! Удачного обучения 🙂

Источник

Оцените статью