I have built a object detection model on Streamlit that allows users to upload their video and it does object detection, saves the video in a folder, and displays it on a viewer using st.video().
However, the issue is that even when the user closes the browser, the old video will still be there in the folder, so when many people use it, it continues to pile up.
Is there anyway to delete folders when the user closes the browser?
Any suggestions welcome!
Thanks,
TeYang
Hi @blackary, thanks for the suggestion.
I read that tempfile will only delete the temp directory when the program is shut down. In the case of streamlit, when the user closes the browser, the script is still running in the cloud. So does that mean that it does not get deleted? Or we have to manually delete it in the code.
Code looks something like this:
# create temp dir for storing video and outputs
temp_dir = tempfile.TemporaryDirectory()
RESULTS_PATH = temp_dir.name
# save video to RESULTS PATH .....
temp_dir.cleanup() # manually remove temp_dir
Perhaps I can start a timer to execute the temp_dir.cleanup() after a certain time? Not ideal though.
Another way is using context manager to auto remove the temp directory. However, this requires that my entire streamlit code be subsumed under the with
context manager?
# create temp dir for storing video and outputs
with tempfile.TemporaryDirectory() as temp_dir :
print('created temporary directory', temp_dir )
# after the context manager, temp_dir will be auto deleted
Any suggestions?
In general, my recommendation is to use the context manager version, so that the cleanup will happen automatically even if you have an error that gets raised. I suspect that you won’t actually have to put your entire streamlit app inside of the context manager, but only some of it, but if you’d prefer you can always move your code to separate functions, and call those in the context manager rather than writing the code directly inside the context manager.
1 Like