Spaces:
Runtime error
Runtime error
Commit
•
dc14111
1
Parent(s):
eb31339
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- README.md +4 -5
- app.py +35 -0
- demos/altair_plot/requirements.txt +2 -0
- demos/altair_plot/run.ipynb +1 -0
- demos/altair_plot/run.py +140 -0
- demos/audio_debugger/cantina.wav +0 -0
- demos/audio_debugger/run.ipynb +1 -0
- demos/audio_debugger/run.py +24 -0
- demos/blocks_essay/run.ipynb +1 -0
- demos/blocks_essay/run.py +35 -0
- demos/blocks_group/run.ipynb +1 -0
- demos/blocks_group/run.py +113 -0
- demos/blocks_js_methods/run.ipynb +1 -0
- demos/blocks_js_methods/run.py +41 -0
- demos/blocks_layout/run.ipynb +1 -0
- demos/blocks_layout/run.py +39 -0
- demos/blocks_mask/image.png +0 -0
- demos/blocks_mask/lion.jpg +0 -0
- demos/blocks_mask/lion.webp +0 -0
- demos/blocks_mask/run.ipynb +1 -0
- demos/blocks_mask/run.py +157 -0
- demos/blocks_multiple_event_triggers/requirements.txt +2 -0
- demos/blocks_multiple_event_triggers/run.ipynb +1 -0
- demos/blocks_multiple_event_triggers/run.py +39 -0
- demos/blocks_update/run.ipynb +1 -0
- demos/blocks_update/run.py +46 -0
- demos/calculator/examples/log.csv +0 -0
- demos/calculator/run.ipynb +1 -0
- demos/calculator/run.py +35 -0
- demos/calculator/screenshot.gif +3 -0
- demos/cancel_events/run.ipynb +1 -0
- demos/cancel_events/run.py +50 -0
- demos/chatbot_multimodal/avatar.png +0 -0
- demos/chatbot_multimodal/run.ipynb +1 -0
- demos/chatbot_multimodal/run.py +54 -0
- demos/chatinterface_streaming_echo/run.ipynb +1 -0
- demos/chatinterface_streaming_echo/run.py +12 -0
- demos/clear_components/__init__.py +0 -0
- demos/clear_components/run.ipynb +1 -0
- demos/clear_components/run.py +182 -0
- demos/code/file.css +11 -0
- demos/code/run.ipynb +1 -0
- demos/code/run.py +43 -0
- demos/fake_diffusion_with_gif/image.gif +3 -0
- demos/fake_diffusion_with_gif/run.ipynb +1 -0
- demos/fake_diffusion_with_gif/run.py +48 -0
- demos/fake_gan/DESCRIPTION.md +1 -0
- demos/fake_gan/files/cheetah1.jpg +0 -0
- demos/fake_gan/run.ipynb +1 -0
.gitattributes
CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
demos/calculator/screenshot.gif filter=lfs diff=lfs merge=lfs -text
|
37 |
+
demos/fake_diffusion_with_gif/image.gif filter=lfs diff=lfs merge=lfs -text
|
38 |
+
demos/kitchen_sink/files/world.mp4 filter=lfs diff=lfs merge=lfs -text
|
39 |
+
demos/video_component/files/world.mp4 filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,12 +1,11 @@
|
|
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
colorFrom: indigo
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
sdk_version: 3.45.1
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
+
|
2 |
---
|
3 |
+
title: pr-5717-all-demos
|
4 |
+
emoji: 💩
|
5 |
colorFrom: indigo
|
6 |
+
colorTo: indigo
|
7 |
sdk: gradio
|
8 |
sdk_version: 3.45.1
|
9 |
app_file: app.py
|
10 |
pinned: false
|
11 |
---
|
|
|
|
app.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
import gradio as gr
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
import copy
|
6 |
+
import pathlib
|
7 |
+
|
8 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
9 |
+
|
10 |
+
demo_dir = pathlib.Path(__file__).parent / "demos"
|
11 |
+
|
12 |
+
|
13 |
+
all_demos = []
|
14 |
+
demo_module = None
|
15 |
+
for p in sorted(os.listdir("./demos")):
|
16 |
+
old_path = copy.deepcopy(sys.path)
|
17 |
+
sys.path = [os.path.join(demo_dir, p)] + sys.path
|
18 |
+
try: # Some demos may not be runnable because of 429 timeouts, etc.
|
19 |
+
if demo_module is None:
|
20 |
+
demo_module = importlib.import_module(f"run")
|
21 |
+
else:
|
22 |
+
demo_module = importlib.reload(demo_module)
|
23 |
+
all_demos.append((p, demo_module.demo))
|
24 |
+
except Exception as e:
|
25 |
+
p = p + " ❌"
|
26 |
+
with gr.Blocks() as demo:
|
27 |
+
gr.Markdown(f"Error loading demo: {e}")
|
28 |
+
all_demos.append((p, demo))
|
29 |
+
|
30 |
+
with gr.Blocks() as mega_demo:
|
31 |
+
for demo_name, demo in all_demos:
|
32 |
+
with gr.Tab(demo_name):
|
33 |
+
demo.render()
|
34 |
+
|
35 |
+
mega_demo.queue().launch()
|
demos/altair_plot/requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
altair
|
2 |
+
vega_datasets
|
demos/altair_plot/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: altair_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio altair vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import altair as alt\n", "import gradio as gr\n", "import numpy as np\n", "import pandas as pd\n", "from vega_datasets import data\n", "\n", "\n", "def make_plot(plot_type):\n", " if plot_type == \"scatter_plot\":\n", " cars = data.cars()\n", " return alt.Chart(cars).mark_point().encode(\n", " x='Horsepower',\n", " y='Miles_per_Gallon',\n", " color='Origin',\n", " )\n", " elif plot_type == \"heatmap\":\n", " # Compute x^2 + y^2 across a 2D grid\n", " x, y = np.meshgrid(range(-5, 5), range(-5, 5))\n", " z = x ** 2 + y ** 2\n", "\n", " # Convert this grid to columnar data expected by Altair\n", " source = pd.DataFrame({'x': x.ravel(),\n", " 'y': y.ravel(),\n", " 'z': z.ravel()})\n", " return alt.Chart(source).mark_rect().encode(\n", " x='x:O',\n", " y='y:O',\n", " color='z:Q'\n", " )\n", " elif plot_type == \"us_map\":\n", " states = alt.topo_feature(data.us_10m.url, 'states')\n", " source = data.income.url\n", "\n", " return alt.Chart(source).mark_geoshape().encode(\n", " shape='geo:G',\n", " color='pct:Q',\n", " tooltip=['name:N', 'pct:Q'],\n", " facet=alt.Facet('group:N', columns=2),\n", " ).transform_lookup(\n", " lookup='id',\n", " from_=alt.LookupData(data=states, key='id'),\n", " as_='geo'\n", " ).properties(\n", " width=300,\n", " height=175,\n", " ).project(\n", " type='albersUsa'\n", " )\n", " elif plot_type == \"interactive_barplot\":\n", " source = data.movies.url\n", "\n", " pts = alt.selection(type=\"single\", encodings=['x'])\n", "\n", " rect = alt.Chart(data.movies.url).mark_rect().encode(\n", " alt.X('IMDB_Rating:Q', bin=True),\n", " alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),\n", " alt.Color('count()',\n", " scale=alt.Scale(scheme='greenblue'),\n", " legend=alt.Legend(title='Total Records')\n", " )\n", " )\n", "\n", " circ = rect.mark_point().encode(\n", " alt.ColorValue('grey'),\n", " alt.Size('count()',\n", " legend=alt.Legend(title='Records in Selection')\n", " )\n", " ).transform_filter(\n", " pts\n", " )\n", "\n", " bar = alt.Chart(source).mark_bar().encode(\n", " x='Major_Genre:N',\n", " y='count()',\n", " color=alt.condition(pts, alt.ColorValue(\"steelblue\"), alt.ColorValue(\"grey\"))\n", " ).properties(\n", " width=550,\n", " height=200\n", " ).add_selection(pts)\n", "\n", " plot = alt.vconcat(\n", " rect + circ,\n", " bar\n", " ).resolve_legend(\n", " color=\"independent\",\n", " size=\"independent\"\n", " )\n", " return plot\n", " elif plot_type == \"radial\":\n", " source = pd.DataFrame({\"values\": [12, 23, 47, 6, 52, 19]})\n", "\n", " base = alt.Chart(source).encode(\n", " theta=alt.Theta(\"values:Q\", stack=True),\n", " radius=alt.Radius(\"values\", scale=alt.Scale(type=\"sqrt\", zero=True, rangeMin=20)),\n", " color=\"values:N\",\n", " )\n", "\n", " c1 = base.mark_arc(innerRadius=20, stroke=\"#fff\")\n", "\n", " c2 = base.mark_text(radiusOffset=10).encode(text=\"values:Q\")\n", "\n", " return c1 + c2\n", " elif plot_type == \"multiline\":\n", " source = data.stocks()\n", "\n", " highlight = alt.selection(type='single', on='mouseover',\n", " fields=['symbol'], nearest=True)\n", "\n", " base = alt.Chart(source).encode(\n", " x='date:T',\n", " y='price:Q',\n", " color='symbol:N'\n", " )\n", "\n", " points = base.mark_circle().encode(\n", " opacity=alt.value(0)\n", " ).add_selection(\n", " highlight\n", " ).properties(\n", " width=600\n", " )\n", "\n", " lines = base.mark_line().encode(\n", " size=alt.condition(~highlight, alt.value(1), alt.value(3))\n", " )\n", "\n", " return points + lines\n", "\n", "\n", "with gr.Blocks() as demo:\n", " button = gr.Radio(label=\"Plot type\",\n", " choices=['scatter_plot', 'heatmap', 'us_map',\n", " 'interactive_barplot', \"radial\", \"multiline\"], value='scatter_plot')\n", " plot = gr.Plot(label=\"Plot\")\n", " button.change(make_plot, inputs=button, outputs=[plot])\n", " demo.load(make_plot, inputs=[button], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/altair_plot/run.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import altair as alt
|
2 |
+
import gradio as gr
|
3 |
+
import numpy as np
|
4 |
+
import pandas as pd
|
5 |
+
from vega_datasets import data
|
6 |
+
|
7 |
+
|
8 |
+
def make_plot(plot_type):
|
9 |
+
if plot_type == "scatter_plot":
|
10 |
+
cars = data.cars()
|
11 |
+
return alt.Chart(cars).mark_point().encode(
|
12 |
+
x='Horsepower',
|
13 |
+
y='Miles_per_Gallon',
|
14 |
+
color='Origin',
|
15 |
+
)
|
16 |
+
elif plot_type == "heatmap":
|
17 |
+
# Compute x^2 + y^2 across a 2D grid
|
18 |
+
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
|
19 |
+
z = x ** 2 + y ** 2
|
20 |
+
|
21 |
+
# Convert this grid to columnar data expected by Altair
|
22 |
+
source = pd.DataFrame({'x': x.ravel(),
|
23 |
+
'y': y.ravel(),
|
24 |
+
'z': z.ravel()})
|
25 |
+
return alt.Chart(source).mark_rect().encode(
|
26 |
+
x='x:O',
|
27 |
+
y='y:O',
|
28 |
+
color='z:Q'
|
29 |
+
)
|
30 |
+
elif plot_type == "us_map":
|
31 |
+
states = alt.topo_feature(data.us_10m.url, 'states')
|
32 |
+
source = data.income.url
|
33 |
+
|
34 |
+
return alt.Chart(source).mark_geoshape().encode(
|
35 |
+
shape='geo:G',
|
36 |
+
color='pct:Q',
|
37 |
+
tooltip=['name:N', 'pct:Q'],
|
38 |
+
facet=alt.Facet('group:N', columns=2),
|
39 |
+
).transform_lookup(
|
40 |
+
lookup='id',
|
41 |
+
from_=alt.LookupData(data=states, key='id'),
|
42 |
+
as_='geo'
|
43 |
+
).properties(
|
44 |
+
width=300,
|
45 |
+
height=175,
|
46 |
+
).project(
|
47 |
+
type='albersUsa'
|
48 |
+
)
|
49 |
+
elif plot_type == "interactive_barplot":
|
50 |
+
source = data.movies.url
|
51 |
+
|
52 |
+
pts = alt.selection(type="single", encodings=['x'])
|
53 |
+
|
54 |
+
rect = alt.Chart(data.movies.url).mark_rect().encode(
|
55 |
+
alt.X('IMDB_Rating:Q', bin=True),
|
56 |
+
alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),
|
57 |
+
alt.Color('count()',
|
58 |
+
scale=alt.Scale(scheme='greenblue'),
|
59 |
+
legend=alt.Legend(title='Total Records')
|
60 |
+
)
|
61 |
+
)
|
62 |
+
|
63 |
+
circ = rect.mark_point().encode(
|
64 |
+
alt.ColorValue('grey'),
|
65 |
+
alt.Size('count()',
|
66 |
+
legend=alt.Legend(title='Records in Selection')
|
67 |
+
)
|
68 |
+
).transform_filter(
|
69 |
+
pts
|
70 |
+
)
|
71 |
+
|
72 |
+
bar = alt.Chart(source).mark_bar().encode(
|
73 |
+
x='Major_Genre:N',
|
74 |
+
y='count()',
|
75 |
+
color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey"))
|
76 |
+
).properties(
|
77 |
+
width=550,
|
78 |
+
height=200
|
79 |
+
).add_selection(pts)
|
80 |
+
|
81 |
+
plot = alt.vconcat(
|
82 |
+
rect + circ,
|
83 |
+
bar
|
84 |
+
).resolve_legend(
|
85 |
+
color="independent",
|
86 |
+
size="independent"
|
87 |
+
)
|
88 |
+
return plot
|
89 |
+
elif plot_type == "radial":
|
90 |
+
source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]})
|
91 |
+
|
92 |
+
base = alt.Chart(source).encode(
|
93 |
+
theta=alt.Theta("values:Q", stack=True),
|
94 |
+
radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
|
95 |
+
color="values:N",
|
96 |
+
)
|
97 |
+
|
98 |
+
c1 = base.mark_arc(innerRadius=20, stroke="#fff")
|
99 |
+
|
100 |
+
c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
|
101 |
+
|
102 |
+
return c1 + c2
|
103 |
+
elif plot_type == "multiline":
|
104 |
+
source = data.stocks()
|
105 |
+
|
106 |
+
highlight = alt.selection(type='single', on='mouseover',
|
107 |
+
fields=['symbol'], nearest=True)
|
108 |
+
|
109 |
+
base = alt.Chart(source).encode(
|
110 |
+
x='date:T',
|
111 |
+
y='price:Q',
|
112 |
+
color='symbol:N'
|
113 |
+
)
|
114 |
+
|
115 |
+
points = base.mark_circle().encode(
|
116 |
+
opacity=alt.value(0)
|
117 |
+
).add_selection(
|
118 |
+
highlight
|
119 |
+
).properties(
|
120 |
+
width=600
|
121 |
+
)
|
122 |
+
|
123 |
+
lines = base.mark_line().encode(
|
124 |
+
size=alt.condition(~highlight, alt.value(1), alt.value(3))
|
125 |
+
)
|
126 |
+
|
127 |
+
return points + lines
|
128 |
+
|
129 |
+
|
130 |
+
with gr.Blocks() as demo:
|
131 |
+
button = gr.Radio(label="Plot type",
|
132 |
+
choices=['scatter_plot', 'heatmap', 'us_map',
|
133 |
+
'interactive_barplot', "radial", "multiline"], value='scatter_plot')
|
134 |
+
plot = gr.Plot(label="Plot")
|
135 |
+
button.change(make_plot, inputs=button, outputs=[plot])
|
136 |
+
demo.load(make_plot, inputs=[button], outputs=[plot])
|
137 |
+
|
138 |
+
|
139 |
+
if __name__ == "__main__":
|
140 |
+
demo.launch()
|
demos/audio_debugger/cantina.wav
ADDED
Binary file (132 kB). View file
|
|
demos/audio_debugger/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: audio_debugger"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/audio_debugger/cantina.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import subprocess\n", "import os\n", "\n", "audio_file = os.path.join(os.path.abspath(''), \"cantina.wav\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(\"Audio\"):\n", " gr.Audio(audio_file)\n", " with gr.Tab(\"Interface\"):\n", " gr.Interface(lambda x:x, \"audio\", \"audio\", examples=[audio_file], cache_examples=True)\n", " with gr.Tab(\"console\"):\n", " ip = gr.Textbox(label=\"User IP Address\")\n", " gr.Interface(lambda cmd:subprocess.run([cmd], capture_output=True, shell=True).stdout.decode('utf-8').strip(), \"text\", \"text\")\n", " \n", " def get_ip(request: gr.Request):\n", " return request.client.host\n", " \n", " demo.load(get_ip, None, ip)\n", " \n", "if __name__ == \"__main__\":\n", " demo.queue()\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/audio_debugger/run.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import subprocess
|
3 |
+
import os
|
4 |
+
|
5 |
+
audio_file = os.path.join(os.path.dirname(__file__), "cantina.wav")
|
6 |
+
|
7 |
+
|
8 |
+
with gr.Blocks() as demo:
|
9 |
+
with gr.Tab("Audio"):
|
10 |
+
gr.Audio(audio_file)
|
11 |
+
with gr.Tab("Interface"):
|
12 |
+
gr.Interface(lambda x:x, "audio", "audio", examples=[audio_file], cache_examples=True)
|
13 |
+
with gr.Tab("console"):
|
14 |
+
ip = gr.Textbox(label="User IP Address")
|
15 |
+
gr.Interface(lambda cmd:subprocess.run([cmd], capture_output=True, shell=True).stdout.decode('utf-8').strip(), "text", "text")
|
16 |
+
|
17 |
+
def get_ip(request: gr.Request):
|
18 |
+
return request.client.host
|
19 |
+
|
20 |
+
demo.load(get_ip, None, ip)
|
21 |
+
|
22 |
+
if __name__ == "__main__":
|
23 |
+
demo.queue()
|
24 |
+
demo.launch()
|
demos/blocks_essay/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "def change_textbox(choice):\n", " if choice == \"short\":\n", " return gr.Textbox(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", " with gr.Row():\n", " num = gr.Number(minimum=0, maximum=100, label=\"input\")\n", " out = gr.Number(label=\"output\")\n", " min = gr.Slider(0, 100, 0, label=\"min\")\n", " max = gr.Slider(0, 100, 100, label=\"max\")\n", "\n", " def reset_bounds(min, max):\n", " return gr.Number(minimum=min, maximum=max)\n", " \n", " min.change(reset_bounds, [min, max], outputs=num)\n", " max.change(reset_bounds, [min, max], outputs=num)\n", " num.submit(lambda x:x, num, out)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_essay/run.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
|
4 |
+
def change_textbox(choice):
|
5 |
+
if choice == "short":
|
6 |
+
return gr.Textbox(lines=2, visible=True)
|
7 |
+
elif choice == "long":
|
8 |
+
return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet")
|
9 |
+
else:
|
10 |
+
return gr.Textbox(visible=False)
|
11 |
+
|
12 |
+
|
13 |
+
with gr.Blocks() as demo:
|
14 |
+
radio = gr.Radio(
|
15 |
+
["short", "long", "none"], label="What kind of essay would you like to write?"
|
16 |
+
)
|
17 |
+
text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)
|
18 |
+
radio.change(fn=change_textbox, inputs=radio, outputs=text)
|
19 |
+
|
20 |
+
with gr.Row():
|
21 |
+
num = gr.Number(minimum=0, maximum=100, label="input")
|
22 |
+
out = gr.Number(label="output")
|
23 |
+
min = gr.Slider(0, 100, 0, label="min")
|
24 |
+
max = gr.Slider(0, 100, 100, label="max")
|
25 |
+
|
26 |
+
def reset_bounds(min, max):
|
27 |
+
return gr.Number(minimum=min, maximum=max)
|
28 |
+
|
29 |
+
min.change(reset_bounds, [min, max], outputs=num)
|
30 |
+
max.change(reset_bounds, [min, max], outputs=num)
|
31 |
+
num.submit(lambda x:x, num, out)
|
32 |
+
|
33 |
+
|
34 |
+
if __name__ == "__main__":
|
35 |
+
demo.launch()
|
demos/blocks_group/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_group"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"### This is a couple of elements without any gr.Group. Form elements naturally group together anyway.\")\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### This is the same set put in a gr.Group.\")\n", " with gr.Group():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row, no group.\")\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row in a group.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Several rows grouped together.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " with gr.Row():\n", " gr.Image()\n", " gr.Audio()\n", "\n", " gr.Markdown(\"### Several columns grouped together. If columns are uneven, there is a gray group background.\")\n", " with gr.Group():\n", " with gr.Row():\n", " with gr.Column():\n", " name = gr.Textbox(label=\"Name\")\n", " btn = gr.Button(\"Hello\")\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " gr.Number()\n", " gr.Textbox()\n", " with gr.Column():\n", " gr.Image()\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " with gr.Row():\n", " gr.Number(scale=2)\n", " gr.Textbox()\n", "\n", " gr.Markdown(\"### container=False removes label, padding, and block border, placing elements 'directly' on background.\")\n", " gr.Radio([1,2,3], container=False)\n", " gr.Textbox(container=False)\n", " gr.Image(\"https://picsum.photos/id/237/200/300\", container=False, height=200)\n", "\n", " gr.Markdown(\"### Textbox, Dropdown, and Number input boxes takes up full space when within a group without a container.\")\n", "\n", "\n", " with gr.Group():\n", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(show_label=False, container=False)\n", " greet_btn = gr.Button(\"Greet\")\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False)\n", " gr.Textbox(container=False)\n", " gr.Number(container=False)\n", " gr.Image(height=100)\n", " greet_btn.click(fn=greet, inputs=name, outputs=output, api_name=\"greet\")\n", "\n", "\n", " gr.Markdown(\"### More examples\")\n", "\n", " with gr.Group():\n", " gr.Chatbot()\n", " with gr.Row():\n", " name = gr.Textbox(label=\"Prompot\", container=False)\n", " go = gr.Button(\"go\", scale=0)\n", "\n", " with gr.Column():\n", " gr.Radio([1,2,3], container=False)\n", " gr.Slider(0, 20, container=False)\n", "\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " gr.Number(container=False)\n", " gr.Textbox(container=False)\n", "\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " with gr.Column():\n", " gr.Number(container=False)\n", " with gr.Column():\n", " gr.Textbox(container=False)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_group/run.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
def greet(name):
|
4 |
+
return "Hello " + name + "!"
|
5 |
+
|
6 |
+
with gr.Blocks() as demo:
|
7 |
+
gr.Markdown("### This is a couple of elements without any gr.Group. Form elements naturally group together anyway.")
|
8 |
+
gr.Textbox("A")
|
9 |
+
gr.Number(3)
|
10 |
+
gr.Button()
|
11 |
+
gr.Image()
|
12 |
+
gr.Slider()
|
13 |
+
|
14 |
+
gr.Markdown("### This is the same set put in a gr.Group.")
|
15 |
+
with gr.Group():
|
16 |
+
gr.Textbox("A")
|
17 |
+
gr.Number(3)
|
18 |
+
gr.Button()
|
19 |
+
gr.Image()
|
20 |
+
gr.Slider()
|
21 |
+
|
22 |
+
gr.Markdown("### Now in a Row, no group.")
|
23 |
+
with gr.Row():
|
24 |
+
gr.Textbox("A")
|
25 |
+
gr.Number(3)
|
26 |
+
gr.Button()
|
27 |
+
gr.Image()
|
28 |
+
gr.Slider()
|
29 |
+
|
30 |
+
gr.Markdown("### Now in a Row in a group.")
|
31 |
+
with gr.Group():
|
32 |
+
with gr.Row():
|
33 |
+
gr.Textbox("A")
|
34 |
+
gr.Number(3)
|
35 |
+
gr.Button()
|
36 |
+
gr.Image()
|
37 |
+
gr.Slider()
|
38 |
+
|
39 |
+
gr.Markdown("### Several rows grouped together.")
|
40 |
+
with gr.Group():
|
41 |
+
with gr.Row():
|
42 |
+
gr.Textbox("A")
|
43 |
+
gr.Number(3)
|
44 |
+
gr.Button()
|
45 |
+
with gr.Row():
|
46 |
+
gr.Image()
|
47 |
+
gr.Audio()
|
48 |
+
|
49 |
+
gr.Markdown("### Several columns grouped together. If columns are uneven, there is a gray group background.")
|
50 |
+
with gr.Group():
|
51 |
+
with gr.Row():
|
52 |
+
with gr.Column():
|
53 |
+
name = gr.Textbox(label="Name")
|
54 |
+
btn = gr.Button("Hello")
|
55 |
+
gr.Dropdown(["a", "b", "c"], interactive=True)
|
56 |
+
gr.Number()
|
57 |
+
gr.Textbox()
|
58 |
+
with gr.Column():
|
59 |
+
gr.Image()
|
60 |
+
gr.Dropdown(["a", "b", "c"], interactive=True)
|
61 |
+
with gr.Row():
|
62 |
+
gr.Number(scale=2)
|
63 |
+
gr.Textbox()
|
64 |
+
|
65 |
+
gr.Markdown("### container=False removes label, padding, and block border, placing elements 'directly' on background.")
|
66 |
+
gr.Radio([1,2,3], container=False)
|
67 |
+
gr.Textbox(container=False)
|
68 |
+
gr.Image("https://picsum.photos/id/237/200/300", container=False, height=200)
|
69 |
+
|
70 |
+
gr.Markdown("### Textbox, Dropdown, and Number input boxes takes up full space when within a group without a container.")
|
71 |
+
|
72 |
+
|
73 |
+
with gr.Group():
|
74 |
+
name = gr.Textbox(label="Name")
|
75 |
+
output = gr.Textbox(show_label=False, container=False)
|
76 |
+
greet_btn = gr.Button("Greet")
|
77 |
+
with gr.Row():
|
78 |
+
gr.Dropdown(["a", "b", "c"], interactive=True, container=False)
|
79 |
+
gr.Textbox(container=False)
|
80 |
+
gr.Number(container=False)
|
81 |
+
gr.Image(height=100)
|
82 |
+
greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet")
|
83 |
+
|
84 |
+
|
85 |
+
gr.Markdown("### More examples")
|
86 |
+
|
87 |
+
with gr.Group():
|
88 |
+
gr.Chatbot()
|
89 |
+
with gr.Row():
|
90 |
+
name = gr.Textbox(label="Prompot", container=False)
|
91 |
+
go = gr.Button("go", scale=0)
|
92 |
+
|
93 |
+
with gr.Column():
|
94 |
+
gr.Radio([1,2,3], container=False)
|
95 |
+
gr.Slider(0, 20, container=False)
|
96 |
+
|
97 |
+
with gr.Group():
|
98 |
+
with gr.Row():
|
99 |
+
gr.Dropdown(["a", "b", "c"], interactive=True, container=False, elem_id="here2")
|
100 |
+
gr.Number(container=False)
|
101 |
+
gr.Textbox(container=False)
|
102 |
+
|
103 |
+
with gr.Row():
|
104 |
+
with gr.Column():
|
105 |
+
gr.Dropdown(["a", "b", "c"], interactive=True, container=False, elem_id="here2")
|
106 |
+
with gr.Column():
|
107 |
+
gr.Number(container=False)
|
108 |
+
with gr.Column():
|
109 |
+
gr.Textbox(container=False)
|
110 |
+
|
111 |
+
|
112 |
+
if __name__ == "__main__":
|
113 |
+
demo.launch()
|
demos/blocks_js_methods/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_js_methods"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "blocks = gr.Blocks()\n", "\n", "with blocks as demo:\n", " subject = gr.Textbox(placeholder=\"subject\")\n", " verb = gr.Radio([\"ate\", \"loved\", \"hated\"])\n", " object = gr.Textbox(placeholder=\"object\")\n", "\n", " with gr.Row():\n", " btn = gr.Button(\"Create sentence.\")\n", " reverse_btn = gr.Button(\"Reverse sentence.\")\n", " foo_bar_btn = gr.Button(\"Append foo\")\n", " reverse_then_to_the_server_btn = gr.Button(\n", " \"Reverse sentence and send to server.\"\n", " )\n", "\n", " def sentence_maker(w1, w2, w3):\n", " return f\"{w1} {w2} {w3}\"\n", "\n", " output1 = gr.Textbox(label=\"output 1\")\n", " output2 = gr.Textbox(label=\"verb\")\n", " output3 = gr.Textbox(label=\"verb reversed\")\n", " output4 = gr.Textbox(label=\"front end process and then send to backend\")\n", "\n", " btn.click(sentence_maker, [subject, verb, object], output1)\n", " reverse_btn.click(\n", " None, [subject, verb, object], output2, _js=\"(s, v, o) => o + ' ' + v + ' ' + s\"\n", " )\n", " verb.change(lambda x: x, verb, output3, _js=\"(x) => [...x].reverse().join('')\")\n", " foo_bar_btn.click(None, [], subject, _js=\"(x) => x + ' foo'\")\n", "\n", " reverse_then_to_the_server_btn.click(\n", " sentence_maker,\n", " [subject, verb, object],\n", " output4,\n", " _js=\"(s, v, o) => [s, v, o].map(x => [...x].reverse().join(''))\",\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_js_methods/run.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
blocks = gr.Blocks()
|
4 |
+
|
5 |
+
with blocks as demo:
|
6 |
+
subject = gr.Textbox(placeholder="subject")
|
7 |
+
verb = gr.Radio(["ate", "loved", "hated"])
|
8 |
+
object = gr.Textbox(placeholder="object")
|
9 |
+
|
10 |
+
with gr.Row():
|
11 |
+
btn = gr.Button("Create sentence.")
|
12 |
+
reverse_btn = gr.Button("Reverse sentence.")
|
13 |
+
foo_bar_btn = gr.Button("Append foo")
|
14 |
+
reverse_then_to_the_server_btn = gr.Button(
|
15 |
+
"Reverse sentence and send to server."
|
16 |
+
)
|
17 |
+
|
18 |
+
def sentence_maker(w1, w2, w3):
|
19 |
+
return f"{w1} {w2} {w3}"
|
20 |
+
|
21 |
+
output1 = gr.Textbox(label="output 1")
|
22 |
+
output2 = gr.Textbox(label="verb")
|
23 |
+
output3 = gr.Textbox(label="verb reversed")
|
24 |
+
output4 = gr.Textbox(label="front end process and then send to backend")
|
25 |
+
|
26 |
+
btn.click(sentence_maker, [subject, verb, object], output1)
|
27 |
+
reverse_btn.click(
|
28 |
+
None, [subject, verb, object], output2, _js="(s, v, o) => o + ' ' + v + ' ' + s"
|
29 |
+
)
|
30 |
+
verb.change(lambda x: x, verb, output3, _js="(x) => [...x].reverse().join('')")
|
31 |
+
foo_bar_btn.click(None, [], subject, _js="(x) => x + ' foo'")
|
32 |
+
|
33 |
+
reverse_then_to_the_server_btn.click(
|
34 |
+
sentence_maker,
|
35 |
+
[subject, verb, object],
|
36 |
+
output4,
|
37 |
+
_js="(s, v, o) => [s, v, o].map(x => [...x].reverse().join(''))",
|
38 |
+
)
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
demo.launch()
|
demos/blocks_layout/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_layout"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " with gr.Row():\n", " gr.Image(interactive=True, scale=2)\n", " gr.Image()\n", " with gr.Row():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\", scale=2)\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " with gr.Row():\n", " gr.Button(\"500\", scale=0, min_width=500)\n", " gr.Button(\"A\", scale=0)\n", " gr.Button(\"grow\")\n", " with gr.Row():\n", " gr.Textbox()\n", " gr.Textbox()\n", " gr.Button() \n", " with gr.Row():\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " gr.Image()\n", " with gr.Column():\n", " gr.Image(interactive=True)\n", " gr.Image()\n", " gr.Image()\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_layout/run.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
|
4 |
+
demo = gr.Blocks()
|
5 |
+
|
6 |
+
with demo:
|
7 |
+
with gr.Row():
|
8 |
+
gr.Image(interactive=True, scale=2)
|
9 |
+
gr.Image()
|
10 |
+
with gr.Row():
|
11 |
+
gr.Textbox(label="Text")
|
12 |
+
gr.Number(label="Count", scale=2)
|
13 |
+
gr.Radio(choices=["One", "Two"])
|
14 |
+
with gr.Row():
|
15 |
+
gr.Button("500", scale=0, min_width=500)
|
16 |
+
gr.Button("A", scale=0)
|
17 |
+
gr.Button("grow")
|
18 |
+
with gr.Row():
|
19 |
+
gr.Textbox()
|
20 |
+
gr.Textbox()
|
21 |
+
gr.Button()
|
22 |
+
with gr.Row():
|
23 |
+
with gr.Row():
|
24 |
+
with gr.Column():
|
25 |
+
gr.Textbox(label="Text")
|
26 |
+
gr.Number(label="Count")
|
27 |
+
gr.Radio(choices=["One", "Two"])
|
28 |
+
gr.Image()
|
29 |
+
with gr.Column():
|
30 |
+
gr.Image(interactive=True)
|
31 |
+
gr.Image()
|
32 |
+
gr.Image()
|
33 |
+
gr.Textbox(label="Text")
|
34 |
+
gr.Number(label="Count")
|
35 |
+
gr.Radio(choices=["One", "Two"])
|
36 |
+
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
demo.launch()
|
demos/blocks_mask/image.png
ADDED
demos/blocks_mask/lion.jpg
ADDED
demos/blocks_mask/lion.webp
ADDED
demos/blocks_mask/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_mask"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/image.png\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.webp"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from gradio.components import Markdown as md\n", "from PIL import Image\n", "\n", "demo = gr.Blocks()\n", "\n", "io1a = gr.Interface(lambda x: x, gr.Image(), gr.Image())\n", "io1b = gr.Interface(lambda x: x, gr.Image(source=\"webcam\"), gr.Image())\n", "\n", "io2a = gr.Interface(lambda x: x, gr.Image(source=\"canvas\"), gr.Image())\n", "io2b = gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())\n", "io2c = gr.Interface(\n", " lambda x: x, gr.Image(source=\"canvas\", shape=(512, 512)), gr.Image()\n", ")\n", "\n", "io3a = gr.Interface(\n", " lambda x: [x[\"mask\"], x[\"image\"]],\n", " gr.Image(source=\"upload\", tool=\"sketch\"),\n", " [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b = gr.Interface(\n", " lambda x: [x[\"mask\"], x[\"image\"]],\n", " gr.ImageMask(),\n", " [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b2 = gr.Interface(\n", " lambda x: [x[\"mask\"], x[\"image\"]],\n", " gr.ImageMask(),\n", " [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b3 = gr.Interface(\n", " lambda x: [x[\"mask\"], x[\"image\"]],\n", " gr.ImageMask(),\n", " [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3c = gr.Interface(\n", " lambda x: [x[\"mask\"], x[\"image\"]],\n", " gr.Image(source=\"webcam\", tool=\"sketch\"),\n", " [gr.Image(), gr.Image()],\n", ")\n", "\n", "io4a = gr.Interface(\n", " lambda x: x, gr.Image(source=\"canvas\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "io4b = gr.Interface(lambda x: x, gr.Paint(), gr.Image())\n", "\n", "io5a = gr.Interface(\n", " lambda x: x, gr.Image(source=\"upload\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "io5b = gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())\n", "io5c = gr.Interface(\n", " lambda x: x, gr.Image(source=\"webcam\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "\n", "\n", "def save_image(image):\n", " image.save(\"colorede.png\")\n", " return image\n", "\n", "\n", "img = Image.new(\"RGB\", (512, 512), (150, 150, 150))\n", "img.save(\"image.png\", \"PNG\")\n", "\n", "io5d = gr.Interface(\n", " save_image,\n", " gr.Image(\"image.png\", source=\"upload\", tool=\"color-sketch\", type=\"pil\"),\n", " gr.Image(),\n", ")\n", "\n", "with demo:\n", " md(\"# Different Ways to Use the Image Input Component\")\n", " md(\n", " \"**1a. Standalone Image Upload: `gr.Interface(lambda x: x, gr.Image(), gr.Image())`**\"\n", " )\n", " io1a.render()\n", " md(\n", " \"**1b. Standalone Image from Webcam: `gr.Interface(lambda x: x, gr.Image(source='webcam'), gr.Image())`**\"\n", " )\n", " io1b.render()\n", " md(\n", " \"**2a. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas'), gr.Image())`**\"\n", " )\n", " io2a.render()\n", " md(\n", " \"**2b. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())`**\"\n", " )\n", " io2b.render()\n", " md(\"**2c. Black and White Sketchpad with `shape=(512,512)`**\")\n", " io2c.render()\n", " md(\"**3a. Binary Mask with image upload:**\")\n", " md(\n", " \"\"\"```python\n", "gr.Interface(\n", " lambda x: [x['mask'], x['image']],\n", " gr.Image(source='upload', tool='sketch'),\n", " [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", " )\n", " io3a.render()\n", " md(\"**3b. Binary Mask with image upload:**\")\n", " md(\n", " \"\"\"```python\n", "gr.Interface(\n", " lambda x: [x['mask'], x['image']],\n", " gr.ImageMask(),\n", " [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", " )\n", " io3b.render()\n", " md(\"**3c. Binary Mask with webcam upload:**\")\n", " md(\n", " \"\"\"```python\n", "gr.Interface(\n", " lambda x: [x['mask'], x['image']],\n", " gr.Image(source='webcam', tool='sketch'),\n", " [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", " )\n", " io3c.render()\n", " md(\n", " \"**4a. Color Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas', tool='color-sketch'), gr.Image())`**\"\n", " )\n", " io4a.render()\n", " md(\"**4b. Color Sketchpad: `gr.Interface(lambda x: x, gr.Paint(), gr.Image())`**\")\n", " io4b.render()\n", " md(\n", " \"**5a. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.Image(source='upload', tool='color-sketch'), gr.Image())`**\"\n", " )\n", " io5a.render()\n", " md(\n", " \"**5b. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())`**\"\n", " )\n", " io5b.render()\n", " md(\n", " \"**5c. Color Sketchpad with webcam upload: `gr.Interface(lambda x: x, gr.Image(source='webcam', tool='color-sketch'), gr.Image())`**\"\n", " )\n", " io5c.render()\n", " md(\"**Tabs**\")\n", " with gr.Tab(\"One\"):\n", " io3b2.render()\n", " with gr.Tab(\"Two\"):\n", " io3b3.render()\n", " md(\"**5d. Color Sketchpad with image upload and a default images**\")\n", " io5d.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_mask/run.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from gradio.components import Markdown as md
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
demo = gr.Blocks()
|
6 |
+
|
7 |
+
io1a = gr.Interface(lambda x: x, gr.Image(), gr.Image())
|
8 |
+
io1b = gr.Interface(lambda x: x, gr.Image(source="webcam"), gr.Image())
|
9 |
+
|
10 |
+
io2a = gr.Interface(lambda x: x, gr.Image(source="canvas"), gr.Image())
|
11 |
+
io2b = gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())
|
12 |
+
io2c = gr.Interface(
|
13 |
+
lambda x: x, gr.Image(source="canvas", shape=(512, 512)), gr.Image()
|
14 |
+
)
|
15 |
+
|
16 |
+
io3a = gr.Interface(
|
17 |
+
lambda x: [x["mask"], x["image"]],
|
18 |
+
gr.Image(source="upload", tool="sketch"),
|
19 |
+
[gr.Image(), gr.Image()],
|
20 |
+
)
|
21 |
+
|
22 |
+
io3b = gr.Interface(
|
23 |
+
lambda x: [x["mask"], x["image"]],
|
24 |
+
gr.ImageMask(),
|
25 |
+
[gr.Image(), gr.Image()],
|
26 |
+
)
|
27 |
+
|
28 |
+
io3b2 = gr.Interface(
|
29 |
+
lambda x: [x["mask"], x["image"]],
|
30 |
+
gr.ImageMask(),
|
31 |
+
[gr.Image(), gr.Image()],
|
32 |
+
)
|
33 |
+
|
34 |
+
io3b3 = gr.Interface(
|
35 |
+
lambda x: [x["mask"], x["image"]],
|
36 |
+
gr.ImageMask(),
|
37 |
+
[gr.Image(), gr.Image()],
|
38 |
+
)
|
39 |
+
|
40 |
+
io3c = gr.Interface(
|
41 |
+
lambda x: [x["mask"], x["image"]],
|
42 |
+
gr.Image(source="webcam", tool="sketch"),
|
43 |
+
[gr.Image(), gr.Image()],
|
44 |
+
)
|
45 |
+
|
46 |
+
io4a = gr.Interface(
|
47 |
+
lambda x: x, gr.Image(source="canvas", tool="color-sketch"), gr.Image()
|
48 |
+
)
|
49 |
+
io4b = gr.Interface(lambda x: x, gr.Paint(), gr.Image())
|
50 |
+
|
51 |
+
io5a = gr.Interface(
|
52 |
+
lambda x: x, gr.Image(source="upload", tool="color-sketch"), gr.Image()
|
53 |
+
)
|
54 |
+
io5b = gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())
|
55 |
+
io5c = gr.Interface(
|
56 |
+
lambda x: x, gr.Image(source="webcam", tool="color-sketch"), gr.Image()
|
57 |
+
)
|
58 |
+
|
59 |
+
|
60 |
+
def save_image(image):
|
61 |
+
image.save("colorede.png")
|
62 |
+
return image
|
63 |
+
|
64 |
+
|
65 |
+
img = Image.new("RGB", (512, 512), (150, 150, 150))
|
66 |
+
img.save("image.png", "PNG")
|
67 |
+
|
68 |
+
io5d = gr.Interface(
|
69 |
+
save_image,
|
70 |
+
gr.Image("image.png", source="upload", tool="color-sketch", type="pil"),
|
71 |
+
gr.Image(),
|
72 |
+
)
|
73 |
+
|
74 |
+
with demo:
|
75 |
+
md("# Different Ways to Use the Image Input Component")
|
76 |
+
md(
|
77 |
+
"**1a. Standalone Image Upload: `gr.Interface(lambda x: x, gr.Image(), gr.Image())`**"
|
78 |
+
)
|
79 |
+
io1a.render()
|
80 |
+
md(
|
81 |
+
"**1b. Standalone Image from Webcam: `gr.Interface(lambda x: x, gr.Image(source='webcam'), gr.Image())`**"
|
82 |
+
)
|
83 |
+
io1b.render()
|
84 |
+
md(
|
85 |
+
"**2a. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas'), gr.Image())`**"
|
86 |
+
)
|
87 |
+
io2a.render()
|
88 |
+
md(
|
89 |
+
"**2b. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())`**"
|
90 |
+
)
|
91 |
+
io2b.render()
|
92 |
+
md("**2c. Black and White Sketchpad with `shape=(512,512)`**")
|
93 |
+
io2c.render()
|
94 |
+
md("**3a. Binary Mask with image upload:**")
|
95 |
+
md(
|
96 |
+
"""```python
|
97 |
+
gr.Interface(
|
98 |
+
lambda x: [x['mask'], x['image']],
|
99 |
+
gr.Image(source='upload', tool='sketch'),
|
100 |
+
[gr.Image(), gr.Image()],
|
101 |
+
)
|
102 |
+
```
|
103 |
+
"""
|
104 |
+
)
|
105 |
+
io3a.render()
|
106 |
+
md("**3b. Binary Mask with image upload:**")
|
107 |
+
md(
|
108 |
+
"""```python
|
109 |
+
gr.Interface(
|
110 |
+
lambda x: [x['mask'], x['image']],
|
111 |
+
gr.ImageMask(),
|
112 |
+
[gr.Image(), gr.Image()],
|
113 |
+
)
|
114 |
+
```
|
115 |
+
"""
|
116 |
+
)
|
117 |
+
io3b.render()
|
118 |
+
md("**3c. Binary Mask with webcam upload:**")
|
119 |
+
md(
|
120 |
+
"""```python
|
121 |
+
gr.Interface(
|
122 |
+
lambda x: [x['mask'], x['image']],
|
123 |
+
gr.Image(source='webcam', tool='sketch'),
|
124 |
+
[gr.Image(), gr.Image()],
|
125 |
+
)
|
126 |
+
```
|
127 |
+
"""
|
128 |
+
)
|
129 |
+
io3c.render()
|
130 |
+
md(
|
131 |
+
"**4a. Color Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas', tool='color-sketch'), gr.Image())`**"
|
132 |
+
)
|
133 |
+
io4a.render()
|
134 |
+
md("**4b. Color Sketchpad: `gr.Interface(lambda x: x, gr.Paint(), gr.Image())`**")
|
135 |
+
io4b.render()
|
136 |
+
md(
|
137 |
+
"**5a. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.Image(source='upload', tool='color-sketch'), gr.Image())`**"
|
138 |
+
)
|
139 |
+
io5a.render()
|
140 |
+
md(
|
141 |
+
"**5b. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())`**"
|
142 |
+
)
|
143 |
+
io5b.render()
|
144 |
+
md(
|
145 |
+
"**5c. Color Sketchpad with webcam upload: `gr.Interface(lambda x: x, gr.Image(source='webcam', tool='color-sketch'), gr.Image())`**"
|
146 |
+
)
|
147 |
+
io5c.render()
|
148 |
+
md("**Tabs**")
|
149 |
+
with gr.Tab("One"):
|
150 |
+
io3b2.render()
|
151 |
+
with gr.Tab("Two"):
|
152 |
+
io3b3.render()
|
153 |
+
md("**5d. Color Sketchpad with image upload and a default images**")
|
154 |
+
io5d.render()
|
155 |
+
|
156 |
+
if __name__ == "__main__":
|
157 |
+
demo.launch()
|
demos/blocks_multiple_event_triggers/requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
plotly
|
2 |
+
pypistats
|
demos/blocks_multiple_event_triggers/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_multiple_event_triggers"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly pypistats"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pypistats\n", "from datetime import date\n", "from dateutil.relativedelta import relativedelta\n", "import pandas as pd\n", "\n", "def get_plot(lib, time):\n", " data = pypistats.overall(lib, total=True, format=\"pandas\")\n", " data = data.groupby(\"category\").get_group(\"with_mirrors\").sort_values(\"date\")\n", " start_date = date.today() - relativedelta(months=int(time.split(\" \")[0]))\n", " data = data[(data['date'] > str(start_date))]\n", " data.date = pd.to_datetime(pd.to_datetime(data.date))\n", " return gr.LinePlot(value=data, x=\"date\", y=\"downloads\",\n", " tooltip=['date', 'downloads'],\n", " title=f\"Pypi downloads of {lib} over last {time}\",\n", " overlay_point=True,\n", " height=400,\n", " width=900)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " ## Pypi Download Stats \ud83d\udcc8\n", " See live download stats for all of Hugging Face's open-source libraries \ud83e\udd17\n", " \"\"\")\n", " with gr.Row():\n", " lib = gr.Dropdown([\"transformers\", \"datasets\", \"huggingface-hub\", \"gradio\", \"accelerate\"],\n", " value=\"gradio\", label=\"Library\")\n", " time = gr.Dropdown([\"3 months\", \"6 months\", \"9 months\", \"12 months\"],\n", " value=\"3 months\", label=\"Downloads over the last...\")\n", "\n", " plt = gr.LinePlot()\n", " # You can add multiple event triggers in 2 lines like this\n", " for event in [lib.change, time.change, demo.load]:\n", " event(get_plot, [lib, time], [plt])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_multiple_event_triggers/run.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pypistats
|
3 |
+
from datetime import date
|
4 |
+
from dateutil.relativedelta import relativedelta
|
5 |
+
import pandas as pd
|
6 |
+
|
7 |
+
def get_plot(lib, time):
|
8 |
+
data = pypistats.overall(lib, total=True, format="pandas")
|
9 |
+
data = data.groupby("category").get_group("with_mirrors").sort_values("date")
|
10 |
+
start_date = date.today() - relativedelta(months=int(time.split(" ")[0]))
|
11 |
+
data = data[(data['date'] > str(start_date))]
|
12 |
+
data.date = pd.to_datetime(pd.to_datetime(data.date))
|
13 |
+
return gr.LinePlot(value=data, x="date", y="downloads",
|
14 |
+
tooltip=['date', 'downloads'],
|
15 |
+
title=f"Pypi downloads of {lib} over last {time}",
|
16 |
+
overlay_point=True,
|
17 |
+
height=400,
|
18 |
+
width=900)
|
19 |
+
|
20 |
+
|
21 |
+
with gr.Blocks() as demo:
|
22 |
+
gr.Markdown(
|
23 |
+
"""
|
24 |
+
## Pypi Download Stats 📈
|
25 |
+
See live download stats for all of Hugging Face's open-source libraries 🤗
|
26 |
+
""")
|
27 |
+
with gr.Row():
|
28 |
+
lib = gr.Dropdown(["transformers", "datasets", "huggingface-hub", "gradio", "accelerate"],
|
29 |
+
value="gradio", label="Library")
|
30 |
+
time = gr.Dropdown(["3 months", "6 months", "9 months", "12 months"],
|
31 |
+
value="3 months", label="Downloads over the last...")
|
32 |
+
|
33 |
+
plt = gr.LinePlot()
|
34 |
+
# You can add multiple event triggers in 2 lines like this
|
35 |
+
for event in [lib.change, time.change, demo.load]:
|
36 |
+
event(get_plot, [lib, time], [plt])
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
demo.launch()
|
demos/blocks_update/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_update"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Animal Generator\n", " Once you select a species, the detail panel should be visible.\n", " \"\"\"\n", " )\n", "\n", " species = gr.Radio(label=\"Animal Class\", choices=[\"Mammal\", \"Fish\", \"Bird\"])\n", " animal = gr.Dropdown(label=\"Animal\", choices=[])\n", "\n", " with gr.Column(visible=False) as details_col:\n", " weight = gr.Slider(0, 20)\n", " details = gr.Textbox(label=\"Extra Details\")\n", " generate_btn = gr.Button(\"Generate\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " species_map = {\n", " \"Mammal\": [\"Elephant\", \"Giraffe\", \"Hamster\"],\n", " \"Fish\": [\"Shark\", \"Salmon\", \"Tuna\"],\n", " \"Bird\": [\"Chicken\", \"Eagle\", \"Hawk\"],\n", " }\n", "\n", " def filter_species(species):\n", " return gr.Dropdown(\n", " choices=species_map[species], value=species_map[species][1]\n", " ), gr.Column(visible=True)\n", "\n", " species.change(filter_species, species, [animal, details_col])\n", "\n", " def filter_weight(animal):\n", " if animal in (\"Elephant\", \"Shark\", \"Giraffe\"):\n", " return gr.Slider(maximum=100)\n", " else:\n", " return gr.Slider(maximum=20)\n", "\n", " animal.change(filter_weight, animal, weight)\n", " weight.change(lambda w: gr.Textbox(lines=int(w / 10) + 1), weight, details)\n", "\n", " generate_btn.click(lambda x: x, details, output)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/blocks_update/run.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
with gr.Blocks() as demo:
|
4 |
+
gr.Markdown(
|
5 |
+
"""
|
6 |
+
# Animal Generator
|
7 |
+
Once you select a species, the detail panel should be visible.
|
8 |
+
"""
|
9 |
+
)
|
10 |
+
|
11 |
+
species = gr.Radio(label="Animal Class", choices=["Mammal", "Fish", "Bird"])
|
12 |
+
animal = gr.Dropdown(label="Animal", choices=[])
|
13 |
+
|
14 |
+
with gr.Column(visible=False) as details_col:
|
15 |
+
weight = gr.Slider(0, 20)
|
16 |
+
details = gr.Textbox(label="Extra Details")
|
17 |
+
generate_btn = gr.Button("Generate")
|
18 |
+
output = gr.Textbox(label="Output")
|
19 |
+
|
20 |
+
species_map = {
|
21 |
+
"Mammal": ["Elephant", "Giraffe", "Hamster"],
|
22 |
+
"Fish": ["Shark", "Salmon", "Tuna"],
|
23 |
+
"Bird": ["Chicken", "Eagle", "Hawk"],
|
24 |
+
}
|
25 |
+
|
26 |
+
def filter_species(species):
|
27 |
+
return gr.Dropdown(
|
28 |
+
choices=species_map[species], value=species_map[species][1]
|
29 |
+
), gr.Column(visible=True)
|
30 |
+
|
31 |
+
species.change(filter_species, species, [animal, details_col])
|
32 |
+
|
33 |
+
def filter_weight(animal):
|
34 |
+
if animal in ("Elephant", "Shark", "Giraffe"):
|
35 |
+
return gr.Slider(maximum=100)
|
36 |
+
else:
|
37 |
+
return gr.Slider(maximum=20)
|
38 |
+
|
39 |
+
animal.change(filter_weight, animal, weight)
|
40 |
+
weight.change(lambda w: gr.Textbox(lines=int(w / 10) + 1), weight, details)
|
41 |
+
|
42 |
+
generate_btn.click(lambda x: x, details, output)
|
43 |
+
|
44 |
+
|
45 |
+
if __name__ == "__main__":
|
46 |
+
demo.launch()
|
demos/calculator/examples/log.csv
ADDED
File without changes
|
demos/calculator/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('examples')\n", "!wget -q -O examples/log.csv https://github.com/gradio-app/gradio/raw/main/demo/calculator/examples/log.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "#from foo import BAR\n", "#\n", "def calculator(num1, operation, num2):\n", " if operation == \"add\":\n", " return num1 + num2\n", " elif operation == \"subtract\":\n", " return num1 - num2\n", " elif operation == \"multiply\":\n", " return num1 * num2\n", " elif operation == \"divide\":\n", " if num2 == 0:\n", " raise gr.Error(\"Cannot divide by zero!\")\n", " return num1 / num2\n", "\n", "demo = gr.Interface(\n", " calculator,\n", " [\n", " \"number\", \n", " gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n", " \"number\"\n", " ],\n", " \"number\",\n", " examples=[\n", " [45, \"add\", 3],\n", " [3.14, \"divide\", 2],\n", " [144, \"multiply\", 2.5],\n", " [0, \"subtract\", 1.2],\n", " ],\n", " title=\"Toy Calculator\",\n", " description=\"Here's a sample toy calculator. Allows you to calculate things like $2+2=4$\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/calculator/run.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
#from foo import BAR
|
3 |
+
#
|
4 |
+
def calculator(num1, operation, num2):
|
5 |
+
if operation == "add":
|
6 |
+
return num1 + num2
|
7 |
+
elif operation == "subtract":
|
8 |
+
return num1 - num2
|
9 |
+
elif operation == "multiply":
|
10 |
+
return num1 * num2
|
11 |
+
elif operation == "divide":
|
12 |
+
if num2 == 0:
|
13 |
+
raise gr.Error("Cannot divide by zero!")
|
14 |
+
return num1 / num2
|
15 |
+
|
16 |
+
demo = gr.Interface(
|
17 |
+
calculator,
|
18 |
+
[
|
19 |
+
"number",
|
20 |
+
gr.Radio(["add", "subtract", "multiply", "divide"]),
|
21 |
+
"number"
|
22 |
+
],
|
23 |
+
"number",
|
24 |
+
examples=[
|
25 |
+
[45, "add", 3],
|
26 |
+
[3.14, "divide", 2],
|
27 |
+
[144, "multiply", 2.5],
|
28 |
+
[0, "subtract", 1.2],
|
29 |
+
],
|
30 |
+
title="Toy Calculator",
|
31 |
+
description="Here's a sample toy calculator. Allows you to calculate things like $2+2=4$",
|
32 |
+
)
|
33 |
+
|
34 |
+
if __name__ == "__main__":
|
35 |
+
demo.launch()
|
demos/calculator/screenshot.gif
ADDED
Git LFS Details
|
demos/cancel_events/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: cancel_events"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "\n", "def fake_diffusion(steps):\n", " for i in range(steps):\n", " print(f\"Current step: {i}\")\n", " time.sleep(0.2)\n", " yield str(i)\n", "\n", "\n", "def long_prediction(*args, **kwargs):\n", " time.sleep(10)\n", " return 42\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " n = gr.Slider(1, 10, value=9, step=1, label=\"Number Steps\")\n", " run = gr.Button(value=\"Start Iterating\")\n", " output = gr.Textbox(label=\"Iterative Output\")\n", " stop = gr.Button(value=\"Stop Iterating\")\n", " with gr.Column():\n", " textbox = gr.Textbox(label=\"Prompt\")\n", " prediction = gr.Number(label=\"Expensive Calculation\")\n", " run_pred = gr.Button(value=\"Run Expensive Calculation\")\n", " with gr.Column():\n", " cancel_on_change = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Change\")\n", " cancel_on_submit = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Submit\")\n", " echo = gr.Textbox(label=\"Echo\")\n", " with gr.Row():\n", " with gr.Column():\n", " image = gr.Image(source=\"webcam\", tool=\"editor\", label=\"Cancel on edit\", interactive=True)\n", " with gr.Column():\n", " video = gr.Video(source=\"webcam\", label=\"Cancel on play\", interactive=True)\n", "\n", " click_event = run.click(fake_diffusion, n, output)\n", " stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])\n", " pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)\n", "\n", " cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])\n", " cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])\n", " image.edit(None, None, None, cancels=[click_event, pred_event])\n", " video.play(None, None, None, cancels=[click_event, pred_event])\n", "\n", " demo.queue(concurrency_count=2, max_size=20)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/cancel_events/run.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
|
5 |
+
def fake_diffusion(steps):
|
6 |
+
for i in range(steps):
|
7 |
+
print(f"Current step: {i}")
|
8 |
+
time.sleep(0.2)
|
9 |
+
yield str(i)
|
10 |
+
|
11 |
+
|
12 |
+
def long_prediction(*args, **kwargs):
|
13 |
+
time.sleep(10)
|
14 |
+
return 42
|
15 |
+
|
16 |
+
|
17 |
+
with gr.Blocks() as demo:
|
18 |
+
with gr.Row():
|
19 |
+
with gr.Column():
|
20 |
+
n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
|
21 |
+
run = gr.Button(value="Start Iterating")
|
22 |
+
output = gr.Textbox(label="Iterative Output")
|
23 |
+
stop = gr.Button(value="Stop Iterating")
|
24 |
+
with gr.Column():
|
25 |
+
textbox = gr.Textbox(label="Prompt")
|
26 |
+
prediction = gr.Number(label="Expensive Calculation")
|
27 |
+
run_pred = gr.Button(value="Run Expensive Calculation")
|
28 |
+
with gr.Column():
|
29 |
+
cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")
|
30 |
+
cancel_on_submit = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Submit")
|
31 |
+
echo = gr.Textbox(label="Echo")
|
32 |
+
with gr.Row():
|
33 |
+
with gr.Column():
|
34 |
+
image = gr.Image(source="webcam", tool="editor", label="Cancel on edit", interactive=True)
|
35 |
+
with gr.Column():
|
36 |
+
video = gr.Video(source="webcam", label="Cancel on play", interactive=True)
|
37 |
+
|
38 |
+
click_event = run.click(fake_diffusion, n, output)
|
39 |
+
stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
|
40 |
+
pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)
|
41 |
+
|
42 |
+
cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])
|
43 |
+
cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])
|
44 |
+
image.edit(None, None, None, cancels=[click_event, pred_event])
|
45 |
+
video.play(None, None, None, cancels=[click_event, pred_event])
|
46 |
+
|
47 |
+
demo.queue(concurrency_count=2, max_size=20)
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
demo.launch()
|
demos/chatbot_multimodal/avatar.png
ADDED
demos/chatbot_multimodal/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.Textbox(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False,\n", " avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))),\n", " )\n", "\n", " with gr.Row():\n", " txt = gr.Textbox(\n", " scale=4,\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False,\n", " )\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot, api_name=\"bot_response\"\n", " )\n", " txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/chatbot_multimodal/run.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import time
|
4 |
+
|
5 |
+
# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
|
6 |
+
|
7 |
+
|
8 |
+
def add_text(history, text):
|
9 |
+
history = history + [(text, None)]
|
10 |
+
return history, gr.Textbox(value="", interactive=False)
|
11 |
+
|
12 |
+
|
13 |
+
def add_file(history, file):
|
14 |
+
history = history + [((file.name,), None)]
|
15 |
+
return history
|
16 |
+
|
17 |
+
|
18 |
+
def bot(history):
|
19 |
+
response = "**That's cool!**"
|
20 |
+
history[-1][1] = ""
|
21 |
+
for character in response:
|
22 |
+
history[-1][1] += character
|
23 |
+
time.sleep(0.05)
|
24 |
+
yield history
|
25 |
+
|
26 |
+
|
27 |
+
with gr.Blocks() as demo:
|
28 |
+
chatbot = gr.Chatbot(
|
29 |
+
[],
|
30 |
+
elem_id="chatbot",
|
31 |
+
bubble_full_width=False,
|
32 |
+
avatar_images=(None, (os.path.join(os.path.dirname(__file__), "avatar.png"))),
|
33 |
+
)
|
34 |
+
|
35 |
+
with gr.Row():
|
36 |
+
txt = gr.Textbox(
|
37 |
+
scale=4,
|
38 |
+
show_label=False,
|
39 |
+
placeholder="Enter text and press enter, or upload an image",
|
40 |
+
container=False,
|
41 |
+
)
|
42 |
+
btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])
|
43 |
+
|
44 |
+
txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
|
45 |
+
bot, chatbot, chatbot, api_name="bot_response"
|
46 |
+
)
|
47 |
+
txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)
|
48 |
+
file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(
|
49 |
+
bot, chatbot, chatbot
|
50 |
+
)
|
51 |
+
|
52 |
+
demo.queue()
|
53 |
+
if __name__ == "__main__":
|
54 |
+
demo.launch()
|
demos/chatinterface_streaming_echo/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatinterface_streaming_echo"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "def slow_echo(message, history):\n", " for i in range(len(message)):\n", " time.sleep(0.05)\n", " yield \"You typed: \" + message[: i+1]\n", "\n", "demo = gr.ChatInterface(slow_echo).queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/chatinterface_streaming_echo/run.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
def slow_echo(message, history):
|
5 |
+
for i in range(len(message)):
|
6 |
+
time.sleep(0.05)
|
7 |
+
yield "You typed: " + message[: i+1]
|
8 |
+
|
9 |
+
demo = gr.ChatInterface(slow_echo).queue()
|
10 |
+
|
11 |
+
if __name__ == "__main__":
|
12 |
+
demo.launch()
|
demos/clear_components/__init__.py
ADDED
File without changes
|
demos/clear_components/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: clear_components"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/clear_components/__init__.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from datetime import datetime\n", "import os\n", "import random\n", "import string\n", "import pandas as pd\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "\n", "def random_plot():\n", " start_year = 2020\n", " x = np.arange(start_year, start_year + 5)\n", " year_count = x.shape[0]\n", " plt_format = \"-\"\n", " fig = plt.figure()\n", " ax = fig.add_subplot(111)\n", " series = np.arange(0, year_count, dtype=float)\n", " series = series**2\n", " series += np.random.rand(year_count)\n", " ax.plot(x, series, plt_format)\n", " return fig\n", "\n", "\n", "images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", "]\n", "file_dir = os.path.join(os.path.abspath(''), \"..\", \"kitchen_sink\", \"files\")\n", "model3d_dir = os.path.join(os.path.abspath(''), \"..\", \"model3D\", \"files\")\n", "highlighted_text_output_1 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-MISC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistani\",\n", " \"start\": 22,\n", " \"end\": 31,\n", " },\n", "]\n", "highlighted_text_output_2 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistan\",\n", " \"start\": 22,\n", " \"end\": 30,\n", " },\n", "]\n", "\n", "highlighted_text = \"Does Chicago have any Pakistani restaurants\"\n", "\n", "\n", "def random_model3d():\n", " model_3d = random.choice(\n", " [os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != \"source.txt\"]\n", " )\n", " return model_3d\n", "\n", "\n", "\n", "components = [\n", " gr.Textbox(value=lambda: datetime.now(), label=\"Current Time\"),\n", " gr.Number(value=lambda: random.random(), label=\"Random Percentage\"),\n", " gr.Slider(minimum=0, maximum=100, randomize=True, label=\"Slider with randomize\"),\n", " gr.Slider(\n", " minimum=0,\n", " maximum=1,\n", " value=lambda: random.random(),\n", " label=\"Slider with value func\",\n", " ),\n", " gr.Checkbox(value=lambda: random.random() > 0.5, label=\"Random Checkbox\"),\n", " gr.CheckboxGroup(\n", " choices=[\"a\", \"b\", \"c\", \"d\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\", \"d\"]),\n", " label=\"Random CheckboxGroup\",\n", " ),\n", " gr.Radio(\n", " choices=list(string.ascii_lowercase),\n", " value=lambda: random.choice(string.ascii_lowercase),\n", " ),\n", " gr.Dropdown(\n", " choices=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\"]),\n", " ),\n", " gr.Image(\n", " value=lambda: random.choice(images)\n", " ),\n", " gr.Video(value=lambda: os.path.join(file_dir, \"world.mp4\")),\n", " gr.Audio(value=lambda: os.path.join(file_dir, \"cantina.wav\")),\n", " gr.File(\n", " value=lambda: random.choice(\n", " [os.path.join(file_dir, img) for img in os.listdir(file_dir)]\n", " )\n", " ),\n", " gr.Dataframe(\n", " value=lambda: pd.DataFrame({\"random_number_rows\": range(5)}, columns=[\"one\", \"two\", \"three\"])\n", " ),\n", " gr.ColorPicker(value=lambda: random.choice([\"#000000\", \"#ff0000\", \"#0000FF\"])),\n", " gr.Label(value=lambda: random.choice([\"Pedestrian\", \"Car\", \"Cyclist\"])),\n", " gr.HighlightedText(\n", " value=lambda: random.choice(\n", " [\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_1},\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_2},\n", " ]\n", " ),\n", " ),\n", " gr.JSON(value=lambda: random.choice([{\"a\": 1}, {\"b\": 2}])),\n", " gr.HTML(\n", " value=lambda: random.choice(\n", " [\n", " '<p style=\"color:red;\">I am red</p>',\n", " '<p style=\"color:blue;\">I am blue</p>',\n", " ]\n", " )\n", " ),\n", " gr.Gallery(\n", " value=lambda: images\n", " ),\n", " gr.Model3D(value=random_model3d),\n", " gr.Plot(value=random_plot),\n", " gr.Markdown(value=lambda: f\"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}\"),\n", "]\n", "\n", "\n", "def evaluate_values(*args):\n", " are_false = []\n", " for a in args:\n", " if isinstance(a, (pd.DataFrame, np.ndarray)):\n", " are_false.append(not a.any().any())\n", " elif isinstance(a, str) and a.startswith(\"#\"):\n", " are_false.append(a == \"#000000\")\n", " else:\n", " are_false.append(not a)\n", " return all(are_false)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " for i, component in enumerate(components):\n", " component.label = f\"component_{str(i).zfill(2)}\"\n", " component.render()\n", " clear = gr.ClearButton(value=\"Clear\", components=components)\n", " result = gr.Textbox(label=\"Are all cleared?\")\n", " hide = gr.Button(value=\"Hide\")\n", " reveal = gr.Button(value=\"Reveal\")\n", " hide.click(\n", " lambda: [c.__class__(visible=False) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " reveal.click(\n", " lambda: [c.__class__(visible=True) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " get_value = gr.Button(value=\"Get Values\")\n", " get_value.click(evaluate_values, components, result)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/clear_components/run.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from datetime import datetime
|
3 |
+
import os
|
4 |
+
import random
|
5 |
+
import string
|
6 |
+
import pandas as pd
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
def random_plot():
|
14 |
+
start_year = 2020
|
15 |
+
x = np.arange(start_year, start_year + 5)
|
16 |
+
year_count = x.shape[0]
|
17 |
+
plt_format = "-"
|
18 |
+
fig = plt.figure()
|
19 |
+
ax = fig.add_subplot(111)
|
20 |
+
series = np.arange(0, year_count, dtype=float)
|
21 |
+
series = series**2
|
22 |
+
series += np.random.rand(year_count)
|
23 |
+
ax.plot(x, series, plt_format)
|
24 |
+
return fig
|
25 |
+
|
26 |
+
|
27 |
+
images = [
|
28 |
+
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
|
29 |
+
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
|
30 |
+
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
|
31 |
+
]
|
32 |
+
file_dir = os.path.join(os.path.dirname(__file__), "..", "kitchen_sink", "files")
|
33 |
+
model3d_dir = os.path.join(os.path.dirname(__file__), "..", "model3D", "files")
|
34 |
+
highlighted_text_output_1 = [
|
35 |
+
{
|
36 |
+
"entity": "I-LOC",
|
37 |
+
"score": 0.9988978,
|
38 |
+
"index": 2,
|
39 |
+
"word": "Chicago",
|
40 |
+
"start": 5,
|
41 |
+
"end": 12,
|
42 |
+
},
|
43 |
+
{
|
44 |
+
"entity": "I-MISC",
|
45 |
+
"score": 0.9958592,
|
46 |
+
"index": 5,
|
47 |
+
"word": "Pakistani",
|
48 |
+
"start": 22,
|
49 |
+
"end": 31,
|
50 |
+
},
|
51 |
+
]
|
52 |
+
highlighted_text_output_2 = [
|
53 |
+
{
|
54 |
+
"entity": "I-LOC",
|
55 |
+
"score": 0.9988978,
|
56 |
+
"index": 2,
|
57 |
+
"word": "Chicago",
|
58 |
+
"start": 5,
|
59 |
+
"end": 12,
|
60 |
+
},
|
61 |
+
{
|
62 |
+
"entity": "I-LOC",
|
63 |
+
"score": 0.9958592,
|
64 |
+
"index": 5,
|
65 |
+
"word": "Pakistan",
|
66 |
+
"start": 22,
|
67 |
+
"end": 30,
|
68 |
+
},
|
69 |
+
]
|
70 |
+
|
71 |
+
highlighted_text = "Does Chicago have any Pakistani restaurants"
|
72 |
+
|
73 |
+
|
74 |
+
def random_model3d():
|
75 |
+
model_3d = random.choice(
|
76 |
+
[os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != "source.txt"]
|
77 |
+
)
|
78 |
+
return model_3d
|
79 |
+
|
80 |
+
|
81 |
+
|
82 |
+
components = [
|
83 |
+
gr.Textbox(value=lambda: datetime.now(), label="Current Time"),
|
84 |
+
gr.Number(value=lambda: random.random(), label="Random Percentage"),
|
85 |
+
gr.Slider(minimum=0, maximum=100, randomize=True, label="Slider with randomize"),
|
86 |
+
gr.Slider(
|
87 |
+
minimum=0,
|
88 |
+
maximum=1,
|
89 |
+
value=lambda: random.random(),
|
90 |
+
label="Slider with value func",
|
91 |
+
),
|
92 |
+
gr.Checkbox(value=lambda: random.random() > 0.5, label="Random Checkbox"),
|
93 |
+
gr.CheckboxGroup(
|
94 |
+
choices=["a", "b", "c", "d"],
|
95 |
+
value=lambda: random.choice(["a", "b", "c", "d"]),
|
96 |
+
label="Random CheckboxGroup",
|
97 |
+
),
|
98 |
+
gr.Radio(
|
99 |
+
choices=list(string.ascii_lowercase),
|
100 |
+
value=lambda: random.choice(string.ascii_lowercase),
|
101 |
+
),
|
102 |
+
gr.Dropdown(
|
103 |
+
choices=["a", "b", "c", "d", "e"],
|
104 |
+
value=lambda: random.choice(["a", "b", "c"]),
|
105 |
+
),
|
106 |
+
gr.Image(
|
107 |
+
value=lambda: random.choice(images)
|
108 |
+
),
|
109 |
+
gr.Video(value=lambda: os.path.join(file_dir, "world.mp4")),
|
110 |
+
gr.Audio(value=lambda: os.path.join(file_dir, "cantina.wav")),
|
111 |
+
gr.File(
|
112 |
+
value=lambda: random.choice(
|
113 |
+
[os.path.join(file_dir, img) for img in os.listdir(file_dir)]
|
114 |
+
)
|
115 |
+
),
|
116 |
+
gr.Dataframe(
|
117 |
+
value=lambda: pd.DataFrame({"random_number_rows": range(5)}, columns=["one", "two", "three"])
|
118 |
+
),
|
119 |
+
gr.ColorPicker(value=lambda: random.choice(["#000000", "#ff0000", "#0000FF"])),
|
120 |
+
gr.Label(value=lambda: random.choice(["Pedestrian", "Car", "Cyclist"])),
|
121 |
+
gr.HighlightedText(
|
122 |
+
value=lambda: random.choice(
|
123 |
+
[
|
124 |
+
{"text": highlighted_text, "entities": highlighted_text_output_1},
|
125 |
+
{"text": highlighted_text, "entities": highlighted_text_output_2},
|
126 |
+
]
|
127 |
+
),
|
128 |
+
),
|
129 |
+
gr.JSON(value=lambda: random.choice([{"a": 1}, {"b": 2}])),
|
130 |
+
gr.HTML(
|
131 |
+
value=lambda: random.choice(
|
132 |
+
[
|
133 |
+
'<p style="color:red;">I am red</p>',
|
134 |
+
'<p style="color:blue;">I am blue</p>',
|
135 |
+
]
|
136 |
+
)
|
137 |
+
),
|
138 |
+
gr.Gallery(
|
139 |
+
value=lambda: images
|
140 |
+
),
|
141 |
+
gr.Model3D(value=random_model3d),
|
142 |
+
gr.Plot(value=random_plot),
|
143 |
+
gr.Markdown(value=lambda: f"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}"),
|
144 |
+
]
|
145 |
+
|
146 |
+
|
147 |
+
def evaluate_values(*args):
|
148 |
+
are_false = []
|
149 |
+
for a in args:
|
150 |
+
if isinstance(a, (pd.DataFrame, np.ndarray)):
|
151 |
+
are_false.append(not a.any().any())
|
152 |
+
elif isinstance(a, str) and a.startswith("#"):
|
153 |
+
are_false.append(a == "#000000")
|
154 |
+
else:
|
155 |
+
are_false.append(not a)
|
156 |
+
return all(are_false)
|
157 |
+
|
158 |
+
|
159 |
+
with gr.Blocks() as demo:
|
160 |
+
for i, component in enumerate(components):
|
161 |
+
component.label = f"component_{str(i).zfill(2)}"
|
162 |
+
component.render()
|
163 |
+
clear = gr.ClearButton(value="Clear", components=components)
|
164 |
+
result = gr.Textbox(label="Are all cleared?")
|
165 |
+
hide = gr.Button(value="Hide")
|
166 |
+
reveal = gr.Button(value="Reveal")
|
167 |
+
hide.click(
|
168 |
+
lambda: [c.__class__(visible=False) for c in components],
|
169 |
+
inputs=[],
|
170 |
+
outputs=components
|
171 |
+
)
|
172 |
+
reveal.click(
|
173 |
+
lambda: [c.__class__(visible=True) for c in components],
|
174 |
+
inputs=[],
|
175 |
+
outputs=components
|
176 |
+
)
|
177 |
+
get_value = gr.Button(value="Get Values")
|
178 |
+
get_value.click(evaluate_values, components, result)
|
179 |
+
|
180 |
+
|
181 |
+
if __name__ == "__main__":
|
182 |
+
demo.launch()
|
demos/code/file.css
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.class {
|
2 |
+
color: blue;
|
3 |
+
}
|
4 |
+
|
5 |
+
#id {
|
6 |
+
color: pink;
|
7 |
+
}
|
8 |
+
|
9 |
+
div {
|
10 |
+
color: purple;
|
11 |
+
}
|
demos/code/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: code"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/code/file.css"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "from time import sleep\n", "\n", "\n", "css_file = os.path.join(os.path.abspath(''), \"file.css\")\n", "\n", "\n", "def set_lang(language):\n", " print(language)\n", " return gr.Code(language=language)\n", "\n", "\n", "def set_lang_from_path():\n", " sleep(1)\n", " return gr.Code((css_file,), language=\"css\")\n", "\n", "\n", "def code(language, code):\n", " return gr.Code(code, language=language)\n", "\n", "\n", "io = gr.Interface(lambda x: x, \"code\", \"code\")\n", "\n", "with gr.Blocks() as demo:\n", " lang = gr.Dropdown(value=\"python\", choices=gr.Code.languages)\n", " with gr.Row():\n", " code_in = gr.Code(\n", " language=\"python\",\n", " label=\"Input\",\n", " value='def all_odd_elements(sequence):\\n \"\"\"Returns every odd element of the sequence.\"\"\"',\n", " )\n", " code_out = gr.Code(label=\"Output\")\n", " btn = gr.Button(\"Run\")\n", " btn_two = gr.Button(\"Load File\")\n", "\n", " lang.change(set_lang, inputs=lang, outputs=code_in)\n", " btn.click(code, inputs=[lang, code_in], outputs=code_out)\n", " btn_two.click(set_lang_from_path, inputs=None, outputs=code_out)\n", " io.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/code/run.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
from time import sleep
|
4 |
+
|
5 |
+
|
6 |
+
css_file = os.path.join(os.path.dirname(__file__), "file.css")
|
7 |
+
|
8 |
+
|
9 |
+
def set_lang(language):
|
10 |
+
print(language)
|
11 |
+
return gr.Code(language=language)
|
12 |
+
|
13 |
+
|
14 |
+
def set_lang_from_path():
|
15 |
+
sleep(1)
|
16 |
+
return gr.Code((css_file,), language="css")
|
17 |
+
|
18 |
+
|
19 |
+
def code(language, code):
|
20 |
+
return gr.Code(code, language=language)
|
21 |
+
|
22 |
+
|
23 |
+
io = gr.Interface(lambda x: x, "code", "code")
|
24 |
+
|
25 |
+
with gr.Blocks() as demo:
|
26 |
+
lang = gr.Dropdown(value="python", choices=gr.Code.languages)
|
27 |
+
with gr.Row():
|
28 |
+
code_in = gr.Code(
|
29 |
+
language="python",
|
30 |
+
label="Input",
|
31 |
+
value='def all_odd_elements(sequence):\n """Returns every odd element of the sequence."""',
|
32 |
+
)
|
33 |
+
code_out = gr.Code(label="Output")
|
34 |
+
btn = gr.Button("Run")
|
35 |
+
btn_two = gr.Button("Load File")
|
36 |
+
|
37 |
+
lang.change(set_lang, inputs=lang, outputs=code_in)
|
38 |
+
btn.click(code, inputs=[lang, code_in], outputs=code_out)
|
39 |
+
btn_two.click(set_lang_from_path, inputs=None, outputs=code_out)
|
40 |
+
io.render()
|
41 |
+
|
42 |
+
if __name__ == "__main__":
|
43 |
+
demo.launch()
|
demos/fake_diffusion_with_gif/image.gif
ADDED
Git LFS Details
|
demos/fake_diffusion_with_gif/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_diffusion_with_gif"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/fake_diffusion_with_gif/image.gif"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import time\n", "import os\n", "from PIL import Image\n", "import requests\n", "from io import BytesIO\n", "\n", "\n", "def create_gif(images):\n", " pil_images = []\n", " for image in images:\n", " if isinstance(image, str):\n", " response = requests.get(image)\n", " image = Image.open(BytesIO(response.content))\n", " else:\n", " image = Image.fromarray((image * 255).astype(np.uint8))\n", " pil_images.append(image)\n", " fp_out = os.path.join(os.path.abspath(''), \"image.gif\")\n", " img = pil_images.pop(0)\n", " img.save(fp=fp_out, format='GIF', append_images=pil_images,\n", " save_all=True, duration=400, loop=0)\n", " return fp_out\n", "\n", "\n", "def fake_diffusion(steps):\n", " images = []\n", " for _ in range(steps):\n", " time.sleep(1)\n", " image = np.random.random((600, 600, 3))\n", " images.append(image)\n", " yield image, gr.Image(visible=False)\n", " \n", " time.sleep(1)\n", " image = \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\" \n", " images.append(image)\n", " gif_path = create_gif(images)\n", " \n", " yield image, gr.Image(value=gif_path, visible=True)\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, \n", " inputs=gr.Slider(1, 10, 3), \n", " outputs=[\"image\", gr.Image(label=\"All Images\", visible=False)])\n", "demo.queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|
demos/fake_diffusion_with_gif/run.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import time
|
4 |
+
import os
|
5 |
+
from PIL import Image
|
6 |
+
import requests
|
7 |
+
from io import BytesIO
|
8 |
+
|
9 |
+
|
10 |
+
def create_gif(images):
|
11 |
+
pil_images = []
|
12 |
+
for image in images:
|
13 |
+
if isinstance(image, str):
|
14 |
+
response = requests.get(image)
|
15 |
+
image = Image.open(BytesIO(response.content))
|
16 |
+
else:
|
17 |
+
image = Image.fromarray((image * 255).astype(np.uint8))
|
18 |
+
pil_images.append(image)
|
19 |
+
fp_out = os.path.join(os.path.dirname(__file__), "image.gif")
|
20 |
+
img = pil_images.pop(0)
|
21 |
+
img.save(fp=fp_out, format='GIF', append_images=pil_images,
|
22 |
+
save_all=True, duration=400, loop=0)
|
23 |
+
return fp_out
|
24 |
+
|
25 |
+
|
26 |
+
def fake_diffusion(steps):
|
27 |
+
images = []
|
28 |
+
for _ in range(steps):
|
29 |
+
time.sleep(1)
|
30 |
+
image = np.random.random((600, 600, 3))
|
31 |
+
images.append(image)
|
32 |
+
yield image, gr.Image(visible=False)
|
33 |
+
|
34 |
+
time.sleep(1)
|
35 |
+
image = "https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg"
|
36 |
+
images.append(image)
|
37 |
+
gif_path = create_gif(images)
|
38 |
+
|
39 |
+
yield image, gr.Image(value=gif_path, visible=True)
|
40 |
+
|
41 |
+
|
42 |
+
demo = gr.Interface(fake_diffusion,
|
43 |
+
inputs=gr.Slider(1, 10, 3),
|
44 |
+
outputs=["image", gr.Image(label="All Images", visible=False)])
|
45 |
+
demo.queue()
|
46 |
+
|
47 |
+
if __name__ == "__main__":
|
48 |
+
demo.launch()
|
demos/fake_gan/DESCRIPTION.md
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/
|
demos/fake_gan/files/cheetah1.jpg
ADDED
demos/fake_gan/run.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan\n", "### This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " images = [\n", " (random.choice(\n", " [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " \"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80\",\n", " ]\n", " ), f\"label {i}\" if i != 0 else \"label\" * 50)\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column(variant=\"panel\"):\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\", scale=0)\n", "\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " , columns=[2], rows=[2], object_fit=\"contain\", height=\"auto\")\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
|