StreamLit - DrAlzahraniProjects/csusb_fall2024_cse6550_team4 GitHub Wiki

Streamlit Documentation

Table of Contents

  1. Installation
  2. Configuration
  3. Implementation
  4. Usage
  5. Troubleshooting

installation

To install Streamlit, you need Python installed on your machine. Streamlit supports Python 3.7 through 3.10. You can install Streamlit using pip:

RUN pip install --no-cache-dir streamlit matplotlib

Screenshot (82)

Ensure you have the latest version of pip:

RUN apt-get update && apt-get install -y \

Screenshot (84)

Install Mamba

Install mamba (a faster package manager) via Conda

RUN conda install -c conda-forge mamba -y

Screenshot (89)

Install Python Packages

Copy the requirements.txt file and install listed packages using mamba:

COPY requirements.txt /app/requirements.txt
RUN mamba install --name team4_env --yes --file requirements.txt && mamba clean --all -f -y

Screenshot (100)

For packages not available via Conda, use pip:

RUN /opt/conda/envs/team4_env/bin/pip install huggingface-hub matplotlib scikit-learn

Screenshot (100)

Starting the Streamlit Server

The CMD command starts the Streamlit server with the following options:

The CMD command starts the Streamlit server with the following options:

Screenshot (101)

Start the Streamlit Server

The CMD section of the Dockerfile starts the Streamlit server. This command ensures that the app is ready to serve on the specified port and path.

CMD ["sh", "-c", "streamlit run app.py --server.port=5004 --server.address=0.0.0.0 --server.baseUrlPath=/team4 --logger.level=error > /dev/null 2>&1 & jupyter server --ip=0.0.0.0 --port=6004 --no-browser --allow-root --ServerApp.token='' --ServerApp.password='' --ServerApp.root_dir='/app/jupyter' --ServerApp.base_url='/team4/jupyter' > /dev/null 2>&1"]

Screenshot (101)

Configuration

Streamlit can be configured using a config.toml file, allowing you to customize various settings. This file typically resides in the .streamlit directory in your project folder.

Set environment variables for Streamlit to specify the port and base URL path

ENV STREAMLIT_SERVER_BASEURLPATH=/team4
ENV STREAMLIT_SERVER_PORT=5004

Screenshot (86)

File Paths

CSS File for Custom Styling Located in the app.py:

css_file_path = os.path.join(os.path.dirname(__file__), 'styles', 'styles.css')

Screenshot (122)

Disable Streamlit usage statistics

RUN mkdir -p ~/.streamlit && \
    echo "[browser]" > ~/.streamlit/config.toml && \
    echo "gatherUsageStats = false" >> ~/.streamlit/config.toml

Screenshot (99)

Expose Required Ports

Open ports for Streamlit and Jupyter

EXPOSE 5004
EXPOSE 6004

Screenshot (87)

Run the Application

Set the default command to launch Streamlit and Jupyter

CMD ["sh", "-c", "streamlit run app.py --server.port=5004 --server.address=0.0.0.0 --server.baseUrlPath=/team4 --logger.level=error > /dev/null 2>&1 & jupyter server --ip=0.0.0.0 --port=6004 --no-browser --allow-root --ServerApp.token='' --ServerApp.password='' --ServerApp.root_dir='/app/jupyter' --ServerApp.base_url='/team4/jupyter' > /dev/null 2>&1"]

Screenshot (99)

Common Configuration Options

  • headless: Run Streamlit in headless mode (useful for deployment).
  • port: The port on which the Streamlit app will run.
  • enableCORS: Enables Cross-Origin Resource Sharing.

Implementation

Performance Metrics Management

Resetting Metrics

def reset_metrics():
    if st.sidebar.button("Reset"):
        try:
            db_client.reset_performance_metrics()
            st.success("Metrics reset successfully.")
            st.rerun()
        except Exception:
            st.sidebar.error("Error resetting performance metrics.")

Screenshot (118)

Displaying Metrics

Sidebar UI

def create_sidebar(result):
    st.sidebar.markdown(f"""
        <div class='custom-container'>
            <div class='keybox'>Sensitivity: {result['sensitivity']}</div>
            ...
    """, unsafe_allow_html=True)

Screenshot (119)

Metric Table

def create_table(result):
    st.sidebar.markdown(f"""
        <div class='custom-container'>
            <table class='table-style'>...</table>
        </div> """, unsafe_allow_html=True)

Screenshot (120)

Bot Responses

def generate_bot_response(user_input, unique_id):
    rag_output = query_rag(user_input)
    bot_response = rag_output[0] if isinstance(rag_output, tuple) else str(rag_output)
    cleaned_response = clean_repeated_text(bot_response)

Screenshot (121)

Basic Example

To implement a basic Streamlit application, create a new Python file, e.g., app.py. Below is a simple example of a Streamlit application:

import streamlit as st

### db_client = DatabaseClient()
st.set_page_config(page_title="Team4 Chatbot", layout="wide")


### User input
name = st.set_page_config(page_title="Team4 Chatbot", layout="wide")

Screenshot (77)

Running Your Streamlit App

streamlit run app.py

This will start a local server, and you can access your app in your web browser at http://localhost:84/team4.

Usage

Streamlit provides a wide range of functionalities for building interactive web applications. Here are some key components you can use:

Common Components

  • Text Elements: st.title(), st.header(), st.subheader(), st.text()
  • Input Widgets: st.button(), st.slider(), st.selectbox(), st.text_input()
  • Display Elements: st.write(), st.dataframe(), st.image(), st.line_chart()
  • Layouts: Use st.sidebar for sidebar elements.

Custom Components

Streamlit allows you to create custom components that can integrate with JavaScript libraries. You can use libraries like streamlit.components.v1 to build interactive components.

Example: Custom Component

Here’s a basic example of using a custom component:

import streamlit as st
import streamlit.components.v1 as components

### Custom component that returns a simple HTML
html_string = "<h1>Hello from Custom Component!</h1>"
components.html(html_string)

Deployment

Once you've built your application, you may want to deploy it. Here are some popular options:

  1. Streamlit Sharing: A free tool provided by Streamlit to share your apps. Simply push your code to GitHub and deploy from there.
  2. Heroku: You can also deploy your Streamlit app on Heroku. You will need to create a requirements.txt file and a Procfile.
  3. Docker: If you prefer containerization, you can create a Docker image for your Streamlit app.

Example of Docker Deployment

Here's a simple Dockerfile to deploy your Streamlit app:

### Use the official Python image from Docker Hub
FROM python:3.8-slim

### Set the working directory
WORKDIR /app

### Copy requirements file
COPY requirements.txt .

### Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

### Copy the app code
COPY . .

### command to run the app
CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]

Usage of Streamlit in the Code

  1. Setting the Page Configuration:

    st.set_page_config(page_title="Team4ChatBot", layout="wide")
  • This line configures the title of the web app and sets the layout to wide, allowing for more space on the page.

Screenshot 2024-10-28 010102

  1. Loading Custom CSS:

    with open(css_file_path) as f:
        st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
    • Streamlit allows for the inclusion of custom HTML and CSS, which is used here to style the chat application.

Screenshot 2024-10-28 010908

  1. Creating the Title:
    st.title("Team4 Chatbot")
    • This displays the main title of the web application.

Screenshot 2024-10-28 011133

  1. Sidebar Header and Metrics:
    st.sidebar.header("10 Statistics Report")
    • This creates a header in the sidebar for displaying various statistics about the chatbot.

Screenshot 2024-10-28 011208

  1. Displaying Statistics:
    for question in questions:
        st.sidebar.markdown(f'<div class="question-box">{question}</div>', unsafe_allow_html=True)
    • Streamlit's markdown function is used to display a list of statistics in the sidebar, styled with custom CSS.

Screenshot 2024-10-28 011229

  1. Session State Management:
    if 'chat_history' not in st.session_state:
        st.session_state.chat_history = []
    • This checks if a session state variable for chat history exists, and if not, initializes it. Streamlit's session state allows the app to maintain state across user interactions.

Screenshot 2024-10-28 011253

  1. Chat Input Box:
    user_input = st.chat_input("Message writing assistant")
    • This creates a chat input field for users to type their messages.

Screenshot 2024-10-28 011315

  1. Displaying Loading Spinner:
    with st.spinner("Response Generating, please wait..."):
    • A spinner is displayed to indicate that a response is being generated, improving user experience by providing feedback during processing.

Screenshot 2024-10-28 011939

  1. Markdown for User and Bot Messages:
    st.markdown(f"<div class='user-message'>{user_input}</div>", unsafe_allow_html=True)
    • Streamlit's markdown function is used to display user messages and bot responses, allowing for custom HTML styles.

Screenshot 2024-10-28 012006

  1. Feedback Mechanism:
    selected = st.feedback("thumbs")
    • This line creates a feedback option for users to provide thumbs-up or thumbs-down feedback on the bot's response.

Screenshot 2024-10-28 012054

  1. Dynamic Content Rendering:
    for message in st.session_state.chat_history:
        if message['role'] == 'user':
            continue
        else:
            st.markdown(f"{message['content']}") 
  • The loop dynamically displays user and bot messages in Streamlit.

Screenshot 2024-10-28 014157

  1. Chat History Management:
    st.session_state.chat_history.append({"role": "user", "content": feedback_message})
  • Session state manages chat history, preserving context for conversations.

Screenshot 2024-11-01 185455

Troubleshooting

If you encounter issues while using Streamlit, consider the following solutions:

App Doesn't Load

Error: Browser shows "500 Internal Server Error" or "Unable to connect."

Solution

Check if the app is running

docker logs STREAMLIT_SERVER_BASEURLPATH=/team4

Screenshot (102)

Verify the Streamlit server settings in the configuration

ENV STREAMLIT_SERVER_PORT=5004
ENV STREAMLIT_SERVER_BASEURLPATH=/team4

Screenshot (102)

Cannot Access App

Error: App doesn't open at http://localhost:5004

Solution

Ensure the container port is exposed

EXPOSE 5004

Screenshot (104)

Run the container with port mapping

docker run -p 5004:5004

Screenshot (105)

Reverse Proxy Misconfiguration

Error: App doesn't load behind Nginx or other reverse proxies.

Solution

Verify the proxy settings. Ensure the proxy is forwarding requests to the correct port

ENV STREAMLIT_SERVER_BASEURLPATH=/team4

Screenshot (106)

Common Issues and Solutions

  1. Streamlit Not Found Error:
    • Ensure that Streamlit is installedCertainly! Here’s the continuation of the troubleshooting section as well as the remaining parts of the documentation.

Common Issues and Solutions (Continued)

  1. Streamlit Not Found Error:

    • Ensure that Streamlit is installed in the correct Python environment. You can create a virtual environment using tools like venv or conda.
  2. Application Crashes or Freezes:

    • Check for infinite loops or blocking calls in your code. Use st.spinner to help visualize ongoing processing.
  3. Performance Issues:

    • If your app is slow, consider optimizing data loading and caching results using the @st.cache decorator.
    @st.cache
    def load_data():
        # Simulate a long loading process
        return pd.read_csv("large_file.csv")

4. *Streamlit App Not Responding:*
  - Ensure you are not running too many heavy computations in the main thread. Offload heavy tasks to background processes if needed.

5. *CORS Issues:*
  - If you encounter Cross-Origin Resource Sharing (CORS) issues while trying to access APIs, ensure that your server settings in config.toml allow CORS requests.

6. *Browser Not Opening:*
  - Check if your firewall or antivirus is blocking the port (default is 8501). Manually open a web browser and enter http://localhost:8501.

7. *App Not Updating:*
  - Streamlit automatically updates when you save your script. If it does not, try refreshing the browser or restarting the Streamlit server.

⚠️ **GitHub.com Fallback** ⚠️