[{"category": "Text", "demos": [{"name": "Hello World", "dir": "hello_world", "code": "import gradio as gr\n\n\ndef greet(name):\n return \"Hello \" + name + \"!\"\n\n\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "The simplest possible Gradio demo. It wraps a 'Hello {name}!' function in an Interface that accepts and returns text.", "requirements": []}, {"name": "Hello Blocks", "dir": "hello_blocks", "code": "import gradio as gr\n\n\ndef greet(name):\n return \"Hello \" + name + \"!\"\n\n\nwith gr.Blocks() as demo:\n name = gr.Textbox(label=\"Name\")\n output = gr.Textbox(label=\"Output Box\")\n greet_btn = gr.Button(\"Greet\")\n greet_btn.click(fn=greet, inputs=name, outputs=output, api_name=\"greet\")\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Sentence Builder", "dir": "sentence_builder", "code": "import gradio as gr\n\ndef sentence_builder(quantity, animal, countries, place, activity_list, morning):\n return f\"\"\"The {quantity} {animal}s from {\" and \".join(countries)} went to the {place} where they {\" and \".join(activity_list)} until the {\"morning\" if morning else \"night\"}\"\"\"\n\ndemo = gr.Interface(\n sentence_builder,\n [\n gr.Slider(2, 20, value=4, label=\"Count\", info=\"Choose between 2 and 20\"),\n gr.Dropdown(\n [\"cat\", \"dog\", \"bird\"], label=\"Animal\", info=\"Will add more animals later!\"\n ),\n gr.CheckboxGroup([\"USA\", \"Japan\", \"Pakistan\"], label=\"Countries\", info=\"Where are they from?\"),\n gr.Radio([\"park\", \"zoo\", \"road\"], label=\"Location\", info=\"Where did they go?\"),\n gr.Dropdown(\n [\"ran\", \"swam\", \"ate\", \"slept\"], value=[\"swam\", \"slept\"], multiselect=True, label=\"Activity\", info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl.\"\n ),\n gr.Checkbox(label=\"Morning\", info=\"Did they do it in the morning?\"),\n ],\n \"text\",\n examples=[\n [2, \"cat\", [\"Japan\", \"Pakistan\"], \"park\", [\"ate\", \"swam\"], True],\n [4, \"dog\", [\"Japan\"], \"zoo\", [\"ate\", \"swam\"], False],\n [10, \"bird\", [\"USA\", \"Pakistan\"], \"road\", [\"ran\"], False],\n [8, \"cat\", [\"Pakistan\"], \"zoo\", [\"ate\"], True],\n ]\n)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Diff Texts", "dir": "diff_texts", "code": "from difflib import Differ\n\nimport gradio as gr\n\ndef 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\ndemo = 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)\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}]}, {"category": "Media", "demos": [{"name": "Sepia Filter", "dir": "sepia_filter", "code": "import numpy as np\nimport gradio as gr\n\ndef sepia(input_img):\n sepia_filter = np.array([\n [0.393, 0.769, 0.189],\n [0.349, 0.686, 0.168],\n [0.272, 0.534, 0.131]\n ])\n sepia_img = input_img.dot(sepia_filter.T)\n sepia_img /= sepia_img.max()\n return sepia_img\n\ndemo = gr.Interface(sepia, gr.Image(), \"image\")\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": ["numpy"]}, {"name": "Video Identity", "dir": "video_identity_2", "code": "import gradio as gr\n\ndef video_identity(video):\n return video\n\ndemo = gr.Interface(video_identity,\n gr.Video(),\n \"playable_video\",\n )\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Iterative Output", "dir": "fake_diffusion", "code": "import gradio as gr\nimport numpy as np\nimport time\n\ndef fake_diffusion(steps):\n rng = np.random.default_rng()\n for i in range(steps):\n time.sleep(1)\n image = rng.random(size=(600, 600, 3))\n yield image\n image = np.ones((1000,1000,3), np.uint8)\n image[:] = [255, 124, 0]\n yield image\n\ndemo = gr.Interface(fake_diffusion,\n inputs=gr.Slider(1, 10, 3, step=1),\n outputs=\"image\")\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "This demo uses a fake model to showcase iterative output. The Image output will update every time a generator is returned until the final image.", "requirements": ["numpy"]}, {"name": "Generate Tone", "dir": "generate_tone", "code": "import numpy as np\nimport gradio as gr\n\nnotes = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n\ndef generate_tone(note, octave, duration):\n sr = 48000\n a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)\n frequency = a4_freq * 2 ** (tones_from_a4 / 12)\n duration = int(duration)\n audio = np.linspace(0, duration, duration * sr)\n audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)\n return sr, audio\n\ndemo = gr.Interface(\n generate_tone,\n [\n gr.Dropdown(notes, type=\"index\"),\n gr.Slider(4, 6, step=1),\n gr.Textbox(value=\"1\", label=\"Duration in seconds\"),\n ],\n \"audio\",\n)\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": ["numpy"]}]}, {"category": "Tabular", "demos": [{"name": "Filter Records", "dir": "filter_records", "code": "import gradio as gr\n\ndef filter_records(records, gender):\n return records[records[\"gender\"] == gender]\n\ndemo = gr.Interface(\n filter_records,\n [\n gr.Dataframe(\n headers=[\"name\", \"age\", \"gender\"],\n datatype=[\"str\", \"number\", \"str\"],\n row_count=5,\n col_count=(3, \"fixed\"),\n ),\n gr.Dropdown([\"M\", \"F\", \"O\"]),\n ],\n \"dataframe\",\n description=\"Enter gender as 'M', 'F', or 'O' for other.\",\n)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Transpose Matrix", "dir": "matrix_transpose", "code": "import numpy as np\n\nimport gradio as gr\n\ndef transpose(matrix):\n return matrix.T\n\ndemo = gr.Interface(\n transpose,\n gr.Dataframe(type=\"numpy\", datatype=\"number\", row_count=5, col_count=3),\n \"numpy\",\n examples=[\n [np.zeros((3, 3)).tolist()],\n [np.ones((2, 2)).tolist()],\n [np.random.randint(0, 10, (3, 10)).tolist()],\n [np.random.randint(0, 10, (10, 3)).tolist()],\n [np.random.randint(0, 10, (10, 10)).tolist()],\n ],\n cache_examples=False\n)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Tax Calculator", "dir": "tax_calculator", "code": "import gradio as gr\n\ndef tax_calculator(income, marital_status, assets):\n tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]\n total_deductible = sum(assets[\"Cost\"])\n taxable_income = income - total_deductible\n\n total_tax = 0\n for bracket, rate in tax_brackets:\n if taxable_income > bracket:\n total_tax += (taxable_income - bracket) * rate / 100\n\n if marital_status == \"Married\":\n total_tax *= 0.75\n elif marital_status == \"Divorced\":\n total_tax *= 0.8\n\n return round(total_tax)\n\ndemo = gr.Interface(\n tax_calculator,\n [\n \"number\",\n gr.Radio([\"Single\", \"Married\", \"Divorced\"]),\n gr.Dataframe(\n headers=[\"Item\", \"Cost\"],\n datatype=[\"str\", \"number\"],\n label=\"Assets Purchased this Year\",\n ),\n ],\n \"number\",\n examples=[\n [10000, \"Married\", [[\"Suit\", 5000], [\"Laptop\", 800], [\"Car\", 1800]]],\n [80000, \"Single\", [[\"Suit\", 800], [\"Watch\", 1800], [\"Car\", 800]]],\n ],\n)\n\ndemo.launch()\n", "text": "Calculate taxes using Textbox, Radio, and Dataframe components", "requirements": []}, {"name": "Kinematics", "dir": "blocks_kinematics", "code": "import pandas as pd\nimport numpy as np\n\nimport gradio as gr\n\ndef plot(v, a):\n g = 9.81\n theta = a / 180 * 3.14\n tmax = ((2 * v) * np.sin(theta)) / g\n timemat = tmax * np.linspace(0, 1, 40)\n\n x = (v * timemat) * np.cos(theta)\n y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))\n df = pd.DataFrame({\"x\": x, \"y\": y})\n return df\n\ndemo = gr.Blocks()\n\nwith demo:\n gr.Markdown(\n r\"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \\cdot \\frac{\\sin(2\\theta)}{g}$\"\n )\n\n with gr.Row():\n speed = gr.Slider(1, 30, 25, label=\"Speed\")\n angle = gr.Slider(0, 90, 45, label=\"Angle\")\n output = gr.LinePlot(\n x=\"x\",\n y=\"y\",\n overlay_point=True,\n tooltip=[\"x\", \"y\"],\n x_lim=[0, 100],\n y_lim=[0, 60],\n width=350,\n height=300,\n )\n btn = gr.Button(value=\"Run\")\n btn.click(plot, [speed, angle], output)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": ["numpy", "pandas"]}, {"name": "Stock Forecast", "dir": "stock_forecast", "code": "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport gradio as gr\n\ndef plot_forecast(final_year, companies, noise, show_legend, point_style):\n start_year = 2020\n x = np.arange(start_year, final_year + 1)\n year_count = x.shape[0]\n plt_format = ({\"cross\": \"X\", \"line\": \"-\", \"circle\": \"o--\"})[point_style]\n fig = plt.figure()\n ax = fig.add_subplot(111)\n for i, company in enumerate(companies):\n series = np.arange(0, year_count, dtype=float)\n series = series**2 * (i + 1)\n series += np.random.rand(year_count) * noise\n ax.plot(x, series, plt_format)\n if show_legend:\n plt.legend(companies)\n return fig\n\ndemo = gr.Interface(\n plot_forecast,\n [\n gr.Radio([2025, 2030, 2035, 2040], label=\"Project to:\"),\n gr.CheckboxGroup([\"Google\", \"Microsoft\", \"Gradio\"], label=\"Company Selection\"),\n gr.Slider(1, 100, label=\"Noise Level\"),\n gr.Checkbox(label=\"Show Legend\"),\n gr.Dropdown([\"cross\", \"line\", \"circle\"], label=\"Style\"),\n ],\n gr.Plot(label=\"forecast\", format=\"png\"),\n)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": ["numpy", "matplotlib"]}]}, {"category": "Other", "demos": [{"name": "Tabbed Interface", "dir": "tabbed_interface_lite", "code": "import gradio as gr\n\nhello_world = gr.Interface(lambda name: \"Hello \" + name, \"text\", \"text\")\nbye_world = gr.Interface(lambda name: \"Bye \" + name, \"text\", \"text\")\n\ndemo = gr.TabbedInterface([hello_world, bye_world], [\"Hello World\", \"Bye World\"])\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Chatbot", "dir": "chatinterface_random_response", "code": "import random\nimport gradio as gr\n\ndef random_response(message, history):\n return random.choice([\"Yes\", \"No\"])\n\ndemo = gr.ChatInterface(random_response, type=\"messages\")\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Streaming Chatbot", "dir": "chatinterface_streaming_echo", "code": "import time\nimport gradio as gr\n\ndef slow_echo(message, history):\n for i in range(len(message)):\n time.sleep(0.05)\n yield \"You typed: \" + message[: i + 1]\n\ndemo = gr.ChatInterface(slow_echo, type=\"messages\")\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Layouts", "dir": "blocks_flipper", "code": "import numpy as np\nimport gradio as gr\n\ndef flip_text(x):\n return x[::-1]\n\ndef flip_image(x):\n return np.fliplr(x)\n\nwith gr.Blocks() as demo:\n gr.Markdown(\"Flip text or image files using this demo.\")\n with gr.Tab(\"Flip Text\"):\n text_input = gr.Textbox()\n text_output = gr.Textbox()\n text_button = gr.Button(\"Flip\")\n with gr.Tab(\"Flip Image\"):\n with gr.Row():\n image_input = gr.Image()\n image_output = gr.Image()\n image_button = gr.Button(\"Flip\")\n\n with gr.Accordion(\"Open for More!\", open=False):\n gr.Markdown(\"Look at me...\")\n temp_slider = gr.Slider(\n 0, 1,\n value=0.1,\n step=0.1,\n interactive=True,\n label=\"Slide me\",\n )\n\n text_button.click(flip_text, inputs=text_input, outputs=text_output)\n image_button.click(flip_image, inputs=image_input, outputs=image_output)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": ["numpy"]}, {"name": "Error", "dir": "calculator", "code": "import gradio as gr\n\ndef calculator(num1, operation, num2):\n if operation == \"add\":\n return num1 + num2\n elif operation == \"subtract\":\n return num1 - num2\n elif operation == \"multiply\":\n return num1 * num2\n elif operation == \"divide\":\n if num2 == 0:\n raise gr.Error(\"Cannot divide by zero!\")\n return num1 / num2\n\ndemo = gr.Interface(\n calculator,\n [\n \"number\",\n gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n \"number\"\n ],\n \"number\",\n examples=[\n [45, \"add\", 3],\n [3.14, \"divide\", 2],\n [144, \"multiply\", 2.5],\n [0, \"subtract\", 1.2],\n ],\n title=\"Toy Calculator\",\n description=\"Here's a sample toy calculator.\",\n)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}, {"name": "Chained Events", "dir": "blocks_chained_events", "code": "import gradio as gr\n\ndef failure():\n raise gr.Error(\"This should fail!\")\n\ndef exception():\n raise ValueError(\"Something went wrong\")\n\ndef success():\n return True\n\ndef warning_fn():\n gr.Warning(\"This is a warning!\")\n\ndef info_fn():\n gr.Info(\"This is some info\")\n\nwith gr.Blocks() as demo:\n gr.Markdown(\"Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests.\"\n \" Also testing that the status modals show up.\")\n with gr.Row():\n result = gr.Textbox(label=\"Result\")\n result_2 = gr.Textbox(label=\"Consecutive Event\")\n with gr.Row():\n success_btn = gr.Button(value=\"Trigger Success\")\n success_btn_2 = gr.Button(value=\"Trigger Consecutive Success\")\n failure_btn = gr.Button(value=\"Trigger Failure\")\n failure_exception = gr.Button(value=\"Trigger Failure With ValueError\")\n with gr.Row():\n trigger_warning = gr.Button(value=\"Trigger Warning\")\n trigger_info = gr.Button(value=\"Trigger Info\")\n\n success_btn_2.click(success, None, None).success(lambda: \"First Event Trigered\", None, result).success(lambda: \"Consecutive Event Triggered\", None, result_2)\n success_btn.click(success, None, None).success(lambda: \"Success event triggered\", inputs=None, outputs=result)\n failure_btn.click(failure, None, None).success(lambda: \"Should not be triggered\", inputs=None, outputs=result)\n failure_exception.click(exception, None, None)\n trigger_warning.click(warning_fn, None, None)\n trigger_info.click(info_fn, None, None)\n\nif __name__ == \"__main__\":\n demo.launch(show_error=True)\n", "text": "", "requirements": []}, {"name": "Change Listener", "dir": "blocks_hello", "code": "import gradio as gr\n\ndef welcome(name):\n return f\"Welcome to Gradio, {name}!\"\n\nwith gr.Blocks() as demo:\n gr.Markdown(\n \"\"\"\n # Hello World!\n Start typing below to see the output.\n \"\"\")\n inp = gr.Textbox(placeholder=\"What is your name?\")\n out = gr.Textbox()\n inp.change(welcome, inp, out)\n\nif __name__ == \"__main__\":\n demo.launch()\n", "text": "", "requirements": []}]}, {"category": "Transformers", "demos": [{"name": "Basic", "dir": "transformers_basic", "lite": true, "code": "import gradio as gr\nfrom transformers_js_py import pipeline\n\npipe = await pipeline('sentiment-analysis')\n\nasync def process(text):\n return await pipe(text)\n\ndemo = gr.Interface(fn=process, inputs=\"text\", outputs=\"json\")\n\ndemo.launch()\n", "text": "", "requirements": ["transformers_js_py"]}]}]