How AI Engineers Can Use the Streamlit Library
Credit: blog.streamli.io

How AI Engineers Can Use the Streamlit Library

Streamlit is an open-source Python framework that allows data scientists and AI/ML engineers to create interactive data applications quickly and effortlessly. This blog will guide you through the essentials of using Streamlit, from installation to advanced features, and provide practical examples to illustrate its capabilities.

Introduction to Streamlit

Streamlit simplifies the process of creating web applications for machine learning and data science projects. Unlike traditional web frameworks, Streamlit allows you to build applications with just a few lines of Python code, eliminating the need for HTML, CSS, or JavaScript.

Why Use Streamlit?

- Ease of Use: Streamlit is designed to be user-friendly. You can create a web app by writing Python scripts.

- Rapid Development: Build and deploy applications quickly without extensive front-end development.

- Interactivity: Add interactive widgets like sliders, buttons, and text inputs with minimal code.

- Integration: Seamlessly integrates with popular Python libraries such as NumPy, Pandas, Matplotlib, and TensorFlow.

Getting Started

Installation

To install Streamlit, you can use pip:

pip install streamlit        

To verify the installation, run the following command:

streamlit hello        

This will launch a sample Streamlit app in your browser.

Basic Structure of a Streamlit App

A basic Streamlit app consists of importing the library and using its functions to display content. Here’s a simple example:

import streamlit as st 
st.title("Hello, Streamlit!")
st.write("This is a simple Streamlit app.")        

To run the app, save the script as app.py and use the command:

streamlit run app.py        

Core Components

Streamlit provides a variety of components to build interactive applications. Here are some of the most commonly used ones:

Text Elements

  • st.title(): Displays a title.
  • st.header(): Displays a header.
  • st.subheader(): Displays a subheader.
  • st.text(): Displays text.
  • st.markdown(): Displays Markdown text.
  • st.latex(): Displays LaTeX equations.

Example:

st.title("Streamlit Components")
st.header("Text Elements")
st.subheader("Subheader Example")
st.text("This is a simple text.")
st.markdown("**Markdown** allows formatting.")
st.latex(r''' e^{i\pi} + 1 = 0 ''')        

Data Display Elements

  • st.dataframe(): Displays a Pandas DataFrame.
  • st.table(): Displays a static table.
  • st.json(): Displays JSON data.

Example:

import pandas as pd
data = {'Column 1': [1, 2, 3], 'Column 2': [4, 5, 6]}
df = pd.DataFrame(data)
st.dataframe(df)
st.table(df)
st.json(data)        

Media Elements

  • st.image(): Displays an image.
  • st.audio(): Plays an audio file.
  • st.video(): Plays a video file.

Example:

st.image("path/to/image.png", caption="Sample Image")
st.audio("path/to/audio.mp3")
st.video("path/to/video.mp4")        

Widgets

  • st.button(): Creates a button.
  • st.checkbox(): Creates a checkbox.
  • st.radio(): Creates a set of radio buttons.
  • st.selectbox(): Creates a dropdown menu.
  • st.slider(): Creates a slider.
  • st.text_input(): Creates a text input box.

Example:

if st.button("Click Me"):
    st.write("Button clicked!")
checkbox = st.checkbox("Check me")
if checkbox:
    st.write("Checkbox checked!")
option = st.selectbox("Select an option", ["Option 1", "Option 2", "Option 3"])
st.write("You selected:", option)
value = st.slider("Select a value", 0, 100)
st.write("Slider value:", value)
text = st.text_input("Enter some text")
st.write("You entered:", text)        

Building a Machine Learning Application

Let's build a simple machine learning application using Streamlit. We'll create an app that allows users to upload an image and classify it using a pre-trained model.

Step 1: Setting Up the Environment

First, install the necessary libraries:

pip install streamlit tensorflow pillow matplotlib numpy        

Step 2: Loading the Pre-trained Model

We'll use a TensorFlow Hub model for image classification. Here’s how to load the model:

import tensorflow as tf
import tensorflow_hub as hub
model = hub.load("https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/5")        

Step 3: Building the Streamlit App

Create a new file app.py and add the following code:

import streamlit as st
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# Load the model
model = hub.load("https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/5")
def predict(image):
    image = np.array(image.resize((224, 224)))/255.0
    image = np.expand_dims(image, axis=0)
    predictions = model(image)
    return predictions
st.title("Image Classification App")
st.header("Upload an Image")
file_uploaded = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if file_uploaded is not None:
    image = Image.open(file_uploaded)
    st.image(image, caption="Uploaded Image", use_column_width=True)
    st.write("")
    st.write("Classifying...")
    predictions = predict(image)
    st.write(predictions)        

Step 4: Running the App

Run the app using the command:

streamlit run app.py        

Advanced Features

Streamlit offers several advanced features that can enhance your applications.

Multipage Apps

Streamlit supports multipage applications, allowing you to create complex apps with multiple pages.

Example:

import streamlit as st
def page1():
    st.title("Page 1")
    st.write("This is the first page.")
def page2():
    st.title("Page 2")
    st.write("This is the second page.")
page = st.sidebar.selectbox("Select a page", ["Page 1", "Page 2"])
if page == "Page 1":
    page1()
else:
    page2()        

Custom Components

You can create custom components to extend Streamlit’s functionality. This is useful when you need features not provided by default.

Example:

import streamlit.components.v1 as components
# Create a custom HTML component
components.html("""
    <div style="color: red; font-size: 20px;">
        Custom HTML Component
    </div>
""")        


Theming and Configuration

Streamlit allows you to customize the appearance and behavior of your app through configuration files.

Example config.toml:

[theme]
primaryColor = "#4CAF50"
backgroundColor = "#FFFFFF"
secondaryBackgroundColor = "#F0F0F0"
textColor = "#000000"
font = "sans serif"        

To apply the configuration, run your app with:

streamlit run app.py --config config.toml        

Deployment

Streamlit apps can be deployed easily using Streamlit Community Cloud or other platforms like Heroku, AWS, and Google Cloud.

Deploying on Streamlit Community Cloud

1. Push your code to a GitHub repository.

2. Go to [Streamlit Community Cloud](https://share.streamlit.io/).

3. Click "New app" and connect your GitHub repository.

4. Select the branch and the main file (`app.py`).

5. Click "Deploy".

Your app will be live and accessible via a URL.

Real-World Applications

Streamlit is versatile and can be used for various applications, including:

- Data Visualization Dashboards: Create interactive dashboards to visualize data.

- Machine Learning Model Deployment: Deploy ML models and provide an interface for users to interact with them.

- Data Analysis Tools: Build tools for data analysis and exploration.

- Generative AI Apps: Integrate with large language models (LLMs) to create generative AI applications.

Conclusion

Streamlit is a powerful tool for AI engineers and data scientists, making it easy to create and share interactive web applications. Its simplicity, flexibility, and integration capabilities make it an excellent choice for rapid application development. Whether you're building a simple data visualization tool or a complex machine learning application, Streamlit provides the tools you need to bring your ideas to life.

By following the steps and examples provided in this blog, you should be well on your way to creating your own Streamlit applications. Happy coding!

Citations:

[1] https://streamlit.io

[2] https://docs.streamlit.io

[3] https://docs.streamlit.io/develop/concepts

[4] https://streamlit.io/generative-ai

[5] https://neptune.ai/blog/streamlit-guide-machine-learning

[6] https://streamlit.io/gallery?category=llms

[7] https://www.youtube.com/watch?v=eoH2NviL8cs

要查看或添加评论,请登录

社区洞察

其他会员也浏览了