File size: 2,343 Bytes
50e0f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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()