Accessing Temporary Files On Streamlit Sharing


I deployed a computer vision app that works with OpenCV and Mediapipe and (also) takes video inputs. My idea was to process the input video (first 10 seconds only); write a new output video to a temporary folder, display the output video using and clean up the temporary folder. The code looks like this:

if type in ["video", "webcam"]:
    # some code
    codec = cv.VideoWriter_fourcc(*"avc1")
    max_frames = 10 * vid_fps

    temp_dir = tempfile.mkdtemp(suffix=None, prefix="SMW_", dir=None)
    if not os.path.lexists(temp_dir):
    out_vid_file = os.path.join(temp_dir, "vid_output.mp4")
    out_vid = cv.VideoWriter(out_vid_file, codec, vid_fps, (vid_w, vid_h))

    if start_clicked:
        placeholders[1].info("Processing video input...")
        progress_bar = st.progress(0)

        while media.isOpened():
            # some opencv code
            out_vid.write(cv.cvtColor(img, cv.COLOR_RGB2BGR))
            # some opencv code

            if out_vid_frame_count == max_frames:
        shutil.rmtree(temp_dir, ignore_errors=True)

This works okay on my PC, but when on Streamlit sharing, I get a FileNotFoundError at the line. I have checked, the temporary folder and output video are created but once the code exits the loop, they get cleaned up before the video can be displayed.

I have also tried to create a temporary folder in the same folder as the python file using temp_dir = os.path.join(os.path.dirname(__file__), "output_vid") but it’s the same issue.

I will appreciate any information on this issue and any workarounds available. Thank you.