What isreliable way to change text of widget text_input?

Is that a way to overwrite or clear user input value ?
For example:

        col3, col4 = st.columns(2)
        with col3:
            start_time = st.text_input('Début',  placeholder="0:00")
        with col4:
            end_time = st.text_input('Fin',  placeholder="0:00")

        st.write("---")

        if st.button('Extraire texte'):
            with st.spinner('En cours...'):
                # Add new text input, don't change 
                start_time = st.text_input('Début', value=datetime.now())
                time.sleep(5)
                 # Add new text input, don't change 
                end_time = st.text_input('Fin', value=datetime.now())

Thanks in advance

When you assign a key to a widget, you can programmatically control the widget’s value through Session State.

st.text_input("Your name", key="name") can be updated by modifying st.session_state.name. (Make sure any manual value assignment happens before the widget function in the script or within a callback. You can’t modify a widget’s value after the widget function is already complete in that script run.)

(Perhaps I should add an example of programmatic control to the Widget behavior guide. There’s some related examples but not exactly the one I’d point to in this case. :thinking:)

        col3, col4 = st.columns(2)
        with col3:
            st.text_input('Début', key="start_time", placeholder="0:00")
        with col4:
            st.text_input('Fin', key="end_time", placeholder="0:00")

        st.write("---")

        if st.button('Extraire texte'):
            with st.spinner('En cours...'):
                st.session_state.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                time.sleep(5)
                st.session_state.end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

I got this error:

StreamlitAPIException: st.session_state.start_time cannot be modified after the widget with key start_time is instantiated.
Traceback:

File "C:\Dev\Python\VideoToText\app_streamlit.py", line 74, in <module>
    main()
File "C:\Dev\Python\VideoToText\app_streamlit.py", line 64, in main
    st.session_state.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

Yes. That’s expected. You can’t modify the value assigned to a widget after you call the widget function. It has to be before.

So try reversing the button and your columns:

# Initialize your columns first, which keeps that content visually above your button on the page
col3, col4 = st.columns(2)

# Call your functions that change the `st.text_input` values before the widget functions
if st.button('Extraire texte'):
    with st.spinner('En cours...'):
        st.session_state.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        time.sleep(5)
        st.session_state.end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Call the widgets with changed values at the end
with col3:
    st.text_input('Début', key="start_time", placeholder="0:00")
with col4:
    st.text_input('Fin', key="end_time", placeholder="0:00")
    st.write("---")

I’m not exactly sure what logic you’re going for here, so there may be other methods more appropriate to your situation. In my case, I most often do widget manipulation within callback functions rather than in the main body of the script.

OK. Thanks for your help. I start with Streamlit.
I want to display the execution time of a process with the start and end time.
Do you have an example within callback functions?

Do you need the start and stop time to be an interactive widget instead of just text displayed on the screen? If your primary purpose is to report values, I’d suggest st.markdown instead.

For reference, a callback would look something like this:

import streamlit as st
import time
from datetime import datetime

if "start" not in st.session_state:
    st.session_state.start = ""
    st.session_state.stop = ""


def update():
    st.session_state.start = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    time.sleep(5)
    st.session_state.stop = datetime.now().strftime("%Y-%m-%d %H:%M:%S")


st.text_input("A", key="start")
st.text_input("B", key="stop")

st.button("Go", on_click=update)

@mathcatsand Thank you again for your support, it helped me a lot.
Below is my python code. Any suggestions are welcome

import os
import time
from datetime import datetime, timedelta

import streamlit as st
import yt_dlp

def upload_file(filename, upload_folder):
    file_source = os.path.join(upload_folder, filename.name)
    os.makedirs(upload_folder, exist_ok=True)

    with open(file_source, 'wb') as out:
        out.write(filename.getbuffer())

    out.close()

    return file_source

def download_video(video_path):
    with yt_dlp.YoutubeDL({'extract_audio': True, 'format': 'bestaudio', 'outtmpl': '%(id)s.%(ext)s'}) as ydl:
        info_dict = ydl.extract_info(video_path, download=True)
        audio_file = ydl.prepare_filename(info_dict)

        return audio_file

def transcript():
    st.session_state.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with st.spinner('En cours...'):
        time.sleep(5) # DO SOMETHING
        st.session_state.end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    st.session_state.time_elapse = str(datetime.strptime(st.session_state.end_time, "%Y-%m-%d %H:%M:%S") - datetime.strptime(st.session_state.start_time, "%Y-%m-%d %H:%M:%S"))

def main():
    st.title("Extraire le texte d'une vidéo")

    st.subheader('Options :')

    col1, col2 = st.columns(2)
    with col1:
        uploaded_file = st.file_uploader("Choisissez un fichier")
    with col2:
        video_url = st.text_input("Ou entrez l'URL de la vidéo à télécharger")

    st.write("---")

    if uploaded_file or video_url:
        if "start_time" not in st.session_state:
            st.session_state.start_time = "0:00"
            st.session_state.end_time = "0:00"
            st.session_state.time_elapse = "0:00"

        if uploaded_file :
            file_source = upload_file(uploaded_file, 'video_uploads')
        elif video_url:
            file_source = download_video(video_url)

        col3, col4, col5 = st.columns(3)
        with col3:
            st.text_input('Début', key="start_time")
        with col4:
            st.text_input('Fin', key="end_time")
        with col5:
            st.text_input('Temps de traitement', key="time_elapse")

        st.write("---")

        st.button('Extraire texte', on_click=transcript)


if __name__ == '__main__':
    main()
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.