BYU Strategy - Marriott School of Business

Streamlit UI

Introduction to Streamlit

In the rapidly evolving landscape of AI, creating intuitive and interactive user interfaces is crucial for effectively demonstrating AI applications. Streamlit is an open-source app framework specifically designed for machine learning and data science projects. It allows developers to quickly prototype and deploy web applications with minimal effort, making it an ideal tool for building strategic AI solutions. This section will introduce you to Streamlit, providing a comprehensive understanding of its features and capabilities.

Streamlit stands out for its simplicity and ease of use. Unlike traditional web development frameworks that require knowledge of HTML, CSS, and JavaScript, Streamlit allows you to build web applications using only Python. This is particularly advantageous for data scientists and AI practitioners who may not have extensive web development experience. Streamlit automatically updates your application as you modify your code, providing a seamless development experience.

# To get started with Streamlit, first ensure you have it installed.
# You can install Streamlit using pip:

!pip install streamlit

Once installed, you can create a simple Streamlit application with just a few lines of code. Let’s walk through a basic example where we create a simple application that displays a greeting message. This will demonstrate the core concepts of Streamlit, including writing text and running the application.

# Import the Streamlit library
import streamlit as st

# Use the 'st.write()' function to display text
st.write('Hello, welcome to your first Streamlit app!')

# To run this application, save the code in a file, say 'app.py', and use the command:
# streamlit run app.py

The code above demonstrates the simplicity of Streamlit. The st.write() function is versatile, allowing you to display text, data, and even plots. To run the application, open your terminal, navigate to the directory where your script is saved, and execute the command streamlit run app.py. This will start a local server and open the application in your default web browser.

Streamlit also supports interactive widgets, which are essential for creating dynamic AI applications. These widgets include sliders, buttons, and input fields, allowing users to interact with the AI models directly. For example, you can use a slider to adjust parameters of a machine learning model and observe the results in real-time.

# Example of adding an interactive slider in Streamlit
import streamlit as st

# Create a slider widget
slider_value = st.slider('Select a value', 0, 100, 50)

# Display the selected value
st.write('The selected value is:', slider_value)

In this example, the st.slider() function creates a slider that allows users to select a value between 0 and 100. The default value is set to 50. The selected value is then displayed using st.write(). Such interactive elements make it easy to prototype AI solutions where user input is required to test different scenarios or parameters.

Streamlit’s ability to integrate seamlessly with popular Python libraries such as NumPy, Pandas, and Matplotlib further enhances its utility in AI applications. You can easily display data frames, plots, and other visualizations, making it a powerful tool for data exploration and model interpretation. In the next sections, we will explore more advanced features of Streamlit, including how to deploy your applications and integrate them with AI models.

Setting Up Your Development Environment

Before diving into developing user interfaces for AI applications using Streamlit, it is essential to set up a robust development environment. A well-configured environment not only streamlines the development process but also reduces potential errors and enhances productivity. In this section, we’ll walk through the steps required to set up a development environment tailored for building AI applications with Streamlit.

The first step in setting up your development environment is to ensure you have Python installed on your machine. Streamlit, being a Python library, requires Python to run. It is recommended to use the latest version of Python 3 for compatibility and performance reasons. You can download Python from the official Python website and follow the installation instructions specific to your operating system.

# To check if Python is installed and to verify the version, you can run the following command in your terminal:
!python --version

Once Python is installed, the next step is to create a virtual environment. Virtual environments are crucial for managing dependencies and ensuring that your projects do not interfere with each other. They allow you to create isolated spaces on your machine where you can install specific versions of libraries without affecting system-wide installations.

# To create a virtual environment, navigate to your project directory and run:
!python -m venv myenv

# To activate the virtual environment, use the following command:
# On Windows
't myenv\Scripts\activate'

# On macOS and Linux
'source myenv/bin/activate'

With the virtual environment activated, you can now install Streamlit. Using a virtual environment ensures that Streamlit and its dependencies are contained within your project, preventing potential conflicts with other Python projects. Streamlit can be installed using the Python package manager, pip.

# Install Streamlit using pip
!pip install streamlit

After installing Streamlit, it’s a good practice to verify the installation by running a simple Streamlit application. This will confirm that Streamlit is working correctly and that your environment is set up properly. Streamlit provides a sample application that you can run with a single command.

# Run Streamlit's hello command to verify the installation
!streamlit hello

If everything is set up correctly, a new browser window should open, displaying the Streamlit hello application. This application demonstrates some of the basic features of Streamlit and confirms that your development environment is ready for building AI applications. If you encounter any issues, ensure that all paths are correctly set and that the virtual environment is activated.

Finally, it’s important to integrate version control into your development workflow. Git is a widely used version control system that helps you track changes in your code and collaborate with others. By initializing a Git repository in your project directory, you can commit your code changes and push them to remote repositories like GitHub for backup and collaboration.

# Initialize a new Git repository
$ git init

# Add all files to the staging area
$ git add .

# Commit the files to the repository
$ git commit -m "Initial commit"

With your development environment set up, including Python, Streamlit, a virtual environment, and version control, you are now equipped to start prototyping user interfaces for AI applications. Remember, a well-configured environment is the foundation of a successful development process, enabling you to focus on building innovative solutions without unnecessary technical hurdles.

Building Your First Streamlit App

In this section, we will guide you through building your first Streamlit app, a popular framework for creating user interfaces for AI applications. Streamlit is designed to simplify the process of turning data scripts into shareable web apps, making it an excellent choice for prototyping AI solutions. With its simplicity and power, you can create interactive, data-driven applications with minimal code. Let’s dive into the core concepts and steps needed to build your first Streamlit app.

Before we start coding, ensure that you have Streamlit installed in your development environment. You can install it using pip, which is Python’s package installer. Open your terminal or command prompt and run the following command:

pip install streamlit

Once Streamlit is installed, you can create a new Python file for your app. Let’s call it app.py. In this file, you will write the code to define the structure and functionality of your Streamlit application. Streamlit apps are built using Python scripts, and the framework automatically handles the creation of the web interface.

The first step in building your Streamlit app is to import the Streamlit library into your script. After importing, you can use its functions to add various elements to your app, such as text, charts, and interactive widgets. Here’s a simple example to get you started:

import streamlit as st

# Title of the app
st.title('My First Streamlit App')

# Adding text
st.write('Welcome to your first Streamlit app! This is where you can prototype your AI solutions.')

In the code above, we first import Streamlit with the alias st, which is a common convention. We then use st.title() to set the title of the app, which appears prominently at the top of the page. The st.write() function is a versatile command that allows you to display text, data, and even Markdown. This makes it easy to add descriptive content to your app.

Streamlit also supports interactive widgets, which are crucial for AI applications that require user input. For example, you might want to let users select parameters for a machine learning model or input data for analysis. Let’s add a simple slider to our app to demonstrate how user input can be handled:

# Adding a slider
number = st.slider('Select a number', 0, 100, 50)

# Display the selected number
st.write(f'The selected number is {number}')

In this example, we use st.slider() to create a slider widget. The function takes three arguments: the label for the slider, the minimum value, and the maximum value. The fourth argument is the default value. The selected value is stored in the variable number, which we then display using st.write(). This interactivity allows users to easily manipulate parameters and see the results immediately.

To run your Streamlit app, navigate to the directory containing your app.py file in the terminal or command prompt and execute the following command:

streamlit run app.py

This command launches a local web server and opens your app in the default web browser. You can now interact with the app and see how your changes affect its behavior. Streamlit automatically updates the app whenever you save changes to the script, making the development process smooth and efficient.

By following these steps, you’ve created a basic Streamlit app that includes a title, text, and an interactive slider. As you continue to explore Streamlit, you’ll discover more features such as data visualization, media elements, and layout customization, all of which can help you build sophisticated and user-friendly AI applications. In the next sections, we’ll delve deeper into these features and demonstrate how to integrate them into your AI solutions.

Designing User-Friendly Interfaces

In the context of AI applications, designing user-friendly interfaces is crucial for ensuring that users can effectively interact with complex models without needing to understand the underlying technical details. A well-designed interface bridges the gap between sophisticated AI models and end-users, facilitating ease of use, enhancing user experience, and ensuring that the AI solutions are accessible to a broader audience.

A user-friendly interface should be intuitive, meaning that users can navigate and utilize it with minimal instruction. This involves clear labeling, logical layout, and responsive design elements that guide users seamlessly through their interactions. For AI applications, this often means providing clear feedback about the AI’s processing and results, as well as offering easy ways to input data and adjust parameters.

import streamlit as st

# Title for the application
st.title('AI-Powered Image Classifier')

# Explanation of what the app does
st.write('Upload an image and let the AI model classify it into one of the predefined categories.')

# File uploader for image input
uploaded_file = st.file_uploader('Choose an image...', type=['jpg', 'png', 'jpeg'])

if uploaded_file is not None:
    # Display the uploaded image
    st.image(uploaded_file, caption='Uploaded Image', use_column_width=True)
    st.write('Classifying...')

    # Placeholder for AI model prediction
    # In a real-world scenario, this is where the model would process the image
    # and provide a prediction. Here, we simulate the behavior.
    import time
    time.sleep(2)  # Simulate model processing time
    st.write('Prediction: Cat')

In the example above, we use Streamlit to create a simple interface for an AI-powered image classifier. The interface includes a title, a brief explanation of the app’s functionality, and a file uploader for users to upload images. Once an image is uploaded, it is displayed on the interface, and a simulated prediction process is shown. This example highlights the importance of providing immediate feedback to users, which is a key aspect of user-friendly design.

Beyond the basic functionality, designing user-friendly interfaces for AI applications should also consider accessibility and inclusivity. This means ensuring that the interface is usable by people with diverse abilities and preferences. For instance, providing alternative text for images, ensuring that the interface is navigable via keyboard, and supporting screen readers can make the application accessible to more users.

Another important concept in designing user-friendly interfaces for AI applications is the transparency of AI operations. Users should be informed about how their data is used and how the AI arrives at its decisions. This can be achieved by incorporating explainability features, such as visualizations of decision paths or confidence scores, which can help users trust and understand the AI’s outputs.

# Example of adding transparency features
# Displaying a confidence score
confidence_score = 0.85

st.write(f'Confidence Score: {confidence_score * 100:.2f}%')

# Providing a simple explanation of the AI model's decision
st.write('The model has determined that the image most closely matches the category "Cat" based on its training data.')

Incorporating features that enhance transparency, such as confidence scores and explanations of AI decisions, can significantly improve user trust and engagement. By understanding not just the ‘what’ but also the ‘why’ behind AI decisions, users are more likely to feel comfortable and confident using the application. This holistic approach to interface design ensures that AI applications are not only functional but also user-centric and trustworthy.

Handling User Inputs and Interactions

In AI applications, handling user inputs and interactions is a critical aspect of creating a seamless user experience. This process involves capturing user data, processing it, and providing meaningful feedback or results. Effective handling of user inputs not only enhances the usability of the application but also ensures that the AI models receive accurate data for processing. Let’s explore the key concepts involved in managing user inputs and interactions in AI-driven interfaces.

First, consider the types of user inputs that an AI application might need to handle. These could range from text inputs, such as search queries or chat messages, to more complex inputs like images, voice commands, or even gestures. Each type of input requires specific methods of capture and processing. For instance, text inputs might be captured using input fields in a web form, while voice commands might require integration with a speech recognition API.

Let’s consider a simple example where we handle text input in a Python-based web application using the Flask framework. This example will demonstrate how to capture user input from a form, process it, and return a response.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def handle_input():
    if request.method == 'POST':
        user_input = request.form['user_input']
        # Process the input here, for example, by passing it to an AI model
        processed_output = f'Processed: {user_input}'
        return render_template('response.html', output=processed_output)
    return render_template('input_form.html')

if __name__ == '__main__':
    app.run(debug=True)

/* input_form.html */
<!doctype html>
<html>
  <body>
    <form method="post">
      <input type="text" name="user_input" placeholder="Enter your input here">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
/* response.html */ <!doctype html>

Your Input:

{{ output }}


In this example, we use Flask to create a simple web application that handles user input from a form. When the user submits the form, the input is captured and processed. The result is then displayed back to the user. This basic structure can be expanded to include more complex processing, such as passing the input to an AI model for predictions or further analysis.

In addition to capturing inputs, it's essential to handle user interactions effectively. This includes providing feedback or responses that are timely and relevant. For instance, when a user submits a query to an AI-powered search engine, the application should quickly return results that are accurate and useful. This can be achieved by optimizing the performance of the AI models and ensuring that the user interface is responsive.

Moreover, handling errors gracefully is a crucial part of managing user interactions. Users might input data that is unexpected or malformed, and the application should be able to handle these cases without crashing. For example, if a user submits non-text data where text is expected, the application should notify the user with a clear error message and guide them on how to correct the input.

::: {#00eb32b2 .cell execution_count=13}
``` {.python .cell-code}
@app.route('/', methods=['GET', 'POST'])
def handle_input():
    if request.method == 'POST':
        user_input = request.form.get('user_input', '')
        try:
            # Simulate processing and check if input is valid
            if not user_input.strip():
                raise ValueError('Input cannot be empty.')
            processed_output = f'Processed: {user_input}'
        except ValueError as e:
            return render_template('input_form.html', error=str(e))
        return render_template('response.html', output=processed_output)
    return render_template('input_form.html')

:::

In this updated code, we add a simple validation step to check if the user input is empty. If it is, a ValueError is raised, and the error message is displayed back to the user. This approach helps maintain a robust user interface that can guide users in providing the correct input, thereby improving the overall user experience.

Displaying AI Outputs Effectively

In the realm of AI applications, effectively displaying AI outputs is crucial for ensuring user understanding and engagement. The outputs generated by AI systems can be complex, ranging from simple numerical predictions to intricate visualizations. Therefore, the design of user interfaces should prioritize clarity, relevance, and accessibility. This involves not only presenting the data in a user-friendly manner but also providing context that helps users interpret the AI’s results accurately.

One important concept to consider is the use of visual hierarchy. By strategically organizing information, you can guide users’ attention to the most important parts of the AI output. For example, in a predictive analytics dashboard, key metrics or alerts should be prominently displayed using larger fonts or contrasting colors. This helps users quickly grasp the essential information without being overwhelmed by less critical details.

import matplotlib.pyplot as plt

# Sample data
categories = ['Accuracy', 'Precision', 'Recall']
values = [0.95, 0.92, 0.89]

# Create a bar chart
plt.figure(figsize=(8, 4))
plt.bar(categories, values, color=['green', 'blue', 'orange'])
plt.title('Model Performance Metrics')
plt.xlabel('Metrics')
plt.ylabel('Values')
plt.ylim(0, 1)
plt.show()

In the code above, we use a bar chart to display model performance metrics such as accuracy, precision, and recall. By choosing different colors for each bar, we enhance the visual distinction between metrics, making it easier for users to compare values at a glance. This approach leverages visual hierarchy by focusing on the most critical performance indicators.

Another key aspect of displaying AI outputs effectively is providing interpretability. Users need to understand not just the ‘what’ but also the ‘why’ behind AI decisions. For instance, when presenting the output of a machine learning model, consider including explanations or confidence intervals that indicate the reliability of the predictions. This can be achieved through tooltips, annotations, or supplementary explanatory text.

import numpy as np

# Sample AI output
predictions = np.array([0.8, 0.1, 0.1])
labels = ['Cat', 'Dog', 'Rabbit']

# Display predictions with confidence intervals
for i, (label, prediction) in enumerate(zip(labels, predictions)):
    print(f"{label}: {prediction*100:.1f}% confidence")
    # Add a simple interpretation
    if prediction > 0.7:
        print("High confidence in prediction.")
    elif prediction > 0.4:
        print("Moderate confidence in prediction.")
    else:
        print("Low confidence in prediction.")
    print()

This Python code snippet demonstrates how to provide interpretability for AI predictions by displaying confidence levels. By categorizing prediction confidence as high, moderate, or low, users gain a better understanding of how much they can trust the AI’s output. This approach can be particularly useful in applications like medical diagnosis or financial forecasting, where decision-making reliability is paramount.

Finally, consider the context in which your AI application is used. Different users may have varying levels of expertise, which should influence how outputs are displayed. For expert users, detailed data and customizable views might be appropriate, whereas non-experts might benefit from simplified visualizations and guided explanations. By tailoring the user interface to meet these diverse needs, you can enhance the overall user experience and facilitate more effective interactions with your AI application.

Deploying Streamlit Applications

Streamlit is a popular open-source framework that allows developers to create interactive web applications for machine learning and data science projects. It is particularly well-suited for prototyping user interfaces for AI applications because it simplifies the process of turning Python scripts into shareable web apps. Streamlit’s simplicity and ease of use make it an ideal choice for quickly deploying AI prototypes to gather user feedback and iterate on design.

One of the key features of Streamlit is its ability to automatically update the interface as the underlying code changes. This means that developers can focus on building the functionality of their AI applications without worrying about the complexities of front-end development. Streamlit handles the rendering of the user interface, allowing developers to create interactive widgets for inputs and display outputs effectively.

To deploy a Streamlit application, you first need to create a Python script that defines the layout and behavior of your app. Streamlit provides a variety of widgets such as sliders, buttons, and text inputs, which can be used to capture user inputs. These inputs can then be processed by your AI models, and the results can be displayed back to the user in an intuitive manner. Let’s look at a simple example of a Streamlit app that takes a user’s input text and returns a sentiment analysis result using a pre-trained AI model.

import streamlit as st
from textblob import TextBlob

# Title of the application
st.title('Sentiment Analysis App')

# Text input widget
user_input = st.text_area('Enter some text to analyze:')

# Button to trigger analysis
if st.button('Analyze'):
    # Perform sentiment analysis
    blob = TextBlob(user_input)
    sentiment = blob.sentiment.polarity
    
    # Display the result
    if sentiment > 0:
        st.write('The sentiment is positive!')
    elif sentiment < 0:
        st.write('The sentiment is negative!')
    else:
        st.write('The sentiment is neutral.')

In this example, we use the TextBlob library to perform sentiment analysis on the user’s input text. The st.text_area widget allows users to enter text, and the st.button widget is used to trigger the analysis when clicked. The result of the sentiment analysis is then displayed to the user using the st.write function. This simple example demonstrates how Streamlit can be used to build a basic AI application with minimal code.

Once your Streamlit app is ready, deploying it is straightforward. You can run the app locally by executing the command streamlit run your_script.py in your terminal, where your_script.py is the name of your Python file. This will start a local server and open the app in your default web browser. For sharing your app with others, you can deploy it on a cloud platform like Streamlit Cloud, Heroku, or AWS. Each of these platforms requires some additional setup, such as creating an account and configuring the deployment environment, but they provide comprehensive guides to help you through the process.

Deploying your Streamlit application to a platform like Streamlit Cloud involves creating a GitHub repository for your project and connecting it to Streamlit Cloud. Once connected, you can deploy your app directly from the repository, and any changes pushed to the repository will automatically update the deployed app. This seamless integration with version control systems makes it easy to manage and iterate on your AI applications.

In conclusion, Streamlit is a powerful tool for prototyping and deploying user interfaces for AI applications. Its ease of use, combined with the ability to quickly iterate on designs and gather user feedback, makes it an invaluable resource for developers. By leveraging Streamlit’s capabilities, you can focus on building effective AI solutions and ensure that they are accessible and user-friendly.

Best Practices and Common Pitfalls

When prototyping user interfaces for AI applications, adhering to best practices and being aware of common pitfalls is crucial for creating effective and user-friendly solutions. A well-designed interface not only enhances user experience but also ensures that the AI functionalities are accessible and intuitive. Let’s explore some of these best practices and pitfalls, providing insights into how to implement them in your projects.

One of the most important best practices is to keep the user interface simple and focused. AI applications can be complex, but the UI should not overwhelm the user with too many options or data points at once. Instead, prioritize clarity and ease of use by presenting only the most relevant information and controls. Use progressive disclosure to reveal more options as needed, allowing users to explore advanced features without feeling intimidated initially.

import streamlit as st

# Example of a simple and focused UI
st.title('AI Application')

# Basic input for user
user_input = st.text_input('Enter your query:')

# Display results based on input
if user_input:
    st.write(f'Results for: {user_input}')
    # Here you would call your AI model to process the input
    # result = ai_model.process(user_input)
    # st.write(result)

Another best practice is to provide clear feedback to users. When users interact with your AI application, it should be evident that their inputs are being processed and what the outcomes are. For instance, if a user submits a query, the application should acknowledge receipt and indicate that processing is underway. This can be achieved through loading indicators or status messages, which reassure users and improve their overall experience.

# Providing feedback to users
if user_input:
    with st.spinner('Processing...'):
        # Simulate processing time
        import time
        time.sleep(2)
        st.success('Done!')
        # Display the result
        st.write('Your processed result here.')

A common pitfall in prototyping AI interfaces is neglecting error handling and edge cases. AI models can sometimes produce unexpected results or fail to handle certain inputs gracefully. It’s crucial to anticipate these scenarios and implement appropriate error messages or fallback mechanisms. This not only improves robustness but also maintains user trust in the application.

# Example of error handling
try:
    # Simulate a function that may raise an exception
    if user_input:
        if len(user_input) < 3:
            raise ValueError('Input is too short!')
        # Simulate AI processing
        st.write('AI processing successful!')
except ValueError as e:
    st.error(f'Error: {e}')
except Exception as e:
    st.error(f'An unexpected error occurred: {e}')

Lastly, ensure that your user interface is accessible to all users. This includes considering users with disabilities by implementing features like keyboard navigation, screen reader compatibility, and high-contrast modes. Accessibility not only broadens your user base but also demonstrates a commitment to inclusivity. Streamlit, for instance, provides several built-in features that support accessibility, but it’s important to test your application with diverse user scenarios to ensure comprehensive accessibility.