gradio-pr-bot commited on
Commit
27aaa45
·
verified ·
1 Parent(s): f36d715

Commit 2: Add 33 file(s)

Browse files
demos/kitchen_sink_random/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ matplotlib
2
+ pandas
demos/kitchen_sink_random/run.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from datetime import datetime
3
+ import random
4
+ import string
5
+ import pandas as pd
6
+
7
+ # get_audio(), get_video(), get_image(), get_model3d(), get_file() return file paths to sample media included with Gradio
8
+ from gradio.media import get_audio, get_video, get_image, get_model3d, get_file
9
+
10
+ from constants import ( # type: ignore
11
+ highlighted_text,
12
+ highlighted_text_output_2,
13
+ highlighted_text_output_1,
14
+ random_plot,
15
+ )
16
+
17
+ demo = gr.Interface(
18
+ lambda *args: args[0],
19
+ inputs=[
20
+ gr.Textbox(value=lambda: datetime.now(), label="Current Time"),
21
+ gr.Number(value=lambda: random.random(), label="Ranom Percentage"),
22
+ gr.Slider(minimum=-1, maximum=1, randomize=True, label="Slider with randomize"),
23
+ gr.Slider(
24
+ minimum=0,
25
+ maximum=1,
26
+ value=lambda: random.random(),
27
+ label="Slider with value func",
28
+ ),
29
+ gr.Checkbox(value=lambda: random.random() > 0.5, label="Random Checkbox"),
30
+ gr.CheckboxGroup(
31
+ choices=["a", "b", "c", "d"],
32
+ value=lambda: random.choice(["a", "b", "c", "d"]),
33
+ label="Random CheckboxGroup",
34
+ ),
35
+ gr.Radio(
36
+ choices=list(string.ascii_lowercase),
37
+ value=lambda: random.choice(string.ascii_lowercase),
38
+ ),
39
+ gr.Dropdown(
40
+ choices=["a", "b", "c", "d", "e"],
41
+ value=lambda: random.choice(["a", "b", "c"]),
42
+ ),
43
+ gr.Image(
44
+ value=lambda: get_image()
45
+ ),
46
+ gr.Video(value=lambda: get_video("world.mp4")),
47
+ gr.Audio(value=lambda: get_audio("cantina.wav")),
48
+ gr.File(
49
+ value=lambda: get_file("titanic.csv")
50
+ ),
51
+ gr.Dataframe(
52
+ value=lambda: pd.DataFrame(
53
+ {"random_number_rows": range(random.randint(0, 10))}
54
+ )
55
+ ),
56
+ gr.State(value=lambda: random.choice(string.ascii_lowercase)),
57
+ gr.ColorPicker(value=lambda: random.choice(["#000000", "#ff0000", "#0000FF"])),
58
+ gr.Label(value=lambda: random.choice(["Pedestrian", "Car", "Cyclist"])),
59
+ gr.HighlightedText(
60
+ value=lambda: random.choice(
61
+ [
62
+ {"text": highlighted_text, "entities": highlighted_text_output_1},
63
+ {"text": highlighted_text, "entities": highlighted_text_output_2},
64
+ ]
65
+ ),
66
+ ),
67
+ gr.JSON(value=lambda: random.choice([{"a": 1}, {"b": 2}])),
68
+ gr.HTML(
69
+ value=lambda: random.choice(
70
+ [
71
+ '<p style="color:red;">I am red</p>',
72
+ '<p style="color:blue;">I am blue</p>',
73
+ ]
74
+ )
75
+ ),
76
+ gr.Gallery(
77
+ value=lambda: [get_image() for _ in range(3)]
78
+ ),
79
+ gr.Chatbot(
80
+ value=lambda: random.choice(
81
+ [
82
+ [
83
+ {"role": "user", "content": "hello"},
84
+ {"role": "assistant", "content": "hi!"},
85
+ ],
86
+ [
87
+ {"role": "user", "content": "bye"},
88
+ {"role": "assistant", "content": "goodbye!"},
89
+ ],
90
+ ]
91
+ )
92
+ ),
93
+ gr.Model3D(value=lambda: get_model3d()),
94
+ gr.Plot(value=random_plot),
95
+ gr.Markdown(value=lambda: f"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}"),
96
+ ],
97
+ outputs=[
98
+ gr.State(value=lambda: random.choice(string.ascii_lowercase))
99
+ ],
100
+ api_name="predict",
101
+ )
102
+
103
+ if __name__ == "__main__":
104
+ demo.launch()
demos/login_with_huggingface/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ huggingface_hub
demos/login_with_huggingface/run.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gradio as gr
4
+ from huggingface_hub import whoami
5
+
6
+ def hello(profile: gr.OAuthProfile | None) -> str:
7
+ if profile is None:
8
+ return "I don't know you."
9
+ return f"Hello {profile.name}"
10
+
11
+ def list_organizations(oauth_token: gr.OAuthToken | None) -> str:
12
+ if oauth_token is None:
13
+ return "Please deploy this on Spaces and log in to list organizations."
14
+ org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]]
15
+ return f"You belong to {', '.join(org_names)}."
16
+
17
+ with gr.Blocks() as demo:
18
+ gr.LoginButton()
19
+ m1 = gr.Markdown()
20
+ m2 = gr.Markdown()
21
+ demo.load(hello, inputs=None, outputs=m1)
22
+ demo.load(list_organizations, inputs=None, outputs=m2)
23
+
24
+ if __name__ == "__main__":
25
+ demo.launch()
demos/matrix_transpose/run.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import gradio as gr
4
+
5
+ def transpose(matrix):
6
+ return matrix.T
7
+
8
+ demo = gr.Interface(
9
+ transpose,
10
+ gr.Dataframe(type="numpy", datatype="number", row_count=5, column_count=3, buttons=["fullscreen"]),
11
+ "numpy",
12
+ examples=[
13
+ [np.zeros((30, 30)).tolist()],
14
+ [np.ones((2, 2)).tolist()],
15
+ [np.random.randint(0, 10, (3, 10)).tolist()],
16
+ [np.random.randint(0, 10, (10, 3)).tolist()],
17
+ [np.random.randint(0, 10, (10, 10)).tolist()],
18
+ ],
19
+ cache_examples=False,
20
+ api_name="predict"
21
+ )
22
+
23
+ if __name__ == "__main__":
24
+ demo.launch()
demos/matrix_transpose/screenshot.png ADDED
demos/mini_leaderboard/assets/__init__.py ADDED
File without changes
demos/mini_leaderboard/assets/custom_css.css ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Hides the final AutoEvalColumn */
2
+ #llm-benchmark-tab-table table td:last-child,
3
+ #llm-benchmark-tab-table table th:last-child {
4
+ display: none;
5
+ }
6
+
7
+ /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
8
+ table td:first-child,
9
+ table th:first-child {
10
+ max-width: 400px;
11
+ overflow: auto;
12
+ white-space: nowrap;
13
+ }
14
+
15
+ /* Full width space */
16
+ .gradio-container {
17
+ max-width: 95%!important;
18
+ }
19
+
20
+ /* Text style and margins */
21
+ .markdown-text {
22
+ font-size: 16px !important;
23
+ }
24
+
25
+ #models-to-add-text {
26
+ font-size: 18px !important;
27
+ }
28
+
29
+ #citation-button span {
30
+ font-size: 16px !important;
31
+ }
32
+
33
+ #citation-button textarea {
34
+ font-size: 16px !important;
35
+ }
36
+
37
+ #citation-button > label > button {
38
+ margin: 6px;
39
+ transform: scale(1.3);
40
+ }
41
+
42
+ #search-bar-table-box > div:first-child {
43
+ background: none;
44
+ border: none;
45
+ }
46
+
47
+ #search-bar {
48
+ padding: 0px;
49
+ }
50
+
51
+ .tab-buttons button {
52
+ font-size: 20px;
53
+ }
54
+
55
+ /* Filters style */
56
+ #filter_type{
57
+ border: 0;
58
+ padding-left: 0;
59
+ padding-top: 0;
60
+ }
61
+ #filter_type label {
62
+ display: flex;
63
+ }
64
+ #filter_type label > span{
65
+ margin-top: var(--spacing-lg);
66
+ margin-right: 0.5em;
67
+ }
68
+ #filter_type label > .wrap{
69
+ width: 103px;
70
+ }
71
+ #filter_type label > .wrap .wrap-inner{
72
+ padding: 2px;
73
+ }
74
+ #filter_type label > .wrap .wrap-inner input{
75
+ width: 1px
76
+ }
77
+ #filter-columns-type{
78
+ border:0;
79
+ padding:0.5;
80
+ }
81
+ #filter-columns-size{
82
+ border:0;
83
+ padding:0.5;
84
+ }
85
+ #box-filter > .form{
86
+ border: 0
87
+ }
demos/mini_leaderboard/assets/leaderboard_data.json ADDED
The diff for this file is too large to render. See raw diff
 
demos/mini_leaderboard/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pandas
demos/mini_leaderboard/run.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # type: ignore
2
+ import gradio as gr
3
+ import pandas as pd
4
+ from pathlib import Path
5
+
6
+ abs_path = Path(__file__).parent.absolute()
7
+
8
+ df = pd.read_json(str(abs_path / "assets/leaderboard_data.json"))
9
+ invisible_df = df.copy()
10
+
11
+ COLS = [
12
+ "T",
13
+ "Model",
14
+ "Average ⬆️",
15
+ "ARC",
16
+ "HellaSwag",
17
+ "MMLU",
18
+ "TruthfulQA",
19
+ "Winogrande",
20
+ "GSM8K",
21
+ "Type",
22
+ "Architecture",
23
+ "Precision",
24
+ "Merged",
25
+ "Hub License",
26
+ "#Params (B)",
27
+ "Hub ❤️",
28
+ "Model sha",
29
+ "model_name_for_query",
30
+ ]
31
+ ON_LOAD_COLS = [
32
+ "T",
33
+ "Model",
34
+ "Average ⬆️",
35
+ "ARC",
36
+ "HellaSwag",
37
+ "MMLU",
38
+ "TruthfulQA",
39
+ "Winogrande",
40
+ "GSM8K",
41
+ "model_name_for_query",
42
+ ]
43
+ TYPES = [
44
+ "str",
45
+ "markdown",
46
+ "number",
47
+ "number",
48
+ "number",
49
+ "number",
50
+ "number",
51
+ "number",
52
+ "number",
53
+ "str",
54
+ "str",
55
+ "str",
56
+ "str",
57
+ "bool",
58
+ "str",
59
+ "number",
60
+ "number",
61
+ "bool",
62
+ "str",
63
+ "bool",
64
+ "bool",
65
+ "str",
66
+ ]
67
+ NUMERIC_INTERVALS = {
68
+ "?": pd.Interval(-1, 0, closed="right"),
69
+ "~1.5": pd.Interval(0, 2, closed="right"),
70
+ "~3": pd.Interval(2, 4, closed="right"),
71
+ "~7": pd.Interval(4, 9, closed="right"),
72
+ "~13": pd.Interval(9, 20, closed="right"),
73
+ "~35": pd.Interval(20, 45, closed="right"),
74
+ "~60": pd.Interval(45, 70, closed="right"),
75
+ "70+": pd.Interval(70, 10000, closed="right"),
76
+ }
77
+ MODEL_TYPE = [str(s) for s in df["T"].unique()]
78
+ Precision = [str(s) for s in df["Precision"].unique()]
79
+
80
+ # Searching and filtering
81
+ def update_table(
82
+ hidden_df: pd.DataFrame,
83
+ columns: list,
84
+ type_query: list,
85
+ precision_query: str,
86
+ size_query: list,
87
+ query: str,
88
+ ):
89
+ filtered_df = filter_models(hidden_df, type_query, size_query, precision_query) # type: ignore
90
+ filtered_df = filter_queries(query, filtered_df)
91
+ df = select_columns(filtered_df, columns)
92
+ return df
93
+
94
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
95
+ return df[(df["model_name_for_query"].str.contains(query, case=False))] # type: ignore
96
+
97
+ def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
98
+ # We use COLS to maintain sorting
99
+ filtered_df = df[[c for c in COLS if c in df.columns and c in columns]]
100
+ return filtered_df # type: ignore
101
+
102
+ def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
103
+ final_df = []
104
+ if query != "":
105
+ queries = [q.strip() for q in query.split(";")]
106
+ for _q in queries:
107
+ _q = _q.strip()
108
+ if _q != "":
109
+ temp_filtered_df = search_table(filtered_df, _q)
110
+ if len(temp_filtered_df) > 0:
111
+ final_df.append(temp_filtered_df)
112
+ if len(final_df) > 0:
113
+ filtered_df = pd.concat(final_df)
114
+ filtered_df = filtered_df.drop_duplicates( # type: ignore
115
+ subset=["Model", "Precision", "Model sha"]
116
+ )
117
+
118
+ return filtered_df
119
+
120
+ def filter_models(
121
+ df: pd.DataFrame,
122
+ type_query: list,
123
+ size_query: list,
124
+ precision_query: list,
125
+ ) -> pd.DataFrame:
126
+ # Show all models
127
+ filtered_df = df
128
+
129
+ type_emoji = [t[0] for t in type_query]
130
+ filtered_df = filtered_df.loc[df["T"].isin(type_emoji)]
131
+ filtered_df = filtered_df.loc[df["Precision"].isin(precision_query + ["None"])]
132
+
133
+ numeric_interval = pd.IntervalIndex(
134
+ sorted([NUMERIC_INTERVALS[s] for s in size_query]) # type: ignore
135
+ )
136
+ params_column = pd.to_numeric(df["#Params (B)"], errors="coerce")
137
+ mask = params_column.apply(lambda x: any(numeric_interval.contains(x))) # type: ignore
138
+ filtered_df = filtered_df.loc[mask]
139
+
140
+ return filtered_df
141
+
142
+ demo = gr.Blocks()
143
+ with demo:
144
+ gr.Markdown("""Test Space of the LLM Leaderboard""", elem_classes="markdown-text")
145
+
146
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
147
+ with gr.TabItem("🏅 LLM Benchmark", elem_id="llm-benchmark-tab-table", id=0):
148
+ with gr.Row():
149
+ with gr.Column():
150
+ with gr.Row():
151
+ search_bar = gr.Textbox(
152
+ placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
153
+ show_label=False,
154
+ elem_id="search-bar",
155
+ )
156
+ with gr.Row():
157
+ shown_columns = gr.CheckboxGroup(
158
+ choices=COLS,
159
+ value=ON_LOAD_COLS,
160
+ label="Select columns to show",
161
+ elem_id="column-select",
162
+ interactive=True,
163
+ )
164
+ with gr.Column(min_width=320):
165
+ filter_columns_type = gr.CheckboxGroup(
166
+ label="Model types",
167
+ choices=MODEL_TYPE,
168
+ value=MODEL_TYPE,
169
+ interactive=True,
170
+ elem_id="filter-columns-type",
171
+ )
172
+ filter_columns_precision = gr.CheckboxGroup(
173
+ label="Precision",
174
+ choices=Precision,
175
+ value=Precision,
176
+ interactive=True,
177
+ elem_id="filter-columns-precision",
178
+ )
179
+ filter_columns_size = gr.CheckboxGroup(
180
+ label="Model sizes (in billions of parameters)",
181
+ choices=list(NUMERIC_INTERVALS.keys()),
182
+ value=list(NUMERIC_INTERVALS.keys()),
183
+ interactive=True,
184
+ elem_id="filter-columns-size",
185
+ )
186
+
187
+ leaderboard_table = gr.components.Dataframe(
188
+ value=df[ON_LOAD_COLS], # type: ignore
189
+ headers=ON_LOAD_COLS,
190
+ datatype=TYPES,
191
+ elem_id="leaderboard-table",
192
+ interactive=False,
193
+ visible=True,
194
+ column_widths=["2%", "33%"],
195
+ )
196
+
197
+ # Dummy leaderboard for handling the case when the user uses backspace key
198
+ hidden_leaderboard_table_for_search = gr.components.Dataframe(
199
+ value=invisible_df[COLS], # type: ignore
200
+ headers=COLS,
201
+ datatype=TYPES,
202
+ visible=False,
203
+ )
204
+ search_bar.submit(
205
+ update_table,
206
+ [
207
+ hidden_leaderboard_table_for_search,
208
+ shown_columns,
209
+ filter_columns_type,
210
+ filter_columns_precision,
211
+ filter_columns_size,
212
+ search_bar,
213
+ ],
214
+ leaderboard_table,
215
+ )
216
+ for selector in [
217
+ shown_columns,
218
+ filter_columns_type,
219
+ filter_columns_precision,
220
+ filter_columns_size,
221
+ ]:
222
+ selector.change(
223
+ update_table,
224
+ [
225
+ hidden_leaderboard_table_for_search,
226
+ shown_columns,
227
+ filter_columns_type,
228
+ filter_columns_precision,
229
+ filter_columns_size,
230
+ search_bar,
231
+ ],
232
+ leaderboard_table,
233
+ queue=True,
234
+ )
235
+
236
+ if __name__ == "__main__":
237
+ demo.queue(default_concurrency_limit=40).launch(css=str(abs_path / "assets/custom_css.css"))
demos/model3D/run.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ # get_model3d() returns the file path to sample 3D models included with Gradio
3
+ from gradio.media import get_model3d, MEDIA_ROOT
4
+
5
+
6
+ def load_mesh(mesh_file_name):
7
+ return mesh_file_name
8
+
9
+
10
+ demo = gr.Interface(
11
+ fn=load_mesh,
12
+ inputs=gr.Model3D(label="Other name", display_mode="wireframe"),
13
+ outputs=gr.Model3D(
14
+ clear_color=(0.0, 0.0, 0.0, 0.0), label="3D Model", display_mode="wireframe"
15
+ ),
16
+ examples=[
17
+ [get_model3d("Bunny.obj")],
18
+ [get_model3d("Duck.glb")],
19
+ [get_model3d("Fox.gltf")],
20
+ [get_model3d("face.obj")],
21
+ [get_model3d("sofia.stl")],
22
+ [
23
+ "https://huggingface.co/datasets/dylanebert/3dgs/resolve/main/bonsai/bonsai-7k-mini.splat"
24
+ ],
25
+ [
26
+ "https://huggingface.co/datasets/dylanebert/3dgs/resolve/main/luigi/luigi.ply"
27
+ ],
28
+ ],
29
+ cache_examples=True,
30
+ api_name="predict",
31
+ )
32
+
33
+ if __name__ == "__main__":
34
+ demo.launch(allowed_paths=[str(MEDIA_ROOT)])
demos/native_plots/bar_plot_demo.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from data import temp_sensor_data, food_rating_data # type: ignore
3
+
4
+ with gr.Blocks() as bar_plots:
5
+ with gr.Row():
6
+ start = gr.DateTime("2021-01-01 00:00:00", label="Start")
7
+ end = gr.DateTime("2021-01-05 00:00:00", label="End")
8
+ apply_btn = gr.Button("Apply", scale=0)
9
+ with gr.Row():
10
+ group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Group by")
11
+ aggregate = gr.Radio(["sum", "mean", "median", "min", "max"], value="sum", label="Aggregation")
12
+
13
+ with gr.Draggable():
14
+ temp_by_time = gr.BarPlot(
15
+ temp_sensor_data,
16
+ x="time",
17
+ y="temperature",
18
+ buttons=["export"],
19
+ )
20
+ temp_by_time_location = gr.BarPlot(
21
+ temp_sensor_data,
22
+ x="time",
23
+ y="temperature",
24
+ color="location",
25
+ buttons=["export"],
26
+ )
27
+
28
+ time_graphs = [temp_by_time, temp_by_time_location]
29
+ group_by.change(
30
+ lambda group: [gr.BarPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
31
+ group_by,
32
+ time_graphs
33
+ )
34
+ aggregate.change(
35
+ lambda aggregate: [gr.BarPlot(y_aggregate=aggregate)] * len(time_graphs),
36
+ aggregate,
37
+ time_graphs
38
+ )
39
+
40
+ def rescale(select: gr.SelectData):
41
+ return select.index
42
+ rescale_evt = gr.on([plot.select for plot in time_graphs], rescale, None, [start, end])
43
+
44
+ for trigger in [apply_btn.click, rescale_evt.then]:
45
+ trigger(
46
+ lambda start, end: [gr.BarPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
47
+ )
48
+
49
+ with gr.Row():
50
+ price_by_cuisine = gr.BarPlot(
51
+ food_rating_data,
52
+ x="cuisine",
53
+ y="price",
54
+ buttons=["export"],
55
+ )
56
+ with gr.Column(scale=0):
57
+ gr.Button("Sort $ > $$$").click(lambda: gr.BarPlot(sort="y"), None, price_by_cuisine)
58
+ gr.Button("Sort $$$ > $").click(lambda: gr.BarPlot(sort="-y"), None, price_by_cuisine)
59
+ gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian", "Mexican"]), None, price_by_cuisine)
60
+
61
+ with gr.Row():
62
+ price_by_rating = gr.BarPlot(
63
+ food_rating_data,
64
+ x="rating",
65
+ y="price",
66
+ x_bin=1,
67
+ buttons=["export"],
68
+ )
69
+ price_by_rating_color = gr.BarPlot(
70
+ food_rating_data,
71
+ x="rating",
72
+ y="price",
73
+ color="cuisine",
74
+ x_bin=1,
75
+ color_map={"Italian": "red", "Mexican": "green", "Chinese": "blue"},
76
+ buttons=["export"],
77
+ )
78
+
79
+ if __name__ == "__main__":
80
+ bar_plots.launch()
demos/native_plots/data.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from random import randint, random
3
+
4
+ temp_sensor_data = pd.DataFrame(
5
+ {
6
+ "time": pd.date_range("2021-01-01", end="2021-01-05", periods=200),
7
+ "temperature": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
8
+ "humidity": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
9
+ "location": ["indoor", "outdoor"] * 100,
10
+ }
11
+ )
12
+
13
+ food_rating_data = pd.DataFrame(
14
+ {
15
+ "cuisine": [["Italian", "Mexican", "Chinese"][i % 3] for i in range(100)],
16
+ "rating": [random() * 4 + 0.5 * (i % 3) for i in range(100)],
17
+ "price": [randint(10, 50) + 4 * (i % 3) for i in range(100)],
18
+ "wait": [random() for i in range(100)],
19
+ }
20
+ )
demos/native_plots/line_plot_demo.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from data import temp_sensor_data, food_rating_data # type: ignore
3
+
4
+ with gr.Blocks() as line_plots:
5
+ with gr.Row():
6
+ start = gr.DateTime("2021-01-01 00:00:00", label="Start")
7
+ end = gr.DateTime("2021-01-05 00:00:00", label="End")
8
+ apply_btn = gr.Button("Apply", scale=0)
9
+ with gr.Row():
10
+ group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Group by")
11
+ aggregate = gr.Radio(["sum", "mean", "median", "min", "max"], value="sum", label="Aggregation")
12
+
13
+ temp_by_time = gr.LinePlot(
14
+ temp_sensor_data,
15
+ x="time",
16
+ y="temperature",
17
+ buttons=["export"],
18
+ )
19
+ temp_by_time_location = gr.LinePlot(
20
+ temp_sensor_data,
21
+ x="time",
22
+ y="temperature",
23
+ color="location",
24
+ buttons=["export"],
25
+ )
26
+
27
+ time_graphs = [temp_by_time, temp_by_time_location]
28
+ group_by.change(
29
+ lambda group: [gr.LinePlot(x_bin=None if group == "None" else group)] * len(time_graphs),
30
+ group_by,
31
+ time_graphs
32
+ )
33
+ aggregate.change(
34
+ lambda aggregate: [gr.LinePlot(y_aggregate=aggregate)] * len(time_graphs),
35
+ aggregate,
36
+ time_graphs
37
+ )
38
+
39
+ def rescale(select: gr.SelectData):
40
+ return select.index
41
+ rescale_evt = gr.on([plot.select for plot in time_graphs], rescale, None, [start, end])
42
+
43
+ for trigger in [apply_btn.click, rescale_evt.then]:
44
+ trigger(
45
+ lambda start, end: [gr.LinePlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
46
+ )
47
+
48
+ price_by_cuisine = gr.LinePlot(
49
+ food_rating_data,
50
+ x="cuisine",
51
+ y="price",
52
+ buttons=["export"],
53
+ )
54
+ with gr.Row():
55
+ price_by_rating = gr.LinePlot(
56
+ food_rating_data,
57
+ title="Price by Rating (for Ratings >2)",
58
+ x="rating",
59
+ y="price",
60
+ x_lim=[2, None],
61
+ buttons=["export"],
62
+ )
63
+ price_by_rating_color = gr.LinePlot(
64
+ food_rating_data,
65
+ title="Price by Rating (for Ratings <4)",
66
+ x="rating",
67
+ y="price",
68
+ x_lim=[None, 4],
69
+ color="cuisine",
70
+ color_map={"Italian": "red", "Mexican": "green", "Chinese": "blue"},
71
+ buttons=["export"],
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ line_plots.launch()
demos/native_plots/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ vega_datasets
2
+ pandas
demos/native_plots/run.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from scatter_plot_demo import scatter_plots # type: ignore
4
+ from line_plot_demo import line_plots # type: ignore
5
+ from bar_plot_demo import bar_plots # type: ignore
6
+
7
+ with gr.Blocks() as demo:
8
+ with gr.Tabs():
9
+ with gr.TabItem("Line Plot"):
10
+ line_plots.render()
11
+ with gr.TabItem("Scatter Plot"):
12
+ scatter_plots.render()
13
+ with gr.TabItem("Bar Plot"):
14
+ bar_plots.render()
15
+
16
+ if __name__ == "__main__":
17
+ demo.launch()
demos/native_plots/scatter_plot_demo.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from data import temp_sensor_data, food_rating_data # type: ignore
3
+
4
+ with gr.Blocks() as scatter_plots:
5
+ with gr.Row():
6
+ start = gr.DateTime("2021-01-01 00:00:00", label="Start")
7
+ end = gr.DateTime("2021-01-05 00:00:00", label="End")
8
+ apply_btn = gr.Button("Apply", scale=0)
9
+ with gr.Row():
10
+ group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Group by")
11
+ aggregate = gr.Radio(["sum", "mean", "median", "min", "max"], value="sum", label="Aggregation")
12
+
13
+ temp_by_time = gr.ScatterPlot(
14
+ temp_sensor_data,
15
+ x="time",
16
+ y="temperature",
17
+ buttons=["export"],
18
+ )
19
+ temp_by_time_location = gr.ScatterPlot(
20
+ temp_sensor_data,
21
+ x="time",
22
+ y="temperature",
23
+ color="location",
24
+ buttons=["export"],
25
+ )
26
+
27
+ time_graphs = [temp_by_time, temp_by_time_location]
28
+ group_by.change(
29
+ lambda group: [gr.ScatterPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
30
+ group_by,
31
+ time_graphs
32
+ )
33
+ aggregate.change(
34
+ lambda aggregate: [gr.ScatterPlot(y_aggregate=aggregate)] * len(time_graphs),
35
+ aggregate,
36
+ time_graphs
37
+ )
38
+
39
+ # def rescale(select: gr.SelectData):
40
+ # return select.index
41
+ # rescale_evt = gr.on([plot.select for plot in time_graphs], rescale, None, [start, end])
42
+
43
+ # for trigger in [apply_btn.click, rescale_evt.then]:
44
+ # trigger(
45
+ # lambda start, end: [gr.ScatterPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
46
+ # )
47
+
48
+ price_by_cuisine = gr.ScatterPlot(
49
+ food_rating_data,
50
+ x="cuisine",
51
+ y="price",
52
+ buttons=["export"],
53
+ )
54
+ with gr.Row():
55
+ price_by_rating = gr.ScatterPlot(
56
+ food_rating_data,
57
+ x="rating",
58
+ y="price",
59
+ color="wait",
60
+ buttons=["actions", "export"], # type: ignore
61
+ )
62
+ price_by_rating_color = gr.ScatterPlot(
63
+ food_rating_data,
64
+ x="rating",
65
+ y="price",
66
+ color="cuisine",
67
+ buttons=["export"],
68
+ )
69
+
70
+ if __name__ == "__main__":
71
+ scatter_plots.launch()
demos/reverse_audio/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ numpy
demos/reverse_audio/run.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+
4
+ import gradio as gr
5
+
6
+ def reverse_audio(audio):
7
+ sr, data = audio
8
+ return (sr, np.flipud(data))
9
+
10
+ input_audio = gr.Audio(
11
+ sources=["microphone"],
12
+ waveform_options=gr.WaveformOptions(
13
+ waveform_color="#01C6FF",
14
+ waveform_progress_color="#0066B4",
15
+ skip_length=2,
16
+ show_recording_waveform=False,
17
+ ),
18
+ )
19
+ demo = gr.Interface(
20
+ fn=reverse_audio,
21
+ inputs=input_audio,
22
+ outputs="audio",
23
+ api_name="predict",
24
+ )
25
+
26
+ if __name__ == "__main__":
27
+ demo.launch()
demos/reverse_audio/screenshot.png ADDED
demos/stream_audio/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ numpy
demos/stream_audio/run.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+
4
+ def add_to_stream(audio, instream):
5
+ if audio is None:
6
+ return gr.Audio(), instream
7
+ if instream is None:
8
+ ret = audio
9
+ else:
10
+ ret = (audio[0], np.concatenate((instream[1], audio[1])))
11
+ return ret, ret
12
+
13
+ with gr.Blocks() as demo:
14
+ inp = gr.Audio(sources=["microphone"])
15
+ out = gr.Audio()
16
+ stream = gr.State()
17
+ clear = gr.Button("Clear")
18
+
19
+ inp.stream(add_to_stream, [inp, stream], [out, stream])
20
+ clear.click(lambda: [None, None, None], None, [inp, out, stream])
21
+
22
+ if __name__ == "__main__":
23
+ demo.launch()
demos/stream_audio_out/run.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pydub import AudioSegment
3
+ from time import sleep
4
+ import os
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ with gr.Blocks() as demo:
9
+ input_audio = gr.Audio(label="Input Audio", type="filepath", format="mp3")
10
+ with gr.Row():
11
+ with gr.Column():
12
+ stream_as_file_btn = gr.Button("Stream as File")
13
+ format = gr.Radio(["wav", "mp3"], value="wav", label="Format")
14
+ stream_as_file_output = gr.Audio(streaming=True, elem_id="stream_as_file_output", autoplay=True, visible=False)
15
+
16
+ def stream_file(audio_file, format):
17
+ audio = AudioSegment.from_file(audio_file)
18
+ i = 0
19
+ chunk_size = 1000
20
+ while chunk_size * i < len(audio):
21
+ chunk = audio[chunk_size * i : chunk_size * (i + 1)]
22
+ i += 1
23
+ if chunk:
24
+ file = Path(tempfile.gettempdir()) / "stream_audio_demo" / f"{i}.{format}"
25
+ file.parent.mkdir(parents=True, exist_ok=True)
26
+ chunk.export(str(file), format=format)
27
+ yield file
28
+ sleep(0.5)
29
+
30
+ stream_as_file_btn.click(
31
+ stream_file, [input_audio, format], stream_as_file_output
32
+ )
33
+
34
+ gr.Examples(
35
+ [[gr.get_audio("cantina.wav"), "wav"],
36
+ [gr.get_audio("cantina.wav"), "mp3"]],
37
+ [input_audio, format],
38
+ fn=stream_file,
39
+ outputs=stream_as_file_output,
40
+ cache_examples=False,
41
+ )
42
+
43
+ with gr.Column():
44
+ stream_as_bytes_btn = gr.Button("Stream as Bytes")
45
+ stream_as_bytes_output = gr.Audio(streaming=True, elem_id="stream_as_bytes_output", autoplay=True)
46
+
47
+ def stream_bytes(audio_file):
48
+ chunk_size = 20_000
49
+ with open(audio_file, "rb") as f:
50
+ while True:
51
+ chunk = f.read(chunk_size)
52
+ if chunk:
53
+ yield chunk
54
+ sleep(1)
55
+ else:
56
+ break
57
+ stream_as_bytes_btn.click(stream_bytes, input_audio, stream_as_bytes_output)
58
+
59
+ if __name__ == "__main__":
60
+ demo.launch()
demos/stream_frames/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ numpy
demos/stream_frames/run.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+
4
+ def flip(im):
5
+ return np.flipud(im)
6
+
7
+ demo = gr.Interface(
8
+ flip,
9
+ gr.Image(sources=["webcam"], streaming=True),
10
+ "image",
11
+ live=True,
12
+ api_name="predict",
13
+ )
14
+ if __name__ == "__main__":
15
+ demo.launch()
demos/stt_or_tts/run.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ tts_examples = [
4
+ "I love learning machine learning",
5
+ "How do you do?",
6
+ ]
7
+
8
+ tts_demo = gr.load(
9
+ "huggingface/facebook/fastspeech2-en-ljspeech",
10
+ title=None,
11
+ examples=tts_examples,
12
+ description="Give me something to say!",
13
+ cache_examples=False
14
+ )
15
+
16
+ stt_demo = gr.load(
17
+ "huggingface/facebook/wav2vec2-base-960h",
18
+ title=None,
19
+ inputs=gr.Microphone(type="filepath"),
20
+ description="Let me try to guess what you're saying!",
21
+ cache_examples=False
22
+ )
23
+
24
+ demo = gr.TabbedInterface([tts_demo, stt_demo], ["Text-to-speech", "Speech-to-text"])
25
+
26
+ if __name__ == "__main__":
27
+ demo.launch()
demos/video_component/run.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ # get_video() returns the file path to sample videos included with Gradio
3
+ from gradio.media import get_video, MEDIA_PATHS
4
+
5
+ demo = gr.Interface(
6
+ fn=lambda x: x,
7
+ inputs=gr.Video(),
8
+ outputs=gr.Video(),
9
+ examples=[
10
+ [get_video("world.mp4")],
11
+ [get_video("a.mp4")],
12
+ [get_video("b.mp4")],
13
+ ],
14
+ api_name="predict",
15
+ cache_examples=True
16
+ )
17
+
18
+ if __name__ == "__main__":
19
+ demo.launch(allowed_paths=[str(p) for p in MEDIA_PATHS])
demos/zip_files/run.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from zipfile import ZipFile
2
+
3
+ import gradio as gr
4
+
5
+ def zip_files(files):
6
+ with ZipFile("tmp.zip", "w") as zip_obj:
7
+ for file in files:
8
+ zip_obj.write(file.name, file.name.split("/")[-1])
9
+ return "tmp.zip"
10
+
11
+ demo = gr.Interface(
12
+ zip_files,
13
+ gr.File(file_count="multiple", file_types=["text", ".json", ".csv"]),
14
+ "file",
15
+ examples=[[[gr.get_file("titanic.csv"),
16
+ gr.get_file("titanic.csv"),
17
+ gr.get_file("titanic.csv")]]],
18
+ cache_examples=True,
19
+ api_name="predict"
20
+ )
21
+
22
+ if __name__ == "__main__":
23
+ demo.launch()
demos/zip_files/screenshot.png ADDED
image.png ADDED
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio-client @ git+https://github.com/gradio-app/gradio@a3716939b6cdcab788a7a295bfa2abaaa87e2196#subdirectory=client/python
2
+ https://huggingface.co/buckets/gradio/pypi-previews/resolve/a3716939b6cdcab788a7a295bfa2abaaa87e2196/gradio-6.26.0-py3-none-any.whl
3
+ pypistats==1.1.0
4
+ plotly
5
+ matplotlib
6
+ altair
7
+ vega_datasets
run.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import gradio as gr
3
+ import os
4
+ import sys
5
+ import copy
6
+ import pathlib
7
+ from gradio.media import MEDIA_ROOT
8
+
9
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
10
+
11
+ demo_dir = pathlib.Path(__file__).parent / "demos"
12
+
13
+ names = sorted(os.listdir("./demos"))
14
+
15
+ all_demos = []
16
+ demo_module = None
17
+ for p in sorted(os.listdir("./demos")):
18
+ old_path = copy.deepcopy(sys.path)
19
+ sys.path = [os.path.join(demo_dir, p)] + sys.path
20
+ try: # Some demos may not be runnable because of 429 timeouts, etc.
21
+ if demo_module is None:
22
+ demo_module = importlib.import_module("run")
23
+ else:
24
+ demo_module = importlib.reload(demo_module)
25
+ all_demos.append((p, demo_module.demo, False)) # type: ignore
26
+ except Exception as e:
27
+ with gr.Blocks() as demo:
28
+ gr.Markdown(f"Error loading demo: {e}")
29
+ all_demos.append((p, demo, True))
30
+
31
+ app = gr.Blocks()
32
+
33
+ with app:
34
+ gr.Markdown("""
35
+ # Deployed Demos
36
+ ## Click through demos to test them out!
37
+ """)
38
+
39
+ for demo_name, demo, _ in all_demos:
40
+ with app.route(demo_name):
41
+ demo.render()
42
+
43
+ # app = gr.mount_gradio_app(app, demo, f"/demo/{demo_name}")
44
+
45
+ if __name__ == "__main__":
46
+ app.launch(allowed_paths=[str(MEDIA_ROOT)])