Streamlit slider refresh the whole code/page

I noticed when slider value changed whole code is reloaded. though most of code has nothing do with slider value.

import streamlit as st
import tempfile

uploaded_file = st.file_uploader("Upload Files",accept_multiple_files=False,type=['mp4'])#upload file
if uploaded_file is not None:#check if file is present
	tfile = tempfile.NamedTemporaryFile(delete=False) 
	tfile.write(uploaded_file.read())
	print("file is present")
d=st.slider('Select threshold', min_value=5 , max_value=15 , value=10 , step=2 )
st.write(d)

If I change the value of the slider it prints file is present in console again, which mean if there is heavy calculations instead of print statement, it will do this all again

Hi @Talha_Anwar -

What you are describing is how the Streamlit user flow works. Upon each widget change, the code will run top-to-bottom, which is frequently easier to reason about than callbacks.

When you have expensive computations, such, the canonical way to handle this in Streamlit is to use the st.cache decorator, which is detailed here:

https://docs.streamlit.io/en/stable/caching.html#improve-app-performance

Best,
Randy

Hi, Randy, thanks for response. Here is my function

@st.cache
def upload_func(model):
	uploaded_file = st.file_uploader("Upload Files",accept_multiple_files=False,type=['mp4','avi'])#upload file
	if uploaded_file is not None:#check if file is present
		with st.spinner('Wait for it...'):
			tfile = tempfile.NamedTemporaryFile(delete=False) 
			tfile.write(uploaded_file.read())
			pulse,resp,fs=predict_vitals(tfile.name,model)
		st.success('Done!')
	return pulse,resp,fs

pulse,resp,fs=upload_func(model)

This is warning I am getting
CachedStFunctionWarning : Your script uses st.file_uploader() or st.write() to write to your Streamlit app from within some cached code at upload_func() . This code will only be called when we detect a cache โ€œmissโ€, which can lead to unexpected results.

How to fix this:

  • Move the st.file_uploader() or st.write() call outside upload_func() .
  • Or, if you know what youโ€™re doing, use @st.cache(suppress_st_warning=True) to suppress the warning.

And this is the error I am getting
UnboundLocalError: local variable โ€˜pulseโ€™ referenced before assignment

In your function code, pulse is only defined when uploaded_file is not None:. So upon first run of your code, the user cannot have uploaded anything yet (thereโ€™s no window presented to them until it renders), and you try to return pulse without defining it yet.

The warning is telling you to move the file_uploader call outside of the function. If you pass uploaded_file as a variable into upload_func, it will then be cached.

Best,
Randy