Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cc fe 2 #5526

Merged
merged 9 commits into from
Sep 13, 2023
Merged

Cc fe 2 #5526

Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .config/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const js_rules_disabled = Object.fromEntries(

const js_rules = {
...js_rules_disabled,
"no-console": ["error", { allow: ["warn", "error", "debug"] }],
"no-console": ["error", { allow: ["warn", "error", "debug", "info"] }],
"no-constant-condition": "error",
"no-dupe-args": "error",
"no-extra-boolean-cast": "error",
Expand Down
2 changes: 1 addition & 1 deletion demo/kitchen_sink/run.ipynb

Large diffs are not rendered by default.

15 changes: 9 additions & 6 deletions demo/kitchen_sink/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def fn(
audio2,
file,
df1,
df2,
):
return (
(text1 if single_checkbox else text2)
Expand Down Expand Up @@ -96,7 +95,12 @@ def fn(
gr.CheckboxGroup(label="CheckboxGroup", choices=CHOICES, value=CHOICES[0:2]),
gr.Radio(label="Radio", choices=CHOICES, value=CHOICES[2]),
gr.Dropdown(label="Dropdown", choices=CHOICES),
gr.Dropdown(label="Multiselect Dropdown (Max choice: 2)", choices=CHOICES, multiselect=True, max_choices=2),
gr.Dropdown(
label="Multiselect Dropdown (Max choice: 2)",
choices=CHOICES,
multiselect=True,
max_choices=2,
),
gr.Image(label="Image"),
gr.Image(label="Image w/ Cropper", tool="select"),
gr.Image(label="Sketchpad", source="canvas"),
Expand All @@ -113,8 +117,8 @@ def fn(
gr.Audio(label="Audio"),
gr.Image(label="Image"),
gr.Video(label="Video"),
gr.HighlightedText(label="HighlightedText",
color_map={"punc": "pink", "test 0": "blue"}
gr.HighlightedText(
label="HighlightedText", color_map={"punc": "pink", "test 0": "blue"}
),
gr.HighlightedText(label="HighlightedText", show_legend=True),
gr.JSON(label="JSON"),
Expand Down Expand Up @@ -144,7 +148,6 @@ def fn(
os.path.join(os.path.dirname(__file__), "files/cantina.wav"),
os.path.join(os.path.dirname(__file__), "files/titanic.csv"),
[[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],
os.path.join(os.path.dirname(__file__), "files/time.csv"),
]
]
* 3,
Expand All @@ -155,4 +158,4 @@ def fn(
)

if __name__ == "__main__":
demo.launch()
demo.launch()
16 changes: 12 additions & 4 deletions gradio/cli/commands/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,14 @@ def ignore(s, names):
source_package_json = json.load(open(str(frontend / "package.json")))
source_package_json["name"] = name.lower()
for dep in source_package_json.get("dependencies", []):
source_package_json["dependencies"][dep] = get_js_dependency_version(
dep, p / "_frontend_code"
)
# if curent working directory is the gradio repo, use the local version of the dependency
if (
"gradio/js/gradio-preview/test" not in pathlib.Path.cwd().as_posix()
and dep.startswith("@gradio/")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice good catch with @gradio

):
source_package_json["dependencies"][dep] = get_js_dependency_version(
dep, p / "_frontend_code"
)

json.dump(
source_package_json, open(str(frontend / "package.json"), "w"), indent=2
Expand Down Expand Up @@ -125,7 +130,9 @@ def _create_backend(name: str, template: str, directory: pathlib.Path):
from {name.lower()} import {name}

with gr.Blocks() as demo:
{name}()
{name}(interactive=True)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something is up when cloning the image component FYI

UploadText.svelte:17 Uncaught (in promise) TypeError: ctx[1] is not a function
    at create_fragment (UploadText.svelte:17:7)
    at init (svelte-internal.js:3237:34)
    at new UploadText (UploadText.svelte:19:37)
    at createProxiedComponent (svelte-hooks.js:341:9)
    at new ProxyComponent (proxy.js:242:7)
    at new Proxy<UploadText> (proxy.js:349:11)
    at Array.create_default_slot_1 (InteractiveImage.svelte:37:15)
    at create_slot (svelte-internal.js:165:23)
    at Array.create_if_block_1 (Image.svelte:219:52)
    at Array.create_default_slot (Image.svelte:238:95)
import gradio as gr
from newimage import NewImage

with gr.Blocks() as demo:
    inp = NewImage(interactive=True)
    out = NewImage(interactive=False)
    # gr.Examples(["https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg"],
    #             [inp], [out], fn=lambda s: s, cache_examples=True)
    

demo.launch()

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually nvm this was my bad

{name}(interactive=False)


demo.launch()
"""
Expand Down Expand Up @@ -246,6 +253,7 @@ def _create(
)
if pipe.returncode != 0:
live.update(":red_square: NPM install [bold][red]failed[/][/]")
live.update(pipe.stdout)
live.update(pipe.stderr)
else:
live.update(":white_check_mark: NPM install succeeded!")
Expand Down
2 changes: 1 addition & 1 deletion gradio/components/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def postprocess(self, y: str | list[str] | None) -> ListFiles | FileData | None:
"data": None,
"is_file": True,
}
return FileData(value=d)
return FileData(**d)

def as_example(self, input_data: str | list | None) -> str:
if input_data is None:
Expand Down
7 changes: 7 additions & 0 deletions gradio/components/json_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Callable, Literal

from gradio_client.documentation import document, set_documentation_group
Expand Down Expand Up @@ -116,6 +117,12 @@ def preprocess(self, x: Any) -> Any:
def example_inputs(self) -> Any:
return {"foo": "bar"}

def flag(self, x: Any, flag_dir: str | Path = "") -> str:
return json.dumps(x)

def read_from_flag(self, x: Any, flag_dir: str | Path | None = None):
return json.loads(x)

def style(self, *, container: bool | None = None, **kwargs):
"""
This method is deprecated. Please set these arguments in the constructor instead.
Expand Down
13 changes: 7 additions & 6 deletions gradio/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,13 @@ def __init__(self, trigger: Block, key_vals, dep_index):
"""
Triggered after directly preceding event is completed, regardless of success or failure.
"""
self.success = partial(EventListener(
"success",
trigger_after=dep_index,
trigger_only_on_success=True,
).listener,
trigger
self.success = partial(
EventListener(
"success",
trigger_after=dep_index,
trigger_only_on_success=True,
).listener,
trigger,
)
"""
Triggered after directly preceding event is completed, if it was successful.
Expand Down
1 change: 0 additions & 1 deletion gradio/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,6 @@ async def get_queue_status():
async def upload_file(
files: List[UploadFile] = File(...),
):
print("Here")
output_files = []
file_manager = gradio.File()
for input_file in files:
Expand Down
1 change: 1 addition & 0 deletions js/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@gradio/column": "workspace:^",
"@gradio/dataframe": "workspace:^",
"@gradio/dropdown": "workspace:^",
"@gradio/fallback": "workspace:^",
"@gradio/file": "workspace:^",
"@gradio/form": "workspace:^",
"@gradio/gallery": "workspace:^",
Expand Down
49 changes: 44 additions & 5 deletions js/app/src/Blocks.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import { _ } from "svelte-i18n";
import type { client } from "@gradio/client";

import { component_map } from "./components/directory";
import {
component_map,
fallback_component_map
} from "./components/directory";
import { create_loading_status_store, app_state } from "./stores";
import type { LoadingStatusCollection } from "./stores";

Expand Down Expand Up @@ -120,7 +123,7 @@

async function load_component<T extends ComponentMeta["type"]>(
name: T,
mode: ComponentMeta["props"]["mode"]
mode: ComponentMeta["props"]["mode"] | "example"
): Promise<{
name: T;
component: LoadedComponent;
Expand All @@ -133,6 +136,16 @@
component: c as LoadedComponent
};
} catch (e) {
if (mode === "example") {
try {
return load_custom_component(name, "example");
} catch (e) {
return {
name,
component: await import("@gradio/fallback/example")
};
}
}
if (mode === "interactive") {
try {
const c = await component_map[name]["static"]();
Expand Down Expand Up @@ -196,13 +209,20 @@

async function load_custom_component<T extends ComponentMeta["type"]>(
name: T,
mode: ComponentMeta["props"]["mode"]
mode: ComponentMeta["props"]["mode"] | "example"
): Promise<{
name: T;
component: LoadedComponent;
}> {
const comps = "__ROOT_PATH__";
try {
if (
typeof comps !== "object" ||
!comps?.[name] ||
!comps?.[name]?.[mode]
) {
throw new Error(`Component ${name} not found`);
}
//@ts-ignore
const c = await comps[name][mode]();
return {
Expand All @@ -212,6 +232,7 @@
} catch (e) {
if (mode === "interactive") {
try {
//@ts-ignore
const c = await comps[name]["static"]();
return {
name,
Expand All @@ -223,8 +244,8 @@
throw e;
}
} else {
console.error(`failed to load: ${name}`);
console.error(e);
// console.error(`failed to load: ${name}`);
// console.error(e);
throw e;
}
}
Expand Down Expand Up @@ -288,6 +309,24 @@
}
__type_for_id.set(c.id, c.props.mode);

if (c.type === "dataset") {
const example_component_map = new Map();

(c.props.components as string[]).forEach((name: string) => {
if (example_component_map.has(name)) {
return;
}
let _c;

//@ts-ignore
_c = load_component(name, "example");

example_component_map.set(name, _c);
});

c.props.component_map = example_component_map;
}

// maybe load custom

const _c = c.props.custom_component
Expand Down
10 changes: 6 additions & 4 deletions js/app/src/Index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,16 @@
active_theme_mode = handle_darkmode(wrapper);
}

//@ts-ignore
const gradio_dev_mode = window.__GRADIO_DEV__;
const server_port = "__GRADIO__SERVER_PORT__";

console.log({ gradio_dev_mode, server_port });
//@ts-ignore
const server_port = window.__GRADIO__SERVER_PORT__;

const api_url =
BUILD_MODE === "dev" || gradio_dev_mode === "dev"
? "http://localhost:7860"
? `http://localhost:${
typeof server_port === "number" ? server_port : 7860
}`
: host || space || src || location.origin;

app = await client(api_url, {
Expand Down
49 changes: 39 additions & 10 deletions js/app/src/components/Dataset/Dataset.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
<script lang="ts">
import { Block } from "@gradio/atoms";
import type { SvelteComponent, ComponentType } from "svelte";
import { component_map } from "./directory";
import type { Gradio, SelectData } from "@gradio/utils";
import { get_fetchable_url_or_file } from "@gradio/upload";
export let components: (keyof typeof component_map)[];
export let components: string[];
export let component_map: Map<
string,
Promise<{
name: string;
component: { default: ComponentType<SvelteComponent> };
}>
>;
export let label = "Examples";
export let headers: string[];
export let samples: any[][];
Expand Down Expand Up @@ -66,12 +72,35 @@
}
}

$: component_meta = selected_samples.map((sample_row) =>
sample_row.map((sample_cell, j) => ({
value: sample_cell,
component: component_map[components[j]] as ComponentType<SvelteComponent>
}))
);
let component_meta: {
value: any;
component: ComponentType<SvelteComponent>;
}[][] = [];

async function get_component_meta(selected_samples: any[][]): Promise<void> {
component_meta = await Promise.all(
selected_samples.map(
async (sample_row) =>
await Promise.all(
sample_row.map(async (sample_cell, j) => {
return {
value: sample_cell,
component: (await component_map.get(components[j]))?.component
?.default as ComponentType<SvelteComponent>
};
})
)
)
);
}

$: get_component_meta(selected_samples);
$: console.log({

Check failure on line 98 in js/app/src/components/Dataset/Dataset.svelte

View workflow job for this annotation

GitHub Actions / static checks

Unexpected console statement
component_meta,
selected_samples,
components,
component_map
});
</script>

<Block
Expand Down Expand Up @@ -115,7 +144,7 @@
on:mouseenter={() => handle_mouseenter(i)}
on:mouseleave={() => handle_mouseleave()}
>
{#if Object.keys(component_map).includes(components[0]) && component_map[components[0]]}
{#if component_meta.length && component_map.get(components[0])}
<svelte:component
this={component_meta[0][0].component}
value={sample_row[0]}
Expand Down Expand Up @@ -153,7 +182,7 @@
>
{#each sample_row as { value, component }, j}
{@const component_name = components[j]}
{#if component_name !== undefined && component_map[component_name] !== undefined}
{#if component_name !== undefined && component_map.get(component_name) !== undefined}
<td
style="max-width: {component_name === 'textbox'
? '35ch'
Expand Down