Home Artificial Intelligence Construct Elegant Web Apps Right From Jupyter Notebook with Mercury

Construct Elegant Web Apps Right From Jupyter Notebook with Mercury

2
Construct Elegant Web Apps Right From Jupyter Notebook with Mercury

Photo by NASA on Unsplash

Effective communication is pivotal in all data-driven projects. Data professionals often need to speak their findings and insights to stakeholders, including business leaders, technical teams, and other data scientists.

While traditional methods of communicating data insights, equivalent to PowerPoint presentations and static reports are widely preferred, they are sometimes time-consuming to create.

What’s more, these services require one to depart the comfort of a Jupyter Notebook — where data scientists spend most of their time.

Separate presentation tools and Jupyter (Image by Writer)

Wouldn’t it’s nice if we could share our findings with others by creating interactive and chic web apps right from a Jupyter Notebook?

To this end, Mercury is an open-source tool that streamlines the creation of web apps right from the comfort of a Jupyter Notebook.

Thus, in this text, I’ll reveal how you should utilize Mercury to create stunning web apps and share them with others.

Yow will discover the code for this blog here: GitHub.

Let’s begin 🚀!

Web apps created by Mercury are primarily driven by two things:

#1) Jupyter Notebook:

That is where you develop the online app. We enable interactivity using Mercury’s input and output widgets.

Input widgets allow the user to offer inputs and interact with the app. A number of the input widgets supported by Mercury are shown below:

Mercury’s widgets (Image by Writer)

Output widgets are used to present the output. This includes Markdowns (with variables), JSONs, etc. What’s more, the output of a Jupyter cell can be rendered by Mercury.

Thus, in case your app creates a plot or prints a DataFrame, etc., they may appear within the output panel of the online app.

#2) Mercury Server

The server renders the Jupyter Notebook as an online application.

Deploying apps with Mercury (Image by Writer)

As we’ll see, rendering the notebook is so simple as running a single command. All you could have to do is create your web app in a notebook.

Establishing an online app with Mercury requires just a few easy steps.

Install Mercury

To begin with, install the library with pip:

pip install mercury

And done!

Now we are able to create our web app with input and output widgets.

As mentioned above, an online app created using Mercury is primarily powered by its widgets.

#1) Import libraries

To make use of them, we first import the library. And to reiterate, we will likely be doing all the pieces from a Jupyter Notebook.

## mercury_app.ipynb

import mercury as mr

Moreover, you could import another library as needed. For this blog, I’ll create an online app to research a self-created dummy worker dataframe. Thus, I’ll use the next libraries as well:

## mercury_app.ipynb

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

sns.set()

#2) Configure the app

Next, we instantiate a Mercury app by providing it a title and description.

## mercury_app.ipynb

app = mr.App(title="Worker Data Evaluation",
description="Worker Report in Mercury")

#3) Populate the app with widgets

Next, let’s add some widgets to permit its user to interact with the next dummy data:

Dummy dataset (Image by Writer)

Essentially, we’ll do the next:

  • Add a widget to upload a CSV file.
  • Let the user filter the information based on the entries within the Company_Name column. This will likely be MultiSelect widget.
  • Moreover, the user may filter the information based on Credits using a Slider.

Once the information has been filtered, we’ll display the next:

  • The size of the filtered DataFrame.
  • A scatter plot of Employee_Salary and Employee_Rating.
  • A bar plot showing the distribution of Employee_Status column.

Let’s construct it now!

First, we add the file upload widget.

## mercury_app.ipynb

data_file = mr.File(label="Upload CSV")

The name of the file is accessible using the filepath attribute of the data_file object. Thus, once the file has been uploaded, we’ll read it with Pandas as follows:

## mercury_app.ipynb

emp_df = pd.read_csv(data_file.filepath)

Now, we’ll add two more widgets — a MultiSelect widget on Company_Name and a Slider on the Credits column.

## mercury_app.ipynb

company = mr.MultiSelect(value=emp_df.Company_Name.unique(),
decisions=emp_df.Company_Name.unique(),
label="Select Firms")

Here, the value argument refers back to the initial value, decisions is displayed as an inventory of values to pick from and the label is a custom text that appears besides the widget.

Next, we’ve got the Slider widget.

## mercury_app.ipynb

credits_filter = mr.Slider(value=1,
min=emp_df.Credits.min(),
max=emp_df.Credits.max(),
label="Credits Filter", step=1)

Here, the value argument defines the initial value, min and max consult with the range of values, label, like before, is a custom text. Finally, step defines the step value of the slider widget.

With this, we’re done with the widget addition for interactivity. The ultimate step is to create the plots based on the values within the widgets.

#4) Populate the output panel

First, we filter the dataframe based on the values received from the widgets. You possibly can access this using the WidgetObj.value attribute.

In other words, to retrieve the worth of company widget, we are able to consult with the company.value attribute.

## mercury_app.ipynb

new_df = emp_df[(emp_df.Company_Name.isin(company.value)) &
(emp_df.Credits>=int(credits_filter.value))]

Next, using the Markdown output widget, we print the dimension of the filtered DataFrame.

## mercury_app.ipynb

mr.Md(f"""The DataFrame has {new_df.shape[0]} rows
and {new_df.shape[1]} columns.""")

One cool thing about Mercury’s markdown is which you can also use f-strings, as shown above.

Lastly, we create the plots:

## mercury_app.ipynb

fig, ax = plt.subplots(1, 2, figsize = (16, 9))

sns.scatterplot(data = new_df, ax = ax[0],
x = "Employee_Rating", y = "Employee_Salary") ## scatter plot

sns.countplot(x = new_df.Employment_Status, ax = ax[1]) ## count plot
plt.show();

That’s it. Now our Mercury application is prepared.

#5) Run the online app

To run the appliance, navigate to the folder of your app within the command line and run the next command:

mercury run

Consequently, we see the next:

First have a look at web app (Image by Writer)

As expected, we’ve got a widget to upload a file. Let’s upload the dummy dataset here.

Uploading dataset (Image by Writer)

Once we upload a CSV, we immediately see the graphs pop up.

Now, we are able to mess around with the input widgets to research the information.

Analyzing Dataset (Image by Writer)

As we update the filter, the plots and the variety of rows update. That is achieved by the Mercury server, which maintains a continuous interaction between the notebook and the app.

In reality, if we update the notebook, the changes are reflected immediately.

A pertinent query at this point is how Mercury stands compared to Streamlit, which I actually have utilized in many previous blogs, like here and here.

Streamlit has indeed emerged as probably the most common decisions for creating web apps. While the general experience is incredible, there are, after all, many limitations with Streamlit:

#1) No Jupyter Support

Streamlit-driven applications are primarily powered by Python scripts, not interactive Python kernels. Thus, while developing an application with Streamlit, one has to repeatedly run a script to see the progress.

Mercury vs. Streamlit — Jupyter support (Image by Writer)

Nevertheless, apps created with Mercury are driven by a Jupyter Notebook, and each update is immediately reflected in the online app.

#2) Export as PDF/HTML

Web apps created with Mercury could be easily exported with the clicking of a button.

Mercury vs. Streamlit — export app (Image by Writer)

This permits you to easily share your applications with others over email, chat, etc., and the recipient doesn’t necessarily need Mercury installed.

Nevertheless, there isn’t a such support with Streamlit.

#3) Create Presentations

Lastly, an online app created with Mercury can run as an interactive presentation with little effort.

Mercury vs. Streamlit — presentation (Image by Writer)

Nevertheless, Streamlit apps don’t offer any such support.

#4) Secure apps with authentication

At times, ensuring that only authorized users can access your apps could be extremely vital. This will be resulting from the presence of sensitive information.

Mercury vs. Streamlit — Security (Image by Writer)

With Mercury, you possibly can immediately enable authentication to secure your web apps. Streamlit, natively, doesn’t support authentication.

In consequence, when someone runs your web app, they will likely be prompted to authenticate their details, as shown below:

Mercury authentication window (Image by Writer)

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here