MITB Banner

Run your first data analysis program in the browser with PyScript

PyScript allows users to build Python applications on the web using an HTML interface.
Share
Listen to this story

Python is mostly utilised on the backend of websites, with frameworks such as Django and Flask. But, Python did not have as much front-end support as other languages such as JavaScript. But this has changed with PyScript.

PyScript is a Python front-end framework that allows users to build Python applications on the web using an HTML interface. This article will be focused on building a webpage with PyScript where we will perform the visualization of data. 

Table of contents

  1. About PyScript
  2. Working of PyScript
  3. Build a webpage

About PyScript 

PyScript is a JavaScript framework that lets users construct Python apps in the browser by combining Python with regular HTML. The eventual purpose of the project is to enable a much larger audience (for example, front-end developers) to benefit from the power of Python and its numerous libraries (statistical, ML/DL, and so on).

Key features of PyScript

  • Allows us to access Python and its extensive ecosystem of libraries from within the browser (including NumPy, pandas, and scikit-learn).
  • Users can control which packages and files are available when running the page’s code by utilising environment management.
  • We can utilise some of the selected UI components right away, such as buttons, containers, text boxes, and so on.
  • We don’t have to bother about deployment because PyScript handles everything in our web browsers. As data scientists, we could share HTML files containing dashboards and/or models with our stakeholders, who would be able to execute them on their browsers without any technical configuration.

Are you looking for a complete repository of Python libraries used in data science, check out here.

Working of PyScript

Pyodide is the foundation of PyScript. Pyodide is a Python distribution (a CPython version) for the browser and Node.js based on WebAssembly. 

WebAssembly is the technology that allows Python programmers to create web pages. It employs a human-readable text format language that is then translated into a binary code that browsers can execute. We can now create code in any language, compile it to WebAssembly, and run it in a web browser.

Image source

Emscripten, an open-source compiler toolchain, may be seen in the following graphic of the tech stack. It enables the compilation of any portable C/C++ codebase into WebAssembly.

Fortunately, end-users, do not need to completely comprehend what is going on behind the scenes. However, it is unquestionably necessary, for example, for security reasons.

PyScript now allows creating and executing Python code in a browser. The plan for the future is to provide support for more languages. This is also where a possible constraint may arise. Currently, while using PyScript, we can only utilise libraries that Pyodide supports.

Build a webpage

To build a webpage we need to know about HTML and CSS. Let’s start with a basic example of printing “Hello world”.

Defining the HTML structure for webpage

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body>
      <py-script>
          print('Hello Folks')
          print("\U0001f600")  
          print('This is sample webpage running on python with the help of Pyscript')
        </py-script>
    </body>
</html>

Below is what the webpage looks like.

Analytics India Magazine

Now let’s move on to the advanced example. In this example, we will plot some charts using matplotlib.

<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
        - numpy
        - matplotlib
        - seaborn
        - pandas
    </py-env>
</head>
 
<body>
    Hello Folks <br> This is sample webpage running on python with the help of Pyscript
 
    <div id="random-plot">
    <py-script >
        import matplotlib.pyplot as plt
        import numpy as np
       
        x = np.random.randn(1000)
        y = np.random.randn(1000)
       
        fig, ax = plt.subplots(figsize=(15,8))
        plt.title("Scatter plot with random number")
        ax.scatter(x, y)
        plt.tick_params(
        axis='both',          
        which='both',      
        bottom=False,  
        top=False,
        left=False,
        right=False,
        labeltop=False,
        labelleft=False,
        labelright=False,      
        labelbottom=False)
       
        plt.xlabel("Random numbers")
        plt.ylabel("Random numbers")
        fig
    </py-script>
</div>
</body>
</html>

In the above code, there is a div tag that will create a blank box for the content inside the tag. Then by using the py-script tag we can write the whole python within the tag and understand it as writing a python script. To use the Matplotlib, Pandas, and NumPy we need to create an environment for that we are using the py-env tag.

Analytics India Magazine

We can also use the CSS for styling the page and modifying the page, leaving that to you.

Conclusions

PyScript will allow us to run Python (and other) scripts directly from our browsers; the project is being developed by Anaconda; the project is currently in alpha, but we can already experiment with a selection of libraries provided by Pyodide. With this article, we have understood about PyScript utilization in building a webpage in python.

References

PS: The story was written using a keyboard.
Share
Picture of Sourabh Mehta

Sourabh Mehta

Sourabh has worked as a full-time data scientist for an ISP organisation, experienced in analysing patterns and their implementation in product development. He has a keen interest in developing solutions for real-time problems with the help of data both in this universe and metaverse.
Related Posts

CORPORATE TRAINING PROGRAMS ON GENERATIVE AI

Generative AI Skilling for Enterprises

Our customized corporate training program on Generative AI provides a unique opportunity to empower, retain, and advance your talent.

Upcoming Large format Conference

May 30 and 31, 2024 | 📍 Bangalore, India

Download the easiest way to
stay informed

Subscribe to The Belamy: Our Weekly Newsletter

Biggest AI stories, delivered to your inbox every week.

AI Courses & Careers

Become a Certified Generative AI Engineer

AI Forum for India

Our Discord Community for AI Ecosystem, In collaboration with NVIDIA. 

Flagship Events

Rising 2024 | DE&I in Tech Summit

April 4 and 5, 2024 | 📍 Hilton Convention Center, Manyata Tech Park, Bangalore

MachineCon GCC Summit 2024

June 28 2024 | 📍Bangalore, India

MachineCon USA 2024

26 July 2024 | 583 Park Avenue, New York

Cypher India 2024

September 25-27, 2024 | 📍Bangalore, India

Cypher USA 2024

Nov 21-22 2024 | 📍Santa Clara Convention Center, California, USA

Data Engineering Summit 2024

May 30 and 31, 2024 | 📍 Bangalore, India