Techno Blender
Digitally Yours.

Build Elegant Web Apps Right From Jupyter Notebook with Mercury | by Avi Chawla | Apr, 2023

0 44


Photo by NASA on Unsplash

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

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

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

Separate presentation tools and Jupyter (Image by Author)

Wouldn’t it be nice if we could share our findings with others by creating interactive and elegant 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 article, I will demonstrate how you can use Mercury to create stunning web apps and share them with others.

You can find the code for this blog here: GitHub.

Let’s begin 🚀!

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

#1) Jupyter Notebook:

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

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

Mercury’s widgets (Image by Author)

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

Thus, if your app creates a plot or prints a DataFrame, etc., they will appear in the output panel of the web app.

#2) Mercury Server

The server renders the Jupyter Notebook as a web application.

Deploying apps with Mercury (Image by Author)

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

Setting up a web app with Mercury requires a few simple steps.

Install Mercury

First of all, install the library with pip:

pip install mercury

And done!

Now we can create our web app with input and output widgets.

As mentioned above, a web app created using Mercury is primarily powered by its widgets.

#1) Import libraries

To use them, we first import the library. And to reiterate, we will be doing everything from a Jupyter Notebook.

## mercury_app.ipynb

import mercury as mr

Additionally, you may import any other library as needed. For this blog, I will create a web app to analyze a self-created dummy employee dataframe. Thus, I will use the following 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="Employee Data Analysis",
description="Employee Report in Mercury")

#3) Populate the app with widgets

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

Dummy dataset (Image by Author)

Essentially, we will do the following:

  • Add a widget to upload a CSV file.
  • Let the user filter the data based on the entries in the Company_Name column. This will be MultiSelect widget.
  • Additionally, the user can also filter the data based on Credits using a Slider.

Once the data has been filtered, we will display the following:

  • The dimensions 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 build 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 will read it with Pandas as follows:

## mercury_app.ipynb

emp_df = pd.read_csv(data_file.filepath)

Now, we will 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(),
choices=emp_df.Company_Name.unique(),
label="Select Companies")

Here, the value argument refers to the initial value, choices is displayed as a list of values to choose from and the label is a custom text that appears besides the widget.

Next, we have 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 refer to the range of values, label, like before, is a custom text. Finally, step defines the step value of the slider widget.

With this, we are done with the widget addition for interactivity. The final step is to create the plots based on the values in the widgets.

#4) Populate the output panel

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

In other words, to retrieve the value of company widget, we can refer to 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 that 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 ready.

#5) Run the web app

To run the application, navigate to the folder of your app in the command line and run the following command:

mercury run

Consequently, we see the following:

First look at web app (Image by Author)

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

Uploading dataset (Image by Author)

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

Now, we can play around with the input widgets to analyze the data.

Analyzing Dataset (Image by Author)

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

In fact, if we update the notebook, the changes are reflected instantly.

A pertinent question at this point is how Mercury stands in comparison to Streamlit, which I have used in many previous blogs, like here and here.

Streamlit has indeed emerged as one of the most common choices for creating web apps. While the overall experience is incredible, there are, of course, 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 Author)

However, apps created with Mercury are driven by a Jupyter Notebook, and every update is instantly reflected in the web app.

#2) Export as PDF/HTML

Web apps created with Mercury can be easily exported with the click of a button.

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

This allows you to easily share your applications with others over email, chat, etc., and the recipient does not necessarily need Mercury installed.

However, there is no such support with Streamlit.

#3) Create Presentations

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

Mercury vs. Streamlit — presentation (Image by Author)

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

#4) Secure apps with authentication

At times, ensuring that only authorized users can access your apps might be extremely important. This may be due to the presence of sensitive information.

Mercury vs. Streamlit — Security (Image by Author)

With Mercury, you can instantly enable authentication to secure your web apps. Streamlit, natively, does not support authentication.

As a result, when someone runs your web app, they will be prompted to authenticate their details, as shown below:

Mercury authentication window (Image by Author)


Photo by NASA on Unsplash

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

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

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

Separate presentation tools and Jupyter (Image by Author)

Wouldn’t it be nice if we could share our findings with others by creating interactive and elegant 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 article, I will demonstrate how you can use Mercury to create stunning web apps and share them with others.

You can find the code for this blog here: GitHub.

Let’s begin 🚀!

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

#1) Jupyter Notebook:

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

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

Mercury’s widgets (Image by Author)

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

Thus, if your app creates a plot or prints a DataFrame, etc., they will appear in the output panel of the web app.

#2) Mercury Server

The server renders the Jupyter Notebook as a web application.

Deploying apps with Mercury (Image by Author)

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

Setting up a web app with Mercury requires a few simple steps.

Install Mercury

First of all, install the library with pip:

pip install mercury

And done!

Now we can create our web app with input and output widgets.

As mentioned above, a web app created using Mercury is primarily powered by its widgets.

#1) Import libraries

To use them, we first import the library. And to reiterate, we will be doing everything from a Jupyter Notebook.

## mercury_app.ipynb

import mercury as mr

Additionally, you may import any other library as needed. For this blog, I will create a web app to analyze a self-created dummy employee dataframe. Thus, I will use the following 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="Employee Data Analysis",
description="Employee Report in Mercury")

#3) Populate the app with widgets

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

Dummy dataset (Image by Author)

Essentially, we will do the following:

  • Add a widget to upload a CSV file.
  • Let the user filter the data based on the entries in the Company_Name column. This will be MultiSelect widget.
  • Additionally, the user can also filter the data based on Credits using a Slider.

Once the data has been filtered, we will display the following:

  • The dimensions 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 build 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 will read it with Pandas as follows:

## mercury_app.ipynb

emp_df = pd.read_csv(data_file.filepath)

Now, we will 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(),
choices=emp_df.Company_Name.unique(),
label="Select Companies")

Here, the value argument refers to the initial value, choices is displayed as a list of values to choose from and the label is a custom text that appears besides the widget.

Next, we have 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 refer to the range of values, label, like before, is a custom text. Finally, step defines the step value of the slider widget.

With this, we are done with the widget addition for interactivity. The final step is to create the plots based on the values in the widgets.

#4) Populate the output panel

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

In other words, to retrieve the value of company widget, we can refer to 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 that 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 ready.

#5) Run the web app

To run the application, navigate to the folder of your app in the command line and run the following command:

mercury run

Consequently, we see the following:

First look at web app (Image by Author)

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

Uploading dataset (Image by Author)

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

Now, we can play around with the input widgets to analyze the data.

Analyzing Dataset (Image by Author)

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

In fact, if we update the notebook, the changes are reflected instantly.

A pertinent question at this point is how Mercury stands in comparison to Streamlit, which I have used in many previous blogs, like here and here.

Streamlit has indeed emerged as one of the most common choices for creating web apps. While the overall experience is incredible, there are, of course, 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 Author)

However, apps created with Mercury are driven by a Jupyter Notebook, and every update is instantly reflected in the web app.

#2) Export as PDF/HTML

Web apps created with Mercury can be easily exported with the click of a button.

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

This allows you to easily share your applications with others over email, chat, etc., and the recipient does not necessarily need Mercury installed.

However, there is no such support with Streamlit.

#3) Create Presentations

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

Mercury vs. Streamlit — presentation (Image by Author)

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

#4) Secure apps with authentication

At times, ensuring that only authorized users can access your apps might be extremely important. This may be due to the presence of sensitive information.

Mercury vs. Streamlit — Security (Image by Author)

With Mercury, you can instantly enable authentication to secure your web apps. Streamlit, natively, does not support authentication.

As a result, when someone runs your web app, they will be prompted to authenticate their details, as shown below:

Mercury authentication window (Image by Author)

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment