gradio-mediagallery 0.0.9
Media Gallery Explorer with Metadata Image Extraction for Gradio UI
Requires Python: >=3.8
Keywords: gradio-custom-component, gradio-template-Gallery

---
tags: [gradio-custom-component, gallery]
title: gradio_mediagallery
short_description: A Media Gallery Explorer for Gradio UI
colorFrom: pink
colorTo: yellow
sdk: gradio
pinned: false
app_file: space.py
---

# `gradio_mediagallery`
<a href="https://pypi.org/project/gradio_mediagallery/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gradio_mediagallery"></a>  

Media Gallery Explorer with Metadata Image Extraction for Gradio UI

## Installation

```bash
pip install gradio_mediagallery
```

## Usage

```python
from typing import Any, List
import gradio as gr
from gradio_folderexplorer import FolderExplorer
from gradio_folderexplorer.helpers import load_media_from_folder
from gradio_mediagallery import MediaGallery
from gradio_mediagallery.helpers import transfer_metadata

# Configuration constant for the root directory containing media files
ROOT_DIR_PATH = "./src/examples"

def handle_load_metadata(image_data: gr.EventData) -> List[Any]:
    """
    Processes image metadata by calling the `transfer_metadata` helper.

    Args:
        image_data (gr.EventData): Event data containing metadata from the MediaGallery component.

    Returns:
        List[Any]: A list of values to populate the output fields, or skipped updates if no data is provided.
    """
    if not image_data or not hasattr(image_data, "_data"):
        return [gr.skip()] * len(output_fields)

    return transfer_metadata(
        output_fields=output_fields,
        metadata=image_data._data,
        remove_prefix_from_keys=True
    )

# UI layout and logic
with gr.Blocks(theme=gr.themes.Ocean()) as demo:
    """
    A Gradio interface for browsing and displaying media files with metadata extraction.
    """
    gr.Markdown("# MediaGallery with Metadata Extraction")
    gr.Markdown(
        """
        **To Test:**
        1. Use the **FolderExplorer** on the left to select a folder containing images with metadata.
        2. Click on an image in the **Media Gallery** to open the preview mode.
        3. In the preview toolbar, click the 'Info' icon (ⓘ) to open the metadata popup.
        4. Click the **'Load Metadata'** button inside the popup.
        5. The fields in the **Metadata Viewer** below will be populated with the data from the image.
        """
    )
    with gr.Row(equal_height=True):
        with gr.Column(scale=1, min_width=300):
            folder_explorer = FolderExplorer(
                label="Select a Folder",
                root_dir=ROOT_DIR_PATH,
                value=ROOT_DIR_PATH
            )

        with gr.Column(scale=3):
            gallery = MediaGallery(
                label="Media in Folder",
                columns=6,
                height="auto",
                preview=False,
                show_download_button=False,
                only_custom_metadata=False,
                popup_metadata_width="40%",
            )

    gr.Markdown("## Metadata Viewer")
    with gr.Row():
        model_box = gr.Textbox(label="Model")
        fnumber_box = gr.Textbox(label="FNumber")
        iso_box = gr.Textbox(label="ISOSpeedRatings")
        s_churn = gr.Slider(label="Schurn", minimum=0.0, maximum=1.0, step=0.01)
        description_box = gr.Textbox(label="Description", lines=2)

    # Event handling
    output_fields = [
        model_box,
        fnumber_box,
        iso_box,
        s_churn,
        description_box
    ]

    # Populate the gallery when the folder changes
    folder_explorer.change(
        fn=load_media_from_folder,
        inputs=folder_explorer,
        outputs=gallery
    )

    # Populate the gallery on initial load
    demo.load(
        fn=load_media_from_folder,
        inputs=folder_explorer,
        outputs=gallery
    )

    # Handle the load_metadata event from MediaGallery
    gallery.load_metadata(
        fn=handle_load_metadata,
        inputs=None,
        outputs=output_fields
    )

if __name__ == "__main__":
    """
    Launches the Gradio interface in debug mode.
    """
    demo.launch(debug=True)
```

## `MediaGallery`

### Initialization

<table>
<thead>
<tr>
<th align="left">name</th>
<th align="left" style="width: 25%;">type</th>
<th align="left">default</th>
<th align="left">description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>value</code></td>
<td align="left" style="width: 25%;">

```python
Sequence[
        np.ndarray | PIL.Image.Image | str | Path | tuple
    ]
    | Callable
    | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Initial list of images or videos, or a function to generate them.</td>
</tr>

<tr>
<td align="left"><code>file_types</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">List of allowed file extensions or types for uploads (e.g., ['image', '.mp4']).</td>
</tr>

<tr>
<td align="left"><code>label</code></td>
<td align="left" style="width: 25%;">

```python
str | I18nData | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Label displayed above the component.</td>
</tr>

<tr>
<td align="left"><code>every</code></td>
<td align="left" style="width: 25%;">

```python
Timer | float | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Interval or Timer to refresh `value` if it's a function.</td>
</tr>

<tr>
<td align="left"><code>inputs</code></td>
<td align="left" style="width: 25%;">

```python
Component | Sequence[Component] | set[Component] | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Components used as inputs to recalculate `value` if it's a function.</td>
</tr>

<tr>
<td align="left"><code>show_label</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Whether to display the label.</td>
</tr>

<tr>
<td align="left"><code>container</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether to place the component in a padded container.</td>
</tr>

<tr>
<td align="left"><code>scale</code></td>
<td align="left" style="width: 25%;">

```python
int | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Relative size compared to adjacent components.</td>
</tr>

<tr>
<td align="left"><code>min_width</code></td>
<td align="left" style="width: 25%;">

```python
int
```

</td>
<td align="left"><code>160</code></td>
<td align="left">Minimum pixel width of the component.</td>
</tr>

<tr>
<td align="left"><code>visible</code></td>
<td align="left" style="width: 25%;">

```python
bool | Literal["hidden"]
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether the component is visible or hidden.</td>
</tr>

<tr>
<td align="left"><code>elem_id</code></td>
<td align="left" style="width: 25%;">

```python
str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">HTML ID for the component.</td>
</tr>

<tr>
<td align="left"><code>elem_classes</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">HTML classes for the component.</td>
</tr>

<tr>
<td align="left"><code>render</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether to render the component in the Blocks context.</td>
</tr>

<tr>
<td align="left"><code>key</code></td>
<td align="left" style="width: 25%;">

```python
int | str | tuple[int | str, ...] | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Identifier for preserving component state across re-renders.</td>
</tr>

<tr>
<td align="left"><code>preserved_by_key</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | str | None
```

</td>
<td align="left"><code>"value"</code></td>
<td align="left">Parameters to preserve during re-renders.</td>
</tr>

<tr>
<td align="left"><code>columns</code></td>
<td align="left" style="width: 25%;">

```python
int | None
```

</td>
<td align="left"><code>2</code></td>
<td align="left">Number of columns in the grid.</td>
</tr>

<tr>
<td align="left"><code>rows</code></td>
<td align="left" style="width: 25%;">

```python
int | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Number of rows in the grid.</td>
</tr>

<tr>
<td align="left"><code>height</code></td>
<td align="left" style="width: 25%;">

```python
int | float | str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Height of the gallery in pixels or CSS units.</td>
</tr>

<tr>
<td align="left"><code>allow_preview</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether images can be enlarged on click.</td>
</tr>

<tr>
<td align="left"><code>preview</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Whether to start in preview mode (requires allow_preview=True).</td>
</tr>

<tr>
<td align="left"><code>selected_index</code></td>
<td align="left" style="width: 25%;">

```python
int | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Index of the initially selected media item.</td>
</tr>

<tr>
<td align="left"><code>object_fit</code></td>
<td align="left" style="width: 25%;">

```python
Literal[
        "contain", "cover", "fill", "none", "scale-down"
    ]
    | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">CSS object-fit for thumbnails ("contain", "cover", etc.).</td>
</tr>

<tr>
<td align="left"><code>show_share_button</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Whether to show a share button (auto-enabled on Hugging Face Spaces).</td>
</tr>

<tr>
<td align="left"><code>show_download_button</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether to show a download button for the selected media.</td>
</tr>

<tr>
<td align="left"><code>interactive</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Whether the gallery allows uploads.</td>
</tr>

<tr>
<td align="left"><code>type</code></td>
<td align="left" style="width: 25%;">

```python
Literal["numpy", "pil", "filepath"]
```

</td>
<td align="left"><code>"filepath"</code></td>
<td align="left">Format for images passed to the prediction function ("numpy", "pil", "filepath").</td>
</tr>

<tr>
<td align="left"><code>show_fullscreen_button</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether to show a fullscreen button.</td>
</tr>

<tr>
<td align="left"><code>only_custom_metadata</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">Whether to filter out technical EXIF metadata in the popup.</td>
</tr>

<tr>
<td align="left"><code>popup_metadata_width</code></td>
<td align="left" style="width: 25%;">

```python
int | str
```

</td>
<td align="left"><code>500</code></td>
<td align="left">Width of the metadata popup (pixels or CSS string).</td>
</tr>
</tbody></table>


### Events

| name | description |
|:-----|:------------|
| `select` | Event listener for when the user selects or deselects the MediaGallery. Uses event data gradio.SelectData to carry `value` referring to the label of the MediaGallery, and `selected` to refer to state of the MediaGallery. See EventData documentation on how to use this event data |
| `change` | Triggered when the value of the MediaGallery changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. |
| `delete` | This listener is triggered when the user deletes and item from the MediaGallery. Uses event data gradio.DeletedFileData to carry `value` referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data |
| `preview_close` | Triggered when the MediaGallery preview is closed by the user. |
| `preview_open` | Triggered when the MediaGallery preview is opened by the user. |
| `load_metadata` | Triggered when the user clicks the 'Load Metadata' button in the metadata popup. Returns a dictionary of image metadata. |



### User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

- When used as an Input, the component only impacts the input signature of the user function.
- When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

- **As output:** Is passed, list of tuples containing file paths and captions, or None if payload is None.
- **As input:** Should return, list of media items (images, videos, or tuples with captions).

 ```python
 def predict(
     value: Any
 ) -> list | None:
     return value
 ```