gradio-pr-bot commited on
Commit
4c608fe
1 Parent(s): f06d440

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. README.md +5 -6
  3. app.py +52 -0
  4. demos/altair_plot/requirements.txt +2 -0
  5. demos/altair_plot/run.ipynb +1 -0
  6. demos/altair_plot/run.py +140 -0
  7. demos/audio_debugger/cantina.wav +0 -0
  8. demos/audio_debugger/run.ipynb +1 -0
  9. demos/audio_debugger/run.py +40 -0
  10. demos/blocks_essay/run.ipynb +1 -0
  11. demos/blocks_essay/run.py +56 -0
  12. demos/blocks_group/run.ipynb +1 -0
  13. demos/blocks_group/run.py +113 -0
  14. demos/blocks_js_methods/run.ipynb +1 -0
  15. demos/blocks_js_methods/run.py +41 -0
  16. demos/blocks_layout/run.ipynb +1 -0
  17. demos/blocks_layout/run.py +39 -0
  18. demos/blocks_multiple_event_triggers/requirements.txt +2 -0
  19. demos/blocks_multiple_event_triggers/run.ipynb +1 -0
  20. demos/blocks_multiple_event_triggers/run.py +39 -0
  21. demos/blocks_update/run.ipynb +1 -0
  22. demos/blocks_update/run.py +46 -0
  23. demos/calculator/examples/log.csv +0 -0
  24. demos/calculator/run.ipynb +1 -0
  25. demos/calculator/run.py +35 -0
  26. demos/calculator/screenshot.gif +3 -0
  27. demos/cancel_events/run.ipynb +1 -0
  28. demos/cancel_events/run.py +57 -0
  29. demos/chatbot_multimodal/files/avatar.png +0 -0
  30. demos/chatbot_multimodal/files/lion.jpg +0 -0
  31. demos/chatbot_multimodal/run.ipynb +1 -0
  32. demos/chatbot_multimodal/run.py +43 -0
  33. demos/chatinterface_streaming_echo/run.ipynb +1 -0
  34. demos/chatinterface_streaming_echo/run.py +14 -0
  35. demos/clear_components/__init__.py +0 -0
  36. demos/clear_components/run.ipynb +1 -0
  37. demos/clear_components/run.py +183 -0
  38. demos/code/file.css +11 -0
  39. demos/code/run.ipynb +1 -0
  40. demos/code/run.py +43 -0
  41. demos/fake_diffusion_with_gif/run.ipynb +1 -0
  42. demos/fake_diffusion_with_gif/run.py +49 -0
  43. demos/fake_gan/DESCRIPTION.md +1 -0
  44. demos/fake_gan/run.ipynb +1 -0
  45. demos/fake_gan/run.py +33 -0
  46. demos/file_explorer_component_events/dir1/bar.txt +0 -0
  47. demos/file_explorer_component_events/dir1/foo.txt +0 -0
  48. demos/file_explorer_component_events/dir2/baz.png +0 -0
  49. demos/file_explorer_component_events/dir2/foo.png +0 -0
  50. demos/file_explorer_component_events/dir3/dir3_bar.log +0 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ 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/kitchen_sink/files/world.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ demos/video_component/files/world.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,11 @@
 
1
  ---
2
- title: Pr 8407 All Demos
3
- emoji: 🌖
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.31.5
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-8407-all-demos
4
+ emoji: 💩
5
+ colorFrom: indigo
6
+ colorTo: indigo
7
  sdk: gradio
8
  sdk_version: 4.31.5
9
  app_file: app.py
10
  pinned: false
11
  ---
 
 
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import gradio as gr
3
+ import os
4
+ import sys
5
+ import copy
6
+ import pathlib
7
+ from fastapi import FastAPI, Request
8
+ from fastapi.templating import Jinja2Templates
9
+ import uvicorn
10
+ from gradio.utils import get_space
11
+
12
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
13
+
14
+ demo_dir = pathlib.Path(__file__).parent / "demos"
15
+
16
+
17
+ app = FastAPI()
18
+
19
+ templates = Jinja2Templates(directory="templates")
20
+
21
+ names = sorted(os.listdir("./demos"))
22
+
23
+
24
+ @app.get("/")
25
+ def index(request: Request):
26
+ names = [[p[0], p[2]] for p in all_demos]
27
+ return templates.TemplateResponse("index.html", {"request": request, "names": names,
28
+ "initial_demo": names[0][0], "is_space": get_space()})
29
+
30
+
31
+ all_demos = []
32
+ demo_module = None
33
+ for p in sorted(os.listdir("./demos")):
34
+ old_path = copy.deepcopy(sys.path)
35
+ sys.path = [os.path.join(demo_dir, p)] + sys.path
36
+ try: # Some demos may not be runnable because of 429 timeouts, etc.
37
+ if demo_module is None:
38
+ demo_module = importlib.import_module(f"run")
39
+ else:
40
+ demo_module = importlib.reload(demo_module)
41
+ all_demos.append((p, demo_module.demo.queue(), False))
42
+ except Exception as e:
43
+ with gr.Blocks() as demo:
44
+ gr.Markdown(f"Error loading demo: {e}")
45
+ all_demos.append((p, demo, True))
46
+
47
+ for demo_name, demo, _ in all_demos:
48
+ app = gr.mount_gradio_app(app, demo, f"/demo/{demo_name}")
49
+
50
+
51
+ if __name__ == "__main__":
52
+ uvicorn.run(app, port=7860, host="0.0.0.0")
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(\n", " lambda x: x, \"audio\", \"audio\", examples=[audio_file], cache_examples=True\n", " )\n", " with gr.Tab(\"Streaming\"):\n", " gr.Interface(\n", " lambda x: x,\n", " gr.Audio(streaming=True),\n", " \"audio\",\n", " examples=[audio_file],\n", " cache_examples=True,\n", " )\n", " with gr.Tab(\"console\"):\n", " ip = gr.Textbox(label=\"User IP Address\")\n", " gr.Interface(\n", " lambda cmd: subprocess.run([cmd], capture_output=True, shell=True)\n", " .stdout.decode(\"utf-8\")\n", " .strip(),\n", " \"text\",\n", " \"text\",\n", " )\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,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
13
+ lambda x: x, "audio", "audio", examples=[audio_file], cache_examples=True
14
+ )
15
+ with gr.Tab("Streaming"):
16
+ gr.Interface(
17
+ lambda x: x,
18
+ gr.Audio(streaming=True),
19
+ "audio",
20
+ examples=[audio_file],
21
+ cache_examples=True,
22
+ )
23
+ with gr.Tab("console"):
24
+ ip = gr.Textbox(label="User IP Address")
25
+ gr.Interface(
26
+ lambda cmd: subprocess.run([cmd], capture_output=True, shell=True)
27
+ .stdout.decode("utf-8")
28
+ .strip(),
29
+ "text",
30
+ "text",
31
+ )
32
+
33
+ def get_ip(request: gr.Request):
34
+ return request.client.host
35
+
36
+ demo.load(get_ip, None, ip)
37
+
38
+ if __name__ == "__main__":
39
+ demo.queue()
40
+ 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", "countries_cities_dict = {\n", " \"USA\": [\"New York\", \"Los Angeles\", \"Chicago\"],\n", " \"Canada\": [\"Toronto\", \"Montreal\", \"Vancouver\"],\n", " \"Pakistan\": [\"Karachi\", \"Lahore\", \"Islamabad\"],\n", "}\n", "\n", "\n", "def change_textbox(choice):\n", " if choice == \"short\":\n", " return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\"), gr.Button(interactive=True)\n", " else:\n", " return gr.Textbox(visible=False), gr.Button(interactive=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", "\n", " with gr.Row():\n", " num = gr.Number(minimum=0, maximum=100, label=\"input\")\n", " out = gr.Number(label=\"output\")\n", " minimum_slider = gr.Slider(0, 100, 0, label=\"min\")\n", " maximum_slider = gr.Slider(0, 100, 100, label=\"max\")\n", " submit_btn = gr.Button(\"Submit\", variant=\"primary\")\n", "\n", " with gr.Row():\n", " country = gr.Dropdown(list(countries_cities_dict.keys()), label=\"Country\")\n", " cities = gr.Dropdown([], label=\"Cities\")\n", " \n", " @country.change(inputs=country, outputs=cities)\n", " def update_cities(country):\n", " cities = list(countries_cities_dict[country])\n", " return gr.Dropdown(choices=cities, value=cities[0], interactive=True)\n", "\n", " def reset_bounds(minimum, maximum):\n", " return gr.Number(minimum=minimum, maximum=maximum)\n", "\n", " radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn])\n", " gr.on(\n", " [minimum_slider.change, maximum_slider.change],\n", " reset_bounds,\n", " [minimum_slider, maximum_slider],\n", " outputs=num,\n", " )\n", " num.submit(lambda x: x, num, out)\n", "\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,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ countries_cities_dict = {
4
+ "USA": ["New York", "Los Angeles", "Chicago"],
5
+ "Canada": ["Toronto", "Montreal", "Vancouver"],
6
+ "Pakistan": ["Karachi", "Lahore", "Islamabad"],
7
+ }
8
+
9
+
10
+ def change_textbox(choice):
11
+ if choice == "short":
12
+ return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True)
13
+ elif choice == "long":
14
+ return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True)
15
+ else:
16
+ return gr.Textbox(visible=False), gr.Button(interactive=False)
17
+
18
+
19
+ with gr.Blocks() as demo:
20
+ radio = gr.Radio(
21
+ ["short", "long", "none"], label="What kind of essay would you like to write?"
22
+ )
23
+ text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)
24
+
25
+ with gr.Row():
26
+ num = gr.Number(minimum=0, maximum=100, label="input")
27
+ out = gr.Number(label="output")
28
+ minimum_slider = gr.Slider(0, 100, 0, label="min")
29
+ maximum_slider = gr.Slider(0, 100, 100, label="max")
30
+ submit_btn = gr.Button("Submit", variant="primary")
31
+
32
+ with gr.Row():
33
+ country = gr.Dropdown(list(countries_cities_dict.keys()), label="Country")
34
+ cities = gr.Dropdown([], label="Cities")
35
+
36
+ @country.change(inputs=country, outputs=cities)
37
+ def update_cities(country):
38
+ cities = list(countries_cities_dict[country])
39
+ return gr.Dropdown(choices=cities, value=cities[0], interactive=True)
40
+
41
+ def reset_bounds(minimum, maximum):
42
+ return gr.Number(minimum=minimum, maximum=maximum)
43
+
44
+ radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn])
45
+ gr.on(
46
+ [minimum_slider.change, maximum_slider.change],
47
+ reset_bounds,
48
+ [minimum_slider, maximum_slider],
49
+ outputs=num,
50
+ )
51
+ num.submit(lambda x: x, num, out)
52
+
53
+
54
+
55
+ if __name__ == "__main__":
56
+ 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_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

  • SHA256: 3698fb03b6507ff954de47559f6830dfff88aa66487d2029a9bcf1c2f3762e08
  • Pointer size: 132 Bytes
  • Size of remote file: 5.72 MB
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", "import atexit\n", "import pathlib\n", "\n", "log_file = (pathlib.Path(__file__).parent / \"cancel_events_output_log.txt\").resolve()\n", "\n", "def fake_diffusion(steps):\n", " log_file.write_text(\"\")\n", " for i in range(steps):\n", " print(f\"Current step: {i}\")\n", " with log_file.open(\"a\") as f:\n", " f.write(f\"Current step: {i}\\n\")\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(sources=[\"webcam\"], label=\"Cancel on clear\", interactive=True)\n", " with gr.Column():\n", " video = gr.Video(sources=[\"webcam\"], label=\"Cancel on start recording\", 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.clear(None, None, None, cancels=[click_event, pred_event])\n", " video.start_recording(None, None, None, cancels=[click_event, pred_event])\n", "\n", " demo.queue(max_size=20)\n", " atexit.register(lambda: log_file.unlink())\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
demos/cancel_events/run.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import gradio as gr
3
+ import atexit
4
+ import pathlib
5
+
6
+ log_file = (pathlib.Path(__file__).parent / "cancel_events_output_log.txt").resolve()
7
+
8
+ def fake_diffusion(steps):
9
+ log_file.write_text("")
10
+ for i in range(steps):
11
+ print(f"Current step: {i}")
12
+ with log_file.open("a") as f:
13
+ f.write(f"Current step: {i}\n")
14
+ time.sleep(0.2)
15
+ yield str(i)
16
+
17
+
18
+ def long_prediction(*args, **kwargs):
19
+ time.sleep(10)
20
+ return 42
21
+
22
+
23
+ with gr.Blocks() as demo:
24
+ with gr.Row():
25
+ with gr.Column():
26
+ n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
27
+ run = gr.Button(value="Start Iterating")
28
+ output = gr.Textbox(label="Iterative Output")
29
+ stop = gr.Button(value="Stop Iterating")
30
+ with gr.Column():
31
+ textbox = gr.Textbox(label="Prompt")
32
+ prediction = gr.Number(label="Expensive Calculation")
33
+ run_pred = gr.Button(value="Run Expensive Calculation")
34
+ with gr.Column():
35
+ cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")
36
+ cancel_on_submit = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Submit")
37
+ echo = gr.Textbox(label="Echo")
38
+ with gr.Row():
39
+ with gr.Column():
40
+ image = gr.Image(sources=["webcam"], label="Cancel on clear", interactive=True)
41
+ with gr.Column():
42
+ video = gr.Video(sources=["webcam"], label="Cancel on start recording", interactive=True)
43
+
44
+ click_event = run.click(fake_diffusion, n, output)
45
+ stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
46
+ pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)
47
+
48
+ cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])
49
+ cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])
50
+ image.clear(None, None, None, cancels=[click_event, pred_event])
51
+ video.start_recording(None, None, None, cancels=[click_event, pred_event])
52
+
53
+ demo.queue(max_size=20)
54
+ atexit.register(lambda: log_file.unlink())
55
+
56
+ if __name__ == "__main__":
57
+ demo.launch()
demos/chatbot_multimodal/files/avatar.png ADDED
demos/chatbot_multimodal/files/lion.jpg 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", "os.mkdir('files')\n", "!wget -q -O files/avatar.png https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/files/avatar.png\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/files/lion.jpg"]}, {"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 print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append(((x,), None))\n", " if message[\"text\"] is not None:\n", " history.append((message[\"text\"], None))\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False\n", " )\n", "\n", " chat_input = gr.MultimodalTextbox(interactive=True, file_types=[\"image\"], placeholder=\"Enter message or upload file...\", show_label=False)\n", "\n", " chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])\n", " bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name=\"bot_response\")\n", " bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])\n", "\n", " chatbot.like(print_like_dislike, None, None)\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,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 print_like_dislike(x: gr.LikeData):
9
+ print(x.index, x.value, x.liked)
10
+
11
+ def add_message(history, message):
12
+ for x in message["files"]:
13
+ history.append(((x,), None))
14
+ if message["text"] is not None:
15
+ history.append((message["text"], None))
16
+ return history, gr.MultimodalTextbox(value=None, interactive=False)
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
+ with gr.Blocks() as demo:
27
+ chatbot = gr.Chatbot(
28
+ [],
29
+ elem_id="chatbot",
30
+ bubble_full_width=False
31
+ )
32
+
33
+ chat_input = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message or upload file...", show_label=False)
34
+
35
+ chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
36
+ bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response")
37
+ bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
38
+
39
+ chatbot.like(print_like_dislike, None, None)
40
+
41
+ demo.queue()
42
+ if __name__ == "__main__":
43
+ 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", "\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", "\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,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import gradio as gr
3
+
4
+
5
+ def slow_echo(message, history):
6
+ for i in range(len(message)):
7
+ time.sleep(0.05)
8
+ yield "You typed: " + message[: i + 1]
9
+
10
+
11
+ demo = gr.ChatInterface(slow_echo).queue()
12
+
13
+ if __name__ == "__main__":
14
+ 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", " clear_button_and_components = components + [clear]\n", " hide.click(\n", " lambda: [c.__class__(visible=False) for c in clear_button_and_components],\n", " inputs=[],\n", " outputs=clear_button_and_components\n", " )\n", " reveal.click(\n", " lambda: [c.__class__(visible=True) for c in clear_button_and_components],\n", " inputs=[],\n", " outputs=clear_button_and_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,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ clear_button_and_components = components + [clear]
168
+ hide.click(
169
+ lambda: [c.__class__(visible=False) for c in clear_button_and_components],
170
+ inputs=[],
171
+ outputs=clear_button_and_components
172
+ )
173
+ reveal.click(
174
+ lambda: [c.__class__(visible=True) for c in clear_button_and_components],
175
+ inputs=[],
176
+ outputs=clear_button_and_components
177
+ )
178
+ get_value = gr.Button(value="Get Values")
179
+ get_value.click(evaluate_values, components, result)
180
+
181
+
182
+ if __name__ == "__main__":
183
+ 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/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": ["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", " rng = np.random.default_rng()\n", " images = []\n", " for _ in range(steps):\n", " time.sleep(1)\n", " image = rng.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, step=1),\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,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ rng = np.random.default_rng()
28
+ images = []
29
+ for _ in range(steps):
30
+ time.sleep(1)
31
+ image = rng.random((600, 600, 3))
32
+ images.append(image)
33
+ yield image, gr.Image(visible=False)
34
+
35
+ time.sleep(1)
36
+ image = "https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg"
37
+ images.append(image)
38
+ gif_path = create_gif(images)
39
+
40
+ yield image, gr.Image(value=gif_path, visible=True)
41
+
42
+
43
+ demo = gr.Interface(fake_diffusion,
44
+ inputs=gr.Slider(1, 10, 3, step=1),
45
+ outputs=["image", gr.Image(label="All Images", visible=False)])
46
+ demo.queue()
47
+
48
+ if __name__ == "__main__":
49
+ 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/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": ["# 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", " \"http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg\",\n", " \"http://www.marketingtool.online/en/face-generator/img/faces/avatar-116b5e92936b766b7fdfc242649337f7.jpg\",\n", " \"http://www.marketingtool.online/en/face-generator/img/faces/avatar-1163530ca19b5cebe1b002b8ec67b6fc.jpg\",\n", " \"http://www.marketingtool.online/en/face-generator/img/faces/avatar-1116395d6e6a6581eef8b8038f4c8e55.jpg\",\n", " \"http://www.marketingtool.online/en/face-generator/img/faces/avatar-11319be65db395d0e8e6855d18ddcef0.jpg\",\n", " ]\n", " ), f\"label {i}\")\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " , columns=[3], rows=[1], object_fit=\"contain\", height=\"auto\")\n", " btn = gr.Button(\"Generate images\", scale=0)\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
demos/fake_gan/run.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This demo needs to be run from the repo folder.
2
+ # python demo/fake_gan/run.py
3
+ import random
4
+
5
+ import gradio as gr
6
+
7
+
8
+ def fake_gan():
9
+ images = [
10
+ (random.choice(
11
+ [
12
+ "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg",
13
+ "http://www.marketingtool.online/en/face-generator/img/faces/avatar-116b5e92936b766b7fdfc242649337f7.jpg",
14
+ "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1163530ca19b5cebe1b002b8ec67b6fc.jpg",
15
+ "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1116395d6e6a6581eef8b8038f4c8e55.jpg",
16
+ "http://www.marketingtool.online/en/face-generator/img/faces/avatar-11319be65db395d0e8e6855d18ddcef0.jpg",
17
+ ]
18
+ ), f"label {i}")
19
+ for i in range(3)
20
+ ]
21
+ return images
22
+
23
+
24
+ with gr.Blocks() as demo:
25
+ gallery = gr.Gallery(
26
+ label="Generated images", show_label=False, elem_id="gallery"
27
+ , columns=[3], rows=[1], object_fit="contain", height="auto")
28
+ btn = gr.Button("Generate images", scale=0)
29
+
30
+ btn.click(fake_gan, None, gallery)
31
+
32
+ if __name__ == "__main__":
33
+ demo.launch()
demos/file_explorer_component_events/dir1/bar.txt ADDED
File without changes
demos/file_explorer_component_events/dir1/foo.txt ADDED
File without changes
demos/file_explorer_component_events/dir2/baz.png ADDED
demos/file_explorer_component_events/dir2/foo.png ADDED
demos/file_explorer_component_events/dir3/dir3_bar.log ADDED
File without changes