Duplicate Widget ID: streamlit

Question:

I am getting this error:

DuplicateWidgetID: There are multiple identical st.button widgets with key=’1′.

To fix this, please make sure that the key argument is unique for each st.button you create.

how can I solve this

def Breccia_Predictions():
    image_=pre_process()
    model = tf.keras.models.load_model(model_path)
    prediction_steps_per_epoch = np.math.ceil(image_.n / image_.batch_size)
    image_.reset()
    Breccia_predictions = model.predict_generator(image_, steps=prediction_steps_per_epoch, verbose=1)
    predicted_classes = np.argmax(Breccia_predictions, axis=1)
    return Predicted_classes
    
   
    
def main():
    image_file=st.file_uploader('upload a breccia rock', type=['png', 'jpg', 'jpeg'], accept_multiple_files=True,)
    if image_file is not None:
        for image in image_file:
            file_details = {"FileName":image.name,"FileType":image.type}
            st.write(file_details)
            img = load_image(image)
            st.image(img)
            #saving file
            with open(os.path.join("Breccia", image.name),"wb") as f: 
                f.write(image.getbuffer())         
            st.success("Saved File")
            if(st.button('Predicted', key = count)):
                predicted=Breccia_Predictions
                
Asked By: Taiwo

||

Answers:

You can be processing multiple images.

for image in image_file:

And you have:

if(st.button('Predicted', key = count)):

Your key is only count. If there are more than 1 image, the next button key is still count.

To solve it, create some variable, increment it per image and use this variable in the button key. Example:

cnt = 0
for image in image_file:
    cnt += 1
    # your stuff

    if(st.button('Predicted', key=f'{count}_{cnt}')):
        # your stuff

The button key is now unique because the cnt is unique [1, 2, …]

Answered By: ferdy

You can one step further and use a python generator to manage this for you. For example:

widget_id = (id for id in range(1, 100_00))
for image in image_file:
    # Do things here

    if(st.button('Predicted', key=next(widget_id):
        # your stuff

Now you don’t have to manually increment!

Answered By: rsigs