Skip to main content

Streamlit Tutorial

STREAMLIT VS GRADIO

INTRODUCTION

Streamlit and Gradio are popular open-source frameworks that simplify the process of transforming complex machine learning models into interactive applications. They cater to the needs of developers and data scientists, each offering distinct features and benefits.

Streamlit: Empowering Data Apps

Overview: Streamlit is celebrated for its simplicity and flexibility, allowing developers to convert data scripts into shareable web apps effortlessly.

Key Features

  1. Rapid Prototyping: Streamlit’s intuitive syntax enables quick prototyping, with instant updates upon saving the script.
  2. Customization: Offers predefined widgets and supports personalized themes and layouts.
  3. Wide Language Support: Primarily Python-based but supports multiple languages.
  4. Seamless Integration: Integrates smoothly with libraries like Matplotlib, Plotly, and pandas for dynamic visualizations.
  5. Deployment: Easy deployment on various platforms, including cloud services and local servers.

Gradio: Simplifying Model Deployment

Overview: Gradio focuses on easing model deployment with user-friendly interfaces, targeting both technical and non-technical users.

Key Features

  1. Interface Generation: Automatically generates interfaces using a straightforward Python API.
  2. Variety of Input Types: Supports diverse input types, such as images, text, and audio.
  3. Multi-Model Integration: Facilitates ensemble deployments and model comparisons.
  4. Shareable URLs: Allows easy collaboration by sharing model interfaces as URLs.
  5. Adversarial Robustness: Provides protection against adversarial attacks, enhancing model security.

Comparison and Considerations

Commonalities

  1. Ease of Use: Both platforms simplify the deployment process, even for non-technical users.
  2. Interactive Visualizations: Enable the creation of visually appealing and interactive dashboards.
  3. Community Support: Both have active communities offering resources, tutorials, and extensions.

Differences

  1. Customization: Streamlit offers more customization options for app appearance and functionality.
  2. Multi-Model Deployment: Gradio excels in multi-model deployment, ideal for projects involving multiple models.
  3. Ease of Sharing: Gradio’s shareable URLs enhance collaboration and stakeholder engagement.
  4. Robustness: Gradio’s adversarial robustness features provide an added security layer for sensitive applications.

Choosing between Streamlit and Gradio depends on specific project requirements and the target audience. Streamlit is ideal for projects needing advanced customization and wide integration options, while Gradio is better suited for projects requiring ease of use, multi-model deployment, and robust security features. By understanding the strengths of each platform, developers can make informed decisions to meet their AI deployment goals.

streamlit vs gradio

Reference: Gradio vs. Streamlit Comparison on StackShare

Streamlit Tutorial

Open-Source Python Framework

Streamlit is a powerful, open-source Python framework that empowers data scientists and AI/ML practitioners to rapidly build interactive data applications. Tailored for machine learning and data science projects, Streamlit simplifies the process of developing web apps that are both engaging and visually compelling, requiring only minimal code to get started.

Streamlit Website is the Fastest Way to Build Data Applications

1. Installation and Setup

To get started with Streamlit, we need to install the library using pip. Make sure Python is already installed on your system, as Streamlit requires it.

  1. Install Streamlit:

    Open your terminal or command prompt and run the following command:

    pip install streamlit
  2. Verify Installation:

    After installation, we can check if everything is set up correctly by running:

    streamlit hello

This will launch a sample web application, which is also featured on Streamlit's gallery page.

Setting Up a Virtual Environment

It’s recommended to create a virtual environment for your project to manage dependencies and avoid conflicts.

  1. Navigate to Your Project Directory:

    Use the cd command to move to your project folder. For example:

    cd path/to/your/project
  2. Create the Virtual Environment: Run the following command to create a virtual environment named .venv:

    python -m venv .venv
  3. Activate the Virtual Environment:

    On Windows:

    .venv\Scripts\activate

    On macOS and Linux:

    source .venv/bin/activate

Installing Streamlit:

  1. Install streamlit: With the virtual environment activated, run
pip install streamlit
  1. Verify Streamlit Installation: Check if Streamlit is installed correctly by running
streamlit --version       

Troubleshooting:

error 1

error 2

If an error like this is received that probably means that python is not installed on internal system and hence we will try to install streamlit using alternative methods.

2. Step-by-Step Guide to Install Streamlit using Anaconda

  1. Open Anaconda Navigator: Open the Anaconda Navigator from your Start menu or Applications folder.

  2. Create a New Environment:

    1. Click on the "Environments" tab on the left side. enviroment

    2. Click the "Create" button at the bottom. create env

    3. Give your new environment a name (e.g., streamlit_env) and choose the Python version you want to use (e.g., Python 3.8 or 3.9). env name and python version

  3. Activate the Environment:

    1. Once the environment is created, click on it in the list to select it. select new enviroment

    2. Click the "Open Terminal" button to open a terminal window with the environment activated. open in terminal

  4. Install Streamlit: In the terminal window, run the following command to install Streamlit:

    pip install streamlit

    install streamlit

  5. Verify the Installation: After the installation is complete, verify that Streamlit is installed correctly by running:

    streamlit --version

    verify

    hello

Streamlist is successfully installed.

3. Step-by-Step Guide to Create and Run a Streamlit App

  1. Set Up Your Project Directory: Create a directory for your Streamlit project if you don't already have one.

    mkdir my_streamlit_app

    alt text

    cd my_streamlit_app

    alt text

  2. Create a Python Script:

    1. Open your favorite text editor or IDE (e.g., VSCode, PyCharm, Jupyter Notebook). alt text

    2. Create a new file named app.py alt text

  3. Write Your Streamlit Code: Open app.py and write your Streamlit application code. Here’s an example of a simple Streamlit app:

import streamlit as st

st.title("Hello Streamlit!")
st.write("This is my first Streamlit app.")

# Add some interactive widgets
name = st.text_input("Enter your name:")
if name:
st.write(f"Hello, {name}!")

number = st.slider("Pick a number:", 0, 100)
st.write(f"Your number is {number}")
  1. Run Your Streamlit App: Open a terminal or Command Prompt. Navigate to the directory containing your app.py file. Run the Streamlit application:
streamlit run app.py

This command will start a local server and open your default web browser to http://localhost:8501, where you can see your Streamlit app running

4. Step-by-Step Guide to Code and Run a Streamlit App Using Anaconda

  1. Set Up Your Project Directory:
    1. Choose a location on your system where you want to store your project files.
    2. Create a new directory for your project, for example, my_streamlit_app.
mkdir my_streamlit_app
cd my_streamlit_app

alt text

  1. Create the app.py File:

    1. Open your text editor or IDE.
    2. Create a new file named app.py in the my_streamlit_app directory.

alt text

  1. Write Your Streamlit Code: Open app.py in your preferred text editor or IDE (e.g., VSCode, PyCharm, Jupyter Notebook). Add your Streamlit code to app.py(example code same as used in previous step)

alt text

  1. Activate Your Anaconda Environment:

    1. Open the Anaconda Prompt.
    2. Navigate to your project directory:
    cd path\to\my_streamlit_app
    1. Activate the environment where you have installed Streamlit. For example, if you created an environment named streamlit_env:
    conda activate streamlit_env

    alt text

  2. Run Your Streamlit App: With the environment activated and while in the project directory, run your Streamlit app:

    streamlit run app.py

    alt text

    This command will start a local server and open the default web browser to http://localhost:8501, where we can see the Streamlit app running alt text

Whenever any change is done to the source code, alt text

It is updated automatically in the app. We select always re-run(Can manually re-run after each change is done too )

alt text

Markdown Cheatsheet Link : https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

FREQUENTLY ASKED QUESTIONS

STOPPING THE STREAMLIT SERVER:

When you run a Streamlit app using the command streamlit run app.py in the terminal, the server will continue to run and serve the Streamlit app until you stop it manually.

  1. In the Terminal Window: Windows/Linux/macOS: Press Ctrl + C. This keyboard shortcut sends an interrupt signal to the terminal, which stops the Streamlit server.
  2. Alternative Method: If you started the Streamlit app in a terminal window that you don’t have access to, you can close the terminal window. This will also stop the Streamlit server.

Assuming your directory structure is like this:

D:\Team Project A\staging\
├── file_upload
└── my_streamlit_app

-To navigate from file_upload to my_streamlit_app:

Navigate Up One Level:

cd ..

alt text

-Navigate to my_streamlit_app:

cd my_streamlit_app

alt text

REFERENCES

  1. The guidance on installing Streamlit using Anaconda
  2. Streamlit Official Website
  3. YouTube Tutorial on Streamlit
  4. Streamlit vs. Gradio: A Comprehensive Comparison