How to update app elements on timer?

Thanks for Streamlit, it is really incredible!!

I developed a small app that (among other things) displays an image from a source folder and allows the user to click a button if they want to save it (to a backup storage).
The tricky part is that I would like the app to show the last file on that source folder, and if a new file appears in said folder, the app will update to reflect it automatically.
I can easily write a script that runs in an infinite loop to check if the folder has new image files, but I suspect that it will cause the app to hang.

Is there a good way to do that? perhaps a timer that can run every 1sec and check for update?
I do have a workaround but it is so ugly I’m ashamed to share it :sweat_smile: please suggest a nicer solution.

Hi @Alon Welcome to the community !

Every file has a ctime associated with it, based on which you can know which file was the last added,
Reference: https://en.wikipedia.org/wiki/Stat_(system_call)

You can do it using stat of Pathlib’s path,

import streamlit as st
from pathlib import Path

uploaded_file = st.file_uploader("Add images !")
open(uploaded_file.name, "wb").write(uploaded_file.getvalue())

dir_path = "."
images = Path(dir_path).glob("*")
latest_image = max(images, key=lambda file: file.stat().st_ctime)

st.image(str(latest_image))

Hope it helps !

3 Likes

@Alon,

So, you want your streamlit app to be notified everytime a new file is created in that dir? @ash2shukla, won’t your solution work the first time, but not really update when you get a new file since the script runs and stops barring any user input? If that is true, wouldn’t you need a solution such as inotify to make it work?

Dinesh

1 Like

@ddutt, If I am not mistaken @Alon doesn’t want to change the image in an already rendered session.

The script re-runs on every change so the file will keep changing. Please correct me if I am wrong.

Regards,
Ashish.

@ash2shukla Thanks! I didn’t explain myself well.
The issue is not finding out the latest file, I actually have a similar code to what you suggested using os.path.getctime(file_path) .
The issue is that I want the rendered image in the streamlit session to be updated in case there is a new file in the sources folder.

My working workaround, ugly as it may be, is to exploit the fact that streamlit already tracks changes in all the imported files automatically. So I set it up such that the path to the image i’m displaying is in a file, let’s say my_image_path.py and in that file there is only one line line: file_path=r"c:\source_folder\image_34.jpg"
then in the streamlit app I have
from my_image_path import file_path
Now for the magic part, I have another script that runs in an infinite loop every 1sec to check if the source folder has a new file, if so, it will override the python file my_image_path.py with the new path. Since streamlit is tracking my_image_path.py for changes, it will re-render the image in the app.

Hey @Alon,
Sorry I didn’t understand the problem properly.

I think you can explicitly request a re-run on all of the session info objects whenever you have a new file uploaded in any of the sessions.

import streamlit as st
from pathlib import Path
from streamlit.server.server import Server
=

def rerun_all():
    session_infos = Server.get_current()._session_info_by_id.values()

    for session_info in session_infos:
        session_info.session.request_rerun()

st.rerun = rerun_all


uploaded_file = st.file_uploader("Add images !")
if uploaded_file:
    # its a new file 
    if not Path(uploaded_file.name).exists():
        open(uploaded_file.name, "wb").write(uploaded_file.getvalue())
        st.rerun()

dir_path = "."
images = list(Path(dir_path).glob("*.jpg"))
if images:
    latest_image = max(images, key=lambda file: file.stat().st_mtime)

    st.image(str(latest_image))
else:
    st.write("No Image to show :(")

This snippet behaves like this,

Let me know if I got it wrong again :sweat_smile:
Hope it helps!

2 Likes

Another very useful response @ash2shukla. All these answers of yours need to go into some permanent place for people to look. Lots of very clever tricks to achieve what you want with streamlit.

Dinesh

1 Like

Thank you! However this is not what I need.
You created a way for the user to add images manually to a list and then show the latest image in that list. But what I need is for the app to monitor a folder on the file system and update if a new file pops in there.

@Alon,

I believe you need to use the inotify package to notify you of changes to the directory. See this page as an example: https://inotify-simple.readthedocs.io/en/latest/#example-usage

Does this help?

Dinesh

@Alon
After scratching my head for 2 days I think I finally have what you are looking for :laughing:

import streamlit as st
from pathlib import Path
import asyncio

PLACEHOLDER_URL = "https://www.gaithersburgdental.com/wp-content/uploads/2016/10/orionthemes-placeholder-image.png"

async def watch(image_pl):
    dir_path = "watch_dir"
    previous = None
    while True:
        images = list(Path(dir_path).glob("*.jpg"))
        if images:
            latest = max(images, key=lambda file: file.stat().st_mtime)
        else:
            image_pl.image(PLACEHOLDER_URL, use_column_width=True)
            latest = None
        if latest != previous:
            image_pl.image(str(latest), use_column_width=True)
            previous = latest
        _ = await asyncio.sleep(1)


image_pl = st.empty()

asyncio.run(watch(image_pl))

Hope it helps ! :slight_smile:

2 Likes