Repository: gradio-app/gradio
Pull request: Add open in colab buttons to demos in docs and /demos
Adds buttons to open a demo in colab: 

https://user-images.githubusercontent.com/9021060/200097976-7089cf0e-6d27-4280-880d-a46726af4fee.mov



If a contributor wants to change a demo in the /demo dir, they just have to run /demo/generate_notebooks.py to regenerate all the .ipynb notebooks. I could create a github action for this but seems like overkill. 

Note that not all the demos will work on colab, the ones that reference another file in the dir won't work (for [example](https://colab.research.google.com/github/gradio-app/gradio/blob/aliabd/colab-buttons/demo/main_note/run.ipynb)). I could detect this and not show a colab button for those, but I feel like it would still be useful for a reader to be able to play with the code (so don't know if it's the right idea to skip them), and usually you can easily replace the file (I could link to the dir in github so they can move the files they need?) 

Closes: #2278 

# Checklist:

- [x] I have performed a self-review of my own code
- [x] I have added a short summary of my change to the CHANGELOG.md
- [x] My code follows the style guidelines of this project
- [x] I have commented my code in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] New and existing unit tests pass locally with my changes



Problem statement:
Add "Run in Colab" Links to demos on the website Demos Page
- [x] I have searched to see if a similar issue already exists.


**Is your feature request related to a problem? Please describe.**  
It would help transition gradio users into gradio developers if they could easily run the demos hosted on our website on colab.

**Describe the solution you'd like**  
Add `Run in Colab` links to all the demos on the website.

Hints from issue discussion:
Great suggestion @freddyaboulton, I'll also add these for the demos on Docs.

Commit message: Merge branch 'main' into aliabd/colab-buttons

Patch to review:
diff --git a/.github/workflows/check-demo-notebooks.yml b/.github/workflows/check-demo-notebooks.yml
new file mode 100644
index 0000000000..d0b22ccd78
--- /dev/null
+++ b/.github/workflows/check-demo-notebooks.yml
@@ -0,0 +1,27 @@
+# This workflow will check if the run.py files in every demo match the run.ipynb notebooks.
+
+name: Check Demos Match Notebooks
+
+on:
+  pull_request:
+    types: [opened, synchronize, labeled, unlabeled]
+    paths:
+        - 'demo/**'
+
+jobs:
+  check-notebooks:
+    name: Generate Notebooks and Check 
+    runs-on: ubuntu-latest
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+        with:
+          ref: ${{ github.event.pull_request.head.ref }}
+          repository: ${{ github.event.pull_request.head.repo.full_name }}
+      - name: Generate Notebooks
+        run: |
+          pip install nbformat && cd demo && python generate_notebooks.py
+      - name: Print Git Status
+        run: echo $(git status) && echo $(git diff)
+      - name: Assert Notebooks Match 
+        run: git status | grep "nothing to commit, working tree clean"
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 729d270c51..465ffb946e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,13 @@ io = gr.Interface(echo, "textbox", "textbox").launch()
 No changes to highlight.
 
 ## Documentation Changes:
-No changes to highlight.
+* Colab buttons on every demo in the website! Just click open in colab, and run the demo there. 
+
+
+
+https://user-images.githubusercontent.com/9021060/202878400-cb16ed47-f4dd-4cb0-b2f0-102a9ff64135.mov
+
+
 
 ## Testing and Infrastructure Changes:
 No changes to highlight.
@@ -36,7 +42,7 @@ No changes to highlight.
 No changes to highlight.
 
 ## Full Changelog:
-No changes to highlight.
+* Add open in colab buttons to demos in docs and /demos by [@aliabd](https://github.com/aliabd) in [PR 2608](https://github.com/gradio-app/gradio/pull/2608)
 
 ## Contributors Shoutout:
 No changes to highlight.
diff --git a/demo/Echocardiogram-Segmentation/run.ipynb b/demo/Echocardiogram-Segmentation/run.ipynb
new file mode 100644
index 0000000000..e59e0f66da
--- /dev/null
+++ b/demo/Echocardiogram-Segmentation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: Echocardiogram-Segmentation"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio -f https://download.pytorch.org/whl/torch_stable.html numpy matplotlib wget torch==1.6.0+cpu  torchvision==0.7.0+cpu   "]}, {"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/Echocardiogram-Segmentation/img1.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/Echocardiogram-Segmentation/img2.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "from os.path import splitext\n", "import numpy as np\n", "import sys\n", "import matplotlib.pyplot as plt\n", "import torch\n", "import torchvision\n", "import wget \n", "\n", "\n", "destination_folder = \"output\"\n", "destination_for_weights = \"weights\"\n", "\n", "if os.path.exists(destination_for_weights):\n", "    print(\"The weights are at\", destination_for_weights)\n", "else:\n", "    print(\"Creating folder at \", destination_for_weights, \" to store weights\")\n", "    os.mkdir(destination_for_weights)\n", "    \n", "segmentationWeightsURL = 'https://github.com/douyang/EchoNetDynamic/releases/download/v1.0.0/deeplabv3_resnet50_random.pt'\n", "\n", "if not os.path.exists(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL))):\n", "    print(\"Downloading Segmentation Weights, \", segmentationWeightsURL,\" to \",os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)))\n", "    filename = wget.download(segmentationWeightsURL, out = destination_for_weights)\n", "else:\n", "    print(\"Segmentation Weights already present\")\n", "\n", "torch.cuda.empty_cache()\n", "\n", "def collate_fn(x):\n", "    x, f = zip(*x)\n", "    i = list(map(lambda t: t.shape[1], x))\n", "    x = torch.as_tensor(np.swapaxes(np.concatenate(x, 1), 0, 1))\n", "    return x, f, i\n", "\n", "model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=False, aux_loss=False)\n", "model.classifier[-1] = torch.nn.Conv2d(model.classifier[-1].in_channels, 1, kernel_size=model.classifier[-1].kernel_size)\n", "\n", "print(\"loading weights from \", os.path.join(destination_for_weights, \"deeplabv3_resnet50_random\"))\n", "\n", "if torch.cuda.is_available():\n", "    print(\"cuda is available, original weights\")\n", "    device = torch.device(\"cuda\")\n", "    model = torch.nn.DataParallel(model)\n", "    model.to(device)\n", "    checkpoint = torch.load(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)))\n", "    model.load_state_dict(checkpoint['state_dict'])\n", "else:\n", "    print(\"cuda is not available, cpu weights\")\n", "    device = torch.device(\"cpu\")\n", "    checkpoint = torch.load(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)), map_location = \"cpu\")\n", "    state_dict_cpu = {k[7:]: v for (k, v) in checkpoint['state_dict'].items()}\n", "    model.load_state_dict(state_dict_cpu)\n", "\n", "model.eval()\n", "\n", "def segment(input):\n", "    inp = input\n", "    x = inp.transpose([2, 0, 1])  #  channels-first\n", "    x = np.expand_dims(x, axis=0)  # adding a batch dimension    \n", "    \n", "    mean = x.mean(axis=(0, 2, 3))\n", "    std = x.std(axis=(0, 2, 3))\n", "    x = x - mean.reshape(1, 3, 1, 1)\n", "    x = x / std.reshape(1, 3, 1, 1)\n", "    \n", "    with torch.no_grad():\n", "        x = torch.from_numpy(x).type('torch.FloatTensor').to(device)\n", "        output = model(x)    \n", "    \n", "    y = output['out'].numpy()\n", "    y = y.squeeze()\n", "    \n", "    out = y>0    \n", "    \n", "    mask = inp.copy()\n", "    mask[out] = np.array([0, 0, 255])\n", "    \n", "    return mask\n", "\n", "import gradio as gr\n", "\n", "i = gr.Image(shape=(112, 112), label=\"Echocardiogram\")\n", "o = gr.Image(label=\"Segmentation Mask\")\n", "\n", "examples = [[\"img1.jpg\"], [\"img2.jpg\"]]\n", "title = None #\"Left Ventricle Segmentation\"\n", "description = \"This semantic segmentation model identifies the left ventricle in echocardiogram images.\"\n", "# videos. Accurate evaluation of the motion and size of the left ventricle is crucial for the assessment of cardiac function and ejection fraction. In this interface, the user inputs apical-4-chamber images from echocardiography videos and the model will output a prediction of the localization of the left ventricle in blue. This model was trained on the publicly released EchoNet-Dynamic dataset of 10k echocardiogram videos with 20k expert annotations of the left ventricle and published as part of \u2018Video-based AI for beat-to-beat assessment of cardiac function\u2019 by Ouyang et al. in Nature, 2020.\"\n", "thumbnail = \"https://raw.githubusercontent.com/gradio-app/hub-echonet/master/thumbnail.png\"\n", "gr.Interface(segment, i, o, examples=examples, allow_flagging=False, analytics_enabled=False, thumbnail=thumbnail, cache_examples=False).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/animeganv2/run.ipynb b/demo/animeganv2/run.ipynb
new file mode 100644
index 0000000000..365abb7480
--- /dev/null
+++ b/demo/animeganv2/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: animeganv2\n", "### Recreate the viral AnimeGAN image transformation demo.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchvision Pillow gdown numpy scipy cmake onnxruntime-gpu opencv-python-headless"]}, {"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/animeganv2/gongyoo.jpeg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/animeganv2/groot.jpeg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from PIL import Image\n", "import torch\n", "\n", "model2 = torch.hub.load(\n", "    \"AK391/animegan2-pytorch:main\",\n", "    \"generator\",\n", "    pretrained=True,\n", "    progress=False\n", ")\n", "model1 = torch.hub.load(\"AK391/animegan2-pytorch:main\", \"generator\", pretrained=\"face_paint_512_v1\")\n", "face2paint = torch.hub.load(\n", "    'AK391/animegan2-pytorch:main', 'face2paint', \n", "    size=512,side_by_side=False\n", ")\n", "\n", "def inference(img, ver):\n", "    if ver == 'version 2 (\ud83d\udd3a robustness,\ud83d\udd3b stylization)':\n", "        out = face2paint(model2, img)\n", "    else:\n", "        out = face2paint(model1, img)\n", "    return out\n", "\n", "title = \"AnimeGANv2\"\n", "description = \"Gradio Demo for AnimeGanv2 Face Portrait. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below. Please use a cropped portrait picture for best results similar to the examples below.\"\n", "article = \"<p style='text-align: center'><a href='https://github.com/bryandlee/animegan2-pytorch' target='_blank'>Github Repo Pytorch</a></p> <center><img src='https://visitor-badge.glitch.me/badge?page_id=akhaliq_animegan' alt='visitor badge'></center></p>\"\n", "examples=[['groot.jpeg','version 2 (\ud83d\udd3a robustness,\ud83d\udd3b stylization)'],['gongyoo.jpeg','version 1 (\ud83d\udd3a stylization, \ud83d\udd3b robustness)']]\n", "\n", "demo = gr.Interface(\n", "    fn=inference, \n", "    inputs=[gr.inputs.Image(type=\"pil\"),gr.inputs.Radio(['version 1 (\ud83d\udd3a stylization, \ud83d\udd3b robustness)','version 2 (\ud83d\udd3a robustness,\ud83d\udd3b stylization)'], type=\"value\", default='version 2 (\ud83d\udd3a robustness,\ud83d\udd3b stylization)', label='version')], \n", "    outputs=gr.outputs.Image(type=\"pil\"),\n", "    title=title,\n", "    description=description,\n", "    article=article,\n", "    examples=examples)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/audio_component/run.ipynb b/demo/audio_component/run.ipynb
new file mode 100644
index 0000000000..521bae8a18
--- /dev/null
+++ b/demo/audio_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: audio_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", "    gr.Audio()\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/audio_component/run.py b/demo/audio_component/run.py
index 82a9b7722b..17508a7af0 100644
--- a/demo/audio_component/run.py
+++ b/demo/audio_component/run.py
@@ -2,5 +2,5 @@
 
 with gr.Blocks() as demo:
     gr.Audio()
-    
-demo.launch()
\ No newline at end of file
+
+demo.launch()
diff --git a/demo/audio_debugger/run.ipynb b/demo/audio_debugger/run.ipynb
new file mode 100644
index 0000000000..67228be8ae
--- /dev/null
+++ b/demo/audio_debugger/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: audio_debugger"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/audio_debugger/cantina.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import subprocess\n", "import os\n", "\n", "audio_file = os.path.join(os.path.abspath(''), \"cantina.wav\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Tab(\"Audio\"):\n", "        gr.Audio(audio_file)\n", "    with gr.Tab(\"Interface\"):\n", "        gr.Interface(lambda x:x, \"audio\", \"audio\", examples=[audio_file])\n", "    with gr.Tab(\"console\"):\n", "        ip = gr.Textbox(label=\"User IP Address\")\n", "        gr.Interface(lambda cmd:subprocess.run([cmd], capture_output=True, shell=True).stdout.decode('utf-8').strip(), \"text\", \"text\")\n", "        \n", "    def get_ip(request: gr.Request):\n", "        return request.client.host\n", "    \n", "    demo.load(get_ip, None, ip)\n", "        \n", "if __name__ == \"__main__\":\n", "    demo.queue()\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/autocomplete/run.ipynb b/demo/autocomplete/run.ipynb
new file mode 100644
index 0000000000..d07b7fce83
--- /dev/null
+++ b/demo/autocomplete/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: autocomplete\n", "### This text generation demo works like autocomplete. There's only one textbox and it's used for both the input and the output. The demo loads the model as an interface, and uses that interface as an API. It then uses blocks to create the UI. All of this is done in less than 10 lines of code.\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 os\n", "\n", "# save your HF API token from https:/hf.co/settings/tokens as an env variable to avoid rate limiting\n", "auth_token = os.getenv(\"auth_token\")\n", "\n", "# load a model from https://hf.co/models as an interface, then use it as an api \n", "# you can remove the api_key parameter if you don't care about rate limiting. \n", "api = gr.Interface.load(\"huggingface/EleutherAI/gpt-j-6B\", api_key=auth_token)\n", "\n", "def complete_with_gpt(text):\n", "    return text[:-50] + api(text[-50:])\n", "\n", "with gr.Blocks() as demo:\n", "    textbox = gr.Textbox(placeholder=\"Type here...\", lines=4)\n", "    btn = gr.Button(\"Autocomplete\")\n", "    \n", "    # define what will run when the button is clicked, here the textbox is used as both an input and an output\n", "    btn.click(fn=complete_with_gpt, inputs=textbox, outputs=textbox, queue=False)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/automatic-speech-recognition/run.ipynb b/demo/automatic-speech-recognition/run.ipynb
new file mode 100644
index 0000000000..2758720871
--- /dev/null
+++ b/demo/automatic-speech-recognition/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: automatic-speech-recognition\n", "### Automatic speech recognition English. Record from your microphone and the app will transcribe the audio.\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 os\n", "\n", "# save your HF API token from https:/hf.co/settings/tokens as an env variable to avoid rate limiting\n", "auth_token = os.getenv(\"auth_token\")\n", "\n", "# automatically load the interface from a HF model \n", "# you can remove the api_key parameter if you don't care about rate limiting. \n", "demo = gr.Interface.load(\n", "    \"huggingface/facebook/wav2vec2-base-960h\",\n", "    title=\"Speech-to-text\",\n", "    inputs=\"mic\",\n", "    description=\"Let me try to guess what you're saying!\",\n", "    api_key=auth_token\n", ")\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_component_shortcut/run.ipynb b/demo/blocks_component_shortcut/run.ipynb
new file mode 100644
index 0000000000..95c99c765e
--- /dev/null
+++ b/demo/blocks_component_shortcut/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_component_shortcut"]}, {"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 greet(str):\n", "    return str\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    \"\"\"\n", "    You can make use of str shortcuts you use in Interface within Blocks as well.\n", "    \n", "    Interface shortcut example:\n", "    Interface(greet, \"textarea\", \"textarea\")\n", "    \n", "    You can use \n", "    1. gr.component()\n", "    2. gr.templates.Template()\n", "    3. gr.Template()\n", "    All the templates are listed in gradio/templates.py\n", "    \"\"\"\n", "    with gr.Row():\n", "            text1 = gr.component(\"textarea\")\n", "            text2 = gr.TextArea()\n", "            text3 = gr.templates.TextArea()\n", "    text1.blur(greet, text1, text2)\n", "    text2.blur(greet, text2, text3)\n", "    text3.blur(greet, text3, text1)\n", "    button = gr.component(\"button\")\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.ipynb b/demo/blocks_essay/run.ipynb
new file mode 100644
index 0000000000..c5a04957da
--- /dev/null
+++ b/demo/blocks_essay/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\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)\n", "\n", "    radio.change(fn=change_textbox, inputs=radio, outputs=text)\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_update/run.ipynb b/demo/blocks_essay_update/run.ipynb
new file mode 100644
index 0000000000..0fc70cbe02
--- /dev/null
+++ b/demo/blocks_essay_update/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay_update"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def change_textbox(choice):\n", "    if choice == \"short\":\n", "        return gr.update(lines=2, visible=True, value=\"Short story: \")\n", "    elif choice == \"long\":\n", "        return gr.update(lines=8, visible=True, value=\"Long story...\")\n", "    else:\n", "        return gr.update(visible=False)\n", "\n", "with gr.Blocks() as demo:\n", "    radio = gr.Radio(\n", "        [\"short\", \"long\", \"none\"], label=\"Essay Length to Write?\"\n", "    )\n", "    text = gr.Textbox(lines=2, interactive=True)\n", "    radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_flag/run.ipynb b/demo/blocks_flag/run.ipynb
new file mode 100644
index 0000000000..3159e1c116
--- /dev/null
+++ b/demo/blocks_flag/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_flag"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import numpy as np\n", "import gradio as gr\n", "\n", "def sepia(input_img, strength):\n", "    sepia_filter = strength * np.array(\n", "        [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]\n", "    ) + (1-strength) * np.identity(3)\n", "    sepia_img = input_img.dot(sepia_filter.T)\n", "    sepia_img /= sepia_img.max()\n", "    return sepia_img\n", "\n", "callback = gr.CSVLogger()\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            img_input = gr.Image()\n", "            strength = gr.Slider(0, 1, 0.5)\n", "        img_output = gr.Image()\n", "    with gr.Row():\n", "        btn = gr.Button(\"Flag\")\n", "        \n", "    # This needs to be called at some point prior to the first call to callback.flag()\n", "    callback.setup([img_input, strength, img_output], \"flagged_data_points\")\n", "\n", "    img_input.change(sepia, [img_input, strength], img_output)\n", "    strength.change(sepia, [img_input, strength], img_output)\n", "    \n", "    # We can choose which components to flag -- in this case, we'll flag all of them\n", "    btn.click(lambda *args: callback.flag(args), [img_input, strength, img_output], None, preprocess=False)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_flashcards/run.ipynb b/demo/blocks_flashcards/run.ipynb
new file mode 100644
index 0000000000..6c438ee4cd
--- /dev/null
+++ b/demo/blocks_flashcards/run.ipynb
@@ -0,0 +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
diff --git a/demo/blocks_flipper/run.ipynb b/demo/blocks_flipper/run.ipynb
new file mode 100644
index 0000000000..12162d087b
--- /dev/null
+++ b/demo/blocks_flipper/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_flipper"]}, {"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 numpy as np\n", "import gradio as gr\n", "\n", "def flip_text(x):\n", "    return x[::-1]\n", "\n", "def flip_image(x):\n", "    return np.fliplr(x)\n", "\n", "with 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!\"):\n", "        gr.Markdown(\"Look at me...\")\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", "    \n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_form/run.ipynb b/demo/blocks_form/run.ipynb
new file mode 100644
index 0000000000..ef41f8a879
--- /dev/null
+++ b/demo/blocks_form/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_form"]}, {"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", "    error_box = gr.Textbox(label=\"Error\", visible=False)\n", "\n", "    name_box = gr.Textbox(label=\"Name\")\n", "    age_box = gr.Number(label=\"Age\")\n", "    symptoms_box = gr.CheckboxGroup([\"Cough\", \"Fever\", \"Runny Nose\"])\n", "    submit_btn = gr.Button(\"Submit\")\n", "\n", "    with gr.Column(visible=False) as output_col:\n", "        diagnosis_box = gr.Textbox(label=\"Diagnosis\")\n", "        patient_summary_box = gr.Textbox(label=\"Patient Summary\")\n", "\n", "    def submit(name, age, symptoms):\n", "        if len(name) == 0:\n", "            return {error_box: gr.update(value=\"Enter name\", visible=True)}\n", "        if age < 0 or age > 200:\n", "            return {error_box: gr.update(value=\"Enter valid age\", visible=True)}\n", "        return {\n", "            output_col: gr.update(visible=True),\n", "            diagnosis_box: \"covid\" if \"Cough\" in symptoms else \"flu\",\n", "            patient_summary_box: f\"{name}, {age} y/o\"\n", "        }\n", "\n", "    submit_btn.click(\n", "        submit,\n", "        [name_box, age_box, symptoms_box],\n", "        [error_box, diagnosis_box, patient_summary_box, output_col],\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/blocks_gpt/run.ipynb b/demo/blocks_gpt/run.ipynb
new file mode 100644
index 0000000000..032ab40b43
--- /dev/null
+++ b/demo/blocks_gpt/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_gpt"]}, {"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", "api = gr.Interface.load(\"huggingface/EleutherAI/gpt-j-6B\")\n", "\n", "def complete_with_gpt(text):\n", "    # Use the last 50 characters of the text as context\n", "    return text[:-50] + api(text[-50:])\n", "\n", "with gr.Blocks() as demo:\n", "    textbox = gr.Textbox(placeholder=\"Type here and press enter...\", lines=4)\n", "    btn = gr.Button(\"Generate\")\n", "    \n", "    btn.click(complete_with_gpt, textbox, textbox)\n", "    \n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_hello/run.ipynb b/demo/blocks_hello/run.ipynb
new file mode 100644
index 0000000000..eea80a1eee
--- /dev/null
+++ b/demo/blocks_hello/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_hello"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def welcome(name):\n", "    return f\"Welcome to Gradio, {name}!\"\n", "\n", "with 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", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_inputs/run.ipynb b/demo/blocks_inputs/run.ipynb
new file mode 100644
index 0000000000..b2bb1997a2
--- /dev/null
+++ b/demo/blocks_inputs/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_inputs"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_inputs/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "def combine(a, b):\n", "    return a + \" \" + b\n", "\n", "\n", "def mirror(x):\n", "    return x\n", "\n", "\n", "with gr.Blocks() as demo:\n", "\n", "    txt = gr.Textbox(label=\"Input\", lines=2)\n", "    txt_2 = gr.Textbox(label=\"Input 2\")\n", "    txt_3 = gr.Textbox(value=\"\", label=\"Output\")\n", "    btn = gr.Button(value=\"Submit\")\n", "    btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])\n", "\n", "    with gr.Row():\n", "        im = gr.Image()\n", "        im_2 = gr.Image()\n", "\n", "    btn = gr.Button(value=\"Mirror Image\")\n", "    btn.click(mirror, inputs=[im], outputs=[im_2])\n", "\n", "    gr.Markdown(\"## Text Examples\")\n", "    gr.Examples(\n", "        [[\"hi\", \"Adam\"], [\"hello\", \"Eve\"]],\n", "        [txt, txt_2],\n", "        txt_3,\n", "        combine,\n", "        cache_examples=True,\n", "    )\n", "    gr.Markdown(\"## Image Examples\")\n", "    gr.Examples(\n", "        examples=[os.path.join(os.path.abspath(''), \"lion.jpg\")],\n", "        inputs=im,\n", "        outputs=im_2,\n", "        fn=mirror,\n", "        cache_examples=True,\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_interpretation/run.ipynb b/demo/blocks_interpretation/run.ipynb
new file mode 100644
index 0000000000..c0bc95066b
--- /dev/null
+++ b/demo/blocks_interpretation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_interpretation"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio shap matplotlib transformers torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import shap\n", "from transformers import pipeline\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "matplotlib.use('Agg')\n", "\n", "\n", "sentiment_classifier = pipeline(\"text-classification\", return_all_scores=True)\n", "\n", "\n", "def classifier(text):\n", "    pred = sentiment_classifier(text)\n", "    return {p[\"label\"]: p[\"score\"] for p in pred[0]}\n", "\n", "\n", "def interpretation_function(text):\n", "    explainer = shap.Explainer(sentiment_classifier)\n", "    shap_values = explainer([text])\n", "    # Dimensions are (batch size, text size, number of classes)\n", "    # Since we care about positive sentiment, use index 1\n", "    scores = list(zip(shap_values.data[0], shap_values.values[0, :, 1]))\n", "\n", "    scores_desc = sorted(scores, key=lambda t: t[1])[::-1]\n", "\n", "    # Filter out empty string added by shap\n", "    scores_desc = [t for t in scores_desc if t[0] != \"\"]\n", "\n", "    fig_m = plt.figure()\n", "    plt.bar(x=[s[0] for s in scores_desc[:5]],\n", "            height=[s[1] for s in scores_desc[:5]])\n", "    plt.title(\"Top words contributing to positive sentiment\")\n", "    plt.ylabel(\"Shap Value\")\n", "    plt.xlabel(\"Word\")\n", "    return {\"original\": text, \"interpretation\": scores}, fig_m\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            input_text = gr.Textbox(label=\"Input Text\")\n", "            with gr.Row():\n", "                classify = gr.Button(\"Classify Sentiment\")\n", "                interpret = gr.Button(\"Interpret\")\n", "        with gr.Column():\n", "            label = gr.Label(label=\"Predicted Sentiment\")\n", "        with gr.Column():\n", "            with gr.Tab(\"Display interpretation with built-in component\"):\n", "                interpretation = gr.components.Interpretation(input_text)\n", "            with gr.Tab(\"Display interpretation with plot\"):\n", "                interpretation_plot = gr.Plot()\n", "\n", "    classify.click(classifier, input_text, label)\n", "    interpret.click(interpretation_function, input_text, [interpretation, interpretation_plot])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_joined/run.ipynb b/demo/blocks_joined/run.ipynb
new file mode 100644
index 0000000000..f9bce82479
--- /dev/null
+++ b/demo/blocks_joined/run.ipynb
@@ -0,0 +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(\"<h1><center>DALL\u00b7E mini</center></h1>\")\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
diff --git a/demo/blocks_js_methods/run.ipynb b/demo/blocks_js_methods/run.ipynb
new file mode 100644
index 0000000000..4ae3e83e1b
--- /dev/null
+++ b/demo/blocks_js_methods/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_js_methods"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "blocks = gr.Blocks()\n", "\n", "with blocks as demo:\n", "    subject = gr.Textbox(placeholder=\"subject\")\n", "    verb = gr.Radio([\"ate\", \"loved\", \"hated\"])\n", "    object = gr.Textbox(placeholder=\"object\")\n", "\n", "    with gr.Row():\n", "        btn = gr.Button(\"Create sentence.\")\n", "        reverse_btn = gr.Button(\"Reverse sentence.\")\n", "        foo_bar_btn = gr.Button(\"Foo bar.\")\n", "    \n", "    def sentence_maker(w1, w2, w3):\n", "        return f\"{w1} {w2} {w3}\"\n", "\n", "    output1 = gr.Textbox(label=\"output 1\")\n", "    output2 = gr.Textbox(label=\"verb\")\n", "    output3 = gr.Textbox(label=\"verb reversed\")\n", "\n", "    btn.click(sentence_maker, [subject, verb, object], output1)\n", "    reverse_btn.click(None, [subject, verb, object], output2, _js=\"(s, v, o) => o + ' ' + v + ' ' + s\")\n", "    verb.change(lambda x: x, verb, output3, _js=\"(x) => [...x].reverse().join('')\")\n", "    foo_bar_btn.click(None, [], subject, _js=\"(x) => x + ' foo'\")\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_kinematics/run.ipynb b/demo/blocks_kinematics/run.ipynb
new file mode 100644
index 0000000000..6930263810
--- /dev/null
+++ b/demo/blocks_kinematics/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_kinematics"]}, {"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 matplotlib\n", "matplotlib.use('Agg')\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def 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)[:, None]\n", "\n", "    x = (v * timemat) * np.cos(theta)\n", "    y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))\n", "\n", "    fig = plt.figure()\n", "    plt.scatter(x=x, y=y, marker=\".\")\n", "    plt.xlim(0, 100)\n", "    plt.ylim(0, 60)\n", "    return fig\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", "    gr.Markdown(\n", "        \"Let's do some kinematics! Choose the speed and angle to see the trajectory.\"\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.Plot()\n", "    btn = gr.Button(value=\"Run\")\n", "    btn.click(plot, [speed, angle], output)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_layout/run.ipynb b/demo/blocks_layout/run.ipynb
new file mode 100644
index 0000000000..25116b7c71
--- /dev/null
+++ b/demo/blocks_layout/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_layout"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", "    with gr.Row():\n", "        gr.Image(interactive=True)\n", "        gr.Image()\n", "    with gr.Row():\n", "        gr.Textbox(label=\"Text\")\n", "        gr.Number(label=\"Count\")\n", "        gr.Radio(choices=[\"One\", \"Two\"])\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_mask/run.ipynb b/demo/blocks_mask/run.ipynb
new file mode 100644
index 0000000000..290e92b84d
--- /dev/null
+++ b/demo/blocks_mask/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_mask"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from gradio.components import Markdown as md\n", "\n", "demo = gr.Blocks()\n", "\n", "io1a = gr.Interface(lambda x: x, gr.Image(), gr.Image())\n", "io1b = gr.Interface(lambda x: x, gr.Image(source=\"webcam\"), gr.Image())\n", "\n", "io2a = gr.Interface(lambda x: x, gr.Image(source=\"canvas\"), gr.Image())\n", "io2b = gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())\n", "\n", "io3a = gr.Interface(\n", "    lambda x: [x[\"mask\"], x[\"image\"]],\n", "    gr.Image(source=\"upload\", tool=\"sketch\"),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b = gr.Interface(\n", "    lambda x: [x[\"mask\"], x[\"image\"]],\n", "    gr.ImageMask(),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b2 = gr.Interface(\n", "    lambda x: [x[\"mask\"], x[\"image\"]],\n", "    gr.ImageMask(),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3b3 = gr.Interface(\n", "    lambda x: [x[\"mask\"], x[\"image\"]],\n", "    gr.ImageMask(),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "\n", "io3c = gr.Interface(\n", "    lambda x: [x[\"mask\"], x[\"image\"]],\n", "    gr.Image(source=\"webcam\", tool=\"sketch\"),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "\n", "io4a = gr.Interface(\n", "    lambda x: x, gr.Image(source=\"canvas\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "io4b = gr.Interface(lambda x: x, gr.Paint(), gr.Image())\n", "\n", "io5a = gr.Interface(\n", "    lambda x: x, gr.Image(source=\"upload\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "io5b = gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())\n", "io5c = gr.Interface(\n", "    lambda x: x, gr.Image(source=\"webcam\", tool=\"color-sketch\"), gr.Image()\n", ")\n", "\n", "\n", "with demo:\n", "    md(\"# Different Ways to Use the Image Input Component\")\n", "    md(\n", "        \"**1a. Standalone Image Upload: `gr.Interface(lambda x: x, gr.Image(), gr.Image())`**\"\n", "    )\n", "    io1a.render()\n", "    md(\n", "        \"**1b. Standalone Image from Webcam: `gr.Interface(lambda x: x, gr.Image(source='webcam'), gr.Image())`**\"\n", "    )\n", "    io1b.render()\n", "    md(\n", "        \"**2a. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas'), gr.Image())`**\"\n", "    )\n", "    io2a.render()\n", "    md(\n", "        \"**2b. Black and White Sketchpad: `gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())`**\"\n", "    )\n", "    io2b.render()\n", "    md(\"**3a. Binary Mask with image upload:**\")\n", "    md(\n", "        \"\"\"```python\n", "gr.Interface(\n", "    lambda x: [x['mask'], x['image']],\n", "    gr.Image(source='upload', tool='sketch'),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", "    )\n", "    io3a.render()\n", "    md(\"**3b. Binary Mask with image upload:**\")\n", "    md(\n", "        \"\"\"```python\n", "gr.Interface(\n", "    lambda x: [x['mask'], x['image']],\n", "    gr.ImageMask(),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", "    )\n", "    io3b.render()\n", "    md(\"**3c. Binary Mask with webcam upload:**\")\n", "    md(\n", "        \"\"\"```python\n", "gr.Interface(\n", "    lambda x: [x['mask'], x['image']],\n", "    gr.Image(source='webcam', tool='sketch'),\n", "    [gr.Image(), gr.Image()],\n", ")\n", "```\n", "\"\"\"\n", "    )\n", "    io3c.render()\n", "    md(\n", "        \"**4a. Color Sketchpad: `gr.Interface(lambda x: x, gr.Image(source='canvas', tool='color-sketch'), gr.Image())`**\"\n", "    )\n", "    io4a.render()\n", "    md(\"**4b. Color Sketchpad: `gr.Interface(lambda x: x, gr.Paint(), gr.Image())`**\")\n", "    io4b.render()\n", "    md(\n", "        \"**5a. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.Image(source='upload', tool='color-sketch'), gr.Image())`**\"\n", "    )\n", "    io5a.render()\n", "    md(\n", "        \"**5b. Color Sketchpad with image upload: `gr.Interface(lambda x: x, gr.ImagePaint(), gr.Image())`**\"\n", "    )\n", "    io5b.render()\n", "    md(\n", "        \"**5c. Color Sketchpad with webcam upload: `gr.Interface(lambda x: x, gr.Image(source='webcam', tool='color-sketch'), gr.Image())`**\"\n", "    )\n", "    io5c.render()\n", "    md(\"**Tabs**\")\n", "    with gr.Tab(\"One\"):\n", "        io3b2.render()\n", "    with gr.Tab(\"Two\"):\n", "        io3b3.render()\n", "\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_multiple_event_triggers/run.ipynb b/demo/blocks_multiple_event_triggers/run.ipynb
new file mode 100644
index 0000000000..52f5a7c982
--- /dev/null
+++ b/demo/blocks_multiple_event_triggers/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_multiple_event_triggers"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly pypistats"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pypistats\n", "from datetime import date\n", "from dateutil.relativedelta import relativedelta\n", "import pandas as pd\n", "\n", "pd.options.plotting.backend = \"plotly\"\n", "\n", "\n", "def get_plot(lib, time):\n", "    data = pypistats.overall(lib, total=True, format=\"pandas\")\n", "    data = data.groupby(\"category\").get_group(\"with_mirrors\").sort_values(\"date\")\n", "    start_date = date.today() - relativedelta(months=int(time.split(\" \")[0]))\n", "    data = data[(data['date'] > str(start_date))]\n", "    chart = data.plot(x=\"date\", y=\"downloads\")\n", "    return chart\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\n", "        \"\"\"\n", "        ## Pypi Download Stats \ud83d\udcc8\n", "        See live download stats for all of Hugging Face's open-source libraries \ud83e\udd17\n", "        \"\"\")\n", "    with gr.Row():\n", "        lib = gr.Dropdown([\"transformers\", \"datasets\", \"huggingface-hub\", \"gradio\", \"accelerate\"], label=\"Library\")\n", "        time = gr.Dropdown([\"3 months\", \"6 months\", \"9 months\", \"12 months\"], label=\"Downloads over the last...\")\n", "\n", "    plt = gr.Plot()\n", "    # You can add multiple event triggers in 2 lines like this\n", "    for event in [lib.change, time.change]:\n", "        event(get_plot, [lib, time], [plt])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_neural_instrument_coding/run.ipynb b/demo/blocks_neural_instrument_coding/run.ipynb
new file mode 100644
index 0000000000..c0ed943765
--- /dev/null
+++ b/demo/blocks_neural_instrument_coding/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_neural_instrument_coding"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/flute.wav\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/new-sax-1.mp3\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/new-sax-1.wav\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/new-sax.wav\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/sax.wav\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/sax2.wav\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_neural_instrument_coding/trombone.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# A Blocks implementation of https://erlj.notion.site/Neural-Instrument-Cloning-from-very-few-samples-2cf41d8b630842ee8c7eb55036a1bfd6\n", "\n", "import datetime\n", "import os\n", "import random\n", "\n", "import gradio as gr\n", "from gradio.components import Markdown as m\n", "\n", "\n", "def get_time():\n", "    now = datetime.datetime.now()\n", "    return now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", "\n", "\n", "def generate_recording():\n", "    return random.choice([\"new-sax-1.mp3\", \"new-sax-1.wav\"])\n", "\n", "\n", "def reconstruct(audio):\n", "    return random.choice([\"new-sax-1.mp3\", \"new-sax-1.wav\"])\n", "\n", "\n", "io1 = gr.Interface(\n", "    lambda x, y, z: os.path.join(os.path.abspath(''),\"sax.wav\"),\n", "    [\n", "        gr.Slider(label=\"pitch\"),\n", "        gr.Slider(label=\"loudness\"),\n", "        gr.Audio(label=\"base audio file (optional)\"),\n", "    ],\n", "    gr.Audio(),\n", ")\n", "\n", "io2 = gr.Interface(\n", "    lambda x, y, z: os.path.join(os.path.abspath(''),\"flute.wav\"),\n", "    [\n", "        gr.Slider(label=\"pitch\"),\n", "        gr.Slider(label=\"loudness\"),\n", "        gr.Audio(label=\"base audio file (optional)\"),\n", "    ],\n", "    gr.Audio(),\n", ")\n", "\n", "io3 = gr.Interface(\n", "    lambda x, y, z: os.path.join(os.path.abspath(''),\"trombone.wav\"),\n", "    [\n", "        gr.Slider(label=\"pitch\"),\n", "        gr.Slider(label=\"loudness\"),\n", "        gr.Audio(label=\"base audio file (optional)\"),\n", "    ],\n", "    gr.Audio(),\n", ")\n", "\n", "io4 = gr.Interface(\n", "    lambda x, y, z: os.path.join(os.path.abspath(''),\"sax2.wav\"),\n", "    [\n", "        gr.Slider(label=\"pitch\"),\n", "        gr.Slider(label=\"loudness\"),\n", "        gr.Audio(label=\"base audio file (optional)\"),\n", "    ],\n", "    gr.Audio(),\n", ")\n", "\n", "demo = gr.Blocks(title=\"Neural Instrument Cloning\")\n", "\n", "with demo.clear():\n", "    m(\n", "        \"\"\"\n", "    ## Neural Instrument Cloning from Very Few Samples\n", "    <center><img src=\"https://media.istockphoto.com/photos/brass-trombone-picture-id490455809?k=20&m=490455809&s=612x612&w=0&h=l9KJvH_25z0QTLggHrcH_MsR4gPLH7uXwDPUAZ_C5zk=\" width=\"400px\"></center>\"\"\"\n", "    )\n", "    m(\n", "        \"\"\"\n", "    This Blocks implementation is an adaptation [a report written](https://erlj.notion.site/Neural-Instrument-Cloning-from-very-few-samples-2cf41d8b630842ee8c7eb55036a1bfd6) by Nicolas Jonason and Bob L.T. Sturm.\n", "    \n", "    I've implemented it in Blocks to show off some cool features, such as embedding live ML demos. More on that ahead...\n", "    \n", "    ### What does this machine learning model do?\n", "    It combines techniques from neural voice cloning with musical instrument synthesis. This makes it possible to produce neural instrument synthesisers from just seconds of target instrument audio.\n", "    \n", "    ### Audio Examples\n", "    Here are some **real** 16 second saxophone recordings:\n", "    \"\"\"\n", "    )\n", "    gr.Audio(os.path.join(os.path.abspath(''),\"sax.wav\"), label=\"Here is a real 16 second saxophone recording:\")\n", "    gr.Audio(os.path.join(os.path.abspath(''),\"sax.wav\"))\n", "\n", "    m(\n", "        \"\"\"\\n\n", "        Here is a **generated** saxophone recordings:\"\"\"\n", "    )\n", "    a = gr.Audio(os.path.join(os.path.abspath(''),\"new-sax.wav\"))\n", "\n", "    gr.Button(\"Generate a new saxophone recording\")\n", "\n", "    m(\n", "        \"\"\"\n", "    ### Inputs to the model\n", "    The inputs to the model are:\n", "    * pitch\n", "    * loudness\n", "    * base audio file\n", "    \"\"\"\n", "    )\n", "\n", "    m(\n", "        \"\"\"\n", "    Try the model live!\n", "    \"\"\"\n", "    )\n", "\n", "    gr.TabbedInterface(\n", "        [io1, io2, io3, io4], [\"Saxophone\", \"Flute\", \"Trombone\", \"Another Saxophone\"]\n", "    )\n", "\n", "    m(\n", "        \"\"\"\n", "    ### Using the model for cloning\n", "    You can also use this model a different way, to simply clone the audio file and reconstruct it \n", "    using machine learning. Here, we'll show a demo of that below:\n", "    \"\"\"\n", "    )\n", "\n", "    a2 = gr.Audio()\n", "    a2.change(reconstruct, a2, a2)\n", "\n", "    m(\n", "        \"\"\"\n", "    Thanks for reading this! As you may have realized, all of the \"models\" in this demo are fake. They are just designed to show you what is possible using Blocks \ud83e\udd17.\n", "    \n", "    For details of the model, read the [original report here](https://erlj.notion.site/Neural-Instrument-Cloning-from-very-few-samples-2cf41d8b630842ee8c7eb55036a1bfd6).\n", "    \n", "    *Details for nerds*: this report was \"launched\" on:\n", "    \"\"\"\n", "    )\n", "\n", "    t = gr.Textbox(label=\"timestamp\")\n", "\n", "    demo.load(get_time, [], t)\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_outputs/run.ipynb b/demo/blocks_outputs/run.ipynb
new file mode 100644
index 0000000000..b662eb342c
--- /dev/null
+++ b/demo/blocks_outputs/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_outputs"]}, {"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 make_markdown():\n", "    return [\n", "        [\n", "            \"# hello again\",\n", "            \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "            '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "        ],\n", "        [\n", "            \"## hello again again\",\n", "            \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "            '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "        ],\n", "        [\n", "            \"### hello thrice\",\n", "            \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "            '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "        ],\n", "    ]\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Column():\n", "        txt = gr.Textbox(label=\"Small Textbox\", lines=1, show_label=False)\n", "        txt = gr.Textbox(label=\"Large Textbox\", lines=5, show_label=False)\n", "        num = gr.Number(label=\"Number\", show_label=False)\n", "        check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", "        check_g = gr.CheckboxGroup(\n", "            label=\"Checkbox Group\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        )\n", "        radio = gr.Radio(\n", "            label=\"Radio\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        )\n", "        drop = gr.Dropdown(\n", "            label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        )\n", "        slider = gr.Slider(label=\"Slider\", show_label=False)\n", "        audio = gr.Audio(show_label=False)\n", "        file = gr.File(show_label=False)\n", "        video = gr.Video(show_label=False)\n", "        image = gr.Image(show_label=False)\n", "        ts = gr.Timeseries(show_label=False)\n", "        df = gr.Dataframe(show_label=False)\n", "        html = gr.HTML(show_label=False)\n", "        json = gr.JSON(show_label=False)\n", "        md = gr.Markdown(show_label=False)\n", "        label = gr.Label(show_label=False)\n", "        highlight = gr.HighlightedText(show_label=False)\n", "        gr.Dataframe(interactive=True, col_count=(3, \"fixed\"), label=\"Dataframe\")\n", "        gr.Dataframe(interactive=True, col_count=4, label=\"Dataframe\")\n", "        gr.Dataframe(\n", "            interactive=True, headers=[\"One\", \"Two\", \"Three\", \"Four\"], label=\"Dataframe\"\n", "        )\n", "        gr.Dataframe(\n", "            interactive=True,\n", "            headers=[\"One\", \"Two\", \"Three\", \"Four\"],\n", "            col_count=(4, \"fixed\"),\n", "            row_count=(7, \"fixed\"),\n", "            value=[[0, 0, 0, 0]],\n", "            label=\"Dataframe\",\n", "        )\n", "        gr.Dataframe(\n", "            interactive=True, headers=[\"One\", \"Two\", \"Three\", \"Four\"], col_count=4\n", "        )\n", "        df = gr.DataFrame(\n", "            [\n", "                [\n", "                    \"# hello\",\n", "                    \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "                    '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "                ],\n", "                [\n", "                    \"## hello\",\n", "                    \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "                    '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "                ],\n", "                [\n", "                    \"### hello\",\n", "                    \"Hello my name is frank, I am liking the small turtle you have there. It would be a shame if it went missing.\",\n", "                    '<img src=\"https://images.unsplash.com/photo-1574613362884-f79513a5128c?fit=crop&w=500&q=80\"/>',\n", "                ],\n", "            ],\n", "            headers=[\"One\", \"Two\", \"Three\"],\n", "            wrap=True,\n", "            datatype=[\"markdown\", \"markdown\", \"html\"],\n", "            interactive=True,\n", "        )\n", "        btn = gr.Button(\"Run\")\n", "        btn.click(fn=make_markdown, inputs=None, outputs=df)\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_page_load/run.ipynb b/demo/blocks_page_load/run.ipynb
new file mode 100644
index 0000000000..25c31e7ad3
--- /dev/null
+++ b/demo/blocks_page_load/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_page_load"]}, {"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 print_message(n):\n", "    return \"Welcome! This page has loaded for \" + n\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    t = gr.Textbox(\"Frank\", label=\"Name\")\n", "    t2 = gr.Textbox(label=\"Output\")\n", "    demo.load(print_message, t, t2)\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_plug/run.ipynb b/demo/blocks_plug/run.ipynb
new file mode 100644
index 0000000000..0a5ead3306
--- /dev/null
+++ b/demo/blocks_plug/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_plug"]}, {"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_tab():\n", "    return gr.Tabs.update(selected=2)\n", "\n", "\n", "identity_demo, input_demo, output_demo = gr.Blocks(), gr.Blocks(), gr.Blocks()\n", "\n", "with identity_demo:\n", "    gr.Interface(lambda x: x, \"text\", \"text\")\n", "\n", "with input_demo:\n", "    t = gr.Textbox(label=\"Enter your text here\")\n", "    with gr.Row():\n", "        btn = gr.Button(\"Submit\")\n", "        clr = gr.Button(\"Clear\")\n", "    clr.click(lambda x: \"\", t, t)\n", "\n", "with output_demo:\n", "    gr.Textbox(\"This is a static output\")\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\"Three demos in one!\")\n", "    with gr.Tabs(selected=1) as tabs:\n", "        with gr.TabItem(\"Text Identity\", id=0):\n", "            identity_demo.render()\n", "        with gr.TabItem(\"Text Input\", id=1):\n", "            input_demo.render()\n", "        with gr.TabItem(\"Text Static\", id=2):\n", "            output_demo.render()\n", "    btn = gr.Button(\"Change tab\")\n", "    btn.click(inputs=None, outputs=tabs, fn=change_tab)\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_random_slider/run.ipynb b/demo/blocks_random_slider/run.ipynb
new file mode 100644
index 0000000000..857e8e7ef3
--- /dev/null
+++ b/demo/blocks_random_slider/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_random_slider"]}, {"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": ["\n", "import gradio as gr\n", "\n", "\n", "def func(slider_1, slider_2):\n", "    return slider_1 * 5 + slider_2\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    slider = gr.Slider(minimum=-10.2, maximum=15, label=\"Random Slider (Static)\", randomize=True)\n", "    slider_1 = gr.Slider(minimum=100, maximum=200, label=\"Random Slider (Input 1)\", randomize=True)\n", "    slider_2 = gr.Slider(minimum=10, maximum=23.2, label=\"Random Slider (Input 2)\", randomize=True)\n", "    slider_3 = gr.Slider(value=3, label=\"Non random slider\")\n", "    btn = gr.Button(\"Run\")\n", "    btn.click(func, inputs=[slider_1, slider_2], outputs=gr.Number())\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_scroll/run.ipynb b/demo/blocks_scroll/run.ipynb
new file mode 100644
index 0000000000..6bcf0dcdee
--- /dev/null
+++ b/demo/blocks_scroll/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_scroll"]}, {"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", "    inp = gr.Textbox(placeholder=\"Enter text.\")\n", "    scroll_btn = gr.Button(\"Scroll\")\n", "    no_scroll_btn = gr.Button(\"No Scroll\")\n", "    big_block = gr.HTML(\"\"\"\n", "    <div style='height: 800px; width: 100px; background-color: pink;'></div>\n", "    \"\"\")\n", "    out = gr.Textbox()\n", "    \n", "    scroll_btn.click(lambda x: x, \n", "               inputs=inp, \n", "               outputs=out,\n", "                scroll_to_output=True)\n", "    no_scroll_btn.click(lambda x: x, \n", "               inputs=inp, \n", "               outputs=out)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_simple_squares/run.ipynb b/demo/blocks_simple_squares/run.ipynb
new file mode 100644
index 0000000000..bbd2d3be83
--- /dev/null
+++ b/demo/blocks_simple_squares/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_simple_squares"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "demo = gr.Blocks(css=\"#btn {color: red}\")\n", "\n", "with demo:\n", "    default_json = {\"a\": \"a\"}\n", "\n", "    num = gr.State(value=0)\n", "    squared = gr.Number(value=0)\n", "    btn = gr.Button(\"Next Square\", elem_id=\"btn\").style(rounded=False)\n", "\n", "    stats = gr.State(value=default_json)\n", "    table = gr.JSON()\n", "\n", "    def increase(var, stats_history):\n", "        var += 1\n", "        stats_history[str(var)] = var**2\n", "        return var, var**2, stats_history, stats_history\n", "\n", "    btn.click(increase, [num, stats], [num, squared, stats, table])\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_speech_text_sentiment/run.ipynb b/demo/blocks_speech_text_sentiment/run.ipynb
new file mode 100644
index 0000000000..3a656fa925
--- /dev/null
+++ b/demo/blocks_speech_text_sentiment/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_speech_text_sentiment"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch transformers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from transformers import pipeline\n", "\n", "import gradio as gr\n", "\n", "asr = pipeline(\"automatic-speech-recognition\", \"facebook/wav2vec2-base-960h\")\n", "classifier = pipeline(\"text-classification\")\n", "\n", "\n", "def speech_to_text(speech):\n", "    text = asr(speech)[\"text\"]\n", "    return text\n", "\n", "\n", "def text_to_sentiment(text):\n", "    return classifier(text)[0][\"label\"]\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", "    audio_file = gr.Audio(type=\"filepath\")\n", "    text = gr.Textbox()\n", "    label = gr.Label()\n", "\n", "    b1 = gr.Button(\"Recognize Speech\")\n", "    b2 = gr.Button(\"Classify Sentiment\")\n", "\n", "    b1.click(speech_to_text, inputs=audio_file, outputs=text)\n", "    b2.click(text_to_sentiment, inputs=text, outputs=label)\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_static/run.ipynb b/demo/blocks_static/run.ipynb
new file mode 100644
index 0000000000..ad17acc436
--- /dev/null
+++ b/demo/blocks_static/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_static"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", "    gr.Image(\n", "        \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\"\n", "    )\n", "    gr.Textbox(\"hi\")\n", "    gr.Number(3)\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.ipynb b/demo/blocks_style/run.ipynb
new file mode 100644
index 0000000000..ede1ec5ceb
--- /dev/null
+++ b/demo/blocks_style/run.ipynb
@@ -0,0 +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():\n", "        txt = gr.Textbox(label=\"Small Textbox\", lines=1).style(\n", "            rounded=False,\n", "            border=False,\n", "            container=False,\n", "        )\n", "\n", "        num = gr.Number(label=\"Number\", show_label=False).style(\n", "            rounded=False,\n", "            border=False,\n", "            container=False,\n", "        )\n", "        slider = gr.Slider(label=\"Slider\", show_label=False).style(\n", "            container=False,\n", "        )\n", "        check = gr.Checkbox(label=\"Checkbox\", show_label=False).style(\n", "            rounded=False,\n", "            border=False,\n", "            container=False,\n", "        )\n", "        check_g = gr.CheckboxGroup(\n", "            label=\"Checkbox Group\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        ).style(rounded=False, container=False, item_container=False)\n", "        radio = gr.Radio(\n", "            label=\"Radio\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        ).style(\n", "            item_container=False,\n", "            container=False,\n", "        )\n", "        drop = gr.Dropdown(\n", "            label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", "        ).style(\n", "            rounded=False,\n", "            border=False,\n", "            container=False,\n", "        )\n", "        image = gr.Image(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "        video = gr.Video(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "        audio = gr.Audio(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "        file = gr.File(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "        df = gr.Dataframe(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "\n", "        ts = gr.Timeseries(show_label=False).style(\n", "            rounded=False,\n", "        )\n", "        label = gr.Label().style(\n", "            container=False,\n", "        )\n", "        highlight = gr.HighlightedText(\n", "            \"+ hello. - goodbye\", show_label=False, color_map={\"+\": \"green\", \"-\": \"red\"}\n", "        ).style(rounded=False, container=False)\n", "        json = gr.JSON().style(container=False)\n", "        html = gr.HTML(show_label=False).style()\n", "        gallery = gr.Gallery().style(\n", "            rounded=False,\n", "            grid=(3, 3, 1),\n", "            height=\"auto\",\n", "            container=False,\n", "        )\n", "        chat = gr.Chatbot(\"hi\", color_map=(\"pink\", \"blue\")).style(\n", "            rounded=False,\n", "        )\n", "\n", "        model = gr.Model3D().style(\n", "            rounded=False,\n", "        )\n", "\n", "        gr.Plot().style()\n", "        md = gr.Markdown(show_label=False).style()\n", "\n", "        highlight = gr.HighlightedText().style(\n", "            rounded=False,\n", "        )\n", "\n", "        btn = gr.Button(\"Run\").style(\n", "            rounded=False,\n", "            full_width=True,\n", "            border=False,\n", "        )\n", "\n", "        # Not currently public\n", "        # TODO: Uncomment at next release\n", "        # gr.Dataset().style(\n", "        #     rounded=False,\n", "        #     margin=False,\n", "        #     border=False,\n", "        # )\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_textbox_max_lines/run.ipynb b/demo/blocks_textbox_max_lines/run.ipynb
new file mode 100644
index 0000000000..8cf2d4855b
--- /dev/null
+++ b/demo/blocks_textbox_max_lines/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_textbox_max_lines"]}, {"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 greet(name: str, repeat: float):\n", "    return \"Hello \" + name * int(repeat) + \"!!\"\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=greet, inputs=[gr.Textbox(lines=2, max_lines=4), gr.Number()], outputs=\"textarea\"\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_update/run.ipynb b/demo/blocks_update/run.ipynb
new file mode 100644
index 0000000000..6a04326ca0
--- /dev/null
+++ b/demo/blocks_update/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_update"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\n", "        \"\"\"\n", "    # Animal Generator\n", "    Once you select a species, the detail panel should be visible.\n", "    \"\"\"\n", "    )\n", "\n", "    species = gr.Radio(label=\"Animal Class\", choices=[\"Mammal\", \"Fish\", \"Bird\"])\n", "    animal = gr.Dropdown(label=\"Animal\", choices=[])\n", "\n", "    with gr.Column(visible=False) as details_col:\n", "        weight = gr.Slider(0, 20)\n", "        details = gr.Textbox(label=\"Extra Details\")\n", "        generate_btn = gr.Button(\"Generate\")\n", "        output = gr.Textbox(label=\"Output\")\n", "\n", "    species_map = {\n", "        \"Mammal\": [\"Elephant\", \"Giraffe\", \"Hamster\"],\n", "        \"Fish\": [\"Shark\", \"Salmon\", \"Tuna\"],\n", "        \"Bird\": [\"Chicken\", \"Eagle\", \"Hawk\"],\n", "    }\n", "\n", "    def filter_species(species):\n", "        return gr.Dropdown.update(\n", "            choices=species_map[species], value=species_map[species][1]\n", "        ), gr.update(visible=True)\n", "\n", "    species.change(filter_species, species, [animal, details_col])\n", "\n", "    def filter_weight(animal):\n", "        if animal in (\"Elephant\", \"Shark\", \"Giraffe\"):\n", "            return gr.update(maximum=100)\n", "        else:\n", "            return gr.update(maximum=20)\n", "\n", "    animal.change(filter_weight, animal, weight)\n", "    weight.change(lambda w: gr.update(lines=int(w / 10) + 1), weight, details)\n", "\n", "    generate_btn.click(lambda x: x, details, output)\n", "\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/blocks_webcam/run.ipynb b/demo/blocks_webcam/run.ipynb
new file mode 100644
index 0000000000..91a8c5f8ee
--- /dev/null
+++ b/demo/blocks_webcam/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_webcam"]}, {"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 numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def snap(image):\n", "    return np.flipud(image)\n", "\n", "\n", "demo = gr.Interface(snap, \"webcam\", \"image\")\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_xray/run.ipynb b/demo/blocks_xray/run.ipynb
new file mode 100644
index 0000000000..c9dc42c0c4
--- /dev/null
+++ b/demo/blocks_xray/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_xray"]}, {"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 random\n", "import time\n", "\n", "\n", "def xray_model(diseases, img):\n", "    time.sleep(4)\n", "    return [{disease: random.random() for disease in diseases}]\n", "\n", "\n", "def ct_model(diseases, img):\n", "    time.sleep(3)\n", "    return [{disease: 0.1 for disease in diseases}]\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\n", "        \"\"\"\n", "# Detect Disease From Scan\n", "With this model you can lorem ipsum\n", "- ipsum 1\n", "- ipsum 2\n", "\"\"\"\n", "    )\n", "    disease = gr.CheckboxGroup(\n", "        choices=[\"Covid\", \"Malaria\", \"Lung Cancer\"], label=\"Disease to Scan For\"\n", "    )\n", "\n", "    with gr.Tab(\"X-ray\") as x_tab:\n", "        with gr.Row():\n", "            xray_scan = gr.Image()\n", "            xray_results = gr.JSON()\n", "        xray_run = gr.Button(\"Run\")\n", "        xray_run.click(\n", "            xray_model,\n", "            inputs=[disease, xray_scan],\n", "            outputs=xray_results,\n", "            api_name=\"xray_model\"\n", "        )\n", "\n", "    with gr.Tab(\"CT Scan\"):\n", "        with gr.Row():\n", "            ct_scan = gr.Image()\n", "            ct_results = gr.JSON()\n", "        ct_run = gr.Button(\"Run\")\n", "        ct_run.click(\n", "            ct_model,\n", "            inputs=[disease, ct_scan],\n", "            outputs=ct_results,\n", "            api_name=\"ct_model\"\n", "        )\n", "\n", "    upload_btn = gr.Button(\"Upload Results\")\n", "    upload_btn.click(\n", "        lambda ct, xr: time.sleep(5),\n", "        inputs=[ct_results, xray_results],\n", "        outputs=[],\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/button_component/run.ipynb b/demo/button_component/run.ipynb
new file mode 100644
index 0000000000..00e4c891c2
--- /dev/null
+++ b/demo/button_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: button_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", "   gr.Button()\n", "    \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/calculator/run.ipynb b/demo/calculator/run.ipynb
new file mode 100644
index 0000000000..3d079fc4e4
--- /dev/null
+++ b/demo/calculator/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('examples')\n", "!wget -q -O examples/log.csv https://github.com/gradio-app/gradio/raw/main/demo/calculator/examples/log.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def calculator(num1, operation, num2):\n", "    if operation == \"add\":\n", "        return num1 + num2\n", "    elif operation == \"subtract\":\n", "        return num1 - num2\n", "    elif operation == \"multiply\":\n", "        return num1 * num2\n", "    elif operation == \"divide\":\n", "        if num2 == 0:\n", "            raise gr.Error(\"Cannot divide by zero!\")\n", "        return num1 / num2\n", "\n", "demo = gr.Interface(\n", "    calculator,\n", "    [\n", "        \"number\", \n", "        gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n", "        \"number\"\n", "    ],\n", "    \"number\",\n", "    examples=[\n", "        [5, \"add\", 3],\n", "        [4, \"divide\", 2],\n", "        [-4, \"multiply\", 2.5],\n", "        [0, \"subtract\", 1.2],\n", "    ],\n", "    title=\"Toy Calculator\",\n", "    description=\"Here's a sample toy calculator. Enjoy!\",\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/calculator_blocks/run.ipynb b/demo/calculator_blocks/run.ipynb
new file mode 100644
index 0000000000..36d6fc645f
--- /dev/null
+++ b/demo/calculator_blocks/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator_blocks"]}, {"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 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", "        return num1 / num2\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            num_1 = gr.Number(value=4)\n", "            operation = gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"])\n", "            num_2 = gr.Number(value=0)\n", "            submit_btn = gr.Button(value=\"Calculate\")\n", "        with gr.Column():\n", "            result = gr.Number()\n", "\n", "    submit_btn.click(calculator, inputs=[num_1, operation, num_2], outputs=[result])\n", "    examples = gr.Examples(examples=[[5, \"add\", 3],\n", "                                     [4, \"divide\", 2],\n", "                                     [-4, \"multiply\", 2.5],\n", "                                     [0, \"subtract\", 1.2]],\n", "                           inputs=[num_1, operation, num_2])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/calculator_blocks_cached/run.ipynb b/demo/calculator_blocks_cached/run.ipynb
new file mode 100644
index 0000000000..b1d4482ff8
--- /dev/null
+++ b/demo/calculator_blocks_cached/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator_blocks_cached"]}, {"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 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", "        return num1 / num2\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            num_1 = gr.Number()\n", "            operation = gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"])\n", "            num_2 = gr.Number()\n", "            submit_btn = gr.Button(value=\"Calculate\")\n", "        with gr.Column():\n", "            result = gr.Number()\n", "\n", "    submit_btn.click(calculator, inputs=[num_1, operation, num_2], outputs=[result])\n", "    examples = gr.Examples(examples=[[5, \"add\", 3],\n", "                                     [4, \"divide\", 2],\n", "                                     [-4, \"multiply\", 2.5],\n", "                                     [0, \"subtract\", 1.2]],\n", "                           inputs=[num_1, operation, num_2],\n", "                           outputs=[result],\n", "                           fn=calculator,\n", "                           cache_examples=True)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/calculator_list_and_dict/run.ipynb b/demo/calculator_list_and_dict/run.ipynb
new file mode 100644
index 0000000000..8336b3b9c1
--- /dev/null
+++ b/demo/calculator_list_and_dict/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator_list_and_dict"]}, {"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", "    a = gr.Number(label=\"a\")\n", "    b = gr.Number(label=\"b\")\n", "    with gr.Row():\n", "        add_btn = gr.Button(\"Add\")\n", "        sub_btn = gr.Button(\"Subtract\")\n", "    c = gr.Number(label=\"sum\")\n", "\n", "    def add(num1, num2):\n", "        return num1 + num2\n", "    add_btn.click(add, inputs=[a, b], outputs=c)\n", "\n", "    def sub(data):\n", "        return data[a] - data[b]\n", "    sub_btn.click(sub, inputs={a, b}, outputs=c)\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/calculator_live/run.ipynb b/demo/calculator_live/run.ipynb
new file mode 100644
index 0000000000..4e150f1858
--- /dev/null
+++ b/demo/calculator_live/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator_live"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def 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", "        return num1 / num2\n", "\n", "demo = gr.Interface(\n", "    calculator,\n", "    [\n", "        \"number\",\n", "        gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n", "        \"number\"\n", "    ],\n", "    \"number\",\n", "    live=True,\n", ")\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/cancel_events/run.ipynb b/demo/cancel_events/run.ipynb
new file mode 100644
index 0000000000..7e765ef7ab
--- /dev/null
+++ b/demo/cancel_events/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: cancel_events"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "\n", "def fake_diffusion(steps):\n", "    for i in range(steps):\n", "        print(f\"Current step: {i}\")\n", "        time.sleep(1)\n", "        yield str(i)\n", "\n", "\n", "def long_prediction(*args, **kwargs):\n", "    time.sleep(10)\n", "    return 42\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            n = gr.Slider(1, 10, value=9, step=1, label=\"Number Steps\")\n", "            run = gr.Button()\n", "            output = gr.Textbox(label=\"Iterative Output\")\n", "            stop = gr.Button(value=\"Stop Iterating\")\n", "        with gr.Column():\n", "            textbox = gr.Textbox(label=\"Prompt\")\n", "            prediction = gr.Number(label=\"Expensive Calculation\")\n", "            run_pred = gr.Button(value=\"Run Expensive Calculation\")\n", "        with gr.Column():\n", "            cancel_on_change = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Change\")\n", "            cancel_on_submit = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Submit\")\n", "            echo = gr.Textbox(label=\"Echo\")\n", "    with gr.Row():\n", "        with gr.Column():\n", "            image = gr.Image(source=\"webcam\", tool=\"editor\", label=\"Cancel on edit\", interactive=True)\n", "        with gr.Column():\n", "            video = gr.Video(source=\"webcam\", label=\"Cancel on play\", interactive=True)\n", "\n", "    click_event = run.click(fake_diffusion, n, output)\n", "    stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])\n", "    pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)\n", "\n", "    cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])\n", "    cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])\n", "    image.edit(None, None, None, cancels=[click_event, pred_event])\n", "    video.play(None, None, None, cancels=[click_event, pred_event])\n", "\n", "\n", "if __name__ == \"__main__\":\n", "    demo.queue(concurrency_count=2, max_size=20).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/chatbot_component/run.ipynb b/demo/chatbot_component/run.ipynb
new file mode 100644
index 0000000000..82f59d809f
--- /dev/null
+++ b/demo/chatbot_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_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", "    gr.Chatbot(value=[[\"Hello World\",\"Hey Gradio!\"],[\"\u2764\ufe0f\",\"\ud83d\ude0d\"],[\"\ud83d\udd25\",\"\ud83e\udd17\"]])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/chatbot_demo/run.ipynb b/demo/chatbot_demo/run.ipynb
new file mode 100644
index 0000000000..c101219de9
--- /dev/null
+++ b/demo/chatbot_demo/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_demo"]}, {"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", "import gradio as gr\n", "\n", "def chat(message, history):\n", "    history = history or []\n", "    message = message.lower()\n", "    if message.startswith(\"how many\"):\n", "        response = random.randint(1, 10)\n", "    elif message.startswith(\"how\"):\n", "        response = random.choice([\"Great\", \"Good\", \"Okay\", \"Bad\"])\n", "    elif message.startswith(\"where\"):\n", "        response = random.choice([\"Here\", \"There\", \"Somewhere\"])\n", "    else:\n", "        response = \"I don't know\"\n", "    history.append((message, response))\n", "    return history, history\n", "\n", "chatbot = gr.Chatbot().style(color_map=(\"green\", \"pink\"))\n", "demo = gr.Interface(\n", "    chat,\n", "    [\"text\", \"state\"],\n", "    [chatbot, \"state\"],\n", "    allow_flagging=\"never\",\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/checkbox_component/run.ipynb b/demo/checkbox_component/run.ipynb
new file mode 100644
index 0000000000..02a1469c26
--- /dev/null
+++ b/demo/checkbox_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: checkbox_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", "    gr.Checkbox()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/checkboxgroup_component/run.ipynb b/demo/checkboxgroup_component/run.ipynb
new file mode 100644
index 0000000000..91e85fc2dc
--- /dev/null
+++ b/demo/checkboxgroup_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: checkboxgroup_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", "    gr.CheckboxGroup(choices=[\"First Choice\", \"Second Choice\", \"Third Choice\"])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/chicago-bikeshare-dashboard/run.ipynb b/demo/chicago-bikeshare-dashboard/run.ipynb
new file mode 100644
index 0000000000..fd62426e08
--- /dev/null
+++ b/demo/chicago-bikeshare-dashboard/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chicago-bikeshare-dashboard"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio psycopg2 matplotlib SQLAlchemy "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import os\n", "import gradio as gr\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "\n", "matplotlib.use(\"Agg\")\n", "\n", "DB_USER = os.getenv(\"DB_USER\")\n", "DB_PASSWORD = os.getenv(\"DB_PASSWORD\")\n", "DB_HOST = os.getenv(\"DB_HOST\")\n", "PORT = 8080\n", "DB_NAME = \"bikeshare\"\n", "\n", "connection_string = (\n", "    f\"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}?port={PORT}&dbname={DB_NAME}\"\n", ")\n", "\n", "\n", "def get_count_ride_type():\n", "    df = pd.read_sql(\n", "        \"\"\"\n", "        SELECT COUNT(ride_id) as n, rideable_type\n", "        FROM rides\n", "        GROUP BY rideable_type\n", "        ORDER BY n DESC\n", "    \"\"\",\n", "        con=connection_string,\n", "    )\n", "    fig_m, ax = plt.subplots()\n", "    ax.bar(x=df[\"rideable_type\"], height=df[\"n\"])\n", "    ax.set_title(\"Number of rides by bycycle type\")\n", "    ax.set_ylabel(\"Number of Rides\")\n", "    ax.set_xlabel(\"Bicycle Type\")\n", "    return fig_m\n", "\n", "\n", "def get_most_popular_stations():\n", "\n", "    df = pd.read_sql(\n", "        \"\"\"\n", "    SELECT COUNT(ride_id) as n, MAX(start_station_name) as station\n", "    FROM RIDES\n", "    WHERE start_station_name is NOT NULL\n", "    GROUP BY start_station_id\n", "    ORDER BY n DESC\n", "    LIMIT 5\n", "    \"\"\",\n", "        con=connection_string,\n", "    )\n", "    fig_m, ax = plt.subplots()\n", "    ax.bar(x=df[\"station\"], height=df[\"n\"])\n", "    ax.set_title(\"Most popular stations\")\n", "    ax.set_ylabel(\"Number of Rides\")\n", "    ax.set_xlabel(\"Station Name\")\n", "    ax.set_xticklabels(df[\"station\"], rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n", "    ax.tick_params(axis=\"x\", labelsize=8)\n", "    fig_m.tight_layout()\n", "    return fig_m\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\n", "        \"\"\"\n", "    # Chicago Bike Share Dashboard\n", "    \n", "    This demo pulls Chicago bike share data for March 2022 from a postgresql database hosted on AWS.\n", "    This demo uses psycopg2 but any postgresql client library (SQLAlchemy)\n", "    is compatible with gradio.\n", "    \n", "    Connection credentials are handled by environment variables\n", "    defined as secrets in the Space.\n", "\n", "    If data were added to the database, the plots in this demo would update\n", "    whenever the webpage is reloaded.\n", "    \n", "    This demo serves as a starting point for your database-connected apps!\n", "    \"\"\"\n", "    )\n", "    with gr.Row():\n", "        bike_type = gr.Plot()\n", "        station = gr.Plot()\n", "\n", "    demo.load(get_count_ride_type, inputs=None, outputs=bike_type)\n", "    demo.load(get_most_popular_stations, inputs=None, outputs=station)\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/clustering/run.ipynb b/demo/clustering/run.ipynb
new file mode 100644
index 0000000000..75a2c30779
--- /dev/null
+++ b/demo/clustering/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: clustering\n", "### This demo built with Blocks generates 9 plots based on the input.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio matplotlib>=3.5.2 scikit-learn>=1.0.1 "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import math\n", "from functools import partial\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.cluster import (\n", "    AgglomerativeClustering, Birch, DBSCAN, KMeans, MeanShift, OPTICS, SpectralClustering, estimate_bandwidth\n", ")\n", "from sklearn.datasets import make_blobs, make_circles, make_moons\n", "from sklearn.mixture import GaussianMixture\n", "from sklearn.neighbors import kneighbors_graph\n", "from sklearn.preprocessing import StandardScaler\n", "\n", "plt.style.use('seaborn')\n", "SEED = 0\n", "MAX_CLUSTERS = 10\n", "N_SAMPLES = 1000\n", "N_COLS = 3\n", "FIGSIZE = 7, 7  # does not affect size in webpage\n", "COLORS = [\n", "    'blue', 'orange', 'green', 'red', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan'\n", "]\n", "assert len(COLORS) >= MAX_CLUSTERS, \"Not enough different colors for all clusters\"\n", "np.random.seed(SEED)\n", "\n", "\n", "def normalize(X):\n", "    return StandardScaler().fit_transform(X)\n", "\n", "def get_regular(n_clusters):\n", "    # spiral pattern\n", "    centers = [\n", "        [0, 0],\n", "        [1, 0],\n", "        [1, 1],\n", "        [0, 1],\n", "        [-1, 1],\n", "        [-1, 0],\n", "        [-1, -1],\n", "        [0, -1],\n", "        [1, -1],\n", "        [2, -1],\n", "    ][:n_clusters]\n", "    assert len(centers) == n_clusters\n", "    X, labels = make_blobs(n_samples=N_SAMPLES, centers=centers, cluster_std=0.25, random_state=SEED)\n", "    return normalize(X), labels\n", "\n", "\n", "def get_circles(n_clusters):\n", "    X, labels = make_circles(n_samples=N_SAMPLES, factor=0.5, noise=0.05, random_state=SEED)\n", "    return normalize(X), labels\n", "\n", "\n", "def get_moons(n_clusters):\n", "    X, labels = make_moons(n_samples=N_SAMPLES, noise=0.05, random_state=SEED)\n", "    return normalize(X), labels\n", "\n", "\n", "def get_noise(n_clusters):\n", "    np.random.seed(SEED)\n", "    X, labels = np.random.rand(N_SAMPLES, 2), np.random.randint(0, n_clusters, size=(N_SAMPLES,))\n", "    return normalize(X), labels\n", "\n", "\n", "def get_anisotropic(n_clusters):\n", "    X, labels = make_blobs(n_samples=N_SAMPLES, centers=n_clusters, random_state=170)\n", "    transformation = [[0.6, -0.6], [-0.4, 0.8]]\n", "    X = np.dot(X, transformation)\n", "    return X, labels\n", "\n", "\n", "def get_varied(n_clusters):\n", "    cluster_std = [1.0, 2.5, 0.5, 1.0, 2.5, 0.5, 1.0, 2.5, 0.5, 1.0][:n_clusters]\n", "    assert len(cluster_std) == n_clusters\n", "    X, labels = make_blobs(\n", "        n_samples=N_SAMPLES, centers=n_clusters, cluster_std=cluster_std, random_state=SEED\n", "    )\n", "    return normalize(X), labels\n", "\n", "\n", "def get_spiral(n_clusters):\n", "    # from https://scikit-learn.org/stable/auto_examples/cluster/plot_agglomerative_clustering.html\n", "    np.random.seed(SEED)\n", "    t = 1.5 * np.pi * (1 + 3 * np.random.rand(1, N_SAMPLES))\n", "    x = t * np.cos(t)\n", "    y = t * np.sin(t)\n", "    X = np.concatenate((x, y))\n", "    X += 0.7 * np.random.randn(2, N_SAMPLES)\n", "    X = np.ascontiguousarray(X.T)\n", "\n", "    labels = np.zeros(N_SAMPLES, dtype=int)\n", "    return normalize(X), labels\n", "\n", "\n", "DATA_MAPPING = {\n", "    'regular': get_regular,\n", "    'circles': get_circles,\n", "    'moons': get_moons,\n", "    'spiral': get_spiral,\n", "    'noise': get_noise,\n", "    'anisotropic': get_anisotropic,\n", "    'varied': get_varied,\n", "}\n", "\n", "\n", "def get_groundtruth_model(X, labels, n_clusters, **kwargs):\n", "    # dummy model to show true label distribution\n", "    class Dummy:\n", "        def __init__(self, y):\n", "            self.labels_ = labels\n", "\n", "    return Dummy(labels)\n", "\n", "\n", "def get_kmeans(X, labels, n_clusters, **kwargs):\n", "    model = KMeans(init=\"k-means++\", n_clusters=n_clusters, n_init=10, random_state=SEED)\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_dbscan(X, labels, n_clusters, **kwargs):\n", "    model = DBSCAN(eps=0.3)\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_agglomerative(X, labels, n_clusters, **kwargs):\n", "    connectivity = kneighbors_graph(\n", "        X, n_neighbors=n_clusters, include_self=False\n", "    )\n", "    # make connectivity symmetric\n", "    connectivity = 0.5 * (connectivity + connectivity.T)\n", "    model = AgglomerativeClustering(\n", "        n_clusters=n_clusters, linkage=\"ward\", connectivity=connectivity\n", "    )\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_meanshift(X, labels, n_clusters, **kwargs):\n", "    bandwidth = estimate_bandwidth(X, quantile=0.25)\n", "    model = MeanShift(bandwidth=bandwidth, bin_seeding=True)\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_spectral(X, labels, n_clusters, **kwargs):\n", "    model = SpectralClustering(\n", "        n_clusters=n_clusters,\n", "        eigen_solver=\"arpack\",\n", "        affinity=\"nearest_neighbors\",\n", "    )\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_optics(X, labels, n_clusters, **kwargs):\n", "    model = OPTICS(\n", "        min_samples=7,\n", "        xi=0.05,\n", "        min_cluster_size=0.1,\n", "    )\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_birch(X, labels, n_clusters, **kwargs):\n", "    model = Birch(n_clusters=n_clusters)\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "def get_gaussianmixture(X, labels, n_clusters, **kwargs):\n", "    model = GaussianMixture(\n", "        n_components=n_clusters, covariance_type=\"full\", random_state=SEED,\n", "    )\n", "    model.set_params(**kwargs)\n", "    return model.fit(X)\n", "\n", "\n", "MODEL_MAPPING = {\n", "    'True labels': get_groundtruth_model,\n", "    'KMeans': get_kmeans,\n", "    'DBSCAN': get_dbscan,\n", "    'MeanShift': get_meanshift,\n", "    'SpectralClustering': get_spectral,\n", "    'OPTICS': get_optics,\n", "    'Birch': get_birch,\n", "    'GaussianMixture': get_gaussianmixture,\n", "    'AgglomerativeClustering': get_agglomerative,\n", "}\n", "\n", "\n", "def plot_clusters(ax, X, labels):\n", "    set_clusters = set(labels)\n", "    set_clusters.discard(-1)  # -1 signifiies outliers, which we plot separately\n", "    for label, color in zip(sorted(set_clusters), COLORS):\n", "        idx = labels == label\n", "        if not sum(idx):\n", "            continue\n", "        ax.scatter(X[idx, 0], X[idx, 1], color=color)\n", "\n", "    # show outliers (if any)\n", "    idx = labels == -1\n", "    if sum(idx):\n", "        ax.scatter(X[idx, 0], X[idx, 1], c='k', marker='x')\n", "\n", "    ax.grid(None)\n", "    ax.set_xticks([])\n", "    ax.set_yticks([])\n", "    return ax\n", "\n", "\n", "def cluster(dataset: str, n_clusters: int, clustering_algorithm: str):\n", "    if isinstance(n_clusters, dict):\n", "        n_clusters = n_clusters['value']\n", "    else:\n", "        n_clusters = int(n_clusters)\n", "\n", "    X, labels = DATA_MAPPING[dataset](n_clusters)\n", "    model = MODEL_MAPPING[clustering_algorithm](X, labels, n_clusters=n_clusters)\n", "    if hasattr(model, \"labels_\"):\n", "        y_pred = model.labels_.astype(int)\n", "    else:\n", "        y_pred = model.predict(X)\n", "\n", "    fig, ax = plt.subplots(figsize=FIGSIZE)\n", "\n", "    plot_clusters(ax, X, y_pred)\n", "    ax.set_title(clustering_algorithm, fontsize=16)\n", "\n", "    return fig\n", "\n", "\n", "title = \"Clustering with Scikit-learn\"\n", "description = (\n", "    \"This example shows how different clustering algorithms work. Simply pick \"\n", "    \"the dataset and the number of clusters to see how the clustering algorithms work. \"\n", "    \"Colored cirles are (predicted) labels and black x are outliers.\"\n", ")\n", "\n", "\n", "def iter_grid(n_rows, n_cols):\n", "    # create a grid using gradio Block\n", "    for _ in range(n_rows):\n", "        with gr.Row():\n", "            for _ in range(n_cols):\n", "                with gr.Column():\n", "                    yield\n", "\n", "with gr.Blocks(title=title) as demo:\n", "    gr.HTML(f\"<b>{title}</b>\")\n", "    gr.Markdown(description)\n", "\n", "    input_models = list(MODEL_MAPPING)\n", "    input_data = gr.Radio(\n", "        list(DATA_MAPPING),\n", "        value=\"regular\",\n", "        label=\"dataset\"\n", "    )\n", "    input_n_clusters = gr.Slider(\n", "        minimum=1,\n", "        maximum=MAX_CLUSTERS,\n", "        value=4,\n", "        step=1,\n", "        label='Number of clusters'\n", "    )\n", "    n_rows = int(math.ceil(len(input_models) / N_COLS))\n", "    counter = 0\n", "    for _ in iter_grid(n_rows, N_COLS):\n", "        if counter >= len(input_models):\n", "            break\n", "\n", "        input_model = input_models[counter]\n", "        plot = gr.Plot(label=input_model)\n", "        fn = partial(cluster, clustering_algorithm=input_model)\n", "        input_data.change(fn=fn, inputs=[input_data, input_n_clusters], outputs=plot)\n", "        input_n_clusters.change(fn=fn, inputs=[input_data, input_n_clusters], outputs=plot)\n", "        counter += 1\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/color_generator/run.ipynb b/demo/color_generator/run.ipynb
new file mode 100644
index 0000000000..03faf48d55
--- /dev/null
+++ b/demo/color_generator/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: color_generator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio opencv-python numpy"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import cv2\n", "import numpy as np\n", "import random\n", "\n", "\n", "# Convert decimal color to hexadecimal color\n", "def RGB_to_Hex(rgb):\n", "    color = \"#\"\n", "    for i in rgb:\n", "        num = int(i)\n", "        color += str(hex(num))[-2:].replace(\"x\", \"0\").upper()\n", "    return color\n", "\n", "\n", "# Randomly generate light or dark colors\n", "def random_color(is_light=True):\n", "    return (\n", "        random.randint(0, 127) + int(is_light) * 128,\n", "        random.randint(0, 127) + int(is_light) * 128,\n", "        random.randint(0, 127) + int(is_light) * 128,\n", "    )\n", "\n", "\n", "def switch_color(color_style):\n", "    if color_style == \"light\":\n", "        is_light = True\n", "    elif color_style == \"dark\":\n", "        is_light = False\n", "    back_color_ = random_color(is_light)  # Randomly generate colors\n", "    back_color = RGB_to_Hex(back_color_)  # Convert to hexadecimal\n", "\n", "    # Draw color pictures.\n", "    w, h = 50, 50\n", "    img = np.zeros((h, w, 3), np.uint8)\n", "    cv2.rectangle(img, (0, 0), (w, h), back_color_, thickness=-1)\n", "\n", "    return back_color, back_color, img\n", "\n", "\n", "inputs = [gr.Radio([\"light\", \"dark\"], value=\"light\")]\n", "\n", "outputs = [\n", "    gr.ColorPicker(label=\"color\"),\n", "    gr.Textbox(label=\"hexadecimal color\"),\n", "    gr.Image(type=\"numpy\", label=\"color picture\"),\n", "]\n", "\n", "title = \"Color Generator\"\n", "description = (\n", "    \"Click the Submit button, and a dark or light color will be randomly generated.\"\n", ")\n", "\n", "demo = gr.Interface(\n", "    fn=switch_color,\n", "    inputs=inputs,\n", "    outputs=outputs,\n", "    title=title,\n", "    description=description,\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/color_picker/run.ipynb b/demo/color_picker/run.ipynb
new file mode 100644
index 0000000000..eb0c1ebcc9
--- /dev/null
+++ b/demo/color_picker/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: color_picker"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio Pillow"]}, {"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/color_picker/rabbit.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import os\n", "from PIL import Image, ImageColor\n", "\n", "\n", "def change_color(icon, color):\n", "\n", "    \"\"\"\n", "    Function that given an icon in .png format changes its color\n", "    Args:\n", "        icon: Icon whose color needs to be changed.\n", "        color: Chosen color with which to edit the input icon.\n", "    Returns:\n", "        edited_image: Edited icon.\n", "    \"\"\"\n", "    img = icon.convert(\"LA\")\n", "    img = img.convert(\"RGBA\")\n", "    image_np = np.array(icon)\n", "    _, _, _, alpha = image_np.T\n", "    mask = alpha > 0\n", "    image_np[..., :-1][mask.T] = ImageColor.getcolor(color, \"RGB\")\n", "    edited_image = Image.fromarray(image_np)\n", "    return edited_image\n", "\n", "\n", "inputs = [\n", "    gr.Image(label=\"icon\", type=\"pil\", image_mode=\"RGBA\"),\n", "    gr.ColorPicker(label=\"color\"),\n", "]\n", "outputs = gr.Image(label=\"colored icon\")\n", "\n", "demo = gr.Interface(\n", "    fn=change_color,\n", "    inputs=inputs,\n", "    outputs=outputs,\n", "    examples=[\n", "        [os.path.join(os.path.abspath(''), \"rabbit.png\"), \"#ff0000\"],\n", "        [os.path.join(os.path.abspath(''), \"rabbit.png\"), \"#0000FF\"],\n", "    ],\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/colorpicker_component/run.ipynb b/demo/colorpicker_component/run.ipynb
new file mode 100644
index 0000000000..349861e937
--- /dev/null
+++ b/demo/colorpicker_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: colorpicker_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", "    gr.ColorPicker()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/concurrency_with_queue/run.ipynb b/demo/concurrency_with_queue/run.ipynb
new file mode 100644
index 0000000000..2b7e0c7aa5
--- /dev/null
+++ b/demo/concurrency_with_queue/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: concurrency_with_queue"]}, {"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", "\n", "\n", "def say_hello(name):\n", "  time.sleep(5)\n", "  return f\"Hello {name}!\"\n", "\n", "\n", "with gr.Blocks() as demo:\n", "  inp = gr.Textbox()\n", "  outp = gr.Textbox()\n", "  button = gr.Button()\n", "  button.click(say_hello, inp, outp)\n", "\n", "  demo.queue(concurrency_count=41).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/concurrency_without_queue/run.ipynb b/demo/concurrency_without_queue/run.ipynb
new file mode 100644
index 0000000000..70f6cf54dd
--- /dev/null
+++ b/demo/concurrency_without_queue/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: concurrency_without_queue"]}, {"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", "\n", "\n", "def say_hello(name):\n", "  time.sleep(5)\n", "  return f\"Hello {name}!\"\n", "\n", "\n", "with gr.Blocks() as demo:\n", "  inp = gr.Textbox()\n", "  outp = gr.Textbox()\n", "  button = gr.Button()\n", "  button.click(say_hello, inp, outp)\n", "\n", "  demo.launch(max_threads=41)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/count_generator/run.ipynb b/demo/count_generator/run.ipynb
new file mode 100644
index 0000000000..d38f568778
--- /dev/null
+++ b/demo/count_generator/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: count_generator"]}, {"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", "\n", "def count(n):\n", "    for i in range(int(n)):\n", "        time.sleep(0.5)\n", "        yield i\n", "\n", "def show(n):\n", "    return str(list(range(int(n))))\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Column():\n", "        num = gr.Number(value=10)\n", "        with gr.Row():\n", "            count_btn = gr.Button(\"Count\")\n", "            list_btn = gr.Button(\"List\")\n", "    with gr.Column():\n", "        out = gr.Textbox()\n", "    \n", "    count_btn.click(count, num, out)\n", "    list_btn.click(show, num, out)\n", "    \n", "demo.queue()\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/dashboard/run.ipynb b/demo/dashboard/run.ipynb
new file mode 100644
index 0000000000..0d8670bc31
--- /dev/null
+++ b/demo/dashboard/run.ipynb
@@ -0,0 +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
diff --git a/demo/dataframe_component/run.ipynb b/demo/dataframe_component/run.ipynb
new file mode 100644
index 0000000000..f0a4d750f3
--- /dev/null
+++ b/demo/dataframe_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataframe_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", "    gr.Dataframe(interactive=True)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/dataframe_datatype/run.ipynb b/demo/dataframe_datatype/run.ipynb
new file mode 100644
index 0000000000..6612fda6b6
--- /dev/null
+++ b/demo/dataframe_datatype/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataframe_datatype"]}, {"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", "import numpy as np\n", "\n", "\n", "def make_dataframe(n_periods):\n", "    return pd.DataFrame({\"date_1\": pd.date_range(\"2021-01-01\", periods=n_periods),\n", "                         \"date_2\": pd.date_range(\"2022-02-15\", periods=n_periods).strftime('%B %d, %Y, %r'),\n", "                         \"number\": np.random.random(n_periods).astype(np.float64),\n", "                         \"number_2\": np.random.randint(0, 100, n_periods).astype(np.int32),\n", "                         \"bool\": [True] * n_periods,\n", "                         \"markdown\": [\"# Hello\"] * n_periods})\n", "\n", "\n", "demo = gr.Interface(make_dataframe,\n", "             gr.Number(precision=0),\n", "             gr.Dataframe(datatype=[\"date\", \"date\", \"number\", \"number\", \"bool\", \"markdown\"]))\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/depth_estimation/run.ipynb b/demo/depth_estimation/run.ipynb
new file mode 100644
index 0000000000..40b6a81fa4
--- /dev/null
+++ b/demo/depth_estimation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: depth_estimation\n", "### A demo for predicting the depth of an image and generating a 3D model of it.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch git+https://github.com/nielsrogge/transformers.git@add_dpt_redesign#egg=transformers numpy Pillow jinja2 open3d"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('examples')\n", "!wget -q -O examples/1-jonathan-borba-CgWTqYxHEkg-unsplash.jpg https://github.com/gradio-app/gradio/raw/main/demo/depth_estimation/examples/1-jonathan-borba-CgWTqYxHEkg-unsplash.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/depth_estimation/packages.txt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import DPTFeatureExtractor, DPTForDepthEstimation\n", "import torch\n", "import numpy as np\n", "from PIL import Image\n", "import open3d as o3d\n", "from pathlib import Path\n", "import os\n", "\n", "feature_extractor = DPTFeatureExtractor.from_pretrained(\"Intel/dpt-large\")\n", "model = DPTForDepthEstimation.from_pretrained(\"Intel/dpt-large\")\n", "\n", "def process_image(image_path):\n", "    image_path = Path(image_path)\n", "    image_raw = Image.open(image_path)\n", "    image = image_raw.resize(\n", "        (800, int(800 * image_raw.size[1] / image_raw.size[0])),\n", "        Image.Resampling.LANCZOS)\n", "\n", "    # prepare image for the model\n", "    encoding = feature_extractor(image, return_tensors=\"pt\")\n", "\n", "    # forward pass\n", "    with torch.no_grad():\n", "        outputs = model(**encoding)\n", "        predicted_depth = outputs.predicted_depth\n", "\n", "    # interpolate to original size\n", "    prediction = torch.nn.functional.interpolate(\n", "        predicted_depth.unsqueeze(1),\n", "        size=image.size[::-1],\n", "        mode=\"bicubic\",\n", "        align_corners=False,\n", "    ).squeeze()\n", "    output = prediction.cpu().numpy()\n", "    depth_image = (output * 255 / np.max(output)).astype('uint8')\n", "    try:\n", "        gltf_path = create_3d_obj(np.array(image), depth_image, image_path)\n", "        img = Image.fromarray(depth_image)\n", "        return [img, gltf_path, gltf_path]\n", "    except Exception as e:\n", "        gltf_path = create_3d_obj(\n", "            np.array(image), depth_image, image_path, depth=8)\n", "        img = Image.fromarray(depth_image)\n", "        return [img, gltf_path, gltf_path]\n", "    except:\n", "        print(\"Error reconstructing 3D model\")\n", "        raise Exception(\"Error reconstructing 3D model\")\n", "\n", "\n", "def create_3d_obj(rgb_image, depth_image, image_path, depth=10):\n", "    depth_o3d = o3d.geometry.Image(depth_image)\n", "    image_o3d = o3d.geometry.Image(rgb_image)\n", "    rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(\n", "        image_o3d, depth_o3d, convert_rgb_to_intensity=False)\n", "    w = int(depth_image.shape[1])\n", "    h = int(depth_image.shape[0])\n", "\n", "    camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()\n", "    camera_intrinsic.set_intrinsics(w, h, 500, 500, w/2, h/2)\n", "\n", "    pcd = o3d.geometry.PointCloud.create_from_rgbd_image(\n", "        rgbd_image, camera_intrinsic)\n", "\n", "    print('normals')\n", "    pcd.normals = o3d.utility.Vector3dVector(\n", "        np.zeros((1, 3)))  # invalidate existing normals\n", "    pcd.estimate_normals(\n", "        search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=30))\n", "    pcd.orient_normals_towards_camera_location(\n", "        camera_location=np.array([0., 0., 1000.]))\n", "    pcd.transform([[1, 0, 0, 0],\n", "                   [0, -1, 0, 0],\n", "                   [0, 0, -1, 0],\n", "                   [0, 0, 0, 1]])\n", "    pcd.transform([[-1, 0, 0, 0],\n", "                   [0, 1, 0, 0],\n", "                   [0, 0, 1, 0],\n", "                   [0, 0, 0, 1]])\n", "\n", "    print('run Poisson surface reconstruction')\n", "    with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:\n", "        mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(\n", "            pcd, depth=depth, width=0, scale=1.1, linear_fit=True)\n", "\n", "    voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 256\n", "    print(f'voxel_size = {voxel_size:e}')\n", "    mesh = mesh_raw.simplify_vertex_clustering(\n", "        voxel_size=voxel_size,\n", "        contraction=o3d.geometry.SimplificationContraction.Average)\n", "\n", "    # vertices_to_remove = densities < np.quantile(densities, 0.001)\n", "    # mesh.remove_vertices_by_mask(vertices_to_remove)\n", "    bbox = pcd.get_axis_aligned_bounding_box()\n", "    mesh_crop = mesh.crop(bbox)\n", "    gltf_path = f'./{image_path.stem}.gltf'\n", "    o3d.io.write_triangle_mesh(\n", "        gltf_path, mesh_crop, write_triangle_uvs=True)\n", "    return gltf_path\n", "\n", "title = \"Demo: zero-shot depth estimation with DPT + 3D Point Cloud\"\n", "description = \"This demo is a variation from the original <a href='https://huggingface.co/spaces/nielsr/dpt-depth-estimation' target='_blank'>DPT Demo</a>. It uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object.\"\n", "examples = [[\"examples/1-jonathan-borba-CgWTqYxHEkg-unsplash.jpg\"]]\n", "\n", "iface = gr.Interface(fn=process_image,\n", "                     inputs=[gr.Image(\n", "                         type=\"filepath\", label=\"Input Image\")],\n", "                     outputs=[gr.Image(label=\"predicted depth\", type=\"pil\"),\n", "                              gr.Model3D(label=\"3d mesh reconstruction\", clear_color=[\n", "                                                 1.0, 1.0, 1.0, 1.0]),\n", "                              gr.File(label=\"3d gLTF\")],\n", "                     title=title,\n", "                     description=description,\n", "                     examples=examples,\n", "                     allow_flagging=\"never\",\n", "                     cache_examples=False)\n", "\n", "iface.launch(debug=True, enable_queue=False)"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/diff_texts/run.ipynb b/demo/diff_texts/run.ipynb
new file mode 100644
index 0000000000..2e4c197a3b
--- /dev/null
+++ b/demo/diff_texts/run.ipynb
@@ -0,0 +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=\"Initial text\",\n", "            lines=3,\n", "            value=\"The quick brown fox jumped over the lazy dogs.\",\n", "        ),\n", "        gr.Textbox(\n", "            label=\"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", "    ).style(color_map={\"+\": \"red\", \"-\": \"green\"}),\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/digit_classifier/run.ipynb b/demo/digit_classifier/run.ipynb
new file mode 100644
index 0000000000..71c09fcfb0
--- /dev/null
+++ b/demo/digit_classifier/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: digit_classifier"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tensorflow"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import os\n", "from urllib.request import urlretrieve\n", "\n", "import tensorflow as tf\n", "\n", "import gradio\n", "import gradio as gr\n", "\n", "urlretrieve(\n", "    \"https://gr-models.s3-us-west-2.amazonaws.com/mnist-model.h5\", \"mnist-model.h5\"\n", ")\n", "model = tf.keras.models.load_model(\"mnist-model.h5\")\n", "\n", "\n", "def recognize_digit(image):\n", "    image = image.reshape(1, -1)\n", "    prediction = model.predict(image).tolist()[0]\n", "    return {str(i): prediction[i] for i in range(10)}\n", "\n", "\n", "im = gradio.Image(shape=(28, 28), image_mode=\"L\", invert_colors=False, source=\"canvas\")\n", "\n", "demo = gr.Interface(\n", "    recognize_digit,\n", "    im,\n", "    gradio.Label(num_top_classes=3),\n", "    live=True,\n", "    interpretation=\"default\",\n", "    capture_session=True,\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/dropdown_component/run.ipynb b/demo/dropdown_component/run.ipynb
new file mode 100644
index 0000000000..ba98c10620
--- /dev/null
+++ b/demo/dropdown_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dropdown_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", "    gr.Dropdown(choices=[\"First Choice\", \"Second Choice\", \"Third Choice\"])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/english_translator/run.ipynb b/demo/english_translator/run.ipynb
new file mode 100644
index 0000000000..e8dde5b1e0
--- /dev/null
+++ b/demo/english_translator/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: english_translator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from transformers import pipeline\n", "\n", "pipe = pipeline(\"translation\", model=\"t5-base\")\n", "\n", "\n", "def translate(text):\n", "    return pipe(text)[0][\"translation_text\"]\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            english = gr.Textbox(label=\"English text\")\n", "            translate_btn = gr.Button(value=\"Translate\")\n", "        with gr.Column():\n", "            german = gr.Textbox(label=\"German Text\")\n", "\n", "    translate_btn.click(translate, inputs=english, outputs=german, api_name=\"translate-to-german\")\n", "    examples = gr.Examples(examples=[\"I went to the supermarket yesterday.\", \"Helen is a good swimmer.\"],\n", "                           inputs=[english])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/fake_diffusion/run.ipynb b/demo/fake_diffusion/run.ipynb
new file mode 100644
index 0000000000..bc6a450a15
--- /dev/null
+++ b/demo/fake_diffusion/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_diffusion\n", "### 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.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import time\n", "\n", "# define core fn, which returns a generator {steps} times before returning the image\n", "def fake_diffusion(steps):\n", "    for _ in range(steps):\n", "        time.sleep(1)\n", "        image = np.random.random((600, 600, 3))\n", "        yield image\n", "\n", "    image = \"https://i.picsum.photos/id/867/600/600.jpg?hmac=qE7QFJwLmlE_WKI7zMH6SgH5iY5fx8ec6ZJQBwKRT44\" \n", "    yield image\n", "\n", "demo = gr.Interface(fake_diffusion, \n", "                    inputs=gr.Slider(1, 10, 3), \n", "                    outputs=\"image\")\n", "\n", "# define queue - required for generators\n", "demo.queue()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/fake_diffusion_with_gif/run.ipynb b/demo/fake_diffusion_with_gif/run.ipynb
new file mode 100644
index 0000000000..5a87244613
--- /dev/null
+++ b/demo/fake_diffusion_with_gif/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_diffusion_with_gif"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/fake_diffusion_with_gif/image.gif"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import time\n", "import os\n", "from PIL import Image\n", "import requests\n", "from io import BytesIO\n", "\n", "\n", "def create_gif(images):\n", "    pil_images = []\n", "    for image in images:\n", "        if isinstance(image, str):\n", "            response = requests.get(image)\n", "            image = Image.open(BytesIO(response.content))\n", "        else:\n", "            image = Image.fromarray((image * 255).astype(np.uint8))\n", "        pil_images.append(image)\n", "    fp_out = os.path.join(os.path.abspath(''), \"image.gif\")\n", "    img = pil_images.pop(0)\n", "    img.save(fp=fp_out, format='GIF', append_images=pil_images,\n", "            save_all=True, duration=400, loop=0)\n", "    return fp_out\n", "\n", "\n", "def fake_diffusion(steps):\n", "    images = []\n", "    for _ in range(steps):\n", "        time.sleep(1)\n", "        image = np.random.random((600, 600, 3))\n", "        images.append(image)\n", "        yield image, gr.Image.update(visible=False)\n", "    \n", "    time.sleep(1)\n", "    image = \"https://i.picsum.photos/id/867/600/600.jpg?hmac=qE7QFJwLmlE_WKI7zMH6SgH5iY5fx8ec6ZJQBwKRT44\" \n", "    images.append(image)\n", "    gif_path = create_gif(images)\n", "    \n", "    yield image, gr.Image.update(value=gif_path, visible=True)\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, \n", "                    inputs=gr.Slider(1, 10, 3), \n", "                    outputs=[\"image\", gr.Image(label=\"All Images\", visible=False)])\n", "demo.queue()\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/fake_gan/run.ipynb b/demo/fake_gan/run.ipynb
new file mode 100644
index 0000000000..df2888d32c
--- /dev/null
+++ b/demo/fake_gan/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan"]}, {"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 os\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(grid=[2], 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_2/run.ipynb b/demo/fake_gan_2/run.ipynb
new file mode 100644
index 0000000000..31bf0a7b4e
--- /dev/null
+++ b/demo/fake_gan_2/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan_2"]}, {"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_2/files/cheetah1.jpg\n", "!wget -q -O files/elephant.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan_2/files/elephant.jpg\n", "!wget -q -O files/tiger.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan_2/files/tiger.jpg\n", "!wget -q -O files/zebra.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan_2/files/zebra.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 os\n", "import random\n", "import time\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan(desc):\n", "    if desc == \"NSFW\":\n", "        raise gr.Error(\"NSFW - banned content.\")\n", "    if desc == \"error\":\n", "        raise ValueError(\"error\")\n", "    time.sleep(2)\n", "    image = random.choice(\n", "        [\n", "            \"files/cheetah1.jpg\",\n", "            \"files/elephant.jpg\",\n", "            \"files/tiger.jpg\",\n", "            \"files/zebra.jpg\",\n", "        ]\n", "    )\n", "    return image\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=fake_gan,\n", "    inputs=gr.Textbox(),\n", "    outputs=gr.Image(label=\"Generated Image\"),\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", "demo.queue(max_size=3)\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.ipynb b/demo/fake_gan_no_input/run.ipynb
new file mode 100644
index 0000000000..c13d033587
--- /dev/null
+++ b/demo/fake_gan_no_input/run.ipynb
@@ -0,0 +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": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "import time\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", "    time.sleep(1)\n", "    image = 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", "    )\n", "    return image\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=fake_gan,\n", "    inputs=None,\n", "    outputs=gr.Image(label=\"Generated Image\"),\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/file_component/run.ipynb b/demo/file_component/run.ipynb
new file mode 100644
index 0000000000..02b6ef749b
--- /dev/null
+++ b/demo/file_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: file_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", "    gr.File()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/filter_records/run.ipynb b/demo/filter_records/run.ipynb
new file mode 100644
index 0000000000..d516e909bd
--- /dev/null
+++ b/demo/filter_records/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: filter_records"]}, {"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 filter_records(records, gender):\n", "    return records[records[\"gender\"] == gender]\n", "\n", "\n", "demo = 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", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/fraud_detector/run.ipynb b/demo/fraud_detector/run.ipynb
new file mode 100644
index 0000000000..7682007e47
--- /dev/null
+++ b/demo/fraud_detector/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fraud_detector"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio pandas"]}, {"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/fraud_detector/fraud.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import random\n", "import os\n", "import gradio as gr\n", "\n", "\n", "def fraud_detector(card_activity, categories, sensitivity):\n", "    activity_range = random.randint(0, 100)\n", "    drop_columns = [\n", "        column for column in [\"retail\", \"food\", \"other\"] if column not in categories\n", "    ]\n", "    if len(drop_columns):\n", "        card_activity.drop(columns=drop_columns, inplace=True)\n", "    return (\n", "        card_activity,\n", "        card_activity,\n", "        {\"fraud\": activity_range / 100.0, \"not fraud\": 1 - activity_range / 100.0},\n", "    )\n", "\n", "\n", "demo = gr.Interface(\n", "    fraud_detector,\n", "    [\n", "        gr.Timeseries(x=\"time\", y=[\"retail\", \"food\", \"other\"]),\n", "        gr.CheckboxGroup(\n", "            [\"retail\", \"food\", \"other\"], value=[\"retail\", \"food\", \"other\"]\n", "        ),\n", "        gr.Slider(1, 3),\n", "    ],\n", "    [\n", "        \"dataframe\",\n", "        gr.Timeseries(x=\"time\", y=[\"retail\", \"food\", \"other\"]),\n", "        gr.Label(label=\"Fraud Level\"),\n", "    ],\n", "    examples=[\n", "        [os.path.join(os.path.abspath(''), \"fraud.csv\"), [\"retail\", \"food\", \"other\"], 1.0],\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/gallery_component/run.ipynb b/demo/gallery_component/run.ipynb
new file mode 100644
index 0000000000..d7bd8244ac
--- /dev/null
+++ b/demo/gallery_component/run.ipynb
@@ -0,0 +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://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQeSdQE5kHykTdB970YGSW3AsF6MHHZzY4QiQ&usqp=CAU\",\n", "        \"https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg\",\n", "        \"https://i.natgeofe.com/n/60004bcc-cd85-4401-8bfa-6f96551557db/cheetah-extinction-3_3x4.jpg\",\n", "        \"https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq\"\n", "    ]\n", "    gr.Gallery(value=cheetahs)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/gender_sentence_custom_interpretation/run.ipynb b/demo/gender_sentence_custom_interpretation/run.ipynb
new file mode 100644
index 0000000000..35f32fad88
--- /dev/null
+++ b/demo/gender_sentence_custom_interpretation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gender_sentence_custom_interpretation"]}, {"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 re\n", "\n", "import gradio as gr\n", "\n", "male_words, female_words = [\"he\", \"his\", \"him\"], [\"she\", \"hers\", \"her\"]\n", "\n", "\n", "def gender_of_sentence(sentence):\n", "    male_count = len([word for word in sentence.split() if word.lower() in male_words])\n", "    female_count = len(\n", "        [word for word in sentence.split() if word.lower() in female_words]\n", "    )\n", "    total = max(male_count + female_count, 1)\n", "    return {\"male\": male_count / total, \"female\": female_count / total}\n", "\n", "\n", "# Number of arguments to interpretation function must\n", "# match number of inputs to prediction function\n", "def interpret_gender(sentence):\n", "    result = gender_of_sentence(sentence)\n", "    is_male = result[\"male\"] > result[\"female\"]\n", "    interpretation = []\n", "    for word in re.split(\"( )\", sentence):\n", "        score = 0\n", "        token = word.lower()\n", "        if (is_male and token in male_words) or (not is_male and token in female_words):\n", "            score = 1\n", "        elif (is_male and token in female_words) or (\n", "            not is_male and token in male_words\n", "        ):\n", "            score = -1\n", "        interpretation.append((word, score))\n", "    # Output must be a list of lists containing the same number of elements as inputs\n", "    # Each element corresponds to the interpretation scores for the given input\n", "    return [interpretation]\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=gender_of_sentence,\n", "    inputs=gr.Textbox(value=\"She went to his house to get her keys.\"),\n", "    outputs=\"label\",\n", "    interpretation=interpret_gender,\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/gender_sentence_default_interpretation/run.ipynb b/demo/gender_sentence_default_interpretation/run.ipynb
new file mode 100644
index 0000000000..3e99c9adb6
--- /dev/null
+++ b/demo/gender_sentence_default_interpretation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gender_sentence_default_interpretation"]}, {"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", "male_words, female_words = [\"he\", \"his\", \"him\"], [\"she\", \"hers\", \"her\"]\n", "\n", "\n", "def gender_of_sentence(sentence):\n", "    male_count = len([word for word in sentence.split() if word.lower() in male_words])\n", "    female_count = len(\n", "        [word for word in sentence.split() if word.lower() in female_words]\n", "    )\n", "    total = max(male_count + female_count, 1)\n", "    return {\"male\": male_count / total, \"female\": female_count / total}\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=gender_of_sentence,\n", "    inputs=gr.Textbox(value=\"She went to his house to get her keys.\"),\n", "    outputs=\"label\",\n", "    interpretation=\"default\",\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/generate_english_german/run.ipynb b/demo/generate_english_german/run.ipynb
new file mode 100644
index 0000000000..475e069021
--- /dev/null
+++ b/demo/generate_english_german/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: generate_english_german"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from transformers import pipeline\n", "\n", "english_translator = gr.Blocks.load(name=\"spaces/gradio/english_translator\")\n", "english_generator = pipeline(\"text-generation\", model=\"distilgpt2\")\n", "\n", "\n", "def generate_text(text):\n", "    english_text = english_generator(text)[0][\"generated_text\"]\n", "    german_text = english_translator(english_text)\n", "    return english_text, german_text\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            seed = gr.Text(label=\"Input Phrase\")\n", "        with gr.Column():\n", "            english = gr.Text(label=\"Generated English Text\")\n", "            german = gr.Text(label=\"Generated German Text\")\n", "    btn = gr.Button(\"Generate\")\n", "    btn.click(generate_text, inputs=[seed], outputs=[english, german])\n", "    gr.Examples([\"My name is Clara and I am\"], inputs=[seed])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/generate_notebooks.py b/demo/generate_notebooks.py
new file mode 100644
index 0000000000..de8573a5cb
--- /dev/null
+++ b/demo/generate_notebooks.py
@@ -0,0 +1,75 @@
+import nbformat as nbf
+import os 
+import json
+import random
+
+GRADIO_DEMO_DIR = os.getcwd()
+DEMOS_TO_SKIP = {"all_demos", "reset_components", "custom_path", "kitchen_sink_random"}
+
+demos = os.listdir(GRADIO_DEMO_DIR)
+demos = [demo for demo in demos if demo not in DEMOS_TO_SKIP and os.path.isdir(os.path.join(GRADIO_DEMO_DIR, demo)) and  os.path.exists(os.path.join(GRADIO_DEMO_DIR, demo, "run.py"))]
+
+for demo in demos: 
+    nb = nbf.v4.new_notebook()
+    text = f"# Gradio Demo: {demo}"
+
+    if os.path.exists(os.path.join(GRADIO_DEMO_DIR, demo, "DESCRIPTION.md")):
+        with open(os.path.join(GRADIO_DEMO_DIR, demo, "DESCRIPTION.md"), "r") as f:
+            description = f.read()
+        text += f"""\n### {description}
+        """
+
+    files = os.listdir(os.path.join(GRADIO_DEMO_DIR, demo))
+    skip = ["run.py", "run.ipynb", "setup.sh", ".gitignore", "requirements.txt", "DESCRIPTION.md", "screenshot.png", "screenshot.gif", ".DS_Store", "flagged", "__pycache__"]
+    files = [file for file in files if file not in skip]
+    files.sort()
+    if files: 
+        get_files = "# Downloading files from the demo repo\nimport os"
+        for file in files:
+            if os.path.isdir(os.path.join(GRADIO_DEMO_DIR, demo, file)):
+                get_files += f"\nos.mkdir('{file}')"
+                sub_files = os.listdir(os.path.join(GRADIO_DEMO_DIR, demo, file))
+                sub_files = [sub for sub in sub_files if sub not in skip]
+                sub_files.sort()
+                for sub_file in sub_files:
+                    get_files += f"\n!wget -q -O {file}/{sub_file} https://github.com/gradio-app/gradio/raw/main/demo/{demo}/{file}/{sub_file}"
+            else:
+                get_files += f"\n!wget -q https://github.com/gradio-app/gradio/raw/main/demo/{demo}/{file}"
+
+    requirements = ""
+    if os.path.exists(os.path.join(GRADIO_DEMO_DIR, demo, "requirements.txt")):
+        with open(os.path.join(GRADIO_DEMO_DIR, demo, "requirements.txt"), "r") as f:
+            requirements = f.read().split("\n")
+        requirements = " ".join(requirements)
+
+    installs = f"!pip install -q gradio {requirements}"
+
+    with open(os.path.join(GRADIO_DEMO_DIR, demo, "run.py"), "r") as f:
+        code = f.read()
+        code = code.replace("os.path.dirname(__file__)", "os.path.abspath('')")
+    
+    if files: 
+        nb['cells'] = [nbf.v4.new_markdown_cell(text),
+                    nbf.v4.new_code_cell(installs),
+                    nbf.v4.new_code_cell(get_files),
+                    nbf.v4.new_code_cell(code)]
+    else:
+        nb['cells'] = [nbf.v4.new_markdown_cell(text),
+                nbf.v4.new_code_cell(installs),
+                nbf.v4.new_code_cell(code)]
+    
+    output_notebook = os.path.join(GRADIO_DEMO_DIR, demo, "run.ipynb")
+
+    with open(output_notebook, 'w') as f:
+        nbf.write(nb, f)
+
+    with open(output_notebook, "r") as f:
+        content = f.read()
+    
+    content = json.loads(content)
+    for i, cell in enumerate(content["cells"]):
+        random.seed(i)
+        cell["id"] = random.getrandbits(128)
+
+    with open(output_notebook, "w") as f:
+        f.write(json.dumps(content))
\ No newline at end of file
diff --git a/demo/generate_tone/run.ipynb b/demo/generate_tone/run.ipynb
new file mode 100644
index 0000000000..3676d3d4e6
--- /dev/null
+++ b/demo/generate_tone/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: generate_tone"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import numpy as np\n", "import gradio as gr\n", "\n", "notes = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n", "\n", "def 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", "\n", "demo = 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", ")\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/gif_maker/run.ipynb b/demo/gif_maker/run.ipynb
new file mode 100644
index 0000000000..ca38a56524
--- /dev/null
+++ b/demo/gif_maker/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gif_maker"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio opencv-python"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import cv2\n", "import gradio as gr\n", "\n", "def gif_maker(img_files):\n", "    img_array = []\n", "    for filename in img_files:\n", "        img = cv2.imread(filename.name)\n", "        height, width, _ = img.shape\n", "        size = (width,height)\n", "        img_array.append(img)\n", "    output_file = \"test.mp4\"\n", "    out = cv2.VideoWriter(output_file,cv2.VideoWriter_fourcc(*'h264'), 15, size) \n", "    for i in range(len(img_array)):\n", "        out.write(img_array[i])\n", "    out.release()\n", "    return output_file\n", "\n", "demo = gr.Interface(gif_maker, inputs=gr.File(file_count=\"multiple\"), outputs=gr.Video())\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/gpt_j/run.ipynb b/demo/gpt_j/run.ipynb
new file mode 100644
index 0000000000..06d255f9f3
--- /dev/null
+++ b/demo/gpt_j/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gpt_j"]}, {"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", "title = \"GPT-J-6B\"\n", "\n", "examples = [\n", "    [\"The tower is 324 metres (1,063 ft) tall,\"],\n", "    [\"The Moon's orbit around Earth has\"],\n", "    [\"The smooth Borealis basin in the Northern Hemisphere covers 40%\"],\n", "]\n", "\n", "demo = gr.Interface.load(\n", "    \"huggingface/EleutherAI/gpt-j-6B\",\n", "    inputs=gr.Textbox(lines=5, max_lines=6, label=\"Input Text\"),\n", "    title=title,\n", "    examples=examples,\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/gpt_j_unified/run.ipynb b/demo/gpt_j_unified/run.ipynb
new file mode 100644
index 0000000000..d840f1d52e
--- /dev/null
+++ b/demo/gpt_j_unified/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gpt_j_unified"]}, {"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", "component = gr.Textbox(lines=5, label=\"Text\")\n", "api = gr.Interface.load(\"huggingface/EleutherAI/gpt-j-6B\")\n", "\n", "demo = gr.Interface(\n", "    fn=lambda x: x[:-50] + api(x[-50:]),\n", "    inputs=component,\n", "    outputs=component,\n", "    title=\"GPT-J-6B\",\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/hangman/run.ipynb b/demo/hangman/run.ipynb
new file mode 100644
index 0000000000..83e285c62c
--- /dev/null
+++ b/demo/hangman/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hangman"]}, {"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 random\n", "\n", "secret_word = \"gradio\"\n", "\n", "with gr.Blocks() as demo:    \n", "    used_letters_var = gr.State([])\n", "    with gr.Row() as row:\n", "        with gr.Column():\n", "            input_letter = gr.Textbox(label=\"Enter letter\")\n", "            btn = gr.Button(\"Guess Letter\")\n", "        with gr.Column():\n", "            hangman = gr.Textbox(\n", "                label=\"Hangman\",\n", "                value=\"_\"*len(secret_word)\n", "            )\n", "            used_letters_box = gr.Textbox(label=\"Used Letters\")\n", "\n", "    def guess_letter(letter, used_letters):\n", "        used_letters.append(letter)\n", "        answer = \"\".join([\n", "            (letter if letter in used_letters else \"_\")\n", "            for letter in secret_word\n", "        ])\n", "        return {\n", "            used_letters_var: used_letters,\n", "            used_letters_box: \", \".join(used_letters),\n", "            hangman: answer\n", "        }\n", "    btn.click(\n", "        guess_letter, \n", "        [input_letter, used_letters_var],\n", "        [used_letters_var, used_letters_box, hangman]\n", "        )\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/hello_blocks/run.ipynb b/demo/hello_blocks/run.ipynb
new file mode 100644
index 0000000000..4ac574d068
--- /dev/null
+++ b/demo/hello_blocks/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_blocks"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name):\n", "    return \"Hello \" + name + \"!\"\n", "\n", "with gr.Blocks() as demo:\n", "    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)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/hello_login/run.ipynb b/demo/hello_login/run.ipynb
new file mode 100644
index 0000000000..05ad4e497b
--- /dev/null
+++ b/demo/hello_login/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_login"]}, {"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", "user_db = {\"admin\": \"admin\", \"foo\": \"bar\"}\n", "\n", "\n", "def greet(name):\n", "    return \"Hello \" + name + \"!!\"\n", "\n", "\n", "demo = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\")\n", "if __name__ == \"__main__\":\n", "    demo.launch(enable_queue=False,\n", "        auth=lambda u, p: user_db.get(u) == p,\n", "        auth_message=\"This is a welcome message\")\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/hello_world/run.ipynb b/demo/hello_world/run.ipynb
new file mode 100644
index 0000000000..af20e1c11a
--- /dev/null
+++ b/demo/hello_world/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_world\n", "### The simplest possible Gradio demo. It wraps a 'Hello {name}!' function in an Interface that accepts and returns text.\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", "\n", "def greet(name):\n", "    return \"Hello \" + name + \"!\"\n", "\n", "demo = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\")\n", "    \n", "demo.launch()   "]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/hello_world_2/run.ipynb b/demo/hello_world_2/run.ipynb
new file mode 100644
index 0000000000..b5b5cfc49f
--- /dev/null
+++ b/demo/hello_world_2/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_world_2"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name):\n", "    return \"Hello \" + name + \"!\"\n", "\n", "demo = gr.Interface(\n", "    fn=greet,\n", "    inputs=gr.Textbox(lines=2, placeholder=\"Name Here...\"),\n", "    outputs=\"text\",\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/hello_world_3/run.ipynb b/demo/hello_world_3/run.ipynb
new file mode 100644
index 0000000000..def950c523
--- /dev/null
+++ b/demo/hello_world_3/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_world_3"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name, is_morning, temperature):\n", "    salutation = \"Good morning\" if is_morning else \"Good evening\"\n", "    greeting = f\"{salutation} {name}. It is {temperature} degrees today\"\n", "    celsius = (temperature - 32) * 5 / 9\n", "    return greeting, round(celsius, 2)\n", "\n", "demo = gr.Interface(\n", "    fn=greet,\n", "    inputs=[\"text\", \"checkbox\", gr.Slider(0, 100)],\n", "    outputs=[\"text\", \"number\"],\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/highlightedtext_component/run.ipynb b/demo/highlightedtext_component/run.ipynb
new file mode 100644
index 0000000000..0fdce05824
--- /dev/null
+++ b/demo/highlightedtext_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: highlightedtext_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", "    gr.HighlightedText(value=[(\"Text\",\"Label 1\"),(\"to be\",\"Label 2\"),(\"highlighted\",\"Label 3\")])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/html_component/run.ipynb b/demo/html_component/run.ipynb
new file mode 100644
index 0000000000..72b8759d00
--- /dev/null
+++ b/demo/html_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: html_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", "    gr.HTML(value=\"<p style='margin-top: 1rem, margin-bottom: 1rem'>Gradio Docs Readers: <img src='https://visitor-badge.glitch.me/badge?page_id=gradio-docs-visitor-badge' alt='visitor badge' style='display: inline-block'/></p>\")\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/image_classification/run.ipynb b/demo/image_classification/run.ipynb
new file mode 100644
index 0000000000..792ee745d1
--- /dev/null
+++ b/demo/image_classification/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_classification\n", "### Simple image classification in Pytorch with Gradio's Image input and Label output.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchvision"]}, {"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/image_classification/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "import requests\n", "from torchvision import transforms\n", "\n", "model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval()\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "def predict(inp):\n", "  inp = transforms.ToTensor()(inp).unsqueeze(0)\n", "  with torch.no_grad():\n", "    prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)\n", "    confidences = {labels[i]: float(prediction[i]) for i in range(1000)}    \n", "  return confidences\n", "\n", "demo = gr.Interface(fn=predict, \n", "             inputs=gr.inputs.Image(type=\"pil\"),\n", "             outputs=gr.outputs.Label(num_top_classes=3),\n", "             examples=[[\"cheetah.jpg\"]],\n", "             )\n", "             \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/image_classifier/run.ipynb b/demo/image_classifier/run.ipynb
new file mode 100644
index 0000000000..6d489271b6
--- /dev/null
+++ b/demo/image_classifier/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_classifier"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy tensorflow"]}, {"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/imagenet_labels.json https://github.com/gradio-app/gradio/raw/main/demo/image_classifier/files/imagenet_labels.json\n", "os.mkdir('images')\n", "!wget -q -O images/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_classifier/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_classifier/images/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import requests\n", "import tensorflow as tf\n", "\n", "import gradio as gr\n", "\n", "inception_net = tf.keras.applications.MobileNetV2()  # load the model\n", "\n", "# Download human-readable labels for ImageNet.\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "\n", "def classify_image(inp):\n", "    inp = inp.reshape((-1, 224, 224, 3))\n", "    inp = tf.keras.applications.mobilenet_v2.preprocess_input(inp)\n", "    prediction = inception_net.predict(inp).flatten()\n", "    return {labels[i]: float(prediction[i]) for i in range(1000)}\n", "\n", "\n", "image = gr.Image(shape=(224, 224))\n", "label = gr.Label(num_top_classes=3)\n", "\n", "demo = gr.Interface(\n", "    fn=classify_image,\n", "    inputs=image,\n", "    outputs=label,\n", "    examples=[\n", "        os.path.join(os.path.abspath(''), \"images/cheetah1.jpg\"),\n", "        os.path.join(os.path.abspath(''), \"images/lion.jpg\")\n", "        ]\n", "    )\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/image_classifier_2/run.ipynb b/demo/image_classifier_2/run.ipynb
new file mode 100644
index 0000000000..7598db8e31
--- /dev/null
+++ b/demo/image_classifier_2/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_classifier_2"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio pillow torch torchvision"]}, {"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/imagenet_labels.json https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_2/files/imagenet_labels.json"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import requests\n", "import torch\n", "from PIL import Image\n", "from torchvision import transforms\n", "\n", "import gradio as gr\n", "\n", "model = torch.hub.load(\"pytorch/vision:v0.6.0\", \"resnet18\", pretrained=True).eval()\n", "\n", "# Download human-readable labels for ImageNet.\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "\n", "def predict(inp):\n", "    inp = Image.fromarray(inp.astype(\"uint8\"), \"RGB\")\n", "    inp = transforms.ToTensor()(inp).unsqueeze(0)\n", "    with torch.no_grad():\n", "        prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)\n", "    return {labels[i]: float(prediction[i]) for i in range(1000)}\n", "\n", "\n", "inputs = gr.Image()\n", "outputs = gr.Label(num_top_classes=3)\n", "\n", "demo = gr.Interface(fn=predict, inputs=inputs, outputs=outputs)\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_classifier_interface_load/run.ipynb b/demo/image_classifier_interface_load/run.ipynb
new file mode 100644
index 0000000000..ffdb026b9d
--- /dev/null
+++ b/demo/image_classifier_interface_load/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_classifier_interface_load"]}, {"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/image_classifier_interface_load/cheetah1.jpeg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_interface_load/cheetah1.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_interface_load/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pathlib\n", "\n", "current_dir = pathlib.Path(__file__).parent\n", "\n", "images = [str(current_dir / \"cheetah1.jpeg\"), str(current_dir / \"cheetah1.jpg\"), str(current_dir / \"lion.jpg\")]\n", "\n", "\n", "img_classifier = gr.Interface.load(\n", "    \"models/google/vit-base-patch16-224\", examples=images, cache_examples=False\n", ")\n", "\n", "\n", "def func(img, text):\n", "    return img_classifier(img), text\n", "\n", "\n", "using_img_classifier_as_function = gr.Interface(\n", "    func,\n", "    [gr.Image(type=\"filepath\"), \"text\"],\n", "    [\"label\", \"text\"],\n", "    examples=[\n", "        [str(current_dir / \"cheetah1.jpeg\"), None],\n", "        [str(current_dir / \"cheetah1.jpg\"), \"cheetah\"],\n", "        [str(current_dir / \"lion.jpg\"), \"lion\"],\n", "    ],\n", "    cache_examples=False,\n", ")\n", "demo = gr.TabbedInterface([using_img_classifier_as_function, img_classifier])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/image_classifier_interpretation/run.ipynb b/demo/image_classifier_interpretation/run.ipynb
new file mode 100644
index 0000000000..92fcfcd714
--- /dev/null
+++ b/demo/image_classifier_interpretation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_classifier_interpretation"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy tensorflow"]}, {"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/imagenet_labels.json https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_interpretation/files/imagenet_labels.json\n", "os.mkdir('images')\n", "!wget -q -O images/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_interpretation/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_classifier_interpretation/images/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import requests\n", "import tensorflow as tf\n", "\n", "import gradio as gr\n", "\n", "inception_net = tf.keras.applications.MobileNetV2()  # load the model\n", "\n", "# Download human-readable labels for ImageNet.\n", "response = requests.get(\"https://git.io/JJkYN\")\n", "labels = response.text.split(\"\\n\")\n", "\n", "\n", "def classify_image(inp):\n", "    inp = inp.reshape((-1, 224, 224, 3))\n", "    inp = tf.keras.applications.mobilenet_v2.preprocess_input(inp)\n", "    prediction = inception_net.predict(inp).flatten()\n", "    return {labels[i]: float(prediction[i]) for i in range(1000)}\n", "\n", "\n", "image = gr.Image(shape=(224, 224))\n", "label = gr.Label(num_top_classes=3)\n", "\n", "demo = gr.Interface(\n", "    fn=classify_image, inputs=image, outputs=label, interpretation=\"default\"\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/image_component/run.ipynb b/demo/image_component/run.ipynb
new file mode 100644
index 0000000000..f27b99ee10
--- /dev/null
+++ b/demo/image_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_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", "    gr.Image()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/image_mod/run.ipynb b/demo/image_mod/run.ipynb
new file mode 100644
index 0000000000..63c368f288
--- /dev/null
+++ b/demo/image_mod/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_mod"]}, {"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/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod/images/lion.jpg\n", "!wget -q -O images/logo.png https://github.com/gradio-app/gradio/raw/main/demo/image_mod/images/logo.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "def image_mod(image):\n", "    return image.rotate(45)\n", "\n", "\n", "demo = gr.Interface(image_mod, gr.Image(type=\"pil\"), \"image\",\n", "    flagging_options=[\"blurry\", \"incorrect\", \"other\"], examples=[\n", "        os.path.join(os.path.abspath(''), \"images/cheetah1.jpg\"),\n", "        os.path.join(os.path.abspath(''), \"images/lion.jpg\"),\n", "        os.path.join(os.path.abspath(''), \"images/logo.png\")\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/image_mod_default_image/run.ipynb b/demo/image_mod_default_image/run.ipynb
new file mode 100644
index 0000000000..48d8ee868f
--- /dev/null
+++ b/demo/image_mod_default_image/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_mod_default_image"]}, {"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/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod_default_image/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod_default_image/images/lion.jpg\n", "!wget -q -O images/logo.png https://github.com/gradio-app/gradio/raw/main/demo/image_mod_default_image/images/logo.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "def image_mod(image):\n", "    return image.rotate(45)\n", "\n", "\n", "cheetah = os.path.join(os.path.abspath(''), \"images/cheetah1.jpg\")\n", "\n", "demo = gr.Interface(image_mod, gr.Image(type=\"pil\", value=cheetah), \"image\",\n", "    flagging_options=[\"blurry\", \"incorrect\", \"other\"], examples=[\n", "        os.path.join(os.path.abspath(''), \"images/lion.jpg\"),\n", "        os.path.join(os.path.abspath(''), \"images/logo.png\")\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/image_segmentation/run.ipynb b/demo/image_segmentation/run.ipynb
new file mode 100644
index 0000000000..34367a20e9
--- /dev/null
+++ b/demo/image_segmentation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_segmentation\n", "### Image segmentation using DETR. Takes in both an inputu image and the desired confidence, and returns a segmented image.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers torch scipy numpy"]}, {"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/image_segmentation/example_2.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "import random\n", "import numpy as np\n", "from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation\n", "\n", "device = torch.device(\"cpu\")\n", "model = MaskFormerForInstanceSegmentation.from_pretrained(\"facebook/maskformer-swin-tiny-ade\").to(device)\n", "model.eval()\n", "preprocessor = MaskFormerFeatureExtractor.from_pretrained(\"facebook/maskformer-swin-tiny-ade\")\n", "\n", "def visualize_instance_seg_mask(mask):\n", "    image = np.zeros((mask.shape[0], mask.shape[1], 3))\n", "    labels = np.unique(mask)\n", "    label2color = {label: (random.randint(0, 1), random.randint(0, 255), random.randint(0, 255)) for label in labels}\n", "    for i in range(image.shape[0]):\n", "      for j in range(image.shape[1]):\n", "        image[i, j, :] = label2color[mask[i, j]]\n", "    image = image / 255\n", "    return image\n", "\n", "def query_image(img):\n", "    target_size = (img.shape[0], img.shape[1])\n", "    inputs = preprocessor(images=img, return_tensors=\"pt\")\n", "    with torch.no_grad():\n", "        outputs = model(**inputs)\n", "    outputs.class_queries_logits = outputs.class_queries_logits.cpu()\n", "    outputs.masks_queries_logits = outputs.masks_queries_logits.cpu()\n", "    results = preprocessor.post_process_segmentation(outputs=outputs, target_size=target_size)[0].cpu().detach()\n", "    results = torch.argmax(results, dim=0).numpy()\n", "    results = visualize_instance_seg_mask(results)\n", "    return results\n", "\n", "demo = gr.Interface(\n", "    query_image, \n", "    inputs=[gr.Image()], \n", "    outputs=\"image\",\n", "    title=\"MaskFormer Demo\",\n", "    examples=[[\"example_2.png\"]]\n", ")\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/input_output/run.ipynb b/demo/input_output/run.ipynb
new file mode 100644
index 0000000000..c8e72fcb86
--- /dev/null
+++ b/demo/input_output/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: input_output"]}, {"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 image_mod(text):\n", "    return text[::-1]\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", "    text = gr.Textbox(label=\"Input-Output\")\n", "    btn = gr.Button(\"Run\")\n", "    btn.click(image_mod, text, text)\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/interface_parallel/run.ipynb b/demo/interface_parallel/run.ipynb
new file mode 100644
index 0000000000..b74d27f117
--- /dev/null
+++ b/demo/interface_parallel/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interface_parallel"]}, {"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", "greeter_1 = gr.Interface(lambda name: f\"Hello {name}!\", inputs=\"textbox\", outputs=gr.Textbox(label=\"Greeter 1\"))\n", "greeter_2 = gr.Interface(lambda name: f\"Greetings {name}!\", inputs=\"textbox\", outputs=gr.Textbox(label=\"Greeter 2\"))\n", "demo = gr.Parallel(greeter_1, greeter_2)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/interface_parallel_load/run.ipynb b/demo/interface_parallel_load/run.ipynb
new file mode 100644
index 0000000000..e29e99ca2d
--- /dev/null
+++ b/demo/interface_parallel_load/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interface_parallel_load"]}, {"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", "generator1 = gr.Interface.load(\"huggingface/gpt2\")\n", "generator2 = gr.Interface.load(\"huggingface/EleutherAI/gpt-neo-2.7B\")\n", "generator3 = gr.Interface.load(\"huggingface/EleutherAI/gpt-j-6B\")\n", "\n", "demo = gr.Parallel(generator1, generator2, generator3)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/interface_random_slider/run.ipynb b/demo/interface_random_slider/run.ipynb
new file mode 100644
index 0000000000..79cccb7540
--- /dev/null
+++ b/demo/interface_random_slider/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interface_random_slider"]}, {"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 func(slider_1, slider_2, *args):\n", "    return slider_1 + slider_2 * 5\n", "\n", "\n", "demo = gr.Interface(\n", "    func,\n", "    [\n", "        gr.Slider(minimum=1.5, maximum=250000.89, randomize=True, label=\"Random Big Range\"),\n", "        gr.Slider(minimum=-1, maximum=1, randomize=True, step=0.05, label=\"Random only multiple of 0.05 allowed\"),\n", "        gr.Slider(minimum=0, maximum=1, randomize=True, step=0.25, label=\"Random only multiples of 0.25 allowed\"),\n", "        gr.Slider(minimum=-100, maximum=100, randomize=True, step=3, label=\"Random between -100 and 100 step 3\"),\n", "        gr.Slider(minimum=-100, maximum=100, randomize=True, label=\"Random between -100 and 100\"),\n", "        gr.Slider(value=0.25, minimum=5, maximum=30, step=-1),\n", "    ],\n", "    \"number\",\n", "    interpretation=\"default\"\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/interface_series/run.ipynb b/demo/interface_series/run.ipynb
new file mode 100644
index 0000000000..638bb79eea
--- /dev/null
+++ b/demo/interface_series/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interface_series"]}, {"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", "get_name = gr.Interface(lambda name: name, inputs=\"textbox\", outputs=\"textbox\")\n", "prepend_hello = gr.Interface(lambda name: f\"Hello {name}!\", inputs=\"textbox\", outputs=\"textbox\")\n", "append_nice = gr.Interface(lambda greeting: f\"{greeting} Nice to meet you!\",\n", "                           inputs=\"textbox\", outputs=gr.Textbox(label=\"Greeting\"))\n", "demo = gr.Series(get_name, prepend_hello, append_nice)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/interface_series_load/run.ipynb b/demo/interface_series_load/run.ipynb
new file mode 100644
index 0000000000..bc2df6775b
--- /dev/null
+++ b/demo/interface_series_load/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interface_series_load"]}, {"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", "generator = gr.Interface.load(\"huggingface/gpt2\")\n", "translator = gr.Interface.load(\"huggingface/t5-small\")\n", "\n", "demo = gr.Series(generator, translator)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/json_component/run.ipynb b/demo/json_component/run.ipynb
new file mode 100644
index 0000000000..d465c76d31
--- /dev/null
+++ b/demo/json_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: json_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", "    gr.JSON(value={\"Key 1\": \"Value 1\", \"Key 2\": {\"Key 3\": \"Value 2\", \"Key 4\": \"Value 3\"}, \"Key 5\": [\"Item 1\", \"Item 2\", \"Item 3\"]})\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/kitchen_sink/run.ipynb b/demo/kitchen_sink/run.ipynb
new file mode 100644
index 0000000000..8c6258101f
--- /dev/null
+++ b/demo/kitchen_sink/run.ipynb
@@ -0,0 +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/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/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", "    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", "        \"<button style='background-color: red'>Click Me: \"\n", "        + radio\n", "        + \"</button>\",  # 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", "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(\n", "            label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]\n", "        ),\n", "        gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", "        gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\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", "            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], [3, 4, 5]],\n", "            os.path.join(os.path.abspath(''), \"files/time.csv\"),\n", "        ]\n", "    ]\n", "    * 3,\n", "    theme=\"default\",\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()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/label_component/run.ipynb b/demo/label_component/run.ipynb
new file mode 100644
index 0000000000..0cd6779e9a
--- /dev/null
+++ b/demo/label_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: label_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", "    gr.Label(value={\"First Label\": 0.7, \"Second Label\": 0.2, \"Third Label\": 0.1})\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/leaderboard/run.ipynb b/demo/leaderboard/run.ipynb
new file mode 100644
index 0000000000..b368932998
--- /dev/null
+++ b/demo/leaderboard/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: leaderboard\n", "### A simple dashboard ranking spaces by number of likes.\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 requests\n", "import pandas as pd\n", "from huggingface_hub.hf_api import SpaceInfo\n", "path = f\"https://huggingface.co/api/spaces\"\n", "\n", "\n", "def get_blocks_party_spaces():\n", "    r = requests.get(path)\n", "    d = r.json()\n", "    spaces = [SpaceInfo(**x) for x in d]\n", "    blocks_spaces = {}\n", "    for i in range(0,len(spaces)):\n", "        if spaces[i].id.split('/')[0] == 'Gradio-Blocks' and hasattr(spaces[i], 'likes') and spaces[i].id != 'Gradio-Blocks/Leaderboard' and spaces[i].id != 'Gradio-Blocks/README':\n", "            blocks_spaces[spaces[i].id]=spaces[i].likes\n", "    df = pd.DataFrame(\n", "    [{\"Spaces_Name\": Spaces, \"likes\": likes} for Spaces,likes in blocks_spaces.items()])\n", "    df = df.sort_values(by=['likes'],ascending=False)\n", "    return df\n", "\n", "block = gr.Blocks()\n", "\n", "with block:    \n", "    gr.Markdown(\"\"\"Leaderboard for the most popular Blocks Event Spaces. To learn more and join, see <a href=\"https://huggingface.co/Gradio-Blocks\" target=\"_blank\" style=\"text-decoration: underline\">Blocks Party Event</a>\"\"\")\n", "    with gr.Tabs():\n", "        with gr.TabItem(\"Blocks Party Leaderboard\"):\n", "            with gr.Row():\n", "                data = gr.outputs.Dataframe(type=\"pandas\")\n", "            with gr.Row():\n", "                data_run = gr.Button(\"Refresh\")\n", "                data_run.click(get_blocks_party_spaces, inputs=None, outputs=data)\n", "    # running the function on page load in addition to when the button is clicked\n", "    block.load(get_blocks_party_spaces, inputs=None, outputs=data)               \n", "\n", "block.launch()\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/live_dashboard/run.ipynb b/demo/live_dashboard/run.ipynb
new file mode 100644
index 0000000000..ea5ed9d7fa
--- /dev/null
+++ b/demo/live_dashboard/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: live_dashboard\n", "### This demo shows how you can build a live interactive dashboard with gradio.\n", "The current time is refreshed every second and the plot every half second by using the 'every' keyword in the event handler.\n", "Changing the value of the slider will control the period of the sine curve (the distance between peaks). \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 math\n", "import gradio as gr\n", "import datetime\n", "import plotly.express as px\n", "import numpy as np\n", "import time\n", "\n", "\n", "def get_time():\n", "    return datetime.datetime.now()\n", "\n", "\n", "plot_end = 2 * math.pi\n", "\n", "\n", "def get_plot(period=1):\n", "    global plot_end\n", "    x = np.arange(plot_end - 2 * math.pi, plot_end, 0.02)\n", "    y = np.sin(2 * math.pi * period * x)\n", "    fig = px.line(x=x, y=y)\n", "    plot_end += 2 * math.pi\n", "    return fig\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            c_time2 = gr.Textbox(label=\"Current Time refreshed every second\")\n", "            gr.Textbox(\n", "                \"Change the value of the slider to automatically update the plot\",\n", "                label=\"\",\n", "            )\n", "            period = gr.Slider(\n", "                label=\"Period of plot\", value=1, minimum=0, maximum=10, step=1\n", "            )\n", "            plot = gr.Plot(label=\"Plot (updates every second)\")\n", "        with gr.Column():\n", "            name = gr.Textbox(label=\"Enter your name\")\n", "            greeting = gr.Textbox(label=\"Greeting\")\n", "            button = gr.Button(value=\"Greet\")\n", "            button.click(lambda s: f\"Hello {s}\", name, greeting)\n", "\n", "    demo.load(lambda: datetime.datetime.now(), None, c_time2, every=1)\n", "    dep = demo.load(get_plot, None, plot, every=1)\n", "    period.change(get_plot, period, plot, every=1, cancels=[dep])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.queue().launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/live_with_vars/run.ipynb b/demo/live_with_vars/run.ipynb
new file mode 100644
index 0000000000..46cafe84f6
--- /dev/null
+++ b/demo/live_with_vars/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: live_with_vars"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "demo = gr.Interface(\n", "    lambda x, y: (x + y if y is not None else x, x + y if y is not None else x), \n", "    [\"textbox\", \"state\"], \n", "    [\"textbox\", \"state\"], live=True)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/longest_word/run.ipynb b/demo/longest_word/run.ipynb
new file mode 100644
index 0000000000..70d70f8aa0
--- /dev/null
+++ b/demo/longest_word/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: longest_word"]}, {"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 longest_word(text):\n", "    words = text.split(\" \")\n", "    lengths = [len(word) for word in words]\n", "    return max(lengths)\n", "\n", "\n", "ex = \"The quick brown fox jumped over the lazy dog.\"\n", "\n", "demo = gr.Interface(\n", "    longest_word, \"textbox\", \"label\", interpretation=\"default\", examples=[[ex]]\n", ")\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/main_note/run.ipynb b/demo/main_note/run.ipynb
new file mode 100644
index 0000000000..8fcfc77fe7
--- /dev/null
+++ b/demo/main_note/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: main_note"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio scipy numpy matplotlib"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('audio')\n", "!wget -q -O audio/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/main_note/audio/cantina.wav\n", "!wget -q -O audio/recording1.wav https://github.com/gradio-app/gradio/raw/main/demo/main_note/audio/recording1.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from math import log2, pow\n", "import os\n", "\n", "import numpy as np\n", "from scipy.fftpack import fft\n", "\n", "import gradio as gr\n", "\n", "A4 = 440\n", "C0 = A4 * pow(2, -4.75)\n", "name = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n", "\n", "\n", "def get_pitch(freq):\n", "    h = round(12 * log2(freq / C0))\n", "    n = h % 12\n", "    return name[n]\n", "\n", "\n", "def main_note(audio):\n", "    rate, y = audio\n", "    if len(y.shape) == 2:\n", "        y = y.T[0]\n", "    N = len(y)\n", "    T = 1.0 / rate\n", "    x = np.linspace(0.0, N * T, N)\n", "    yf = fft(y)\n", "    yf2 = 2.0 / N * np.abs(yf[0 : N // 2])\n", "    xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)\n", "\n", "    volume_per_pitch = {}\n", "    total_volume = np.sum(yf2)\n", "    for freq, volume in zip(xf, yf2):\n", "        if freq == 0:\n", "            continue\n", "        pitch = get_pitch(freq)\n", "        if pitch not in volume_per_pitch:\n", "            volume_per_pitch[pitch] = 0\n", "        volume_per_pitch[pitch] += 1.0 * volume / total_volume\n", "    volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}\n", "    return volume_per_pitch\n", "\n", "\n", "demo = gr.Interface(\n", "    main_note,\n", "    gr.Audio(source=\"microphone\"),\n", "    gr.Label(num_top_classes=4),\n", "    examples=[\n", "        [os.path.join(os.path.abspath(''),\"audio/recording1.wav\")],\n", "        [os.path.join(os.path.abspath(''),\"audio/cantina.wav\")],\n", "    ],\n", "    interpretation=\"default\",\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/map_airbnb/run.ipynb b/demo/map_airbnb/run.ipynb
new file mode 100644
index 0000000000..8d3a3836d3
--- /dev/null
+++ b/demo/map_airbnb/run.ipynb
@@ -0,0 +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 pandas as pd\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='<b>Name</b>: %{customdata[0]}<br><b>Price</b>: $%{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
diff --git a/demo/markdown_component/run.ipynb b/demo/markdown_component/run.ipynb
new file mode 100644
index 0000000000..63e5a75cf3
--- /dev/null
+++ b/demo/markdown_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: markdown_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", "    gr.Markdown(value=\"This _example_ was **written** in [Markdown](https://en.wikipedia.org/wiki/Markdown)\\n\")\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/matrix_transpose/run.ipynb b/demo/matrix_transpose/run.ipynb
new file mode 100644
index 0000000000..2db96b42ca
--- /dev/null
+++ b/demo/matrix_transpose/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: matrix_transpose"]}, {"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 numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def transpose(matrix):\n", "    return matrix.T\n", "\n", "\n", "demo = 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", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/model3D/run.ipynb b/demo/model3D/run.ipynb
new file mode 100644
index 0000000000..dbc4c5cf7e
--- /dev/null
+++ b/demo/model3D/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: model3D"]}, {"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/Bunny.obj https://github.com/gradio-app/gradio/raw/main/demo/model3D/files/Bunny.obj\n", "!wget -q -O files/Duck.glb https://github.com/gradio-app/gradio/raw/main/demo/model3D/files/Duck.glb\n", "!wget -q -O files/Fox.gltf https://github.com/gradio-app/gradio/raw/main/demo/model3D/files/Fox.gltf\n", "!wget -q -O files/face.obj https://github.com/gradio-app/gradio/raw/main/demo/model3D/files/face.obj\n", "!wget -q -O files/source.txt https://github.com/gradio-app/gradio/raw/main/demo/model3D/files/source.txt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "def load_mesh(mesh_file_name):\n", "    return mesh_file_name, mesh_file_name\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=load_mesh,\n", "    inputs=gr.Model3D(),\n", "    outputs=[\n", "        gr.Model3D(\n", "            clear_color=[0.0, 0.0, 0.0, 0.0],  label=\"3D Model\"),\n", "        gr.File(label=\"Download 3D Model\")\n", "    ],\n", "    examples=[\n", "        [os.path.join(os.path.abspath(''), \"files/Bunny.obj\")],\n", "        [os.path.join(os.path.abspath(''), \"files/Duck.glb\")],\n", "        [os.path.join(os.path.abspath(''), \"files/Fox.gltf\")],\n", "        [os.path.join(os.path.abspath(''), \"files/face.obj\")],\n", "    ],\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/model3d_component/run.ipynb b/demo/model3d_component/run.ipynb
new file mode 100644
index 0000000000..02e07d34f8
--- /dev/null
+++ b/demo/model3d_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: model3d_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", "    gr.Model3D()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/musical_instrument_identification/run.ipynb b/demo/musical_instrument_identification/run.ipynb
new file mode 100644
index 0000000000..7c5fa57919
--- /dev/null
+++ b/demo/musical_instrument_identification/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: musical_instrument_identification\n", "### This demo identifies musical instruments from an audio file. It uses Gradio's Audio and Label components.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch==1.12.0 torchvision==0.13.0 torchaudio==0.12.0 librosa==0.9.2 gdown"]}, {"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/musical_instrument_identification/data_setups.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch, torchaudio\n", "from timeit import default_timer as timer\n", "from data_setups import audio_preprocess, resample\n", "import gdown\n", "\n", "url = 'https://drive.google.com/uc?id=1X5CR18u0I-ZOi_8P0cNptCe5JGk9Ro0C'\n", "output = 'piano.wav'\n", "gdown.download(url, output, quiet=False)\n", "url = 'https://drive.google.com/uc?id=1W-8HwmGR5SiyDbUcGAZYYDKdCIst07__'\n", "output= 'torch_efficientnet_fold2_CNN.pth'\n", "gdown.download(url, output, quiet=False)\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "SAMPLE_RATE = 44100\n", "AUDIO_LEN = 2.90\n", "model = torch.load(\"torch_efficientnet_fold2_CNN.pth\", map_location=torch.device('cpu'))\n", "LABELS = [\n", "    \"Cello\", \"Clarinet\", \"Flute\", \"Acoustic Guitar\", \"Electric Guitar\", \"Organ\", \"Piano\", \"Saxophone\", \"Trumpet\", \"Violin\", \"Voice\"\n", "]\n", "example_list = [\n", "    [\"piano.wav\"]\n", "]\n", "\n", "\n", "def predict(audio_path):\n", "    start_time = timer()\n", "    wavform, sample_rate = torchaudio.load(audio_path)\n", "    wav = resample(wavform, sample_rate, SAMPLE_RATE)\n", "    if len(wav) > int(AUDIO_LEN * SAMPLE_RATE):\n", "        wav = wav[:int(AUDIO_LEN * SAMPLE_RATE)]\n", "    else:\n", "        print(f\"input length {len(wav)} too small!, need over {int(AUDIO_LEN * SAMPLE_RATE)}\")\n", "        return\n", "    img = audio_preprocess(wav, SAMPLE_RATE).unsqueeze(0)\n", "    model.eval()\n", "    with torch.inference_mode():\n", "        pred_probs = torch.softmax(model(img), dim=1)\n", "    pred_labels_and_probs = {LABELS[i]: float(pred_probs[0][i]) for i in range(len(LABELS))}\n", "    pred_time = round(timer() - start_time, 5)\n", "    return pred_labels_and_probs, pred_time\n", "\n", "demo = gr.Interface(fn=predict,\n", "                    inputs=gr.Audio(type=\"filepath\"),\n", "                    outputs=[gr.Label(num_top_classes=11, label=\"Predictions\"), \n", "                             gr.Number(label=\"Prediction time (s)\")],\n", "                    examples=example_list,\n", "                    cache_examples=False\n", "                    )\n", "\n", "demo.launch(debug=False)"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/neon-tts-plugin-coqui/run.ipynb b/demo/neon-tts-plugin-coqui/run.ipynb
new file mode 100644
index 0000000000..9ae70bf87b
--- /dev/null
+++ b/demo/neon-tts-plugin-coqui/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: neon-tts-plugin-coqui\n", "### This  demo converts text to speech in 14 languages.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio neon-tts-plugin-coqui==0.4.1a9"]}, {"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/neon-tts-plugin-coqui/packages.txt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import tempfile\n", "import gradio as gr\n", "from neon_tts_plugin_coqui import CoquiTTS\n", "\n", "LANGUAGES = list(CoquiTTS.langs.keys())\n", "coquiTTS = CoquiTTS()\n", "\n", "def tts(text: str, language: str):\n", "    with tempfile.NamedTemporaryFile(suffix=\".wav\", delete=False) as fp:\n", "        coquiTTS.get_tts(text, fp, speaker = {\"language\" : language})\n", "        return fp.name\n", "\n", "inputs = [gr.Textbox(label=\"Input\", value=CoquiTTS.langs[\"en\"][\"sentence\"], max_lines=3), \n", "            gr.Radio(label=\"Language\", choices=LANGUAGES, value=\"en\")]\n", "outputs = gr.Audio(label=\"Output\")\n", "\n", "demo = gr.Interface(fn=tts, inputs=inputs, outputs=outputs)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/ner_pipeline/run.ipynb b/demo/ner_pipeline/run.ipynb
new file mode 100644
index 0000000000..f9933e1f4b
--- /dev/null
+++ b/demo/ner_pipeline/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: ner_pipeline"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch transformers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from transformers import pipeline\n", "\n", "import gradio as gr\n", "\n", "ner_pipeline = pipeline(\"ner\")\n", "\n", "examples = [\n", "    \"Does Chicago have any stores and does Joe live here?\",\n", "]\n", "\n", "def ner(text):\n", "    output = ner_pipeline(text)\n", "    return {\"text\": text, \"entities\": output}    \n", "\n", "demo = gr.Interface(ner,\n", "             gr.Textbox(placeholder=\"Enter sentence here...\"), \n", "             gr.HighlightedText(),\n", "             examples=examples)\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/no_input/run.ipynb b/demo/no_input/run.ipynb
new file mode 100644
index 0000000000..6322b6c05a
--- /dev/null
+++ b/demo/no_input/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: 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 gradio as gr\n", "import random\n", "\n", "sentence_list = [\n", "    \"Good morning!\",\n", "    \"Prayers are with you, have a safe day!\",\n", "    \"I love you!\"\n", "]\n", "\n", "\n", "def random_sentence():\n", "    return sentence_list[random.randint(0, 2)]\n", "\n", "\n", "demo = gr.Interface(fn=random_sentence, inputs=None, outputs=\"text\")\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/number_component/run.ipynb b/demo/number_component/run.ipynb
new file mode 100644
index 0000000000..a894d597d5
--- /dev/null
+++ b/demo/number_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: number_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", "    gr.Number()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/outbreak_forecast/run.ipynb b/demo/outbreak_forecast/run.ipynb
new file mode 100644
index 0000000000..41e991d6d3
--- /dev/null
+++ b/demo/outbreak_forecast/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: outbreak_forecast\n", "### Generate a plot based on 5 inputs.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy matplotlib bokeh plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from math import sqrt\n", "import matplotlib\n", "\n", "matplotlib.use(\"Agg\")\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import plotly.express as px\n", "import pandas as pd\n", "\n", "\n", "def outbreak(plot_type, r, month, countries, social_distancing):\n", "    months = [\"January\", \"February\", \"March\", \"April\", \"May\"]\n", "    m = months.index(month)\n", "    start_day = 30 * m\n", "    final_day = 30 * (m + 1)\n", "    x = np.arange(start_day, final_day + 1)\n", "    pop_count = {\"USA\": 350, \"Canada\": 40, \"Mexico\": 300, \"UK\": 120}\n", "    if social_distancing:\n", "        r = sqrt(r)\n", "    df = pd.DataFrame({\"day\": x})\n", "    for country in countries:\n", "        df[country] = x ** (r) * (pop_count[country] + 1)\n", "\n", "    if plot_type == \"Matplotlib\":\n", "        fig = plt.figure()\n", "        plt.plot(df[\"day\"], df[countries].to_numpy())\n", "        plt.title(\"Outbreak in \" + month)\n", "        plt.ylabel(\"Cases\")\n", "        plt.xlabel(\"Days since Day 0\")\n", "        plt.legend(countries)\n", "        return fig\n", "    elif plot_type == \"Plotly\":\n", "        fig = px.line(df, x=\"day\", y=countries)\n", "        fig.update_layout(\n", "            title=\"Outbreak in \" + month,\n", "            xaxis_title=\"Cases\",\n", "            yaxis_title=\"Days Since Day 0\",\n", "        )\n", "        return fig\n", "    else:\n", "        raise ValueError(\"A plot type must be selected\")\n", "\n", "\n", "inputs = [\n", "    gr.Dropdown([\"Matplotlib\", \"Plotly\"], label=\"Plot Type\"),\n", "    gr.Slider(1, 4, 3.2, label=\"R\"),\n", "    gr.Dropdown([\"January\", \"February\", \"March\", \"April\", \"May\"], label=\"Month\"),\n", "    gr.CheckboxGroup(\n", "        [\"USA\", \"Canada\", \"Mexico\", \"UK\"], label=\"Countries\", value=[\"USA\", \"Canada\"]\n", "    ),\n", "    gr.Checkbox(label=\"Social Distancing?\"),\n", "]\n", "outputs = gr.Plot()\n", "\n", "demo = gr.Interface(\n", "    fn=outbreak,\n", "    inputs=inputs,\n", "    outputs=outputs,\n", "    examples=[\n", "        [\"Matplotlib\", 2, \"March\", [\"Mexico\", \"UK\"], True],\n", "        [\"Plotly\", 3.6, \"February\", [\"Canada\", \"Mexico\", \"UK\"], False],\n", "    ],\n", "    cache_examples=True,\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/pictionary/run.ipynb b/demo/pictionary/run.ipynb
new file mode 100644
index 0000000000..d60ddbeb5f
--- /dev/null
+++ b/demo/pictionary/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: pictionary"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch gdown"]}, {"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/pictionary/class_names.txt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from pathlib import Path\n", "\n", "import torch\n", "import gradio as gr\n", "from torch import nn\n", "import gdown \n", "\n", "url = 'https://drive.google.com/uc?id=1dsk2JNZLRDjC-0J4wIQX_FcVurPaXaAZ'\n", "output = 'pytorch_model.bin'\n", "gdown.download(url, output, quiet=False)\n", "\n", "LABELS = Path('class_names.txt').read_text().splitlines()\n", "\n", "model = nn.Sequential(\n", "    nn.Conv2d(1, 32, 3, padding='same'),\n", "    nn.ReLU(),\n", "    nn.MaxPool2d(2),\n", "    nn.Conv2d(32, 64, 3, padding='same'),\n", "    nn.ReLU(),\n", "    nn.MaxPool2d(2),\n", "    nn.Conv2d(64, 128, 3, padding='same'),\n", "    nn.ReLU(),\n", "    nn.MaxPool2d(2),\n", "    nn.Flatten(),\n", "    nn.Linear(1152, 256),\n", "    nn.ReLU(),\n", "    nn.Linear(256, len(LABELS)),\n", ")\n", "state_dict = torch.load('pytorch_model.bin', map_location='cpu')\n", "model.load_state_dict(state_dict, strict=False)\n", "model.eval()\n", "\n", "def predict(input):\n", "    im = input\n", "    if im is None:\n", "        return None\n", "        \n", "    x = torch.tensor(im, dtype=torch.float32).unsqueeze(0).unsqueeze(0) / 255.\n", "\n", "    with torch.no_grad():\n", "        out = model(x)\n", "\n", "    probabilities = torch.nn.functional.softmax(out[0], dim=0)\n", "\n", "    values, indices = torch.topk(probabilities, 5)\n", "\n", "    return {LABELS[i]: v.item() for i, v in zip(indices, values)}\n", "\n", "\n", "interface = gr.Interface(predict, inputs=gr.templates.Sketchpad(label=\"Draw Here\"), outputs=gr.Label(label=\"Guess\"), theme=\"default\", css=\".footer{display:none !important}\", live=True)\n", "interface.launch(enable_queue=False)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/plot_component/run.ipynb b/demo/plot_component/run.ipynb
new file mode 100644
index 0000000000..ef726a88f4
--- /dev/null
+++ b/demo/plot_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: plot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio matplotlib numpy"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "Fs = 8000\n", "f = 5\n", "sample = 8000\n", "x = np.arange(sample)\n", "y = np.sin(2 * np.pi * f * x / Fs)\n", "plt.plot(x, y)\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Plot(value=plt)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/question-answering/run.ipynb b/demo/question-answering/run.ipynb
new file mode 100644
index 0000000000..8c7cde6804
--- /dev/null
+++ b/demo/question-answering/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: question-answering"]}, {"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", "context = \"The Amazon rainforest, also known in English as Amazonia or the Amazon Jungle, is a moist broadleaf forest that covers most of the Amazon basin of South America. This basin encompasses 7,000,000 square kilometres (2,700,000 sq mi), of which 5,500,000 square kilometres (2,100,000 sq mi) are covered by the rainforest. This region includes territory belonging to nine nations. The majority of the forest is contained within Brazil, with 60% of the rainforest, followed by Peru with 13%, Colombia with 10%, and with minor amounts in Venezuela, Ecuador, Bolivia, Guyana, Suriname and French Guiana. The Amazon represents over half of the planet's remaining rainforests, and comprises the largest and most biodiverse tract of tropical rainforest in the world, with an estimated 390 billion individual trees divided into 16,000 species.\"\n", "question = \"Which continent is the Amazon rainforest in?\"\n", "gr.Interface.load(\n", "             \"huggingface/deepset/roberta-base-squad2\",\n", "             theme=\"default\",\n", "             inputs=[gr.inputs.Textbox(lines=7, default=context, label=\"Context Paragraph\"), gr.inputs.Textbox(lines=2, default=question, label=\"Question\")],\n", "             outputs=[gr.outputs.Textbox(label=\"Answer\"), gr.outputs.Textbox(label=\"Score\")],\n", "             title=None).launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/radio_component/run.ipynb b/demo/radio_component/run.ipynb
new file mode 100644
index 0000000000..7306ddebeb
--- /dev/null
+++ b/demo/radio_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: radio_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", "    gr.Radio(choices=[\"First Choice\", \"Second Choice\", \"Third Choice\"])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/reverse_audio/run.ipynb b/demo/reverse_audio/run.ipynb
new file mode 100644
index 0000000000..2055898d69
--- /dev/null
+++ b/demo/reverse_audio/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: reverse_audio"]}, {"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('audio')\n", "!wget -q -O audio/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/reverse_audio/audio/cantina.wav\n", "!wget -q -O audio/recording1.wav https://github.com/gradio-app/gradio/raw/main/demo/reverse_audio/audio/recording1.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def reverse_audio(audio):\n", "    sr, data = audio\n", "    return (sr, np.flipud(data))\n", "\n", "\n", "demo = gr.Interface(fn=reverse_audio, \n", "                    inputs=\"microphone\", \n", "                    outputs=\"audio\", \n", "                    examples=[\n", "                    \"https://samplelib.com/lib/preview/mp3/sample-3s.mp3\",\n", "                    os.path.join(os.path.abspath(''), \"audio/recording1.wav\")\n", "        ], cache_examples=True)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/reversible_flow/run.ipynb b/demo/reversible_flow/run.ipynb
new file mode 100644
index 0000000000..14fa4d7005
--- /dev/null
+++ b/demo/reversible_flow/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: reversible_flow"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def increase(num):\n", "    return num + 1\n", "\n", "with gr.Blocks() as demo:\n", "    a = gr.Number(label=\"a\")\n", "    b = gr.Number(label=\"b\")\n", "    btoa = gr.Button(\"a > b\")\n", "    atob = gr.Button(\"b > a\")\n", "    atob.click(increase, a, b)\n", "    btoa.click(increase, b, a)\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.ipynb b/demo/rows_and_columns/run.ipynb
new file mode 100644
index 0000000000..4f05752c97
--- /dev/null
+++ b/demo/rows_and_columns/run.ipynb
@@ -0,0 +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
diff --git a/demo/sales_projections/run.ipynb b/demo/sales_projections/run.ipynb
new file mode 100644
index 0000000000..a5b09c927c
--- /dev/null
+++ b/demo/sales_projections/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sales_projections"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio pandas numpy matplotlib"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import matplotlib\n", "matplotlib.use('Agg')\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def sales_projections(employee_data):\n", "    sales_data = employee_data.iloc[:, 1:4].astype(\"int\").to_numpy()\n", "    regression_values = np.apply_along_axis(\n", "        lambda row: np.array(np.poly1d(np.polyfit([0, 1, 2], row, 2))), 0, sales_data\n", "    )\n", "    projected_months = np.repeat(\n", "        np.expand_dims(np.arange(3, 12), 0), len(sales_data), axis=0\n", "    )\n", "    projected_values = np.array(\n", "        [\n", "            month * month * regression[0] + month * regression[1] + regression[2]\n", "            for month, regression in zip(projected_months, regression_values)\n", "        ]\n", "    )\n", "    plt.plot(projected_values.T)\n", "    plt.legend(employee_data[\"Name\"])\n", "    return employee_data, plt.gcf(), regression_values\n", "\n", "\n", "demo = gr.Interface(\n", "    sales_projections,\n", "    gr.Dataframe(\n", "        headers=[\"Name\", \"Jan Sales\", \"Feb Sales\", \"Mar Sales\"],\n", "        value=[[\"Jon\", 12, 14, 18], [\"Alice\", 14, 17, 2], [\"Sana\", 8, 9.5, 12]],\n", "    ),\n", "    [\"dataframe\", \"plot\", \"numpy\"],\n", "    description=\"Enter sales figures for employees to predict sales trajectory over year.\",\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/same-person-or-different/run.ipynb b/demo/same-person-or-different/run.ipynb
new file mode 100644
index 0000000000..8454416852
--- /dev/null
+++ b/demo/same-person-or-different/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: same-person-or-different\n", "### This demo identifies if two speakers are the same person using Gradio's Audio and HTML components.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio git+https://github.com/huggingface/transformers torchaudio "]}, {"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/same-person-or-different/packages.txt\n", "os.mkdir('samples')\n", "!wget -q -O samples/cate_blanch.mp3 https://github.com/gradio-app/gradio/raw/main/demo/same-person-or-different/samples/cate_blanch.mp3\n", "!wget -q -O samples/cate_blanch_2.mp3 https://github.com/gradio-app/gradio/raw/main/demo/same-person-or-different/samples/cate_blanch_2.mp3\n", "!wget -q -O samples/heath_ledger.mp3 https://github.com/gradio-app/gradio/raw/main/demo/same-person-or-different/samples/heath_ledger.mp3"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from torchaudio.sox_effects import apply_effects_file\n", "from transformers import AutoFeatureExtractor, AutoModelForAudioXVector\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "OUTPUT_OK = (\n", "    \"\"\"\n", "    <div class=\"container\">\n", "        <div class=\"row\"><h1 style=\"text-align: center\">The speakers are</h1></div>\n", "        <div class=\"row\"><h1 class=\"display-1 text-success\" style=\"text-align: center\">{:.1f}%</h1></div>\n", "        <div class=\"row\"><h1 style=\"text-align: center\">similar</h1></div>\n", "        <div class=\"row\"><h1 class=\"text-success\" style=\"text-align: center\">Welcome, human!</h1></div>\n", "        <div class=\"row\"><small style=\"text-align: center\">(You must get at least 85% to be considered the same person)</small><div class=\"row\">\n", "    </div>\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", "    \"\"\"\n", "    <div class=\"container\">\n", "        <div class=\"row\"><h1 style=\"text-align: center\">The speakers are</h1></div>\n", "        <div class=\"row\"><h1 class=\"display-1 text-danger\" style=\"text-align: center\">{:.1f}%</h1></div>\n", "        <div class=\"row\"><h1 style=\"text-align: center\">similar</h1></div>\n", "        <div class=\"row\"><h1 class=\"text-danger\" style=\"text-align: center\">You shall not pass!</h1></div>\n", "        <div class=\"row\"><small style=\"text-align: center\">(You must get at least 85% to be considered the same person)</small><div class=\"row\">\n", "    </div>\n", "\"\"\"\n", ")\n", "\n", "EFFECTS = [\n", "    [\"remix\", \"-\"],\n", "    [\"channels\", \"1\"],\n", "    [\"rate\", \"16000\"],\n", "    [\"gain\", \"-1.0\"],\n", "    [\"silence\", \"1\", \"0.1\", \"0.1%\", \"-1\", \"0.1\", \"0.1%\"],\n", "    [\"trim\", \"0\", \"10\"],\n", "]\n", "\n", "THRESHOLD = 0.85\n", "\n", "model_name = \"microsoft/unispeech-sat-base-plus-sv\"\n", "feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)\n", "model = AutoModelForAudioXVector.from_pretrained(model_name).to(device)\n", "cosine_sim = torch.nn.CosineSimilarity(dim=-1)\n", "\n", "\n", "def similarity_fn(path1, path2):\n", "    if not (path1 and path2):\n", "        return '<b style=\"color:red\">ERROR: Please record audio for *both* speakers!</b>'\n", "\n", "    wav1, _ = apply_effects_file(path1, EFFECTS)\n", "    wav2, _ = apply_effects_file(path2, EFFECTS)\n", "    print(wav1.shape, wav2.shape)\n", "\n", "    input1 = feature_extractor(wav1.squeeze(0), return_tensors=\"pt\", sampling_rate=16000).input_values.to(device)\n", "    input2 = feature_extractor(wav2.squeeze(0), return_tensors=\"pt\", sampling_rate=16000).input_values.to(device)\n", "\n", "    with torch.no_grad():\n", "        emb1 = model(input1).embeddings\n", "        emb2 = model(input2).embeddings\n", "    emb1 = torch.nn.functional.normalize(emb1, dim=-1).cpu()\n", "    emb2 = torch.nn.functional.normalize(emb2, dim=-1).cpu()\n", "    similarity = cosine_sim(emb1, emb2).numpy()[0]\n", "\n", "    if similarity >= THRESHOLD:\n", "        output = OUTPUT_OK.format(similarity * 100)\n", "    else:\n", "        output = OUTPUT_FAIL.format(similarity * 100)\n", "\n", "    return output\n", "\n", "inputs = [\n", "    gr.inputs.Audio(source=\"microphone\", type=\"filepath\", optional=True, label=\"Speaker #1\"),\n", "    gr.inputs.Audio(source=\"microphone\", type=\"filepath\", optional=True, label=\"Speaker #2\"),\n", "]\n", "output = gr.outputs.HTML(label=\"\")\n", "\n", "\n", "description = (\n", "    \"This demo from Microsoft will compare two speech samples and determine if they are from the same speaker. \"\n", "    \"Try it with your own voice!\"\n", ")\n", "article = (\n", "    \"<p style='text-align: center'>\"\n", "    \"<a href='https://huggingface.co/microsoft/unispeech-sat-large-sv' target='_blank'>\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT</a> | \"\n", "    \"<a href='https://arxiv.org/abs/2110.05752' target='_blank'>\ud83d\udcda UniSpeech-SAT paper</a> | \"\n", "    \"<a href='https://www.danielpovey.com/files/2018_icassp_xvectors.pdf' target='_blank'>\ud83d\udcda X-Vector paper</a>\"\n", "    \"</p>\"\n", ")\n", "examples = [\n", "    [\"samples/cate_blanch.mp3\", \"samples/cate_blanch_2.mp3\"],\n", "    [\"samples/cate_blanch.mp3\", \"samples/heath_ledger.mp3\"],\n", "]\n", "\n", "interface = gr.Interface(\n", "    fn=similarity_fn,\n", "    inputs=inputs,\n", "    outputs=output,\n", "    layout=\"horizontal\",\n", "    theme=\"huggingface\",\n", "    allow_flagging=False,\n", "    live=False,\n", "    examples=examples,\n", "    cache_examples=False\n", ")\n", "interface.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/score_tracker/run.ipynb b/demo/score_tracker/run.ipynb
new file mode 100644
index 0000000000..c089e64c46
--- /dev/null
+++ b/demo/score_tracker/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: score_tracker"]}, {"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", "scores = []\n", "\n", "def track_score(score):\n", "    scores.append(score)\n", "    top_scores = sorted(scores, reverse=True)[:3]\n", "    return top_scores\n", "\n", "demo = gr.Interface(\n", "    track_score, \n", "    gr.Number(label=\"Score\"), \n", "    gr.JSON(label=\"Top Scores\")\n", ")\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/sentence_builder/run.ipynb b/demo/sentence_builder/run.ipynb
new file mode 100644
index 0000000000..c292e91615
--- /dev/null
+++ b/demo/sentence_builder/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sentence_builder"]}, {"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 sentence_builder(quantity, animal, place, activity_list, morning):\n", "    return f\"\"\"The {quantity} {animal}s went to the {place} where they {\" and \".join(activity_list)} until the {\"morning\" if morning else \"night\"}\"\"\"\n", "\n", "\n", "demo = gr.Interface(\n", "    sentence_builder,\n", "    [\n", "        gr.Slider(2, 20, value=4),\n", "        gr.Dropdown([\"cat\", \"dog\", \"bird\"]),\n", "        gr.Radio([\"park\", \"zoo\", \"road\"]),\n", "        gr.CheckboxGroup([\"ran\", \"swam\", \"ate\", \"slept\"]),\n", "        gr.Checkbox(label=\"Is it the morning?\"),\n", "    ],\n", "    \"text\",\n", "    examples=[\n", "        [2, \"cat\", \"park\", [\"ran\", \"swam\"], True],\n", "        [4, \"dog\", \"zoo\", [\"ate\", \"swam\"], False],\n", "        [10, \"bird\", \"road\", [\"ran\"], False],\n", "        [8, \"cat\", \"zoo\", [\"ate\"], True],\n", "    ],\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/sentiment_analysis/run.ipynb b/demo/sentiment_analysis/run.ipynb
new file mode 100644
index 0000000000..84ca228e2f
--- /dev/null
+++ b/demo/sentiment_analysis/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sentiment_analysis\n", "### This sentiment analaysis demo takes in input text and returns its classification for either positive, negative or neutral using Gradio's Label output. It also uses the default interpretation method so users can click the Interpret button after a submission and see which words had the biggest effect on the output.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio nltk"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import nltk\n", "from nltk.sentiment.vader import SentimentIntensityAnalyzer\n", "\n", "nltk.download(\"vader_lexicon\")\n", "sid = SentimentIntensityAnalyzer()\n", "\n", "def sentiment_analysis(text):\n", "    scores = sid.polarity_scores(text)\n", "    del scores[\"compound\"]\n", "    return scores\n", "\n", "demo = gr.Interface(\n", "    fn=sentiment_analysis, \n", "    inputs=gr.Textbox(placeholder=\"Enter a positive or negative sentence here...\"), \n", "    outputs=\"label\", \n", "    interpretation=\"default\",\n", "    examples=[[\"This is wonderful!\"]])\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/sepia_filter/run.ipynb b/demo/sepia_filter/run.ipynb
new file mode 100644
index 0000000000..74fc34c204
--- /dev/null
+++ b/demo/sepia_filter/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sepia_filter"]}, {"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 numpy as np\n", "import gradio as gr\n", "\n", "def 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", "\n", "demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), \"image\")\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/sine_curve/run.ipynb b/demo/sine_curve/run.ipynb
new file mode 100644
index 0000000000..6871a2655e
--- /dev/null
+++ b/demo/sine_curve/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sine_curve"]}, {"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 math\n", "import gradio as gr\n", "import plotly.express as px\n", "import numpy as np\n", "\n", "\n", "plot_end = 2 * math.pi\n", "\n", "\n", "def get_plot(period=1):\n", "    global plot_end\n", "    x = np.arange(plot_end - 2 * math.pi, plot_end, 0.02)\n", "    y = np.sin(2*math.pi*period * x)\n", "    fig = px.line(x=x, y=y)\n", "    plot_end += 2 * math.pi\n", "    if plot_end > 1000:\n", "        plot_end = 2 * math.pi\n", "    return fig\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    with gr.Row():\n", "        with gr.Column():\n", "            gr.Markdown(\"Change the value of the slider to automatically update the plot\")\n", "            period = gr.Slider(label=\"Period of plot\", value=1, minimum=0, maximum=10, step=1)\n", "            plot = gr.Plot(label=\"Plot (updates every half second)\")\n", "\n", "    dep = demo.load(get_plot, None, plot, every=1)\n", "    period.change(get_plot, period, plot, every=1, cancels=[dep])\n", "\n", "\n", "if __name__ == \"__main__\":\n", "    demo.queue().launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/slider_component/run.ipynb b/demo/slider_component/run.ipynb
new file mode 100644
index 0000000000..ea8007b32a
--- /dev/null
+++ b/demo/slider_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: slider_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", "    gr.Slider()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/sound_alert/run.ipynb b/demo/sound_alert/run.ipynb
new file mode 100644
index 0000000000..550ffd8c7f
--- /dev/null
+++ b/demo/sound_alert/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: sound_alert"]}, {"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/sound_alert/beep.mp3"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "\n", "js_function = \"() => {new Audio('file=beep.mp3').play();}\"\n", "\n", "def task(x):\n", "    time.sleep(2)\n", "    return \"Hello, \" + x \n", "\n", "with gr.Blocks() as demo:\n", "    name = gr.Textbox(label=\"name\")\n", "    greeting = gr.Textbox(label=\"greeting\")\n", "    name.blur(task, name, greeting)\n", "    greeting.change(None, [], [], _js=js_function)  # Note that _js is a special arugment whose usage may change in the future\n", "    \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/spectogram/run.ipynb b/demo/spectogram/run.ipynb
new file mode 100644
index 0000000000..f4b592cc6e
--- /dev/null
+++ b/demo/spectogram/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: spectogram"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio scipy numpy matplotlib"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import matplotlib.pyplot as plt\n", "import numpy as np\n", "from scipy import signal\n", "\n", "import gradio as gr\n", "\n", "\n", "def spectrogram(audio):\n", "    sr, data = audio\n", "    if len(data.shape) == 2:\n", "        data = np.mean(data, axis=0)\n", "    frequencies, times, spectrogram_data = signal.spectrogram(\n", "        data, sr, window=\"hamming\"\n", "    )\n", "    plt.pcolormesh(times, frequencies, np.log10(spectrogram_data))\n", "    return plt\n", "\n", "\n", "demo = gr.Interface(spectrogram, \"audio\", \"plot\")\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/stable-diffusion/run.ipynb b/demo/stable-diffusion/run.ipynb
new file mode 100644
index 0000000000..876a3e25aa
--- /dev/null
+++ b/demo/stable-diffusion/run.ipynb
@@ -0,0 +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 torch import autocast\n", "from diffusers import StableDiffusionPipeline\n", "from datasets import load_dataset\n", "from PIL import Image  \n", "import re\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
diff --git a/demo/state_component/run.ipynb b/demo/state_component/run.ipynb
new file mode 100644
index 0000000000..83e1049d34
--- /dev/null
+++ b/demo/state_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: state_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", "    gr.State()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/stock_forecast/run.ipynb b/demo/stock_forecast/run.ipynb
new file mode 100644
index 0000000000..5da2cf3b10
--- /dev/null
+++ b/demo/stock_forecast/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stock_forecast"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy matplotlib"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import matplotlib\n", "matplotlib.use('Agg')\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def 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", "\n", "\n", "demo = 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\"),\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/stream_audio/run.ipynb b/demo/stream_audio/run.ipynb
new file mode 100644
index 0000000000..801062c1c5
--- /dev/null
+++ b/demo/stream_audio/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stream_audio"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import time\n", "\n", "def add_to_stream(audio, instream):\n", "    time.sleep(1)\n", "    if audio is None:\n", "        return gr.update(), instream\n", "    if instream is None:\n", "        ret = audio\n", "    else:\n", "        ret = (audio[0], np.concatenate((instream[1], audio[1])))\n", "    return ret, ret\n", "\n", "\n", "with gr.Blocks() as demo:\n", "    inp = gr.Audio(source=\"microphone\")\n", "    out = gr.Audio()\n", "    stream = gr.State()\n", "    clear = gr.Button(\"Clear\")\n", "\n", "    inp.stream(add_to_stream, [inp, stream], [out, stream])\n", "    clear.click(lambda: [None, None, None], None, [inp, out, stream])\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/stream_frames/run.ipynb b/demo/stream_frames/run.ipynb
new file mode 100644
index 0000000000..b3a468ac91
--- /dev/null
+++ b/demo/stream_frames/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stream_frames"]}, {"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", "\n", "def flip(im):\n", "    return np.flipud(im)\n", "\n", "demo = gr.Interface(\n", "    flip, \n", "    gr.Image(source=\"webcam\", streaming=True), \n", "    \"image\",\n", "    live=True\n", ")\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/streaming_stt/run.ipynb b/demo/streaming_stt/run.ipynb
new file mode 100644
index 0000000000..4e08dbae89
--- /dev/null
+++ b/demo/streaming_stt/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: streaming_stt"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio deepspeech==0.9.3"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from deepspeech import Model\n", "import gradio as gr\n", "import numpy as np\n", "import urllib.request\n", "\n", "model_file_path = \"deepspeech-0.9.3-models.pbmm\"\n", "lm_file_path = \"deepspeech-0.9.3-models.scorer\"\n", "url = \"https://github.com/mozilla/DeepSpeech/releases/download/v0.9.3/\"\n", "\n", "urllib.request.urlretrieve(url + model_file_path, filename=model_file_path)\n", "urllib.request.urlretrieve(url + lm_file_path, filename=lm_file_path)\n", "\n", "beam_width = 100\n", "lm_alpha = 0.93\n", "lm_beta = 1.18\n", "\n", "model = Model(model_file_path)\n", "model.enableExternalScorer(lm_file_path)\n", "model.setScorerAlphaBeta(lm_alpha, lm_beta)\n", "model.setBeamWidth(beam_width)\n", "\n", "\n", "def reformat_freq(sr, y):\n", "    if sr not in (\n", "        48000,\n", "        16000,\n", "    ):  # Deepspeech only supports 16k, (we convert 48k -> 16k)\n", "        raise ValueError(\"Unsupported rate\", sr)\n", "    if sr == 48000:\n", "        y = (\n", "            ((y / max(np.max(y), 1)) * 32767)\n", "            .reshape((-1, 3))\n", "            .mean(axis=1)\n", "            .astype(\"int16\")\n", "        )\n", "        sr = 16000\n", "    return sr, y\n", "\n", "\n", "def transcribe(speech, stream):\n", "    _, y = reformat_freq(*speech)\n", "    if stream is None:\n", "        stream = model.createStream()\n", "    stream.feedAudioContent(y)\n", "    text = stream.intermediateDecode()\n", "    return text, stream\n", "\n", "\n", "demo = gr.Interface(\n", "    transcribe,\n", "    [gr.Audio(source=\"microphone\", streaming=True), \"state\"],\n", "    [\"text\", \"state\"],\n", "    live=True,\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/streaming_wav2vec/run.ipynb b/demo/streaming_wav2vec/run.ipynb
new file mode 100644
index 0000000000..b92040cb1d
--- /dev/null
+++ b/demo/streaming_wav2vec/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: streaming_wav2vec"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch transformers "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from transformers import pipeline\n", "import gradio as gr\n", "import time\n", "\n", "p = pipeline(\"automatic-speech-recognition\")\n", "\n", "def transcribe(audio, state=\"\"):\n", "    time.sleep(2)\n", "    text = p(audio)[\"text\"]\n", "    state += text + \" \"\n", "    return state, state\n", "\n", "demo = gr.Interface(\n", "    fn=transcribe, \n", "    inputs=[\n", "        gr.Audio(source=\"microphone\", type=\"filepath\", streaming=True), \n", "        \"state\"\n", "    ],\n", "    outputs=[\n", "        \"textbox\",\n", "        \"state\"\n", "    ],\n", "    live=True\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/stt_or_tts/run.ipynb b/demo/stt_or_tts/run.ipynb
new file mode 100644
index 0000000000..028c02cbfa
--- /dev/null
+++ b/demo/stt_or_tts/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stt_or_tts"]}, {"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", "title = \"GPT-J-6B\"\n", "\n", "tts_examples = [\n", "    \"I love learning machine learning\",\n", "    \"How do you do?\",\n", "]\n", "\n", "tts_demo = gr.Interface.load(\n", "    \"huggingface/facebook/fastspeech2-en-ljspeech\",\n", "    title=None,\n", "    examples=tts_examples,\n", "    description=\"Give me something to say!\",\n", ")\n", "\n", "stt_demo = gr.Interface.load(\n", "    \"huggingface/facebook/wav2vec2-base-960h\",\n", "    title=None,\n", "    inputs=\"mic\",\n", "    description=\"Let me try to guess what you're saying!\",\n", ")\n", "\n", "demo = gr.TabbedInterface([tts_demo, stt_demo], [\"Text-to-speech\", \"Speech-to-text\"])\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/tax_calculator/run.ipynb b/demo/tax_calculator/run.ipynb
new file mode 100644
index 0000000000..b85290fd46
--- /dev/null
+++ b/demo/tax_calculator/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: tax_calculator\n", "### Calculate taxes using Textbox, Radio, and Dataframe components\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", "\n", "def 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", "\n", "demo = 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", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/text_analysis/run.ipynb b/demo/text_analysis/run.ipynb
new file mode 100644
index 0000000000..cc53c4e960
--- /dev/null
+++ b/demo/text_analysis/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: text_analysis\n", "### This simple demo takes advantage of Gradio's HighlightedText, JSON and HTML outputs to create a clear NER segmentation.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio spacy"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "os.system('python -m spacy download en_core_web_sm')\n", "import spacy\n", "from spacy import displacy\n", "\n", "nlp = spacy.load(\"en_core_web_sm\")\n", "\n", "def text_analysis(text):\n", "    doc = nlp(text)\n", "    html = displacy.render(doc, style=\"dep\", page=True)\n", "    html = (\n", "        \"<div style='max-width:100%; max-height:360px; overflow:auto'>\"\n", "        + html\n", "        + \"</div>\"\n", "    )\n", "    pos_count = {\n", "        \"char_count\": len(text),\n", "        \"token_count\": 0,\n", "    }\n", "    pos_tokens = []\n", "\n", "    for token in doc:\n", "        pos_tokens.extend([(token.text, token.pos_), (\" \", None)])\n", "\n", "    return pos_tokens, pos_count, html\n", "\n", "demo = gr.Interface(\n", "    text_analysis,\n", "    gr.Textbox(placeholder=\"Enter sentence here...\"),\n", "    [\"highlight\", \"json\", \"html\"],\n", "    examples=[\n", "        [\"What a beautiful morning for a walk!\"],\n", "        [\"It was the best of times, it was the worst of times.\"],\n", "    ],\n", ")\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/text_generation/run.ipynb b/demo/text_generation/run.ipynb
new file mode 100644
index 0000000000..c4eb578be9
--- /dev/null
+++ b/demo/text_generation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: text_generation\n", "### This text generation demo takes in input text and returns generated text. It uses the Transformers library to set up the model and has two examples.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio git+https://github.com/huggingface/transformers gradio torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import pipeline\n", "\n", "generator = pipeline('text-generation', model='gpt2')\n", "\n", "def generate(text):\n", "    result = generator(text, max_length=30, num_return_sequences=1)\n", "    return result[0][\"generated_text\"]\n", "\n", "examples = [\n", "    [\"The Moon's orbit around Earth has\"],\n", "    [\"The smooth Borealis basin in the Northern Hemisphere covers 40%\"],\n", "]\n", "\n", "demo = gr.Interface(\n", "    fn=generate,\n", "    inputs=gr.inputs.Textbox(lines=5, label=\"Input Text\"),\n", "    outputs=gr.outputs.Textbox(label=\"Generated Text\"),\n", "    examples=examples\n", ")\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/textbox_component/run.ipynb b/demo/textbox_component/run.ipynb
new file mode 100644
index 0000000000..e0375502e3
--- /dev/null
+++ b/demo/textbox_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: textbox_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", "    gr.Textbox()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/timeseries-forecasting-with-prophet/run.ipynb b/demo/timeseries-forecasting-with-prophet/run.ipynb
new file mode 100644
index 0000000000..2d5688e9ed
--- /dev/null
+++ b/demo/timeseries-forecasting-with-prophet/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: timeseries-forecasting-with-prophet\n", "### A simple dashboard showing pypi stats for python libraries. Updates on load, and has no buttons!\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio prophet==1.1 pandas pypistats plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pypistats\n", "from datetime import date\n", "from dateutil.relativedelta import relativedelta\n", "import pandas as pd\n", "from prophet import Prophet\n", "pd.options.plotting.backend = \"plotly\"\n", "\n", "def get_forecast(lib, time):\n", "\n", "    data = pypistats.overall(lib, total=True, format=\"pandas\")\n", "    data = data.groupby(\"category\").get_group(\"with_mirrors\").sort_values(\"date\")\n", "    start_date = date.today() - relativedelta(months=int(time.split(\" \")[0]))\n", "    df = data[(data['date'] > str(start_date))] \n", "\n", "    df1 = df[['date','downloads']]\n", "    df1.columns = ['ds','y']\n", "\n", "    m = Prophet()\n", "    m.fit(df1)\n", "    future = m.make_future_dataframe(periods=90)\n", "    forecast = m.predict(future)\n", "    fig1 = m.plot(forecast)\n", "    return fig1 \n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\n", "    \"\"\"\n", "    **Pypi Download Stats \ud83d\udcc8 with Prophet Forecasting**: see live download stats for popular open-source libraries \ud83e\udd17 along with a 3 month forecast using Prophet. The [ source code for this Gradio demo is here](https://huggingface.co/spaces/gradio/timeseries-forecasting-with-prophet/blob/main/app.py).\n", "    \"\"\")\n", "    with gr.Row():\n", "        lib = gr.Dropdown([\"pandas\", \"scikit-learn\", \"torch\", \"prophet\"], label=\"Library\", value=\"pandas\")\n", "        time = gr.Dropdown([\"3 months\", \"6 months\", \"9 months\", \"12 months\"], label=\"Downloads over the last...\", value=\"12 months\")\n", "\n", "    plt = gr.Plot()\n", "\n", "    lib.change(get_forecast, [lib, time], plt, queue=False)\n", "    time.change(get_forecast, [lib, time], plt, queue=False)    \n", "    demo.load(get_forecast, [lib, time], plt, queue=False)    \n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/timeseries_component/run.ipynb b/demo/timeseries_component/run.ipynb
new file mode 100644
index 0000000000..db959d32a7
--- /dev/null
+++ b/demo/timeseries_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: timeseries_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", "    gr.Timeseries()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/titanic_survival/run.ipynb b/demo/titanic_survival/run.ipynb
new file mode 100644
index 0000000000..fe40deecab
--- /dev/null
+++ b/demo/titanic_survival/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: titanic_survival"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio scikit-learn numpy pandas"]}, {"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/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/titanic_survival/files/titanic.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "\n", "import pandas as pd\n", "from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.model_selection import train_test_split\n", "\n", "import gradio as gr\n", "\n", "current_dir = os.path.dirname(os.path.realpath(__file__))\n", "data = pd.read_csv(os.path.join(current_dir, \"files/titanic.csv\"))\n", "\n", "\n", "def encode_age(df):\n", "    df.Age = df.Age.fillna(-0.5)\n", "    bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)\n", "    categories = pd.cut(df.Age, bins, labels=False)\n", "    df.Age = categories\n", "    return df\n", "\n", "\n", "def encode_fare(df):\n", "    df.Fare = df.Fare.fillna(-0.5)\n", "    bins = (-1, 0, 8, 15, 31, 1000)\n", "    categories = pd.cut(df.Fare, bins, labels=False)\n", "    df.Fare = categories\n", "    return df\n", "\n", "\n", "def encode_df(df):\n", "    df = encode_age(df)\n", "    df = encode_fare(df)\n", "    sex_mapping = {\"male\": 0, \"female\": 1}\n", "    df = df.replace({\"Sex\": sex_mapping})\n", "    embark_mapping = {\"S\": 1, \"C\": 2, \"Q\": 3}\n", "    df = df.replace({\"Embarked\": embark_mapping})\n", "    df.Embarked = df.Embarked.fillna(0)\n", "    df[\"Company\"] = 0\n", "    df.loc[(df[\"SibSp\"] > 0), \"Company\"] = 1\n", "    df.loc[(df[\"Parch\"] > 0), \"Company\"] = 2\n", "    df.loc[(df[\"SibSp\"] > 0) & (df[\"Parch\"] > 0), \"Company\"] = 3\n", "    df = df[\n", "        [\n", "            \"PassengerId\",\n", "            \"Pclass\",\n", "            \"Sex\",\n", "            \"Age\",\n", "            \"Fare\",\n", "            \"Embarked\",\n", "            \"Company\",\n", "            \"Survived\",\n", "        ]\n", "    ]\n", "    return df\n", "\n", "\n", "train = encode_df(data)\n", "\n", "X_all = train.drop([\"Survived\", \"PassengerId\"], axis=1)\n", "y_all = train[\"Survived\"]\n", "\n", "num_test = 0.20\n", "X_train, X_test, y_train, y_test = train_test_split(\n", "    X_all, y_all, test_size=num_test, random_state=23\n", ")\n", "\n", "clf = RandomForestClassifier()\n", "clf.fit(X_train, y_train)\n", "predictions = clf.predict(X_test)\n", "\n", "\n", "def predict_survival(passenger_class, is_male, age, company, fare, embark_point):\n", "    if passenger_class is None or embark_point is None:\n", "        return None\n", "    df = pd.DataFrame.from_dict(\n", "        {\n", "            \"Pclass\": [passenger_class + 1],\n", "            \"Sex\": [0 if is_male else 1],\n", "            \"Age\": [age],\n", "            \"Company\": [\n", "                (1 if \"Sibling\" in company else 0) + (2 if \"Child\" in company else 0)\n", "            ],\n", "            \"Fare\": [fare],\n", "            \"Embarked\": [embark_point + 1],\n", "        }\n", "    )\n", "    df = encode_age(df)\n", "    df = encode_fare(df)\n", "    pred = clf.predict_proba(df)[0]\n", "    return {\"Perishes\": float(pred[0]), \"Survives\": float(pred[1])}\n", "\n", "\n", "demo = gr.Interface(\n", "    predict_survival,\n", "    [\n", "        gr.Dropdown([\"first\", \"second\", \"third\"], type=\"index\"),\n", "        \"checkbox\",\n", "        gr.Slider(0, 80, value=25),\n", "        gr.CheckboxGroup([\"Sibling\", \"Child\"], label=\"Travelling with (select all)\"),\n", "        gr.Number(value=20),\n", "        gr.Radio([\"S\", \"C\", \"Q\"], type=\"index\"),\n", "    ],\n", "    \"label\",\n", "    examples=[\n", "        [\"first\", True, 30, [], 50, \"S\"],\n", "        [\"second\", False, 40, [\"Sibling\", \"Child\"], 10, \"Q\"],\n", "        [\"third\", True, 30, [\"Child\"], 20, \"S\"],\n", "    ],\n", "    interpretation=\"default\",\n", "    live=True,\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/translation/run.ipynb b/demo/translation/run.ipynb
new file mode 100644
index 0000000000..535508112c
--- /dev/null
+++ b/demo/translation/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: translation\n", "### This translation demo takes in the text, source and target languages, and returns the translation. It uses the Transformers library to set up the model and has a title, description, and example.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio git+https://github.com/huggingface/transformers gradio torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline\n", "import torch\n", "\n", "# this model was loaded from https://hf.co/models\n", "model = AutoModelForSeq2SeqLM.from_pretrained(\"facebook/nllb-200-distilled-600M\")\n", "tokenizer = AutoTokenizer.from_pretrained(\"facebook/nllb-200-distilled-600M\")\n", "device = 0 if torch.cuda.is_available() else -1\n", "LANGS = [\"ace_Arab\", \"eng_Latn\", \"fra_Latn\", \"spa_Latn\"]\n", "\n", "def translate(text, src_lang, tgt_lang):\n", "    \"\"\"\n", "    Translate the text from source lang to target lang\n", "    \"\"\"\n", "    translation_pipeline = pipeline(\"translation\", model=model, tokenizer=tokenizer, src_lang=src_lang, tgt_lang=tgt_lang, max_length=400, device=device)\n", "    result = translation_pipeline(text)\n", "    return result[0]['translation_text']\n", "\n", "demo = gr.Interface(\n", "    fn=translate,\n", "    inputs=[\n", "        gr.components.Textbox(label=\"Text\"),\n", "        gr.components.Dropdown(label=\"Source Language\", choices=LANGS),\n", "        gr.components.Dropdown(label=\"Target Language\", choices=LANGS),\n", "    ],\n", "    outputs=[\"text\"],\n", "    examples=[[\"Building a translation demo with Gradio is so easy!\", \"eng_Latn\", \"spa_Latn\"]],\n", "    cache_examples=False,\n", "    title=\"Translation Demo\",\n", "    description=\"This demo is a simplified version of the original [NLLB-Translator](https://huggingface.co/spaces/Narrativaai/NLLB-Translator) space\"\n", ")\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/unispeech-speaker-verification/run.ipynb b/demo/unispeech-speaker-verification/run.ipynb
new file mode 100644
index 0000000000..717934e068
--- /dev/null
+++ b/demo/unispeech-speaker-verification/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: unispeech-speaker-verification"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio git+https://github.com/huggingface/transformers torchaudio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('samples')\n", "!wget -q -O samples/cate_blanch.mp3 https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/cate_blanch.mp3\n", "!wget -q -O samples/cate_blanch_2.mp3 https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/cate_blanch_2.mp3\n", "!wget -q -O samples/cate_blanch_3.mp3 https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/cate_blanch_3.mp3\n", "!wget -q -O samples/heath_ledger.mp3 https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/heath_ledger.mp3\n", "!wget -q -O samples/heath_ledger_2.mp3 https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/heath_ledger_2.mp3\n", "!wget -q -O samples/kirsten_dunst.wav https://github.com/gradio-app/gradio/raw/main/demo/unispeech-speaker-verification/samples/kirsten_dunst.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from torchaudio.sox_effects import apply_effects_file\n", "from transformers import AutoFeatureExtractor, AutoModelForAudioXVector\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "STYLE = \"\"\"\n", "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css\" integrity=\"sha256-YvdLHPgkqJ8DVUxjjnGVlMMJtNimJ6dYkowFFvp4kKs=\" crossorigin=\"anonymous\">\n", "\"\"\"\n", "OUTPUT_OK = (\n", "    STYLE\n", "    + \"\"\"\n", "    <div class=\"container\">\n", "        <div class=\"row\"><h1 style=\"text-align: center\">The speakers are</h1></div>\n", "        <div class=\"row\"><h1 class=\"display-1 text-success\" style=\"text-align: center\">{:.1f}%</h1></div>\n", "        <div class=\"row\"><h1 style=\"text-align: center\">similar</h1></div>\n", "        <div class=\"row\"><h1 class=\"text-success\" style=\"text-align: center\">Welcome, human!</h1></div>\n", "        <div class=\"row\"><small style=\"text-align: center\">(You must get at least 85% to be considered the same person)</small><div class=\"row\">\n", "    </div>\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", "    STYLE\n", "    + \"\"\"\n", "    <div class=\"container\">\n", "        <div class=\"row\"><h1 style=\"text-align: center\">The speakers are</h1></div>\n", "        <div class=\"row\"><h1 class=\"display-1 text-danger\" style=\"text-align: center\">{:.1f}%</h1></div>\n", "        <div class=\"row\"><h1 style=\"text-align: center\">similar</h1></div>\n", "        <div class=\"row\"><h1 class=\"text-danger\" style=\"text-align: center\">You shall not pass!</h1></div>\n", "        <div class=\"row\"><small style=\"text-align: center\">(You must get at least 85% to be considered the same person)</small><div class=\"row\">\n", "    </div>\n", "\"\"\"\n", ")\n", "\n", "EFFECTS = [\n", "    [\"remix\", \"-\"],\n", "    [\"channels\", \"1\"],\n", "    [\"rate\", \"16000\"],\n", "    [\"gain\", \"-1.0\"],\n", "    [\"silence\", \"1\", \"0.1\", \"0.1%\", \"-1\", \"0.1\", \"0.1%\"],\n", "    [\"trim\", \"0\", \"10\"],\n", "]\n", "\n", "THRESHOLD = 0.85\n", "\n", "model_name = \"microsoft/unispeech-sat-base-plus-sv\"\n", "feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)\n", "model = AutoModelForAudioXVector.from_pretrained(model_name).to(device)\n", "cosine_sim = torch.nn.CosineSimilarity(dim=-1)\n", "\n", "\n", "def similarity_fn(path1, path2):\n", "    if not (path1 and path2):\n", "        return '<b style=\"color:red\">ERROR: Please record audio for *both* speakers!</b>'\n", "    wav1, _ = apply_effects_file(path1, EFFECTS)\n", "    wav2, _ = apply_effects_file(path2, EFFECTS)\n", "    print(wav1.shape, wav2.shape)\n", "\n", "    input1 = feature_extractor(wav1.squeeze(0), return_tensors=\"pt\", sampling_rate=16000).input_values.to(device)\n", "    input2 = feature_extractor(wav2.squeeze(0), return_tensors=\"pt\", sampling_rate=16000).input_values.to(device)\n", "\n", "    with torch.no_grad():\n", "        emb1 = model(input1).embeddings\n", "        emb2 = model(input2).embeddings\n", "    emb1 = torch.nn.functional.normalize(emb1, dim=-1).cpu()\n", "    emb2 = torch.nn.functional.normalize(emb2, dim=-1).cpu()\n", "    similarity = cosine_sim(emb1, emb2).numpy()[0]\n", "\n", "    if similarity >= THRESHOLD:\n", "        output = OUTPUT_OK.format(similarity * 100)\n", "    else:\n", "        output = OUTPUT_FAIL.format(similarity * 100)\n", "\n", "    return output\n", "\n", "\n", "inputs = [\n", "    gr.Audio(source=\"microphone\", type=\"filepath\", optional=True, label=\"Speaker #1\"),\n", "    gr.Audio(source=\"microphone\", type=\"filepath\", optional=True, label=\"Speaker #2\"),\n", "]\n", "output = gr.HTML(label=\"\")\n", "\n", "\n", "description = (\n", "    \"This demo will compare two speech samples and determine if they are from the same speaker. \"\n", "    \"Try it with your own voice!\"\n", ")\n", "article = (\n", "    \"<p style='text-align: center'>\"\n", "    \"<a href='https://huggingface.co/microsoft/unispeech-sat-large-sv' target='_blank'>\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT</a> | \"\n", "    \"<a href='https://arxiv.org/abs/2110.05752' target='_blank'>\ud83d\udcda UniSpeech-SAT paper</a> | \"\n", "    \"<a href='https://www.danielpovey.com/files/2018_icassp_xvectors.pdf' target='_blank'>\ud83d\udcda X-Vector paper</a>\"\n", "    \"</p>\"\n", ")\n", "examples = [\n", "    [\"samples/cate_blanch.mp3\", \"samples/cate_blanch_2.mp3\"],\n", "    [\"samples/cate_blanch.mp3\", \"samples/cate_blanch_3.mp3\"],\n", "    [\"samples/cate_blanch_2.mp3\", \"samples/cate_blanch_3.mp3\"],\n", "    [\"samples/heath_ledger.mp3\", \"samples/heath_ledger_2.mp3\"],\n", "    [\"samples/cate_blanch.mp3\", \"samples/kirsten_dunst.wav\"],\n", "]\n", "\n", "demo = gr.Interface(\n", "    fn=similarity_fn,\n", "    inputs=inputs,\n", "    outputs=output,\n", "    title=\"Voice Authentication with UniSpeech-SAT + X-Vectors\",\n", "    description=description,\n", "    article=article,\n", "    layout=\"horizontal\",\n", "    theme=\"huggingface\",\n", "    allow_flagging=\"never\",\n", "    live=False,\n", "    examples=examples,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/video_component/run.ipynb b/demo/video_component/run.ipynb
new file mode 100644
index 0000000000..dea83cb799
--- /dev/null
+++ b/demo/video_component/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: video_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", "    gr.Video()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/video_identity/run.ipynb b/demo/video_identity/run.ipynb
new file mode 100644
index 0000000000..19b4d287be
--- /dev/null
+++ b/demo/video_identity/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: video_identity"]}, {"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('video')\n", "!wget -q -O video/video_sample.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_identity/video/video_sample.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "def video_identity(video):\n", "    return video\n", "\n", "\n", "demo = gr.Interface(video_identity, \n", "                    gr.Video(), \n", "                    \"playable_video\", \n", "                    examples=[\n", "                        os.path.join(os.path.abspath(''), \n", "                                     \"video/video_sample.mp4\")], \n", "                    cache_examples=True)\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/webcam/run.ipynb b/demo/webcam/run.ipynb
new file mode 100644
index 0000000000..c5cf957c9e
--- /dev/null
+++ b/demo/webcam/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: webcam"]}, {"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 numpy as np\n", "\n", "import gradio as gr\n", "\n", "\n", "def snap(image, video):\n", "    return [image, video]\n", "\n", "\n", "demo = gr.Interface(\n", "    snap,\n", "    [gr.Image(source=\"webcam\", tool=None), gr.Video(source=\"webcam\")],\n", "    [\"image\", \"video\"],\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/white_noise_vid_not_playable/run.ipynb b/demo/white_noise_vid_not_playable/run.ipynb
new file mode 100644
index 0000000000..69139bcbc9
--- /dev/null
+++ b/demo/white_noise_vid_not_playable/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: white_noise_vid_not_playable"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio opencv-python"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import cv2\n", "import gradio as gr\n", "import numpy as np\n", "\n", "\n", "def gif_maker():\n", "    img_array = []\n", "    height, width = 50, 50\n", "    for i in range(30):\n", "        img_array.append(np.random.randint(0, 255, size=(height, width, 3)).astype(np.uint8))\n", "    output_file = \"test.mp4\"\n", "    out = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc(*'mp4v'), 15, (height, width))\n", "    for i in range(len(img_array)):\n", "        out.write(img_array[i])\n", "    out.release()\n", "    return output_file, output_file\n", "\n", "\n", "demo = gr.Interface(gif_maker, inputs=None, outputs=[gr.Video(), gr.File()])\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/xgboost-income-prediction-with-explainability/run.ipynb b/demo/xgboost-income-prediction-with-explainability/run.ipynb
new file mode 100644
index 0000000000..43d526982a
--- /dev/null
+++ b/demo/xgboost-income-prediction-with-explainability/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: xgboost-income-prediction-with-explainability\n", "### This demo takes in 12 inputs from the user in dropdowns and sliders and predicts income. It also has a separate button for explaining the prediction.\n", "        "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio matplotlib shap xgboost pandas datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "import shap\n", "import xgboost as xgb\n", "from datasets import load_dataset\n", "\n", "\n", "matplotlib.use(\"Agg\")\n", "dataset = load_dataset(\"scikit-learn/adult-census-income\")\n", "X_train = dataset[\"train\"].to_pandas()\n", "_ = X_train.pop(\"fnlwgt\")\n", "_ = X_train.pop(\"race\")\n", "y_train = X_train.pop(\"income\")\n", "y_train = (y_train == \">50K\").astype(int)\n", "categorical_columns = [\n", "    \"workclass\",\n", "    \"education\",\n", "    \"marital.status\",\n", "    \"occupation\",\n", "    \"relationship\",\n", "    \"sex\",\n", "    \"native.country\",\n", "]\n", "X_train = X_train.astype({col: \"category\" for col in categorical_columns})\n", "data = xgb.DMatrix(X_train, label=y_train, enable_categorical=True)\n", "model = xgb.train(params={\"objective\": \"binary:logistic\"}, dtrain=data)\n", "explainer = shap.TreeExplainer(model)\n", "\n", "def predict(*args):\n", "    df = pd.DataFrame([args], columns=X_train.columns)\n", "    df = df.astype({col: \"category\" for col in categorical_columns})\n", "    pos_pred = model.predict(xgb.DMatrix(df, enable_categorical=True))\n", "    return {\">50K\": float(pos_pred[0]), \"<=50K\": 1 - float(pos_pred[0])}\n", "\n", "\n", "def interpret(*args):\n", "    df = pd.DataFrame([args], columns=X_train.columns)\n", "    df = df.astype({col: \"category\" for col in categorical_columns})\n", "    shap_values = explainer.shap_values(xgb.DMatrix(df, enable_categorical=True))\n", "    scores_desc = list(zip(shap_values[0], X_train.columns))\n", "    scores_desc = sorted(scores_desc)\n", "    fig_m = plt.figure(tight_layout=True)\n", "    plt.barh([s[1] for s in scores_desc], [s[0] for s in scores_desc])\n", "    plt.title(\"Feature Shap Values\")\n", "    plt.ylabel(\"Shap Value\")\n", "    plt.xlabel(\"Feature\")\n", "    plt.tight_layout()\n", "    return fig_m\n", "\n", "\n", "unique_class = sorted(X_train[\"workclass\"].unique())\n", "unique_education = sorted(X_train[\"education\"].unique())\n", "unique_marital_status = sorted(X_train[\"marital.status\"].unique())\n", "unique_relationship = sorted(X_train[\"relationship\"].unique())\n", "unique_occupation = sorted(X_train[\"occupation\"].unique())\n", "unique_sex = sorted(X_train[\"sex\"].unique())\n", "unique_country = sorted(X_train[\"native.country\"].unique())\n", "\n", "with gr.Blocks() as demo:\n", "    gr.Markdown(\"\"\"\n", "    **Income Classification with XGBoost \ud83d\udcb0**:  This demo uses an XGBoost classifier predicts income based on demographic factors, along with Shapley value-based *explanations*. The [source code for this Gradio demo is here](https://huggingface.co/spaces/gradio/xgboost-income-prediction-with-explainability/blob/main/app.py).\n", "    \"\"\")\n", "    with gr.Row():\n", "        with gr.Column():\n", "            age = gr.Slider(label=\"Age\", minimum=17, maximum=90, step=1, randomize=True)\n", "            work_class = gr.Dropdown(\n", "                label=\"Workclass\",\n", "                choices=unique_class,\n", "                value=lambda: random.choice(unique_class),\n", "            )\n", "            education = gr.Dropdown(\n", "                label=\"Education Level\",\n", "                choices=unique_education,\n", "                value=lambda: random.choice(unique_education),\n", "            )\n", "            years = gr.Slider(\n", "                label=\"Years of schooling\",\n", "                minimum=1,\n", "                maximum=16,\n", "                step=1,\n", "                randomize=True,\n", "            )\n", "            marital_status = gr.Dropdown(\n", "                label=\"Marital Status\",\n", "                choices=unique_marital_status,\n", "                value=lambda: random.choice(unique_marital_status),\n", "            )\n", "            occupation = gr.Dropdown(\n", "                label=\"Occupation\",\n", "                choices=unique_occupation,\n", "                value=lambda: random.choice(unique_occupation),\n", "            )\n", "            relationship = gr.Dropdown(\n", "                label=\"Relationship Status\",\n", "                choices=unique_relationship,\n", "                value=lambda: random.choice(unique_relationship),\n", "            )\n", "            sex = gr.Dropdown(\n", "                label=\"Sex\", choices=unique_sex, value=lambda: random.choice(unique_sex)\n", "            )\n", "            capital_gain = gr.Slider(\n", "                label=\"Capital Gain\",\n", "                minimum=0,\n", "                maximum=100000,\n", "                step=500,\n", "                randomize=True,\n", "            )\n", "            capital_loss = gr.Slider(\n", "                label=\"Capital Loss\", minimum=0, maximum=10000, step=500, randomize=True\n", "            )\n", "            hours_per_week = gr.Slider(\n", "                label=\"Hours Per Week Worked\", minimum=1, maximum=99, step=1\n", "            )\n", "            country = gr.Dropdown(\n", "                label=\"Native Country\",\n", "                choices=unique_country,\n", "                value=lambda: random.choice(unique_country),\n", "            )\n", "        with gr.Column():\n", "            label = gr.Label()\n", "            plot = gr.Plot()\n", "            with gr.Row():\n", "                predict_btn = gr.Button(value=\"Predict\")\n", "                interpret_btn = gr.Button(value=\"Explain\")\n", "            predict_btn.click(\n", "                predict,\n", "                inputs=[\n", "                    age,\n", "                    work_class,\n", "                    education,\n", "                    years,\n", "                    marital_status,\n", "                    occupation,\n", "                    relationship,\n", "                    sex,\n", "                    capital_gain,\n", "                    capital_loss,\n", "                    hours_per_week,\n", "                    country,\n", "                ],\n", "                outputs=[label],\n", "            )\n", "            interpret_btn.click(\n", "                interpret,\n", "                inputs=[\n", "                    age,\n", "                    work_class,\n", "                    education,\n", "                    years,\n", "                    marital_status,\n", "                    occupation,\n", "                    relationship,\n", "                    sex,\n", "                    capital_gain,\n", "                    capital_loss,\n", "                    hours_per_week,\n", "                    country,\n", "                ],\n", "                outputs=[plot],\n", "            )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/zip_files/run.ipynb b/demo/zip_files/run.ipynb
new file mode 100644
index 0000000000..f3724c532c
--- /dev/null
+++ b/demo/zip_files/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: zip_files"]}, {"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/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/zip_files/files/titanic.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "from zipfile import ZipFile\n", "\n", "import gradio as gr\n", "\n", "\n", "def zip_files(files):\n", "    with ZipFile(\"tmp.zip\", \"w\") as zipObj:\n", "        for idx, file in enumerate(files):\n", "            zipObj.write(file.name, \"file\" + str(idx))\n", "    return \"tmp.zip\"\n", "\n", "demo = gr.Interface(\n", "    zip_files,\n", "    gr.File(file_count=\"multiple\"),\n", "    \"file\",\n", "    examples=[[[os.path.join(os.path.abspath(''),\"files/titanic.csv\"), \n", "    os.path.join(os.path.abspath(''),\"files/titanic.csv\"), \n", "    os.path.join(os.path.abspath(''),\"files/titanic.csv\")]]], \n", "    cache_examples=True\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/zip_to_json/run.ipynb b/demo/zip_to_json/run.ipynb
new file mode 100644
index 0000000000..0928b97b52
--- /dev/null
+++ b/demo/zip_to_json/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: zip_to_json"]}, {"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 zipfile import ZipFile\n", "\n", "import gradio as gr\n", "\n", "\n", "def zip_to_json(file_obj):\n", "    files = []\n", "    with ZipFile(file_obj.name) as zfile:\n", "        for zinfo in zfile.infolist():\n", "            files.append(\n", "                {\n", "                    \"name\": zinfo.filename,\n", "                    \"file_size\": zinfo.file_size,\n", "                    \"compressed_size\": zinfo.compress_size,\n", "                }\n", "            )\n", "    return files\n", "\n", "\n", "demo = gr.Interface(zip_to_json, \"file\", \"json\")\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/scripts/check_notebooks_diff.py b/scripts/check_notebooks_diff.py
new file mode 100644
index 0000000000..33bdaef62d
--- /dev/null
+++ b/scripts/check_notebooks_diff.py
@@ -0,0 +1,11 @@
+import re 
+import sys 
+
+with open("diff.txt") as f:
+    diff = f.read()
+
+regexp = re.compile(r"^((\+|\-)   )((?!id).)*$",  re.MULTILINE)
+found = re.findall(regexp, diff)
+if found:
+    print(found)
+    sys.exit(1)
\ No newline at end of file
diff --git a/website/homepage/src/demos/template.html b/website/homepage/src/demos/template.html
index b8c60629f3..518f851cdf 100644
--- a/website/homepage/src/demos/template.html
+++ b/website/homepage/src/demos/template.html
@@ -31,6 +31,9 @@ <h2 class="mb-4 text-2xl font-thin block">{{ category_demos["category"] }}</h2>
               <div class="demo-content px-4 {% if not ((category_loop.index==1) and (loop.index==1)) %}hidden{% endif %} {% if (category_loop.index==1) and (loop.index==1) %}selected-demo-window{% endif %}" name="{{ demo['dir'] }}">
                 <p class="my-4 text-lg text-gray-600">{{ demo['text'] }}</p>
                 <div class="codeblock" id="{{ demo['dir']}}_code">
+                  <a class ="clipboard-button" href="https://colab.research.google.com/github/gradio-app/gradio/blob/main/demo/{{demo['dir']}}/run.ipynb" target="_blank" style="right:30px">
+                    <img src="https://colab.research.google.com/assets/colab-badge.svg">
+                  </a>
                   <pre class=" max-h-80 overflow-auto"><code class="lang-python">{{ demo['code'] }}</code></pre>
                 </div>
                 {% if 'external_space' in demo %}
diff --git a/website/homepage/src/docs/obj_doc_template.html b/website/homepage/src/docs/obj_doc_template.html
index 9bdb0007a2..ebc757b08f 100644
--- a/website/homepage/src/docs/obj_doc_template.html
+++ b/website/homepage/src/docs/obj_doc_template.html
@@ -14,7 +14,12 @@
       </div>
       {% for demo_name, demo_code in obj["demos"] %}
       <div class="demo-content {% if loop.index != 1 %}hidden{% endif %}" name="{{ demo_name }}">
-        <div class="codeblock"><pre class=" max-h-80 overflow-auto"><code class="lang-python">{{ demo_code }}</code></pre></div>
+        <div class="codeblock">
+          <a class ="clipboard-button" href="https://colab.research.google.com/github/gradio-app/gradio/blob/main/demo/{{demo_name}}/run.ipynb" target="_blank" style="right:30px">
+            <img src="https://colab.research.google.com/assets/colab-badge.svg">
+          </a>
+          <pre class=" max-h-80 overflow-auto"><code class="lang-python">{{ demo_code }}</code></pre>
+        </div>
         {% if version=="main" %}
           <gradio-app space="gradio/{{ demo_name }}_main" />
         {% else %}
diff --git a/website/homepage/src/docs/template.html b/website/homepage/src/docs/template.html
index 33ff4ebeef..1b996c09aa 100644
--- a/website/homepage/src/docs/template.html
+++ b/website/homepage/src/docs/template.html
@@ -316,7 +316,6 @@ <h3 class="text-3xl font-light my-4" id="update-section-header">Update</h3>
     {% else %}
     <script type="module" src="https://gradio.s3-us-west-2.amazonaws.com/{{ gradio_version }}/gradio.js"></script>
     {% endif %}
-  
 
     {% include 'templates/footer.html' %}
     <script>{% include 'templates/guide-color.js' %}</script>


Code review comments:
diff_hunk: @@ -0,0 +1,27 @@
+# This workflow will check if the run.py files in every demo match the run.ipynb notebooks.
+
+name: Check Demos Match Notebooks
+
+on:
+  pull_request:
+    types: [opened, synchronize, labeled, unlabeled]
path: .github/workflows/check-demo-notebooks.yml
text: @user1:
I don't think we need labeled/unlabeled, but we might want reopened
```suggestion
    types: [opened, synchronize, reopened]
```

@author:
you're right we don't need labeled/unlabeled but do need reopened. committed