Skip to content

Commit

Permalink
Add a simpleimage template for custom components (#7129)
Browse files Browse the repository at this point in the history
* 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 <gradio-pr-bot@users.noreply.github.com>
  • Loading branch information
abidlabs and gradio-pr-bot committed Jan 27, 2024
1 parent 46919c5 commit ccdaec4
Show file tree
Hide file tree
Showing 16 changed files with 553 additions and 16 deletions.
7 changes: 7 additions & 0 deletions .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
3 changes: 2 additions & 1 deletion 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"]
106 changes: 106 additions & 0 deletions 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"
43 changes: 30 additions & 13 deletions gradio/cli/commands/components/_create_utils.py
Expand Up @@ -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(
Expand Down Expand Up @@ -327,7 +341,7 @@ def _create_backend(
pyproject_contents = pyproject.read_text()
pyproject_dest = directory / "pyproject.toml"
pyproject_contents = pyproject_contents.replace("<<name>>", package_name).replace(
"<<template>>", PATTERN.format(template=component.template)
"<<template>>", PATTERN.format(template=correct_cased_template)
)
pyproject_dest.write_text(pyproject_contents)

Expand Down Expand Up @@ -358,6 +372,7 @@ def _create_backend(

p = Path(inspect.getfile(gradio)).parent
python_file = backend / f"{name.lower()}.py"
assert module is not None

shutil.copy(
str(p / module / component.python_file_name),
Expand All @@ -370,9 +385,11 @@ def _create_backend(
shutil.copy(str(source_pyi_file), str(pyi_file))

content = python_file.read_text()
python_file.write_text(_replace_old_class_name(component.template, name, content))
python_file.write_text(
_replace_old_class_name(correct_cased_template, name, content)
)
if pyi_file.exists():
pyi_content = pyi_file.read_text()
pyi_file.write_text(
_replace_old_class_name(component.template, name, pyi_content)
_replace_old_class_name(correct_cased_template, name, pyi_content)
)
Expand Up @@ -38,7 +38,7 @@ gradio cc create MyComponent --template SimpleTextbox
Instead of `MyComponent`, give your component any name.

Instead of `SimpleTextbox`, you can use any Gradio component as a template. `SimpleTextbox` is actually a special component that a stripped-down version of the `Textbox` component that makes it particularly useful when creating your first custom component.
Some other components that are good if you are starting out: `SimpleDropdown` or `File`.
Some other components that are good if you are starting out: `SimpleDropdown`, `SimpleImage`, or `File`.

Tip: Run `gradio cc show` to get a list of available component templates.

Expand Down
1 change: 1 addition & 0 deletions js/app/build_plugins.ts
Expand Up @@ -199,6 +199,7 @@ const ignore_list = [
"lite",
"preview",
"simpledropdown",
"simpleimage",
"simpletextbox",
"storybook",
"theme",
Expand Down
1 change: 1 addition & 0 deletions js/app/package.json
Expand Up @@ -58,6 +58,7 @@
"@gradio/radio": "workspace:^",
"@gradio/row": "workspace:^",
"@gradio/simpledropdown": "workspace:^",
"@gradio/simpleimage": "workspace:^",
"@gradio/simpletextbox": "workspace:^",
"@gradio/slider": "workspace:^",
"@gradio/state": "workspace:^",
Expand Down
2 changes: 2 additions & 0 deletions js/simpleimage/CHANGELOG.md
@@ -0,0 +1,2 @@
# @gradio/simpleimage

44 changes: 44 additions & 0 deletions js/simpleimage/Example.svelte
@@ -0,0 +1,44 @@
<script lang="ts">
import type { FileData } from "@gradio/client";
export let value: null | FileData;
export let samples_dir: string;
export let type: "gallery" | "table";
export let selected = false;
</script>

<div
class="container"
class:table={type === "table"}
class:gallery={type === "gallery"}
class:selected
>
<img src={samples_dir + value?.path} alt="" />
</div>

<style>
.container :global(img) {
width: 100%;
height: 100%;
}
.container.selected {
border-color: var(--border-color-accent);
}
.container.table {
margin: 0 auto;
border: 2px solid var(--border-color-primary);
border-radius: var(--radius-lg);
overflow: hidden;
width: var(--size-20);
height: var(--size-20);
object-fit: cover;
}
.container.gallery {
height: var(--size-20);
max-height: var(--size-20);
object-fit: cover;
}
</style>
106 changes: 106 additions & 0 deletions js/simpleimage/Index.svelte
@@ -0,0 +1,106 @@
<svelte:options accessors={true} />

<script context="module" lang="ts">
export { default as BaseImageUploader } from "./shared/ImageUploader.svelte";
export { default as BaseStaticImage } from "./shared/ImagePreview.svelte";
export { default as BaseExample } from "./Example.svelte";
</script>

<script lang="ts">
import type { Gradio } from "@gradio/utils";
import ImagePreview from "./shared/ImagePreview.svelte";
import ImageUploader from "./shared/ImageUploader.svelte";
import { Block, UploadText } from "@gradio/atoms";
import { StatusTracker } from "@gradio/statustracker";
import type { FileData } from "@gradio/client";
import type { LoadingStatus } from "@gradio/statustracker";
import { normalise_file } from "@gradio/client";
export let elem_id = "";
export let elem_classes: string[] = [];
export let visible = true;
export let value: null | FileData = null;
export let root: string;
export let proxy_url: null | string;
export let label: string;
export let show_label: boolean;
export let show_download_button: boolean;
export let container = true;
export let scale: number | null = null;
export let min_width: number | undefined = undefined;
export let loading_status: LoadingStatus;
export let interactive: boolean;
$: _value = normalise_file(value, root, proxy_url);
export let gradio: Gradio<{
change: never;
upload: never;
clear: never;
}>;
$: url = _value?.url;
$: url, gradio.dispatch("change");
let dragging: boolean;
</script>

{#if !interactive}
<Block
{visible}
variant={"solid"}
border_mode={dragging ? "focus" : "base"}
padding={false}
{elem_id}
{elem_classes}
allow_overflow={false}
{container}
{scale}
{min_width}
>
<StatusTracker
autoscroll={gradio.autoscroll}
i18n={gradio.i18n}
{...loading_status}
/>
<ImagePreview
value={_value}
{label}
{show_label}
{show_download_button}
i18n={gradio.i18n}
/>
</Block>
{:else}
<Block
{visible}
variant={_value === null ? "dashed" : "solid"}
border_mode={dragging ? "focus" : "base"}
padding={false}
{elem_id}
{elem_classes}
allow_overflow={false}
{container}
{scale}
{min_width}
>
<StatusTracker
autoscroll={gradio.autoscroll}
i18n={gradio.i18n}
{...loading_status}
/>

<ImageUploader
bind:value
{root}
on:clear={() => gradio.dispatch("clear")}
on:drag={({ detail }) => (dragging = detail)}
on:upload={() => gradio.dispatch("upload")}
{label}
{show_label}
>
<UploadText i18n={gradio.i18n} type="image" />
</ImageUploader>
</Block>
{/if}

0 comments on commit ccdaec4

Please sign in to comment.