| import gradio as gr | |
| from gradio_folderexplorer import FolderExplorer | |
| from gradio_folderexplorer.helpers import load_media_from_folder | |
| from PIL import Image | |
| import os | |
| # --- Configuration Constants --- | |
| # Define the root directory for the FolderExplorer to start in. | |
| # All browsable folders will be relative to this path. | |
| ROOT_DIR_PATH = "./src/examples" | |
| # --- UI Layout and Logic --- | |
| # Create the user interface using Gradio Blocks. | |
| with gr.Blocks(theme=gr.themes.Ocean()) as demo: | |
| # A single row is used to create a side-by-side layout. | |
| gr.Markdown("# FolderExplorer Component Demo") | |
| with gr.Row(equal_height=True): | |
| # The first column contains the custom folder explorer component. | |
| with gr.Column(scale=1, min_width=300): | |
| folder_explorer = FolderExplorer( | |
| label="Select a Folder", | |
| root_dir=ROOT_DIR_PATH, | |
| # Set the initial selected value to the root directory itself. | |
| # This is used by the demo.load() event. | |
| value=ROOT_DIR_PATH | |
| ) | |
| # The second column contains the gallery to display the media. | |
| with gr.Column(scale=3): | |
| gallery = gr.Gallery( | |
| label="Selected Images", | |
| columns=6, | |
| height="auto", | |
| ) | |
| # --- Event Handling --- | |
| # 1. Event for user interaction: | |
| # When the user selects a new folder in the FolderExplorer, the .change() event | |
| # is triggered. The `load_media_from_folder` helper is called with the new | |
| # folder path, and its output populates the gallery. | |
| folder_explorer.change( | |
| fn=load_media_from_folder, | |
| inputs=folder_explorer, | |
| outputs=gallery | |
| ) | |
| # 2. Event for initial page load: | |
| # This event runs once when the app starts. It takes the initial `value` of the | |
| # folder_explorer ('ROOT_DIR_PATH'), passes it to the helper function, | |
| # and populates the gallery with the media from the root directory. | |
| demo.load( | |
| fn=load_media_from_folder, | |
| inputs=folder_explorer, | |
| outputs=gallery | |
| ) | |
| # --- Application Launch --- | |
| if __name__ == "__main__": | |
| demo.launch() |