gradio-imagemeta


Namegradio-imagemeta JSON
Version 0.0.1 PyPI version JSON
download
home_pageNone
SummaryImage Preview with Metadata for Gradio Interface
upload_time2025-08-11 23:12:28
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseNone
keywords gradio-custom-component gradio-template-image
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ---
tags: [gradio-custom-component, Image]
title: gradio_imagemeta
short_description: Image Preview with Metadata for Gradio Interface
colorFrom: blue
colorTo: yellow
sdk: gradio
pinned: false
app_file: space.py
---

# `gradio_imagemeta`
<img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20orange">  

Image Preview with Metadata for Gradio Interface

## Installation

```bash
pip install gradio_imagemeta
```

## Usage

```python
from dataclasses import dataclass, field
from typing import List, Any
import gradio as gr
from gradio_imagemeta import ImageMeta
from gradio_imagemeta.helpers import extract_metadata, add_metadata, transfer_metadata
from gradio_propertysheet import PropertySheet
from gradio_propertysheet.helpers import build_dataclass_fields, create_dataclass_instance
from pathlib import Path

output_dir = Path("outputs")
output_dir.mkdir(exist_ok=True)

@dataclass
class ImageSettings:
    """Configuration for image metadata settings."""
    model: str = field(default="", metadata={"label": "Model"})
    f_number: str = field(default="", metadata={"label": "FNumber"})
    iso_speed_ratings: str = field(default="", metadata={"label": "ISOSpeedRatings"})
    s_churn: float = field(
        default=0.0,
        metadata={"component": "slider", "label": "Schurn", "minimum": 0.0, "maximum": 1.0, "step": 0.01},
    )

@dataclass
class PropertyConfig:
    """Root configuration for image properties, including nested image settings."""
    image_settings: ImageSettings = field(default_factory=ImageSettings)
    description: str = field(default="", metadata={"label": "Description"})

def process_example_images(img_custom_path: str, img_all_path: str) -> tuple[str, str]:
    """
    Processes example image paths for display in ImageMeta components.

    Args:
        img_custom_path: File path for the image to display in img_custom.
        img_all_path: File path for the image to display in img_all.

    Returns:
        Tuple of file paths for img_custom and img_all outputs.
    """
    # Verify file existence
    if not Path(img_custom_path).is_file():
        raise FileNotFoundError(f"Image not found: {img_custom_path}")
    if not Path(img_all_path).is_file():
        raise FileNotFoundError(f"Image not found: {img_all_path}")
    
    # Return file paths as strings (ImageMeta accepts file paths as input)
    return str(img_custom_path), str(img_all_path)

def handle_load_metadata(image_data: ImageMeta | None) -> List[Any]:
    """
    Processes image metadata and maps it to output components.

    Args:
        image_data: ImageMeta object containing image data and metadata, or None.

    Returns:
        A list of values for output components (Textbox, Slider, or PropertySheet instances).
    """
    if not image_data:
        return [gr.Textbox(value="") for _ in output_fields]

    metadata = extract_metadata(image_data, only_custom_metadata=True)
    dataclass_fields = build_dataclass_fields(PropertyConfig)
    raw_values = transfer_metadata(output_fields, metadata, dataclass_fields)

    output_values = [gr.skip()] * len(output_fields)
    for i, (component, value) in enumerate(zip(output_fields, raw_values)):
        if hasattr(component, 'root_label'):
            output_values[i] = create_dataclass_instance(PropertyConfig, value)
        else:
            output_values[i] = gr.Textbox(value=value)
    
    return output_values

def save_image_with_metadata(image_data: Any, *inputs: Any) -> str | None:
    """
    Saves an image with updated metadata to a file.

    Args:
        image_data: Input image data (e.g., file path or PIL Image).
        *inputs: Variable number of input values from UI components (Textbox, Slider).

    Returns:
        The file path of the saved image, or None if no image is provided.
    """
    if not image_data:
        return None
    
    params = list(inputs)
    image_params = dict(zip(input_fields.keys(), params))
    dataclass_fields = build_dataclass_fields(PropertyConfig)
    metadata = {label: image_params.get(label, "") for label in dataclass_fields.keys()}
    
    new_filepath = output_dir / "image_with_meta.png"
    add_metadata(image_data, metadata, new_filepath)
    
    return str(new_filepath)

initial_property_from_meta_config = PropertyConfig()

with gr.Blocks() as demo:
    gr.Markdown("# ImageMeta Component Demo")
    gr.Markdown(
        """
        **To Test:**
        1. Upload an image with EXIF or PNG metadata using either the "Upload Imagem (Custom metadata only)" component or the "Upload Imagem (all metadata)" component.
        2. Click the 'Info' icon (ⓘ) in the top-left of the image component to view the metadata panel.
        3. Click 'Load Metadata' in the popup to populate the fields below with metadata values (`Model`, `FNumber`, `ISOSpeedRatings`, `Schurn`, `Description`).
        4. The section below displays how metadata is rendered in components and the `PropertySheet` custom component, showing the hierarchical structure of the image settings.
        5. In the "Metadata Viewer" section, you can add field values as metadata to a previously uploaded image in "Upload Image (Custom metadata only)." Then click 'Add metadata and save image' to save a new image with the metadata.
        """
    )
    property_sheet_state = gr.State(value=initial_property_from_meta_config)
    with gr.Row():
        img_custom = ImageMeta(
            label="Upload Image (Custom metadata only)",
            type="filepath",
            width=300,
            height=400,
            disable_preprocess=False,
            interactive=True
        )
        img_all = ImageMeta(
            label="Upload Image (All metadata)",
            only_custom_metadata=False,
            width=300,
            height=400,
            popup_metadata_height=400,
            popup_metadata_width=500
        )

    gr.Markdown("## Metadata Viewer")
    gr.Markdown("### Individual Components")
    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", value=1.0, minimum=0.0, maximum=1.0, step=0.1)
        description_box = gr.Textbox(label="Description")
    
    gr.Markdown("### PropertySheet Component")
    with gr.Row():
        property_sheet = PropertySheet(
            value=initial_property_from_meta_config,
            label="Image Settings",
            width=400,
            height=550,
            visible=True,
            root_label="General"
        )    
    gr.Markdown("## Metadata Editor")
    with gr.Row():
        save_button = gr.Button("Add Metadata and Save Image")
        saved_file_output = gr.File(label="Download Image")
    
    with gr.Row():
        gr.Examples(
            examples=[
                ["./examples/image_with_meta.png", "./examples/image_with_meta.png"]
            ],
            fn=process_example_images,
            inputs=[img_custom, img_all],
            outputs=[img_custom, img_all],
            cache_examples=True
        )
        
    input_fields = {
        "Model": model_box,
        "FNumber": fnumber_box,
        "ISOSpeedRatings": iso_box,
        "Schurn": s_churn,
        "Description": description_box
    }
    
    output_fields = [
        property_sheet,
        model_box,
        fnumber_box,
        iso_box,
        s_churn,
        description_box
    ]
    
    img_custom.load_metadata(handle_load_metadata, inputs=img_custom, outputs=output_fields)
    img_all.load_metadata(handle_load_metadata, inputs=img_all, outputs=output_fields)
    
    def handle_render_change(updated_config: PropertyConfig, current_state: PropertyConfig):
        """
        Updates the PropertySheet state when its configuration changes.

        Args:
            updated_config: The new PropertyConfig instance from the PropertySheet.
            current_state: The current PropertyConfig state.

        Returns:
            A tuple of (updated_config, updated_config) or (current_state, current_state) if updated_config is None.
        """
        if updated_config is None:
            return current_state, current_state
        return updated_config, updated_config
    
    property_sheet.change(
        fn=handle_render_change,
        inputs=[property_sheet, property_sheet_state],
        outputs=[property_sheet, property_sheet_state]
    )
    save_button.click(
        save_image_with_metadata,
        inputs=[img_custom, *input_fields.values()],
        outputs=[saved_file_output]
    )
    
if __name__ == "__main__":
    demo.launch()
```

## `ImageMeta`

### 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
str | Image.Image | np.ndarray | Callable | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.</td>
</tr>

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

```python
str
```

</td>
<td align="left"><code>"webp"</code></td>
<td align="left">File format (e.g. "png" or "gif"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files.</td>
</tr>

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

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

</td>
<td align="left"><code>None</code></td>
<td align="left">The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.</td>
</tr>

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

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

</td>
<td align="left"><code>None</code></td>
<td align="left">The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.</td>
</tr>

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

```python
Literal[
        "1",
        "L",
        "P",
        "RGB",
        "RGBA",
        "CMYK",
        "YCbCr",
        "LAB",
        "HSV",
        "I",
        "F",
    ]
    | None
```

</td>
<td align="left"><code>"RGB"</code></td>
<td align="left">The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases).</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>"numpy"</code></td>
<td align="left">The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath".</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">The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.</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">Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.</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 that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.</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">If True, will display label.</td>
</tr>

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

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output).</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">If True, will place the component in a container - providing some extra padding around the border.</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. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.</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, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.</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">If True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.</td>
</tr>

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

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">If False, component will be 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">An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.</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">An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.</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">If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.</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">In a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.</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">A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.</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">If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.</td>
</tr>

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

```python
str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.</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">If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear.</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">If True, extracts only custom metadata, excluding technical metadata like ImageWidth or ImageHeight. Defaults to True.</td>
</tr>

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

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">If True, skips preprocessing and returns the raw ImageMetaData payload. Defaults to True.</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>400</code></td>
<td align="left">Metadata popup width in pixels or CSS units. Defaults to 400.</td>
</tr>

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

```python
int | str
```

</td>
<td align="left"><code>300</code></td>
<td align="left">Metadata popup height in pixels or CSS units. Defaults to 300.</td>
</tr>
</tbody></table>


### Events

| name | description |
|:-----|:------------|
| `clear` | This listener is triggered when the user clears the ImageMeta using the clear button for the component. |
| `change` | Triggered when the value of the ImageMeta 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. |
| `select` | Event listener for when the user selects or deselects the ImageMeta. Uses event data gradio.SelectData to carry `value` referring to the label of the ImageMeta, and `selected` to refer to state of the ImageMeta. See EventData documentation on how to use this event data |
| `upload` | This listener is triggered when the user uploads a file into the ImageMeta. |
| `input` | This listener is triggered when the user changes the value of the ImageMeta. |
| `load_metadata` | Triggered when the user clicks the 'Load Metadata' button, expecting ImageMetaData as input. |



### 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, preprocessed image as a NumPy array, PIL Image, filepath, ImageMetaData, or None.
- **As input:** Should return, input image as a NumPy array, PIL Image, string (file path or URL), Path object, or None.

 ```python
 def predict(
     value: numpy.ndarray | PIL.Image.Image | str | ImageMetaData | None
 ) -> numpy.ndarray | PIL.Image.Image | str | pathlib.Path | None:
     return value
 ```
 

## `ImageMetaData`
```python
class ImageMetaData(ImageData):
    pass
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "gradio-imagemeta",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "gradio-custom-component, gradio-template-Image",
    "author": null,
    "author_email": "Eliseu Silva <elismasilva@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/0e/75/561c77b47a293affc1f604a6c0d08cb74a029dbf548fcfcf02b62a745ef1/gradio_imagemeta-0.0.1.tar.gz",
    "platform": null,
    "description": "---\ntags: [gradio-custom-component, Image]\ntitle: gradio_imagemeta\nshort_description: Image Preview with Metadata for Gradio Interface\ncolorFrom: blue\ncolorTo: yellow\nsdk: gradio\npinned: false\napp_file: space.py\n---\n\n# `gradio_imagemeta`\n<img alt=\"Static Badge\" src=\"https://img.shields.io/badge/version%20-%200.0.1%20-%20orange\">  \n\nImage Preview with Metadata for Gradio Interface\n\n## Installation\n\n```bash\npip install gradio_imagemeta\n```\n\n## Usage\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Any\nimport gradio as gr\nfrom gradio_imagemeta import ImageMeta\nfrom gradio_imagemeta.helpers import extract_metadata, add_metadata, transfer_metadata\nfrom gradio_propertysheet import PropertySheet\nfrom gradio_propertysheet.helpers import build_dataclass_fields, create_dataclass_instance\nfrom pathlib import Path\n\noutput_dir = Path(\"outputs\")\noutput_dir.mkdir(exist_ok=True)\n\n@dataclass\nclass ImageSettings:\n    \"\"\"Configuration for image metadata settings.\"\"\"\n    model: str = field(default=\"\", metadata={\"label\": \"Model\"})\n    f_number: str = field(default=\"\", metadata={\"label\": \"FNumber\"})\n    iso_speed_ratings: str = field(default=\"\", metadata={\"label\": \"ISOSpeedRatings\"})\n    s_churn: float = field(\n        default=0.0,\n        metadata={\"component\": \"slider\", \"label\": \"Schurn\", \"minimum\": 0.0, \"maximum\": 1.0, \"step\": 0.01},\n    )\n\n@dataclass\nclass PropertyConfig:\n    \"\"\"Root configuration for image properties, including nested image settings.\"\"\"\n    image_settings: ImageSettings = field(default_factory=ImageSettings)\n    description: str = field(default=\"\", metadata={\"label\": \"Description\"})\n\ndef process_example_images(img_custom_path: str, img_all_path: str) -> tuple[str, str]:\n    \"\"\"\n    Processes example image paths for display in ImageMeta components.\n\n    Args:\n        img_custom_path: File path for the image to display in img_custom.\n        img_all_path: File path for the image to display in img_all.\n\n    Returns:\n        Tuple of file paths for img_custom and img_all outputs.\n    \"\"\"\n    # Verify file existence\n    if not Path(img_custom_path).is_file():\n        raise FileNotFoundError(f\"Image not found: {img_custom_path}\")\n    if not Path(img_all_path).is_file():\n        raise FileNotFoundError(f\"Image not found: {img_all_path}\")\n    \n    # Return file paths as strings (ImageMeta accepts file paths as input)\n    return str(img_custom_path), str(img_all_path)\n\ndef handle_load_metadata(image_data: ImageMeta | None) -> List[Any]:\n    \"\"\"\n    Processes image metadata and maps it to output components.\n\n    Args:\n        image_data: ImageMeta object containing image data and metadata, or None.\n\n    Returns:\n        A list of values for output components (Textbox, Slider, or PropertySheet instances).\n    \"\"\"\n    if not image_data:\n        return [gr.Textbox(value=\"\") for _ in output_fields]\n\n    metadata = extract_metadata(image_data, only_custom_metadata=True)\n    dataclass_fields = build_dataclass_fields(PropertyConfig)\n    raw_values = transfer_metadata(output_fields, metadata, dataclass_fields)\n\n    output_values = [gr.skip()] * len(output_fields)\n    for i, (component, value) in enumerate(zip(output_fields, raw_values)):\n        if hasattr(component, 'root_label'):\n            output_values[i] = create_dataclass_instance(PropertyConfig, value)\n        else:\n            output_values[i] = gr.Textbox(value=value)\n    \n    return output_values\n\ndef save_image_with_metadata(image_data: Any, *inputs: Any) -> str | None:\n    \"\"\"\n    Saves an image with updated metadata to a file.\n\n    Args:\n        image_data: Input image data (e.g., file path or PIL Image).\n        *inputs: Variable number of input values from UI components (Textbox, Slider).\n\n    Returns:\n        The file path of the saved image, or None if no image is provided.\n    \"\"\"\n    if not image_data:\n        return None\n    \n    params = list(inputs)\n    image_params = dict(zip(input_fields.keys(), params))\n    dataclass_fields = build_dataclass_fields(PropertyConfig)\n    metadata = {label: image_params.get(label, \"\") for label in dataclass_fields.keys()}\n    \n    new_filepath = output_dir / \"image_with_meta.png\"\n    add_metadata(image_data, metadata, new_filepath)\n    \n    return str(new_filepath)\n\ninitial_property_from_meta_config = PropertyConfig()\n\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# ImageMeta Component Demo\")\n    gr.Markdown(\n        \"\"\"\n        **To Test:**\n        1. Upload an image with EXIF or PNG metadata using either the \"Upload Imagem (Custom metadata only)\" component or the \"Upload Imagem (all metadata)\" component.\n        2. Click the 'Info' icon (\u24d8) in the top-left of the image component to view the metadata panel.\n        3. Click 'Load Metadata' in the popup to populate the fields below with metadata values (`Model`, `FNumber`, `ISOSpeedRatings`, `Schurn`, `Description`).\n        4. The section below displays how metadata is rendered in components and the `PropertySheet` custom component, showing the hierarchical structure of the image settings.\n        5. In the \"Metadata Viewer\" section, you can add field values as metadata to a previously uploaded image in \"Upload Image (Custom metadata only).\" Then click 'Add metadata and save image' to save a new image with the metadata.\n        \"\"\"\n    )\n    property_sheet_state = gr.State(value=initial_property_from_meta_config)\n    with gr.Row():\n        img_custom = ImageMeta(\n            label=\"Upload Image (Custom metadata only)\",\n            type=\"filepath\",\n            width=300,\n            height=400,\n            disable_preprocess=False,\n            interactive=True\n        )\n        img_all = ImageMeta(\n            label=\"Upload Image (All metadata)\",\n            only_custom_metadata=False,\n            width=300,\n            height=400,\n            popup_metadata_height=400,\n            popup_metadata_width=500\n        )\n\n    gr.Markdown(\"## Metadata Viewer\")\n    gr.Markdown(\"### Individual Components\")\n    with gr.Row():\n        model_box = gr.Textbox(label=\"Model\")\n        fnumber_box = gr.Textbox(label=\"FNumber\")\n        iso_box = gr.Textbox(label=\"ISOSpeedRatings\")\n        s_churn = gr.Slider(label=\"Schurn\", value=1.0, minimum=0.0, maximum=1.0, step=0.1)\n        description_box = gr.Textbox(label=\"Description\")\n    \n    gr.Markdown(\"### PropertySheet Component\")\n    with gr.Row():\n        property_sheet = PropertySheet(\n            value=initial_property_from_meta_config,\n            label=\"Image Settings\",\n            width=400,\n            height=550,\n            visible=True,\n            root_label=\"General\"\n        )    \n    gr.Markdown(\"## Metadata Editor\")\n    with gr.Row():\n        save_button = gr.Button(\"Add Metadata and Save Image\")\n        saved_file_output = gr.File(label=\"Download Image\")\n    \n    with gr.Row():\n        gr.Examples(\n            examples=[\n                [\"./examples/image_with_meta.png\", \"./examples/image_with_meta.png\"]\n            ],\n            fn=process_example_images,\n            inputs=[img_custom, img_all],\n            outputs=[img_custom, img_all],\n            cache_examples=True\n        )\n        \n    input_fields = {\n        \"Model\": model_box,\n        \"FNumber\": fnumber_box,\n        \"ISOSpeedRatings\": iso_box,\n        \"Schurn\": s_churn,\n        \"Description\": description_box\n    }\n    \n    output_fields = [\n        property_sheet,\n        model_box,\n        fnumber_box,\n        iso_box,\n        s_churn,\n        description_box\n    ]\n    \n    img_custom.load_metadata(handle_load_metadata, inputs=img_custom, outputs=output_fields)\n    img_all.load_metadata(handle_load_metadata, inputs=img_all, outputs=output_fields)\n    \n    def handle_render_change(updated_config: PropertyConfig, current_state: PropertyConfig):\n        \"\"\"\n        Updates the PropertySheet state when its configuration changes.\n\n        Args:\n            updated_config: The new PropertyConfig instance from the PropertySheet.\n            current_state: The current PropertyConfig state.\n\n        Returns:\n            A tuple of (updated_config, updated_config) or (current_state, current_state) if updated_config is None.\n        \"\"\"\n        if updated_config is None:\n            return current_state, current_state\n        return updated_config, updated_config\n    \n    property_sheet.change(\n        fn=handle_render_change,\n        inputs=[property_sheet, property_sheet_state],\n        outputs=[property_sheet, property_sheet_state]\n    )\n    save_button.click(\n        save_image_with_metadata,\n        inputs=[img_custom, *input_fields.values()],\n        outputs=[saved_file_output]\n    )\n    \nif __name__ == \"__main__\":\n    demo.launch()\n```\n\n## `ImageMeta`\n\n### Initialization\n\n<table>\n<thead>\n<tr>\n<th align=\"left\">name</th>\n<th align=\"left\" style=\"width: 25%;\">type</th>\n<th align=\"left\">default</th>\n<th align=\"left\">description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>value</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nstr | Image.Image | np.ndarray | Callable | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>format</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nstr\n```\n\n</td>\n<td align=\"left\"><code>\"webp\"</code></td>\n<td align=\"left\">File format (e.g. \"png\" or \"gif\"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>height</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | str | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>width</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | str | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>image_mode</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nLiteral[\n        \"1\",\n        \"L\",\n        \"P\",\n        \"RGB\",\n        \"RGBA\",\n        \"CMYK\",\n        \"YCbCr\",\n        \"LAB\",\n        \"HSV\",\n        \"I\",\n        \"F\",\n    ]\n    | None\n```\n\n</td>\n<td align=\"left\"><code>\"RGB\"</code></td>\n<td align=\"left\">The pixel format and color depth that the image should be loaded and preprocessed as. \"RGB\" will load the image as a color image, or \"L\" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. \"RGBA\" for a .png image, \"RGB\" in most other cases).</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>type</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nLiteral[\"numpy\", \"pil\", \"filepath\"]\n```\n\n</td>\n<td align=\"left\"><code>\"numpy\"</code></td>\n<td align=\"left\">The format the image is converted before being passed into the prediction function. \"numpy\" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, \"pil\" converts the image to a PIL image object, \"filepath\" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to \"filepath\" or \"pil\". To support SVGs, the `type` should be set to \"filepath\".</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>label</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nstr | I18nData | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>every</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nTimer | float | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>inputs</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nComponent | Sequence[Component] | set[Component] | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>show_label</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">If True, will display label.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>show_download_button</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output).</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>container</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If True, will place the component in a container - providing some extra padding around the border.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>scale</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">Relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>min_width</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint\n```\n\n</td>\n<td align=\"left\"><code>160</code></td>\n<td align=\"left\">Minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>interactive</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">If True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>visible</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If False, component will be hidden.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>elem_id</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nstr | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>elem_classes</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nlist[str] | str | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>render</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>key</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | str | tuple[int | str, ...] | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">In a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>preserved_by_key</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nlist[str] | str | None\n```\n\n</td>\n<td align=\"left\"><code>\"value\"</code></td>\n<td align=\"left\">A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>show_share_button</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>placeholder</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nstr | None\n```\n\n</td>\n<td align=\"left\"><code>None</code></td>\n<td align=\"left\">Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>show_fullscreen_button</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>only_custom_metadata</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If True, extracts only custom metadata, excluding technical metadata like ImageWidth or ImageHeight. Defaults to True.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>disable_preprocess</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nbool\n```\n\n</td>\n<td align=\"left\"><code>True</code></td>\n<td align=\"left\">If True, skips preprocessing and returns the raw ImageMetaData payload. Defaults to True.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>popup_metadata_width</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | str\n```\n\n</td>\n<td align=\"left\"><code>400</code></td>\n<td align=\"left\">Metadata popup width in pixels or CSS units. Defaults to 400.</td>\n</tr>\n\n<tr>\n<td align=\"left\"><code>popup_metadata_height</code></td>\n<td align=\"left\" style=\"width: 25%;\">\n\n```python\nint | str\n```\n\n</td>\n<td align=\"left\"><code>300</code></td>\n<td align=\"left\">Metadata popup height in pixels or CSS units. Defaults to 300.</td>\n</tr>\n</tbody></table>\n\n\n### Events\n\n| name | description |\n|:-----|:------------|\n| `clear` | This listener is triggered when the user clears the ImageMeta using the clear button for the component. |\n| `change` | Triggered when the value of the ImageMeta 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. |\n| `select` | Event listener for when the user selects or deselects the ImageMeta. Uses event data gradio.SelectData to carry `value` referring to the label of the ImageMeta, and `selected` to refer to state of the ImageMeta. See EventData documentation on how to use this event data |\n| `upload` | This listener is triggered when the user uploads a file into the ImageMeta. |\n| `input` | This listener is triggered when the user changes the value of the ImageMeta. |\n| `load_metadata` | Triggered when the user clicks the 'Load Metadata' button, expecting ImageMetaData as input. |\n\n\n\n### User function\n\nThe impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).\n\n- When used as an Input, the component only impacts the input signature of the user function.\n- When used as an output, the component only impacts the return signature of the user function.\n\nThe code snippet below is accurate in cases where the component is used as both an input and an output.\n\n- **As output:** Is passed, preprocessed image as a NumPy array, PIL Image, filepath, ImageMetaData, or None.\n- **As input:** Should return, input image as a NumPy array, PIL Image, string (file path or URL), Path object, or None.\n\n ```python\n def predict(\n     value: numpy.ndarray | PIL.Image.Image | str | ImageMetaData | None\n ) -> numpy.ndarray | PIL.Image.Image | str | pathlib.Path | None:\n     return value\n ```\n \n\n## `ImageMetaData`\n```python\nclass ImageMetaData(ImageData):\n    pass\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Image Preview with Metadata for Gradio Interface",
    "version": "0.0.1",
    "project_urls": null,
    "split_keywords": [
        "gradio-custom-component",
        " gradio-template-image"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "acab634955544017ec27ce4a535a386bce8e536d4b5461d9cf3c1a68cb31b4ad",
                "md5": "4b3bcbdf4adc99b857c9d0aa9a7e7b4a",
                "sha256": "08827587f25cfa5574eedd524282d50e7c6f00b6d5fb7fded6e64bc11226ee00"
            },
            "downloads": -1,
            "filename": "gradio_imagemeta-0.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4b3bcbdf4adc99b857c9d0aa9a7e7b4a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 174863,
            "upload_time": "2025-08-11T23:12:26",
            "upload_time_iso_8601": "2025-08-11T23:12:26.020662Z",
            "url": "https://files.pythonhosted.org/packages/ac/ab/634955544017ec27ce4a535a386bce8e536d4b5461d9cf3c1a68cb31b4ad/gradio_imagemeta-0.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0e75561c77b47a293affc1f604a6c0d08cb74a029dbf548fcfcf02b62a745ef1",
                "md5": "f7103bb06aa2c0764e9ba9abfdb7c472",
                "sha256": "756ff65a6a641c782e16691cbb03196910c1d369cd0a34bfc0742c7a431aded5"
            },
            "downloads": -1,
            "filename": "gradio_imagemeta-0.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "f7103bb06aa2c0764e9ba9abfdb7c472",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 6047418,
            "upload_time": "2025-08-11T23:12:28",
            "upload_time_iso_8601": "2025-08-11T23:12:28.484520Z",
            "url": "https://files.pythonhosted.org/packages/0e/75/561c77b47a293affc1f604a6c0d08cb74a029dbf548fcfcf02b62a745ef1/gradio_imagemeta-0.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-11 23:12:28",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "gradio-imagemeta"
}
        
Elapsed time: 0.66083s