import gradio as gr def load_images(files): if not files: return [], gr.update(visible=False), 0, "" # Sort alphabetically by file name (handles imageA, imageB, image1, image2) sorted_files = sorted(files, key=lambda x: x.name) # Return the sorted list, make the carousel visible, # set index to 0, and update the display return sorted_files, gr.update(visible=True), 0, sorted_files[0].name def navigate(direction, current_index, file_list): if not file_list: return 0, None, "" # Calculate new index with wrap-around logic new_index = (current_index + direction) % len(file_list) active_file = file_list[new_index] return new_index, active_file.name, active_file.name with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# 🖼️ Sequential Image Carousel") # State to keep track of the uploaded files and current position file_state = gr.State([]) index_state = gr.State(0) # 1. Upload Section with gr.Row(): upload_btn = gr.File( label="Upload Images", file_count="multiple", file_types=["image"] ) # 2. Carousel Section (Hidden until images are uploaded) with gr.Column(visible=False) as carousel_container: with gr.Row(): prev_btn = gr.Button("⬅️ Previous", scale=1) # Display area for the single image image_display = gr.Image(label="Viewing Image", interactive=False, scale=4) next_btn = gr.Button("Next ➡️", scale=1) image_name_label = gr.Markdown(elem_id="img-label") # --- Event Listeners --- # When files are uploaded: Sort them and show the first one upload_btn.upload( fn=load_images, inputs=upload_btn, outputs=[file_state, carousel_container, index_state, image_display] ) # Navigation Buttons prev_btn.click( fn=lambda idx, files: navigate(-1, idx, files), inputs=[index_state, file_state], outputs=[index_state, image_display, image_name_label] ) next_btn.click( fn=lambda idx, files: navigate(1, idx, files), inputs=[index_state, file_state], outputs=[index_state, image_display, image_name_label] ) if __name__ == "__main__": demo.launch()