From ccdaec45002d0a9d6016e8e2078b843a1ff9172b Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 26 Jan 2024 17:29:29 -0800 Subject: [PATCH] Add a `simpleimage` template for custom components (#7129) * simpleimage template * add changeset * changes * change * changes * update backend * update frontend * add changeset * lint * fix package * add changeset * remove warnings * docstrings * fix error * fixes --------- Co-authored-by: gradio-pr-bot --- .changeset/angry-onions-hope.md | 7 ++ gradio/_simple_templates/__init__.py | 3 +- gradio/_simple_templates/simpleimage.py | 106 ++++++++++++++++++ .../cli/commands/components/_create_utils.py | 43 ++++--- .../01_custom-components-in-five-minutes.md | 2 +- js/app/build_plugins.ts | 1 + js/app/package.json | 1 + js/simpleimage/CHANGELOG.md | 2 + js/simpleimage/Example.svelte | 44 ++++++++ js/simpleimage/Index.svelte | 106 ++++++++++++++++++ js/simpleimage/package.json | 28 +++++ js/simpleimage/shared/ClearImage.svelte | 30 +++++ js/simpleimage/shared/ImagePreview.svelte | 61 ++++++++++ js/simpleimage/shared/ImageUploader.svelte | 97 ++++++++++++++++ pnpm-lock.yaml | 36 ++++++ test/test_gradio_component_cli.py | 2 +- 16 files changed, 553 insertions(+), 16 deletions(-) create mode 100644 .changeset/angry-onions-hope.md create mode 100644 gradio/_simple_templates/simpleimage.py create mode 100644 js/simpleimage/CHANGELOG.md create mode 100644 js/simpleimage/Example.svelte create mode 100644 js/simpleimage/Index.svelte create mode 100644 js/simpleimage/package.json create mode 100644 js/simpleimage/shared/ClearImage.svelte create mode 100644 js/simpleimage/shared/ImagePreview.svelte create mode 100644 js/simpleimage/shared/ImageUploader.svelte diff --git a/.changeset/angry-onions-hope.md b/.changeset/angry-onions-hope.md new file mode 100644 index 0000000000..16474fa4e2 --- /dev/null +++ b/.changeset/angry-onions-hope.md @@ -0,0 +1,7 @@ +--- +"@gradio/app": minor +"@gradio/simpleimage": minor +"gradio": minor +--- + +feat:Add a `simpleimage` template for custom components diff --git a/gradio/_simple_templates/__init__.py b/gradio/_simple_templates/__init__.py index 8c61b4e4b1..bf5acb3755 100644 --- a/gradio/_simple_templates/__init__.py +++ b/gradio/_simple_templates/__init__.py @@ -1,4 +1,5 @@ from .simpledropdown import SimpleDropdown +from .simpleimage import SimpleImage from .simpletextbox import SimpleTextbox -__all__ = ["SimpleDropdown", "SimpleTextbox"] +__all__ = ["SimpleDropdown", "SimpleTextbox", "SimpleImage"] diff --git a/gradio/_simple_templates/simpleimage.py b/gradio/_simple_templates/simpleimage.py new file mode 100644 index 0000000000..22de90f672 --- /dev/null +++ b/gradio/_simple_templates/simpleimage.py @@ -0,0 +1,106 @@ +"""gr.SimpleImage() component.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from gradio_client.documentation import document, set_documentation_group + +from gradio.components.base import Component +from gradio.data_classes import FileData +from gradio.events import Events + +set_documentation_group("component") + + +@document() +class SimpleImage(Component): + """ + Creates an image component that can be used to upload images (as an input) or display images (as an output). + Preprocessing: passes the uploaded image as a {str} filepath. + Postprocessing: expects a {str} or {pathlib.Path} filepath to an image and displays the image. + Examples-format: a {str} local filepath or URL to an image. + """ + + EVENTS = [ + Events.clear, + Events.change, + Events.upload, + ] + + data_model = FileData + + def __init__( + self, + value: str | None = None, + *, + label: str | None = None, + every: float | None = None, + show_label: bool | None = None, + show_download_button: bool = True, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + ): + """ + Parameters: + value: A path or URL for the default value that SimpleImage component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. + label: 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. + every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. + show_label: if True, will display label. + show_download_button: If True, will display button to download image. + container: If True, will place the component in a container - providing some extra padding around the border. + scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. + min_width: 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. + interactive: 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. + visible: If False, component will be hidden. + elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. + elem_classes: 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. + render: 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. + """ + self.show_download_button = show_download_button + super().__init__( + label=label, + every=every, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + value=value, + ) + + def preprocess(self, payload: FileData | None) -> str | None: + """ + Parameters: + payload: A FileData object containing the image data. + Returns: + A string containing the path to the image. + """ + if payload is None: + return None + return payload.path + + def postprocess(self, value: str | Path | None) -> FileData | None: + """ + Parameters: + value: A string or pathlib.Path object containing the path to the image. + Returns: + A FileData object containing the image data. + """ + if value is None: + return None + return FileData(path=str(value), orig_name=Path(value).name) + + def example_inputs(self) -> Any: + return "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png" diff --git a/gradio/cli/commands/components/_create_utils.py b/gradio/cli/commands/components/_create_utils.py index ef401ef615..5fce63f775 100644 --- a/gradio/cli/commands/components/_create_utils.py +++ b/gradio/cli/commands/components/_create_utils.py @@ -287,17 +287,31 @@ def _replace_old_class_name(old_class_name: str, new_class_name: str, content: s def _create_backend( name: str, component: ComponentFiles, directory: Path, package_name: str ): - if component.template in gradio.components.__all__: - module = "components" - elif component.template in gradio.layouts.__all__: - module = "layouts" - elif component.template in gradio._simple_templates.__all__: # type: ignore - module = "_simple_templates" - else: + def find_template_in_list(template, list_to_search): + for item in list_to_search: + if template.lower() == item.lower(): + return item + return None + + lists_to_search = [ + (gradio.components.__all__, "components"), + (gradio.layouts.__all__, "layouts"), + (gradio._simple_templates.__all__, "_simple_templates"), # type: ignore + ] + + correct_cased_template = None + module = None + + for list_, module_name in lists_to_search: + correct_cased_template = find_template_in_list(component.template, list_) + if correct_cased_template: + module = module_name + break + + if not correct_cased_template: raise ValueError( - f"Cannot find {component.template} in gradio.components or gradio.layouts. " - "Please pass in a valid component name via the --template option. " - "It must match the name of the python class exactly." + f"Cannot find {component.template} in gradio.components, gradio.layouts, or gradio._simple_templates. " + "Please pass in a valid component name via the --template option. It must match the name of the python class." ) readme_contents = textwrap.dedent( @@ -327,7 +341,7 @@ from {package_name} import {name} pyproject_contents = pyproject.read_text() pyproject_dest = directory / "pyproject.toml" pyproject_contents = pyproject_contents.replace("<>", package_name).replace( - "<