hi im trying to update the timer (update in the UI) whenthe button is pressed, right now the timer_placeholder disappears when the users presses the button, how can I have a blocking operation that does not stop from showing the timer, here's the original code: import asyncio
import streamlit as st
import datetime
from audiorecorder import audiorecorder
from audio import AudioToText, TextToAudio
from helper import autoplay_audio_from_array
from chat_model import InterViewer
from datetime import timedelta
INTERVIEW_DURATION = 1 * 60
def initialize_interview_state():
if "messages" not in st.session_state:
st.session_state.messages = []
if "interview_started" not in st.session_state:
st.session_state["interview_started"] = False
if "start_time" not in st.session_state:
st.session_state["start_time"] = datetime.datetime.now()
if "remaining_time" not in st.session_state:
st.session_state["remaining_time"] = INTERVIEW_DURATION
async def countdown_timer(timer_placeholder):
while st.session_state.remaining_time > 0:
elapsed_time = (datetime.datetime.now() - st.session_state.start_time).total_seconds()
st.session_state.remaining_time = max(0, INTERVIEW_DURATION - int(elapsed_time))
timer_placeholder.info(
f"⏳ Time remaining: {str(timedelta(seconds=st.session_state.remaining_time))}"
)
if st.session_state.remaining_time <= 0:
timer_placeholder.warning("⏰ Time's up!")
# st.switch_page('pages/evaluation.py')
await asyncio.sleep(1)
def block_fnc():
import time
time.sleep(5)
st.button("test")
return "hello"
def main():
initialize_interview_state()
timer_placeholder = st.empty()
block_fnc()
if st.session_state.remaining_time > 0:
asyncio.run(countdown_timer(timer_placeholder))
if name == "main":
main()
Assistant
When integrating real-time elements like timers in Streamlit, it's essential to manage blocking operations properly to ensure the UI remains responsive. In your current setup, the time.sleep(5) within the block_fnc function is causing the main thread to block, which prevents the timer from updating and results in the timer_placeholder disappearing.
To resolve this, you can utilize Python's threading module to run blocking operations in separate threads. This approach allows the main thread to continue handling UI updates, such as your countdown timer, without interruption.
Below is a refactored version of your code that addresses these issues:
python
import streamlit as st
import datetime
from datetime import timedelta
import threading
import time
# Constants
INTERVIEW_DURATION = 1 * 60 # 1 minute in seconds
# Initialize session state variables
def initialize_interview_state():
if "messages" not in st.session_state:
st.session_state.messages = []
if "interview_started" not in st.session_state:
st.session_state["interview_started"] = False
if "start_time" not in st.session_state:
st.session_state["start_time"] = None
if "remaining_time" not in st.session_state:
st.session_state["remaining_time"] = INTERVIEW_DURATION
if "block_result" not in st.session_state:
st.session_state["block_result"] = ""
# Function to handle countdown without blocking
def update_countdown():
while st.session_state["interview_started"] and st.session_state["remaining_time"] > 0:
elapsed_time = (datetime.datetime.now() - st.session_state["start_time"]).total_seconds()
st.session_state["remaining_time"] = max(0, INTERVIEW_DURATION - int(elapsed_time))
time.sleep(1)
if st.session_state["remaining_time"] <= 0:
st.session_state["interview_started"] = False # Stop the timer when time's up
# Blocking function to run in a separate thread
def block_fnc():
time.sleep(5) # Simulate a blocking operation
st.session_state["block_result"] = "Operation Completed!"
# Function to start the interview and timer
def start_interview():
st.session_state["interview_started"] = True
st.session_state["start_time"] = datetime.datetime.now()
st.session_state["remaining_time"] = INTERVIEW_DURATION
# Start the countdown in a separate thread
countdown_thread = threading.Thread(target=update_countdown, daemon=True)
countdown_thread.start()
# Function to handle button press without blocking
def handle_button_press():
threading.Thread(target=block_fnc, daemon=True).start()
def main():
st.title("Interview Timer Application")
initialize_interview_state()
# Placeholder for the timer
timer_placeholder = st.empty()
if not st.session_state["interview_started"]:
if st.button("Start Interview"):
start_interview()
else:
# Display the timer
timer_text = f"⏳ Time remaining: {str(timedelta(seconds=st.session_state['remaining_time']))}"
timer_placeholder.info(timer_text)
if st.session_state["remaining_time"] <= 0:
timer_placeholder.warning("⏰ Time's up!")
else:
# Button that triggers a blocking operation
if st.button("Press Me"):
handle_button_press()
# Display result from the blocking operation
if st.session_state["block_result"]:
st.success(st.session_state["block_result"])
# Auto-refresh the Streamlit app to update the timer
st.experimental_rerun()
if __name__ == "__main__":
main()
Key Changes and Explanations:
Using threading for Blocking Operations:
block_fnc: This function simulates a blocking operation using time.sleep(5). By running this function in a separate thread using threading.Thread, it prevents the main thread (which handles the UI) from being blocked.
handle_button_press: When the "Press Me" button is clicked, this function starts the block_fnc in a new daemon thread.
Managing the Countdown Timer:
update_countdown: This function updates the remaining time every second. It's run in a separate daemon thread to ensure the UI remains responsive.
start_interview: Initializes the interview state and starts the countdown timer thread.
UI Updates and Auto-Refresh:
timer_placeholder: An st.empty() placeholder is used to dynamically update the timer display.
st.experimental_rerun(): After each UI interaction, the app reruns to reflect the updated timer and any changes from the blocking operations.
Session State Management:
Initialization: The initialize_interview_state function sets up all necessary session state variables to track the interview status, start time, remaining time, and results from blocking operations.
Updating States: The countdown and blocking functions update the session state appropriately, allowing the UI to react to these changes.
Additional Recommendations:
Avoid Using asyncio with Streamlit:
Streamlit's architecture isn't inherently designed for asynchronous operations with asyncio. Mixing asyncio with Streamlit can lead to unexpected behaviors. Instead, using threading (as shown) is more compatible.
Auto-Refresh for Real-Time Updates:
For real-time UI updates like timers, consider using Streamlit's st_autorefresh or similar mechanisms to periodically refresh the app without requiring manual interactions.
Thread Safety:
While threading can be beneficial, ensure that shared resources (like st.session_state) are accessed in a thread-safe manner to prevent race conditions or inconsistencies.
By implementing these changes, your Streamlit app will maintain a responsive countdown timer even when performing blocking operations triggered by button presses.