diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..4d2b05a547adbc1c08e62fc38f450c623645cc37 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +demos/calculator/screenshot.gif filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 6e8b67fda2331f62b3e022dd6091fd381dc16c98..dc5d6a2f03082d3769682f267ceebb412d650014 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,11 @@ + --- -title: Pr 9811 All Demos -emoji: 😻 -colorFrom: yellow -colorTo: yellow +title: pr-9811-all-demos +emoji: 💩 +colorFrom: indigo +colorTo: indigo sdk: gradio sdk_version: 5.3.0 -app_file: app.py +app_file: run.py pinned: false --- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/demos/audio_debugger/cantina.wav b/demos/audio_debugger/cantina.wav new file mode 100644 index 0000000000000000000000000000000000000000..41f020438468229763ec4a2321325e5916e09106 Binary files /dev/null and b/demos/audio_debugger/cantina.wav differ diff --git a/demos/audio_debugger/run.ipynb b/demos/audio_debugger/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..208af9aed8213849ec5b2470d481042b76fe3b79 --- /dev/null +++ b/demos/audio_debugger/run.ipynb @@ -0,0 +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", "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, check=False)\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.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/audio_debugger/run.py b/demos/audio_debugger/run.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4b04d2d72836f1898fea483b11e1672acaecc7 --- /dev/null +++ b/demos/audio_debugger/run.py @@ -0,0 +1,38 @@ +import gradio as gr +import subprocess +import os + +audio_file = os.path.join(os.path.dirname(__file__), "cantina.wav") + +with gr.Blocks() as demo: + with gr.Tab("Audio"): + gr.Audio(audio_file) + with gr.Tab("Interface"): + gr.Interface( + lambda x: x, "audio", "audio", examples=[audio_file], cache_examples=True + ) + with gr.Tab("Streaming"): + gr.Interface( + lambda x: x, + gr.Audio(streaming=True), + "audio", + examples=[audio_file], + cache_examples=True, + ) + with gr.Tab("console"): + ip = gr.Textbox(label="User IP Address") + gr.Interface( + lambda cmd: subprocess.run([cmd], capture_output=True, shell=True, check=False) + .stdout.decode("utf-8") + .strip(), + "text", + "text", + ) + + def get_ip(request: gr.Request): + return request.client.host + + demo.load(get_ip, None, ip) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_essay/run.ipynb b/demos/blocks_essay/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8878ec76a8de8534413e83ba5c0908d3f70a11d2 --- /dev/null +++ b/demos/blocks_essay/run.ipynb @@ -0,0 +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", "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", "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", " @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", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/blocks_essay/run.py b/demos/blocks_essay/run.py new file mode 100644 index 0000000000000000000000000000000000000000..f06f10a88f7fd41125ec78e0eccd01c71ee394cf --- /dev/null +++ b/demos/blocks_essay/run.py @@ -0,0 +1,51 @@ +import gradio as gr + +countries_cities_dict = { + "USA": ["New York", "Los Angeles", "Chicago"], + "Canada": ["Toronto", "Montreal", "Vancouver"], + "Pakistan": ["Karachi", "Lahore", "Islamabad"], +} + +def change_textbox(choice): + if choice == "short": + return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True) + elif choice == "long": + return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True) + else: + return gr.Textbox(visible=False), gr.Button(interactive=False) + +with gr.Blocks() as demo: + radio = gr.Radio( + ["short", "long", "none"], label="What kind of essay would you like to write?" + ) + text = gr.Textbox(lines=2, interactive=True, show_copy_button=True) + + with gr.Row(): + num = gr.Number(minimum=0, maximum=100, label="input") + out = gr.Number(label="output") + minimum_slider = gr.Slider(0, 100, 0, label="min") + maximum_slider = gr.Slider(0, 100, 100, label="max") + submit_btn = gr.Button("Submit", variant="primary") + + with gr.Row(): + country = gr.Dropdown(list(countries_cities_dict.keys()), label="Country") + cities = gr.Dropdown([], label="Cities") + @country.change(inputs=country, outputs=cities) + def update_cities(country): + cities = list(countries_cities_dict[country]) + return gr.Dropdown(choices=cities, value=cities[0], interactive=True) + + def reset_bounds(minimum, maximum): + return gr.Number(minimum=minimum, maximum=maximum) + + radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn]) + gr.on( + [minimum_slider.change, maximum_slider.change], + reset_bounds, + [minimum_slider, maximum_slider], + outputs=num, + ) + num.submit(lambda x: x, num, out) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_group/run.ipynb b/demos/blocks_group/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f8b5f935659b9ba4e63e4cead1f1ef7bf46c68eb --- /dev/null +++ b/demos/blocks_group/run.ipynb @@ -0,0 +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", " 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", " 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", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/blocks_group/run.py b/demos/blocks_group/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b91d4bc5c71fe2c389fd3a4f8b1fbce1ab5b8c8a --- /dev/null +++ b/demos/blocks_group/run.py @@ -0,0 +1,110 @@ +import gradio as gr + +def greet(name): + return "Hello " + name + "!" + +with gr.Blocks() as demo: + gr.Markdown("### This is a couple of elements without any gr.Group. Form elements naturally group together anyway.") + gr.Textbox("A") + gr.Number(3) + gr.Button() + gr.Image() + gr.Slider() + + gr.Markdown("### This is the same set put in a gr.Group.") + with gr.Group(): + gr.Textbox("A") + gr.Number(3) + gr.Button() + gr.Image() + gr.Slider() + + gr.Markdown("### Now in a Row, no group.") + with gr.Row(): + gr.Textbox("A") + gr.Number(3) + gr.Button() + gr.Image() + gr.Slider() + + gr.Markdown("### Now in a Row in a group.") + with gr.Group(): + with gr.Row(): + gr.Textbox("A") + gr.Number(3) + gr.Button() + gr.Image() + gr.Slider() + + gr.Markdown("### Several rows grouped together.") + with gr.Group(): + with gr.Row(): + gr.Textbox("A") + gr.Number(3) + gr.Button() + with gr.Row(): + gr.Image() + gr.Audio() + + gr.Markdown("### Several columns grouped together. If columns are uneven, there is a gray group background.") + with gr.Group(): + with gr.Row(): + with gr.Column(): + name = gr.Textbox(label="Name") + btn = gr.Button("Hello") + gr.Dropdown(["a", "b", "c"], interactive=True) + gr.Number() + gr.Textbox() + with gr.Column(): + gr.Image() + gr.Dropdown(["a", "b", "c"], interactive=True) + with gr.Row(): + gr.Number(scale=2) + gr.Textbox() + + gr.Markdown("### container=False removes label, padding, and block border, placing elements 'directly' on background.") + gr.Radio([1,2,3], container=False) + gr.Textbox(container=False) + gr.Image("https://picsum.photos/id/237/200/300", container=False, height=200) + + gr.Markdown("### Textbox, Dropdown, and Number input boxes takes up full space when within a group without a container.") + + with gr.Group(): + name = gr.Textbox(label="Name") + output = gr.Textbox(show_label=False, container=False) + greet_btn = gr.Button("Greet") + with gr.Row(): + gr.Dropdown(["a", "b", "c"], interactive=True, container=False) + gr.Textbox(container=False) + gr.Number(container=False) + gr.Image(height=100) + greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet") + + gr.Markdown("### More examples") + + with gr.Group(): + gr.Chatbot() + with gr.Row(): + name = gr.Textbox(label="Prompot", container=False) + go = gr.Button("go", scale=0) + + with gr.Column(): + gr.Radio([1,2,3], container=False) + gr.Slider(0, 20, container=False) + + with gr.Group(): + with gr.Row(): + gr.Dropdown(["a", "b", "c"], interactive=True, container=False, elem_id="here2") + gr.Number(container=False) + gr.Textbox(container=False) + + with gr.Row(): + with gr.Column(): + gr.Dropdown(["a", "b", "c"], interactive=True, container=False, elem_id="here2") + with gr.Column(): + gr.Number(container=False) + with gr.Column(): + gr.Textbox(container=False) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_js_methods/run.ipynb b/demos/blocks_js_methods/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1a5195c09b6de1ce5d3510e0a47eb1d1aa1e1d65 --- /dev/null +++ b/demos/blocks_js_methods/run.ipynb @@ -0,0 +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} \ No newline at end of file diff --git a/demos/blocks_js_methods/run.py b/demos/blocks_js_methods/run.py new file mode 100644 index 0000000000000000000000000000000000000000..2abb2d9d3bca4114009da9ae61ef1ebfc347da81 --- /dev/null +++ b/demos/blocks_js_methods/run.py @@ -0,0 +1,41 @@ +import gradio as gr + +blocks = gr.Blocks() + +with blocks as demo: + subject = gr.Textbox(placeholder="subject") + verb = gr.Radio(["ate", "loved", "hated"]) + object = gr.Textbox(placeholder="object") + + with gr.Row(): + btn = gr.Button("Create sentence.") + reverse_btn = gr.Button("Reverse sentence.") + foo_bar_btn = gr.Button("Append foo") + reverse_then_to_the_server_btn = gr.Button( + "Reverse sentence and send to server." + ) + + def sentence_maker(w1, w2, w3): + return f"{w1} {w2} {w3}" + + output1 = gr.Textbox(label="output 1") + output2 = gr.Textbox(label="verb") + output3 = gr.Textbox(label="verb reversed") + output4 = gr.Textbox(label="front end process and then send to backend") + + btn.click(sentence_maker, [subject, verb, object], output1) + reverse_btn.click( + None, [subject, verb, object], output2, js="(s, v, o) => o + ' ' + v + ' ' + s" + ) + verb.change(lambda x: x, verb, output3, js="(x) => [...x].reverse().join('')") + foo_bar_btn.click(None, [], subject, js="(x) => x + ' foo'") + + reverse_then_to_the_server_btn.click( + sentence_maker, + [subject, verb, object], + output4, + js="(s, v, o) => [s, v, o].map(x => [...x].reverse().join(''))", + ) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_layout/run.ipynb b/demos/blocks_layout/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a3ea74271df38babdd0d24e3cdf437d6aafc9bbd --- /dev/null +++ b/demos/blocks_layout/run.ipynb @@ -0,0 +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", "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", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/blocks_layout/run.py b/demos/blocks_layout/run.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7686f4bbec3db5cd2e660f7bec095989680084 --- /dev/null +++ b/demos/blocks_layout/run.py @@ -0,0 +1,37 @@ +import gradio as gr + +demo = gr.Blocks() + +with demo: + with gr.Row(): + gr.Image(interactive=True, scale=2) + gr.Image() + with gr.Row(): + gr.Textbox(label="Text") + gr.Number(label="Count", scale=2) + gr.Radio(choices=["One", "Two"]) + with gr.Row(): + gr.Button("500", scale=0, min_width=500) + gr.Button("A", scale=0) + gr.Button("grow") + with gr.Row(): + gr.Textbox() + gr.Textbox() + gr.Button() + with gr.Row(): + with gr.Row(): + with gr.Column(): + gr.Textbox(label="Text") + gr.Number(label="Count") + gr.Radio(choices=["One", "Two"]) + gr.Image() + with gr.Column(): + gr.Image(interactive=True) + gr.Image() + gr.Image() + gr.Textbox(label="Text") + gr.Number(label="Count") + gr.Radio(choices=["One", "Two"]) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_multiple_event_triggers/requirements.txt b/demos/blocks_multiple_event_triggers/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbe82b5897e5e15186ae546be9dba1c38ea66873 --- /dev/null +++ b/demos/blocks_multiple_event_triggers/requirements.txt @@ -0,0 +1,3 @@ +plotly +pypistats +python-dateutil diff --git a/demos/blocks_multiple_event_triggers/run.ipynb b/demos/blocks_multiple_event_triggers/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ec9efcc3599a9f0258f71c87c637cc6c6b1c7375 --- /dev/null +++ b/demos/blocks_multiple_event_triggers/run.ipynb @@ -0,0 +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 python-dateutil "]}, {"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", "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} \ No newline at end of file diff --git a/demos/blocks_multiple_event_triggers/run.py b/demos/blocks_multiple_event_triggers/run.py new file mode 100644 index 0000000000000000000000000000000000000000..16eeda543eb9efd732809ff69045e28b7f6528af --- /dev/null +++ b/demos/blocks_multiple_event_triggers/run.py @@ -0,0 +1,38 @@ +import gradio as gr +import pypistats +from datetime import date +from dateutil.relativedelta import relativedelta +import pandas as pd + +def get_plot(lib, time): + data = pypistats.overall(lib, total=True, format="pandas") + data = data.groupby("category").get_group("with_mirrors").sort_values("date") + start_date = date.today() - relativedelta(months=int(time.split(" ")[0])) + data = data[(data['date'] > str(start_date))] + data.date = pd.to_datetime(pd.to_datetime(data.date)) + return gr.LinePlot(value=data, x="date", y="downloads", + tooltip=['date', 'downloads'], + title=f"Pypi downloads of {lib} over last {time}", + overlay_point=True, + height=400, + width=900) + +with gr.Blocks() as demo: + gr.Markdown( + """ + ## Pypi Download Stats 📈 + See live download stats for all of Hugging Face's open-source libraries 🤗 + """) + with gr.Row(): + lib = gr.Dropdown(["transformers", "datasets", "huggingface-hub", "gradio", "accelerate"], + value="gradio", label="Library") + time = gr.Dropdown(["3 months", "6 months", "9 months", "12 months"], + value="3 months", label="Downloads over the last...") + + plt = gr.LinePlot() + # You can add multiple event triggers in 2 lines like this + for event in [lib.change, time.change, demo.load]: + event(get_plot, [lib, time], [plt]) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/blocks_update/run.ipynb b/demos/blocks_update/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cd094c525fa4fe509a2f066f562c28e60e4fe00a --- /dev/null +++ b/demos/blocks_update/run.ipynb @@ -0,0 +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", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/blocks_update/run.py b/demos/blocks_update/run.py new file mode 100644 index 0000000000000000000000000000000000000000..03d4e5a6fd139e4ffc8c6d51673a3dd5d28aa7cb --- /dev/null +++ b/demos/blocks_update/run.py @@ -0,0 +1,45 @@ +import gradio as gr + +with gr.Blocks() as demo: + gr.Markdown( + """ + # Animal Generator + Once you select a species, the detail panel should be visible. + """ + ) + + species = gr.Radio(label="Animal Class", choices=["Mammal", "Fish", "Bird"]) + animal = gr.Dropdown(label="Animal", choices=[]) + + with gr.Column(visible=False) as details_col: + weight = gr.Slider(0, 20) + details = gr.Textbox(label="Extra Details") + generate_btn = gr.Button("Generate") + output = gr.Textbox(label="Output") + + species_map = { + "Mammal": ["Elephant", "Giraffe", "Hamster"], + "Fish": ["Shark", "Salmon", "Tuna"], + "Bird": ["Chicken", "Eagle", "Hawk"], + } + + def filter_species(species): + return gr.Dropdown( + choices=species_map[species], value=species_map[species][1] + ), gr.Column(visible=True) + + species.change(filter_species, species, [animal, details_col]) + + def filter_weight(animal): + if animal in ("Elephant", "Shark", "Giraffe"): + return gr.Slider(maximum=100) + else: + return gr.Slider(maximum=20) + + animal.change(filter_weight, animal, weight) + weight.change(lambda w: gr.Textbox(lines=int(w / 10) + 1), weight, details) + + generate_btn.click(lambda x: x, details, output) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/calculator/examples/log.csv b/demos/calculator/examples/log.csv new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/calculator/run.ipynb b/demos/calculator/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..31d7b700f5d71366141762a1d4d5744cf4cebbef --- /dev/null +++ b/demos/calculator/run.ipynb @@ -0,0 +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", "\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.\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/calculator/run.py b/demos/calculator/run.py new file mode 100644 index 0000000000000000000000000000000000000000..9883f44db9e432ca4624c7a39038fabaa08d22ab --- /dev/null +++ b/demos/calculator/run.py @@ -0,0 +1,34 @@ +import gradio as gr + +def calculator(num1, operation, num2): + if operation == "add": + return num1 + num2 + elif operation == "subtract": + return num1 - num2 + elif operation == "multiply": + return num1 * num2 + elif operation == "divide": + if num2 == 0: + raise gr.Error("Cannot divide by zero!") + return num1 / num2 + +demo = gr.Interface( + calculator, + [ + "number", + gr.Radio(["add", "subtract", "multiply", "divide"]), + "number" + ], + "number", + examples=[ + [45, "add", 3], + [3.14, "divide", 2], + [144, "multiply", 2.5], + [0, "subtract", 1.2], + ], + title="Toy Calculator", + description="Here's a sample toy calculator.", +) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/calculator/screenshot.gif b/demos/calculator/screenshot.gif new file mode 100644 index 0000000000000000000000000000000000000000..8ae0d0494adf069b4e23cf30956b43262258021c --- /dev/null +++ b/demos/calculator/screenshot.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3698fb03b6507ff954de47559f6830dfff88aa66487d2029a9bcf1c2f3762e08 +size 5718090 diff --git a/demos/cancel_events/run.ipynb b/demos/cancel_events/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..82e9c09d6b630bcb671733a2440c1c4c9ccafca6 --- /dev/null +++ b/demos/cancel_events/run.ipynb @@ -0,0 +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\"\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", "def long_prediction(*args, **kwargs):\n", " time.sleep(10)\n", " return 42\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(\n", " label=\"Cancel Iteration and Expensive Calculation on Change\"\n", " )\n", " cancel_on_submit = gr.Textbox(\n", " label=\"Cancel Iteration and Expensive Calculation on Submit\"\n", " )\n", " echo = gr.Textbox(label=\"Echo\")\n", " with gr.Row():\n", " with gr.Column():\n", " image = gr.Image(\n", " sources=[\"webcam\"], label=\"Cancel on clear\", interactive=True\n", " )\n", " with gr.Column():\n", " video = gr.Video(\n", " sources=[\"webcam\"], label=\"Cancel on start recording\", interactive=True\n", " )\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(\n", " fn=long_prediction, inputs=[textbox], outputs=prediction\n", " )\n", "\n", " cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])\n", " cancel_on_submit.submit(\n", " lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event]\n", " )\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} \ No newline at end of file diff --git a/demos/cancel_events/run.py b/demos/cancel_events/run.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c2f5700d89fcb00b92803e3c92628482d5f0fe --- /dev/null +++ b/demos/cancel_events/run.py @@ -0,0 +1,67 @@ +import time +import gradio as gr +import atexit +import pathlib + +log_file = pathlib.Path(__file__).parent / "cancel_events_output_log.txt" + +def fake_diffusion(steps): + log_file.write_text("") + for i in range(steps): + print(f"Current step: {i}") + with log_file.open("a") as f: + f.write(f"Current step: {i}\n") + time.sleep(0.2) + yield str(i) + +def long_prediction(*args, **kwargs): + time.sleep(10) + return 42 + +with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + n = gr.Slider(1, 10, value=9, step=1, label="Number Steps") + run = gr.Button(value="Start Iterating") + output = gr.Textbox(label="Iterative Output") + stop = gr.Button(value="Stop Iterating") + with gr.Column(): + textbox = gr.Textbox(label="Prompt") + prediction = gr.Number(label="Expensive Calculation") + run_pred = gr.Button(value="Run Expensive Calculation") + with gr.Column(): + cancel_on_change = gr.Textbox( + label="Cancel Iteration and Expensive Calculation on Change" + ) + cancel_on_submit = gr.Textbox( + label="Cancel Iteration and Expensive Calculation on Submit" + ) + echo = gr.Textbox(label="Echo") + with gr.Row(): + with gr.Column(): + image = gr.Image( + sources=["webcam"], label="Cancel on clear", interactive=True + ) + with gr.Column(): + video = gr.Video( + sources=["webcam"], label="Cancel on start recording", interactive=True + ) + + click_event = run.click(fake_diffusion, n, output) + stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event]) + pred_event = run_pred.click( + fn=long_prediction, inputs=[textbox], outputs=prediction + ) + + cancel_on_change.change(None, None, None, cancels=[click_event, pred_event]) + cancel_on_submit.submit( + lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event] + ) + image.clear(None, None, None, cancels=[click_event, pred_event]) + video.start_recording(None, None, None, cancels=[click_event, pred_event]) + + demo.queue(max_size=20) + atexit.register(lambda: log_file.unlink()) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/chatbot_multimodal/run.ipynb b/demos/chatbot_multimodal/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0299e0799d9e9dc46fd3b261b922a09179264a71 --- /dev/null +++ b/demos/chatbot_multimodal/run.ipynb @@ -0,0 +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/tuples_testcase.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\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", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append({\"role\": \"user\", \"content\": {\"path\": x}})\n", " if message[\"text\"] is not None:\n", " history.append({\"role\": \"user\", \"content\": message[\"text\"]})\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "\n", "def bot(history: list):\n", " response = \"**That's cool!**\"\n", " history.append({\"role\": \"assistant\", \"content\": \"\"})\n", " for character in response:\n", " history[-1][\"content\"] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(elem_id=\"chatbot\", bubble_full_width=False, type=\"messages\")\n", "\n", " chat_input = gr.MultimodalTextbox(\n", " interactive=True,\n", " file_count=\"multiple\",\n", " placeholder=\"Enter message or upload file...\",\n", " show_label=False,\n", " )\n", "\n", " chat_msg = chat_input.submit(\n", " add_message, [chatbot, chat_input], [chatbot, chat_input]\n", " )\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, like_user_message=True)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/chatbot_multimodal/run.py b/demos/chatbot_multimodal/run.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0cb18805246592c0872cc15c7ed7455dbc7a65 --- /dev/null +++ b/demos/chatbot_multimodal/run.py @@ -0,0 +1,47 @@ +import gradio as gr +import time + +# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. + + +def print_like_dislike(x: gr.LikeData): + print(x.index, x.value, x.liked) + + +def add_message(history, message): + for x in message["files"]: + history.append({"role": "user", "content": {"path": x}}) + if message["text"] is not None: + history.append({"role": "user", "content": message["text"]}) + return history, gr.MultimodalTextbox(value=None, interactive=False) + + +def bot(history: list): + response = "**That's cool!**" + history.append({"role": "assistant", "content": ""}) + for character in response: + history[-1]["content"] += character + time.sleep(0.05) + yield history + + +with gr.Blocks() as demo: + chatbot = gr.Chatbot(elem_id="chatbot", bubble_full_width=False, type="messages") + + chat_input = gr.MultimodalTextbox( + interactive=True, + file_count="multiple", + placeholder="Enter message or upload file...", + show_label=False, + ) + + chat_msg = chat_input.submit( + add_message, [chatbot, chat_input], [chatbot, chat_input] + ) + bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response") + bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) + + chatbot.like(print_like_dislike, None, None, like_user_message=True) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/chatbot_multimodal/tuples_testcase.py b/demos/chatbot_multimodal/tuples_testcase.py new file mode 100644 index 0000000000000000000000000000000000000000..c4919c5e9223bbdb630c17d1a0afe09b8787856e --- /dev/null +++ b/demos/chatbot_multimodal/tuples_testcase.py @@ -0,0 +1,46 @@ +import gradio as gr +import plotly.express as px + +# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. + +def random_plot(): + df = px.data.iris() + fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", + size='petal_length', hover_data=['petal_width']) + return fig + +def print_like_dislike(x: gr.LikeData): + print(x.index, x.value, x.liked) + +def add_message(history, message): + for x in message["files"]: + history.append(((x,), None)) + if message["text"] is not None: + history.append((message["text"], None)) + return history, gr.MultimodalTextbox(value=None, interactive=False) + +def bot(history): + history[-1][1] = "Cool!" + return history + +fig = random_plot() + +with gr.Blocks(fill_height=True) as demo: + chatbot = gr.Chatbot( + elem_id="chatbot", + bubble_full_width=False, + scale=1, + ) + + chat_input = gr.MultimodalTextbox(interactive=True, + file_count="multiple", + placeholder="Enter message or upload file...", show_label=False) + + chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input]) + bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response") + bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) + + chatbot.like(print_like_dislike, None, None) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/chatinterface_streaming_echo/run.ipynb b/demos/chatinterface_streaming_echo/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d077e6dcccf98d5aecc2a3241e8879adad82d154 --- /dev/null +++ b/demos/chatinterface_streaming_echo/run.ipynb @@ -0,0 +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, type=\"messages\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/chatinterface_streaming_echo/run.py b/demos/chatinterface_streaming_echo/run.py new file mode 100644 index 0000000000000000000000000000000000000000..6e87b7dcc0759273b1cd28304b5ef461634f85b3 --- /dev/null +++ b/demos/chatinterface_streaming_echo/run.py @@ -0,0 +1,12 @@ +import time +import gradio as gr + +def slow_echo(message, history): + for i in range(len(message)): + time.sleep(0.05) + yield "You typed: " + message[: i + 1] + +demo = gr.ChatInterface(slow_echo, type="messages") + +if __name__ == "__main__": + demo.launch() diff --git a/demos/clear_components/__init__.py b/demos/clear_components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/clear_components/requirements.txt b/demos/clear_components/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..402187013ab1e32605a006a01e169492b2329ad1 --- /dev/null +++ b/demos/clear_components/requirements.txt @@ -0,0 +1,3 @@ +numpy +pandas +matplotlib diff --git a/demos/clear_components/run.ipynb b/demos/clear_components/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a447c537a1b40a733e02f32a0e83a846f6b617c7 --- /dev/null +++ b/demos/clear_components/run.ipynb @@ -0,0 +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 numpy pandas matplotlib "]}, {"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", "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", "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", "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", "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\"]) # type: ignore\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", " '

I am red

',\n", " '

I am blue

',\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", "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()) # type: ignore\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", "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", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/clear_components/run.py b/demos/clear_components/run.py new file mode 100644 index 0000000000000000000000000000000000000000..3457e12c5c06f662a117214866e149f0c88358e4 --- /dev/null +++ b/demos/clear_components/run.py @@ -0,0 +1,174 @@ +import gradio as gr +from datetime import datetime +import os +import random +import string +import pandas as pd + +import numpy as np +import matplotlib.pyplot as plt + +def random_plot(): + start_year = 2020 + x = np.arange(start_year, start_year + 5) + year_count = x.shape[0] + plt_format = "-" + fig = plt.figure() + ax = fig.add_subplot(111) + series = np.arange(0, year_count, dtype=float) + series = series**2 + series += np.random.rand(year_count) + ax.plot(x, series, plt_format) + return fig + +images = [ + "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80", + "https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80", + "https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80", +] +file_dir = os.path.join(os.path.dirname(__file__), "..", "kitchen_sink", "files") +model3d_dir = os.path.join(os.path.dirname(__file__), "..", "model3D", "files") +highlighted_text_output_1 = [ + { + "entity": "I-LOC", + "score": 0.9988978, + "index": 2, + "word": "Chicago", + "start": 5, + "end": 12, + }, + { + "entity": "I-MISC", + "score": 0.9958592, + "index": 5, + "word": "Pakistani", + "start": 22, + "end": 31, + }, +] +highlighted_text_output_2 = [ + { + "entity": "I-LOC", + "score": 0.9988978, + "index": 2, + "word": "Chicago", + "start": 5, + "end": 12, + }, + { + "entity": "I-LOC", + "score": 0.9958592, + "index": 5, + "word": "Pakistan", + "start": 22, + "end": 30, + }, +] + +highlighted_text = "Does Chicago have any Pakistani restaurants" + +def random_model3d(): + model_3d = random.choice( + [os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != "source.txt"] + ) + return model_3d + +components = [ + gr.Textbox(value=lambda: datetime.now(), label="Current Time"), + gr.Number(value=lambda: random.random(), label="Random Percentage"), + gr.Slider(minimum=0, maximum=100, randomize=True, label="Slider with randomize"), + gr.Slider( + minimum=0, + maximum=1, + value=lambda: random.random(), + label="Slider with value func", + ), + gr.Checkbox(value=lambda: random.random() > 0.5, label="Random Checkbox"), + gr.CheckboxGroup( + choices=["a", "b", "c", "d"], + value=lambda: random.choice(["a", "b", "c", "d"]), + label="Random CheckboxGroup", + ), + gr.Radio( + choices=list(string.ascii_lowercase), + value=lambda: random.choice(string.ascii_lowercase), + ), + gr.Dropdown( + choices=["a", "b", "c", "d", "e"], + value=lambda: random.choice(["a", "b", "c"]), + ), + gr.Image( + value=lambda: random.choice(images) + ), + gr.Video(value=lambda: os.path.join(file_dir, "world.mp4")), + gr.Audio(value=lambda: os.path.join(file_dir, "cantina.wav")), + gr.File( + value=lambda: random.choice( + [os.path.join(file_dir, img) for img in os.listdir(file_dir)] + ) + ), + gr.Dataframe( + value=lambda: pd.DataFrame({"random_number_rows": range(5)}, columns=["one", "two", "three"]) # type: ignore + ), + gr.ColorPicker(value=lambda: random.choice(["#000000", "#ff0000", "#0000FF"])), + gr.Label(value=lambda: random.choice(["Pedestrian", "Car", "Cyclist"])), + gr.HighlightedText( + value=lambda: random.choice( + [ + {"text": highlighted_text, "entities": highlighted_text_output_1}, + {"text": highlighted_text, "entities": highlighted_text_output_2}, + ] + ), + ), + gr.JSON(value=lambda: random.choice([{"a": 1}, {"b": 2}])), + gr.HTML( + value=lambda: random.choice( + [ + '

I am red

', + '

I am blue

', + ] + ) + ), + gr.Gallery( + value=lambda: images + ), + gr.Model3D(value=random_model3d), + gr.Plot(value=random_plot), + gr.Markdown(value=lambda: f"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}"), +] + +def evaluate_values(*args): + are_false = [] + for a in args: + if isinstance(a, (pd.DataFrame, np.ndarray)): + are_false.append(not a.any().any()) # type: ignore + elif isinstance(a, str) and a.startswith("#"): + are_false.append(a == "#000000") + else: + are_false.append(not a) + return all(are_false) + +with gr.Blocks() as demo: + for i, component in enumerate(components): + component.label = f"component_{str(i).zfill(2)}" + component.render() + clear = gr.ClearButton(value="Clear", components=components) + result = gr.Textbox(label="Are all cleared?") + hide = gr.Button(value="Hide") + reveal = gr.Button(value="Reveal") + clear_button_and_components = components + [clear] + hide.click( + lambda: [c.__class__(visible=False) for c in clear_button_and_components], + inputs=[], + outputs=clear_button_and_components + ) + reveal.click( + lambda: [c.__class__(visible=True) for c in clear_button_and_components], + inputs=[], + outputs=clear_button_and_components + ) + get_value = gr.Button(value="Get Values") + get_value.click(evaluate_values, components, result) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/code/file.css b/demos/code/file.css new file mode 100644 index 0000000000000000000000000000000000000000..abc61b61cbb2045ad539bb1cc23c232a97aab8ee --- /dev/null +++ b/demos/code/file.css @@ -0,0 +1,11 @@ +.class { + color: blue; +} + +#id { + color: pink; +} + +div { + color: purple; +} \ No newline at end of file diff --git a/demos/code/run.ipynb b/demos/code/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e7daf42b04a66bf6a7504a7cc4c55032a3bc13c3 --- /dev/null +++ b/demos/code/run.ipynb @@ -0,0 +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", "css_file = os.path.join(os.path.abspath(''), \"file.css\")\n", "\n", "def set_lang(language):\n", " print(language)\n", " return gr.Code(language=language)\n", "\n", "def set_lang_from_path():\n", " sleep(1)\n", " return gr.Code(open(css_file).read(), language=\"css\")\n", "\n", "def code(language, code):\n", " return gr.Code(code, language=language)\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} \ No newline at end of file diff --git a/demos/code/run.py b/demos/code/run.py new file mode 100644 index 0000000000000000000000000000000000000000..03cbad845295d7982e583f7d5f2a270ad428d239 --- /dev/null +++ b/demos/code/run.py @@ -0,0 +1,38 @@ +import gradio as gr +import os +from time import sleep + +css_file = os.path.join(os.path.dirname(__file__), "file.css") + +def set_lang(language): + print(language) + return gr.Code(language=language) + +def set_lang_from_path(): + sleep(1) + return gr.Code(open(css_file).read(), language="css") + +def code(language, code): + return gr.Code(code, language=language) + +io = gr.Interface(lambda x: x, "code", "code") + +with gr.Blocks() as demo: + lang = gr.Dropdown(value="python", choices=gr.Code.languages) + with gr.Row(): + code_in = gr.Code( + language="python", + label="Input", + value='def all_odd_elements(sequence):\n """Returns every odd element of the sequence."""', + ) + code_out = gr.Code(label="Output") + btn = gr.Button("Run") + btn_two = gr.Button("Load File") + + lang.change(set_lang, inputs=lang, outputs=code_in) + btn.click(code, inputs=[lang, code_in], outputs=code_out) + btn_two.click(set_lang_from_path, inputs=None, outputs=code_out) + io.render() + +if __name__ == "__main__": + demo.launch() diff --git a/demos/fake_diffusion_with_gif/requirements.txt b/demos/fake_diffusion_with_gif/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6dd520b61558d16863e797ae41f66f3b96f234a1 --- /dev/null +++ b/demos/fake_diffusion_with_gif/requirements.txt @@ -0,0 +1,3 @@ +numpy +requests +Pillow diff --git a/demos/fake_diffusion_with_gif/run.ipynb b/demos/fake_diffusion_with_gif/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5f0600aff358d106bb5662f516d26e44fa0582ac --- /dev/null +++ b/demos/fake_diffusion_with_gif/run.ipynb @@ -0,0 +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 numpy requests Pillow "]}, {"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", "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", "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", "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", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demos/fake_diffusion_with_gif/run.py b/demos/fake_diffusion_with_gif/run.py new file mode 100644 index 0000000000000000000000000000000000000000..833686cf5c946ea573f4222256ac8dba4143d832 --- /dev/null +++ b/demos/fake_diffusion_with_gif/run.py @@ -0,0 +1,45 @@ +import gradio as gr +import numpy as np +import time +import os +from PIL import Image +import requests +from io import BytesIO + +def create_gif(images): + pil_images = [] + for image in images: + if isinstance(image, str): + response = requests.get(image) + image = Image.open(BytesIO(response.content)) + else: + image = Image.fromarray((image * 255).astype(np.uint8)) + pil_images.append(image) + fp_out = os.path.join(os.path.dirname(__file__), "image.gif") + img = pil_images.pop(0) + img.save(fp=fp_out, format='GIF', append_images=pil_images, + save_all=True, duration=400, loop=0) + return fp_out + +def fake_diffusion(steps): + rng = np.random.default_rng() + images = [] + for _ in range(steps): + time.sleep(1) + image = rng.random((600, 600, 3)) + images.append(image) + yield image, gr.Image(visible=False) + + time.sleep(1) + image = "https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg" + images.append(image) + gif_path = create_gif(images) + + yield image, gr.Image(value=gif_path, visible=True) + +demo = gr.Interface(fake_diffusion, + inputs=gr.Slider(1, 10, 3, step=1), + outputs=["image", gr.Image(label="All Images", visible=False)]) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/fake_gan/DESCRIPTION.md b/demos/fake_gan/DESCRIPTION.md new file mode 100644 index 0000000000000000000000000000000000000000..2eb2efc0f04eb97bb167e391ab7aa8f5dea8e3b4 --- /dev/null +++ b/demos/fake_gan/DESCRIPTION.md @@ -0,0 +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/ \ No newline at end of file diff --git a/demos/fake_gan/run.ipynb b/demos/fake_gan/run.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59ab8560bf475ef9b5142ccfda4227b77c3769e1 --- /dev/null +++ b/demos/fake_gan/run.ipynb @@ -0,0 +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", "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", "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} \ No newline at end of file diff --git a/demos/fake_gan/run.py b/demos/fake_gan/run.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9d69cb10a6f16da97d1c028a2eca7fca588a49 --- /dev/null +++ b/demos/fake_gan/run.py @@ -0,0 +1,31 @@ +# This demo needs to be run from the repo folder. +# python demo/fake_gan/run.py +import random + +import gradio as gr + +def fake_gan(): + images = [ + (random.choice( + [ + "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg", + "http://www.marketingtool.online/en/face-generator/img/faces/avatar-116b5e92936b766b7fdfc242649337f7.jpg", + "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1163530ca19b5cebe1b002b8ec67b6fc.jpg", + "http://www.marketingtool.online/en/face-generator/img/faces/avatar-1116395d6e6a6581eef8b8038f4c8e55.jpg", + "http://www.marketingtool.online/en/face-generator/img/faces/avatar-11319be65db395d0e8e6855d18ddcef0.jpg", + ] + ), f"label {i}") + for i in range(3) + ] + return images + +with gr.Blocks() as demo: + gallery = gr.Gallery( + label="Generated images", show_label=False, elem_id="gallery" + , columns=[3], rows=[1], object_fit="contain", height="auto") + btn = gr.Button("Generate images", scale=0) + + btn.click(fake_gan, None, gallery) + +if __name__ == "__main__": + demo.launch() diff --git a/demos/file_explorer_component_events/dir1/bar.txt b/demos/file_explorer_component_events/dir1/bar.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir1/foo.txt b/demos/file_explorer_component_events/dir1/foo.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir2/baz.png b/demos/file_explorer_component_events/dir2/baz.png new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir2/foo.png b/demos/file_explorer_component_events/dir2/foo.png new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir3/dir3_bar.log b/demos/file_explorer_component_events/dir3/dir3_bar.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir3/dir3_foo.txt b/demos/file_explorer_component_events/dir3/dir3_foo.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir3/dir4/dir5/dir5_foo.txt b/demos/file_explorer_component_events/dir3/dir4/dir5/dir5_foo.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir3/dir4/dir7/dir7_foo.txt b/demos/file_explorer_component_events/dir3/dir4/dir7/dir7_foo.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demos/file_explorer_component_events/dir3/dir4/dir_4_bar.log b/demos/file_explorer_component_events/dir3/dir4/dir_4_bar.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391