Spaces:
Running
Running
added custom plot component
Browse files
app.py
CHANGED
@@ -5,6 +5,7 @@ import pickle
|
|
5 |
from prefixspan import PrefixSpan
|
6 |
import gradio as gr
|
7 |
import altair as alt
|
|
|
8 |
alt.data_transformers.enable("vegafusion")
|
9 |
# from dynabench.task_evaluator import *
|
10 |
|
@@ -1024,7 +1025,7 @@ def hide_fpm_and_dist_components(domain, partition, category):
|
|
1024 |
btn_pattern = gr.Button(value="Find patterns among tasks", visible=False)
|
1025 |
|
1026 |
table = gr.DataFrame({}, height=250, visible=False)
|
1027 |
-
dist_chart =
|
1028 |
|
1029 |
col_name = gr.Dropdown([], value=None, label="by task metadata", visible=False)
|
1030 |
btn_dist = gr.Button(value="Visualize task distribution", visible=False)
|
@@ -1041,7 +1042,7 @@ def hide_fpm_and_dist_components(domain, partition, category):
|
|
1041 |
btn_pattern = gr.Button(value="Find patterns among tasks", interactive=True, visible=True)
|
1042 |
|
1043 |
table = gr.DataFrame({}, height=250, interactive=True, visible=True)
|
1044 |
-
dist_chart =
|
1045 |
|
1046 |
btn_dist = gr.Button(value="Visualize task distribution", interactive=True, visible=True)
|
1047 |
return [num_patterns, btn_pattern, table, col_name, btn_dist, dist_chart]
|
@@ -1089,7 +1090,7 @@ with demo:
|
|
1089 |
category = gr.Dropdown([], value=None, label="task metadata")
|
1090 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=category)
|
1091 |
with gr.Row():
|
1092 |
-
output =
|
1093 |
with gr.Row():
|
1094 |
btn = gr.Button(value="Plot")
|
1095 |
btn.click(plot_task_distribution, [domain, partition, category], output)
|
@@ -1110,7 +1111,7 @@ with demo:
|
|
1110 |
category1.change(fn=update_category2, inputs=[domain, partition, category1], outputs=category2)
|
1111 |
domain.change(fn=update_partition_and_models, inputs=domain, outputs=[partition, models])
|
1112 |
with gr.Row():
|
1113 |
-
output =
|
1114 |
with gr.Row():
|
1115 |
btn = gr.Button(value="Plot")
|
1116 |
btn.click(plot_all, [domain, partition, models, category1, category2, aggregate], output)
|
@@ -1130,7 +1131,7 @@ with demo:
|
|
1130 |
partition2.change(fn=update_category, inputs=[domain2, partition2], outputs=category2)
|
1131 |
|
1132 |
with gr.Row():
|
1133 |
-
output2 =
|
1134 |
with gr.Row():
|
1135 |
btn = gr.Button(value="Run")
|
1136 |
btn.click(plot_embedding, [domain2, partition2, category2], output2)
|
@@ -1201,7 +1202,7 @@ with demo:
|
|
1201 |
btn.click(select_tasks, [domain, partition, category, query_type, aggregate, model, model_aggregate, rank, k, direction, threshold, baseline, baseline_aggregate], df)
|
1202 |
|
1203 |
with gr.Row():
|
1204 |
-
plot =
|
1205 |
with gr.Row():
|
1206 |
col_name2 = gr.Dropdown([], value=None, label="by task metadata", interactive=True)
|
1207 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=col_name2)
|
@@ -1209,7 +1210,7 @@ with demo:
|
|
1209 |
btn_plot.click(plot_performance_for_selected_tasks, [domain, partition, df, query_type, model, baseline, category, col_name2, aggregate, model_aggregate, baseline_aggregate, rank, direction, threshold], plot)
|
1210 |
|
1211 |
with gr.Row():
|
1212 |
-
dist_chart =
|
1213 |
with gr.Row():
|
1214 |
col_name = gr.Dropdown([], value=None, label="by task metadata", interactive=True)
|
1215 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=col_name)
|
@@ -1241,7 +1242,7 @@ with demo:
|
|
1241 |
domain3.change(fn=update_partition_and_models, inputs=domain3, outputs=[partition3, model3])
|
1242 |
# partition3.change(fn=update_k, inputs=[domain3, partition3], outputs=k3)
|
1243 |
with gr.Row():
|
1244 |
-
output3 =
|
1245 |
with gr.Row():
|
1246 |
btn = gr.Button(value="Plot")
|
1247 |
btn.click(plot_surprisingness, [domain3, partition3, model3, rank3, k3, num_neighbors], output3)
|
|
|
5 |
from prefixspan import PrefixSpan
|
6 |
import gradio as gr
|
7 |
import altair as alt
|
8 |
+
from plot import Plot
|
9 |
alt.data_transformers.enable("vegafusion")
|
10 |
# from dynabench.task_evaluator import *
|
11 |
|
|
|
1025 |
btn_pattern = gr.Button(value="Find patterns among tasks", visible=False)
|
1026 |
|
1027 |
table = gr.DataFrame({}, height=250, visible=False)
|
1028 |
+
dist_chart = Plot(visible=False)
|
1029 |
|
1030 |
col_name = gr.Dropdown([], value=None, label="by task metadata", visible=False)
|
1031 |
btn_dist = gr.Button(value="Visualize task distribution", visible=False)
|
|
|
1042 |
btn_pattern = gr.Button(value="Find patterns among tasks", interactive=True, visible=True)
|
1043 |
|
1044 |
table = gr.DataFrame({}, height=250, interactive=True, visible=True)
|
1045 |
+
dist_chart = Plot(visible=True)
|
1046 |
|
1047 |
btn_dist = gr.Button(value="Visualize task distribution", interactive=True, visible=True)
|
1048 |
return [num_patterns, btn_pattern, table, col_name, btn_dist, dist_chart]
|
|
|
1090 |
category = gr.Dropdown([], value=None, label="task metadata")
|
1091 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=category)
|
1092 |
with gr.Row():
|
1093 |
+
output = Plot()
|
1094 |
with gr.Row():
|
1095 |
btn = gr.Button(value="Plot")
|
1096 |
btn.click(plot_task_distribution, [domain, partition, category], output)
|
|
|
1111 |
category1.change(fn=update_category2, inputs=[domain, partition, category1], outputs=category2)
|
1112 |
domain.change(fn=update_partition_and_models, inputs=domain, outputs=[partition, models])
|
1113 |
with gr.Row():
|
1114 |
+
output = Plot()
|
1115 |
with gr.Row():
|
1116 |
btn = gr.Button(value="Plot")
|
1117 |
btn.click(plot_all, [domain, partition, models, category1, category2, aggregate], output)
|
|
|
1131 |
partition2.change(fn=update_category, inputs=[domain2, partition2], outputs=category2)
|
1132 |
|
1133 |
with gr.Row():
|
1134 |
+
output2 = Plot()
|
1135 |
with gr.Row():
|
1136 |
btn = gr.Button(value="Run")
|
1137 |
btn.click(plot_embedding, [domain2, partition2, category2], output2)
|
|
|
1202 |
btn.click(select_tasks, [domain, partition, category, query_type, aggregate, model, model_aggregate, rank, k, direction, threshold, baseline, baseline_aggregate], df)
|
1203 |
|
1204 |
with gr.Row():
|
1205 |
+
plot = Plot()
|
1206 |
with gr.Row():
|
1207 |
col_name2 = gr.Dropdown([], value=None, label="by task metadata", interactive=True)
|
1208 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=col_name2)
|
|
|
1210 |
btn_plot.click(plot_performance_for_selected_tasks, [domain, partition, df, query_type, model, baseline, category, col_name2, aggregate, model_aggregate, baseline_aggregate, rank, direction, threshold], plot)
|
1211 |
|
1212 |
with gr.Row():
|
1213 |
+
dist_chart = Plot()
|
1214 |
with gr.Row():
|
1215 |
col_name = gr.Dropdown([], value=None, label="by task metadata", interactive=True)
|
1216 |
partition.change(fn=update_category, inputs=[domain, partition], outputs=col_name)
|
|
|
1242 |
domain3.change(fn=update_partition_and_models, inputs=domain3, outputs=[partition3, model3])
|
1243 |
# partition3.change(fn=update_k, inputs=[domain3, partition3], outputs=k3)
|
1244 |
with gr.Row():
|
1245 |
+
output3 = Plot()
|
1246 |
with gr.Row():
|
1247 |
btn = gr.Button(value="Plot")
|
1248 |
btn.click(plot_surprisingness, [domain3, partition3, model3, rank3, k3, num_neighbors], output3)
|
plot.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""gr.Plot() component."""
|
2 |
+
|
3 |
+
from __future__ import annotations
|
4 |
+
|
5 |
+
import json
|
6 |
+
from types import ModuleType
|
7 |
+
from typing import Any, Literal
|
8 |
+
|
9 |
+
import altair as alt
|
10 |
+
from gradio_client.documentation import document
|
11 |
+
|
12 |
+
from gradio import processing_utils
|
13 |
+
from gradio.components.base import Component
|
14 |
+
from gradio.data_classes import GradioModel
|
15 |
+
from gradio.events import Events
|
16 |
+
|
17 |
+
|
18 |
+
class PlotData(GradioModel):
|
19 |
+
type: Literal["altair", "bokeh", "plotly", "matplotlib"]
|
20 |
+
plot: str
|
21 |
+
|
22 |
+
|
23 |
+
class AltairPlotData(PlotData):
|
24 |
+
chart: Literal["bar", "line", "scatter"]
|
25 |
+
type: Literal["altair"] = "altair"
|
26 |
+
|
27 |
+
|
28 |
+
@document()
|
29 |
+
class Plot(Component):
|
30 |
+
"""
|
31 |
+
Creates a plot component to display various kinds of plots (matplotlib, plotly, altair, or bokeh plots are supported). As this component does
|
32 |
+
not accept user input, it is rarely used as an input component.
|
33 |
+
|
34 |
+
Demos: altair_plot, outbreak_forecast, blocks_kinematics, stock_forecast, map_airbnb
|
35 |
+
Guides: plot-component-for-maps
|
36 |
+
"""
|
37 |
+
|
38 |
+
data_model = PlotData
|
39 |
+
EVENTS = [Events.change, Events.clear]
|
40 |
+
|
41 |
+
def __init__(
|
42 |
+
self,
|
43 |
+
value: Any | None = None,
|
44 |
+
*,
|
45 |
+
format: str = "png",
|
46 |
+
label: str | None = None,
|
47 |
+
every: float | None = None,
|
48 |
+
show_label: bool | None = None,
|
49 |
+
container: bool = True,
|
50 |
+
scale: int | None = None,
|
51 |
+
min_width: int = 160,
|
52 |
+
visible: bool = True,
|
53 |
+
elem_id: str | None = None,
|
54 |
+
elem_classes: list[str] | str | None = None,
|
55 |
+
render: bool = True,
|
56 |
+
):
|
57 |
+
"""
|
58 |
+
Parameters:
|
59 |
+
value: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
|
60 |
+
format: File format in which to send matplotlib plots to the front end, such as 'jpg' or 'png'.
|
61 |
+
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.
|
62 |
+
every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
|
63 |
+
show_label: if True, will display label.
|
64 |
+
container: If True, will place the component in a container - providing some extra padding around the border.
|
65 |
+
scale: 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.
|
66 |
+
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.
|
67 |
+
visible: If False, component will be hidden.
|
68 |
+
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.
|
69 |
+
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.
|
70 |
+
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.
|
71 |
+
"""
|
72 |
+
self.format = format
|
73 |
+
super().__init__(
|
74 |
+
label=label,
|
75 |
+
every=every,
|
76 |
+
show_label=show_label,
|
77 |
+
container=container,
|
78 |
+
scale=scale,
|
79 |
+
min_width=min_width,
|
80 |
+
visible=visible,
|
81 |
+
elem_id=elem_id,
|
82 |
+
elem_classes=elem_classes,
|
83 |
+
render=render,
|
84 |
+
value=value,
|
85 |
+
)
|
86 |
+
|
87 |
+
def get_config(self):
|
88 |
+
try:
|
89 |
+
import bokeh # type: ignore
|
90 |
+
|
91 |
+
bokeh_version = bokeh.__version__
|
92 |
+
except ImportError:
|
93 |
+
bokeh_version = None
|
94 |
+
|
95 |
+
config = super().get_config()
|
96 |
+
config["bokeh_version"] = bokeh_version
|
97 |
+
return config
|
98 |
+
|
99 |
+
def preprocess(self, payload: PlotData | None) -> PlotData | None:
|
100 |
+
"""
|
101 |
+
Parameters:
|
102 |
+
payload: The data to display in the plot.
|
103 |
+
Returns:
|
104 |
+
(Rarely used) passes the data displayed in the plot as an PlotData dataclass, which includes the plot information as a JSON string, as well as the type of chart and the plotting library.
|
105 |
+
"""
|
106 |
+
return payload
|
107 |
+
|
108 |
+
def example_payload(self) -> Any:
|
109 |
+
return None
|
110 |
+
|
111 |
+
def example_value(self) -> Any:
|
112 |
+
return None
|
113 |
+
|
114 |
+
def postprocess(self, value: Any) -> PlotData | None:
|
115 |
+
"""
|
116 |
+
Parameters:
|
117 |
+
value: Expects plot data in one of these formats: a matplotlib.Figure, bokeh.Model, plotly.Figure, or altair.Chart object.
|
118 |
+
Returns:
|
119 |
+
PlotData: A dataclass containing the plot data as a JSON string, as well as the type of chart and the plotting library.
|
120 |
+
"""
|
121 |
+
import matplotlib.figure
|
122 |
+
|
123 |
+
if value is None:
|
124 |
+
return None
|
125 |
+
if isinstance(value, (ModuleType, matplotlib.figure.Figure)): # type: ignore
|
126 |
+
dtype = "matplotlib"
|
127 |
+
out_y = processing_utils.encode_plot_to_base64(value, self.format)
|
128 |
+
elif "bokeh" in value.__module__:
|
129 |
+
dtype = "bokeh"
|
130 |
+
from bokeh.embed import json_item # type: ignore
|
131 |
+
|
132 |
+
out_y = json.dumps(json_item(value))
|
133 |
+
else:
|
134 |
+
is_altair = "altair" in value.__module__
|
135 |
+
dtype = "altair" if is_altair else "plotly"
|
136 |
+
out_y = value.to_json(format="vega")
|
137 |
+
return PlotData(type=dtype, plot=out_y)
|
138 |
+
|
139 |
+
|
140 |
+
class AltairPlot:
|
141 |
+
@staticmethod
|
142 |
+
def create_legend(position, title):
|
143 |
+
if position == "none":
|
144 |
+
legend = None
|
145 |
+
else:
|
146 |
+
position = {"orient": position} if position else {}
|
147 |
+
legend = {"title": title, **position}
|
148 |
+
|
149 |
+
return legend
|
150 |
+
|
151 |
+
@staticmethod
|
152 |
+
def create_scale(limit):
|
153 |
+
return alt.Scale(domain=limit) if limit else alt.Undefined
|
plot.pyi
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""gr.Plot() component."""
|
2 |
+
|
3 |
+
from __future__ import annotations
|
4 |
+
|
5 |
+
import json
|
6 |
+
from types import ModuleType
|
7 |
+
from typing import Any, Literal
|
8 |
+
|
9 |
+
import altair as alt
|
10 |
+
from gradio_client.documentation import document
|
11 |
+
|
12 |
+
from gradio import processing_utils
|
13 |
+
from gradio.components.base import Component
|
14 |
+
from gradio.data_classes import GradioModel
|
15 |
+
from gradio.events import Events
|
16 |
+
|
17 |
+
|
18 |
+
class PlotData(GradioModel):
|
19 |
+
type: Literal["altair", "bokeh", "plotly", "matplotlib"]
|
20 |
+
plot: str
|
21 |
+
|
22 |
+
|
23 |
+
class AltairPlotData(PlotData):
|
24 |
+
chart: Literal["bar", "line", "scatter"]
|
25 |
+
type: Literal["altair"] = "altair"
|
26 |
+
|
27 |
+
from gradio.events import Dependency
|
28 |
+
|
29 |
+
@document()
|
30 |
+
class Plot(Component):
|
31 |
+
"""
|
32 |
+
Creates a plot component to display various kinds of plots (matplotlib, plotly, altair, or bokeh plots are supported). As this component does
|
33 |
+
not accept user input, it is rarely used as an input component.
|
34 |
+
|
35 |
+
Demos: altair_plot, outbreak_forecast, blocks_kinematics, stock_forecast, map_airbnb
|
36 |
+
Guides: plot-component-for-maps
|
37 |
+
"""
|
38 |
+
|
39 |
+
data_model = PlotData
|
40 |
+
EVENTS = [Events.change, Events.clear]
|
41 |
+
|
42 |
+
def __init__(
|
43 |
+
self,
|
44 |
+
value: Any | None = None,
|
45 |
+
*,
|
46 |
+
format: str = "png",
|
47 |
+
label: str | None = None,
|
48 |
+
every: float | None = None,
|
49 |
+
show_label: bool | None = None,
|
50 |
+
container: bool = True,
|
51 |
+
scale: int | None = None,
|
52 |
+
min_width: int = 160,
|
53 |
+
visible: bool = True,
|
54 |
+
elem_id: str | None = None,
|
55 |
+
elem_classes: list[str] | str | None = None,
|
56 |
+
render: bool = True,
|
57 |
+
):
|
58 |
+
"""
|
59 |
+
Parameters:
|
60 |
+
value: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
|
61 |
+
format: File format in which to send matplotlib plots to the front end, such as 'jpg' or 'png'.
|
62 |
+
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.
|
63 |
+
every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
|
64 |
+
show_label: if True, will display label.
|
65 |
+
container: If True, will place the component in a container - providing some extra padding around the border.
|
66 |
+
scale: 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.
|
67 |
+
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.
|
68 |
+
visible: If False, component will be hidden.
|
69 |
+
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.
|
70 |
+
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.
|
71 |
+
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.
|
72 |
+
"""
|
73 |
+
self.format = format
|
74 |
+
super().__init__(
|
75 |
+
label=label,
|
76 |
+
every=every,
|
77 |
+
show_label=show_label,
|
78 |
+
container=container,
|
79 |
+
scale=scale,
|
80 |
+
min_width=min_width,
|
81 |
+
visible=visible,
|
82 |
+
elem_id=elem_id,
|
83 |
+
elem_classes=elem_classes,
|
84 |
+
render=render,
|
85 |
+
value=value,
|
86 |
+
)
|
87 |
+
|
88 |
+
def get_config(self):
|
89 |
+
try:
|
90 |
+
import bokeh # type: ignore
|
91 |
+
|
92 |
+
bokeh_version = bokeh.__version__
|
93 |
+
except ImportError:
|
94 |
+
bokeh_version = None
|
95 |
+
|
96 |
+
config = super().get_config()
|
97 |
+
config["bokeh_version"] = bokeh_version
|
98 |
+
return config
|
99 |
+
|
100 |
+
def preprocess(self, payload: PlotData | None) -> PlotData | None:
|
101 |
+
"""
|
102 |
+
Parameters:
|
103 |
+
payload: The data to display in the plot.
|
104 |
+
Returns:
|
105 |
+
(Rarely used) passes the data displayed in the plot as an PlotData dataclass, which includes the plot information as a JSON string, as well as the type of chart and the plotting library.
|
106 |
+
"""
|
107 |
+
return payload
|
108 |
+
|
109 |
+
def example_payload(self) -> Any:
|
110 |
+
return None
|
111 |
+
|
112 |
+
def example_value(self) -> Any:
|
113 |
+
return None
|
114 |
+
|
115 |
+
def postprocess(self, value: Any) -> PlotData | None:
|
116 |
+
"""
|
117 |
+
Parameters:
|
118 |
+
value: Expects plot data in one of these formats: a matplotlib.Figure, bokeh.Model, plotly.Figure, or altair.Chart object.
|
119 |
+
Returns:
|
120 |
+
PlotData: A dataclass containing the plot data as a JSON string, as well as the type of chart and the plotting library.
|
121 |
+
"""
|
122 |
+
import matplotlib.figure
|
123 |
+
|
124 |
+
if value is None:
|
125 |
+
return None
|
126 |
+
if isinstance(value, (ModuleType, matplotlib.figure.Figure)): # type: ignore
|
127 |
+
dtype = "matplotlib"
|
128 |
+
out_y = processing_utils.encode_plot_to_base64(value, self.format)
|
129 |
+
elif "bokeh" in value.__module__:
|
130 |
+
dtype = "bokeh"
|
131 |
+
from bokeh.embed import json_item # type: ignore
|
132 |
+
|
133 |
+
out_y = json.dumps(json_item(value))
|
134 |
+
else:
|
135 |
+
is_altair = "altair" in value.__module__
|
136 |
+
dtype = "altair" if is_altair else "plotly"
|
137 |
+
out_y = value.to_json(format="vega")
|
138 |
+
return PlotData(type=dtype, plot=out_y)
|
139 |
+
|
140 |
+
|
141 |
+
def change(self,
|
142 |
+
fn: Callable | None,
|
143 |
+
inputs: Component | Sequence[Component] | set[Component] | None = None,
|
144 |
+
outputs: Component | Sequence[Component] | None = None,
|
145 |
+
api_name: str | None | Literal[False] = None,
|
146 |
+
scroll_to_output: bool = False,
|
147 |
+
show_progress: Literal["full", "minimal", "hidden"] = "full",
|
148 |
+
queue: bool | None = None,
|
149 |
+
batch: bool = False,
|
150 |
+
max_batch_size: int = 4,
|
151 |
+
preprocess: bool = True,
|
152 |
+
postprocess: bool = True,
|
153 |
+
cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
|
154 |
+
every: float | None = None,
|
155 |
+
trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
|
156 |
+
js: str | None = None,
|
157 |
+
concurrency_limit: int | None | Literal["default"] = "default",
|
158 |
+
concurrency_id: str | None = None,
|
159 |
+
show_api: bool = True) -> Dependency:
|
160 |
+
"""
|
161 |
+
Parameters:
|
162 |
+
fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
|
163 |
+
inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
|
164 |
+
outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
|
165 |
+
api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
|
166 |
+
scroll_to_output: If True, will scroll to output component on completion
|
167 |
+
show_progress: If True, will show progress animation while pending
|
168 |
+
queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
|
169 |
+
batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
|
170 |
+
max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
|
171 |
+
preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
|
172 |
+
postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
|
173 |
+
cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
|
174 |
+
every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds.
|
175 |
+
trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
|
176 |
+
js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
|
177 |
+
concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
|
178 |
+
concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
|
179 |
+
show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps to use this event. If fn is None, show_api will automatically be set to False.
|
180 |
+
"""
|
181 |
+
...
|
182 |
+
|
183 |
+
def clear(self,
|
184 |
+
fn: Callable | None,
|
185 |
+
inputs: Component | Sequence[Component] | set[Component] | None = None,
|
186 |
+
outputs: Component | Sequence[Component] | None = None,
|
187 |
+
api_name: str | None | Literal[False] = None,
|
188 |
+
scroll_to_output: bool = False,
|
189 |
+
show_progress: Literal["full", "minimal", "hidden"] = "full",
|
190 |
+
queue: bool | None = None,
|
191 |
+
batch: bool = False,
|
192 |
+
max_batch_size: int = 4,
|
193 |
+
preprocess: bool = True,
|
194 |
+
postprocess: bool = True,
|
195 |
+
cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
|
196 |
+
every: float | None = None,
|
197 |
+
trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
|
198 |
+
js: str | None = None,
|
199 |
+
concurrency_limit: int | None | Literal["default"] = "default",
|
200 |
+
concurrency_id: str | None = None,
|
201 |
+
show_api: bool = True) -> Dependency:
|
202 |
+
"""
|
203 |
+
Parameters:
|
204 |
+
fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
|
205 |
+
inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
|
206 |
+
outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
|
207 |
+
api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
|
208 |
+
scroll_to_output: If True, will scroll to output component on completion
|
209 |
+
show_progress: If True, will show progress animation while pending
|
210 |
+
queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
|
211 |
+
batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
|
212 |
+
max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
|
213 |
+
preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
|
214 |
+
postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
|
215 |
+
cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
|
216 |
+
every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds.
|
217 |
+
trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
|
218 |
+
js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
|
219 |
+
concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
|
220 |
+
concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
|
221 |
+
show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps to use this event. If fn is None, show_api will automatically be set to False.
|
222 |
+
"""
|
223 |
+
...
|
224 |
+
|
225 |
+
|
226 |
+
class AltairPlot:
|
227 |
+
@staticmethod
|
228 |
+
def create_legend(position, title):
|
229 |
+
if position == "none":
|
230 |
+
legend = None
|
231 |
+
else:
|
232 |
+
position = {"orient": position} if position else {}
|
233 |
+
legend = {"title": title, **position}
|
234 |
+
|
235 |
+
return legend
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def create_scale(limit):
|
239 |
+
return alt.Scale(domain=limit) if limit else alt.Undefined
|