diff --git a/.changeset/fancy-bats-deny.md b/.changeset/fancy-bats-deny.md new file mode 100644 index 0000000000..7012e0003d --- /dev/null +++ b/.changeset/fancy-bats-deny.md @@ -0,0 +1,10 @@ +--- +"@gradio/highlightedtext": patch +"gradio": patch +"website": patch +--- + +feat:Minor bug fix sweep + +- Our use of __exit__ was catching errors and corrupting the traceback of any component that failed to instantiate (try running blocks_kitchen_sink off main for an example). Now the __exit__ exits immediately if there's been an exception, so the original exception can be printed cleanly +- HighlightedText was rendering weird, cleaned it up diff --git a/demo/barplot_component/run.ipynb b/demo/barplot_component/run.ipynb index e6bc998512..0fd82df174 100644 --- a/demo/barplot_component/run.ipynb +++ b/demo/barplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: barplot_component"]}, {"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 pandas as pd\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"item\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"inventory\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "with gr.Blocks() as demo:\n", " gr.BarPlot(value=simple, x=\"item\", y=\"inventory\", title=\"Simple Bar Plot\").style(\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: barplot_component"]}, {"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 pandas as pd\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"item\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"inventory\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "with gr.Blocks() as demo:\n", " gr.BarPlot(\n", " value=simple,\n", " x=\"item\",\n", " y=\"inventory\",\n", " title=\"Simple Bar Plot\",\n", " container=False,\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/demo/barplot_component/run.py b/demo/barplot_component/run.py index a8d793f69f..d8e135bd9b 100644 --- a/demo/barplot_component/run.py +++ b/demo/barplot_component/run.py @@ -9,7 +9,11 @@ simple = pd.DataFrame( ) with gr.Blocks() as demo: - gr.BarPlot(value=simple, x="item", y="inventory", title="Simple Bar Plot").style( + gr.BarPlot( + value=simple, + x="item", + y="inventory", + title="Simple Bar Plot", container=False, ) diff --git a/demo/blocks_essay/run.ipynb b/demo/blocks_essay/run.ipynb index 5f3652d604..480378226a 100644 --- a/demo/blocks_essay/run.ipynb +++ b/demo/blocks_essay/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "def change_textbox(choice):\n", " if choice == \"short\":\n", " return gr.Textbox.update(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox.update(lines=8, visible=True)\n", " else:\n", " return gr.Textbox.update(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True).style(show_copy_button=True)\n", "\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "def change_textbox(choice):\n", " if choice == \"short\":\n", " return gr.Textbox.update(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox.update(lines=8, visible=True)\n", " else:\n", " return gr.Textbox.update(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", "\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\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/demo/blocks_essay/run.py b/demo/blocks_essay/run.py index 8b80f7c761..127ca62e0f 100644 --- a/demo/blocks_essay/run.py +++ b/demo/blocks_essay/run.py @@ -14,7 +14,7 @@ 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).style(show_copy_button=True) + text = gr.Textbox(lines=2, interactive=True, show_copy_button=True) radio.change(fn=change_textbox, inputs=radio, outputs=text) diff --git a/demo/blocks_flashcards/run.ipynb b/demo/blocks_flashcards/run.ipynb index 6c438ee4cd..7508d80392 100644 --- a/demo/blocks_flashcards/run.ipynb +++ b/demo/blocks_flashcards/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_flashcards"]}, {"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 random\n", "\n", "import gradio as gr\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " \"Load the flashcards in the table below, then use the Practice tab to practice.\"\n", " )\n", "\n", " with gr.Tab(\"Word Bank\"):\n", " flashcards_table = gr.Dataframe(headers=[\"front\", \"back\"], type=\"array\")\n", " with gr.Tab(\"Practice\"):\n", " with gr.Row():\n", " with gr.Column():\n", " front = gr.Textbox(label=\"Prompt\")\n", " with gr.Row():\n", " new_btn = gr.Button(\"New Card\").style(full_width=True)\n", " flip_btn = gr.Button(\"Flip Card\").style(full_width=True)\n", " with gr.Column(visible=False) as answer_col:\n", " back = gr.Textbox(label=\"Answer\")\n", " selected_card = gr.State()\n", " with gr.Row():\n", " correct_btn = gr.Button(\n", " \"Correct\",\n", " ).style(full_width=True)\n", " incorrect_btn = gr.Button(\"Incorrect\").style(full_width=True)\n", "\n", " with gr.Tab(\"Results\"):\n", " results = gr.State(value={})\n", " correct_field = gr.Markdown(\"# Correct: 0\")\n", " incorrect_field = gr.Markdown(\"# Incorrect: 0\")\n", " gr.Markdown(\"Card Statistics: \")\n", " results_table = gr.Dataframe(headers=[\"Card\", \"Correct\", \"Incorrect\"])\n", "\n", " def load_new_card(flashcards):\n", " card = random.choice(flashcards)\n", " return (\n", " card,\n", " card[0],\n", " gr.Column.update(visible=False),\n", " )\n", "\n", " new_btn.click(\n", " load_new_card,\n", " [flashcards_table],\n", " [selected_card, front, answer_col],\n", " )\n", "\n", " def flip_card(card):\n", " return card[1], gr.Column.update(visible=True)\n", "\n", " flip_btn.click(flip_card, [selected_card], [back, answer_col])\n", "\n", " def mark_correct(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][0] += 1\n", " correct_count = sum(result[0] for result in results.values())\n", " return (\n", " results,\n", " f\"# Correct: {correct_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " def mark_incorrect(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][1] += 1\n", " incorrect_count = sum(result[1] for result in results.values())\n", " return (\n", " results,\n", " f\"# Inorrect: {incorrect_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " correct_btn.click(\n", " mark_correct,\n", " [selected_card, results],\n", " [results, correct_field, results_table],\n", " )\n", "\n", " incorrect_btn.click(\n", " mark_incorrect,\n", " [selected_card, results],\n", " [results, incorrect_field, results_table],\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_flashcards"]}, {"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 random\n", "\n", "import gradio as gr\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " \"Load the flashcards in the table below, then use the Practice tab to practice.\"\n", " )\n", "\n", " with gr.Tab(\"Word Bank\"):\n", " flashcards_table = gr.Dataframe(headers=[\"front\", \"back\"], type=\"array\")\n", " with gr.Tab(\"Practice\"):\n", " with gr.Row():\n", " with gr.Column():\n", " front = gr.Textbox(label=\"Prompt\")\n", " with gr.Row():\n", " new_btn = gr.Button(\"New Card\")\n", " flip_btn = gr.Button(\"Flip Card\")\n", " with gr.Column(visible=False) as answer_col:\n", " back = gr.Textbox(label=\"Answer\")\n", " selected_card = gr.State()\n", " with gr.Row():\n", " correct_btn = gr.Button(\"Correct\")\n", " incorrect_btn = gr.Button(\"Incorrect\")\n", "\n", " with gr.Tab(\"Results\"):\n", " results = gr.State(value={})\n", " correct_field = gr.Markdown(\"# Correct: 0\")\n", " incorrect_field = gr.Markdown(\"# Incorrect: 0\")\n", " gr.Markdown(\"Card Statistics: \")\n", " results_table = gr.Dataframe(headers=[\"Card\", \"Correct\", \"Incorrect\"])\n", "\n", " def load_new_card(flashcards):\n", " card = random.choice(flashcards)\n", " return (\n", " card,\n", " card[0],\n", " gr.Column.update(visible=False),\n", " )\n", "\n", " new_btn.click(\n", " load_new_card,\n", " [flashcards_table],\n", " [selected_card, front, answer_col],\n", " )\n", "\n", " def flip_card(card):\n", " return card[1], gr.Column.update(visible=True)\n", "\n", " flip_btn.click(flip_card, [selected_card], [back, answer_col])\n", "\n", " def mark_correct(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][0] += 1\n", " correct_count = sum(result[0] for result in results.values())\n", " return (\n", " results,\n", " f\"# Correct: {correct_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " def mark_incorrect(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][1] += 1\n", " incorrect_count = sum(result[1] for result in results.values())\n", " return (\n", " results,\n", " f\"# Inorrect: {incorrect_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " correct_btn.click(\n", " mark_correct,\n", " [selected_card, results],\n", " [results, correct_field, results_table],\n", " )\n", "\n", " incorrect_btn.click(\n", " mark_incorrect,\n", " [selected_card, results],\n", " [results, incorrect_field, results_table],\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/demo/blocks_flashcards/run.py b/demo/blocks_flashcards/run.py index 5cb1eced2f..c7dc0ee9f5 100644 --- a/demo/blocks_flashcards/run.py +++ b/demo/blocks_flashcards/run.py @@ -16,16 +16,14 @@ with demo: with gr.Column(): front = gr.Textbox(label="Prompt") with gr.Row(): - new_btn = gr.Button("New Card").style(full_width=True) - flip_btn = gr.Button("Flip Card").style(full_width=True) + new_btn = gr.Button("New Card") + flip_btn = gr.Button("Flip Card") with gr.Column(visible=False) as answer_col: back = gr.Textbox(label="Answer") selected_card = gr.State() with gr.Row(): - correct_btn = gr.Button( - "Correct", - ).style(full_width=True) - incorrect_btn = gr.Button("Incorrect").style(full_width=True) + correct_btn = gr.Button("Correct") + incorrect_btn = gr.Button("Incorrect") with gr.Tab("Results"): results = gr.State(value={}) diff --git a/demo/blocks_joined/run.ipynb b/demo/blocks_joined/run.ipynb index f9bce82479..e18ac6911e 100644 --- a/demo/blocks_joined/run.ipynb +++ b/demo/blocks_joined/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_joined"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/blocks_joined/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from time import sleep\n", "import gradio as gr\n", "import os\n", "\n", "cheetah = os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\")\n", "\n", "\n", "def img(text):\n", " sleep(3)\n", " return [\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " ]\n", "\n", "\n", "with gr.Blocks(css=\".container { max-width: 800px; margin: auto; }\") as demo:\n", " gr.Markdown(\"

DALL\u00b7E mini

\")\n", " gr.Markdown(\n", " \"DALL\u00b7E mini is an AI model that generates images from any prompt you give!\"\n", " )\n", " with gr.Group():\n", " with gr.Box():\n", " with gr.Row().style(equal_height=True):\n", "\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\", show_label=False, max_lines=1\n", " ).style(\n", " border=(True, False, True, True),\n", " rounded=(True, False, False, True),\n", " container=False,\n", " )\n", " btn = gr.Button(\"Run\").style(\n", " margin=False,\n", " rounded=(False, True, True, False),\n", " )\n", " gallery = gr.Gallery(label=\"Generated images\", show_label=False).style(\n", " grid=(\n", " 1,\n", " 3,\n", " ),\n", " height=\"auto\",\n", " )\n", " btn.click(img, inputs=text, outputs=gallery)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n", "\n", "\n", "# margin = (TOP, RIGHT, BOTTOM, LEFT)\n", "# rounded = (TOPLEFT, TOPRIGHT, BOTTOMRIGHT, BOTTOMLEFT)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_joined"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/blocks_joined/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from time import sleep\n", "import gradio as gr\n", "import os\n", "\n", "cheetah = os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\")\n", "\n", "\n", "def img(text):\n", " sleep(3)\n", " return [\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " ]\n", "\n", "\n", "with gr.Blocks(css=\".container { max-width: 800px; margin: auto; }\") as demo:\n", " gr.Markdown(\"

DALL\u00b7E mini

\")\n", " gr.Markdown(\n", " \"DALL\u00b7E mini is an AI model that generates images from any prompt you give!\"\n", " )\n", " with gr.Group():\n", " with gr.Row(equal_height=True):\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " container=False,\n", " )\n", " btn = gr.Button(\"Run\", scale=0)\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " columns=(1, 3),\n", " height=\"auto\",\n", " )\n", " btn.click(img, inputs=text, outputs=gallery)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n", "\n", "\n", "# margin = (TOP, RIGHT, BOTTOM, LEFT)\n", "# rounded = (TOPLEFT, TOPRIGHT, BOTTOMRIGHT, BOTTOMLEFT)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_joined/run.py b/demo/blocks_joined/run.py index e09e92d8ef..ba2d71e24f 100644 --- a/demo/blocks_joined/run.py +++ b/demo/blocks_joined/run.py @@ -26,25 +26,17 @@ with gr.Blocks(css=".container { max-width: 800px; margin: auto; }") as demo: "DALLĀ·E mini is an AI model that generates images from any prompt you give!" ) with gr.Group(): - with gr.Box(): - with gr.Row().style(equal_height=True): - - text = gr.Textbox( - label="Enter your prompt", show_label=False, max_lines=1 - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True), - container=False, - ) - btn = gr.Button("Run").style( - margin=False, - rounded=(False, True, True, False), - ) - gallery = gr.Gallery(label="Generated images", show_label=False).style( - grid=( - 1, - 3, - ), + with gr.Row(equal_height=True): + text = gr.Textbox( + label="Enter your prompt", + max_lines=1, + container=False, + ) + btn = gr.Button("Run", scale=0) + gallery = gr.Gallery( + label="Generated images", + show_label=False, + columns=(1, 3), height="auto", ) btn.click(img, inputs=text, outputs=gallery) diff --git a/demo/blocks_kitchen_sink/run.ipynb b/demo/blocks_kitchen_sink/run.ipynb index f235288bd8..10128f8ff7 100644 --- a/demo/blocks_kitchen_sink/run.ipynb +++ b/demo/blocks_kitchen_sink/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_kitchen_sink"]}, {"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 time\n", "from os.path import abspath, join, pardir\n", "\n", "KS_FILES = abspath(join(__file__, pardir, pardir, \"kitchen_sink\", \"files\"))\n", "\n", "base_theme = gr.themes.Base()\n", "default_theme = gr.themes.Default()\n", "monochrome_theme = gr.themes.Monochrome()\n", "soft_theme = gr.themes.Soft()\n", "glass_theme = gr.themes.Glass()\n", "\n", "with gr.Blocks(theme=base_theme) as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Blocks Kitchen Sink\n", " This is a demo of most Gradio features. Test all themes and toggle dark mode\n", " ## Elements\n", " - Use of Rows, Columns, Tabs, and Accordion\n", " - Use of Form elements: Textbox, Dropdown, Checkbox, Radio, Slider\n", " ## Other\n", " Other stuff\n", " - Buttons of variants: \"primary\", \"secondary\", \"stop\"\n", " - Embedded interface\n", " - Custom progress bar\n", " \"\"\"\n", " )\n", " toggle_dark = gr.Button(\"Toggle Dark\").style(full_width=False)\n", " toggle_dark.click(\n", " None,\n", " _js=\"\"\"\n", " () => { \n", " document.body.classList.toggle('dark');\n", " }\n", " \"\"\",\n", " )\n", " theme_selector = gr.Radio(\n", " [\"Base\", \"Default\", \"Monochrome\", \"Soft\", \"Glass\"],\n", " value=\"Base\",\n", " label=\"Theme\",\n", " )\n", " theme_selector.change(\n", " None,\n", " theme_selector,\n", " None,\n", " _js=f\"\"\"\n", " (theme) => {{\n", " if (!document.querySelector('.theme-css')) {{\n", " var theme_elem = document.createElement('style');\n", " theme_elem.classList.add('theme-css');\n", " document.head.appendChild(theme_elem);\n", "\n", " var link_elem = document.createElement('link');\n", " link_elem.classList.add('link-css');\n", " link_elem.rel = 'stylesheet';\n", " document.head.appendChild(link_elem);\n", " }} else {{\n", " var theme_elem = document.querySelector('.theme-css');\n", " var link_elem = document.querySelector('.link-css');\n", " }}\n", " if (theme == \"Base\") {{\n", " var theme_css = `{base_theme._get_theme_css()}`;\n", " var link_css = `{base_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Default\") {{\n", " var theme_css = `{default_theme._get_theme_css()}`;\n", " var link_css = `{default_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Monochrome\") {{\n", " var theme_css = `{monochrome_theme._get_theme_css()}`;\n", " var link_css = `{monochrome_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Soft\") {{\n", " var theme_css = `{soft_theme._get_theme_css()}`;\n", " var link_css = `{soft_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Glass\") {{\n", " var theme_css = `{glass_theme._get_theme_css()}`;\n", " var link_css = `{glass_theme._stylesheets[0]}`;\n", " }}\n", " theme_elem.innerHTML = theme_css;\n", " link_elem.href = link_css;\n", " }}\n", " \"\"\",\n", " )\n", "\n", " name = gr.Textbox(\n", " label=\"Name (select)\",\n", " info=\"Full name, including middle name. No special characters.\",\n", " placeholder=\"John Doe\",\n", " value=\"John Doe\",\n", " interactive=True,\n", " )\n", "\n", " with gr.Row():\n", " slider1 = gr.Slider(label=\"Slider 1\")\n", " slider2 = gr.Slider(label=\"Slider 2\")\n", " checkboxes = gr.CheckboxGroup([\"A\", \"B\", \"C\"], label=\"Checkbox Group (select)\")\n", "\n", " with gr.Row():\n", " with gr.Column(variant=\"panel\", scale=1):\n", " gr.Markdown(\"## Panel 1\")\n", " radio = gr.Radio(\n", " [\"A\", \"B\", \"C\"],\n", " label=\"Radio (select)\",\n", " info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n", " )\n", " drop = gr.Dropdown([\"Option 1\", \"Option 2\", \"Option 3\"], show_label=False)\n", " drop_2 = gr.Dropdown(\n", " [\"Option A\", \"Option B\", \"Option C\"],\n", " multiselect=True,\n", " value=[\"Option A\"],\n", " label=\"Dropdown (select)\",\n", " interactive=True,\n", " )\n", " check = gr.Checkbox(label=\"Go\")\n", " with gr.Column(variant=\"panel\", scale=2):\n", " img = gr.Image(\n", " \"https://gradio.app/assets/img/header-image.jpg\", label=\"Image\"\n", " ).style(height=320)\n", " with gr.Row():\n", " go_btn = gr.Button(\"Go\", label=\"Primary Button\", variant=\"primary\")\n", " clear_btn = gr.Button(\n", " \"Clear\", label=\"Secondary Button\", variant=\"secondary\"\n", " )\n", "\n", " def go(*args):\n", " time.sleep(3)\n", " return \"https://i.ibb.co/6BgKdSj/groot.jpg\"\n", "\n", " go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name=\"go\")\n", "\n", " def clear():\n", " time.sleep(0.2)\n", " return None\n", "\n", " clear_btn.click(clear, None, img)\n", "\n", " with gr.Row():\n", " btn1 = gr.Button(\"Button 1\").style(size=\"sm\")\n", " btn2 = gr.UploadButton().style(size=\"sm\")\n", " stop_btn = gr.Button(\"Stop\", label=\"Stop Button\", variant=\"stop\").style(\n", " size=\"sm\"\n", " )\n", "\n", " gr.Examples(\n", " examples=[join(KS_FILES, \"lion.jpg\"), join(KS_FILES, \"tower.jpg\")],\n", " inputs=img,\n", " )\n", "\n", " gr.Examples(\n", " examples=[\n", " [\"A\", \"Option 1\", [\"Option B\"], True, join(KS_FILES, \"lion.jpg\")],\n", " [\n", " \"B\",\n", " \"Option 2\",\n", " [\"Option B\", \"Option C\"],\n", " False,\n", " join(KS_FILES, \"tower.jpg\"),\n", " ],\n", " ],\n", " inputs=[radio, drop, drop_2, check, img],\n", " label=\"Examples (select)\",\n", " )\n", "\n", " gr.Markdown(\"## Media Files\")\n", "\n", " with gr.Tabs() as tabs:\n", " with gr.Tab(\"Audio\"):\n", " with gr.Row():\n", " gr.Audio()\n", " gr.Audio(source=\"microphone\")\n", " gr.Audio(join(KS_FILES, \"cantina.wav\"))\n", " with gr.Tab(\"Other\"):\n", " # gr.Image(source=\"webcam\")\n", " gr.HTML(\n", " \"
\"\n", " )\n", " with gr.Row():\n", " dataframe = gr.Dataframe(\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label=\"Dataframe (select)\"\n", " )\n", " gr.JSON(\n", " value={\"a\": 1, \"b\": 2, \"c\": {\"test\": \"a\", \"test2\": [1, 2, 3]}}, label=\"JSON\"\n", " )\n", " label = gr.Label(\n", " value={\"cat\": 0.7, \"dog\": 0.2, \"fish\": 0.1}, label=\"Label (select)\"\n", " )\n", " file = gr.File(label=\"File (select)\")\n", " with gr.Row():\n", " gr.ColorPicker()\n", " gr.Video(join(KS_FILES, \"world.mp4\"))\n", " gallery = gr.Gallery(\n", " [\n", " (join(KS_FILES, \"lion.jpg\"), \"lion\"),\n", " (join(KS_FILES, \"logo.png\"), \"logo\"),\n", " (join(KS_FILES, \"tower.jpg\"), \"tower\"),\n", " ],\n", " label=\"Gallery (select)\",\n", " )\n", "\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " highlight = gr.HighlightedText(\n", " [[\"The\", \"art\"], [\"dog\", \"noun\"], [\"is\", None], [\"fat\", \"adj\"]],\n", " label=\"Highlighted Text (select)\",\n", " )\n", " chatbot = gr.Chatbot([[\"Hello\", \"Hi\"]], label=\"Chatbot (select)\")\n", " chat_btn = gr.Button(\"Add messages\")\n", "\n", " def chat(history):\n", " time.sleep(2)\n", " yield [[\"How are you?\", \"I am good.\"]]\n", " time\n", "\n", " chat_btn.click(\n", " lambda history: history\n", " + [[\"How are you?\", \"I am good.\"]]\n", " + (time.sleep(2) or []),\n", " chatbot,\n", " chatbot,\n", " )\n", " with gr.Column(scale=1):\n", " with gr.Accordion(\"Select Info\"):\n", " gr.Markdown(\n", " \"Click on any part of any component with '(select)' in the label and see the SelectData data here.\"\n", " )\n", " select_index = gr.Textbox(label=\"Index\")\n", " select_value = gr.Textbox(label=\"Value\")\n", " select_selected = gr.Textbox(label=\"Selected\")\n", "\n", " selectables = [\n", " name,\n", " checkboxes,\n", " radio,\n", " drop_2,\n", " dataframe,\n", " label,\n", " file,\n", " highlight,\n", " chatbot,\n", " gallery,\n", " tabs\n", " ]\n", "\n", " def select_data(evt: gr.SelectData):\n", " return [\n", " evt.index,\n", " evt.value,\n", " evt.selected,\n", " ]\n", "\n", " for selectable in selectables:\n", " selectable.select(\n", " select_data,\n", " None,\n", " [select_index, select_value, select_selected],\n", " )\n", "\n", " gr.Markdown(\"## Dataset Examples\")\n", "\n", " component_example_set = [\n", " (gr.Audio(render=False), join(KS_FILES, \"cantina.wav\")),\n", " (gr.Checkbox(render=False), True),\n", " (gr.CheckboxGroup(render=False), [\"A\", \"B\"]),\n", " (gr.ColorPicker(render=False), \"#FF0000\"),\n", " (gr.Dataframe(render=False), [[1, 2, 3], [4, 5, 6]]),\n", " (gr.Dropdown(render=False), \"A\"),\n", " (gr.File(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.HTML(render=False), \"
Test
\"),\n", " (gr.Image(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.Markdown(render=False), \"# Test\"),\n", " (gr.Number(render=False), 1),\n", " (gr.Radio(render=False), \"A\"),\n", " (gr.Slider(render=False), 1),\n", " (gr.Textbox(render=False), \"A\"),\n", " (gr.Video(render=False), join(KS_FILES, \"world.mp4\")),\n", " ]\n", " gr.Dataset(\n", " components=[c for c, _ in component_example_set],\n", " samples=[[e for _, e in component_example_set]],\n", " )\n", "\n", " with gr.Tabs():\n", " for c, e in component_example_set:\n", " with gr.Tab(c.__class__.__name__):\n", " gr.Dataset(components=[c], samples=[[e]] * 3)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(file_directories=[KS_FILES])\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_kitchen_sink"]}, {"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 time\n", "from os.path import abspath, join, pardir\n", "\n", "KS_FILES = abspath(join(__file__, pardir, pardir, \"kitchen_sink\", \"files\"))\n", "\n", "base_theme = gr.themes.Base()\n", "default_theme = gr.themes.Default()\n", "monochrome_theme = gr.themes.Monochrome()\n", "soft_theme = gr.themes.Soft()\n", "glass_theme = gr.themes.Glass()\n", "\n", "with gr.Blocks(theme=base_theme) as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Blocks Kitchen Sink\n", " This is a demo of most Gradio features. Test all themes and toggle dark mode\n", " ## Elements\n", " - Use of Rows, Columns, Tabs, and Accordion\n", " - Use of Form elements: Textbox, Dropdown, Checkbox, Radio, Slider\n", " ## Other\n", " Other stuff\n", " - Buttons of variants: \"primary\", \"secondary\", \"stop\"\n", " - Embedded interface\n", " - Custom progress bar\n", " \"\"\"\n", " )\n", " toggle_dark = gr.Button(\"Toggle Dark\", scale=0)\n", " toggle_dark.click(\n", " None,\n", " _js=\"\"\"\n", " () => { \n", " document.body.classList.toggle('dark');\n", " }\n", " \"\"\",\n", " )\n", " theme_selector = gr.Radio(\n", " [\"Base\", \"Default\", \"Monochrome\", \"Soft\", \"Glass\"],\n", " value=\"Base\",\n", " label=\"Theme\",\n", " )\n", " theme_selector.change(\n", " None,\n", " theme_selector,\n", " None,\n", " _js=f\"\"\"\n", " (theme) => {{\n", " if (!document.querySelector('.theme-css')) {{\n", " var theme_elem = document.createElement('style');\n", " theme_elem.classList.add('theme-css');\n", " document.head.appendChild(theme_elem);\n", "\n", " var link_elem = document.createElement('link');\n", " link_elem.classList.add('link-css');\n", " link_elem.rel = 'stylesheet';\n", " document.head.appendChild(link_elem);\n", " }} else {{\n", " var theme_elem = document.querySelector('.theme-css');\n", " var link_elem = document.querySelector('.link-css');\n", " }}\n", " if (theme == \"Base\") {{\n", " var theme_css = `{base_theme._get_theme_css()}`;\n", " var link_css = `{base_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Default\") {{\n", " var theme_css = `{default_theme._get_theme_css()}`;\n", " var link_css = `{default_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Monochrome\") {{\n", " var theme_css = `{monochrome_theme._get_theme_css()}`;\n", " var link_css = `{monochrome_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Soft\") {{\n", " var theme_css = `{soft_theme._get_theme_css()}`;\n", " var link_css = `{soft_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Glass\") {{\n", " var theme_css = `{glass_theme._get_theme_css()}`;\n", " var link_css = `{glass_theme._stylesheets[0]}`;\n", " }}\n", " theme_elem.innerHTML = theme_css;\n", " link_elem.href = link_css;\n", " }}\n", " \"\"\",\n", " )\n", "\n", " name = gr.Textbox(\n", " label=\"Name (select)\",\n", " info=\"Full name, including middle name. No special characters.\",\n", " placeholder=\"John Doe\",\n", " value=\"John Doe\",\n", " interactive=True,\n", " )\n", "\n", " with gr.Row():\n", " slider1 = gr.Slider(label=\"Slider 1\")\n", " slider2 = gr.Slider(label=\"Slider 2\")\n", " checkboxes = gr.CheckboxGroup([\"A\", \"B\", \"C\"], label=\"Checkbox Group (select)\")\n", "\n", " with gr.Row():\n", " with gr.Column(variant=\"panel\", scale=1):\n", " gr.Markdown(\"## Panel 1\")\n", " radio = gr.Radio(\n", " [\"A\", \"B\", \"C\"],\n", " label=\"Radio (select)\",\n", " info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n", " )\n", " drop = gr.Dropdown([\"Option 1\", \"Option 2\", \"Option 3\"], show_label=False)\n", " drop_2 = gr.Dropdown(\n", " [\"Option A\", \"Option B\", \"Option C\"],\n", " multiselect=True,\n", " value=[\"Option A\"],\n", " label=\"Dropdown (select)\",\n", " interactive=True,\n", " )\n", " check = gr.Checkbox(label=\"Go\")\n", " with gr.Column(variant=\"panel\", scale=2):\n", " img = gr.Image(\n", " \"https://picsum.photos/536/354\",\n", " label=\"Image\",\n", " height=320,\n", " )\n", " with gr.Row():\n", " go_btn = gr.Button(\"Go\", label=\"Primary Button\", variant=\"primary\")\n", " clear_btn = gr.Button(\n", " \"Clear\", label=\"Secondary Button\", variant=\"secondary\"\n", " )\n", "\n", " def go(*args):\n", " time.sleep(3)\n", " return \"https://i.ibb.co/6BgKdSj/groot.jpg\"\n", "\n", " go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name=\"go\")\n", "\n", " def clear():\n", " time.sleep(0.2)\n", " return None\n", "\n", " clear_btn.click(clear, None, img)\n", "\n", " with gr.Row():\n", " btn1 = gr.Button(\"Button 1\", size=\"sm\")\n", " btn2 = gr.UploadButton(size=\"sm\")\n", " stop_btn = gr.Button(\n", " \"Stop\", label=\"Stop Button\", variant=\"stop\", size=\"sm\"\n", " )\n", "\n", " gr.Examples(\n", " examples=[join(KS_FILES, \"lion.jpg\"), join(KS_FILES, \"tower.jpg\")],\n", " inputs=img,\n", " )\n", "\n", " gr.Examples(\n", " examples=[\n", " [\"A\", \"Option 1\", [\"Option B\"], True, join(KS_FILES, \"lion.jpg\")],\n", " [\n", " \"B\",\n", " \"Option 2\",\n", " [\"Option B\", \"Option C\"],\n", " False,\n", " join(KS_FILES, \"tower.jpg\"),\n", " ],\n", " ],\n", " inputs=[radio, drop, drop_2, check, img],\n", " label=\"Examples (select)\",\n", " )\n", "\n", " gr.Markdown(\"## Media Files\")\n", "\n", " with gr.Tabs() as tabs:\n", " with gr.Tab(\"Audio\"):\n", " with gr.Row():\n", " gr.Audio()\n", " gr.Audio(source=\"microphone\")\n", " gr.Audio(join(KS_FILES, \"cantina.wav\"))\n", " with gr.Tab(\"Other\"):\n", " # gr.Image(source=\"webcam\")\n", " gr.HTML(\n", " \"
\"\n", " )\n", " with gr.Row():\n", " dataframe = gr.Dataframe(\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label=\"Dataframe (select)\"\n", " )\n", " gr.JSON(\n", " value={\"a\": 1, \"b\": 2, \"c\": {\"test\": \"a\", \"test2\": [1, 2, 3]}}, label=\"JSON\"\n", " )\n", " label = gr.Label(\n", " value={\"cat\": 0.7, \"dog\": 0.2, \"fish\": 0.1}, label=\"Label (select)\"\n", " )\n", " file = gr.File(label=\"File (select)\")\n", " with gr.Row():\n", " gr.ColorPicker()\n", " gr.Video(join(KS_FILES, \"world.mp4\"))\n", " gallery = gr.Gallery(\n", " [\n", " (join(KS_FILES, \"lion.jpg\"), \"lion\"),\n", " (join(KS_FILES, \"logo.png\"), \"logo\"),\n", " (join(KS_FILES, \"tower.jpg\"), \"tower\"),\n", " ],\n", " label=\"Gallery (select)\",\n", " )\n", "\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " highlight = gr.HighlightedText(\n", " [[\"The\", \"art\"], [\"dog\", \"noun\"], [\"is\", None], [\"fat\", \"adj\"]],\n", " label=\"Highlighted Text (select)\",\n", " )\n", " chatbot = gr.Chatbot([[\"Hello\", \"Hi\"]], label=\"Chatbot (select)\")\n", " chat_btn = gr.Button(\"Add messages\")\n", "\n", " def chat(history):\n", " time.sleep(2)\n", " yield [[\"How are you?\", \"I am good.\"]]\n", " time\n", "\n", " chat_btn.click(\n", " lambda history: history\n", " + [[\"How are you?\", \"I am good.\"]]\n", " + (time.sleep(2) or []),\n", " chatbot,\n", " chatbot,\n", " )\n", " with gr.Column(scale=1):\n", " with gr.Accordion(\"Select Info\"):\n", " gr.Markdown(\n", " \"Click on any part of any component with '(select)' in the label and see the SelectData data here.\"\n", " )\n", " select_index = gr.Textbox(label=\"Index\")\n", " select_value = gr.Textbox(label=\"Value\")\n", " select_selected = gr.Textbox(label=\"Selected\")\n", "\n", " selectables = [\n", " name,\n", " checkboxes,\n", " radio,\n", " drop_2,\n", " dataframe,\n", " label,\n", " file,\n", " highlight,\n", " chatbot,\n", " gallery,\n", " tabs,\n", " ]\n", "\n", " def select_data(evt: gr.SelectData):\n", " return [\n", " evt.index,\n", " evt.value,\n", " evt.selected,\n", " ]\n", "\n", " for selectable in selectables:\n", " selectable.select(\n", " select_data,\n", " None,\n", " [select_index, select_value, select_selected],\n", " )\n", "\n", " gr.Markdown(\"## Dataset Examples\")\n", "\n", " component_example_set = [\n", " (gr.Audio(render=False), join(KS_FILES, \"cantina.wav\")),\n", " (gr.Checkbox(render=False), True),\n", " (gr.CheckboxGroup(render=False, choices=[\"A\", \"B\"]), [\"A\", \"B\"]),\n", " (gr.ColorPicker(render=False), \"#FF0000\"),\n", " (gr.Dataframe(render=False), [[1, 2, 3], [4, 5, 6]]),\n", " (gr.Dropdown(render=False), \"A\"),\n", " (gr.File(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.HTML(render=False), \"
Test
\"),\n", " (gr.Image(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.Markdown(render=False), \"# Test\"),\n", " (gr.Number(render=False), 1),\n", " (gr.Radio(render=False), \"A\"),\n", " (gr.Slider(render=False), 1),\n", " (gr.Textbox(render=False), \"A\"),\n", " (gr.Video(render=False), join(KS_FILES, \"world.mp4\")),\n", " ]\n", " gr.Dataset(\n", " components=[c for c, _ in component_example_set],\n", " samples=[[e for _, e in component_example_set]],\n", " )\n", "\n", " with gr.Tabs():\n", " for c, e in component_example_set:\n", " with gr.Tab(c.__class__.__name__):\n", " gr.Dataset(components=[c], samples=[[e]] * 3)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(allowed_paths=[KS_FILES])\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_kitchen_sink/run.py b/demo/blocks_kitchen_sink/run.py index 58517ba2d4..99e6571265 100644 --- a/demo/blocks_kitchen_sink/run.py +++ b/demo/blocks_kitchen_sink/run.py @@ -25,7 +25,7 @@ with gr.Blocks(theme=base_theme) as demo: - Custom progress bar """ ) - toggle_dark = gr.Button("Toggle Dark").style(full_width=False) + toggle_dark = gr.Button("Toggle Dark", scale=0) toggle_dark.click( None, _js=""" @@ -112,8 +112,10 @@ with gr.Blocks(theme=base_theme) as demo: check = gr.Checkbox(label="Go") with gr.Column(variant="panel", scale=2): img = gr.Image( - "https://gradio.app/assets/img/header-image.jpg", label="Image" - ).style(height=320) + "https://picsum.photos/536/354", + label="Image", + height=320, + ) with gr.Row(): go_btn = gr.Button("Go", label="Primary Button", variant="primary") clear_btn = gr.Button( @@ -133,10 +135,10 @@ with gr.Blocks(theme=base_theme) as demo: clear_btn.click(clear, None, img) with gr.Row(): - btn1 = gr.Button("Button 1").style(size="sm") - btn2 = gr.UploadButton().style(size="sm") - stop_btn = gr.Button("Stop", label="Stop Button", variant="stop").style( - size="sm" + btn1 = gr.Button("Button 1", size="sm") + btn2 = gr.UploadButton(size="sm") + stop_btn = gr.Button( + "Stop", label="Stop Button", variant="stop", size="sm" ) gr.Examples( @@ -236,7 +238,7 @@ with gr.Blocks(theme=base_theme) as demo: highlight, chatbot, gallery, - tabs + tabs, ] def select_data(evt: gr.SelectData): @@ -258,7 +260,7 @@ with gr.Blocks(theme=base_theme) as demo: component_example_set = [ (gr.Audio(render=False), join(KS_FILES, "cantina.wav")), (gr.Checkbox(render=False), True), - (gr.CheckboxGroup(render=False), ["A", "B"]), + (gr.CheckboxGroup(render=False, choices=["A", "B"]), ["A", "B"]), (gr.ColorPicker(render=False), "#FF0000"), (gr.Dataframe(render=False), [[1, 2, 3], [4, 5, 6]]), (gr.Dropdown(render=False), "A"), @@ -284,4 +286,4 @@ with gr.Blocks(theme=base_theme) as demo: if __name__ == "__main__": - demo.launch(file_directories=[KS_FILES]) + demo.launch(allowed_paths=[KS_FILES]) diff --git a/demo/blocks_layout/run.ipynb b/demo/blocks_layout/run.ipynb index 557419298e..92c54ed7d5 100644 --- a/demo/blocks_layout/run.ipynb +++ b/demo/blocks_layout/run.ipynb @@ -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\").style(full_width=False)\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} \ No newline at end of file +{"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} \ No newline at end of file diff --git a/demo/blocks_layout/run.py b/demo/blocks_layout/run.py index 431e86bb0b..6a7f3660ff 100644 --- a/demo/blocks_layout/run.py +++ b/demo/blocks_layout/run.py @@ -13,7 +13,7 @@ with demo: gr.Radio(choices=["One", "Two"]) with gr.Row(): gr.Button("500", scale=0, min_width=500) - gr.Button("A").style(full_width=False) + gr.Button("A", scale=0) gr.Button("grow") with gr.Row(): gr.Textbox() diff --git a/demo/blocks_style/run.ipynb b/demo/blocks_style/run.ipynb index d2972a9d75..ff59d8ba72 100644 --- a/demo/blocks_style/run.ipynb +++ b/demo/blocks_style/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_style"]}, {"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(title=\"Styling Examples\") as demo:\n", " with gr.Column(variant=\"box\"):\n", " txt = gr.Textbox(label=\"Small Textbox\", lines=1)\n", " num = gr.Number(label=\"Number\", show_label=False)\n", " slider = gr.Slider(label=\"Slider\", show_label=False)\n", " check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", " check_g = gr.CheckboxGroup(\n", " label=\"Checkbox Group\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " radio = gr.Radio(\n", " label=\"Radio\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " ).style(\n", " item_container=False,\n", " )\n", " drop = gr.Dropdown(\n", " label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " )\n", " image = gr.Image(show_label=False)\n", " video = gr.Video(show_label=False)\n", " audio = gr.Audio(show_label=False)\n", " file = gr.File(show_label=False)\n", " df = gr.Dataframe(show_label=False)\n", " ts = gr.Timeseries(show_label=False)\n", " label = gr.Label().style(\n", " container=False,\n", " )\n", " highlight = gr.HighlightedText(\n", " \"+ hello. - goodbye\",\n", " show_label=False,\n", " ).style(color_map={\"+\": \"green\", \"-\": \"red\"}, container=False)\n", " json = gr.JSON().style(container=False)\n", " html = gr.HTML(show_label=False)\n", " gallery = gr.Gallery().style(\n", " grid=(3, 3, 1),\n", " height=\"auto\",\n", " container=False,\n", " )\n", " chat = gr.Chatbot([(\"hi\", \"good bye\")]).style(color_map=(\"pink\", \"blue\"))\n", "\n", " model = gr.Model3D()\n", "\n", " md = gr.Markdown(show_label=False)\n", "\n", " highlight = gr.HighlightedText()\n", "\n", " btn = gr.Button(\"Run\").style(\n", " full_width=True,\n", " )\n", "\n", " gr.Dataset(components=[txt, num])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_style"]}, {"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(title=\"Styling Examples\") as demo:\n", " with gr.Column(variant=\"box\"):\n", " txt = gr.Textbox(label=\"Small Textbox\", lines=1)\n", " num = gr.Number(label=\"Number\", show_label=False)\n", " slider = gr.Slider(label=\"Slider\", show_label=False)\n", " check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", " check_g = gr.CheckboxGroup(\n", " label=\"Checkbox Group\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " radio = gr.Radio(\n", " label=\"Radio\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " drop = gr.Dropdown(\n", " label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " )\n", " image = gr.Image(show_label=False)\n", " video = gr.Video(show_label=False)\n", " audio = gr.Audio(show_label=False)\n", " file = gr.File(show_label=False)\n", " df = gr.Dataframe(show_label=False)\n", " ts = gr.Timeseries(show_label=False)\n", " label = gr.Label(container=False)\n", " highlight = gr.HighlightedText(\n", " [(\"hello\", None), (\"goodbye\", \"-\")],\n", " color_map={\"+\": \"green\", \"-\": \"red\"},\n", " container=False,\n", " )\n", " json = gr.JSON(container=False)\n", " html = gr.HTML(show_label=False)\n", " gallery = gr.Gallery(\n", " columns=(3, 3, 1),\n", " height=\"auto\",\n", " container=False,\n", " )\n", " chat = gr.Chatbot([(\"hi\", \"good bye\")])\n", "\n", " model = gr.Model3D()\n", "\n", " md = gr.Markdown(show_label=False)\n", "\n", " highlight = gr.HighlightedText()\n", "\n", " btn = gr.Button(\"Run\")\n", "\n", " gr.Dataset(components=[txt, num])\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/demo/blocks_style/run.py b/demo/blocks_style/run.py index 3ac52e2825..9e40fcdc21 100644 --- a/demo/blocks_style/run.py +++ b/demo/blocks_style/run.py @@ -12,9 +12,9 @@ with gr.Blocks(title="Styling Examples") as demo: show_label=False, ) radio = gr.Radio( - label="Radio", choices=["One", "Two", "Three"], show_label=False - ).style( - item_container=False, + label="Radio", + choices=["One", "Two", "Three"], + show_label=False, ) drop = gr.Dropdown( label="Dropdown", choices=["One", "Two", "Three"], show_label=False @@ -25,21 +25,20 @@ with gr.Blocks(title="Styling Examples") as demo: file = gr.File(show_label=False) df = gr.Dataframe(show_label=False) ts = gr.Timeseries(show_label=False) - label = gr.Label().style( + label = gr.Label(container=False) + highlight = gr.HighlightedText( + [("hello", None), ("goodbye", "-")], + color_map={"+": "green", "-": "red"}, container=False, ) - highlight = gr.HighlightedText( - "+ hello. - goodbye", - show_label=False, - ).style(color_map={"+": "green", "-": "red"}, container=False) - json = gr.JSON().style(container=False) + json = gr.JSON(container=False) html = gr.HTML(show_label=False) - gallery = gr.Gallery().style( - grid=(3, 3, 1), + gallery = gr.Gallery( + columns=(3, 3, 1), height="auto", container=False, ) - chat = gr.Chatbot([("hi", "good bye")]).style(color_map=("pink", "blue")) + chat = gr.Chatbot([("hi", "good bye")]) model = gr.Model3D() @@ -47,9 +46,7 @@ with gr.Blocks(title="Styling Examples") as demo: highlight = gr.HighlightedText() - btn = gr.Button("Run").style( - full_width=True, - ) + btn = gr.Button("Run") gr.Dataset(components=[txt, num]) diff --git a/demo/chatbot_multimodal/run.ipynb b/demo/chatbot_multimodal/run.ipynb index 9c3546a432..c3726d628a 100644 --- a/demo/chatbot_multimodal/run.ipynb +++ b/demo/chatbot_multimodal/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.update(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot([], elem_id=\"chatbot\", height=750, avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))))\n", "\n", " with gr.Row():\n", " with gr.Column(scale=0.85):\n", " txt = gr.Textbox(\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False)\n", " with gr.Column(scale=0.15, min_width=0):\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.update(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))),\n", " )\n", "\n", " with gr.Row():\n", " txt = gr.Textbox(\n", " scale=4,\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False,\n", " )\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/chatbot_multimodal/run.py b/demo/chatbot_multimodal/run.py index 6feaadd1d7..a17297451a 100644 --- a/demo/chatbot_multimodal/run.py +++ b/demo/chatbot_multimodal/run.py @@ -4,6 +4,7 @@ import time # Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. + def add_text(history, text): history = history + [(text, None)] return history, gr.update(value="", interactive=False) @@ -24,16 +25,20 @@ def bot(history): with gr.Blocks() as demo: - chatbot = gr.Chatbot([], elem_id="chatbot", height=750, avatar_images=(None, (os.path.join(os.path.dirname(__file__), "avatar.png")))) + chatbot = gr.Chatbot( + [], + elem_id="chatbot", + avatar_images=(None, (os.path.join(os.path.dirname(__file__), "avatar.png"))), + ) with gr.Row(): - with gr.Column(scale=0.85): - txt = gr.Textbox( - show_label=False, - placeholder="Enter text and press enter, or upload an image", - container=False) - with gr.Column(scale=0.15, min_width=0): - btn = gr.UploadButton("šŸ“", file_types=["image", "video", "audio"]) + txt = gr.Textbox( + scale=4, + show_label=False, + placeholder="Enter text and press enter, or upload an image", + container=False, + ) + btn = gr.UploadButton("šŸ“", file_types=["image", "video", "audio"]) txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then( bot, chatbot, chatbot diff --git a/demo/dashboard/run.ipynb b/demo/dashboard/run.ipynb index 0d8670bc31..06abbaf396 100644 --- a/demo/dashboard/run.ipynb +++ b/demo/dashboard/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dashboard\n", "### This demo shows how you can build an interactive dashboard with gradio. Click on a python library on the left hand side and then on the right hand side click on the metric you'd like to see plot over time. Data is pulled from HuggingFace Hub datasets.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"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/dashboard/helpers.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "import plotly.express as px\n", "from helpers import *\n", "\n", "\n", "LIBRARIES = [\"accelerate\", \"datasets\", \"diffusers\", \"evaluate\", \"gradio\", \"hub_docs\",\n", " \"huggingface_hub\", \"optimum\", \"pytorch_image_models\", \"tokenizers\", \"transformers\"]\n", "\n", "\n", "def create_pip_plot(libraries, pip_choices):\n", " if \"Pip\" not in pip_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_pip_installs(libraries, \"Cumulated\" in pip_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Pip installs\")\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "def create_star_plot(libraries, star_choices):\n", " if \"Stars\" not in star_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_stars(libraries, \"Week over Week\" in star_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Number of stargazers\")\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "def create_issue_plot(libraries, issue_choices):\n", " if \"Issue\" not in issue_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_issues(libraries,\n", " exclude_org_members=\"Exclude org members\" in issue_choices,\n", " week_over_week=\"Week over Week\" in issue_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Cumulated number of issues, PRs, and comments\",\n", " )\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " with gr.Box():\n", " gr.Markdown(\"## Select libraries to display\")\n", " libraries = gr.CheckboxGroup(choices=LIBRARIES, label=\"\")\n", " with gr.Column():\n", " with gr.Box():\n", " gr.Markdown(\"## Select graphs to display\")\n", " pip = gr.CheckboxGroup(choices=[\"Pip\", \"Cumulated\"], label=\"\")\n", " stars = gr.CheckboxGroup(choices=[\"Stars\", \"Week over Week\"], label=\"\")\n", " issues = gr.CheckboxGroup(choices=[\"Issue\", \"Exclude org members\", \"week over week\"], label=\"\")\n", " with gr.Row():\n", " fetch = gr.Button(value=\"Fetch\")\n", " with gr.Row():\n", " with gr.Column():\n", " pip_plot = gr.Plot(visible=False)\n", " star_plot = gr.Plot(visible=False)\n", " issue_plot = gr.Plot(visible=False)\n", "\n", " fetch.click(create_pip_plot, inputs=[libraries, pip], outputs=pip_plot)\n", " fetch.click(create_star_plot, inputs=[libraries, stars], outputs=star_plot)\n", " fetch.click(create_issue_plot, inputs=[libraries, issues], outputs=issue_plot)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dashboard\n", "### This demo shows how you can build an interactive dashboard with gradio. Click on a python library on the left hand side and then on the right hand side click on the metric you'd like to see plot over time. Data is pulled from HuggingFace Hub datasets.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"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/dashboard/helpers.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "import plotly.express as px\n", "from helpers import *\n", "\n", "\n", "LIBRARIES = [\"accelerate\", \"datasets\", \"diffusers\", \"evaluate\", \"gradio\", \"hub_docs\",\n", " \"huggingface_hub\", \"optimum\", \"pytorch_image_models\", \"tokenizers\", \"transformers\"]\n", "\n", "\n", "def create_pip_plot(libraries, pip_choices):\n", " if \"Pip\" not in pip_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_pip_installs(libraries, \"Cumulated\" in pip_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Pip installs\")\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "def create_star_plot(libraries, star_choices):\n", " if \"Stars\" not in star_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_stars(libraries, \"Week over Week\" in star_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Number of stargazers\")\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "def create_issue_plot(libraries, issue_choices):\n", " if \"Issue\" not in issue_choices:\n", " return gr.update(visible=False)\n", " output = retrieve_issues(libraries,\n", " exclude_org_members=\"Exclude org members\" in issue_choices,\n", " week_over_week=\"Week over Week\" in issue_choices)\n", " df = pd.DataFrame(output).melt(id_vars=\"day\")\n", " plot = px.line(df, x=\"day\", y=\"value\", color=\"variable\",\n", " title=\"Cumulated number of issues, PRs, and comments\",\n", " )\n", " plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text=\"\")\n", " return gr.update(value=plot, visible=True)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Markdown(\"## Select libraries to display\")\n", " libraries = gr.CheckboxGroup(choices=LIBRARIES, label=\"\")\n", " with gr.Column():\n", " gr.Markdown(\"## Select graphs to display\")\n", " pip = gr.CheckboxGroup(choices=[\"Pip\", \"Cumulated\"], label=\"\")\n", " stars = gr.CheckboxGroup(choices=[\"Stars\", \"Week over Week\"], label=\"\")\n", " issues = gr.CheckboxGroup(choices=[\"Issue\", \"Exclude org members\", \"week over week\"], label=\"\")\n", " with gr.Row():\n", " fetch = gr.Button(value=\"Fetch\")\n", " with gr.Row():\n", " with gr.Column():\n", " pip_plot = gr.Plot(visible=False)\n", " star_plot = gr.Plot(visible=False)\n", " issue_plot = gr.Plot(visible=False)\n", "\n", " fetch.click(create_pip_plot, inputs=[libraries, pip], outputs=pip_plot)\n", " fetch.click(create_star_plot, inputs=[libraries, stars], outputs=star_plot)\n", " fetch.click(create_issue_plot, inputs=[libraries, issues], outputs=issue_plot)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/dashboard/run.py b/demo/dashboard/run.py index 24073040b1..8f14689c3c 100644 --- a/demo/dashboard/run.py +++ b/demo/dashboard/run.py @@ -47,15 +47,13 @@ def create_issue_plot(libraries, issue_choices): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): - with gr.Box(): - gr.Markdown("## Select libraries to display") - libraries = gr.CheckboxGroup(choices=LIBRARIES, label="") + gr.Markdown("## Select libraries to display") + libraries = gr.CheckboxGroup(choices=LIBRARIES, label="") with gr.Column(): - with gr.Box(): - gr.Markdown("## Select graphs to display") - pip = gr.CheckboxGroup(choices=["Pip", "Cumulated"], label="") - stars = gr.CheckboxGroup(choices=["Stars", "Week over Week"], label="") - issues = gr.CheckboxGroup(choices=["Issue", "Exclude org members", "week over week"], label="") + gr.Markdown("## Select graphs to display") + pip = gr.CheckboxGroup(choices=["Pip", "Cumulated"], label="") + stars = gr.CheckboxGroup(choices=["Stars", "Week over Week"], label="") + issues = gr.CheckboxGroup(choices=["Issue", "Exclude org members", "week over week"], label="") with gr.Row(): fetch = gr.Button(value="Fetch") with gr.Row(): diff --git a/demo/diff_texts/run.ipynb b/demo/diff_texts/run.ipynb index 2ea67fe392..b83ece9c39 100644 --- a/demo/diff_texts/run.ipynb +++ b/demo/diff_texts/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: diff_texts"]}, {"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": ["from difflib import Differ\n", "\n", "import gradio as gr\n", "\n", "\n", "def diff_texts(text1, text2):\n", " d = Differ()\n", " return [\n", " (token[2:], token[0] if token[0] != \" \" else None)\n", " for token in d.compare(text1, text2)\n", " ]\n", "\n", "\n", "demo = gr.Interface(\n", " diff_texts,\n", " [\n", " gr.Textbox(\n", " label=\"Text 1\",\n", " info=\"Initial text\",\n", " lines=3,\n", " value=\"The quick brown fox jumped over the lazy dogs.\",\n", " ),\n", " gr.Textbox(\n", " label=\"Text 2\",\n", " info=\"Text to compare\",\n", " lines=3,\n", " value=\"The fast brown fox jumps over lazy dogs.\",\n", " ),\n", " ],\n", " gr.HighlightedText(\n", " label=\"Diff\",\n", " combine_adjacent=True,\n", " show_legend=True,\n", " ).style(color_map={\"+\": \"red\", \"-\": \"green\"}),\n", " theme=gr.themes.Base()\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: diff_texts"]}, {"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": ["from difflib import Differ\n", "\n", "import gradio as gr\n", "\n", "\n", "def diff_texts(text1, text2):\n", " d = Differ()\n", " return [\n", " (token[2:], token[0] if token[0] != \" \" else None)\n", " for token in d.compare(text1, text2)\n", " ]\n", "\n", "\n", "demo = gr.Interface(\n", " diff_texts,\n", " [\n", " gr.Textbox(\n", " label=\"Text 1\",\n", " info=\"Initial text\",\n", " lines=3,\n", " value=\"The quick brown fox jumped over the lazy dogs.\",\n", " ),\n", " gr.Textbox(\n", " label=\"Text 2\",\n", " info=\"Text to compare\",\n", " lines=3,\n", " value=\"The fast brown fox jumps over lazy dogs.\",\n", " ),\n", " ],\n", " gr.HighlightedText(\n", " label=\"Diff\",\n", " combine_adjacent=True,\n", " show_legend=True,\n", " color_map={\"+\": \"red\", \"-\": \"green\"}),\n", " theme=gr.themes.Base()\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/diff_texts/run.py b/demo/diff_texts/run.py index ddacac53be..badf25a0d7 100644 --- a/demo/diff_texts/run.py +++ b/demo/diff_texts/run.py @@ -31,7 +31,7 @@ demo = gr.Interface( label="Diff", combine_adjacent=True, show_legend=True, - ).style(color_map={"+": "red", "-": "green"}), + color_map={"+": "red", "-": "green"}), theme=gr.themes.Base() ) if __name__ == "__main__": diff --git a/demo/fake_gan/run.ipynb b/demo/fake_gan/run.ipynb index c053bb0eec..cd6cfb3d37 100644 --- a/demo/fake_gan/run.ipynb +++ b/demo/fake_gan/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan\n", "### This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " images = [\n", " (random.choice(\n", " [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " \"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80\",\n", " ]\n", " ), f\"label {i}\" if i != 0 else \"label\" * 50)\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column(variant=\"panel\"):\n", " with gr.Row(variant=\"compact\"):\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " show_label=False,\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " ).style(\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\").style(full_width=False)\n", "\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " ).style(columns=[2], rows=[2], object_fit=\"contain\", height=\"auto\")\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan\n", "### This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " images = [\n", " (random.choice(\n", " [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " \"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80\",\n", " ]\n", " ), f\"label {i}\" if i != 0 else \"label\" * 50)\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column(variant=\"panel\"):\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\", scale=0)\n", "\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " , columns=[2], rows=[2], object_fit=\"contain\", height=\"auto\")\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/fake_gan/run.py b/demo/fake_gan/run.py index 6757a78462..b8d8ab732d 100644 --- a/demo/fake_gan/run.py +++ b/demo/fake_gan/run.py @@ -23,20 +23,18 @@ def fake_gan(): with gr.Blocks() as demo: with gr.Column(variant="panel"): - with gr.Row(variant="compact"): + with gr.Row(): text = gr.Textbox( label="Enter your prompt", - show_label=False, max_lines=1, placeholder="Enter your prompt", - ).style( container=False, ) - btn = gr.Button("Generate image").style(full_width=False) + btn = gr.Button("Generate image", scale=0) gallery = gr.Gallery( label="Generated images", show_label=False, elem_id="gallery" - ).style(columns=[2], rows=[2], object_fit="contain", height="auto") + , columns=[2], rows=[2], object_fit="contain", height="auto") btn.click(fake_gan, None, gallery) diff --git a/demo/fake_gan_no_input/run.ipynb b/demo/fake_gan_no_input/run.ipynb index 2819f34d17..411088e0f7 100644 --- a/demo/fake_gan_no_input/run.ipynb +++ b/demo/fake_gan_no_input/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan_no_input"]}, {"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", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " time.sleep(1)\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", " return images\n", "\n", "\n", "demo = gr.Interface(\n", " fn=fake_gan,\n", " inputs=None,\n", " outputs=gr.Gallery(label=\"Generated Images\").style(grid=[2]),\n", " title=\"FD-GAN\",\n", " description=\"This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan_no_input"]}, {"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", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " time.sleep(1)\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", " return images\n", "\n", "\n", "demo = gr.Interface(\n", " fn=fake_gan,\n", " inputs=None,\n", " outputs=gr.Gallery(label=\"Generated Images\", columns=[2]),\n", " title=\"FD-GAN\",\n", " description=\"This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.\",\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/demo/fake_gan_no_input/run.py b/demo/fake_gan_no_input/run.py index 156012abf3..de46905c56 100644 --- a/demo/fake_gan_no_input/run.py +++ b/demo/fake_gan_no_input/run.py @@ -16,7 +16,7 @@ def fake_gan(): demo = gr.Interface( fn=fake_gan, inputs=None, - outputs=gr.Gallery(label="Generated Images").style(grid=[2]), + outputs=gr.Gallery(label="Generated Images", columns=[2]), title="FD-GAN", description="This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.", ) diff --git a/demo/gallery_component/run.ipynb b/demo/gallery_component/run.ipynb index c3d3b0f71c..875dea1801 100644 --- a/demo/gallery_component/run.ipynb +++ b/demo/gallery_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gallery_component"]}, {"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", " cheetahs = [\n", " \"https://upload.wikimedia.org/wikipedia/commons/0/09/TheCheethcat.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-003.jpg\",\n", " \"https://img.etimg.com/thumb/msid-50159822,width-650,imgsize-129520,,resizemode-4,quality-100/.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-002.jpg\",\n", " \"https://images.theconversation.com/files/375893/original/file-20201218-13-a8h8uq.jpg?ixlib=rb-1.1.0&rect=16%2C407%2C5515%2C2924&q=45&auto=format&w=496&fit=clip\",\n", " \"https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg\",\n", " \"https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq\"\n", " ]\n", " gr.Gallery(value=cheetahs).style(grid=4)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gallery_component"]}, {"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", " cheetahs = [\n", " \"https://upload.wikimedia.org/wikipedia/commons/0/09/TheCheethcat.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-003.jpg\",\n", " \"https://img.etimg.com/thumb/msid-50159822,width-650,imgsize-129520,,resizemode-4,quality-100/.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-002.jpg\",\n", " \"https://images.theconversation.com/files/375893/original/file-20201218-13-a8h8uq.jpg?ixlib=rb-1.1.0&rect=16%2C407%2C5515%2C2924&q=45&auto=format&w=496&fit=clip\",\n", " \"https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg\",\n", " \"https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq\"\n", " ]\n", " gr.Gallery(value=cheetahs, columns=4)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/gallery_component/run.py b/demo/gallery_component/run.py index 3487906d32..3acc659c7a 100644 --- a/demo/gallery_component/run.py +++ b/demo/gallery_component/run.py @@ -10,6 +10,6 @@ with gr.Blocks() as demo: "https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg", "https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq" ] - gr.Gallery(value=cheetahs).style(grid=4) + gr.Gallery(value=cheetahs, columns=4) demo.launch() \ No newline at end of file diff --git a/demo/image_segmentation/run.ipynb b/demo/image_segmentation/run.ipynb index 9e52b323c1..8544aedd02 100644 --- a/demo/image_segmentation/run.ipynb +++ b/demo/image_segmentation/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_segmentation\n", "### Simple image segmentation using gradio's AnnotatedImage component.\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": ["import gradio as gr\n", "import numpy as np\n", "import random\n", "\n", "with gr.Blocks() as demo:\n", " section_labels = [\n", " \"apple\",\n", " \"banana\",\n", " \"carrot\",\n", " \"donut\",\n", " \"eggplant\",\n", " \"fish\",\n", " \"grapes\",\n", " \"hamburger\",\n", " \"ice cream\",\n", " \"juice\",\n", " ]\n", "\n", " with gr.Row():\n", " num_boxes = gr.Slider(0, 5, 2, step=1, label=\"Number of boxes\")\n", " num_segments = gr.Slider(0, 5, 1, step=1, label=\"Number of segments\")\n", "\n", " with gr.Row():\n", " img_input = gr.Image()\n", " img_output = gr.AnnotatedImage().style(\n", " color_map={\"banana\": \"#a89a00\", \"carrot\": \"#ffae00\"}\n", " )\n", "\n", " section_btn = gr.Button(\"Identify Sections\")\n", " selected_section = gr.Textbox(label=\"Selected Section\")\n", "\n", " def section(img, num_boxes, num_segments):\n", " sections = []\n", " for a in range(num_boxes):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " w = random.randint(0, img.shape[1] - x)\n", " h = random.randint(0, img.shape[0] - y)\n", " sections.append(((x, y, x + w, y + h), section_labels[a]))\n", " for b in range(num_segments):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))\n", " mask = np.zeros(img.shape[:2])\n", " for i in range(img.shape[0]):\n", " for j in range(img.shape[1]):\n", " dist_square = (i - y) ** 2 + (j - x) ** 2\n", " if dist_square < r**2:\n", " mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4\n", " sections.append((mask, section_labels[b + num_boxes]))\n", " return (img, sections)\n", "\n", " section_btn.click(section, [img_input, num_boxes, num_segments], img_output)\n", "\n", " def select_section(evt: gr.SelectData):\n", " return section_labels[evt.index]\n", "\n", " img_output.select(select_section, None, selected_section)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_segmentation\n", "### Simple image segmentation using gradio's AnnotatedImage component.\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": ["import gradio as gr\n", "import numpy as np\n", "import random\n", "\n", "with gr.Blocks() as demo:\n", " section_labels = [\n", " \"apple\",\n", " \"banana\",\n", " \"carrot\",\n", " \"donut\",\n", " \"eggplant\",\n", " \"fish\",\n", " \"grapes\",\n", " \"hamburger\",\n", " \"ice cream\",\n", " \"juice\",\n", " ]\n", "\n", " with gr.Row():\n", " num_boxes = gr.Slider(0, 5, 2, step=1, label=\"Number of boxes\")\n", " num_segments = gr.Slider(0, 5, 1, step=1, label=\"Number of segments\")\n", "\n", " with gr.Row():\n", " img_input = gr.Image()\n", " img_output = gr.AnnotatedImage(\n", " color_map={\"banana\": \"#a89a00\", \"carrot\": \"#ffae00\"}\n", " )\n", "\n", " section_btn = gr.Button(\"Identify Sections\")\n", " selected_section = gr.Textbox(label=\"Selected Section\")\n", "\n", " def section(img, num_boxes, num_segments):\n", " sections = []\n", " for a in range(num_boxes):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " w = random.randint(0, img.shape[1] - x)\n", " h = random.randint(0, img.shape[0] - y)\n", " sections.append(((x, y, x + w, y + h), section_labels[a]))\n", " for b in range(num_segments):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))\n", " mask = np.zeros(img.shape[:2])\n", " for i in range(img.shape[0]):\n", " for j in range(img.shape[1]):\n", " dist_square = (i - y) ** 2 + (j - x) ** 2\n", " if dist_square < r**2:\n", " mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4\n", " sections.append((mask, section_labels[b + num_boxes]))\n", " return (img, sections)\n", "\n", " section_btn.click(section, [img_input, num_boxes, num_segments], img_output)\n", "\n", " def select_section(evt: gr.SelectData):\n", " return section_labels[evt.index]\n", "\n", " img_output.select(select_section, None, selected_section)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/image_segmentation/run.py b/demo/image_segmentation/run.py index 6918d9ae9b..af3793f321 100644 --- a/demo/image_segmentation/run.py +++ b/demo/image_segmentation/run.py @@ -22,7 +22,7 @@ with gr.Blocks() as demo: with gr.Row(): img_input = gr.Image() - img_output = gr.AnnotatedImage().style( + img_output = gr.AnnotatedImage( color_map={"banana": "#a89a00", "carrot": "#ffae00"} ) diff --git a/demo/kitchen_sink/run.ipynb b/demo/kitchen_sink/run.ipynb index 2174fbf389..257071e586 100644 --- a/demo/kitchen_sink/run.ipynb +++ b/demo/kitchen_sink/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: kitchen_sink"]}, {"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/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cheetah1.jpg\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/lion.jpg\n", "!wget -q -O files/logo.png https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/logo.png\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/titanic.csv\n", "!wget -q -O files/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/tower.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import json\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "CHOICES = [\"foo\", \"bar\", \"baz\"]\n", "JSONOBJ = \"\"\"{\"items\":{\"item\":[{\"id\": \"0001\",\"type\": null,\"is_good\": false,\"ppu\": 0.55,\"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" },{ \"id\": \"1003\", \"type\": \"Blueberry\" },{ \"id\": \"1004\", \"type\": \"Devil's Food\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" },{ \"id\": \"5005\", \"type\": \"Sugar\" },{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },{ \"id\": \"5003\", \"type\": \"Chocolate\" },{ \"id\": \"5004\", \"type\": \"Maple\" }]}]}}\"\"\"\n", "\n", "\n", "def fn(\n", " text1,\n", " text2,\n", " num,\n", " slider1,\n", " slider2,\n", " single_checkbox,\n", " checkboxes,\n", " radio,\n", " dropdown,\n", " multi_dropdown,\n", " im1,\n", " im2,\n", " im3,\n", " im4,\n", " video,\n", " audio1,\n", " audio2,\n", " file,\n", " df1,\n", " df2,\n", "):\n", " return (\n", " (text1 if single_checkbox else text2)\n", " + \", selected:\"\n", " + \", \".join(checkboxes), # Text\n", " {\n", " \"positive\": num / (num + slider1 + slider2),\n", " \"negative\": slider1 / (num + slider1 + slider2),\n", " \"neutral\": slider2 / (num + slider1 + slider2),\n", " }, # Label\n", " (audio1[0], np.flipud(audio1[1]))\n", " if audio1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cantina.wav\"), # Audio\n", " np.flipud(im1)\n", " if im1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"), # Image\n", " video\n", " if video is not None\n", " else os.path.join(os.path.abspath(''), \"files/world.mp4\"), # Video\n", " [\n", " (\"The\", \"art\"),\n", " (\"quick brown\", \"adj\"),\n", " (\"fox\", \"nn\"),\n", " (\"jumped\", \"vrb\"),\n", " (\"testing testing testing\", None),\n", " (\"over\", \"prp\"),\n", " (\"the\", \"art\"),\n", " (\"testing\", None),\n", " (\"lazy\", \"adj\"),\n", " (\"dogs\", \"nn\"),\n", " (\".\", \"punc\"),\n", " ]\n", " + [(f\"test {x}\", f\"test {x}\") for x in range(10)], # HighlightedText\n", " # [(\"The testing testing testing\", None), (\"quick brown\", 0.2), (\"fox\", 1), (\"jumped\", -1), (\"testing testing testing\", 0), (\"over\", 0), (\"the\", 0), (\"testing\", 0), (\"lazy\", 1), (\"dogs\", 0), (\".\", 1)] + [(f\"test {x}\", x/10) for x in range(-10, 10)], # HighlightedText\n", " [\n", " (\"The testing testing testing\", None),\n", " (\"over\", 0.6),\n", " (\"the\", 0.2),\n", " (\"testing\", None),\n", " (\"lazy\", -0.1),\n", " (\"dogs\", 0.4),\n", " (\".\", 0),\n", " ]\n", " + [(f\"test\", x / 10) for x in range(-10, 10)], # HighlightedText\n", " json.loads(JSONOBJ), # JSON\n", " \"\", # HTML\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " df1, # Dataframe\n", " np.random.randint(0, 10, (4, 4)), # Dataframe\n", " df2, # Timeseries\n", " )\n", "\n", "\n", "demo = gr.Interface(\n", " fn,\n", " inputs=[\n", " gr.Textbox(value=\"Lorem ipsum\", label=\"Textbox\"),\n", " gr.Textbox(lines=3, placeholder=\"Type here..\", label=\"Textbox 2\"),\n", " gr.Number(label=\"Number\", value=42),\n", " gr.Slider(10, 20, value=15, label=\"Slider: 10 - 20\"),\n", " gr.Slider(maximum=20, step=0.04, label=\"Slider: step @ 0.04\"),\n", " gr.Checkbox(label=\"Checkbox\"),\n", " gr.CheckboxGroup(label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]),\n", " gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", " gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\n", " gr.Dropdown(label=\"Multiselect Dropdown (Max choice: 2)\", choices=CHOICES, multiselect=True, max_choices=2),\n", " gr.Image(label=\"Image\"),\n", " gr.Image(label=\"Image w/ Cropper\", tool=\"select\"),\n", " gr.Image(label=\"Sketchpad\", source=\"canvas\"),\n", " gr.Image(label=\"Webcam\", source=\"webcam\"),\n", " gr.Video(label=\"Video\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Audio(label=\"Microphone\", source=\"microphone\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\", headers=[\"Name\", \"Age\", \"Gender\"]),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], colors=[\"pink\", \"purple\"]),\n", " ],\n", " outputs=[\n", " gr.Textbox(label=\"Textbox\"),\n", " gr.Label(label=\"Label\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Image(label=\"Image\"),\n", " gr.Video(label=\"Video\"),\n", " gr.HighlightedText(label=\"HighlightedText\").style(\n", " color_map={\"punc\": \"pink\", \"test 0\": \"blue\"}\n", " ),\n", " gr.HighlightedText(label=\"HighlightedText\", show_legend=True),\n", " gr.JSON(label=\"JSON\"),\n", " gr.HTML(label=\"HTML\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\"),\n", " gr.Dataframe(label=\"Numpy\"),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], label=\"Timeseries\"),\n", " ],\n", " examples=[\n", " [\n", " \"the quick brown fox\",\n", " \"jumps over the lazy dog\",\n", " 10,\n", " 12,\n", " 4,\n", " True,\n", " [\"foo\", \"baz\"],\n", " \"baz\",\n", " \"bar\",\n", " [\"foo\", \"bar\"],\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/world.mp4\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],\n", " os.path.join(os.path.abspath(''), \"files/time.csv\"),\n", " ]\n", " ]\n", " * 3,\n", " title=\"Kitchen Sink\",\n", " description=\"Try out all the components!\",\n", " article=\"Learn more about [Gradio](http://gradio.app)\",\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: kitchen_sink"]}, {"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/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cheetah1.jpg\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/lion.jpg\n", "!wget -q -O files/logo.png https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/logo.png\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/titanic.csv\n", "!wget -q -O files/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/tower.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import json\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "CHOICES = [\"foo\", \"bar\", \"baz\"]\n", "JSONOBJ = \"\"\"{\"items\":{\"item\":[{\"id\": \"0001\",\"type\": null,\"is_good\": false,\"ppu\": 0.55,\"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" },{ \"id\": \"1003\", \"type\": \"Blueberry\" },{ \"id\": \"1004\", \"type\": \"Devil's Food\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" },{ \"id\": \"5005\", \"type\": \"Sugar\" },{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },{ \"id\": \"5003\", \"type\": \"Chocolate\" },{ \"id\": \"5004\", \"type\": \"Maple\" }]}]}}\"\"\"\n", "\n", "\n", "def fn(\n", " text1,\n", " text2,\n", " num,\n", " slider1,\n", " slider2,\n", " single_checkbox,\n", " checkboxes,\n", " radio,\n", " dropdown,\n", " multi_dropdown,\n", " im1,\n", " im2,\n", " im3,\n", " im4,\n", " video,\n", " audio1,\n", " audio2,\n", " file,\n", " df1,\n", " df2,\n", "):\n", " return (\n", " (text1 if single_checkbox else text2)\n", " + \", selected:\"\n", " + \", \".join(checkboxes), # Text\n", " {\n", " \"positive\": num / (num + slider1 + slider2),\n", " \"negative\": slider1 / (num + slider1 + slider2),\n", " \"neutral\": slider2 / (num + slider1 + slider2),\n", " }, # Label\n", " (audio1[0], np.flipud(audio1[1]))\n", " if audio1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cantina.wav\"), # Audio\n", " np.flipud(im1)\n", " if im1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"), # Image\n", " video\n", " if video is not None\n", " else os.path.join(os.path.abspath(''), \"files/world.mp4\"), # Video\n", " [\n", " (\"The\", \"art\"),\n", " (\"quick brown\", \"adj\"),\n", " (\"fox\", \"nn\"),\n", " (\"jumped\", \"vrb\"),\n", " (\"testing testing testing\", None),\n", " (\"over\", \"prp\"),\n", " (\"the\", \"art\"),\n", " (\"testing\", None),\n", " (\"lazy\", \"adj\"),\n", " (\"dogs\", \"nn\"),\n", " (\".\", \"punc\"),\n", " ]\n", " + [(f\"test {x}\", f\"test {x}\") for x in range(10)], # HighlightedText\n", " # [(\"The testing testing testing\", None), (\"quick brown\", 0.2), (\"fox\", 1), (\"jumped\", -1), (\"testing testing testing\", 0), (\"over\", 0), (\"the\", 0), (\"testing\", 0), (\"lazy\", 1), (\"dogs\", 0), (\".\", 1)] + [(f\"test {x}\", x/10) for x in range(-10, 10)], # HighlightedText\n", " [\n", " (\"The testing testing testing\", None),\n", " (\"over\", 0.6),\n", " (\"the\", 0.2),\n", " (\"testing\", None),\n", " (\"lazy\", -0.1),\n", " (\"dogs\", 0.4),\n", " (\".\", 0),\n", " ]\n", " + [(f\"test\", x / 10) for x in range(-10, 10)], # HighlightedText\n", " json.loads(JSONOBJ), # JSON\n", " \"\", # HTML\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " df1, # Dataframe\n", " np.random.randint(0, 10, (4, 4)), # Dataframe\n", " df2, # Timeseries\n", " )\n", "\n", "\n", "demo = gr.Interface(\n", " fn,\n", " inputs=[\n", " gr.Textbox(value=\"Lorem ipsum\", label=\"Textbox\"),\n", " gr.Textbox(lines=3, placeholder=\"Type here..\", label=\"Textbox 2\"),\n", " gr.Number(label=\"Number\", value=42),\n", " gr.Slider(10, 20, value=15, label=\"Slider: 10 - 20\"),\n", " gr.Slider(maximum=20, step=0.04, label=\"Slider: step @ 0.04\"),\n", " gr.Checkbox(label=\"Checkbox\"),\n", " gr.CheckboxGroup(label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]),\n", " gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", " gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\n", " gr.Dropdown(label=\"Multiselect Dropdown (Max choice: 2)\", choices=CHOICES, multiselect=True, max_choices=2),\n", " gr.Image(label=\"Image\"),\n", " gr.Image(label=\"Image w/ Cropper\", tool=\"select\"),\n", " gr.Image(label=\"Sketchpad\", source=\"canvas\"),\n", " gr.Image(label=\"Webcam\", source=\"webcam\"),\n", " gr.Video(label=\"Video\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Audio(label=\"Microphone\", source=\"microphone\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\", headers=[\"Name\", \"Age\", \"Gender\"]),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], colors=[\"pink\", \"purple\"]),\n", " ],\n", " outputs=[\n", " gr.Textbox(label=\"Textbox\"),\n", " gr.Label(label=\"Label\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Image(label=\"Image\"),\n", " gr.Video(label=\"Video\"),\n", " gr.HighlightedText(label=\"HighlightedText\", \n", " color_map={\"punc\": \"pink\", \"test 0\": \"blue\"}\n", " ),\n", " gr.HighlightedText(label=\"HighlightedText\", show_legend=True),\n", " gr.JSON(label=\"JSON\"),\n", " gr.HTML(label=\"HTML\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\"),\n", " gr.Dataframe(label=\"Numpy\"),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], label=\"Timeseries\"),\n", " ],\n", " examples=[\n", " [\n", " \"the quick brown fox\",\n", " \"jumps over the lazy dog\",\n", " 10,\n", " 12,\n", " 4,\n", " True,\n", " [\"foo\", \"baz\"],\n", " \"baz\",\n", " \"bar\",\n", " [\"foo\", \"bar\"],\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/world.mp4\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],\n", " os.path.join(os.path.abspath(''), \"files/time.csv\"),\n", " ]\n", " ]\n", " * 3,\n", " title=\"Kitchen Sink\",\n", " description=\"Try out all the components!\",\n", " article=\"Learn more about [Gradio](http://gradio.app)\",\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/kitchen_sink/run.py b/demo/kitchen_sink/run.py index 196ed596a4..70a2715006 100755 --- a/demo/kitchen_sink/run.py +++ b/demo/kitchen_sink/run.py @@ -115,7 +115,7 @@ demo = gr.Interface( gr.Audio(label="Audio"), gr.Image(label="Image"), gr.Video(label="Video"), - gr.HighlightedText(label="HighlightedText").style( + gr.HighlightedText(label="HighlightedText", color_map={"punc": "pink", "test 0": "blue"} ), gr.HighlightedText(label="HighlightedText", show_legend=True), diff --git a/demo/lineplot_component/run.ipynb b/demo/lineplot_component/run.ipynb index 7d345c77b0..9a118e0084 100644 --- a/demo/lineplot_component/run.ipynb +++ b/demo/lineplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: lineplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "with gr.Blocks() as demo:\n", " gr.LinePlot(\n", " data.stocks(),\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=300,\n", " show_label=False,\n", " ).style(\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: lineplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "with gr.Blocks() as demo:\n", " gr.LinePlot(\n", " data.stocks(),\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=300,\n", " container=False,\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/demo/lineplot_component/run.py b/demo/lineplot_component/run.py index 0bb731fd95..e1a236d19e 100644 --- a/demo/lineplot_component/run.py +++ b/demo/lineplot_component/run.py @@ -12,8 +12,6 @@ with gr.Blocks() as demo: tooltip=["date", "price", "symbol"], height=300, width=300, - show_label=False, - ).style( container=False, ) diff --git a/demo/map_airbnb/run.ipynb b/demo/map_airbnb/run.ipynb index 77050d3f6e..d94989ab55 100644 --- a/demo/map_airbnb/run.ipynb +++ b/demo/map_airbnb/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: map_airbnb\n", "### Display an interactive map of AirBnB locations with Plotly. Data is hosted on HuggingFace Datasets. \n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import plotly.graph_objects as go\n", "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\n", "df = dataset.to_pandas()\n", "\n", "def filter_map(min_price, max_price, boroughs):\n", "\n", " filtered_df = df[(df['neighbourhood_group'].isin(boroughs)) & \n", " (df['price'] > min_price) & (df['price'] < max_price)]\n", " names = filtered_df[\"name\"].tolist()\n", " prices = filtered_df[\"price\"].tolist()\n", " text_list = [(names[i], prices[i]) for i in range(0, len(names))]\n", " fig = go.Figure(go.Scattermapbox(\n", " customdata=text_list,\n", " lat=filtered_df['latitude'].tolist(),\n", " lon=filtered_df['longitude'].tolist(),\n", " mode='markers',\n", " marker=go.scattermapbox.Marker(\n", " size=6\n", " ),\n", " hoverinfo=\"text\",\n", " hovertemplate='Name: %{customdata[0]}
Price: $%{customdata[1]}'\n", " ))\n", "\n", " fig.update_layout(\n", " mapbox_style=\"open-street-map\",\n", " hovermode='closest',\n", " mapbox=dict(\n", " bearing=0,\n", " center=go.layout.mapbox.Center(\n", " lat=40.67,\n", " lon=-73.90\n", " ),\n", " pitch=0,\n", " zoom=9\n", " ),\n", " )\n", "\n", " return fig\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column():\n", " with gr.Row():\n", " min_price = gr.Number(value=250, label=\"Minimum Price\")\n", " max_price = gr.Number(value=1000, label=\"Maximum Price\")\n", " boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n", " btn = gr.Button(value=\"Update Filter\")\n", " map = gr.Plot().style()\n", " demo.load(filter_map, [min_price, max_price, boroughs], map)\n", " btn.click(filter_map, [min_price, max_price, boroughs], map)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: map_airbnb\n", "### Display an interactive map of AirBnB locations with Plotly. Data is hosted on HuggingFace Datasets. \n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import plotly.graph_objects as go\n", "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\n", "df = dataset.to_pandas()\n", "\n", "def filter_map(min_price, max_price, boroughs):\n", "\n", " filtered_df = df[(df['neighbourhood_group'].isin(boroughs)) & \n", " (df['price'] > min_price) & (df['price'] < max_price)]\n", " names = filtered_df[\"name\"].tolist()\n", " prices = filtered_df[\"price\"].tolist()\n", " text_list = [(names[i], prices[i]) for i in range(0, len(names))]\n", " fig = go.Figure(go.Scattermapbox(\n", " customdata=text_list,\n", " lat=filtered_df['latitude'].tolist(),\n", " lon=filtered_df['longitude'].tolist(),\n", " mode='markers',\n", " marker=go.scattermapbox.Marker(\n", " size=6\n", " ),\n", " hoverinfo=\"text\",\n", " hovertemplate='Name: %{customdata[0]}
Price: $%{customdata[1]}'\n", " ))\n", "\n", " fig.update_layout(\n", " mapbox_style=\"open-street-map\",\n", " hovermode='closest',\n", " mapbox=dict(\n", " bearing=0,\n", " center=go.layout.mapbox.Center(\n", " lat=40.67,\n", " lon=-73.90\n", " ),\n", " pitch=0,\n", " zoom=9\n", " ),\n", " )\n", "\n", " return fig\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column():\n", " with gr.Row():\n", " min_price = gr.Number(value=250, label=\"Minimum Price\")\n", " max_price = gr.Number(value=1000, label=\"Maximum Price\")\n", " boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n", " btn = gr.Button(value=\"Update Filter\")\n", " map = gr.Plot()\n", " demo.load(filter_map, [min_price, max_price, boroughs], map)\n", " btn.click(filter_map, [min_price, max_price, boroughs], map)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/map_airbnb/run.py b/demo/map_airbnb/run.py index 46f3091a81..cc770e5615 100644 --- a/demo/map_airbnb/run.py +++ b/demo/map_airbnb/run.py @@ -47,7 +47,7 @@ with gr.Blocks() as demo: max_price = gr.Number(value=1000, label="Maximum Price") boroughs = gr.CheckboxGroup(choices=["Queens", "Brooklyn", "Manhattan", "Bronx", "Staten Island"], value=["Queens", "Brooklyn"], label="Select Boroughs:") btn = gr.Button(value="Update Filter") - map = gr.Plot().style() + map = gr.Plot() demo.load(filter_map, [min_price, max_price, boroughs], map) btn.click(filter_map, [min_price, max_price, boroughs], map) diff --git a/demo/native_plots/bar_plot_demo.py b/demo/native_plots/bar_plot_demo.py index 67431944f4..3b4323858e 100644 --- a/demo/native_plots/bar_plot_demo.py +++ b/demo/native_plots/bar_plot_demo.py @@ -84,6 +84,6 @@ with gr.Blocks() as bar_plot: label="Type of Bar Plot" ) with gr.Column(): - plot = gr.BarPlot(show_label=False).style(container=True) + plot = gr.BarPlot(show_label=False) display.change(bar_plot_fn, inputs=display, outputs=plot) bar_plot.load(fn=bar_plot_fn, inputs=display, outputs=plot) diff --git a/demo/native_plots/line_plot_demo.py b/demo/native_plots/line_plot_demo.py index 4d4c7e0ab4..423d0998d2 100644 --- a/demo/native_plots/line_plot_demo.py +++ b/demo/native_plots/line_plot_demo.py @@ -69,7 +69,7 @@ with gr.Blocks() as line_plot: value="stocks", ) with gr.Column(): - plot = gr.LinePlot(show_label=False).style(container=False) + plot = gr.LinePlot(show_label=False, container=False) dataset.change(line_plot_fn, inputs=dataset, outputs=plot) line_plot.load(fn=line_plot_fn, inputs=dataset, outputs=plot) diff --git a/demo/native_plots/scatter_plot_demo.py b/demo/native_plots/scatter_plot_demo.py index 3897f6ef1e..45a0ca8b5f 100644 --- a/demo/native_plots/scatter_plot_demo.py +++ b/demo/native_plots/scatter_plot_demo.py @@ -39,7 +39,7 @@ with gr.Blocks() as scatter_plot: with gr.Column(): dataset = gr.Dropdown(choices=["cars", "iris"], value="cars") with gr.Column(): - plot = gr.ScatterPlot(show_label=False).style(container=True) + plot = gr.ScatterPlot(show_label=False) dataset.change(scatter_plot_fn, inputs=dataset, outputs=plot) scatter_plot.load(fn=scatter_plot_fn, inputs=dataset, outputs=plot) diff --git a/demo/rows_and_columns/run.ipynb b/demo/rows_and_columns/run.ipynb index 4f05752c97..8ffbaff7df 100644 --- a/demo/rows_and_columns/run.ipynb +++ b/demo/rows_and_columns/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: rows_and_columns"]}, {"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('images')\n", "!wget -q -O images/cheetah.jpg https://github.com/gradio-app/gradio/raw/main/demo/rows_and_columns/images/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text1 = gr.Textbox(label=\"t1\")\n", " slider2 = gr.Textbox(label=\"s2\")\n", " drop3 = gr.Dropdown([\"a\", \"b\", \"c\"], label=\"d3\")\n", " with gr.Row():\n", " with gr.Column(scale=1, min_width=600):\n", " text1 = gr.Textbox(label=\"prompt 1\")\n", " text2 = gr.Textbox(label=\"prompt 2\")\n", " inbtw = gr.Button(\"Between\")\n", " text4 = gr.Textbox(label=\"prompt 1\")\n", " text5 = gr.Textbox(label=\"prompt 2\")\n", " with gr.Column(scale=2, min_width=600):\n", " img1 = gr.Image(\"images/cheetah.jpg\")\n", " btn = gr.Button(\"Go\").style(full_width=True)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: rows_and_columns"]}, {"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('images')\n", "!wget -q -O images/cheetah.jpg https://github.com/gradio-app/gradio/raw/main/demo/rows_and_columns/images/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text1 = gr.Textbox(label=\"t1\")\n", " slider2 = gr.Textbox(label=\"s2\")\n", " drop3 = gr.Dropdown([\"a\", \"b\", \"c\"], label=\"d3\")\n", " with gr.Row():\n", " with gr.Column(scale=1, min_width=600):\n", " text1 = gr.Textbox(label=\"prompt 1\")\n", " text2 = gr.Textbox(label=\"prompt 2\")\n", " inbtw = gr.Button(\"Between\")\n", " text4 = gr.Textbox(label=\"prompt 1\")\n", " text5 = gr.Textbox(label=\"prompt 2\")\n", " with gr.Column(scale=2, min_width=600):\n", " img1 = gr.Image(\"images/cheetah.jpg\")\n", " btn = gr.Button(\"Go\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/rows_and_columns/run.py b/demo/rows_and_columns/run.py index 68d5b94e87..d5dbdd74b3 100644 --- a/demo/rows_and_columns/run.py +++ b/demo/rows_and_columns/run.py @@ -14,7 +14,7 @@ with gr.Blocks() as demo: text5 = gr.Textbox(label="prompt 2") with gr.Column(scale=2, min_width=600): img1 = gr.Image("images/cheetah.jpg") - btn = gr.Button("Go").style(full_width=True) + btn = gr.Button("Go") if __name__ == "__main__": demo.launch() \ No newline at end of file diff --git a/demo/scatterplot_component/run.ipynb b/demo/scatterplot_component/run.ipynb index 75d7a60528..66f60f7be4 100644 --- a/demo/scatterplot_component/run.ipynb +++ b/demo/scatterplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: scatterplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "\n", "with gr.Blocks() as demo:\n", " gr.ScatterPlot(show_label=False,\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\").style(container=False)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: scatterplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "\n", "with gr.Blocks() as demo:\n", " gr.ScatterPlot(\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\",\n", " container=False,\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/demo/scatterplot_component/run.py b/demo/scatterplot_component/run.py index 4b005c6390..b7069c873b 100644 --- a/demo/scatterplot_component/run.py +++ b/demo/scatterplot_component/run.py @@ -4,15 +4,17 @@ from vega_datasets import data cars = data.cars() with gr.Blocks() as demo: - gr.ScatterPlot(show_label=False, - value=cars, - x="Horsepower", - y="Miles_per_Gallon", - color="Origin", - tooltip="Name", - title="Car Data", - y_title="Miles per Gallon", - color_legend_title="Origin of Car").style(container=False) + gr.ScatterPlot( + value=cars, + x="Horsepower", + y="Miles_per_Gallon", + color="Origin", + tooltip="Name", + title="Car Data", + y_title="Miles per Gallon", + color_legend_title="Origin of Car", + container=False, + ) if __name__ == "__main__": - demo.launch() \ No newline at end of file + demo.launch() diff --git a/demo/stable-diffusion/run.ipynb b/demo/stable-diffusion/run.ipynb index abbfee3dce..6ecc4c57bb 100644 --- a/demo/stable-diffusion/run.ipynb +++ b/demo/stable-diffusion/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stable-diffusion\n", "### Note: This is a simplified version of the code needed to create the Stable Diffusion demo. See full code here: https://hf.co/spaces/stabilityai/stable-diffusion/tree/main\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio diffusers transformers nvidia-ml-py3 ftfy torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from diffusers import StableDiffusionPipeline\n", "from PIL import Image \n", "import os\n", "\n", "auth_token = os.getenv(\"auth_token\")\n", "model_id = \"CompVis/stable-diffusion-v1-4\"\n", "device = \"cpu\"\n", "pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=auth_token, revision=\"fp16\", torch_dtype=torch.float16)\n", "pipe = pipe.to(device)\n", "\n", "def infer(prompt, samples, steps, scale, seed): \n", " generator = torch.Generator(device=device).manual_seed(seed)\n", " images_list = pipe(\n", " [prompt] * samples,\n", " num_inference_steps=steps,\n", " guidance_scale=scale,\n", " generator=generator,\n", " )\n", " images = []\n", " safe_image = Image.open(r\"unsafe.png\")\n", " for i, image in enumerate(images_list[\"sample\"]):\n", " if(images_list[\"nsfw_content_detected\"][i]):\n", " images.append(safe_image)\n", " else:\n", " images.append(image)\n", " return images\n", " \n", "\n", "\n", "block = gr.Blocks()\n", "\n", "with block:\n", " with gr.Group():\n", " with gr.Box():\n", " with gr.Row().style(mobile_collapse=False, equal_height=True):\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " show_label=False,\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " ).style(\n", " border=(True, False, True, True),\n", " rounded=(True, False, False, True),\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\").style(\n", " margin=False,\n", " rounded=(False, True, True, False),\n", " )\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " ).style(grid=[2], height=\"auto\")\n", "\n", " advanced_button = gr.Button(\"Advanced options\", elem_id=\"advanced-btn\")\n", "\n", " with gr.Row(elem_id=\"advanced-options\"):\n", " samples = gr.Slider(label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n", " steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n", " scale = gr.Slider(\n", " label=\"Guidance Scale\", minimum=0, maximum=50, value=7.5, step=0.1\n", " )\n", " seed = gr.Slider(\n", " label=\"Seed\",\n", " minimum=0,\n", " maximum=2147483647,\n", " step=1,\n", " randomize=True,\n", " )\n", " text.submit(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " btn.click(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " advanced_button.click(\n", " None,\n", " [],\n", " text,\n", " )\n", " \n", "block.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stable-diffusion\n", "### Note: This is a simplified version of the code needed to create the Stable Diffusion demo. See full code here: https://hf.co/spaces/stabilityai/stable-diffusion/tree/main\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio diffusers transformers nvidia-ml-py3 ftfy torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from diffusers import StableDiffusionPipeline\n", "from PIL import Image\n", "import os\n", "\n", "auth_token = os.getenv(\"auth_token\")\n", "model_id = \"CompVis/stable-diffusion-v1-4\"\n", "device = \"cpu\"\n", "pipe = StableDiffusionPipeline.from_pretrained(\n", " model_id, use_auth_token=auth_token, revision=\"fp16\", torch_dtype=torch.float16\n", ")\n", "pipe = pipe.to(device)\n", "\n", "\n", "def infer(prompt, samples, steps, scale, seed):\n", " generator = torch.Generator(device=device).manual_seed(seed)\n", " images_list = pipe(\n", " [prompt] * samples,\n", " num_inference_steps=steps,\n", " guidance_scale=scale,\n", " generator=generator,\n", " )\n", " images = []\n", " safe_image = Image.open(r\"unsafe.png\")\n", " for i, image in enumerate(images_list[\"sample\"]):\n", " if images_list[\"nsfw_content_detected\"][i]:\n", " images.append(safe_image)\n", " else:\n", " images.append(image)\n", " return images\n", "\n", "\n", "block = gr.Blocks()\n", "\n", "with block:\n", " with gr.Group():\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\")\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " elem_id=\"gallery\",\n", " columns=[2],\n", " height=\"auto\",\n", " )\n", "\n", " advanced_button = gr.Button(\"Advanced options\", elem_id=\"advanced-btn\")\n", "\n", " with gr.Row(elem_id=\"advanced-options\"):\n", " samples = gr.Slider(label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n", " steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n", " scale = gr.Slider(\n", " label=\"Guidance Scale\", minimum=0, maximum=50, value=7.5, step=0.1\n", " )\n", " seed = gr.Slider(\n", " label=\"Seed\",\n", " minimum=0,\n", " maximum=2147483647,\n", " step=1,\n", " randomize=True,\n", " )\n", " text.submit(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " btn.click(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " advanced_button.click(\n", " None,\n", " [],\n", " text,\n", " )\n", "\n", "block.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/stable-diffusion/run.py b/demo/stable-diffusion/run.py index 26e0ec8df1..20cf9ca5ba 100644 --- a/demo/stable-diffusion/run.py +++ b/demo/stable-diffusion/run.py @@ -1,16 +1,19 @@ import gradio as gr import torch from diffusers import StableDiffusionPipeline -from PIL import Image +from PIL import Image import os auth_token = os.getenv("auth_token") model_id = "CompVis/stable-diffusion-v1-4" device = "cpu" -pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=auth_token, revision="fp16", torch_dtype=torch.float16) +pipe = StableDiffusionPipeline.from_pretrained( + model_id, use_auth_token=auth_token, revision="fp16", torch_dtype=torch.float16 +) pipe = pipe.to(device) -def infer(prompt, samples, steps, scale, seed): + +def infer(prompt, samples, steps, scale, seed): generator = torch.Generator(device=device).manual_seed(seed) images_list = pipe( [prompt] * samples, @@ -21,37 +24,32 @@ def infer(prompt, samples, steps, scale, seed): images = [] safe_image = Image.open(r"unsafe.png") for i, image in enumerate(images_list["sample"]): - if(images_list["nsfw_content_detected"][i]): + if images_list["nsfw_content_detected"][i]: images.append(safe_image) else: images.append(image) return images - block = gr.Blocks() with block: with gr.Group(): - with gr.Box(): - with gr.Row().style(mobile_collapse=False, equal_height=True): - text = gr.Textbox( - label="Enter your prompt", - show_label=False, - max_lines=1, - placeholder="Enter your prompt", - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True), - container=False, - ) - btn = gr.Button("Generate image").style( - margin=False, - rounded=(False, True, True, False), - ) + with gr.Row(): + text = gr.Textbox( + label="Enter your prompt", + max_lines=1, + placeholder="Enter your prompt", + container=False, + ) + btn = gr.Button("Generate image") gallery = gr.Gallery( - label="Generated images", show_label=False, elem_id="gallery" - ).style(grid=[2], height="auto") + label="Generated images", + show_label=False, + elem_id="gallery", + columns=[2], + height="auto", + ) advanced_button = gr.Button("Advanced options", elem_id="advanced-btn") @@ -75,5 +73,5 @@ with block: [], text, ) - -block.launch() \ No newline at end of file + +block.launch() diff --git a/gradio/blocks.py b/gradio/blocks.py index c7da1f86aa..64bb7b7fe1 100644 --- a/gradio/blocks.py +++ b/gradio/blocks.py @@ -377,10 +377,12 @@ class BlockContext(Block): child.parent = pseudo_parent self.children = children - def __exit__(self, *args): + def __exit__(self, exc_type: type[BaseException] | None = None, *args): + Context.block = self.parent + if exc_type is not None: + return if getattr(self, "allow_expected_parents", True): self.fill_expected_parents() - Context.block = self.parent def postprocess(self, y): """ @@ -432,12 +434,6 @@ class BlockFunction: return str(self) -class class_or_instancemethod(classmethod): # noqa: N801 - def __get__(self, instance, type_): - descr_get = super().__get__ if instance is None else self.__func__.__get__ - return descr_get(instance, type_) - - def postprocess_update_dict(block: Block, update_dict: dict, postprocess: bool = True): """ Converts a dictionary of updates into a format that can be sent to the frontend. @@ -1518,7 +1514,11 @@ Received outputs: self.exited = False return self - def __exit__(self, *args): + def __exit__(self, exc_type: type[BaseException] | None = None, *args): + if exc_type is not None: + Context.block = None + Context.root_block = None + return super().fill_expected_parents() Context.block = self.parent # Configure the load events before root_block is reset @@ -1532,9 +1532,8 @@ Received outputs: self.progress_tracking = any(block_fn.tracks_progress for block_fn in self.fns) self.exited = True - @class_or_instancemethod def load( - self_or_cls, # noqa: N805 + self: Blocks | None = None, fn: Callable | None = None, inputs: list[Component] | None = None, outputs: list[Component] | None = None, @@ -1559,10 +1558,8 @@ Received outputs: For reverse compatibility reasons, this is both a class method and an instance method, the two of which, confusingly, do two completely different things. - Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead. - Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below. Parameters: name: Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base") @@ -1591,7 +1588,7 @@ Received outputs: demo.load(get_time, inputs=None, outputs=dt) demo.launch() """ - if isinstance(self_or_cls, type): + if self is None: warn_deprecation( "gr.Blocks.load() will be deprecated. Use gr.load() instead." ) @@ -1605,7 +1602,7 @@ Received outputs: else: from gradio.events import Dependency - dep, dep_index = self_or_cls.set_event_trigger( + dep, dep_index = self.set_event_trigger( event_name="load", fn=fn, inputs=inputs, @@ -1622,7 +1619,7 @@ Received outputs: every=every, no_target=True, ) - return Dependency(self_or_cls, dep, dep_index) + return Dependency(self, dep, dep_index) def clear(self): """Resets the layout of the Blocks object.""" diff --git a/gradio/components/checkboxgroup.py b/gradio/components/checkboxgroup.py index 80a5dc31b4..edf89454e2 100644 --- a/gradio/components/checkboxgroup.py +++ b/gradio/components/checkboxgroup.py @@ -227,6 +227,9 @@ class CheckboxGroup( return None elif not isinstance(input_data, list): input_data = [input_data] + for data in input_data: + if data not in [c[0] for c in self.choices]: + raise ValueError(f"Example {data} provided not a valid choice.") return [ next((c[0] for c in self.choices if c[1] == data), None) for data in input_data diff --git a/gradio/components/gallery.py b/gradio/components/gallery.py index 1c0bd9cf05..316be3517e 100644 --- a/gradio/components/gallery.py +++ b/gradio/components/gallery.py @@ -231,7 +231,7 @@ class Gallery(IOComponent, GallerySerializable, Selectable): warn_style_method_deprecation() if grid is not None: warn_deprecation( - "The 'grid' parameter will be deprecated. Please use 'grid_cols' in the constructor instead.", + "The 'grid' parameter will be deprecated. Please use 'columns' in the constructor instead.", ) self.grid_cols = grid if columns is not None: diff --git a/gradio/layouts.py b/gradio/layouts.py index 58a4f20ba2..c370651deb 100644 --- a/gradio/layouts.py +++ b/gradio/layouts.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Literal from gradio_client.documentation import document, set_documentation_group from gradio.blocks import BlockContext -from gradio.deprecation import warn_style_method_deprecation +from gradio.deprecation import warn_deprecation, warn_style_method_deprecation from gradio.events import Changeable, Selectable if TYPE_CHECKING: @@ -119,6 +119,11 @@ class Column(BlockContext): visible: If False, column will be hidden. elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. """ + if scale != round(scale): + warn_deprecation( + f"'scale' value should be an integer. Using {scale} will cause issues." + ) + self.scale = scale self.min_width = min_width self.variant = variant @@ -273,9 +278,9 @@ class Group(BlockContext): } -@document() class Box(BlockContext): """ + DEPRECATED. Box is a a layout element which places children in a box with rounded corners and some padding around them. Example: diff --git a/js/_website/generate_jsons/src/docs/__init__.py b/js/_website/generate_jsons/src/docs/__init__.py index 121c8c23db..23497f428d 100644 --- a/js/_website/generate_jsons/src/docs/__init__.py +++ b/js/_website/generate_jsons/src/docs/__init__.py @@ -133,7 +133,6 @@ override_signature("Row", "with gradio.Row():") override_signature("Column", "with gradio.Column():") override_signature("Tab", "with gradio.Tab():") override_signature("Group", "with gradio.Group():") -override_signature("Box", "with gradio.Box():") override_signature("Dataset", "gr.Dataset(components, samples)") diff --git a/js/_website/src/routes/[[version]]/docs/block-layouts/+page.server.ts b/js/_website/src/routes/[[version]]/docs/block-layouts/+page.server.ts index 556367fcfb..f4a929e868 100644 --- a/js/_website/src/routes/[[version]]/docs/block-layouts/+page.server.ts +++ b/js/_website/src/routes/[[version]]/docs/block-layouts/+page.server.ts @@ -18,9 +18,8 @@ export async function load({ parent }) { let objs = [ docs.building.row, docs.building.column, - docs.building.group, docs.building.tab, - docs.building.box, + docs.building.group, docs.building.accordion ]; @@ -29,9 +28,9 @@ export async function load({ parent }) { ["Column", "column"], ["Tab", "tab"], ["Group", "group"], - ["Box", "box"], ["Accordion", "accordion"] ]; + let method_headers: string[][] = []; const get_slug = make_slug_processor(); diff --git a/js/highlightedtext/static/Highlightedtext.svelte b/js/highlightedtext/static/Highlightedtext.svelte index f68bf9bf0a..2b4ba51a02 100644 --- a/js/highlightedtext/static/Highlightedtext.svelte +++ b/js/highlightedtext/static/Highlightedtext.svelte @@ -257,7 +257,6 @@ .label { transition: 150ms; margin-top: 1px; - margin-right: calc(var(--size-1) * -1); border-radius: var(--radius-xs); padding: 1px 5px; color: var(--body-text-color); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1bc0eb1b8b..629e8b211c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,4 +1,4 @@ -lockfileVersion: '6.0' +lockfileVersion: '6.1' settings: autoInstallPeers: true @@ -6393,7 +6393,7 @@ packages: peerDependencies: '@sveltejs/kit': ^1.0.0 dependencies: - '@sveltejs/kit': 1.16.3(svelte@3.57.0)(vite@4.3.5) + '@sveltejs/kit': 1.16.3(svelte@3.59.2)(vite@4.3.9) import-meta-resolve: 3.0.0 dev: true