diff --git a/.changeset/all-crabs-doubt.md b/.changeset/all-crabs-doubt.md new file mode 100644 index 0000000000000..3b49fb419afe6 --- /dev/null +++ b/.changeset/all-crabs-doubt.md @@ -0,0 +1,5 @@ +--- +"@gradio/wasm": patch +--- + +fix:Lite: Add a break statement diff --git a/.changeset/angry-states-battle.md b/.changeset/angry-states-battle.md new file mode 100644 index 0000000000000..b19c81c95ca42 --- /dev/null +++ b/.changeset/angry-states-battle.md @@ -0,0 +1,6 @@ +--- +"@gradio/client": patch +"gradio": patch +--- + +fix:Ensure websocket polyfill doesn't load if there is already a `global.Webocket` property set diff --git a/.changeset/every-eggs-arrive.md b/.changeset/every-eggs-arrive.md new file mode 100644 index 0000000000000..f1804a053feff --- /dev/null +++ b/.changeset/every-eggs-arrive.md @@ -0,0 +1,5 @@ +--- +"gradio": minor +--- + +feat:Added dimensionality check to avoid bad array dimensions diff --git a/.changeset/green-forks-float.md b/.changeset/green-forks-float.md new file mode 100644 index 0000000000000..4f84a89d10d9e --- /dev/null +++ b/.changeset/green-forks-float.md @@ -0,0 +1,5 @@ +--- +"gradio": patch +--- + +fix:Define Font.__repr__() to be printed in the doc in a readable format diff --git a/.changeset/new-ideas-sniff.md b/.changeset/new-ideas-sniff.md new file mode 100644 index 0000000000000..c3360476e21ad --- /dev/null +++ b/.changeset/new-ideas-sniff.md @@ -0,0 +1,5 @@ +--- +"gradio": minor +--- + +feat:Fix curly brackets in docstrings diff --git a/.changeset/tall-tables-sing.md b/.changeset/tall-tables-sing.md new file mode 100644 index 0000000000000..d21d2f76c5f52 --- /dev/null +++ b/.changeset/tall-tables-sing.md @@ -0,0 +1,5 @@ +--- +"gradio": patch +--- + +fix:Remove deprecation warning from `gr.update` and clean up associated code diff --git a/.changeset/thirty-planets-smash.md b/.changeset/thirty-planets-smash.md new file mode 100644 index 0000000000000..a26b5fd3fc665 --- /dev/null +++ b/.changeset/thirty-planets-smash.md @@ -0,0 +1,6 @@ +--- +"@gradio/markdown": patch +"gradio": patch +--- + +fix:Fix Dataframe `line_breaks` diff --git a/.changeset/tricky-spoons-slide.md b/.changeset/tricky-spoons-slide.md new file mode 100644 index 0000000000000..8c661a32b3bc6 --- /dev/null +++ b/.changeset/tricky-spoons-slide.md @@ -0,0 +1,5 @@ +--- +"gradio": minor +--- + +feat:Fix type the docstring of the Code component diff --git a/CHANGELOG.md b/CHANGELOG.md index fbb4197533db0..04b46b565b24d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,71 +113,6 @@ For more information check the [`FileExplorer` documentation](https://gradio.app ### Fixes - [#5625](https://github.com/gradio-app/gradio/pull/5625) [`9ccc4794a`](https://github.com/gradio-app/gradio/commit/9ccc4794a72ce8319417119f6c370e7af3ffca6d) - Use ContextVar instead of threading.local(). Thanks [@cbensimon](https://github.com/cbensimon)! -- [#5636](https://github.com/gradio-app/gradio/pull/5636) [`fb5964fb8`](https://github.com/gradio-app/gradio/commit/fb5964fb88082e7b956853b543c468116811cab9) - Fix bug in example cache loading event. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! -- [#5633](https://github.com/gradio-app/gradio/pull/5633) [`341402337`](https://github.com/gradio-app/gradio/commit/34140233794c29d4722020e13c2d045da642dfae) - Allow Gradio apps containing `gr.Radio()`, `gr.Checkboxgroup()`, or `gr.Dropdown()` to be loaded with `gr.load()`. Thanks [@abidlabs](https://github.com/abidlabs)! -- [#5593](https://github.com/gradio-app/gradio/pull/5593) [`88d43bd12`](https://github.com/gradio-app/gradio/commit/88d43bd124792d216da445adef932a2b02f5f416) - Fixes avatar image in chatbot being squashed. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)! - -## 3.45.0-beta.8 - -### Features - -- [#5649](https://github.com/gradio-app/gradio/pull/5649) [`d56b355c1`](https://github.com/gradio-app/gradio/commit/d56b355c12ccdeeb8406a3520fecc15ae69d9141) - Fix front-end imports + other misc fixes. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! -- [#5651](https://github.com/gradio-app/gradio/pull/5651) [`0ab84bf80`](https://github.com/gradio-app/gradio/commit/0ab84bf80f66c866327473d08fe5bdc8d32f155a) - Add overwrite flag to create command. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - -## 3.45.0-beta.7 - -### Features - -- [#5648](https://github.com/gradio-app/gradio/pull/5648) [`c573e2339`](https://github.com/gradio-app/gradio/commit/c573e2339b86c85b378dc349de5e9223a3c3b04a) - Publish all components to npm. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! -- [#5637](https://github.com/gradio-app/gradio/pull/5637) [`670cfb75b`](https://github.com/gradio-app/gradio/commit/670cfb75b7cfd5a25a22c5aa307cd29c8879889e) - Some minor v4 fixes. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - -## 3.45.0-beta.6 - -### Features - -- [#5630](https://github.com/gradio-app/gradio/pull/5630) [`0b4fd5b6d`](https://github.com/gradio-app/gradio/commit/0b4fd5b6db96fc95a155e5e935e17e1ab11d1161) - Fix esbuild. Thanks [@pngwn](https://github.com/pngwn)! - -## 3.45.0-beta.5 - -### Features - -- [#5624](https://github.com/gradio-app/gradio/pull/5624) [`14fc612d8`](https://github.com/gradio-app/gradio/commit/14fc612d84bf6b1408eccd3a40fab41f25477571) - Fix esbuild. Thanks [@pngwn](https://github.com/pngwn)! - -## 3.45.0-beta.4 - -### Features - -- [#5620](https://github.com/gradio-app/gradio/pull/5620) [`c4c25ecdf`](https://github.com/gradio-app/gradio/commit/c4c25ecdf8c2fab5e3c41b519564e3b6a9ebfce3) - fix build and broken imports. Thanks [@pngwn](https://github.com/pngwn)! - -## 3.45.0-beta.3 - -### Features - -- [#5618](https://github.com/gradio-app/gradio/pull/5618) [`327cc4a6c`](https://github.com/gradio-app/gradio/commit/327cc4a6c1a213238cecd21f2b6c9cedc64bde5b) - Add docstring to trigger release. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - -## 3.45.0-beta.2 - -### Features - -- [#5615](https://github.com/gradio-app/gradio/pull/5615) [`142880ba5`](https://github.com/gradio-app/gradio/commit/142880ba589126d98da3d6a38866828864cc6b81) - Publish js theme. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! -- [#5613](https://github.com/gradio-app/gradio/pull/5613) [`d0b22b6cf`](https://github.com/gradio-app/gradio/commit/d0b22b6cf4345ce9954b166f8b4278f8d3e24472) - backend linting. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - -## 3.45.0-beta.1 - -### Features - -- [#5610](https://github.com/gradio-app/gradio/pull/5610) [`73f2e8e7e`](https://github.com/gradio-app/gradio/commit/73f2e8e7e426e80e397b5bf23b3a64b0dd6f4e09) - Fix js deps in cli and add gradio-preview artifacts to build. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - -## 3.45.0-beta.0 - -### Features - -- [#5507](https://github.com/gradio-app/gradio/pull/5507) [`1385dc688`](https://github.com/gradio-app/gradio/commit/1385dc6881f2d8ae7a41106ec21d33e2ef04d6a9) - Custom components. Thanks [@pngwn](https://github.com/pngwn)! -- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`681f10c31`](https://github.com/gradio-app/gradio/commit/681f10c315a75cc8cd0473c9a0167961af7696db) - release first version. Thanks [@pngwn](https://github.com/pngwn)! -- [#5589](https://github.com/gradio-app/gradio/pull/5589) [`af1b2f9ba`](https://github.com/gradio-app/gradio/commit/af1b2f9bafbacf2804fcfe68af6bb4b921442aca) - image fixes. Thanks [@pngwn](https://github.com/pngwn)! -- [#5240](https://github.com/gradio-app/gradio/pull/5240) [`da05e59a5`](https://github.com/gradio-app/gradio/commit/da05e59a53bbad15e5755a47f46685da18e1031e) - Cleanup of .update and .get_config per component. Thanks [@aliabid94](https://github.com/aliabid94)!/n get_config is removed, the config used is simply any attribute that is in the Block that shares a name with one of the constructor paramaters./n update is not removed for backwards compatibility, but deprecated. Instead return the component itself. Created a updateable decorator that simply checks to see if we're in an update, and if so, skips the constructor and wraps the args and kwargs in an update dictionary. easy peasy. - -### Fixes - [#5602](https://github.com/gradio-app/gradio/pull/5602) [`54d21d3f1`](https://github.com/gradio-app/gradio/commit/54d21d3f18f2ddd4e796d149a0b41461f49c711b) - Ensure `HighlightedText` with `merge_elements` loads without a value. Thanks [@hannahblair](https://github.com/hannahblair)! - [#5636](https://github.com/gradio-app/gradio/pull/5636) [`fb5964fb8`](https://github.com/gradio-app/gradio/commit/fb5964fb88082e7b956853b543c468116811cab9) - Fix bug in example cache loading event. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - [#5633](https://github.com/gradio-app/gradio/pull/5633) [`341402337`](https://github.com/gradio-app/gradio/commit/34140233794c29d4722020e13c2d045da642dfae) - Allow Gradio apps containing `gr.Radio()`, `gr.Checkboxgroup()`, or `gr.Dropdown()` to be loaded with `gr.load()`. Thanks [@abidlabs](https://github.com/abidlabs)! diff --git a/client/js/src/client.ts b/client/js/src/client.ts index 412366efdfb95..f3a8b8ad4e4b6 100644 --- a/client/js/src/client.ts +++ b/client/js/src/client.ts @@ -255,7 +255,10 @@ export function api_factory( }; const transform_files = normalise_files ?? true; - if (typeof window === "undefined" || !("WebSocket" in window)) { + if ( + (typeof window === "undefined" || !("WebSocket" in window)) && + !global.Websocket + ) { const ws = await import("ws"); NodeBlob = (await import("node:buffer")).Blob; //@ts-ignore diff --git a/demo/Echocardiogram-Segmentation/run.ipynb b/demo/Echocardiogram-Segmentation/run.ipynb index 45fd4ec28cff6..21f9c60b2efe0 100644 --- a/demo/Echocardiogram-Segmentation/run.ipynb +++ b/demo/Echocardiogram-Segmentation/run.ipynb @@ -1 +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 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/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", "import numpy as np\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 +{"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 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/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", "import numpy as np\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/altair_plot/run.ipynb b/demo/altair_plot/run.ipynb index d98c209bd0267..de688ebe7c92c 100644 --- a/demo/altair_plot/run.ipynb +++ b/demo/altair_plot/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: altair_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio altair vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import altair as alt\n", "import gradio as gr\n", "import numpy as np\n", "import pandas as pd\n", "from vega_datasets import data\n", "\n", "\n", "def make_plot(plot_type):\n", " if plot_type == \"scatter_plot\":\n", " cars = data.cars()\n", " return alt.Chart(cars).mark_point().encode(\n", " x='Horsepower',\n", " y='Miles_per_Gallon',\n", " color='Origin',\n", " )\n", " elif plot_type == \"heatmap\":\n", " # Compute x^2 + y^2 across a 2D grid\n", " x, y = np.meshgrid(range(-5, 5), range(-5, 5))\n", " z = x ** 2 + y ** 2\n", "\n", " # Convert this grid to columnar data expected by Altair\n", " source = pd.DataFrame({'x': x.ravel(),\n", " 'y': y.ravel(),\n", " 'z': z.ravel()})\n", " return alt.Chart(source).mark_rect().encode(\n", " x='x:O',\n", " y='y:O',\n", " color='z:Q'\n", " )\n", " elif plot_type == \"us_map\":\n", " states = alt.topo_feature(data.us_10m.url, 'states')\n", " source = data.income.url\n", "\n", " return alt.Chart(source).mark_geoshape().encode(\n", " shape='geo:G',\n", " color='pct:Q',\n", " tooltip=['name:N', 'pct:Q'],\n", " facet=alt.Facet('group:N', columns=2),\n", " ).transform_lookup(\n", " lookup='id',\n", " from_=alt.LookupData(data=states, key='id'),\n", " as_='geo'\n", " ).properties(\n", " width=300,\n", " height=175,\n", " ).project(\n", " type='albersUsa'\n", " )\n", " elif plot_type == \"interactive_barplot\":\n", " source = data.movies.url\n", "\n", " pts = alt.selection(type=\"single\", encodings=['x'])\n", "\n", " rect = alt.Chart(data.movies.url).mark_rect().encode(\n", " alt.X('IMDB_Rating:Q', bin=True),\n", " alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),\n", " alt.Color('count()',\n", " scale=alt.Scale(scheme='greenblue'),\n", " legend=alt.Legend(title='Total Records')\n", " )\n", " )\n", "\n", " circ = rect.mark_point().encode(\n", " alt.ColorValue('grey'),\n", " alt.Size('count()',\n", " legend=alt.Legend(title='Records in Selection')\n", " )\n", " ).transform_filter(\n", " pts\n", " )\n", "\n", " bar = alt.Chart(source).mark_bar().encode(\n", " x='Major_Genre:N',\n", " y='count()',\n", " color=alt.condition(pts, alt.ColorValue(\"steelblue\"), alt.ColorValue(\"grey\"))\n", " ).properties(\n", " width=550,\n", " height=200\n", " ).add_selection(pts)\n", "\n", " plot = alt.vconcat(\n", " rect + circ,\n", " bar\n", " ).resolve_legend(\n", " color=\"independent\",\n", " size=\"independent\"\n", " )\n", " return plot\n", " elif plot_type == \"radial\":\n", " source = pd.DataFrame({\"values\": [12, 23, 47, 6, 52, 19]})\n", "\n", " base = alt.Chart(source).encode(\n", " theta=alt.Theta(\"values:Q\", stack=True),\n", " radius=alt.Radius(\"values\", scale=alt.Scale(type=\"sqrt\", zero=True, rangeMin=20)),\n", " color=\"values:N\",\n", " )\n", "\n", " c1 = base.mark_arc(innerRadius=20, stroke=\"#fff\")\n", "\n", " c2 = base.mark_text(radiusOffset=10).encode(text=\"values:Q\")\n", "\n", " return c1 + c2\n", " elif plot_type == \"multiline\":\n", " source = data.stocks()\n", "\n", " highlight = alt.selection(type='single', on='mouseover',\n", " fields=['symbol'], nearest=True)\n", "\n", " base = alt.Chart(source).encode(\n", " x='date:T',\n", " y='price:Q',\n", " color='symbol:N'\n", " )\n", "\n", " points = base.mark_circle().encode(\n", " opacity=alt.value(0)\n", " ).add_selection(\n", " highlight\n", " ).properties(\n", " width=600\n", " )\n", "\n", " lines = base.mark_line().encode(\n", " size=alt.condition(~highlight, alt.value(1), alt.value(3))\n", " )\n", "\n", " return points + lines\n", "\n", "\n", "with gr.Blocks() as demo:\n", " button = gr.Radio(label=\"Plot type\",\n", " choices=['scatter_plot', 'heatmap', 'us_map',\n", " 'interactive_barplot', \"radial\", \"multiline\"], value='scatter_plot')\n", " plot = gr.Plot(label=\"Plot\")\n", " button.change(make_plot, inputs=button, outputs=[plot])\n", " demo.load(make_plot, inputs=[button], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: altair_plot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio altair vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import altair as alt\n", "import gradio as gr\n", "import numpy as np\n", "import pandas as pd\n", "from vega_datasets import data\n", "\n", "\n", "def make_plot(plot_type):\n", " if plot_type == \"scatter_plot\":\n", " cars = data.cars()\n", " return alt.Chart(cars).mark_point().encode(\n", " x='Horsepower',\n", " y='Miles_per_Gallon',\n", " color='Origin',\n", " )\n", " elif plot_type == \"heatmap\":\n", " # Compute x^2 + y^2 across a 2D grid\n", " x, y = np.meshgrid(range(-5, 5), range(-5, 5))\n", " z = x ** 2 + y ** 2\n", "\n", " # Convert this grid to columnar data expected by Altair\n", " source = pd.DataFrame({'x': x.ravel(),\n", " 'y': y.ravel(),\n", " 'z': z.ravel()})\n", " return alt.Chart(source).mark_rect().encode(\n", " x='x:O',\n", " y='y:O',\n", " color='z:Q'\n", " )\n", " elif plot_type == \"us_map\":\n", " states = alt.topo_feature(data.us_10m.url, 'states')\n", " source = data.income.url\n", "\n", " return alt.Chart(source).mark_geoshape().encode(\n", " shape='geo:G',\n", " color='pct:Q',\n", " tooltip=['name:N', 'pct:Q'],\n", " facet=alt.Facet('group:N', columns=2),\n", " ).transform_lookup(\n", " lookup='id',\n", " from_=alt.LookupData(data=states, key='id'),\n", " as_='geo'\n", " ).properties(\n", " width=300,\n", " height=175,\n", " ).project(\n", " type='albersUsa'\n", " )\n", " elif plot_type == \"interactive_barplot\":\n", " source = data.movies.url\n", "\n", " pts = alt.selection(type=\"single\", encodings=['x'])\n", "\n", " rect = alt.Chart(data.movies.url).mark_rect().encode(\n", " alt.X('IMDB_Rating:Q', bin=True),\n", " alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),\n", " alt.Color('count()',\n", " scale=alt.Scale(scheme='greenblue'),\n", " legend=alt.Legend(title='Total Records')\n", " )\n", " )\n", "\n", " circ = rect.mark_point().encode(\n", " alt.ColorValue('grey'),\n", " alt.Size('count()',\n", " legend=alt.Legend(title='Records in Selection')\n", " )\n", " ).transform_filter(\n", " pts\n", " )\n", "\n", " bar = alt.Chart(source).mark_bar().encode(\n", " x='Major_Genre:N',\n", " y='count()',\n", " color=alt.condition(pts, alt.ColorValue(\"steelblue\"), alt.ColorValue(\"grey\"))\n", " ).properties(\n", " width=550,\n", " height=200\n", " ).add_selection(pts)\n", "\n", " plot = alt.vconcat(\n", " rect + circ,\n", " bar\n", " ).resolve_legend(\n", " color=\"independent\",\n", " size=\"independent\"\n", " )\n", " return plot\n", " elif plot_type == \"radial\":\n", " source = pd.DataFrame({\"values\": [12, 23, 47, 6, 52, 19]})\n", "\n", " base = alt.Chart(source).encode(\n", " theta=alt.Theta(\"values:Q\", stack=True),\n", " radius=alt.Radius(\"values\", scale=alt.Scale(type=\"sqrt\", zero=True, rangeMin=20)),\n", " color=\"values:N\",\n", " )\n", "\n", " c1 = base.mark_arc(innerRadius=20, stroke=\"#fff\")\n", "\n", " c2 = base.mark_text(radiusOffset=10).encode(text=\"values:Q\")\n", "\n", " return c1 + c2\n", " elif plot_type == \"multiline\":\n", " source = data.stocks()\n", "\n", " highlight = alt.selection(type='single', on='mouseover',\n", " fields=['symbol'], nearest=True)\n", "\n", " base = alt.Chart(source).encode(\n", " x='date:T',\n", " y='price:Q',\n", " color='symbol:N'\n", " )\n", "\n", " points = base.mark_circle().encode(\n", " opacity=alt.value(0)\n", " ).add_selection(\n", " highlight\n", " ).properties(\n", " width=600\n", " )\n", "\n", " lines = base.mark_line().encode(\n", " size=alt.condition(~highlight, alt.value(1), alt.value(3))\n", " )\n", "\n", " return points + lines\n", "\n", "\n", "with gr.Blocks() as demo:\n", " button = gr.Radio(label=\"Plot type\",\n", " choices=['scatter_plot', 'heatmap', 'us_map',\n", " 'interactive_barplot', \"radial\", \"multiline\"], value='scatter_plot')\n", " plot = gr.Plot(label=\"Plot\")\n", " button.change(make_plot, inputs=button, outputs=[plot])\n", " demo.load(make_plot, inputs=[button], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/animeganv2/run.ipynb b/demo/animeganv2/run.ipynb index 555bef12fc39e..970dbdc59bfa8 100644 --- a/demo/animeganv2/run.ipynb +++ b/demo/animeganv2/run.ipynb @@ -1 +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", "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 = \"

Github Repo Pytorch

visitor badge

\"\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 +{"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", "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 = \"

Github Repo Pytorch

visitor badge

\"\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/annotatedimage_component/run.ipynb b/demo/annotatedimage_component/run.ipynb index d5aed277c7a78..d470bc595c616 100644 --- a/demo/annotatedimage_component/run.ipynb +++ b/demo/annotatedimage_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: annotatedimage_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pathlib\n", "from PIL import Image\n", "import numpy as np\n", "import urllib.request\n", "\n", "\n", "source_dir = pathlib.Path(__file__).parent\n", "\n", "urllib.request.urlretrieve(\n", " 'https://gradio-builds.s3.amazonaws.com/demo-files/base.png',\n", " str(source_dir / \"base.png\")\n", ")\n", "urllib.request.urlretrieve(\n", " \"https://gradio-builds.s3.amazonaws.com/demo-files/buildings.png\",\n", " str(source_dir / \"buildings.png\")\n", ")\n", "\n", "base_image = Image.open(str(source_dir / \"base.png\"))\n", "building_image = Image.open(str(source_dir / \"buildings.png\"))\n", "\n", "# Create segmentation mask\n", "building_image = np.asarray(building_image)[:, :, -1] > 0\n", "\n", "with gr.Blocks() as demo:\n", " gr.AnnotatedImage(\n", " value=(base_image, [(building_image, \"buildings\")]),\n", " height=500,\n", " )\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: annotatedimage_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pathlib\n", "from PIL import Image\n", "import numpy as np\n", "import urllib.request\n", "\n", "\n", "source_dir = pathlib.Path(__file__).parent\n", "\n", "urllib.request.urlretrieve(\n", " 'https://gradio-builds.s3.amazonaws.com/demo-files/base.png',\n", " str(source_dir / \"base.png\")\n", ")\n", "urllib.request.urlretrieve(\n", " \"https://gradio-builds.s3.amazonaws.com/demo-files/buildings.png\",\n", " str(source_dir / \"buildings.png\")\n", ")\n", "\n", "base_image = Image.open(str(source_dir / \"base.png\"))\n", "building_image = Image.open(str(source_dir / \"buildings.png\"))\n", "\n", "# Create segmentation mask\n", "building_image = np.asarray(building_image)[:, :, -1] > 0\n", "\n", "with gr.Blocks() as demo:\n", " gr.AnnotatedImage(\n", " value=(base_image, [(building_image, \"buildings\")]),\n", " height=500,\n", " )\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/asr/run.ipynb b/demo/asr/run.ipynb index e9d355677fbe5..5d063d5fd906b 100644 --- a/demo/asr/run.ipynb +++ b/demo/asr/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: asr"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchaudio transformers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import pipeline\n", "import numpy as np\n", "\n", "transcriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n", "\n", "def transcribe(audio):\n", " sr, y = audio\n", " y = y.astype(np.float32)\n", " y /= np.max(np.abs(y))\n", "\n", " return transcriber({\"sampling_rate\": sr, \"raw\": y})[\"text\"]\n", "\n", "\n", "demo = gr.Interface(\n", " transcribe,\n", " gr.Audio(source=\"microphone\"),\n", " \"text\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: asr"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchaudio transformers"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import pipeline\n", "import numpy as np\n", "\n", "transcriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n", "\n", "def transcribe(audio):\n", " sr, y = audio\n", " y = y.astype(np.float32)\n", " y /= np.max(np.abs(y))\n", "\n", " return transcriber({\"sampling_rate\": sr, \"raw\": y})[\"text\"]\n", "\n", "\n", "demo = gr.Interface(\n", " transcribe,\n", " gr.Audio(source=\"microphone\"),\n", " \"text\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/audio_component/run.ipynb b/demo/audio_component/run.ipynb index 4cead25d7e976..12e3cf3cb3b91 100644 --- a/demo/audio_component/run.ipynb +++ b/demo/audio_component/run.ipynb @@ -1 +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()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/audio_debugger/run.ipynb b/demo/audio_debugger/run.ipynb index eb416213dfca2..336800b78b39a 100644 --- a/demo/audio_debugger/run.ipynb +++ b/demo/audio_debugger/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: audio_debugger"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/audio_debugger/cantina.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import subprocess\n", "import os\n", "\n", "audio_file = os.path.join(os.path.abspath(''), \"cantina.wav\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(\"Audio\"):\n", " gr.Audio(audio_file)\n", " with gr.Tab(\"Interface\"):\n", " gr.Interface(lambda x:x, \"audio\", \"audio\", examples=[audio_file], cache_examples=True)\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 +{"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} diff --git a/demo/autocomplete/run.ipynb b/demo/autocomplete/run.ipynb index 326a602e18b50..0d63872d3ca8e 100644 --- a/demo/autocomplete/run.ipynb +++ b/demo/autocomplete/run.ipynb @@ -1 +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.load(\"huggingface/gpt2-xl\", hf_token=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 +{"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.load(\"huggingface/gpt2-xl\", hf_token=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 index 81d2c2d7acd04..895d6c6b35fae 100644 --- a/demo/automatic-speech-recognition/run.ipynb +++ b/demo/automatic-speech-recognition/run.ipynb @@ -1 +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.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", " hf_token=auth_token\n", ")\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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.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", " hf_token=auth_token\n", ")\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/bar_plot/run.ipynb b/demo/bar_plot/run.ipynb index 0b97d4dffd519..f02c08df24013 100644 --- a/demo/bar_plot/run.ipynb +++ b/demo/bar_plot/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: bar_plot"]}, {"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": ["import gradio as gr\n", "import pandas as pd\n", "import random\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"a\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"b\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "fake_barley = pd.DataFrame(\n", " {\n", " \"site\": [\n", " random.choice(\n", " [\n", " \"University Farm\",\n", " \"Waseca\",\n", " \"Morris\",\n", " \"Crookston\",\n", " \"Grand Rapids\",\n", " \"Duluth\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " \"yield\": [random.randint(25, 75) for _ in range(120)],\n", " \"variety\": [\n", " random.choice(\n", " [\n", " \"Manchuria\",\n", " \"Wisconsin No. 38\",\n", " \"Glabron\",\n", " \"No. 457\",\n", " \"No. 462\",\n", " \"No. 475\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " \"year\": [\n", " random.choice(\n", " [\n", " \"1931\",\n", " \"1932\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " }\n", ")\n", "\n", "\n", "def bar_plot_fn(display):\n", " if display == \"simple\":\n", " return gr.BarPlot(\n", " simple,\n", " x=\"a\",\n", " y=\"b\",\n", " title=\"Simple Bar Plot with made up data\",\n", " tooltip=[\"a\", \"b\"],\n", " y_lim=[20, 100],\n", " )\n", " elif display == \"stacked\":\n", " return gr.BarPlot(\n", " fake_barley,\n", " x=\"variety\",\n", " y=\"yield\",\n", " color=\"site\",\n", " title=\"Barley Yield Data\",\n", " tooltip=[\"variety\", \"site\"],\n", " )\n", " elif display == \"grouped\":\n", " return gr.BarPlot(\n", " fake_barley.astype({\"year\": str}),\n", " x=\"year\",\n", " y=\"yield\",\n", " color=\"year\",\n", " group=\"site\",\n", " title=\"Barley Yield by Year and Site\",\n", " group_title=\"\",\n", " tooltip=[\"yield\", \"site\", \"year\"],\n", " )\n", " elif display == \"simple-horizontal\":\n", " return gr.BarPlot(\n", " simple,\n", " x=\"a\",\n", " y=\"b\",\n", " x_title=\"Variable A\",\n", " y_title=\"Variable B\",\n", " title=\"Simple Bar Plot with made up data\",\n", " tooltip=[\"a\", \"b\"],\n", " vertical=False,\n", " y_lim=[20, 100],\n", " )\n", " elif display == \"stacked-horizontal\":\n", " return gr.BarPlot(\n", " fake_barley,\n", " x=\"variety\",\n", " y=\"yield\",\n", " color=\"site\",\n", " title=\"Barley Yield Data\",\n", " vertical=False,\n", " tooltip=[\"variety\", \"site\"],\n", " )\n", " elif display == \"grouped-horizontal\":\n", " return gr.BarPlot(\n", " fake_barley.astype({\"year\": str}),\n", " x=\"year\",\n", " y=\"yield\",\n", " color=\"year\",\n", " group=\"site\",\n", " title=\"Barley Yield by Year and Site\",\n", " group_title=\"\",\n", " tooltip=[\"yield\", \"site\", \"year\"],\n", " vertical=False,\n", " )\n", "\n", "\n", "with gr.Blocks() as bar_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " display = gr.Dropdown(\n", " choices=[\n", " \"simple\",\n", " \"stacked\",\n", " \"grouped\",\n", " \"simple-horizontal\",\n", " \"stacked-horizontal\",\n", " \"grouped-horizontal\",\n", " ],\n", " value=\"simple\",\n", " label=\"Type of Bar Plot\",\n", " )\n", " with gr.Column():\n", " plot = gr.BarPlot()\n", " display.change(bar_plot_fn, inputs=display, outputs=plot)\n", " bar_plot.load(fn=bar_plot_fn, inputs=display, outputs=plot)\n", "\n", "bar_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: bar_plot"]}, {"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": ["import gradio as gr\n", "import pandas as pd\n", "import random\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"a\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"b\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "fake_barley = pd.DataFrame(\n", " {\n", " \"site\": [\n", " random.choice(\n", " [\n", " \"University Farm\",\n", " \"Waseca\",\n", " \"Morris\",\n", " \"Crookston\",\n", " \"Grand Rapids\",\n", " \"Duluth\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " \"yield\": [random.randint(25, 75) for _ in range(120)],\n", " \"variety\": [\n", " random.choice(\n", " [\n", " \"Manchuria\",\n", " \"Wisconsin No. 38\",\n", " \"Glabron\",\n", " \"No. 457\",\n", " \"No. 462\",\n", " \"No. 475\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " \"year\": [\n", " random.choice(\n", " [\n", " \"1931\",\n", " \"1932\",\n", " ]\n", " )\n", " for _ in range(120)\n", " ],\n", " }\n", ")\n", "\n", "\n", "def bar_plot_fn(display):\n", " if display == \"simple\":\n", " return gr.BarPlot(\n", " simple,\n", " x=\"a\",\n", " y=\"b\",\n", " title=\"Simple Bar Plot with made up data\",\n", " tooltip=[\"a\", \"b\"],\n", " y_lim=[20, 100],\n", " )\n", " elif display == \"stacked\":\n", " return gr.BarPlot(\n", " fake_barley,\n", " x=\"variety\",\n", " y=\"yield\",\n", " color=\"site\",\n", " title=\"Barley Yield Data\",\n", " tooltip=[\"variety\", \"site\"],\n", " )\n", " elif display == \"grouped\":\n", " return gr.BarPlot(\n", " fake_barley.astype({\"year\": str}),\n", " x=\"year\",\n", " y=\"yield\",\n", " color=\"year\",\n", " group=\"site\",\n", " title=\"Barley Yield by Year and Site\",\n", " group_title=\"\",\n", " tooltip=[\"yield\", \"site\", \"year\"],\n", " )\n", " elif display == \"simple-horizontal\":\n", " return gr.BarPlot(\n", " simple,\n", " x=\"a\",\n", " y=\"b\",\n", " x_title=\"Variable A\",\n", " y_title=\"Variable B\",\n", " title=\"Simple Bar Plot with made up data\",\n", " tooltip=[\"a\", \"b\"],\n", " vertical=False,\n", " y_lim=[20, 100],\n", " )\n", " elif display == \"stacked-horizontal\":\n", " return gr.BarPlot(\n", " fake_barley,\n", " x=\"variety\",\n", " y=\"yield\",\n", " color=\"site\",\n", " title=\"Barley Yield Data\",\n", " vertical=False,\n", " tooltip=[\"variety\", \"site\"],\n", " )\n", " elif display == \"grouped-horizontal\":\n", " return gr.BarPlot(\n", " fake_barley.astype({\"year\": str}),\n", " x=\"year\",\n", " y=\"yield\",\n", " color=\"year\",\n", " group=\"site\",\n", " title=\"Barley Yield by Year and Site\",\n", " group_title=\"\",\n", " tooltip=[\"yield\", \"site\", \"year\"],\n", " vertical=False,\n", " )\n", "\n", "\n", "with gr.Blocks() as bar_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " display = gr.Dropdown(\n", " choices=[\n", " \"simple\",\n", " \"stacked\",\n", " \"grouped\",\n", " \"simple-horizontal\",\n", " \"stacked-horizontal\",\n", " \"grouped-horizontal\",\n", " ],\n", " value=\"simple\",\n", " label=\"Type of Bar Plot\",\n", " )\n", " with gr.Column():\n", " plot = gr.BarPlot()\n", " display.change(bar_plot_fn, inputs=display, outputs=plot)\n", " bar_plot.load(fn=bar_plot_fn, inputs=display, outputs=plot)\n", "\n", "bar_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/barplot_component/run.ipynb b/demo/barplot_component/run.ipynb index 0fd82df174f25..309aef4a438eb 100644 --- a/demo/barplot_component/run.ipynb +++ b/demo/barplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: barplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"item\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"inventory\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "with gr.Blocks() as demo:\n", " gr.BarPlot(\n", " value=simple,\n", " x=\"item\",\n", " y=\"inventory\",\n", " title=\"Simple Bar Plot\",\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: barplot_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "\n", "simple = pd.DataFrame(\n", " {\n", " \"item\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"],\n", " \"inventory\": [28, 55, 43, 91, 81, 53, 19, 87, 52],\n", " }\n", ")\n", "\n", "with gr.Blocks() as demo:\n", " gr.BarPlot(\n", " value=simple,\n", " x=\"item\",\n", " y=\"inventory\",\n", " title=\"Simple Bar Plot\",\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_chained_events/run.ipynb b/demo/blocks_chained_events/run.ipynb index bf678bda4a75b..de44e2499d4d6 100644 --- a/demo/blocks_chained_events/run.ipynb +++ b/demo/blocks_chained_events/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_chained_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 gradio as gr\n", "import time\n", "\n", "\n", "def failure():\n", " raise gr.Error(\"This should fail!\")\n", "\n", "def exception():\n", " raise ValueError(\"Something went wrong\")\n", "\n", "def success():\n", " return True\n", "\n", "def warning_fn():\n", " gr.Warning(\"This is a warning!\")\n", "\n", "def info_fn():\n", " gr.Info(\"This is some info\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests.\"\n", " \" Also testing that the status modals show up.\")\n", " with gr.Row():\n", " result = gr.Textbox(label=\"Result\")\n", " result_2 = gr.Textbox(label=\"Consecutive Event\")\n", " with gr.Row():\n", " success_btn = gr.Button(value=\"Trigger Success\")\n", " success_btn_2 = gr.Button(value=\"Trigger Consecutive Success\")\n", " failure_btn = gr.Button(value=\"Trigger Failure\")\n", " failure_exception = gr.Button(value=\"Trigger Failure With ValueError\")\n", " with gr.Row():\n", " trigger_warning = gr.Button(value=\"Trigger Warning\")\n", " trigger_info = gr.Button(value=\"Trigger Info\")\n", "\n", " success_btn_2.click(success, None, None).success(lambda: \"First Event Trigered\", None, result).success(lambda: \"Consecutive Event Triggered\", None, result_2)\n", " success_btn.click(success, None, None).success(lambda: \"Success event triggered\", inputs=None, outputs=result)\n", " failure_btn.click(failure, None, None).success(lambda: \"Should not be triggered\", inputs=None, outputs=result)\n", " failure_exception.click(exception, None, None)\n", " trigger_warning.click(warning_fn, None, None)\n", " trigger_info.click(info_fn, None, None)\n", "\n", "demo.queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(show_error=True)"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_chained_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 gradio as gr\n", "import time\n", "\n", "\n", "def failure():\n", " raise gr.Error(\"This should fail!\")\n", "\n", "def exception():\n", " raise ValueError(\"Something went wrong\")\n", "\n", "def success():\n", " return True\n", "\n", "def warning_fn():\n", " gr.Warning(\"This is a warning!\")\n", "\n", "def info_fn():\n", " gr.Info(\"This is some info\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests.\"\n", " \" Also testing that the status modals show up.\")\n", " with gr.Row():\n", " result = gr.Textbox(label=\"Result\")\n", " result_2 = gr.Textbox(label=\"Consecutive Event\")\n", " with gr.Row():\n", " success_btn = gr.Button(value=\"Trigger Success\")\n", " success_btn_2 = gr.Button(value=\"Trigger Consecutive Success\")\n", " failure_btn = gr.Button(value=\"Trigger Failure\")\n", " failure_exception = gr.Button(value=\"Trigger Failure With ValueError\")\n", " with gr.Row():\n", " trigger_warning = gr.Button(value=\"Trigger Warning\")\n", " trigger_info = gr.Button(value=\"Trigger Info\")\n", "\n", " success_btn_2.click(success, None, None).success(lambda: \"First Event Trigered\", None, result).success(lambda: \"Consecutive Event Triggered\", None, result_2)\n", " success_btn.click(success, None, None).success(lambda: \"Success event triggered\", inputs=None, outputs=result)\n", " failure_btn.click(failure, None, None).success(lambda: \"Should not be triggered\", inputs=None, outputs=result)\n", " failure_exception.click(exception, None, None)\n", " trigger_warning.click(warning_fn, None, None)\n", " trigger_info.click(info_fn, None, None)\n", "\n", "demo.queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(show_error=True)"]}], "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 index 95c99c765e5ad..dc800e0d71335 100644 --- a/demo/blocks_component_shortcut/run.ipynb +++ b/demo/blocks_component_shortcut/run.ipynb @@ -1 +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 +{"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 index 124c0deae2154..6ca9dfb89a718 100644 --- a/demo/blocks_essay/run.ipynb +++ b/demo/blocks_essay/run.ipynb @@ -1 +1,5 @@ -{"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(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", " with gr.Row():\n", " num = gr.Number(minimum=0, maximum=100, label=\"input\")\n", " out = gr.Number(label=\"output\")\n", " minimum_slider = gr.Slider(0, 100, 0, label=\"min\")\n", " maximum_slider = gr.Slider(0, 100, 100, label=\"max\")\n", "\n", " def reset_bounds(minimum, maximum):\n", " return gr.Number(minimum=minimum, maximum=maximum)\n", " \n", " minimum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " maximum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " num.submit(lambda x:x, num, out)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", " with gr.Row():\n", " num = gr.Number(minimum=0, maximum=100, label=\"input\")\n", " out = gr.Number(label=\"output\")\n", " minimum_slider = gr.Slider(0, 100, 0, label=\"min\")\n", " maximum_slider = gr.Slider(0, 100, 100, label=\"max\")\n", "\n", " def reset_bounds(minimum, maximum):\n", " return gr.Number(minimum=minimum, maximum=maximum)\n", " \n", " minimum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " maximum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " num.submit(lambda x:x, num, out)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", " with gr.Row():\n", " num = gr.Number(minimum=0, maximum=100, label=\"input\")\n", " out = gr.Number(label=\"output\")\n", " minimum_slider = gr.Slider(0, 100, 0, label=\"min\")\n", " maximum_slider = gr.Slider(0, 100, 100, label=\"max\")\n", "\n", " def reset_bounds(minimum, maximum):\n", " return gr.Number(minimum=minimum, maximum=maximum)\n", " \n", " minimum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " maximum_slider.change(reset_bounds, [minimum_slider, maximum_slider], outputs=num)\n", " num.submit(lambda x:x, num, out)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/blocks_essay_simple/run.ipynb b/demo/blocks_essay_simple/run.ipynb index a378968e215ac..bb226466ff647 100644 --- a/demo/blocks_essay_simple/run.ipynb +++ b/demo/blocks_essay_simple/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_essay_simple"]}, {"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(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_essay_simple"]}, {"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(lines=2, visible=True)\n", " elif choice == \"long\":\n", " return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n", " else:\n", " return gr.Textbox(visible=False)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " radio = gr.Radio(\n", " [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n", " )\n", " text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)\n", " radio.change(fn=change_textbox, inputs=radio, outputs=text)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_flag/run.ipynb b/demo/blocks_flag/run.ipynb index 3159e1c11690f..504089245202b 100644 --- a/demo/blocks_flag/run.ipynb +++ b/demo/blocks_flag/run.ipynb @@ -1 +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 +{"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 index 96dd33e5d89c0..d8bede64f904e 100644 --- a/demo/blocks_flashcards/run.ipynb +++ b/demo/blocks_flashcards/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_flashcards"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import random\n", "\n", "import gradio as gr\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " \"Load the flashcards in the table below, then use the Practice tab to practice.\"\n", " )\n", "\n", " with gr.Tab(\"Word Bank\"):\n", " flashcards_table = gr.Dataframe(headers=[\"front\", \"back\"], type=\"array\")\n", " with gr.Tab(\"Practice\"):\n", " with gr.Row():\n", " with gr.Column():\n", " front = gr.Textbox(label=\"Prompt\")\n", " with gr.Row():\n", " new_btn = gr.Button(\"New Card\")\n", " flip_btn = gr.Button(\"Flip Card\")\n", " with gr.Column(visible=False) as answer_col:\n", " back = gr.Textbox(label=\"Answer\")\n", " selected_card = gr.State()\n", " with gr.Row():\n", " correct_btn = gr.Button(\"Correct\")\n", " incorrect_btn = gr.Button(\"Incorrect\")\n", "\n", " with gr.Tab(\"Results\"):\n", " results = gr.State(value={})\n", " correct_field = gr.Markdown(\"# Correct: 0\")\n", " incorrect_field = gr.Markdown(\"# Incorrect: 0\")\n", " gr.Markdown(\"Card Statistics: \")\n", " results_table = gr.Dataframe(headers=[\"Card\", \"Correct\", \"Incorrect\"])\n", "\n", " def load_new_card(flashcards):\n", " card = random.choice(flashcards)\n", " return (\n", " card,\n", " card[0],\n", " gr.Column(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(visible=True)\n", "\n", " flip_btn.click(flip_card, [selected_card], [back, answer_col])\n", "\n", " def mark_correct(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][0] += 1\n", " correct_count = sum(result[0] for result in results.values())\n", " return (\n", " results,\n", " f\"# Correct: {correct_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " def mark_incorrect(card, results):\n", " if card[0] not in results:\n", " results[card[0]] = [0, 0]\n", " results[card[0]][1] += 1\n", " incorrect_count = sum(result[1] for result in results.values())\n", " return (\n", " results,\n", " f\"# Inorrect: {incorrect_count}\",\n", " [[front, scores[0], scores[1]] for front, scores in results.items()],\n", " )\n", "\n", " correct_btn.click(\n", " mark_correct,\n", " [selected_card, results],\n", " [results, correct_field, results_table],\n", " )\n", "\n", " incorrect_btn.click(\n", " mark_incorrect,\n", " [selected_card, results],\n", " [results, incorrect_field, results_table],\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_flashcards"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import random\n", "\n", "import gradio as gr\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " \"Load the flashcards in the table below, then use the Practice tab to practice.\"\n", " )\n", "\n", " with gr.Tab(\"Word Bank\"):\n", " flashcards_table = gr.Dataframe(headers=[\"front\", \"back\"], type=\"array\")\n", " with gr.Tab(\"Practice\"):\n", " with gr.Row():\n", " with gr.Column():\n", " front = gr.Textbox(label=\"Prompt\")\n", " with gr.Row():\n", " new_btn = gr.Button(\"New Card\")\n", " flip_btn = gr.Button(\"Flip Card\")\n", " with gr.Column(visible=False) as answer_col:\n", " back = gr.Textbox(label=\"Answer\")\n", " selected_card = gr.State()\n", " with gr.Row():\n", " correct_btn = gr.Button(\"Correct\")\n", " incorrect_btn = gr.Button(\"Incorrect\")\n", "\n", " with gr.Tab(\"Results\"):\n", " results = gr.State(value={})\n", " correct_field = gr.Markdown(\"# Correct: 0\")\n", " incorrect_field = gr.Markdown(\"# Incorrect: 0\")\n", " gr.Markdown(\"Card Statistics: \")\n", " results_table = gr.Dataframe(headers=[\"Card\", \"Correct\", \"Incorrect\"])\n", "\n", " def load_new_card(flashcards):\n", " card = random.choice(flashcards)\n", " return (\n", " card,\n", " card[0],\n", " gr.Column(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(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 index a4f48e1867856..8fc016f28250a 100644 --- a/demo/blocks_flipper/run.ipynb +++ b/demo/blocks_flipper/run.ipynb @@ -1 +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", "\n", "def flip_text(x):\n", " return x[::-1]\n", "\n", "\n", "def flip_image(x):\n", " return np.fliplr(x)\n", "\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()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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", "\n", "def flip_text(x):\n", " return x[::-1]\n", "\n", "\n", "def flip_image(x):\n", " return np.fliplr(x)\n", "\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()\n"]}], "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 index ee6a47e2e0ff1..5980197cc1470 100644 --- a/demo/blocks_form/run.ipynb +++ b/demo/blocks_form/run.ipynb @@ -1 +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\", minimum=0, maximum=100)\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.Textbox(value=\"Enter name\", visible=True)}\n", " return {\n", " output_col: gr.Column(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()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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\", minimum=0, maximum=100)\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.Textbox(value=\"Enter name\", visible=True)}\n", " return {\n", " output_col: gr.Column(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()\n"]}], "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 index 4b935ce032dd6..9300205870350 100644 --- a/demo/blocks_gpt/run.ipynb +++ b/demo/blocks_gpt/run.ipynb @@ -1 +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.load(\"huggingface/gpt2-xl\")\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 +{"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.load(\"huggingface/gpt2-xl\")\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_group/run.ipynb b/demo/blocks_group/run.ipynb index 90a5a5f070695..15b658417cbf5 100644 --- a/demo/blocks_group/run.ipynb +++ b/demo/blocks_group/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_group"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"### This is a couple of elements without any gr.Group. Form elements naturally group together anyway.\")\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### This is the same set put in a gr.Group.\")\n", " with gr.Group():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row, no group.\")\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row in a group.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Several rows grouped together.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " with gr.Row():\n", " gr.Image()\n", " gr.Audio()\n", "\n", " gr.Markdown(\"### Several columns grouped together. If columns are uneven, there is a gray group background.\")\n", " with gr.Group():\n", " with gr.Row():\n", " with gr.Column():\n", " name = gr.Textbox(label=\"Name\")\n", " btn = gr.Button(\"Hello\")\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " gr.Number()\n", " gr.Textbox()\n", " with gr.Column():\n", " gr.Image()\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " with gr.Row():\n", " gr.Number(scale=2)\n", " gr.Textbox()\n", "\n", " gr.Markdown(\"### container=False removes label, padding, and block border, placing elements 'directly' on background.\")\n", " gr.Radio([1,2,3], container=False)\n", " gr.Textbox(container=False)\n", " gr.Image(\"https://picsum.photos/id/237/200/300\", container=False, height=200)\n", "\n", " gr.Markdown(\"### Textbox, Dropdown, and Number input boxes takes up full space when within a group without a container.\")\n", "\n", "\n", " with gr.Group():\n", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(show_label=False, container=False)\n", " greet_btn = gr.Button(\"Greet\")\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False)\n", " gr.Textbox(container=False)\n", " gr.Number(container=False)\n", " gr.Image(height=100)\n", " greet_btn.click(fn=greet, inputs=name, outputs=output, api_name=\"greet\")\n", "\n", "\n", " gr.Markdown(\"### More examples\")\n", "\n", " with gr.Group():\n", " gr.Chatbot()\n", " with gr.Row():\n", " name = gr.Textbox(label=\"Prompot\", container=False)\n", " go = gr.Button(\"go\", scale=0)\n", "\n", " with gr.Column():\n", " gr.Radio([1,2,3], container=False)\n", " gr.Slider(0, 20, container=False)\n", "\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " gr.Number(container=False)\n", " gr.Textbox(container=False)\n", "\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " with gr.Column():\n", " gr.Number(container=False)\n", " with gr.Column():\n", " gr.Textbox(container=False)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_group"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"### This is a couple of elements without any gr.Group. Form elements naturally group together anyway.\")\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### This is the same set put in a gr.Group.\")\n", " with gr.Group():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row, no group.\")\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Now in a Row in a group.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " gr.Image()\n", " gr.Slider()\n", "\n", " gr.Markdown(\"### Several rows grouped together.\")\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Textbox(\"A\")\n", " gr.Number(3)\n", " gr.Button()\n", " with gr.Row():\n", " gr.Image()\n", " gr.Audio()\n", "\n", " gr.Markdown(\"### Several columns grouped together. If columns are uneven, there is a gray group background.\")\n", " with gr.Group():\n", " with gr.Row():\n", " with gr.Column():\n", " name = gr.Textbox(label=\"Name\")\n", " btn = gr.Button(\"Hello\")\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " gr.Number()\n", " gr.Textbox()\n", " with gr.Column():\n", " gr.Image()\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True)\n", " with gr.Row():\n", " gr.Number(scale=2)\n", " gr.Textbox()\n", "\n", " gr.Markdown(\"### container=False removes label, padding, and block border, placing elements 'directly' on background.\")\n", " gr.Radio([1,2,3], container=False)\n", " gr.Textbox(container=False)\n", " gr.Image(\"https://picsum.photos/id/237/200/300\", container=False, height=200)\n", "\n", " gr.Markdown(\"### Textbox, Dropdown, and Number input boxes takes up full space when within a group without a container.\")\n", "\n", "\n", " with gr.Group():\n", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(show_label=False, container=False)\n", " greet_btn = gr.Button(\"Greet\")\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False)\n", " gr.Textbox(container=False)\n", " gr.Number(container=False)\n", " gr.Image(height=100)\n", " greet_btn.click(fn=greet, inputs=name, outputs=output, api_name=\"greet\")\n", "\n", "\n", " gr.Markdown(\"### More examples\")\n", "\n", " with gr.Group():\n", " gr.Chatbot()\n", " with gr.Row():\n", " name = gr.Textbox(label=\"Prompot\", container=False)\n", " go = gr.Button(\"go\", scale=0)\n", "\n", " with gr.Column():\n", " gr.Radio([1,2,3], container=False)\n", " gr.Slider(0, 20, container=False)\n", "\n", " with gr.Group():\n", " with gr.Row():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " gr.Number(container=False)\n", " gr.Textbox(container=False)\n", "\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Dropdown([\"a\", \"b\", \"c\"], interactive=True, container=False, elem_id=\"here2\")\n", " with gr.Column():\n", " gr.Number(container=False)\n", " with gr.Column():\n", " gr.Textbox(container=False)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_hello/run.ipynb b/demo/blocks_hello/run.ipynb index eea80a1eee39f..e7ac92072f123 100644 --- a/demo/blocks_hello/run.ipynb +++ b/demo/blocks_hello/run.ipynb @@ -1 +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 +{"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 index b2bb1997a2385..93b3d9d876954 100644 --- a/demo/blocks_inputs/run.ipynb +++ b/demo/blocks_inputs/run.ipynb @@ -1 +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 +{"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 index da7d3388b667e..704c311d4a9fb 100644 --- a/demo/blocks_interpretation/run.ipynb +++ b/demo/blocks_interpretation/run.ipynb @@ -1 +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.pyplot as plt\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 +{"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.pyplot as plt\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 index e18ac6911e277..9158608ec53b6 100644 --- a/demo/blocks_joined/run.ipynb +++ b/demo/blocks_joined/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_joined"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/blocks_joined/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from time import sleep\n", "import gradio as gr\n", "import os\n", "\n", "cheetah = os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\")\n", "\n", "\n", "def img(text):\n", " sleep(3)\n", " return [\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " cheetah,\n", " ]\n", "\n", "\n", "with gr.Blocks(css=\".container { max-width: 800px; margin: auto; }\") as demo:\n", " gr.Markdown(\"

DALL\u00b7E mini

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

DALL\u00b7E mini

\")\n", " gr.Markdown(\n", " \"DALL\u00b7E mini is an AI model that generates images from any prompt you give!\"\n", " )\n", " with gr.Group():\n", " with gr.Row(equal_height=True):\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " container=False,\n", " )\n", " btn = gr.Button(\"Run\", scale=0)\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " columns=(1, 3),\n", " height=\"auto\",\n", " )\n", " btn.click(img, inputs=text, outputs=gallery)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n", "\n", "\n", "# margin = (TOP, RIGHT, BOTTOM, LEFT)\n", "# rounded = (TOPLEFT, TOPRIGHT, BOTTOMRIGHT, BOTTOMLEFT)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_js_methods/run.ipynb b/demo/blocks_js_methods/run.ipynb index fdf6f4dcbf935..f20abe643823a 100644 --- a/demo/blocks_js_methods/run.ipynb +++ b/demo/blocks_js_methods/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_js_methods"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "blocks = gr.Blocks()\n", "\n", "with blocks as demo:\n", " subject = gr.Textbox(placeholder=\"subject\")\n", " verb = gr.Radio([\"ate\", \"loved\", \"hated\"])\n", " object = gr.Textbox(placeholder=\"object\")\n", "\n", " with gr.Row():\n", " btn = gr.Button(\"Create sentence.\")\n", " reverse_btn = gr.Button(\"Reverse sentence.\")\n", " foo_bar_btn = gr.Button(\"Append foo\")\n", " reverse_then_to_the_server_btn = gr.Button(\n", " \"Reverse sentence and send to server.\"\n", " )\n", "\n", " def sentence_maker(w1, w2, w3):\n", " return f\"{w1} {w2} {w3}\"\n", "\n", " output1 = gr.Textbox(label=\"output 1\")\n", " output2 = gr.Textbox(label=\"verb\")\n", " output3 = gr.Textbox(label=\"verb reversed\")\n", " output4 = gr.Textbox(label=\"front end process and then send to backend\")\n", "\n", " btn.click(sentence_maker, [subject, verb, object], output1)\n", " reverse_btn.click(\n", " None, [subject, verb, object], output2, _js=\"(s, v, o) => o + ' ' + v + ' ' + s\"\n", " )\n", " verb.change(lambda x: x, verb, output3, _js=\"(x) => [...x].reverse().join('')\")\n", " foo_bar_btn.click(None, [], subject, _js=\"(x) => x + ' foo'\")\n", "\n", " reverse_then_to_the_server_btn.click(\n", " sentence_maker,\n", " [subject, verb, object],\n", " output4,\n", " _js=\"(s, v, o) => [s, v, o].map(x => [...x].reverse().join(''))\",\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_js_methods"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "blocks = gr.Blocks()\n", "\n", "with blocks as demo:\n", " subject = gr.Textbox(placeholder=\"subject\")\n", " verb = gr.Radio([\"ate\", \"loved\", \"hated\"])\n", " object = gr.Textbox(placeholder=\"object\")\n", "\n", " with gr.Row():\n", " btn = gr.Button(\"Create sentence.\")\n", " reverse_btn = gr.Button(\"Reverse sentence.\")\n", " foo_bar_btn = gr.Button(\"Append foo\")\n", " reverse_then_to_the_server_btn = gr.Button(\n", " \"Reverse sentence and send to server.\"\n", " )\n", "\n", " def sentence_maker(w1, w2, w3):\n", " return f\"{w1} {w2} {w3}\"\n", "\n", " output1 = gr.Textbox(label=\"output 1\")\n", " output2 = gr.Textbox(label=\"verb\")\n", " output3 = gr.Textbox(label=\"verb reversed\")\n", " output4 = gr.Textbox(label=\"front end process and then send to backend\")\n", "\n", " btn.click(sentence_maker, [subject, verb, object], output1)\n", " reverse_btn.click(\n", " None, [subject, verb, object], output2, _js=\"(s, v, o) => o + ' ' + v + ' ' + s\"\n", " )\n", " verb.change(lambda x: x, verb, output3, _js=\"(x) => [...x].reverse().join('')\")\n", " foo_bar_btn.click(None, [], subject, _js=\"(x) => x + ' foo'\")\n", "\n", " reverse_then_to_the_server_btn.click(\n", " sentence_maker,\n", " [subject, verb, object],\n", " output4,\n", " _js=\"(s, v, o) => [s, v, o].map(x => [...x].reverse().join(''))\",\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_kinematics/run.ipynb b/demo/blocks_kinematics/run.ipynb index fda5b6341dbce..dfc050ca61ce4 100644 --- a/demo/blocks_kinematics/run.ipynb +++ b/demo/blocks_kinematics/run.ipynb @@ -1 +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 pandas as pd\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)\n", "\n", " x = (v * timemat) * np.cos(theta)\n", " y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))\n", " df = pd.DataFrame({\"x\": x, \"y\": y})\n", " return df\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " r\"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \\cdot \\frac{\\sin(2\\theta)}{g}$\"\n", " )\n", "\n", " with gr.Row():\n", " speed = gr.Slider(1, 30, 25, label=\"Speed\")\n", " angle = gr.Slider(0, 90, 45, label=\"Angle\")\n", " output = gr.LinePlot(\n", " x=\"x\",\n", " y=\"y\",\n", " overlay_point=True,\n", " tooltip=[\"x\", \"y\"],\n", " x_lim=[0, 100],\n", " y_lim=[0, 60],\n", " width=350,\n", " height=300,\n", " )\n", " btn = gr.Button(value=\"Run\")\n", " btn.click(plot, [speed, angle], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_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 pandas as pd\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)\n", "\n", " x = (v * timemat) * np.cos(theta)\n", " y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))\n", " df = pd.DataFrame({\"x\": x, \"y\": y})\n", " return df\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " gr.Markdown(\n", " r\"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \\cdot \\frac{\\sin(2\\theta)}{g}$\"\n", " )\n", "\n", " with gr.Row():\n", " speed = gr.Slider(1, 30, 25, label=\"Speed\")\n", " angle = gr.Slider(0, 90, 45, label=\"Angle\")\n", " output = gr.LinePlot(\n", " x=\"x\",\n", " y=\"y\",\n", " overlay_point=True,\n", " tooltip=[\"x\", \"y\"],\n", " x_lim=[0, 100],\n", " y_lim=[0, 60],\n", " width=350,\n", " height=300,\n", " )\n", " btn = gr.Button(value=\"Run\")\n", " btn.click(plot, [speed, angle], output)\n", "\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_kitchen_sink/run.ipynb b/demo/blocks_kitchen_sink/run.ipynb index 10128f8ff735f..c8b6dc27e30e4 100644 --- a/demo/blocks_kitchen_sink/run.ipynb +++ b/demo/blocks_kitchen_sink/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_kitchen_sink"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import time\n", "from os.path import abspath, join, pardir\n", "\n", "KS_FILES = abspath(join(__file__, pardir, pardir, \"kitchen_sink\", \"files\"))\n", "\n", "base_theme = gr.themes.Base()\n", "default_theme = gr.themes.Default()\n", "monochrome_theme = gr.themes.Monochrome()\n", "soft_theme = gr.themes.Soft()\n", "glass_theme = gr.themes.Glass()\n", "\n", "with gr.Blocks(theme=base_theme) as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Blocks Kitchen Sink\n", " This is a demo of most Gradio features. Test all themes and toggle dark mode\n", " ## Elements\n", " - Use of Rows, Columns, Tabs, and Accordion\n", " - Use of Form elements: Textbox, Dropdown, Checkbox, Radio, Slider\n", " ## Other\n", " Other stuff\n", " - Buttons of variants: \"primary\", \"secondary\", \"stop\"\n", " - Embedded interface\n", " - Custom progress bar\n", " \"\"\"\n", " )\n", " toggle_dark = gr.Button(\"Toggle Dark\", scale=0)\n", " toggle_dark.click(\n", " None,\n", " _js=\"\"\"\n", " () => { \n", " document.body.classList.toggle('dark');\n", " }\n", " \"\"\",\n", " )\n", " theme_selector = gr.Radio(\n", " [\"Base\", \"Default\", \"Monochrome\", \"Soft\", \"Glass\"],\n", " value=\"Base\",\n", " label=\"Theme\",\n", " )\n", " theme_selector.change(\n", " None,\n", " theme_selector,\n", " None,\n", " _js=f\"\"\"\n", " (theme) => {{\n", " if (!document.querySelector('.theme-css')) {{\n", " var theme_elem = document.createElement('style');\n", " theme_elem.classList.add('theme-css');\n", " document.head.appendChild(theme_elem);\n", "\n", " var link_elem = document.createElement('link');\n", " link_elem.classList.add('link-css');\n", " link_elem.rel = 'stylesheet';\n", " document.head.appendChild(link_elem);\n", " }} else {{\n", " var theme_elem = document.querySelector('.theme-css');\n", " var link_elem = document.querySelector('.link-css');\n", " }}\n", " if (theme == \"Base\") {{\n", " var theme_css = `{base_theme._get_theme_css()}`;\n", " var link_css = `{base_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Default\") {{\n", " var theme_css = `{default_theme._get_theme_css()}`;\n", " var link_css = `{default_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Monochrome\") {{\n", " var theme_css = `{monochrome_theme._get_theme_css()}`;\n", " var link_css = `{monochrome_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Soft\") {{\n", " var theme_css = `{soft_theme._get_theme_css()}`;\n", " var link_css = `{soft_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Glass\") {{\n", " var theme_css = `{glass_theme._get_theme_css()}`;\n", " var link_css = `{glass_theme._stylesheets[0]}`;\n", " }}\n", " theme_elem.innerHTML = theme_css;\n", " link_elem.href = link_css;\n", " }}\n", " \"\"\",\n", " )\n", "\n", " name = gr.Textbox(\n", " label=\"Name (select)\",\n", " info=\"Full name, including middle name. No special characters.\",\n", " placeholder=\"John Doe\",\n", " value=\"John Doe\",\n", " interactive=True,\n", " )\n", "\n", " with gr.Row():\n", " slider1 = gr.Slider(label=\"Slider 1\")\n", " slider2 = gr.Slider(label=\"Slider 2\")\n", " checkboxes = gr.CheckboxGroup([\"A\", \"B\", \"C\"], label=\"Checkbox Group (select)\")\n", "\n", " with gr.Row():\n", " with gr.Column(variant=\"panel\", scale=1):\n", " gr.Markdown(\"## Panel 1\")\n", " radio = gr.Radio(\n", " [\"A\", \"B\", \"C\"],\n", " label=\"Radio (select)\",\n", " info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n", " )\n", " drop = gr.Dropdown([\"Option 1\", \"Option 2\", \"Option 3\"], show_label=False)\n", " drop_2 = gr.Dropdown(\n", " [\"Option A\", \"Option B\", \"Option C\"],\n", " multiselect=True,\n", " value=[\"Option A\"],\n", " label=\"Dropdown (select)\",\n", " interactive=True,\n", " )\n", " check = gr.Checkbox(label=\"Go\")\n", " with gr.Column(variant=\"panel\", scale=2):\n", " img = gr.Image(\n", " \"https://picsum.photos/536/354\",\n", " label=\"Image\",\n", " height=320,\n", " )\n", " with gr.Row():\n", " go_btn = gr.Button(\"Go\", label=\"Primary Button\", variant=\"primary\")\n", " clear_btn = gr.Button(\n", " \"Clear\", label=\"Secondary Button\", variant=\"secondary\"\n", " )\n", "\n", " def go(*args):\n", " time.sleep(3)\n", " return \"https://i.ibb.co/6BgKdSj/groot.jpg\"\n", "\n", " go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name=\"go\")\n", "\n", " def clear():\n", " time.sleep(0.2)\n", " return None\n", "\n", " clear_btn.click(clear, None, img)\n", "\n", " with gr.Row():\n", " btn1 = gr.Button(\"Button 1\", size=\"sm\")\n", " btn2 = gr.UploadButton(size=\"sm\")\n", " stop_btn = gr.Button(\n", " \"Stop\", label=\"Stop Button\", variant=\"stop\", size=\"sm\"\n", " )\n", "\n", " gr.Examples(\n", " examples=[join(KS_FILES, \"lion.jpg\"), join(KS_FILES, \"tower.jpg\")],\n", " inputs=img,\n", " )\n", "\n", " gr.Examples(\n", " examples=[\n", " [\"A\", \"Option 1\", [\"Option B\"], True, join(KS_FILES, \"lion.jpg\")],\n", " [\n", " \"B\",\n", " \"Option 2\",\n", " [\"Option B\", \"Option C\"],\n", " False,\n", " join(KS_FILES, \"tower.jpg\"),\n", " ],\n", " ],\n", " inputs=[radio, drop, drop_2, check, img],\n", " label=\"Examples (select)\",\n", " )\n", "\n", " gr.Markdown(\"## Media Files\")\n", "\n", " with gr.Tabs() as tabs:\n", " with gr.Tab(\"Audio\"):\n", " with gr.Row():\n", " gr.Audio()\n", " gr.Audio(source=\"microphone\")\n", " gr.Audio(join(KS_FILES, \"cantina.wav\"))\n", " with gr.Tab(\"Other\"):\n", " # gr.Image(source=\"webcam\")\n", " gr.HTML(\n", " \"
\"\n", " )\n", " with gr.Row():\n", " dataframe = gr.Dataframe(\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label=\"Dataframe (select)\"\n", " )\n", " gr.JSON(\n", " value={\"a\": 1, \"b\": 2, \"c\": {\"test\": \"a\", \"test2\": [1, 2, 3]}}, label=\"JSON\"\n", " )\n", " label = gr.Label(\n", " value={\"cat\": 0.7, \"dog\": 0.2, \"fish\": 0.1}, label=\"Label (select)\"\n", " )\n", " file = gr.File(label=\"File (select)\")\n", " with gr.Row():\n", " gr.ColorPicker()\n", " gr.Video(join(KS_FILES, \"world.mp4\"))\n", " gallery = gr.Gallery(\n", " [\n", " (join(KS_FILES, \"lion.jpg\"), \"lion\"),\n", " (join(KS_FILES, \"logo.png\"), \"logo\"),\n", " (join(KS_FILES, \"tower.jpg\"), \"tower\"),\n", " ],\n", " label=\"Gallery (select)\",\n", " )\n", "\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " highlight = gr.HighlightedText(\n", " [[\"The\", \"art\"], [\"dog\", \"noun\"], [\"is\", None], [\"fat\", \"adj\"]],\n", " label=\"Highlighted Text (select)\",\n", " )\n", " chatbot = gr.Chatbot([[\"Hello\", \"Hi\"]], label=\"Chatbot (select)\")\n", " chat_btn = gr.Button(\"Add messages\")\n", "\n", " def chat(history):\n", " time.sleep(2)\n", " yield [[\"How are you?\", \"I am good.\"]]\n", " time\n", "\n", " chat_btn.click(\n", " lambda history: history\n", " + [[\"How are you?\", \"I am good.\"]]\n", " + (time.sleep(2) or []),\n", " chatbot,\n", " chatbot,\n", " )\n", " with gr.Column(scale=1):\n", " with gr.Accordion(\"Select Info\"):\n", " gr.Markdown(\n", " \"Click on any part of any component with '(select)' in the label and see the SelectData data here.\"\n", " )\n", " select_index = gr.Textbox(label=\"Index\")\n", " select_value = gr.Textbox(label=\"Value\")\n", " select_selected = gr.Textbox(label=\"Selected\")\n", "\n", " selectables = [\n", " name,\n", " checkboxes,\n", " radio,\n", " drop_2,\n", " dataframe,\n", " label,\n", " file,\n", " highlight,\n", " chatbot,\n", " gallery,\n", " tabs,\n", " ]\n", "\n", " def select_data(evt: gr.SelectData):\n", " return [\n", " evt.index,\n", " evt.value,\n", " evt.selected,\n", " ]\n", "\n", " for selectable in selectables:\n", " selectable.select(\n", " select_data,\n", " None,\n", " [select_index, select_value, select_selected],\n", " )\n", "\n", " gr.Markdown(\"## Dataset Examples\")\n", "\n", " component_example_set = [\n", " (gr.Audio(render=False), join(KS_FILES, \"cantina.wav\")),\n", " (gr.Checkbox(render=False), True),\n", " (gr.CheckboxGroup(render=False, choices=[\"A\", \"B\"]), [\"A\", \"B\"]),\n", " (gr.ColorPicker(render=False), \"#FF0000\"),\n", " (gr.Dataframe(render=False), [[1, 2, 3], [4, 5, 6]]),\n", " (gr.Dropdown(render=False), \"A\"),\n", " (gr.File(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.HTML(render=False), \"
Test
\"),\n", " (gr.Image(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.Markdown(render=False), \"# Test\"),\n", " (gr.Number(render=False), 1),\n", " (gr.Radio(render=False), \"A\"),\n", " (gr.Slider(render=False), 1),\n", " (gr.Textbox(render=False), \"A\"),\n", " (gr.Video(render=False), join(KS_FILES, \"world.mp4\")),\n", " ]\n", " gr.Dataset(\n", " components=[c for c, _ in component_example_set],\n", " samples=[[e for _, e in component_example_set]],\n", " )\n", "\n", " with gr.Tabs():\n", " for c, e in component_example_set:\n", " with gr.Tab(c.__class__.__name__):\n", " gr.Dataset(components=[c], samples=[[e]] * 3)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(allowed_paths=[KS_FILES])\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_kitchen_sink"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import time\n", "from os.path import abspath, join, pardir\n", "\n", "KS_FILES = abspath(join(__file__, pardir, pardir, \"kitchen_sink\", \"files\"))\n", "\n", "base_theme = gr.themes.Base()\n", "default_theme = gr.themes.Default()\n", "monochrome_theme = gr.themes.Monochrome()\n", "soft_theme = gr.themes.Soft()\n", "glass_theme = gr.themes.Glass()\n", "\n", "with gr.Blocks(theme=base_theme) as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Blocks Kitchen Sink\n", " This is a demo of most Gradio features. Test all themes and toggle dark mode\n", " ## Elements\n", " - Use of Rows, Columns, Tabs, and Accordion\n", " - Use of Form elements: Textbox, Dropdown, Checkbox, Radio, Slider\n", " ## Other\n", " Other stuff\n", " - Buttons of variants: \"primary\", \"secondary\", \"stop\"\n", " - Embedded interface\n", " - Custom progress bar\n", " \"\"\"\n", " )\n", " toggle_dark = gr.Button(\"Toggle Dark\", scale=0)\n", " toggle_dark.click(\n", " None,\n", " _js=\"\"\"\n", " () => { \n", " document.body.classList.toggle('dark');\n", " }\n", " \"\"\",\n", " )\n", " theme_selector = gr.Radio(\n", " [\"Base\", \"Default\", \"Monochrome\", \"Soft\", \"Glass\"],\n", " value=\"Base\",\n", " label=\"Theme\",\n", " )\n", " theme_selector.change(\n", " None,\n", " theme_selector,\n", " None,\n", " _js=f\"\"\"\n", " (theme) => {{\n", " if (!document.querySelector('.theme-css')) {{\n", " var theme_elem = document.createElement('style');\n", " theme_elem.classList.add('theme-css');\n", " document.head.appendChild(theme_elem);\n", "\n", " var link_elem = document.createElement('link');\n", " link_elem.classList.add('link-css');\n", " link_elem.rel = 'stylesheet';\n", " document.head.appendChild(link_elem);\n", " }} else {{\n", " var theme_elem = document.querySelector('.theme-css');\n", " var link_elem = document.querySelector('.link-css');\n", " }}\n", " if (theme == \"Base\") {{\n", " var theme_css = `{base_theme._get_theme_css()}`;\n", " var link_css = `{base_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Default\") {{\n", " var theme_css = `{default_theme._get_theme_css()}`;\n", " var link_css = `{default_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Monochrome\") {{\n", " var theme_css = `{monochrome_theme._get_theme_css()}`;\n", " var link_css = `{monochrome_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Soft\") {{\n", " var theme_css = `{soft_theme._get_theme_css()}`;\n", " var link_css = `{soft_theme._stylesheets[0]}`;\n", " }} else if (theme == \"Glass\") {{\n", " var theme_css = `{glass_theme._get_theme_css()}`;\n", " var link_css = `{glass_theme._stylesheets[0]}`;\n", " }}\n", " theme_elem.innerHTML = theme_css;\n", " link_elem.href = link_css;\n", " }}\n", " \"\"\",\n", " )\n", "\n", " name = gr.Textbox(\n", " label=\"Name (select)\",\n", " info=\"Full name, including middle name. No special characters.\",\n", " placeholder=\"John Doe\",\n", " value=\"John Doe\",\n", " interactive=True,\n", " )\n", "\n", " with gr.Row():\n", " slider1 = gr.Slider(label=\"Slider 1\")\n", " slider2 = gr.Slider(label=\"Slider 2\")\n", " checkboxes = gr.CheckboxGroup([\"A\", \"B\", \"C\"], label=\"Checkbox Group (select)\")\n", "\n", " with gr.Row():\n", " with gr.Column(variant=\"panel\", scale=1):\n", " gr.Markdown(\"## Panel 1\")\n", " radio = gr.Radio(\n", " [\"A\", \"B\", \"C\"],\n", " label=\"Radio (select)\",\n", " info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n", " )\n", " drop = gr.Dropdown([\"Option 1\", \"Option 2\", \"Option 3\"], show_label=False)\n", " drop_2 = gr.Dropdown(\n", " [\"Option A\", \"Option B\", \"Option C\"],\n", " multiselect=True,\n", " value=[\"Option A\"],\n", " label=\"Dropdown (select)\",\n", " interactive=True,\n", " )\n", " check = gr.Checkbox(label=\"Go\")\n", " with gr.Column(variant=\"panel\", scale=2):\n", " img = gr.Image(\n", " \"https://picsum.photos/536/354\",\n", " label=\"Image\",\n", " height=320,\n", " )\n", " with gr.Row():\n", " go_btn = gr.Button(\"Go\", label=\"Primary Button\", variant=\"primary\")\n", " clear_btn = gr.Button(\n", " \"Clear\", label=\"Secondary Button\", variant=\"secondary\"\n", " )\n", "\n", " def go(*args):\n", " time.sleep(3)\n", " return \"https://i.ibb.co/6BgKdSj/groot.jpg\"\n", "\n", " go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name=\"go\")\n", "\n", " def clear():\n", " time.sleep(0.2)\n", " return None\n", "\n", " clear_btn.click(clear, None, img)\n", "\n", " with gr.Row():\n", " btn1 = gr.Button(\"Button 1\", size=\"sm\")\n", " btn2 = gr.UploadButton(size=\"sm\")\n", " stop_btn = gr.Button(\n", " \"Stop\", label=\"Stop Button\", variant=\"stop\", size=\"sm\"\n", " )\n", "\n", " gr.Examples(\n", " examples=[join(KS_FILES, \"lion.jpg\"), join(KS_FILES, \"tower.jpg\")],\n", " inputs=img,\n", " )\n", "\n", " gr.Examples(\n", " examples=[\n", " [\"A\", \"Option 1\", [\"Option B\"], True, join(KS_FILES, \"lion.jpg\")],\n", " [\n", " \"B\",\n", " \"Option 2\",\n", " [\"Option B\", \"Option C\"],\n", " False,\n", " join(KS_FILES, \"tower.jpg\"),\n", " ],\n", " ],\n", " inputs=[radio, drop, drop_2, check, img],\n", " label=\"Examples (select)\",\n", " )\n", "\n", " gr.Markdown(\"## Media Files\")\n", "\n", " with gr.Tabs() as tabs:\n", " with gr.Tab(\"Audio\"):\n", " with gr.Row():\n", " gr.Audio()\n", " gr.Audio(source=\"microphone\")\n", " gr.Audio(join(KS_FILES, \"cantina.wav\"))\n", " with gr.Tab(\"Other\"):\n", " # gr.Image(source=\"webcam\")\n", " gr.HTML(\n", " \"
\"\n", " )\n", " with gr.Row():\n", " dataframe = gr.Dataframe(\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label=\"Dataframe (select)\"\n", " )\n", " gr.JSON(\n", " value={\"a\": 1, \"b\": 2, \"c\": {\"test\": \"a\", \"test2\": [1, 2, 3]}}, label=\"JSON\"\n", " )\n", " label = gr.Label(\n", " value={\"cat\": 0.7, \"dog\": 0.2, \"fish\": 0.1}, label=\"Label (select)\"\n", " )\n", " file = gr.File(label=\"File (select)\")\n", " with gr.Row():\n", " gr.ColorPicker()\n", " gr.Video(join(KS_FILES, \"world.mp4\"))\n", " gallery = gr.Gallery(\n", " [\n", " (join(KS_FILES, \"lion.jpg\"), \"lion\"),\n", " (join(KS_FILES, \"logo.png\"), \"logo\"),\n", " (join(KS_FILES, \"tower.jpg\"), \"tower\"),\n", " ],\n", " label=\"Gallery (select)\",\n", " )\n", "\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " highlight = gr.HighlightedText(\n", " [[\"The\", \"art\"], [\"dog\", \"noun\"], [\"is\", None], [\"fat\", \"adj\"]],\n", " label=\"Highlighted Text (select)\",\n", " )\n", " chatbot = gr.Chatbot([[\"Hello\", \"Hi\"]], label=\"Chatbot (select)\")\n", " chat_btn = gr.Button(\"Add messages\")\n", "\n", " def chat(history):\n", " time.sleep(2)\n", " yield [[\"How are you?\", \"I am good.\"]]\n", " time\n", "\n", " chat_btn.click(\n", " lambda history: history\n", " + [[\"How are you?\", \"I am good.\"]]\n", " + (time.sleep(2) or []),\n", " chatbot,\n", " chatbot,\n", " )\n", " with gr.Column(scale=1):\n", " with gr.Accordion(\"Select Info\"):\n", " gr.Markdown(\n", " \"Click on any part of any component with '(select)' in the label and see the SelectData data here.\"\n", " )\n", " select_index = gr.Textbox(label=\"Index\")\n", " select_value = gr.Textbox(label=\"Value\")\n", " select_selected = gr.Textbox(label=\"Selected\")\n", "\n", " selectables = [\n", " name,\n", " checkboxes,\n", " radio,\n", " drop_2,\n", " dataframe,\n", " label,\n", " file,\n", " highlight,\n", " chatbot,\n", " gallery,\n", " tabs,\n", " ]\n", "\n", " def select_data(evt: gr.SelectData):\n", " return [\n", " evt.index,\n", " evt.value,\n", " evt.selected,\n", " ]\n", "\n", " for selectable in selectables:\n", " selectable.select(\n", " select_data,\n", " None,\n", " [select_index, select_value, select_selected],\n", " )\n", "\n", " gr.Markdown(\"## Dataset Examples\")\n", "\n", " component_example_set = [\n", " (gr.Audio(render=False), join(KS_FILES, \"cantina.wav\")),\n", " (gr.Checkbox(render=False), True),\n", " (gr.CheckboxGroup(render=False, choices=[\"A\", \"B\"]), [\"A\", \"B\"]),\n", " (gr.ColorPicker(render=False), \"#FF0000\"),\n", " (gr.Dataframe(render=False), [[1, 2, 3], [4, 5, 6]]),\n", " (gr.Dropdown(render=False), \"A\"),\n", " (gr.File(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.HTML(render=False), \"
Test
\"),\n", " (gr.Image(render=False), join(KS_FILES, \"lion.jpg\")),\n", " (gr.Markdown(render=False), \"# Test\"),\n", " (gr.Number(render=False), 1),\n", " (gr.Radio(render=False), \"A\"),\n", " (gr.Slider(render=False), 1),\n", " (gr.Textbox(render=False), \"A\"),\n", " (gr.Video(render=False), join(KS_FILES, \"world.mp4\")),\n", " ]\n", " gr.Dataset(\n", " components=[c for c, _ in component_example_set],\n", " samples=[[e for _, e in component_example_set]],\n", " )\n", "\n", " with gr.Tabs():\n", " for c, e in component_example_set:\n", " with gr.Tab(c.__class__.__name__):\n", " gr.Dataset(components=[c], samples=[[e]] * 3)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(allowed_paths=[KS_FILES])\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_layout/run.ipynb b/demo/blocks_layout/run.ipynb index 92c54ed7d5a72..deef224dfb413 100644 --- a/demo/blocks_layout/run.ipynb +++ b/demo/blocks_layout/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_layout"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " with gr.Row():\n", " gr.Image(interactive=True, scale=2)\n", " gr.Image()\n", " with gr.Row():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\", scale=2)\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " with gr.Row():\n", " gr.Button(\"500\", scale=0, min_width=500)\n", " gr.Button(\"A\", scale=0)\n", " gr.Button(\"grow\")\n", " with gr.Row():\n", " gr.Textbox()\n", " gr.Textbox()\n", " gr.Button() \n", " with gr.Row():\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " gr.Image()\n", " with gr.Column():\n", " gr.Image(interactive=True)\n", " gr.Image()\n", " gr.Image()\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_layout"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "demo = gr.Blocks()\n", "\n", "with demo:\n", " with gr.Row():\n", " gr.Image(interactive=True, scale=2)\n", " gr.Image()\n", " with gr.Row():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\", scale=2)\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " with gr.Row():\n", " gr.Button(\"500\", scale=0, min_width=500)\n", " gr.Button(\"A\", scale=0)\n", " gr.Button(\"grow\")\n", " with gr.Row():\n", " gr.Textbox()\n", " gr.Textbox()\n", " gr.Button() \n", " with gr.Row():\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", " gr.Image()\n", " with gr.Column():\n", " gr.Image(interactive=True)\n", " gr.Image()\n", " gr.Image()\n", " gr.Textbox(label=\"Text\")\n", " gr.Number(label=\"Count\")\n", " gr.Radio(choices=[\"One\", \"Two\"])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_mask/run.ipynb b/demo/blocks_mask/run.ipynb index 47d91349e5685..254bb7e332efd 100644 --- a/demo/blocks_mask/run.ipynb +++ b/demo/blocks_mask/run.ipynb @@ -1 +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/image.png\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.webp"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from gradio.components import Markdown as md\n", "from PIL import Image\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", "io2c = gr.Interface(\n", " lambda x: x, gr.Image(source=\"canvas\", shape=(512, 512)), gr.Image()\n", ")\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", "def save_image(image):\n", " image.save(\"colorede.png\")\n", " return image\n", "\n", "\n", "img = Image.new(\"RGB\", (512, 512), (150, 150, 150))\n", "img.save(\"image.png\", \"PNG\")\n", "\n", "io5d = gr.Interface(\n", " save_image,\n", " gr.Image(\"image.png\", source=\"upload\", tool=\"color-sketch\", type=\"pil\"),\n", " gr.Image(),\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(\"**2c. Black and White Sketchpad with `shape=(512,512)`**\")\n", " io2c.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", " md(\"**5d. Color Sketchpad with image upload and a default images**\")\n", " io5d.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_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/image.png\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.jpg\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/blocks_mask/lion.webp"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from gradio.components import Markdown as md\n", "from PIL import Image\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", "io2c = gr.Interface(\n", " lambda x: x, gr.Image(source=\"canvas\", shape=(512, 512)), gr.Image()\n", ")\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", "def save_image(image):\n", " image.save(\"colorede.png\")\n", " return image\n", "\n", "\n", "img = Image.new(\"RGB\", (512, 512), (150, 150, 150))\n", "img.save(\"image.png\", \"PNG\")\n", "\n", "io5d = gr.Interface(\n", " save_image,\n", " gr.Image(\"image.png\", source=\"upload\", tool=\"color-sketch\", type=\"pil\"),\n", " gr.Image(),\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(\"**2c. Black and White Sketchpad with `shape=(512,512)`**\")\n", " io2c.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", " md(\"**5d. Color Sketchpad with image upload and a default images**\")\n", " io5d.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_multiple_event_triggers/run.ipynb b/demo/blocks_multiple_event_triggers/run.ipynb index 52d3052d5c4d4..1ada4f02c5276 100644 --- a/demo/blocks_multiple_event_triggers/run.ipynb +++ b/demo/blocks_multiple_event_triggers/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_multiple_event_triggers"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly pypistats"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pypistats\n", "from datetime import date\n", "from dateutil.relativedelta import relativedelta\n", "import pandas as pd\n", "\n", "def get_plot(lib, time):\n", " data = pypistats.overall(lib, total=True, format=\"pandas\")\n", " data = data.groupby(\"category\").get_group(\"with_mirrors\").sort_values(\"date\")\n", " start_date = date.today() - relativedelta(months=int(time.split(\" \")[0]))\n", " data = data[(data['date'] > str(start_date))]\n", " data.date = pd.to_datetime(pd.to_datetime(data.date))\n", " return gr.LinePlot(value=data, x=\"date\", y=\"downloads\",\n", " tooltip=['date', 'downloads'],\n", " title=f\"Pypi downloads of {lib} over last {time}\",\n", " overlay_point=True,\n", " height=400,\n", " width=900)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " ## Pypi Download Stats \ud83d\udcc8\n", " See live download stats for all of Hugging Face's open-source libraries \ud83e\udd17\n", " \"\"\")\n", " with gr.Row():\n", " lib = gr.Dropdown([\"transformers\", \"datasets\", \"huggingface-hub\", \"gradio\", \"accelerate\"],\n", " value=\"gradio\", label=\"Library\")\n", " time = gr.Dropdown([\"3 months\", \"6 months\", \"9 months\", \"12 months\"],\n", " value=\"3 months\", label=\"Downloads over the last...\")\n", "\n", " plt = gr.LinePlot()\n", " # You can add multiple event triggers in 2 lines like this\n", " for event in [lib.change, time.change, demo.load]:\n", " event(get_plot, [lib, time], [plt])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_multiple_event_triggers"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly pypistats"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pypistats\n", "from datetime import date\n", "from dateutil.relativedelta import relativedelta\n", "import pandas as pd\n", "\n", "def get_plot(lib, time):\n", " data = pypistats.overall(lib, total=True, format=\"pandas\")\n", " data = data.groupby(\"category\").get_group(\"with_mirrors\").sort_values(\"date\")\n", " start_date = date.today() - relativedelta(months=int(time.split(\" \")[0]))\n", " data = data[(data['date'] > str(start_date))]\n", " data.date = pd.to_datetime(pd.to_datetime(data.date))\n", " return gr.LinePlot(value=data, x=\"date\", y=\"downloads\",\n", " tooltip=['date', 'downloads'],\n", " title=f\"Pypi downloads of {lib} over last {time}\",\n", " overlay_point=True,\n", " height=400,\n", " width=900)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " ## Pypi Download Stats \ud83d\udcc8\n", " See live download stats for all of Hugging Face's open-source libraries \ud83e\udd17\n", " \"\"\")\n", " with gr.Row():\n", " lib = gr.Dropdown([\"transformers\", \"datasets\", \"huggingface-hub\", \"gradio\", \"accelerate\"],\n", " value=\"gradio\", label=\"Library\")\n", " time = gr.Dropdown([\"3 months\", \"6 months\", \"9 months\", \"12 months\"],\n", " value=\"3 months\", label=\"Downloads over the last...\")\n", "\n", " plt = gr.LinePlot()\n", " # You can add multiple event triggers in 2 lines like this\n", " for event in [lib.change, time.change, demo.load]:\n", " event(get_plot, [lib, time], [plt])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_neural_instrument_coding/run.ipynb b/demo/blocks_neural_instrument_coding/run.ipynb index c0ed94376531f..55e6aab3890df 100644 --- a/demo/blocks_neural_instrument_coding/run.ipynb +++ b/demo/blocks_neural_instrument_coding/run.ipynb @@ -1 +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", "
\"\"\"\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 +{"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", "
\"\"\"\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 index 27bc1d876828a..a2505d427420a 100644 --- a/demo/blocks_outputs/run.ipynb +++ b/demo/blocks_outputs/run.ipynb @@ -1 +1,5 @@ -{"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", " '',\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", " '',\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", " '',\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", " 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", " '',\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", " '',\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", " '',\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 +<<<<<<< HEAD +{"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", " '',\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", " '',\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", " '',\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", " 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", " '',\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", " '',\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", " '',\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} +======= +{"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", " '',\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", " '',\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", " '',\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", " '',\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", " '',\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", " '',\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} +>>>>>>> main diff --git a/demo/blocks_page_load/run.ipynb b/demo/blocks_page_load/run.ipynb index 25c31e7ad315b..dfd1ad0ed795e 100644 --- a/demo/blocks_page_load/run.ipynb +++ b/demo/blocks_page_load/run.ipynb @@ -1 +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 +{"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 index c005fbae9abb9..8a037f584a6a5 100644 --- a/demo/blocks_plug/run.ipynb +++ b/demo/blocks_plug/run.ipynb @@ -1 +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(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.ClearButton(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) as tab0:\n", " tab0.select(lambda: gr.Tabs(selected=0), None, tabs)\n", " identity_demo.render()\n", " with gr.TabItem(\"Text Input\", id=1) as tab1:\n", " tab1.select(lambda: gr.Tabs(selected=1), None, tabs)\n", " input_demo.render()\n", " with gr.TabItem(\"Text Static\", id=2) as tab2:\n", " tab2.select(lambda: gr.Tabs(selected=2), None, tabs)\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 +{"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(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.ClearButton(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) as tab0:\n", " tab0.select(lambda: gr.Tabs(selected=0), None, tabs)\n", " identity_demo.render()\n", " with gr.TabItem(\"Text Input\", id=1) as tab1:\n", " tab1.select(lambda: gr.Tabs(selected=1), None, tabs)\n", " input_demo.render()\n", " with gr.TabItem(\"Text Static\", id=2) as tab2:\n", " tab2.select(lambda: gr.Tabs(selected=2), None, tabs)\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 index 857e8e7ef3c83..52b32cb819a67 100644 --- a/demo/blocks_random_slider/run.ipynb +++ b/demo/blocks_random_slider/run.ipynb @@ -1 +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 +{"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 index 6bcf0dcdeecaf..075ff8c943334 100644 --- a/demo/blocks_scroll/run.ipynb +++ b/demo/blocks_scroll/run.ipynb @@ -1 +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", "
\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 +{"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", "
\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 index 37ce209a22eb3..0d4b6d5f41732 100644 --- a/demo/blocks_simple_squares/run.ipynb +++ b/demo/blocks_simple_squares/run.ipynb @@ -1 +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} .abc {font-family: \"Comic Sans MS\", \"Comic Sans\", cursive !important}\"\"\")\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\", elem_classes=[\"abc\", \"def\"])\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 +{"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} .abc {font-family: \"Comic Sans MS\", \"Comic Sans\", cursive !important}\"\"\")\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\", elem_classes=[\"abc\", \"def\"])\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 index 3a656fa92522e..c864e6fe66190 100644 --- a/demo/blocks_speech_text_sentiment/run.ipynb +++ b/demo/blocks_speech_text_sentiment/run.ipynb @@ -1 +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 +{"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 index ad17acc436d82..2010f8432016d 100644 --- a/demo/blocks_static/run.ipynb +++ b/demo/blocks_static/run.ipynb @@ -1 +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 +{"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 index fcff0d7d706a1..65b1b200f7a72 100644 --- a/demo/blocks_style/run.ipynb +++ b/demo/blocks_style/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_style"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks(title=\"Styling Examples\") as demo:\n", " with gr.Column(variant=\"box\"):\n", " txt = gr.Textbox(label=\"Small Textbox\", lines=1)\n", " num = gr.Number(label=\"Number\", show_label=False)\n", " slider = gr.Slider(label=\"Slider\", show_label=False)\n", " check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", " check_g = gr.CheckboxGroup(\n", " label=\"Checkbox Group\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " radio = gr.Radio(\n", " label=\"Radio\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " drop = gr.Dropdown(\n", " label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " )\n", " image = gr.Image(show_label=False)\n", " video = gr.Video(show_label=False)\n", " audio = gr.Audio(show_label=False)\n", " file = gr.File(show_label=False)\n", " df = gr.Dataframe(show_label=False)\n", " label = gr.Label(container=False)\n", " highlight = gr.HighlightedText(\n", " [(\"hello\", None), (\"goodbye\", \"-\")],\n", " color_map={\"+\": \"green\", \"-\": \"red\"},\n", " container=False,\n", " )\n", " json = gr.JSON(container=False)\n", " html = gr.HTML(show_label=False)\n", " gallery = gr.Gallery(\n", " columns=(3, 3, 1),\n", " height=\"auto\",\n", " container=False,\n", " )\n", " chat = gr.Chatbot([(\"hi\", \"good bye\")])\n", "\n", " model = gr.Model3D()\n", "\n", " md = gr.Markdown(show_label=False)\n", "\n", " highlight = gr.HighlightedText()\n", "\n", " btn = gr.Button(\"Run\")\n", "\n", " gr.Dataset(components=[txt, num])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_style"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks(title=\"Styling Examples\") as demo:\n", " with gr.Column(variant=\"box\"):\n", " txt = gr.Textbox(label=\"Small Textbox\", lines=1)\n", " num = gr.Number(label=\"Number\", show_label=False)\n", " slider = gr.Slider(label=\"Slider\", show_label=False)\n", " check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", " check_g = gr.CheckboxGroup(\n", " label=\"Checkbox Group\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " radio = gr.Radio(\n", " label=\"Radio\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " drop = gr.Dropdown(\n", " label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " )\n", " image = gr.Image(show_label=False)\n", " video = gr.Video(show_label=False)\n", " audio = gr.Audio(show_label=False)\n", " file = gr.File(show_label=False)\n", " df = gr.Dataframe(show_label=False)\n", " label = gr.Label(container=False)\n", " highlight = gr.HighlightedText(\n", " [(\"hello\", None), (\"goodbye\", \"-\")],\n", " color_map={\"+\": \"green\", \"-\": \"red\"},\n", " container=False,\n", " )\n", " json = gr.JSON(container=False)\n", " html = gr.HTML(show_label=False)\n", " gallery = gr.Gallery(\n", " columns=(3, 3, 1),\n", " height=\"auto\",\n", " container=False,\n", " )\n", " chat = gr.Chatbot([(\"hi\", \"good bye\")])\n", "\n", " model = gr.Model3D()\n", "\n", " md = gr.Markdown(show_label=False)\n", "\n", " highlight = gr.HighlightedText()\n", "\n", " btn = gr.Button(\"Run\")\n", "\n", " gr.Dataset(components=[txt, num])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_style"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks(title=\"Styling Examples\") as demo:\n", " with gr.Column(variant=\"box\"):\n", " txt = gr.Textbox(label=\"Small Textbox\", lines=1)\n", " num = gr.Number(label=\"Number\", show_label=False)\n", " slider = gr.Slider(label=\"Slider\", show_label=False)\n", " check = gr.Checkbox(label=\"Checkbox\", show_label=False)\n", " check_g = gr.CheckboxGroup(\n", " label=\"Checkbox Group\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " radio = gr.Radio(\n", " label=\"Radio\",\n", " choices=[\"One\", \"Two\", \"Three\"],\n", " show_label=False,\n", " )\n", " drop = gr.Dropdown(\n", " label=\"Dropdown\", choices=[\"One\", \"Two\", \"Three\"], show_label=False\n", " )\n", " image = gr.Image(show_label=False)\n", " video = gr.Video(show_label=False)\n", " audio = gr.Audio(show_label=False)\n", " file = gr.File(show_label=False)\n", " df = gr.Dataframe(show_label=False)\n", " ts = gr.Timeseries(show_label=False)\n", " label = gr.Label(container=False)\n", " highlight = gr.HighlightedText(\n", " [(\"hello\", None), (\"goodbye\", \"-\")],\n", " color_map={\"+\": \"green\", \"-\": \"red\"},\n", " container=False,\n", " )\n", " json = gr.JSON(container=False)\n", " html = gr.HTML(show_label=False)\n", " gallery = gr.Gallery(\n", " columns=(3, 3, 1),\n", " height=\"auto\",\n", " container=False,\n", " )\n", " chat = gr.Chatbot([(\"hi\", \"good bye\")])\n", "\n", " model = gr.Model3D()\n", "\n", " md = gr.Markdown(show_label=False)\n", "\n", " highlight = gr.HighlightedText()\n", "\n", " btn = gr.Button(\"Run\")\n", "\n", " gr.Dataset(components=[txt, num])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/blocks_textbox_max_lines/run.ipynb b/demo/blocks_textbox_max_lines/run.ipynb index 8cf2d4855b7f8..00c909378f062 100644 --- a/demo/blocks_textbox_max_lines/run.ipynb +++ b/demo/blocks_textbox_max_lines/run.ipynb @@ -1 +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 +{"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 index 285db671e5497..31eb77c2f3c4d 100644 --- a/demo/blocks_update/run.ipynb +++ b/demo/blocks_update/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: blocks_update"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Animal Generator\n", " Once you select a species, the detail panel should be visible.\n", " \"\"\"\n", " )\n", "\n", " species = gr.Radio(label=\"Animal Class\", choices=[\"Mammal\", \"Fish\", \"Bird\"])\n", " animal = gr.Dropdown(label=\"Animal\", choices=[])\n", "\n", " with gr.Column(visible=False) as details_col:\n", " weight = gr.Slider(0, 20)\n", " details = gr.Textbox(label=\"Extra Details\")\n", " generate_btn = gr.Button(\"Generate\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " species_map = {\n", " \"Mammal\": [\"Elephant\", \"Giraffe\", \"Hamster\"],\n", " \"Fish\": [\"Shark\", \"Salmon\", \"Tuna\"],\n", " \"Bird\": [\"Chicken\", \"Eagle\", \"Hawk\"],\n", " }\n", "\n", " def filter_species(species):\n", " return gr.Dropdown(\n", " choices=species_map[species], value=species_map[species][1]\n", " ), gr.Column(visible=True)\n", "\n", " species.change(filter_species, species, [animal, details_col])\n", "\n", " def filter_weight(animal):\n", " if animal in (\"Elephant\", \"Shark\", \"Giraffe\"):\n", " return gr.Slider(maximum=100)\n", " else:\n", " return gr.Slider(maximum=20)\n", "\n", " animal.change(filter_weight, animal, weight)\n", " weight.change(lambda w: gr.Textbox(lines=int(w / 10) + 1), weight, details)\n", "\n", " generate_btn.click(lambda x: x, details, output)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: blocks_update"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"\"\"\n", " # Animal Generator\n", " Once you select a species, the detail panel should be visible.\n", " \"\"\"\n", " )\n", "\n", " species = gr.Radio(label=\"Animal Class\", choices=[\"Mammal\", \"Fish\", \"Bird\"])\n", " animal = gr.Dropdown(label=\"Animal\", choices=[])\n", "\n", " with gr.Column(visible=False) as details_col:\n", " weight = gr.Slider(0, 20)\n", " details = gr.Textbox(label=\"Extra Details\")\n", " generate_btn = gr.Button(\"Generate\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " species_map = {\n", " \"Mammal\": [\"Elephant\", \"Giraffe\", \"Hamster\"],\n", " \"Fish\": [\"Shark\", \"Salmon\", \"Tuna\"],\n", " \"Bird\": [\"Chicken\", \"Eagle\", \"Hawk\"],\n", " }\n", "\n", " def filter_species(species):\n", " return gr.Dropdown(\n", " choices=species_map[species], value=species_map[species][1]\n", " ), gr.Column(visible=True)\n", "\n", " species.change(filter_species, species, [animal, details_col])\n", "\n", " def filter_weight(animal):\n", " if animal in (\"Elephant\", \"Shark\", \"Giraffe\"):\n", " return gr.Slider(maximum=100)\n", " else:\n", " return gr.Slider(maximum=20)\n", "\n", " animal.change(filter_weight, animal, weight)\n", " weight.change(lambda w: gr.Textbox(lines=int(w / 10) + 1), weight, details)\n", "\n", " generate_btn.click(lambda x: x, details, output)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/blocks_webcam/run.ipynb b/demo/blocks_webcam/run.ipynb index 91a8c5f8ee53c..730332f69314a 100644 --- a/demo/blocks_webcam/run.ipynb +++ b/demo/blocks_webcam/run.ipynb @@ -1 +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 +{"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 index e287312a15063..6754b73faff91 100644 --- a/demo/blocks_xray/run.ipynb +++ b/demo/blocks_xray/run.ipynb @@ -1 +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 time\n", "\n", "disease_values = [0.25, 0.5, 0.75]\n", "\n", "def xray_model(diseases, img):\n", " return [{disease: disease_values[idx] for idx,disease in enumerate(diseases)}]\n", "\n", "\n", "def ct_model(diseases, img):\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", " gr.DuplicateButton()\n", " disease = gr.CheckboxGroup(\n", " info=\"Select the diseases you want to scan for.\",\n", " choices=[\"Covid\", \"Malaria\", \"Lung Cancer\"], label=\"Disease to Scan For\"\n", " )\n", " slider = gr.Slider(0, 100)\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\", variant=\"primary\")\n", " upload_btn.click(\n", " lambda ct, xr: None,\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 +{"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 time\n", "\n", "disease_values = [0.25, 0.5, 0.75]\n", "\n", "def xray_model(diseases, img):\n", " return [{disease: disease_values[idx] for idx,disease in enumerate(diseases)}]\n", "\n", "\n", "def ct_model(diseases, img):\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", " gr.DuplicateButton()\n", " disease = gr.CheckboxGroup(\n", " info=\"Select the diseases you want to scan for.\",\n", " choices=[\"Covid\", \"Malaria\", \"Lung Cancer\"], label=\"Disease to Scan For\"\n", " )\n", " slider = gr.Slider(0, 100)\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\", variant=\"primary\")\n", " upload_btn.click(\n", " lambda ct, xr: None,\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/bokeh_plot/run.ipynb b/demo/bokeh_plot/run.ipynb index 2949824df0d52..43cddee02193f 100644 --- a/demo/bokeh_plot/run.ipynb +++ b/demo/bokeh_plot/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: bokeh_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio bokeh>=3.0 xyzservices"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import xyzservices.providers as xyz\n", "from bokeh.models import ColumnDataSource, Whisker\n", "from bokeh.plotting import figure\n", "from bokeh.sampledata.autompg2 import autompg2 as df\n", "from bokeh.sampledata.penguins import data\n", "from bokeh.transform import factor_cmap, jitter, factor_mark\n", "\n", "\n", "def get_plot(plot_type):\n", " if plot_type == \"map\":\n", " plot = figure(\n", " x_range=(-2000000, 6000000),\n", " y_range=(-1000000, 7000000),\n", " x_axis_type=\"mercator\",\n", " y_axis_type=\"mercator\",\n", " )\n", " plot.add_tile(xyz.OpenStreetMap.Mapnik)\n", " return plot\n", " elif plot_type == \"whisker\":\n", " classes = list(sorted(df[\"class\"].unique()))\n", "\n", " p = figure(\n", " height=400,\n", " x_range=classes,\n", " background_fill_color=\"#efefef\",\n", " title=\"Car class vs HWY mpg with quintile ranges\",\n", " )\n", " p.xgrid.grid_line_color = None\n", "\n", " g = df.groupby(\"class\")\n", " upper = g.hwy.quantile(0.80)\n", " lower = g.hwy.quantile(0.20)\n", " source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))\n", "\n", " error = Whisker(\n", " base=\"base\",\n", " upper=\"upper\",\n", " lower=\"lower\",\n", " source=source,\n", " level=\"annotation\",\n", " line_width=2,\n", " )\n", " error.upper_head.size = 20\n", " error.lower_head.size = 20\n", " p.add_layout(error)\n", "\n", " p.circle(\n", " jitter(\"class\", 0.3, range=p.x_range),\n", " \"hwy\",\n", " source=df,\n", " alpha=0.5,\n", " size=13,\n", " line_color=\"white\",\n", " color=factor_cmap(\"class\", \"Light6\", classes),\n", " )\n", " return p\n", " elif plot_type == \"scatter\":\n", "\n", " SPECIES = sorted(data.species.unique())\n", " MARKERS = [\"hex\", \"circle_x\", \"triangle\"]\n", "\n", " p = figure(title=\"Penguin size\", background_fill_color=\"#fafafa\")\n", " p.xaxis.axis_label = \"Flipper Length (mm)\"\n", " p.yaxis.axis_label = \"Body Mass (g)\"\n", "\n", " p.scatter(\n", " \"flipper_length_mm\",\n", " \"body_mass_g\",\n", " source=data,\n", " legend_group=\"species\",\n", " fill_alpha=0.4,\n", " size=12,\n", " marker=factor_mark(\"species\", MARKERS, SPECIES),\n", " color=factor_cmap(\"species\", \"Category10_3\", SPECIES),\n", " )\n", "\n", " p.legend.location = \"top_left\"\n", " p.legend.title = \"Species\"\n", " return p\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " plot_type = gr.Radio(value=\"scatter\", choices=[\"scatter\", \"whisker\", \"map\"])\n", " plot = gr.Plot()\n", " plot_type.change(get_plot, inputs=[plot_type], outputs=[plot])\n", " demo.load(get_plot, inputs=[plot_type], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: bokeh_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio bokeh>=3.0 xyzservices"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import xyzservices.providers as xyz\n", "from bokeh.models import ColumnDataSource, Whisker\n", "from bokeh.plotting import figure\n", "from bokeh.sampledata.autompg2 import autompg2 as df\n", "from bokeh.sampledata.penguins import data\n", "from bokeh.transform import factor_cmap, jitter, factor_mark\n", "\n", "\n", "def get_plot(plot_type):\n", " if plot_type == \"map\":\n", " plot = figure(\n", " x_range=(-2000000, 6000000),\n", " y_range=(-1000000, 7000000),\n", " x_axis_type=\"mercator\",\n", " y_axis_type=\"mercator\",\n", " )\n", " plot.add_tile(xyz.OpenStreetMap.Mapnik)\n", " return plot\n", " elif plot_type == \"whisker\":\n", " classes = list(sorted(df[\"class\"].unique()))\n", "\n", " p = figure(\n", " height=400,\n", " x_range=classes,\n", " background_fill_color=\"#efefef\",\n", " title=\"Car class vs HWY mpg with quintile ranges\",\n", " )\n", " p.xgrid.grid_line_color = None\n", "\n", " g = df.groupby(\"class\")\n", " upper = g.hwy.quantile(0.80)\n", " lower = g.hwy.quantile(0.20)\n", " source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))\n", "\n", " error = Whisker(\n", " base=\"base\",\n", " upper=\"upper\",\n", " lower=\"lower\",\n", " source=source,\n", " level=\"annotation\",\n", " line_width=2,\n", " )\n", " error.upper_head.size = 20\n", " error.lower_head.size = 20\n", " p.add_layout(error)\n", "\n", " p.circle(\n", " jitter(\"class\", 0.3, range=p.x_range),\n", " \"hwy\",\n", " source=df,\n", " alpha=0.5,\n", " size=13,\n", " line_color=\"white\",\n", " color=factor_cmap(\"class\", \"Light6\", classes),\n", " )\n", " return p\n", " elif plot_type == \"scatter\":\n", "\n", " SPECIES = sorted(data.species.unique())\n", " MARKERS = [\"hex\", \"circle_x\", \"triangle\"]\n", "\n", " p = figure(title=\"Penguin size\", background_fill_color=\"#fafafa\")\n", " p.xaxis.axis_label = \"Flipper Length (mm)\"\n", " p.yaxis.axis_label = \"Body Mass (g)\"\n", "\n", " p.scatter(\n", " \"flipper_length_mm\",\n", " \"body_mass_g\",\n", " source=data,\n", " legend_group=\"species\",\n", " fill_alpha=0.4,\n", " size=12,\n", " marker=factor_mark(\"species\", MARKERS, SPECIES),\n", " color=factor_cmap(\"species\", \"Category10_3\", SPECIES),\n", " )\n", "\n", " p.legend.location = \"top_left\"\n", " p.legend.title = \"Species\"\n", " return p\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " plot_type = gr.Radio(value=\"scatter\", choices=[\"scatter\", \"whisker\", \"map\"])\n", " plot = gr.Plot()\n", " plot_type.change(get_plot, inputs=[plot_type], outputs=[plot])\n", " demo.load(get_plot, inputs=[plot_type], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: bokeh_plot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio bokeh>=3.0 xyzservices"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import xyzservices.providers as xyz\n", "from bokeh.models import ColumnDataSource, Whisker\n", "from bokeh.plotting import figure\n", "from bokeh.sampledata.autompg2 import autompg2 as df\n", "from bokeh.sampledata.penguins import data\n", "from bokeh.transform import factor_cmap, jitter, factor_mark\n", "\n", "\n", "def get_plot(plot_type):\n", " if plot_type == \"map\":\n", " plot = figure(\n", " x_range=(-2000000, 6000000),\n", " y_range=(-1000000, 7000000),\n", " x_axis_type=\"mercator\",\n", " y_axis_type=\"mercator\",\n", " )\n", " plot.add_tile(xyz.OpenStreetMap.Mapnik)\n", " return plot\n", " elif plot_type == \"whisker\":\n", " classes = list(sorted(df[\"class\"].unique()))\n", "\n", " p = figure(\n", " height=400,\n", " x_range=classes,\n", " background_fill_color=\"#efefef\",\n", " title=\"Car class vs HWY mpg with quintile ranges\",\n", " )\n", " p.xgrid.grid_line_color = None\n", "\n", " g = df.groupby(\"class\")\n", " upper = g.hwy.quantile(0.80)\n", " lower = g.hwy.quantile(0.20)\n", " source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))\n", "\n", " error = Whisker(\n", " base=\"base\",\n", " upper=\"upper\",\n", " lower=\"lower\",\n", " source=source,\n", " level=\"annotation\",\n", " line_width=2,\n", " )\n", " error.upper_head.size = 20\n", " error.lower_head.size = 20\n", " p.add_layout(error)\n", "\n", " p.circle(\n", " jitter(\"class\", 0.3, range=p.x_range),\n", " \"hwy\",\n", " source=df,\n", " alpha=0.5,\n", " size=13,\n", " line_color=\"white\",\n", " color=factor_cmap(\"class\", \"Light6\", classes),\n", " )\n", " return p\n", " elif plot_type == \"scatter\":\n", "\n", " SPECIES = sorted(data.species.unique())\n", " MARKERS = [\"hex\", \"circle_x\", \"triangle\"]\n", "\n", " p = figure(title=\"Penguin size\", background_fill_color=\"#fafafa\")\n", " p.xaxis.axis_label = \"Flipper Length (mm)\"\n", " p.yaxis.axis_label = \"Body Mass (g)\"\n", "\n", " p.scatter(\n", " \"flipper_length_mm\",\n", " \"body_mass_g\",\n", " source=data,\n", " legend_group=\"species\",\n", " fill_alpha=0.4,\n", " size=12,\n", " marker=factor_mark(\"species\", MARKERS, SPECIES),\n", " color=factor_cmap(\"species\", \"Category10_3\", SPECIES),\n", " )\n", "\n", " p.legend.location = \"top_left\"\n", " p.legend.title = \"Species\"\n", " return p\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " plot_type = gr.Radio(value=\"scatter\", choices=[\"scatter\", \"whisker\", \"map\"])\n", " plot = gr.Plot()\n", " plot_type.change(get_plot, inputs=[plot_type], outputs=[plot])\n", " demo.load(get_plot, inputs=[plot_type], outputs=[plot])\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/button_component/run.ipynb b/demo/button_component/run.ipynb index 00e4c891c2603..641a17bf891cc 100644 --- a/demo/button_component/run.ipynb +++ b/demo/button_component/run.ipynb @@ -1 +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 +{"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 index 3fbf935446837..8b4e1433c39c4 100644 --- a/demo/calculator/run.ipynb +++ b/demo/calculator/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('examples')\n", "!wget -q -O examples/log.csv https://github.com/gradio-app/gradio/raw/main/demo/calculator/examples/log.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "#from foo import BAR\n", "#\n", "def calculator(num1, operation, num2):\n", " if operation == \"add\":\n", " return num1 + num2\n", " elif operation == \"subtract\":\n", " return num1 - num2\n", " elif operation == \"multiply\":\n", " return num1 * num2\n", " elif operation == \"divide\":\n", " if num2 == 0:\n", " raise gr.Error(\"Cannot divide by zero!\")\n", " return num1 / num2\n", "\n", "demo = gr.Interface(\n", " calculator,\n", " [\n", " \"number\", \n", " gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n", " \"number\"\n", " ],\n", " \"number\",\n", " examples=[\n", " [45, \"add\", 3],\n", " [3.14, \"divide\", 2],\n", " [144, \"multiply\", 2.5],\n", " [0, \"subtract\", 1.2],\n", " ],\n", " title=\"Toy Calculator\",\n", " description=\"Here's a sample toy calculator. Allows you to calculate things like $2+2=4$\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: calculator"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('examples')\n", "!wget -q -O examples/log.csv https://github.com/gradio-app/gradio/raw/main/demo/calculator/examples/log.csv"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "#from foo import BAR\n", "#\n", "def calculator(num1, operation, num2):\n", " if operation == \"add\":\n", " return num1 + num2\n", " elif operation == \"subtract\":\n", " return num1 - num2\n", " elif operation == \"multiply\":\n", " return num1 * num2\n", " elif operation == \"divide\":\n", " if num2 == 0:\n", " raise gr.Error(\"Cannot divide by zero!\")\n", " return num1 / num2\n", "\n", "demo = gr.Interface(\n", " calculator,\n", " [\n", " \"number\", \n", " gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n", " \"number\"\n", " ],\n", " \"number\",\n", " examples=[\n", " [45, \"add\", 3],\n", " [3.14, \"divide\", 2],\n", " [144, \"multiply\", 2.5],\n", " [0, \"subtract\", 1.2],\n", " ],\n", " title=\"Toy Calculator\",\n", " description=\"Here's a sample toy calculator. Allows you to calculate things like $2+2=4$\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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. Allows you to calculate things like $2+2=4$\",\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/calculator_blocks/run.ipynb b/demo/calculator_blocks/run.ipynb index b7523f3e87dcf..bad9e149406bc 100644 --- a/demo/calculator_blocks/run.ipynb +++ b/demo/calculator_blocks/run.ipynb @@ -1 +1,5 @@ -{"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], api_name=False)\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(show_api=False)"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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], api_name=False)\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(show_api=False)"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/calculator_blocks_cached/run.ipynb b/demo/calculator_blocks_cached/run.ipynb index b1d4482ff8b35..5ca1b4d3af8f5 100644 --- a/demo/calculator_blocks_cached/run.ipynb +++ b/demo/calculator_blocks_cached/run.ipynb @@ -1 +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 +{"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 index 8336b3b9c13c5..c967498f3f82c 100644 --- a/demo/calculator_list_and_dict/run.ipynb +++ b/demo/calculator_list_and_dict/run.ipynb @@ -1 +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 +{"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 index 4e150f1858133..a5c2131ad1b4b 100644 --- a/demo/calculator_live/run.ipynb +++ b/demo/calculator_live/run.ipynb @@ -1 +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 +{"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 index a00f54fb1e769..449220364b136 100644 --- a/demo/cancel_events/run.ipynb +++ b/demo/cancel_events/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: cancel_events"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "\n", "def fake_diffusion(steps):\n", " for i in range(steps):\n", " print(f\"Current step: {i}\")\n", " time.sleep(0.2)\n", " yield str(i)\n", "\n", "\n", "def long_prediction(*args, **kwargs):\n", " time.sleep(10)\n", " return 42\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " n = gr.Slider(1, 10, value=9, step=1, label=\"Number Steps\")\n", " run = gr.Button(value=\"Start Iterating\")\n", " output = gr.Textbox(label=\"Iterative Output\")\n", " stop = gr.Button(value=\"Stop Iterating\")\n", " with gr.Column():\n", " textbox = gr.Textbox(label=\"Prompt\")\n", " prediction = gr.Number(label=\"Expensive Calculation\")\n", " run_pred = gr.Button(value=\"Run Expensive Calculation\")\n", " with gr.Column():\n", " cancel_on_change = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Change\")\n", " cancel_on_submit = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Submit\")\n", " echo = gr.Textbox(label=\"Echo\")\n", " with gr.Row():\n", " with gr.Column():\n", " image = gr.Image(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", " demo.queue(concurrency_count=2, max_size=20)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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(0.2)\n", " yield str(i)\n", "\n", "\n", "def long_prediction(*args, **kwargs):\n", " time.sleep(10)\n", " return 42\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " n = gr.Slider(1, 10, value=9, step=1, label=\"Number Steps\")\n", " run = gr.Button(value=\"Start Iterating\")\n", " output = gr.Textbox(label=\"Iterative Output\")\n", " stop = gr.Button(value=\"Stop Iterating\")\n", " with gr.Column():\n", " textbox = gr.Textbox(label=\"Prompt\")\n", " prediction = gr.Number(label=\"Expensive Calculation\")\n", " run_pred = gr.Button(value=\"Run Expensive Calculation\")\n", " with gr.Column():\n", " cancel_on_change = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Change\")\n", " cancel_on_submit = gr.Textbox(label=\"Cancel Iteration and Expensive Calculation on Submit\")\n", " echo = gr.Textbox(label=\"Echo\")\n", " with gr.Row():\n", " with gr.Column():\n", " image = gr.Image(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", " demo.queue(concurrency_count=2, max_size=20)\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/change_vs_input/run.ipynb b/demo/change_vs_input/run.ipynb index 4fccd7df65cb5..49df4f8a00a17 100644 --- a/demo/change_vs_input/run.ipynb +++ b/demo/change_vs_input/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: change_vs_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": ["# 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/change_vs_input/files/cantina.wav\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/change_vs_input/files/lion.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/change_vs_input/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " set_button = gr.Button(\"Set Values\")\n", " with gr.Row():\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# Enter Here\")\n", " text = gr.Textbox()\n", " num = gr.Number()\n", " slider = gr.Slider()\n", " checkbox = gr.Checkbox()\n", " checkbox_group = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker = gr.ColorPicker()\n", " code = gr.Code()\n", " dataframe = gr.Dataframe()\n", " image = gr.Image(elem_id=\"image-original\")\n", " audio = gr.Audio(elem_id=\"audio-original\")\n", " video = gr.Video(elem_id=\"video-original\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:INPUT/UPLOAD\")\n", " text_in = gr.Textbox()\n", " num_in = gr.Number()\n", " slider_in = gr.Slider()\n", " checkbox_in = gr.Checkbox()\n", " checkbox_group_in = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_in = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_in = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_in = gr.ColorPicker()\n", " code_in = gr.Code()\n", " dataframe_in = gr.Dataframe()\n", " image_up = gr.Image(elem_id=\"image-upload\")\n", " audio_up = gr.Audio(elem_id=\"audio-upload\")\n", " video_up = gr.Video(elem_id=\"video-upload\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:CHANGE\")\n", " text_ch = gr.Textbox()\n", " num_ch = gr.Number()\n", " slider_ch = gr.Slider()\n", " checkbox_ch = gr.Checkbox()\n", " checkbox_group_ch = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_ch = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_ch = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_ch = gr.ColorPicker()\n", " code_ch = gr.Code()\n", " dataframe_ch = gr.Dataframe()\n", " image_ch = gr.Image(elem_id=\"image-change\")\n", " audio_ch = gr.Audio(elem_id=\"audio-change\")\n", " video_ch = gr.Video(elem_id=\"video-change\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:CHANGE x2\")\n", " text_ch2 = gr.Textbox()\n", " num_ch2 = gr.Number()\n", " slider_ch2 = gr.Slider()\n", " checkbox_ch2 = gr.Checkbox()\n", " checkbox_group_ch2 = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_ch2 = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_ch2 = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_ch2 = gr.ColorPicker()\n", " code_ch2 = gr.Code()\n", " dataframe_ch2 = gr.Dataframe()\n", " image_ch2 = gr.Image(elem_id=\"image-change-2\")\n", " audio_ch2 = gr.Audio(elem_id=\"audio-change-2\")\n", " video_ch2 = gr.Video(elem_id=\"video-change-2\")\n", "\n", " counter = gr.Number(label=\"Change counter\")\n", "\n", " lion = os.path.join(os.path.abspath(''), \"files/lion.jpg\")\n", " cantina = os.path.join(os.path.abspath(''), \"files/cantina.wav\")\n", " world = os.path.join(os.path.abspath(''), \"files/world.mp4\")\n", "\n", " set_button.click(\n", " lambda: [\"asdf\", 555, 12, True, [\"a\", \"c\"], \"b\", \"b\", \"#FF0000\", \"import gradio as gr\", [[\"a\", \"b\", \"c\", \"d\"], [\"1\", \"2\", \"3\", \"4\"]], lion, cantina, world], \n", " None, \n", " [text, num, slider, checkbox, checkbox_group, radio, dropdown, colorpicker, code, dataframe, image, audio, video])\n", "\n", " text.input(lambda x:x, text, text_in)\n", " num.input(lambda x:x, num, num_in)\n", " slider.input(lambda x:x, slider, slider_in)\n", " checkbox.input(lambda x:x, checkbox, checkbox_in)\n", " checkbox_group.input(lambda x:x, checkbox_group, checkbox_group_in)\n", " radio.input(lambda x:x, radio, radio_in)\n", " dropdown.input(lambda x:x, dropdown, dropdown_in)\n", " colorpicker.input(lambda x:x, colorpicker, colorpicker_in)\n", " code.input(lambda x:x, code, code_in)\n", " dataframe.input(lambda x:x, dataframe, dataframe_in)\n", " image.upload(lambda x:x, image, image_up)\n", " audio.upload(lambda x:x, audio, audio_up)\n", " video.upload(lambda x:x, video, video_up)\n", "\n", " text.change(lambda x,y:(x,y+1), [text, counter], [text_ch, counter])\n", " num.change(lambda x,y:(x, y+1), [num, counter], [num_ch, counter])\n", " slider.change(lambda x,y:(x, y+1), [slider, counter], [slider_ch, counter])\n", " checkbox.change(lambda x,y:(x, y+1), [checkbox, counter], [checkbox_ch, counter])\n", " checkbox_group.change(lambda x,y:(x, y+1), [checkbox_group, counter], [checkbox_group_ch, counter])\n", " radio.change(lambda x,y:(x, y+1), [radio, counter], [radio_ch, counter])\n", " dropdown.change(lambda x,y:(x, y+1), [dropdown, counter], [dropdown_ch, counter])\n", " colorpicker.change(lambda x,y:(x, y+1), [colorpicker, counter], [colorpicker_ch, counter])\n", " code.change(lambda x,y:(x, y+1), [code, counter], [code_ch, counter])\n", " dataframe.change(lambda x,y:(x, y+1), [dataframe, counter], [dataframe_ch, counter])\n", " image.change(lambda x,y:(x, y+1), [image, counter], [image_ch, counter])\n", " audio.change(lambda x,y:(x, y+1), [audio, counter], [audio_ch, counter])\n", " video.change(lambda x,y:(x, y+1), [video, counter], [video_ch, counter])\n", "\n", " text_ch.change(lambda x:x, text_ch, text_ch2)\n", " num_ch.change(lambda x:x, num_ch, num_ch2)\n", " slider_ch.change(lambda x:x, slider_ch, slider_ch2)\n", " checkbox_ch.change(lambda x:x, checkbox_ch, checkbox_ch2)\n", " checkbox_group_ch.change(lambda x:x, checkbox_group_ch, checkbox_group_ch2)\n", " radio_ch.change(lambda x:x, radio_ch, radio_ch2)\n", " dropdown_ch.change(lambda x:x, dropdown_ch, dropdown_ch2)\n", " colorpicker_ch.change(lambda x:x, colorpicker_ch, colorpicker_ch2)\n", " code_ch.change(lambda x:x, code_ch, code_ch2)\n", " dataframe_ch.change(lambda x:x, dataframe_ch, dataframe_ch2)\n", " image_ch.change(lambda x:x, image_ch, image_ch2)\n", " audio_ch.change(lambda x:x, audio_ch, audio_ch2)\n", " video_ch.change(lambda x:x, video_ch, video_ch2)\n", " \n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: change_vs_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": ["# 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/change_vs_input/files/cantina.wav\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/change_vs_input/files/lion.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/change_vs_input/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import os\n", "import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " set_button = gr.Button(\"Set Values\")\n", " with gr.Row():\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# Enter Here\")\n", " text = gr.Textbox()\n", " num = gr.Number()\n", " slider = gr.Slider()\n", " checkbox = gr.Checkbox()\n", " checkbox_group = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker = gr.ColorPicker()\n", " code = gr.Code()\n", " dataframe = gr.Dataframe()\n", " image = gr.Image(elem_id=\"image-original\")\n", " audio = gr.Audio(elem_id=\"audio-original\")\n", " video = gr.Video(elem_id=\"video-original\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:INPUT/UPLOAD\")\n", " text_in = gr.Textbox()\n", " num_in = gr.Number()\n", " slider_in = gr.Slider()\n", " checkbox_in = gr.Checkbox()\n", " checkbox_group_in = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_in = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_in = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_in = gr.ColorPicker()\n", " code_in = gr.Code()\n", " dataframe_in = gr.Dataframe()\n", " image_up = gr.Image(elem_id=\"image-upload\")\n", " audio_up = gr.Audio(elem_id=\"audio-upload\")\n", " video_up = gr.Video(elem_id=\"video-upload\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:CHANGE\")\n", " text_ch = gr.Textbox()\n", " num_ch = gr.Number()\n", " slider_ch = gr.Slider()\n", " checkbox_ch = gr.Checkbox()\n", " checkbox_group_ch = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_ch = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_ch = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_ch = gr.ColorPicker()\n", " code_ch = gr.Code()\n", " dataframe_ch = gr.Dataframe()\n", " image_ch = gr.Image(elem_id=\"image-change\")\n", " audio_ch = gr.Audio(elem_id=\"audio-change\")\n", " video_ch = gr.Video(elem_id=\"video-change\")\n", "\n", " with gr.Column(min_width=200):\n", " gr.Markdown(\"# ON:CHANGE x2\")\n", " text_ch2 = gr.Textbox()\n", " num_ch2 = gr.Number()\n", " slider_ch2 = gr.Slider()\n", " checkbox_ch2 = gr.Checkbox()\n", " checkbox_group_ch2 = gr.CheckboxGroup([\"a\", \"b\", \"c\"])\n", " radio_ch2 = gr.Radio([\"a\", \"b\", \"c\"])\n", " dropdown_ch2 = gr.Dropdown([\"a\", \"b\", \"c\"])\n", " colorpicker_ch2 = gr.ColorPicker()\n", " code_ch2 = gr.Code()\n", " dataframe_ch2 = gr.Dataframe()\n", " image_ch2 = gr.Image(elem_id=\"image-change-2\")\n", " audio_ch2 = gr.Audio(elem_id=\"audio-change-2\")\n", " video_ch2 = gr.Video(elem_id=\"video-change-2\")\n", "\n", " counter = gr.Number(label=\"Change counter\")\n", "\n", " lion = os.path.join(os.path.abspath(''), \"files/lion.jpg\")\n", " cantina = os.path.join(os.path.abspath(''), \"files/cantina.wav\")\n", " world = os.path.join(os.path.abspath(''), \"files/world.mp4\")\n", "\n", " set_button.click(\n", " lambda: [\"asdf\", 555, 12, True, [\"a\", \"c\"], \"b\", \"b\", \"#FF0000\", \"import gradio as gr\", [[\"a\", \"b\", \"c\", \"d\"], [\"1\", \"2\", \"3\", \"4\"]], lion, cantina, world], \n", " None, \n", " [text, num, slider, checkbox, checkbox_group, radio, dropdown, colorpicker, code, dataframe, image, audio, video])\n", "\n", " text.input(lambda x:x, text, text_in)\n", " num.input(lambda x:x, num, num_in)\n", " slider.input(lambda x:x, slider, slider_in)\n", " checkbox.input(lambda x:x, checkbox, checkbox_in)\n", " checkbox_group.input(lambda x:x, checkbox_group, checkbox_group_in)\n", " radio.input(lambda x:x, radio, radio_in)\n", " dropdown.input(lambda x:x, dropdown, dropdown_in)\n", " colorpicker.input(lambda x:x, colorpicker, colorpicker_in)\n", " code.input(lambda x:x, code, code_in)\n", " dataframe.input(lambda x:x, dataframe, dataframe_in)\n", " image.upload(lambda x:x, image, image_up)\n", " audio.upload(lambda x:x, audio, audio_up)\n", " video.upload(lambda x:x, video, video_up)\n", "\n", " text.change(lambda x,y:(x,y+1), [text, counter], [text_ch, counter])\n", " num.change(lambda x,y:(x, y+1), [num, counter], [num_ch, counter])\n", " slider.change(lambda x,y:(x, y+1), [slider, counter], [slider_ch, counter])\n", " checkbox.change(lambda x,y:(x, y+1), [checkbox, counter], [checkbox_ch, counter])\n", " checkbox_group.change(lambda x,y:(x, y+1), [checkbox_group, counter], [checkbox_group_ch, counter])\n", " radio.change(lambda x,y:(x, y+1), [radio, counter], [radio_ch, counter])\n", " dropdown.change(lambda x,y:(x, y+1), [dropdown, counter], [dropdown_ch, counter])\n", " colorpicker.change(lambda x,y:(x, y+1), [colorpicker, counter], [colorpicker_ch, counter])\n", " code.change(lambda x,y:(x, y+1), [code, counter], [code_ch, counter])\n", " dataframe.change(lambda x,y:(x, y+1), [dataframe, counter], [dataframe_ch, counter])\n", " image.change(lambda x,y:(x, y+1), [image, counter], [image_ch, counter])\n", " audio.change(lambda x,y:(x, y+1), [audio, counter], [audio_ch, counter])\n", " video.change(lambda x,y:(x, y+1), [video, counter], [video_ch, counter])\n", "\n", " text_ch.change(lambda x:x, text_ch, text_ch2)\n", " num_ch.change(lambda x:x, num_ch, num_ch2)\n", " slider_ch.change(lambda x:x, slider_ch, slider_ch2)\n", " checkbox_ch.change(lambda x:x, checkbox_ch, checkbox_ch2)\n", " checkbox_group_ch.change(lambda x:x, checkbox_group_ch, checkbox_group_ch2)\n", " radio_ch.change(lambda x:x, radio_ch, radio_ch2)\n", " dropdown_ch.change(lambda x:x, dropdown_ch, dropdown_ch2)\n", " colorpicker_ch.change(lambda x:x, colorpicker_ch, colorpicker_ch2)\n", " code_ch.change(lambda x:x, code_ch, code_ch2)\n", " dataframe_ch.change(lambda x:x, dataframe_ch, dataframe_ch2)\n", " image_ch.change(lambda x:x, image_ch, image_ch2)\n", " audio_ch.change(lambda x:x, audio_ch, audio_ch2)\n", " video_ch.change(lambda x:x, video_ch, video_ch2)\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/chatbot_component/run.ipynb b/demo/chatbot_component/run.ipynb index 82f59d809f75b..d95d2c5f4f473 100644 --- a/demo/chatbot_component/run.ipynb +++ b/demo/chatbot_component/run.ipynb @@ -1 +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 +{"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_consecutive/run.ipynb b/demo/chatbot_consecutive/run.ipynb index 93c2fcf8e9f85..ff489e011a9a6 100644 --- a/demo/chatbot_consecutive/run.ipynb +++ b/demo/chatbot_consecutive/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_consecutive"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def user(user_message, history):\n", " return \"\", history + [[user_message, None]]\n", "\n", " def bot(history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " time.sleep(2)\n", " history[-1][1] = bot_message\n", " return history\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", " \n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_consecutive"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def user(user_message, history):\n", " return \"\", history + [[user_message, None]]\n", "\n", " def bot(history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " time.sleep(2)\n", " history[-1][1] = bot_message\n", " return history\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", " \n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/chatbot_dialogpt/run.ipynb b/demo/chatbot_dialogpt/run.ipynb index 879b1d5c7b775..650f7abcb9041 100644 --- a/demo/chatbot_dialogpt/run.ipynb +++ b/demo/chatbot_dialogpt/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_dialogpt"]}, {"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": ["import gradio as gr\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "import torch\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(\"microsoft/DialoGPT-medium\")\n", "model = AutoModelForCausalLM.from_pretrained(\"microsoft/DialoGPT-medium\")\n", "\n", "\n", "def user(message, history):\n", " return \"\", history + [[message, None]]\n", "\n", "\n", "def bot(history):\n", " user_message = history[-1][0]\n", " new_user_input_ids = tokenizer.encode(\n", " user_message + tokenizer.eos_token, return_tensors=\"pt\"\n", " )\n", "\n", " # append the new user input tokens to the chat history\n", " bot_input_ids = torch.cat([torch.LongTensor([]), new_user_input_ids], dim=-1)\n", "\n", " # generate a response\n", " response = model.generate(\n", " bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id\n", " ).tolist()\n", "\n", " # convert the tokens to text, and then split the responses into lines\n", " response = tokenizer.decode(response[0]).split(\"<|endoftext|>\")\n", " response = [\n", " (response[i], response[i + 1]) for i in range(0, len(response) - 1, 2)\n", " ] # convert to tuples of list\n", " history[-1] = response[0]\n", " return history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_dialogpt"]}, {"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": ["import gradio as gr\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "import torch\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(\"microsoft/DialoGPT-medium\")\n", "model = AutoModelForCausalLM.from_pretrained(\"microsoft/DialoGPT-medium\")\n", "\n", "\n", "def user(message, history):\n", " return \"\", history + [[message, None]]\n", "\n", "\n", "def bot(history):\n", " user_message = history[-1][0]\n", " new_user_input_ids = tokenizer.encode(\n", " user_message + tokenizer.eos_token, return_tensors=\"pt\"\n", " )\n", "\n", " # append the new user input tokens to the chat history\n", " bot_input_ids = torch.cat([torch.LongTensor([]), new_user_input_ids], dim=-1)\n", "\n", " # generate a response\n", " response = model.generate(\n", " bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id\n", " ).tolist()\n", "\n", " # convert the tokens to text, and then split the responses into lines\n", " response = tokenizer.decode(response[0]).split(\"<|endoftext|>\")\n", " response = [\n", " (response[i], response[i + 1]) for i in range(0, len(response) - 1, 2)\n", " ] # convert to tuples of list\n", " history[-1] = response[0]\n", " return history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=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/chatbot_multimodal/run.ipynb b/demo/chatbot_multimodal/run.ipynb index 5b20ca0c24f9f..dfe33c0335e58 100644 --- a/demo/chatbot_multimodal/run.ipynb +++ b/demo/chatbot_multimodal/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.Textbox(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False,\n", " avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))),\n", " )\n", "\n", " with gr.Row():\n", " txt = gr.Textbox(\n", " scale=4,\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False,\n", " )\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot, api_name=\"bot_response\"\n", " )\n", " txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.Textbox(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False,\n", " avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))),\n", " )\n", "\n", " with gr.Row():\n", " txt = gr.Textbox(\n", " scale=4,\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False,\n", " )\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot, api_name=\"bot_response\"\n", " )\n", " txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def add_text(history, text):\n", " history = history + [(text, None)]\n", " return history, gr.Textbox(value=\"\", interactive=False)\n", "\n", "\n", "def add_file(history, file):\n", " history = history + [((file.name,), None)]\n", " return history\n", "\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False,\n", " avatar_images=(None, (os.path.join(os.path.abspath(''), \"avatar.png\"))),\n", " )\n", "\n", " with gr.Row():\n", " txt = gr.Textbox(\n", " scale=4,\n", " show_label=False,\n", " placeholder=\"Enter text and press enter, or upload an image\",\n", " container=False,\n", " )\n", " btn = gr.UploadButton(\"\ud83d\udcc1\", file_types=[\"image\", \"video\", \"audio\"])\n", "\n", " txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)\n", " file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/chatbot_simple/run.ipynb b/demo/chatbot_simple/run.ipynb index 472690ebc1383..9085788db1004 100644 --- a/demo/chatbot_simple/run.ipynb +++ b/demo/chatbot_simple/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_simple"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.ClearButton([msg, chatbot])\n", "\n", " def respond(message, chat_history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " chat_history.append((message, bot_message))\n", " time.sleep(2)\n", " return \"\", chat_history\n", "\n", " msg.submit(respond, [msg, chatbot], [msg, chatbot])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_simple"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.ClearButton([msg, chatbot])\n", "\n", " def respond(message, chat_history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " chat_history.append((message, bot_message))\n", " time.sleep(2)\n", " return \"\", chat_history\n", "\n", " msg.submit(respond, [msg, chatbot], [msg, chatbot])\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/chatbot_streaming/run.ipynb b/demo/chatbot_streaming/run.ipynb index 72a22daacc75d..f93bf5b3ec328 100644 --- a/demo/chatbot_streaming/run.ipynb +++ b/demo/chatbot_streaming/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_streaming"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def user(user_message, history):\n", " return \"\", history + [[user_message, None]]\n", "\n", " def bot(history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " history[-1][1] = \"\"\n", " for character in bot_message:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", " \n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_streaming"]}, {"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", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def user(user_message, history):\n", " return \"\", history + [[user_message, None]]\n", "\n", " def bot(history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " history[-1][1] = \"\"\n", " for character in bot_message:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", " msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n", " bot, chatbot, chatbot\n", " )\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", " \n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/chatinterface_random_response/run.ipynb b/demo/chatinterface_random_response/run.ipynb index 7e8fbdd684fcc..dd95ecee051e2 100644 --- a/demo/chatinterface_random_response/run.ipynb +++ b/demo/chatinterface_random_response/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatinterface_random_response"]}, {"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 random_response(message, history):\n", " return random.choice([\"Yes\", \"No\"])\n", "\n", "demo = gr.ChatInterface(random_response)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatinterface_random_response"]}, {"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 random_response(message, history):\n", " return random.choice([\"Yes\", \"No\"])\n", "\n", "demo = gr.ChatInterface(random_response)\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/chatinterface_streaming_echo/run.ipynb b/demo/chatinterface_streaming_echo/run.ipynb index c19db84df761b..7b56e7526db6f 100644 --- a/demo/chatinterface_streaming_echo/run.ipynb +++ b/demo/chatinterface_streaming_echo/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatinterface_streaming_echo"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "def slow_echo(message, history):\n", " for i in range(len(message)):\n", " time.sleep(0.05)\n", " yield \"You typed: \" + message[: i+1]\n", "\n", "demo = gr.ChatInterface(slow_echo).queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatinterface_streaming_echo"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import time\n", "import gradio as gr\n", "\n", "def slow_echo(message, history):\n", " for i in range(len(message)):\n", " time.sleep(0.05)\n", " yield \"You typed: \" + message[: i+1]\n", "\n", "demo = gr.ChatInterface(slow_echo).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/chatinterface_system_prompt/run.ipynb b/demo/chatinterface_system_prompt/run.ipynb index c92e7ea5d9082..7ad525d719a5a 100644 --- a/demo/chatinterface_system_prompt/run.ipynb +++ b/demo/chatinterface_system_prompt/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatinterface_system_prompt"]}, {"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 echo(message, history, system_prompt, tokens):\n", " response = f\"System prompt: {system_prompt}\\n Message: {message}.\"\n", " for i in range(min(len(response), int(tokens))):\n", " time.sleep(0.05)\n", " yield response[: i+1]\n", "\n", "demo = gr.ChatInterface(echo, \n", " additional_inputs=[\n", " gr.Textbox(\"You are helpful AI.\", label=\"System Prompt\"), \n", " gr.Slider(10, 100)\n", " ]\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue().launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatinterface_system_prompt"]}, {"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 echo(message, history, system_prompt, tokens):\n", " response = f\"System prompt: {system_prompt}\\n Message: {message}.\"\n", " for i in range(min(len(response), int(tokens))):\n", " time.sleep(0.05)\n", " yield response[: i+1]\n", "\n", "demo = gr.ChatInterface(echo, \n", " additional_inputs=[\n", " gr.Textbox(\"You are helpful AI.\", label=\"System Prompt\"), \n", " gr.Slider(10, 100)\n", " ]\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue().launch()"]}], "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 index 02a1469c2665e..2fa85f1986b02 100644 --- a/demo/checkbox_component/run.ipynb +++ b/demo/checkbox_component/run.ipynb @@ -1 +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 +{"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 index 91e85fc2dc6a2..bac9ffa2c07a2 100644 --- a/demo/checkboxgroup_component/run.ipynb +++ b/demo/checkboxgroup_component/run.ipynb @@ -1 +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 +{"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 index f936d3be1f983..a8023631fa47e 100644 --- a/demo/chicago-bikeshare-dashboard/run.ipynb +++ b/demo/chicago-bikeshare-dashboard/run.ipynb @@ -1 +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 pandas as pd\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", " return df\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", " return df\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.BarPlot(\n", " x=\"rideable_type\",\n", " y='n',\n", " title=\"Number of rides per bicycle type\",\n", " y_title=\"Number of Rides\",\n", " x_title=\"Bicycle Type\",\n", " vertical=False,\n", " tooltip=['rideable_type', \"n\"],\n", " height=300,\n", " width=300,\n", " )\n", " station = gr.BarPlot(\n", " x='station',\n", " y='n',\n", " title=\"Most Popular Stations\",\n", " y_title=\"Number of Rides\",\n", " x_title=\"Station Name\",\n", " vertical=False,\n", " tooltip=['station', 'n'],\n", " height=300,\n", " width=300\n", " )\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 +{"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 pandas as pd\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", " return df\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", " return df\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.BarPlot(\n", " x=\"rideable_type\",\n", " y='n',\n", " title=\"Number of rides per bicycle type\",\n", " y_title=\"Number of Rides\",\n", " x_title=\"Bicycle Type\",\n", " vertical=False,\n", " tooltip=['rideable_type', \"n\"],\n", " height=300,\n", " width=300,\n", " )\n", " station = gr.BarPlot(\n", " x='station',\n", " y='n',\n", " title=\"Most Popular Stations\",\n", " y_title=\"Number of Rides\",\n", " x_title=\"Station Name\",\n", " vertical=False,\n", " tooltip=['station', 'n'],\n", " height=300,\n", " width=300\n", " )\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/clear_components/run.ipynb b/demo/clear_components/run.ipynb index 4316a9a7717b1..a5b0c358523c2 100644 --- a/demo/clear_components/run.ipynb +++ b/demo/clear_components/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: clear_components"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/clear_components/__init__.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from datetime import datetime\n", "import os\n", "import random\n", "import string\n", "import pandas as pd\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "\n", "def random_plot():\n", " start_year = 2020\n", " x = np.arange(start_year, start_year + 5)\n", " year_count = x.shape[0]\n", " plt_format = \"-\"\n", " fig = plt.figure()\n", " ax = fig.add_subplot(111)\n", " series = np.arange(0, year_count, dtype=float)\n", " series = series**2\n", " series += np.random.rand(year_count)\n", " ax.plot(x, series, plt_format)\n", " return fig\n", "\n", "\n", "images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", "]\n", "file_dir = os.path.join(os.path.abspath(''), \"..\", \"kitchen_sink\", \"files\")\n", "model3d_dir = os.path.join(os.path.abspath(''), \"..\", \"model3D\", \"files\")\n", "highlighted_text_output_1 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-MISC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistani\",\n", " \"start\": 22,\n", " \"end\": 31,\n", " },\n", "]\n", "highlighted_text_output_2 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistan\",\n", " \"start\": 22,\n", " \"end\": 30,\n", " },\n", "]\n", "\n", "highlighted_text = \"Does Chicago have any Pakistani restaurants\"\n", "\n", "\n", "def random_model3d():\n", " model_3d = random.choice(\n", " [os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != \"source.txt\"]\n", " )\n", " return model_3d\n", "\n", "\n", "\n", "components = [\n", " gr.Textbox(value=lambda: datetime.now(), label=\"Current Time\"),\n", " gr.Number(value=lambda: random.random(), label=\"Random Percentage\"),\n", " gr.Slider(minimum=0, maximum=100, randomize=True, label=\"Slider with randomize\"),\n", " gr.Slider(\n", " minimum=0,\n", " maximum=1,\n", " value=lambda: random.random(),\n", " label=\"Slider with value func\",\n", " ),\n", " gr.Checkbox(value=lambda: random.random() > 0.5, label=\"Random Checkbox\"),\n", " gr.CheckboxGroup(\n", " choices=[\"a\", \"b\", \"c\", \"d\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\", \"d\"]),\n", " label=\"Random CheckboxGroup\",\n", " ),\n", " gr.Radio(\n", " choices=list(string.ascii_lowercase),\n", " value=lambda: random.choice(string.ascii_lowercase),\n", " ),\n", " gr.Dropdown(\n", " choices=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\"]),\n", " ),\n", " gr.Image(\n", " value=lambda: random.choice(images)\n", " ),\n", " gr.Video(value=lambda: os.path.join(file_dir, \"world.mp4\")),\n", " gr.Audio(value=lambda: os.path.join(file_dir, \"cantina.wav\")),\n", " gr.File(\n", " value=lambda: random.choice(\n", " [os.path.join(file_dir, img) for img in os.listdir(file_dir)]\n", " )\n", " ),\n", " gr.Dataframe(\n", " value=lambda: pd.DataFrame({\"random_number_rows\": range(5)}, columns=[\"one\", \"two\", \"three\"])\n", " ),\n", " gr.ColorPicker(value=lambda: random.choice([\"#000000\", \"#ff0000\", \"#0000FF\"])),\n", " gr.Label(value=lambda: random.choice([\"Pedestrian\", \"Car\", \"Cyclist\"])),\n", " gr.HighlightedText(\n", " value=lambda: random.choice(\n", " [\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_1},\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_2},\n", " ]\n", " ),\n", " ),\n", " gr.JSON(value=lambda: random.choice([{\"a\": 1}, {\"b\": 2}])),\n", " gr.HTML(\n", " value=lambda: random.choice(\n", " [\n", " '

I am red

',\n", " '

I am blue

',\n", " ]\n", " )\n", " ),\n", " gr.Gallery(\n", " value=lambda: images\n", " ),\n", " gr.Model3D(value=random_model3d),\n", " gr.Plot(value=random_plot),\n", " gr.Markdown(value=lambda: f\"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}\"),\n", "]\n", "\n", "\n", "def evaluate_values(*args):\n", " are_false = []\n", " for a in args:\n", " if isinstance(a, (pd.DataFrame, np.ndarray)):\n", " are_false.append(not a.any().any())\n", " elif isinstance(a, str) and a.startswith(\"#\"):\n", " are_false.append(a == \"#000000\")\n", " else:\n", " are_false.append(not a)\n", " return all(are_false)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " for i, component in enumerate(components):\n", " component.label = f\"component_{str(i).zfill(2)}\"\n", " component.render()\n", " clear = gr.ClearButton(value=\"Clear\", components=components)\n", " result = gr.Textbox(label=\"Are all cleared?\")\n", " hide = gr.Button(value=\"Hide\")\n", " reveal = gr.Button(value=\"Reveal\")\n", " hide.click(\n", " lambda: [c.__class__(visible=False) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " reveal.click(\n", " lambda: [c.__class__(visible=True) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " get_value = gr.Button(value=\"Get Values\")\n", " get_value.click(evaluate_values, components, result)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: clear_components"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/clear_components/__init__.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from datetime import datetime\n", "import os\n", "import random\n", "import string\n", "import pandas as pd\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "\n", "def random_plot():\n", " start_year = 2020\n", " x = np.arange(start_year, start_year + 5)\n", " year_count = x.shape[0]\n", " plt_format = \"-\"\n", " fig = plt.figure()\n", " ax = fig.add_subplot(111)\n", " series = np.arange(0, year_count, dtype=float)\n", " series = series**2\n", " series += np.random.rand(year_count)\n", " ax.plot(x, series, plt_format)\n", " return fig\n", "\n", "\n", "images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", "]\n", "file_dir = os.path.join(os.path.abspath(''), \"..\", \"kitchen_sink\", \"files\")\n", "model3d_dir = os.path.join(os.path.abspath(''), \"..\", \"model3D\", \"files\")\n", "highlighted_text_output_1 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-MISC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistani\",\n", " \"start\": 22,\n", " \"end\": 31,\n", " },\n", "]\n", "highlighted_text_output_2 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistan\",\n", " \"start\": 22,\n", " \"end\": 30,\n", " },\n", "]\n", "\n", "highlighted_text = \"Does Chicago have any Pakistani restaurants\"\n", "\n", "\n", "def random_model3d():\n", " model_3d = random.choice(\n", " [os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != \"source.txt\"]\n", " )\n", " return model_3d\n", "\n", "\n", "\n", "components = [\n", " gr.Textbox(value=lambda: datetime.now(), label=\"Current Time\"),\n", " gr.Number(value=lambda: random.random(), label=\"Random Percentage\"),\n", " gr.Slider(minimum=0, maximum=100, randomize=True, label=\"Slider with randomize\"),\n", " gr.Slider(\n", " minimum=0,\n", " maximum=1,\n", " value=lambda: random.random(),\n", " label=\"Slider with value func\",\n", " ),\n", " gr.Checkbox(value=lambda: random.random() > 0.5, label=\"Random Checkbox\"),\n", " gr.CheckboxGroup(\n", " choices=[\"a\", \"b\", \"c\", \"d\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\", \"d\"]),\n", " label=\"Random CheckboxGroup\",\n", " ),\n", " gr.Radio(\n", " choices=list(string.ascii_lowercase),\n", " value=lambda: random.choice(string.ascii_lowercase),\n", " ),\n", " gr.Dropdown(\n", " choices=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\"]),\n", " ),\n", " gr.Image(\n", " value=lambda: random.choice(images)\n", " ),\n", " gr.Video(value=lambda: os.path.join(file_dir, \"world.mp4\")),\n", " gr.Audio(value=lambda: os.path.join(file_dir, \"cantina.wav\")),\n", " gr.File(\n", " value=lambda: random.choice(\n", " [os.path.join(file_dir, img) for img in os.listdir(file_dir)]\n", " )\n", " ),\n", " gr.Dataframe(\n", " value=lambda: pd.DataFrame({\"random_number_rows\": range(5)}, columns=[\"one\", \"two\", \"three\"])\n", " ),\n", " gr.ColorPicker(value=lambda: random.choice([\"#000000\", \"#ff0000\", \"#0000FF\"])),\n", " gr.Label(value=lambda: random.choice([\"Pedestrian\", \"Car\", \"Cyclist\"])),\n", " gr.HighlightedText(\n", " value=lambda: random.choice(\n", " [\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_1},\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_2},\n", " ]\n", " ),\n", " ),\n", " gr.JSON(value=lambda: random.choice([{\"a\": 1}, {\"b\": 2}])),\n", " gr.HTML(\n", " value=lambda: random.choice(\n", " [\n", " '

I am red

',\n", " '

I am blue

',\n", " ]\n", " )\n", " ),\n", " gr.Gallery(\n", " value=lambda: images\n", " ),\n", " gr.Model3D(value=random_model3d),\n", " gr.Plot(value=random_plot),\n", " gr.Markdown(value=lambda: f\"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}\"),\n", "]\n", "\n", "\n", "def evaluate_values(*args):\n", " are_false = []\n", " for a in args:\n", " if isinstance(a, (pd.DataFrame, np.ndarray)):\n", " are_false.append(not a.any().any())\n", " elif isinstance(a, str) and a.startswith(\"#\"):\n", " are_false.append(a == \"#000000\")\n", " else:\n", " are_false.append(not a)\n", " return all(are_false)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " for i, component in enumerate(components):\n", " component.label = f\"component_{str(i).zfill(2)}\"\n", " component.render()\n", " clear = gr.ClearButton(value=\"Clear\", components=components)\n", " result = gr.Textbox(label=\"Are all cleared?\")\n", " hide = gr.Button(value=\"Hide\")\n", " reveal = gr.Button(value=\"Reveal\")\n", " hide.click(\n", " lambda: [c.__class__(visible=False) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " reveal.click(\n", " lambda: [c.__class__(visible=True) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " get_value = gr.Button(value=\"Get Values\")\n", " get_value.click(evaluate_values, components, result)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: clear_components"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/clear_components/__init__.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from datetime import datetime\n", "import os\n", "import random\n", "import string\n", "import pandas as pd\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "\n", "def random_plot():\n", " start_year = 2020\n", " x = np.arange(start_year, start_year + 5)\n", " year_count = x.shape[0]\n", " plt_format = \"-\"\n", " fig = plt.figure()\n", " ax = fig.add_subplot(111)\n", " series = np.arange(0, year_count, dtype=float)\n", " series = series**2\n", " series += np.random.rand(year_count)\n", " ax.plot(x, series, plt_format)\n", " return fig\n", "\n", "\n", "images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", "]\n", "file_dir = os.path.join(os.path.abspath(''), \"..\", \"kitchen_sink\", \"files\")\n", "model3d_dir = os.path.join(os.path.abspath(''), \"..\", \"model3D\", \"files\")\n", "highlighted_text_output_1 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-MISC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistani\",\n", " \"start\": 22,\n", " \"end\": 31,\n", " },\n", "]\n", "highlighted_text_output_2 = [\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9988978,\n", " \"index\": 2,\n", " \"word\": \"Chicago\",\n", " \"start\": 5,\n", " \"end\": 12,\n", " },\n", " {\n", " \"entity\": \"I-LOC\",\n", " \"score\": 0.9958592,\n", " \"index\": 5,\n", " \"word\": \"Pakistan\",\n", " \"start\": 22,\n", " \"end\": 30,\n", " },\n", "]\n", "\n", "highlighted_text = \"Does Chicago have any Pakistani restaurants\"\n", "\n", "\n", "def random_model3d():\n", " model_3d = random.choice(\n", " [os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != \"source.txt\"]\n", " )\n", " return model_3d\n", "\n", "\n", "\n", "components = [\n", " gr.Textbox(value=lambda: datetime.now(), label=\"Current Time\"),\n", " gr.Number(value=lambda: random.random(), label=\"Random Percentage\"),\n", " gr.Slider(minimum=0, maximum=100, randomize=True, label=\"Slider with randomize\"),\n", " gr.Slider(\n", " minimum=0,\n", " maximum=1,\n", " value=lambda: random.random(),\n", " label=\"Slider with value func\",\n", " ),\n", " gr.Checkbox(value=lambda: random.random() > 0.5, label=\"Random Checkbox\"),\n", " gr.CheckboxGroup(\n", " choices=[\"a\", \"b\", \"c\", \"d\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\", \"d\"]),\n", " label=\"Random CheckboxGroup\",\n", " ),\n", " gr.Radio(\n", " choices=list(string.ascii_lowercase),\n", " value=lambda: random.choice(string.ascii_lowercase),\n", " ),\n", " gr.Dropdown(\n", " choices=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n", " value=lambda: random.choice([\"a\", \"b\", \"c\"]),\n", " ),\n", " gr.Image(\n", " value=lambda: random.choice(images)\n", " ),\n", " gr.Video(value=lambda: os.path.join(file_dir, \"world.mp4\")),\n", " gr.Audio(value=lambda: os.path.join(file_dir, \"cantina.wav\")),\n", " gr.File(\n", " value=lambda: random.choice(\n", " [os.path.join(file_dir, img) for img in os.listdir(file_dir)]\n", " )\n", " ),\n", " gr.Dataframe(\n", " value=lambda: pd.DataFrame({\"random_number_rows\": range(5)}, columns=[\"one\", \"two\", \"three\"])\n", " ),\n", " gr.Timeseries(value=lambda: os.path.join(file_dir, \"time.csv\")),\n", " gr.ColorPicker(value=lambda: random.choice([\"#000000\", \"#ff0000\", \"#0000FF\"])),\n", " gr.Label(value=lambda: random.choice([\"Pedestrian\", \"Car\", \"Cyclist\"])),\n", " gr.HighlightedText(\n", " value=lambda: random.choice(\n", " [\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_1},\n", " {\"text\": highlighted_text, \"entities\": highlighted_text_output_2},\n", " ]\n", " ),\n", " ),\n", " gr.JSON(value=lambda: random.choice([{\"a\": 1}, {\"b\": 2}])),\n", " gr.HTML(\n", " value=lambda: random.choice(\n", " [\n", " '

I am red

',\n", " '

I am blue

',\n", " ]\n", " )\n", " ),\n", " gr.Gallery(\n", " value=lambda: images\n", " ),\n", " gr.Model3D(value=random_model3d),\n", " gr.Plot(value=random_plot),\n", " gr.Markdown(value=lambda: f\"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}\"),\n", "]\n", "\n", "\n", "def evaluate_values(*args):\n", " are_false = []\n", " for a in args:\n", " if isinstance(a, (pd.DataFrame, np.ndarray)):\n", " are_false.append(not a.any().any())\n", " elif isinstance(a, str) and a.startswith(\"#\"):\n", " are_false.append(a == \"#000000\")\n", " else:\n", " are_false.append(not a)\n", " return all(are_false)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " for i, component in enumerate(components):\n", " component.label = f\"component_{str(i).zfill(2)}\"\n", " component.render()\n", " clear = gr.ClearButton(value=\"Clear\", components=components)\n", " result = gr.Textbox(label=\"Are all cleared?\")\n", " hide = gr.Button(value=\"Hide\")\n", " reveal = gr.Button(value=\"Reveal\")\n", " hide.click(\n", " lambda: [c.__class__(visible=False) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " reveal.click(\n", " lambda: [c.__class__(visible=True) for c in components],\n", " inputs=[],\n", " outputs=components\n", " )\n", " get_value = gr.Button(value=\"Get Values\")\n", " get_value.click(evaluate_values, components, result)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/clearbutton_component/run.ipynb b/demo/clearbutton_component/run.ipynb index cf3b373bdf469..ddcf635a234ac 100644 --- a/demo/clearbutton_component/run.ipynb +++ b/demo/clearbutton_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: clearbutton_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", "\n", "with gr.Blocks() as demo:\n", " textbox = gr.Textbox(value=\"This is some text\")\n", " gr.ClearButton(textbox)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: clearbutton_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", "\n", "with gr.Blocks() as demo:\n", " textbox = gr.Textbox(value=\"This is some text\")\n", " gr.ClearButton(textbox)\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 index adfb40bc63556..b21a4c5d6ff99 100644 --- a/demo/clustering/run.ipynb +++ b/demo/clustering/run.ipynb @@ -1 +1,5 @@ -{"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-v0_8')\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", "if len(COLORS) <= MAX_CLUSTERS:\n", " raise ValueError(\"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 circles 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\"{title}\")\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 +<<<<<<< HEAD +{"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-v0_8')\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", "if len(COLORS) <= MAX_CLUSTERS:\n", " raise ValueError(\"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 circles 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\"{title}\")\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} +======= +{"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-v0_8')\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", "if len(COLORS) <= MAX_CLUSTERS:\n", " raise ValueError(\"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 circles 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\"{title}\")\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} +>>>>>>> main diff --git a/demo/code/run.ipynb b/demo/code/run.ipynb index bd0bb5efe2fe4..06f147924fcc1 100644 --- a/demo/code/run.ipynb +++ b/demo/code/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: code"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/code/file.css"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "from time import sleep\n", "\n", "\n", "css_file = os.path.join(os.path.abspath(''), \"file.css\")\n", "\n", "\n", "def set_lang(language):\n", " print(language)\n", " return gr.Code(language=language)\n", "\n", "\n", "def set_lang_from_path():\n", " sleep(1)\n", " return gr.Code((css_file,), language=\"css\")\n", "\n", "\n", "def code(language, code):\n", " return gr.Code(code, language=language)\n", "\n", "\n", "io = gr.Interface(lambda x: x, \"code\", \"code\")\n", "\n", "with gr.Blocks() as demo:\n", " lang = gr.Dropdown(value=\"python\", choices=gr.Code.languages)\n", " with gr.Row():\n", " code_in = gr.Code(\n", " language=\"python\",\n", " label=\"Input\",\n", " value='def all_odd_elements(sequence):\\n \"\"\"Returns every odd element of the sequence.\"\"\"',\n", " )\n", " code_out = gr.Code(label=\"Output\")\n", " btn = gr.Button(\"Run\")\n", " btn_two = gr.Button(\"Load File\")\n", "\n", " lang.change(set_lang, inputs=lang, outputs=code_in)\n", " btn.click(code, inputs=[lang, code_in], outputs=code_out)\n", " btn_two.click(set_lang_from_path, inputs=None, outputs=code_out)\n", " io.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: code"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/code/file.css"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "from time import sleep\n", "\n", "\n", "css_file = os.path.join(os.path.abspath(''), \"file.css\")\n", "\n", "\n", "def set_lang(language):\n", " print(language)\n", " return gr.Code(language=language)\n", "\n", "\n", "def set_lang_from_path():\n", " sleep(1)\n", " return gr.Code((css_file,), language=\"css\")\n", "\n", "\n", "def code(language, code):\n", " return gr.Code(code, language=language)\n", "\n", "\n", "io = gr.Interface(lambda x: x, \"code\", \"code\")\n", "\n", "with gr.Blocks() as demo:\n", " lang = gr.Dropdown(value=\"python\", choices=gr.Code.languages)\n", " with gr.Row():\n", " code_in = gr.Code(\n", " language=\"python\",\n", " label=\"Input\",\n", " value='def all_odd_elements(sequence):\\n \"\"\"Returns every odd element of the sequence.\"\"\"',\n", " )\n", " code_out = gr.Code(label=\"Output\")\n", " btn = gr.Button(\"Run\")\n", " btn_two = gr.Button(\"Load File\")\n", "\n", " lang.change(set_lang, inputs=lang, outputs=code_in)\n", " btn.click(code, inputs=[lang, code_in], outputs=code_out)\n", " btn_two.click(set_lang_from_path, inputs=None, outputs=code_out)\n", " io.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/code_component/run.ipynb b/demo/code_component/run.ipynb index 97c871f025da3..22ac4a3a17db8 100644 --- a/demo/code_component/run.ipynb +++ b/demo/code_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: code_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.Code(\n", " value=\"\"\"def hello_world():\n", " return \"Hello, world!\"\n", " \n", "print(hello_world())\"\"\",\n", " language=\"python\",\n", " interactive=True,\n", " show_label=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: code_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.Code(\n", " value=\"\"\"def hello_world():\n", " return \"Hello, world!\"\n", " \n", "print(hello_world())\"\"\",\n", " language=\"python\",\n", " interactive=True,\n", " show_label=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/color_generator/run.ipynb b/demo/color_generator/run.ipynb index 03faf48d55cb2..f36577da5d485 100644 --- a/demo/color_generator/run.ipynb +++ b/demo/color_generator/run.ipynb @@ -1 +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 +{"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 index eb0c1ebcc9692..83fed85097bad 100644 --- a/demo/color_picker/run.ipynb +++ b/demo/color_picker/run.ipynb @@ -1 +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 +{"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 index 349861e93766c..2e41a5c7ff5f2 100644 --- a/demo/colorpicker_component/run.ipynb +++ b/demo/colorpicker_component/run.ipynb @@ -1 +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 +{"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 index 2b7e0c7aa5eb2..52974299e2877 100644 --- a/demo/concurrency_with_queue/run.ipynb +++ b/demo/concurrency_with_queue/run.ipynb @@ -1 +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 +{"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 index 70f6cf54ddd94..5418a82d71c0d 100644 --- a/demo/concurrency_without_queue/run.ipynb +++ b/demo/concurrency_without_queue/run.ipynb @@ -1 +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 +{"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 index d38f56877869b..3a75d90ac0ff7 100644 --- a/demo/count_generator/run.ipynb +++ b/demo/count_generator/run.ipynb @@ -1 +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 +{"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 index 4506d6aee0d0c..453dad0ee04ae 100644 --- a/demo/dashboard/run.ipynb +++ b/demo/dashboard/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dashboard\n", "### This demo shows how you can build an interactive dashboard with gradio. Click on a python library on the left hand side and then on the right hand side click on the metric you'd like to see plot over time. Data is pulled from HuggingFace Hub datasets.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/dashboard/helpers.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "import plotly.express as px\n", "from helpers import *\n", "\n", "\n", "LIBRARIES = [\"accelerate\", \"datasets\", \"diffusers\", \"evaluate\", \"gradio\", \"hub_docs\",\n", " \"huggingface_hub\", \"optimum\", \"pytorch_image_models\", \"tokenizers\", \"transformers\"]\n", "\n", "\n", "def create_pip_plot(libraries, pip_choices):\n", " if \"Pip\" not in pip_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "def create_star_plot(libraries, star_choices):\n", " if \"Stars\" not in star_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "def create_issue_plot(libraries, issue_choices):\n", " if \"Issue\" not in issue_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Markdown(\"## Select libraries to display\")\n", " libraries = gr.CheckboxGroup(choices=LIBRARIES, show_label=False)\n", " with gr.Column():\n", " gr.Markdown(\"## Select graphs to display\")\n", " pip = gr.CheckboxGroup(choices=[\"Pip\", \"Cumulated\"], show_label=False)\n", " stars = gr.CheckboxGroup(choices=[\"Stars\", \"Week over Week\"], show_label=False)\n", " issues = gr.CheckboxGroup(choices=[\"Issue\", \"Exclude org members\", \"week over week\"], show_label=False)\n", " with gr.Row():\n", " fetch = gr.Button(value=\"Fetch\")\n", " with gr.Row():\n", " with gr.Column():\n", " pip_plot = gr.Plot(visible=False)\n", " star_plot = gr.Plot(visible=False)\n", " issue_plot = gr.Plot(visible=False)\n", "\n", " fetch.click(create_pip_plot, inputs=[libraries, pip], outputs=pip_plot)\n", " fetch.click(create_star_plot, inputs=[libraries, stars], outputs=star_plot)\n", " fetch.click(create_issue_plot, inputs=[libraries, issues], outputs=issue_plot)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: dashboard\n", "### This demo shows how you can build an interactive dashboard with gradio. Click on a python library on the left hand side and then on the right hand side click on the metric you'd like to see plot over time. Data is pulled from HuggingFace Hub datasets.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/dashboard/helpers.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import pandas as pd\n", "import plotly.express as px\n", "from helpers import *\n", "\n", "\n", "LIBRARIES = [\"accelerate\", \"datasets\", \"diffusers\", \"evaluate\", \"gradio\", \"hub_docs\",\n", " \"huggingface_hub\", \"optimum\", \"pytorch_image_models\", \"tokenizers\", \"transformers\"]\n", "\n", "\n", "def create_pip_plot(libraries, pip_choices):\n", " if \"Pip\" not in pip_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "def create_star_plot(libraries, star_choices):\n", " if \"Stars\" not in star_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "def create_issue_plot(libraries, issue_choices):\n", " if \"Issue\" not in issue_choices:\n", " return gr.Plot(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.Plot(value=plot, visible=True)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Markdown(\"## Select libraries to display\")\n", " libraries = gr.CheckboxGroup(choices=LIBRARIES, show_label=False)\n", " with gr.Column():\n", " gr.Markdown(\"## Select graphs to display\")\n", " pip = gr.CheckboxGroup(choices=[\"Pip\", \"Cumulated\"], show_label=False)\n", " stars = gr.CheckboxGroup(choices=[\"Stars\", \"Week over Week\"], show_label=False)\n", " issues = gr.CheckboxGroup(choices=[\"Issue\", \"Exclude org members\", \"week over week\"], show_label=False)\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} diff --git a/demo/dataframe_block-ui-test/run.ipynb b/demo/dataframe_block-ui-test/run.ipynb index 9c7dced1a1644..62b2ea6c3aafe 100644 --- a/demo/dataframe_block-ui-test/run.ipynb +++ b/demo/dataframe_block-ui-test/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataframe_block-ui-test"]}, {"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", " count = gr.Slider(minimum=1, maximum=10, step=1, label=\"count\")\n", " data = gr.DataFrame(\n", " headers=[\"A\", \"B\"], col_count=(2, \"fixed\"), type=\"array\", interactive=True\n", " )\n", " btn = gr.Button(value=\"click\")\n", " btn.click(\n", " fn=lambda cnt: [[str(2 * i), str(2 * i + 1)] for i in range(int(cnt))],\n", " inputs=[count],\n", " outputs=[data],\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: dataframe_block-ui-test"]}, {"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", " count = gr.Slider(minimum=1, maximum=10, step=1, label=\"count\")\n", " data = gr.DataFrame(\n", " headers=[\"A\", \"B\"], col_count=(2, \"fixed\"), type=\"array\", interactive=True\n", " )\n", " btn = gr.Button(value=\"click\")\n", " btn.click(\n", " fn=lambda cnt: [[str(2 * i), str(2 * i + 1)] for i in range(int(cnt))],\n", " inputs=[count],\n", " outputs=[data],\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/dataframe_colorful/run.ipynb b/demo/dataframe_colorful/run.ipynb index cf144477eaf6a..e7df93c5aa22b 100644 --- a/demo/dataframe_colorful/run.ipynb +++ b/demo/dataframe_colorful/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataframe_colorful"]}, {"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 pandas as pd \n", "import gradio as gr\n", "\n", "df = pd.DataFrame({\"A\" : [14, 4, 5, 4, 1], \n", "\t\t\t\t\"B\" : [5, 2, 54, 3, 2], \n", "\t\t\t\t\"C\" : [20, 20, 7, 3, 8], \n", "\t\t\t\t\"D\" : [14, 3, 6, 2, 6], \n", "\t\t\t\t\"E\" : [23, 45, 64, 32, 23]}) \n", "\n", "t = df.style.highlight_max(color = 'lightgreen', axis = 0)\n", "\n", "with gr.Blocks() as demo:\n", " gr.Dataframe(t)\n", " \n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataframe_colorful"]}, {"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 pandas as pd \n", "import gradio as gr\n", "\n", "df = pd.DataFrame({\"A\" : [14, 4, 5, 4, 1], \n", "\t\t\t\t\"B\" : [5, 2, 54, 3, 2], \n", "\t\t\t\t\"C\" : [20, 20, 7, 3, 8], \n", "\t\t\t\t\"D\" : [14, 3, 6, 2, 6], \n", "\t\t\t\t\"E\" : [23, 45, 64, 32, 23]}) \n", "\n", "t = df.style.highlight_max(color = 'lightgreen', axis = 0)\n", "\n", "with gr.Blocks() as demo:\n", " gr.Dataframe(t)\n", " \n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: dataframe_colorful"]}, {"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 pandas as pd \n", "import gradio as gr\n", "\n", "df = pd.DataFrame({\"A\" : [14, 4, 5, 4, 1], \n", "\t\t\t\t\"B\" : [5, 2, 54, 3, 2], \n", "\t\t\t\t\"C\" : [20, 20, 7, 3, 8], \n", "\t\t\t\t\"D\" : [14, 3, 6, 2, 6], \n", "\t\t\t\t\"E\" : [23, 45, 64, 32, 23]}) \n", "\n", "t = df.style.highlight_max(color = 'lightgreen', axis = 0)\n", "\n", "with gr.Blocks() as demo:\n", " gr.Dataframe(t)\n", " \n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/dataframe_component/run.ipynb b/demo/dataframe_component/run.ipynb index f0a4d750f33ed..8efac85a93a4f 100644 --- a/demo/dataframe_component/run.ipynb +++ b/demo/dataframe_component/run.ipynb @@ -1 +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 +{"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 index 6612fda6b6350..42654a0b5a6c4 100644 --- a/demo/dataframe_datatype/run.ipynb +++ b/demo/dataframe_datatype/run.ipynb @@ -1 +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 +{"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/dataset/run.ipynb b/demo/dataset/run.ipynb index e4f8677e27409..ed500d57d2928 100644 --- a/demo/dataset/run.ipynb +++ b/demo/dataset/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataset"]}, {"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/dataset/files/Bunny.obj\n", "!wget -q -O files/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/cheetah1.jpg\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/titanic.csv\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import numpy as np\n", "\n", "\n", "txt = \"the quick brown fox\"\n", "num = 10\n", "\n", "img = os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\")\n", "vid = os.path.join(os.path.abspath(''), \"files/world.mp4\")\n", "audio = os.path.join(os.path.abspath(''), \"files/cantina.wav\")\n", "csv = os.path.join(os.path.abspath(''), \"files/time.csv\")\n", "model = os.path.join(os.path.abspath(''), \"files/Bunny.obj\")\n", "\n", "dataframe = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]]\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"# Dataset previews\")\n", " a = gr.Audio(visible=False)\n", " gr.Dataset(\n", " components=[a],\n", " label=\"Audio\",\n", " samples=[\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " ],\n", " )\n", " c = gr.Checkbox(visible=False)\n", " gr.Dataset(\n", " label=\"Checkbox\",\n", " components=[c],\n", " samples=[[True], [True], [False], [True], [False], [False]],\n", " )\n", "\n", " c_2 = gr.CheckboxGroup(visible=False, choices=['a', 'b', 'c'])\n", " gr.Dataset(\n", " label=\"CheckboxGroup\",\n", " components=[c_2],\n", " samples=[\n", " [[\"a\"]],\n", " [[\"a\", \"b\"]],\n", " [[\"a\", \"b\", \"c\"]],\n", " [[\"b\"]],\n", " [[\"c\"]],\n", " [[\"a\", \"c\"]],\n", " ],\n", " )\n", " c_3 = gr.ColorPicker(visible=False)\n", " gr.Dataset(\n", " label=\"ColorPicker\",\n", " components=[c_3],\n", " samples=[\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " ],\n", " )\n", " d = gr.DataFrame(visible=False)\n", " gr.Dataset(\n", " components=[d],\n", " label=\"Dataframe\",\n", " samples=[\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", " )\n", " d_2 = gr.Dropdown(visible=False, choices=[\"one\", \"two\", \"three\"])\n", " gr.Dataset(\n", " components=[d_2],\n", " label=\"Dropdown\",\n", " samples=[[\"one\"], [\"two\"], [\"three\"], [\"one\"], [\"two\"], [\"three\"]],\n", " )\n", " f = gr.File(visible=False)\n", " gr.Dataset(\n", " components=[f],\n", " label=\"File\",\n", " samples=[\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " ],\n", " )\n", " h = gr.HTML(visible=False)\n", " gr.Dataset(\n", " components=[h],\n", " label=\"HTML\",\n", " samples=[\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " ],\n", " )\n", " i = gr.Image(visible=False)\n", " gr.Dataset(\n", " components=[i],\n", " label=\"Image\",\n", " samples=[[img], [img], [img], [img], [img], [img]],\n", " )\n", " m = gr.Markdown(visible=False)\n", " gr.Dataset(\n", " components=[m],\n", " label=\"Markdown\",\n", " samples=[\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " ],\n", " )\n", " m_2 = gr.Model3D(visible=False)\n", " gr.Dataset(\n", " components=[m_2],\n", " label=\"Model3D\",\n", " samples=[[model], [model], [model], [model], [model], [model]],\n", " )\n", " n = gr.Number(visible=False)\n", " gr.Dataset(\n", " label=\"Number\",\n", " components=[n],\n", " samples=[[1], [1], [1], [1], [1], [1]],\n", " )\n", " r = gr.Radio(visible=False, choices=[\"one\", \"two\", \"three\"])\n", " gr.Dataset(\n", " components=[r],\n", " label=\"Radio\",\n", " samples=[[\"one\"], [\"two\"], [\"three\"], [\"one\"], [\"two\"], [\"three\"]],\n", " )\n", " s = gr.Slider(visible=False)\n", " gr.Dataset(\n", " label=\"Slider\",\n", " components=[s],\n", " samples=[[1], [1], [1], [1], [1], [1]],\n", " )\n", " t = gr.Textbox(visible=False)\n", " gr.Dataset(\n", " label=\"Textbox\",\n", " components=[t],\n", " samples=[\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " ],\n", " )\n", " t_2 = gr.TimeSeries(visible=False)\n", " gr.Dataset(\n", " components=[t_2],\n", " label=\"TimeSeries\",\n", " samples=[[csv], [csv], [csv], [csv], [csv], [csv]],\n", " )\n", " v = gr.Video(visible=False)\n", " gr.Dataset(\n", " components=[v],\n", " label=\"Video\",\n", " samples=[[vid], [vid], [vid], [vid], [vid], [vid]],\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: dataset"]}, {"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/dataset/files/Bunny.obj\n", "!wget -q -O files/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/cheetah1.jpg\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/titanic.csv\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/dataset/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import numpy as np\n", "\n", "\n", "txt = \"the quick brown fox\"\n", "num = 10\n", "\n", "img = os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\")\n", "vid = os.path.join(os.path.abspath(''), \"files/world.mp4\")\n", "audio = os.path.join(os.path.abspath(''), \"files/cantina.wav\")\n", "csv = os.path.join(os.path.abspath(''), \"files/time.csv\")\n", "model = os.path.join(os.path.abspath(''), \"files/Bunny.obj\")\n", "\n", "dataframe = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]]\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"# Dataset previews\")\n", " a = gr.Audio(visible=False)\n", " gr.Dataset(\n", " components=[a],\n", " label=\"Audio\",\n", " samples=[\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " [audio],\n", " ],\n", " )\n", " c = gr.Checkbox(visible=False)\n", " gr.Dataset(\n", " label=\"Checkbox\",\n", " components=[c],\n", " samples=[[True], [True], [False], [True], [False], [False]],\n", " )\n", "\n", " c_2 = gr.CheckboxGroup(visible=False, choices=['a', 'b', 'c'])\n", " gr.Dataset(\n", " label=\"CheckboxGroup\",\n", " components=[c_2],\n", " samples=[\n", " [[\"a\"]],\n", " [[\"a\", \"b\"]],\n", " [[\"a\", \"b\", \"c\"]],\n", " [[\"b\"]],\n", " [[\"c\"]],\n", " [[\"a\", \"c\"]],\n", " ],\n", " )\n", " c_3 = gr.ColorPicker(visible=False)\n", " gr.Dataset(\n", " label=\"ColorPicker\",\n", " components=[c_3],\n", " samples=[\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " [\"#FFFFFF\"],\n", " [\"#000000\"],\n", " ],\n", " )\n", " d = gr.DataFrame(visible=False)\n", " gr.Dataset(\n", " components=[d],\n", " label=\"Dataframe\",\n", " samples=[\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", " )\n", " d_2 = gr.Dropdown(visible=False, choices=[\"one\", \"two\", \"three\"])\n", " gr.Dataset(\n", " components=[d_2],\n", " label=\"Dropdown\",\n", " samples=[[\"one\"], [\"two\"], [\"three\"], [\"one\"], [\"two\"], [\"three\"]],\n", " )\n", " f = gr.File(visible=False)\n", " gr.Dataset(\n", " components=[f],\n", " label=\"File\",\n", " samples=[\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " [csv],\n", " ],\n", " )\n", " h = gr.HTML(visible=False)\n", " gr.Dataset(\n", " components=[h],\n", " label=\"HTML\",\n", " samples=[\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " [\"

hi

\"],\n", " ],\n", " )\n", " i = gr.Image(visible=False)\n", " gr.Dataset(\n", " components=[i],\n", " label=\"Image\",\n", " samples=[[img], [img], [img], [img], [img], [img]],\n", " )\n", " m = gr.Markdown(visible=False)\n", " gr.Dataset(\n", " components=[m],\n", " label=\"Markdown\",\n", " samples=[\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " [\"# hi\"],\n", " ],\n", " )\n", " m_2 = gr.Model3D(visible=False)\n", " gr.Dataset(\n", " components=[m_2],\n", " label=\"Model3D\",\n", " samples=[[model], [model], [model], [model], [model], [model]],\n", " )\n", " n = gr.Number(visible=False)\n", " gr.Dataset(\n", " label=\"Number\",\n", " components=[n],\n", " samples=[[1], [1], [1], [1], [1], [1]],\n", " )\n", " r = gr.Radio(visible=False, choices=[\"one\", \"two\", \"three\"])\n", " gr.Dataset(\n", " components=[r],\n", " label=\"Radio\",\n", " samples=[[\"one\"], [\"two\"], [\"three\"], [\"one\"], [\"two\"], [\"three\"]],\n", " )\n", " s = gr.Slider(visible=False)\n", " gr.Dataset(\n", " label=\"Slider\",\n", " components=[s],\n", " samples=[[1], [1], [1], [1], [1], [1]],\n", " )\n", " t = gr.Textbox(visible=False)\n", " gr.Dataset(\n", " label=\"Textbox\",\n", " components=[t],\n", " samples=[\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " [\"Some value\"],\n", " ],\n", " )\n", " t_2 = gr.TimeSeries(visible=False)\n", " gr.Dataset(\n", " components=[t_2],\n", " label=\"TimeSeries\",\n", " samples=[[csv], [csv], [csv], [csv], [csv], [csv]],\n", " )\n", " v = gr.Video(visible=False)\n", " gr.Dataset(\n", " components=[v],\n", " label=\"Video\",\n", " samples=[[vid], [vid], [vid], [vid], [vid], [vid]],\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/dataset_component/run.ipynb b/demo/dataset_component/run.ipynb index 86172b29f85c8..00645124315cd 100644 --- a/demo/dataset_component/run.ipynb +++ b/demo/dataset_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: dataset_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.Dataset(components=[gr.Textbox(visible=False)],\n", " label=\"Text Dataset\",\n", " samples=[\n", " [\"The quick brown fox jumps over the lazy dog\"],\n", " [\"Build & share delightful machine learning apps\"],\n", " [\"She sells seashells by the seashore\"],\n", " [\"Supercalifragilisticexpialidocious\"],\n", " [\"Lorem ipsum\"],\n", " [\"That's all folks!\"]\n", " ],\n", " )\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: dataset_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.Dataset(components=[gr.Textbox(visible=False)],\n", " label=\"Text Dataset\",\n", " samples=[\n", " [\"The quick brown fox jumps over the lazy dog\"],\n", " [\"Build & share delightful machine learning apps\"],\n", " [\"She sells seashells by the seashore\"],\n", " [\"Supercalifragilisticexpialidocious\"],\n", " [\"Lorem ipsum\"],\n", " [\"That's all folks!\"]\n", " ],\n", " )\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 index 0907dd406d4ad..f27d6742f9308 100644 --- a/demo/depth_estimation/run.ipynb +++ b/demo/depth_estimation/run.ipynb @@ -1 +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", "\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:\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):\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 DPT Demo. 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 +{"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", "\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:\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):\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 DPT Demo. 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 index b83ece9c396d2..44143c71cfc3d 100644 --- a/demo/diff_texts/run.ipynb +++ b/demo/diff_texts/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: diff_texts"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from difflib import Differ\n", "\n", "import gradio as gr\n", "\n", "\n", "def diff_texts(text1, text2):\n", " d = Differ()\n", " return [\n", " (token[2:], token[0] if token[0] != \" \" else None)\n", " for token in d.compare(text1, text2)\n", " ]\n", "\n", "\n", "demo = gr.Interface(\n", " diff_texts,\n", " [\n", " gr.Textbox(\n", " label=\"Text 1\",\n", " info=\"Initial text\",\n", " lines=3,\n", " value=\"The quick brown fox jumped over the lazy dogs.\",\n", " ),\n", " gr.Textbox(\n", " label=\"Text 2\",\n", " info=\"Text to compare\",\n", " lines=3,\n", " value=\"The fast brown fox jumps over lazy dogs.\",\n", " ),\n", " ],\n", " gr.HighlightedText(\n", " label=\"Diff\",\n", " combine_adjacent=True,\n", " show_legend=True,\n", " color_map={\"+\": \"red\", \"-\": \"green\"}),\n", " theme=gr.themes.Base()\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: diff_texts"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["from difflib import Differ\n", "\n", "import gradio as gr\n", "\n", "\n", "def diff_texts(text1, text2):\n", " d = Differ()\n", " return [\n", " (token[2:], token[0] if token[0] != \" \" else None)\n", " for token in d.compare(text1, text2)\n", " ]\n", "\n", "\n", "demo = gr.Interface(\n", " diff_texts,\n", " [\n", " gr.Textbox(\n", " label=\"Text 1\",\n", " info=\"Initial text\",\n", " lines=3,\n", " value=\"The quick brown fox jumped over the lazy dogs.\",\n", " ),\n", " gr.Textbox(\n", " label=\"Text 2\",\n", " info=\"Text to compare\",\n", " lines=3,\n", " value=\"The fast brown fox jumps over lazy dogs.\",\n", " ),\n", " ],\n", " gr.HighlightedText(\n", " label=\"Diff\",\n", " combine_adjacent=True,\n", " show_legend=True,\n", " color_map={\"+\": \"red\", \"-\": \"green\"}),\n", " theme=gr.themes.Base()\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/diffusers_with_batching/run.ipynb b/demo/diffusers_with_batching/run.ipynb index 9313209a63d85..03fd6cbc7afc7 100644 --- a/demo/diffusers_with_batching/run.ipynb +++ b/demo/diffusers_with_batching/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: diffusers_with_batching"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch transformers diffusers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import torch\n", "from diffusers import DiffusionPipeline\n", "import gradio as gr\n", "\n", "generator = DiffusionPipeline.from_pretrained(\"CompVis/ldm-text2im-large-256\")\n", "# move to GPU if available\n", "if torch.cuda.is_available():\n", " generator = generator.to(\"cuda\")\n", "\n", "def generate(prompts):\n", " images = generator(list(prompts)).images\n", " return [images]\n", "\n", "demo = gr.Interface(generate, \n", " \"textbox\", \n", " \"image\", \n", " batch=True, \n", " max_batch_size=4 # Set the batch size based on your CPU/GPU memory\n", ").queue()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: diffusers_with_batching"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch transformers diffusers"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import torch\n", "from diffusers import DiffusionPipeline\n", "import gradio as gr\n", "\n", "generator = DiffusionPipeline.from_pretrained(\"CompVis/ldm-text2im-large-256\")\n", "# move to GPU if available\n", "if torch.cuda.is_available():\n", " generator = generator.to(\"cuda\")\n", "\n", "def generate(prompts):\n", " images = generator(list(prompts)).images\n", " return [images]\n", "\n", "demo = gr.Interface(generate, \n", " \"textbox\", \n", " \"image\", \n", " batch=True, \n", " max_batch_size=4 # Set the batch size based on your CPU/GPU memory\n", ").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/digit_classifier/run.ipynb b/demo/digit_classifier/run.ipynb index a2610e73cb4c5..2345584b1b4eb 100644 --- a/demo/digit_classifier/run.ipynb +++ b/demo/digit_classifier/run.ipynb @@ -1 +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": ["from urllib.request import urlretrieve\n", "\n", "import tensorflow as tf\n", "\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 = gr.Image(shape=(28, 28), image_mode=\"L\", invert_colors=False, source=\"canvas\")\n", "\n", "demo = gr.Interface(\n", " recognize_digit,\n", " im,\n", " gr.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 +{"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": ["from urllib.request import urlretrieve\n", "\n", "import tensorflow as tf\n", "\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 = gr.Image(shape=(28, 28), image_mode=\"L\", invert_colors=False, source=\"canvas\")\n", "\n", "demo = gr.Interface(\n", " recognize_digit,\n", " im,\n", " gr.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 index ba98c10620a20..b4fe8baf63f6d 100644 --- a/demo/dropdown_component/run.ipynb +++ b/demo/dropdown_component/run.ipynb @@ -1 +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 +{"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/duplicatebutton_component/run.ipynb b/demo/duplicatebutton_component/run.ipynb index 712304fbee663..af5cb73164434 100644 --- a/demo/duplicatebutton_component/run.ipynb +++ b/demo/duplicatebutton_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: duplicatebutton_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.DuplicateButton()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: duplicatebutton_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.DuplicateButton()\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 index e8dde5b1e0716..eb3f9893220d2 100644 --- a/demo/english_translator/run.ipynb +++ b/demo/english_translator/run.ipynb @@ -1 +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 +{"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/event_trigger/run.ipynb b/demo/event_trigger/run.ipynb index 66ed05b489ada..62ddb0dcc111b 100644 --- a/demo/event_trigger/run.ipynb +++ b/demo/event_trigger/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: event_trigger"]}, {"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('img')\n", "!wget -q -O img/a.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/a.jpg\n", "!wget -q -O img/b.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/b.jpg\n", "os.mkdir('mp4')\n", "!wget -q -O mp4/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/a.mp4\n", "!wget -q -O mp4/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/b.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# %%\n", "import gradio as gr\n", "\n", "\n", "TEST_VIDEO_A = \"mp4/a.mp4\"\n", "TEST_VIDEO_B = \"mp4/b.mp4\"\n", "\n", "TEST_IMAGE_A = \"img/a.jpg\"\n", "TEST_IMAGE_B = \"img/b.jpg\"\n", "\n", "\n", "def alert_change(component, value):\n", " print(f\"Detected {component} change, {type(value)}\")\n", "\n", " if type(value) == list or type(value) == str:\n", " print(value)\n", "\n", "\n", "def change_interactive(state):\n", " return gr.Video(interactive=not state), not state\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(label=\"Text change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " textbox1 = gr.Textbox()\n", " textbox2 = gr.Textbox(interactive=True)\n", "\n", " with gr.Column():\n", " btn = gr.Button()\n", "\n", " def btn_click(state):\n", " return state\n", "\n", " def text_change(value):\n", " print(\"text_change\", value)\n", "\n", " btn.click(fn=btn_click, inputs=textbox1, outputs=textbox2)\n", " textbox2.change(fn=alert_change, inputs=[gr.State(\"Text\"), textbox2])\n", "\n", " with gr.Tab(label=\"Video change, play, pause\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio1 = gr.Radio(\n", " choices=[TEST_VIDEO_A, TEST_VIDEO_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " video_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " video1 = gr.Video(value=TEST_VIDEO_A, interactive=False)\n", " video1_interactive = gr.State(value=False)\n", "\n", " def change_video(index):\n", " if index == 0:\n", " return TEST_VIDEO_A\n", " elif index == 1:\n", " return TEST_VIDEO_B\n", "\n", " def video_play():\n", " print(\"video_play\")\n", "\n", " def video_pause():\n", " print(\"video_pause\")\n", "\n", " def video_stop():\n", " print(\"video_stop\")\n", "\n", " def video_end():\n", " print(\"video_end\")\n", "\n", " video1.play(fn=video_play)\n", " video1.pause(fn=video_pause)\n", " video1.stop(fn=video_stop)\n", " video1.end(fn=video_end)\n", "\n", " radio1.change(fn=change_video, inputs=radio1, outputs=video1)\n", " video1.change(fn=alert_change, inputs=[gr.State(\"Video\"), video1])\n", "\n", " video_btn.click(\n", " fn=change_interactive,\n", " inputs=video1_interactive,\n", " outputs=[video1, video1_interactive],\n", " )\n", "\n", " with gr.Tab(label=\"Image change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio2 = gr.Radio(\n", " choices=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " with gr.Column():\n", " image1 = gr.Image(value=TEST_IMAGE_A, interactive=True)\n", "\n", " def change_image(index):\n", " if index == 0:\n", " return TEST_IMAGE_A\n", " elif index == 1:\n", " return TEST_IMAGE_B\n", "\n", " radio2.change(fn=change_image, inputs=radio2, outputs=image1)\n", " image1.change(fn=alert_change, inputs=[gr.State(\"Image\"), image1])\n", "\n", " with gr.Tab(label=\"File\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio3 = gr.Radio(\n", " choices=[\"A\", \"B\", \"AB\"],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " file_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " file1 = gr.File(\n", " value=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=False,\n", " file_count=\"multiple\",\n", " )\n", " file1_interactive = gr.State(value=False)\n", "\n", " def change_file(index):\n", " if index == 0:\n", " return [TEST_IMAGE_A]\n", " elif index == 1:\n", " return [TEST_IMAGE_A]\n", " elif index == 2:\n", " return [TEST_IMAGE_A, TEST_IMAGE_B]\n", "\n", " radio3.change(fn=change_file, inputs=radio3, outputs=file1)\n", " file1.change(fn=alert_change, inputs=[gr.State(\"File\"), file1])\n", "\n", " file_btn.click(\n", " fn=change_interactive,\n", " inputs=file1_interactive,\n", " outputs=[file1, file1_interactive],\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: event_trigger"]}, {"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('img')\n", "!wget -q -O img/a.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/a.jpg\n", "!wget -q -O img/b.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/b.jpg\n", "os.mkdir('mp4')\n", "!wget -q -O mp4/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/a.mp4\n", "!wget -q -O mp4/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/b.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["# %%\n", "import gradio as gr\n", "\n", "\n", "TEST_VIDEO_A = \"mp4/a.mp4\"\n", "TEST_VIDEO_B = \"mp4/b.mp4\"\n", "\n", "TEST_IMAGE_A = \"img/a.jpg\"\n", "TEST_IMAGE_B = \"img/b.jpg\"\n", "\n", "\n", "def alert_change(component, value):\n", " print(f\"Detected {component} change, {type(value)}\")\n", "\n", " if type(value) == list or type(value) == str:\n", " print(value)\n", "\n", "\n", "def change_interactive(state):\n", " return gr.Video(interactive=not state), not state\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(label=\"Text change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " textbox1 = gr.Textbox()\n", " textbox2 = gr.Textbox(interactive=True)\n", "\n", " with gr.Column():\n", " btn = gr.Button()\n", "\n", " def btn_click(state):\n", " return state\n", "\n", " def text_change(value):\n", " print(\"text_change\", value)\n", "\n", " btn.click(fn=btn_click, inputs=textbox1, outputs=textbox2)\n", " textbox2.change(fn=alert_change, inputs=[gr.State(\"Text\"), textbox2])\n", "\n", " with gr.Tab(label=\"Video change, play, pause\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio1 = gr.Radio(\n", " choices=[TEST_VIDEO_A, TEST_VIDEO_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " video_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " video1 = gr.Video(value=TEST_VIDEO_A, interactive=False)\n", " video1_interactive = gr.State(value=False)\n", "\n", " def change_video(index):\n", " if index == 0:\n", " return TEST_VIDEO_A\n", " elif index == 1:\n", " return TEST_VIDEO_B\n", "\n", " def video_play():\n", " print(\"video_play\")\n", "\n", " def video_pause():\n", " print(\"video_pause\")\n", "\n", " def video_stop():\n", " print(\"video_stop\")\n", "\n", " def video_end():\n", " print(\"video_end\")\n", "\n", " video1.play(fn=video_play)\n", " video1.pause(fn=video_pause)\n", " video1.stop(fn=video_stop)\n", " video1.end(fn=video_end)\n", "\n", " radio1.change(fn=change_video, inputs=radio1, outputs=video1)\n", " video1.change(fn=alert_change, inputs=[gr.State(\"Video\"), video1])\n", "\n", " video_btn.click(\n", " fn=change_interactive,\n", " inputs=video1_interactive,\n", " outputs=[video1, video1_interactive],\n", " )\n", "\n", " with gr.Tab(label=\"Image change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio2 = gr.Radio(\n", " choices=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " with gr.Column():\n", " image1 = gr.Image(value=TEST_IMAGE_A, interactive=True)\n", "\n", " def change_image(index):\n", " if index == 0:\n", " return TEST_IMAGE_A\n", " elif index == 1:\n", " return TEST_IMAGE_B\n", "\n", " radio2.change(fn=change_image, inputs=radio2, outputs=image1)\n", " image1.change(fn=alert_change, inputs=[gr.State(\"Image\"), image1])\n", "\n", " with gr.Tab(label=\"File\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio3 = gr.Radio(\n", " choices=[\"A\", \"B\", \"AB\"],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " file_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " file1 = gr.File(\n", " value=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=False,\n", " file_count=\"multiple\",\n", " )\n", " file1_interactive = gr.State(value=False)\n", "\n", " def change_file(index):\n", " if index == 0:\n", " return [TEST_IMAGE_A]\n", " elif index == 1:\n", " return [TEST_IMAGE_A]\n", " elif index == 2:\n", " return [TEST_IMAGE_A, TEST_IMAGE_B]\n", "\n", " radio3.change(fn=change_file, inputs=radio3, outputs=file1)\n", " file1.change(fn=alert_change, inputs=[gr.State(\"File\"), file1])\n", "\n", " file_btn.click(\n", " fn=change_interactive,\n", " inputs=file1_interactive,\n", " outputs=[file1, file1_interactive],\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/examples_component/run.ipynb b/demo/examples_component/run.ipynb index 93c0f78cdab1e..ec52d7767f2f9 100644 --- a/demo/examples_component/run.ipynb +++ b/demo/examples_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: examples_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": ["# 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/examples_component/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/lion.jpg\n", "!wget -q -O images/lion.webp https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/lion.webp\n", "!wget -q -O images/logo.png https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/logo.png"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "def flip(i):\n", " return i.rotate(180)\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " img_i = gr.Image(label=\"Input Image\", type=\"pil\")\n", " with gr.Column():\n", " img_o = gr.Image(label=\"Output Image\")\n", " with gr.Row():\n", " btn = gr.Button(value=\"Flip Image\")\n", " btn.click(flip, inputs=[img_i], outputs=[img_o])\n", "\n", " gr.Examples(\n", " [ \n", " os.path.join(os.path.abspath(''), \"images/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"images/lion.jpg\"),\n", " ],\n", " img_i,\n", " img_o,\n", " flip\n", " )\n", " \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: examples_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": ["# 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/examples_component/images/cheetah1.jpg\n", "!wget -q -O images/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/lion.jpg\n", "!wget -q -O images/lion.webp https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/lion.webp\n", "!wget -q -O images/logo.png https://github.com/gradio-app/gradio/raw/main/demo/examples_component/images/logo.png"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "def flip(i):\n", " return i.rotate(180)\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " img_i = gr.Image(label=\"Input Image\", type=\"pil\")\n", " with gr.Column():\n", " img_o = gr.Image(label=\"Output Image\")\n", " with gr.Row():\n", " btn = gr.Button(value=\"Flip Image\")\n", " btn.click(flip, inputs=[img_i], outputs=[img_o])\n", "\n", " gr.Examples(\n", " [ \n", " os.path.join(os.path.abspath(''), \"images/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"images/lion.jpg\"),\n", " ],\n", " img_i,\n", " img_o,\n", " flip\n", " )\n", " \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 index 150075f9ed908..72dd6b0c20346 100644 --- a/demo/fake_diffusion/run.ipynb +++ b/demo/fake_diffusion/run.ipynb @@ -1 +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", " image = \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\"\n", " yield image\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, inputs=gr.Slider(1, 10, 3), outputs=\"image\")\n", "\n", "# define queue - required for generators\n", "demo.queue()\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: fake_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", " image = \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\"\n", " yield image\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, inputs=gr.Slider(1, 10, 3), outputs=\"image\")\n", "\n", "# define queue - required for generators\n", "demo.queue()\n", "\n", "demo.launch()\n"]}], "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 index a6f27a41349a3..da430b0a53a1d 100644 --- a/demo/fake_diffusion_with_gif/run.ipynb +++ b/demo/fake_diffusion_with_gif/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_diffusion_with_gif"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# 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(visible=False)\n", " \n", " time.sleep(1)\n", " image = \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\" \n", " images.append(image)\n", " gif_path = create_gif(images)\n", " \n", " yield image, gr.Image(value=gif_path, visible=True)\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, \n", " inputs=gr.Slider(1, 10, 3), \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 +{"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(visible=False)\n", " \n", " time.sleep(1)\n", " image = \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\" \n", " images.append(image)\n", " gif_path = create_gif(images)\n", " \n", " yield image, gr.Image(value=gif_path, visible=True)\n", "\n", "\n", "demo = gr.Interface(fake_diffusion, \n", " inputs=gr.Slider(1, 10, 3), \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 index cd6cfb3d37631..e0c21f7cb4d35 100644 --- a/demo/fake_gan/run.ipynb +++ b/demo/fake_gan/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan\n", "### This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " images = [\n", " (random.choice(\n", " [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " \"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80\",\n", " ]\n", " ), f\"label {i}\" if i != 0 else \"label\" * 50)\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column(variant=\"panel\"):\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\", scale=0)\n", "\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " , columns=[2], rows=[2], object_fit=\"contain\", height=\"auto\")\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: fake_gan\n", "### This is a fake GAN that shows how to create a text-to-image interface for image generation. Check out the Stable Diffusion demo for more: https://hf.co/spaces/stabilityai/stable-diffusion/\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/fake_gan/files/cheetah1.jpg"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["# This demo needs to be run from the repo folder.\n", "# python demo/fake_gan/run.py\n", "import random\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " images = [\n", " (random.choice(\n", " [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " \"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80\",\n", " ]\n", " ), f\"label {i}\" if i != 0 else \"label\" * 50)\n", " for i in range(3)\n", " ]\n", " return images\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column(variant=\"panel\"):\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\", scale=0)\n", "\n", " gallery = gr.Gallery(\n", " label=\"Generated images\", show_label=False, elem_id=\"gallery\"\n", " , columns=[2], rows=[2], object_fit=\"contain\", height=\"auto\")\n", "\n", " btn.click(fake_gan, None, gallery)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/fake_gan_2/run.ipynb b/demo/fake_gan_2/run.ipynb index 1abe0a0999136..fd35b2f5389fe 100644 --- a/demo/fake_gan_2/run.ipynb +++ b/demo/fake_gan_2/run.ipynb @@ -1 +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 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(9)\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 +{"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 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(9)\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 index 411088e0f7008..2bc045f386c1c 100644 --- a/demo/fake_gan_no_input/run.ipynb +++ b/demo/fake_gan_no_input/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: fake_gan_no_input"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import time\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " time.sleep(1)\n", " images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " ]\n", " return images\n", "\n", "\n", "demo = gr.Interface(\n", " fn=fake_gan,\n", " inputs=None,\n", " outputs=gr.Gallery(label=\"Generated Images\", columns=[2]),\n", " title=\"FD-GAN\",\n", " description=\"This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: fake_gan_no_input"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import time\n", "\n", "import gradio as gr\n", "\n", "\n", "def fake_gan():\n", " time.sleep(1)\n", " images = [\n", " \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n", " \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n", " \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n", " ]\n", " return images\n", "\n", "\n", "demo = gr.Interface(\n", " fn=fake_gan,\n", " inputs=None,\n", " outputs=gr.Gallery(label=\"Generated Images\", columns=[2]),\n", " title=\"FD-GAN\",\n", " description=\"This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/file_component/run.ipynb b/demo/file_component/run.ipynb index 02b6ef749bf78..ea487a02e3dfd 100644 --- a/demo/file_component/run.ipynb +++ b/demo/file_component/run.ipynb @@ -1 +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 +{"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/file_explorer/run.ipynb b/demo/file_explorer/run.ipynb index de782294fca5e..50d6410edf6f8 100644 --- a/demo/file_explorer/run.ipynb +++ b/demo/file_explorer/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: file_explorer"]}, {"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", "from pathlib import Path\n", "\n", "current_file_path = Path(__file__).resolve()\n", "relative_path = \"path/to/file\"\n", "absolute_path = (current_file_path.parent / \"..\" / \"..\" / \"gradio\").resolve()\n", "\n", "\n", "def get_file_content(file):\n", " return (file,)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown('### `FileExplorer` to `FileExplorer` -- `file_count=\"multiple\"`')\n", " submit_btn = gr.Button(\"Select\")\n", " with gr.Row():\n", " file = gr.FileExplorer(\n", " glob=\"**/{components,themes}/*.py\",\n", " # value=[\"themes/utils\"],\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", "\n", " file2 = gr.FileExplorer(\n", " glob=\"**/{components,themes}/**/*.py\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", " submit_btn.click(lambda x: x, file, file2)\n", "\n", " gr.Markdown(\"---\")\n", " gr.Markdown('### `FileExplorer` to `Code` -- `file_count=\"single\"`')\n", " with gr.Group():\n", " with gr.Row():\n", " file_3 = gr.FileExplorer(\n", " scale=1,\n", " glob=\"**/{components,themes}/**/*.py\",\n", " value=[\"themes/utils\"],\n", " file_count=\"single\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " elem_id=\"file\",\n", " )\n", "\n", " code = gr.Code(lines=30, scale=2, language=\"python\")\n", "\n", " file_3.change(get_file_content, file_3, code)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: file_explorer"]}, {"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", "from pathlib import Path\n", "\n", "current_file_path = Path(__file__).resolve()\n", "relative_path = \"path/to/file\"\n", "absolute_path = (current_file_path.parent / \"..\" / \"..\" / \"gradio\").resolve()\n", "\n", "\n", "def get_file_content(file):\n", " return (file,)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown('### `FileExplorer` to `FileExplorer` -- `file_count=\"multiple\"`')\n", " submit_btn = gr.Button(\"Select\")\n", " with gr.Row():\n", " file = gr.FileExplorer(\n", " glob=\"**/{components,themes}/*.py\",\n", " # value=[\"themes/utils\"],\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", "\n", " file2 = gr.FileExplorer(\n", " glob=\"**/{components,themes}/**/*.py\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", " submit_btn.click(lambda x: x, file, file2)\n", "\n", " gr.Markdown(\"---\")\n", " gr.Markdown('### `FileExplorer` to `Code` -- `file_count=\"single\"`')\n", " with gr.Group():\n", " with gr.Row():\n", " file_3 = gr.FileExplorer(\n", " scale=1,\n", " glob=\"**/{components,themes}/**/*.py\",\n", " value=[\"themes/utils\"],\n", " file_count=\"single\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " elem_id=\"file\",\n", " )\n", "\n", " code = gr.Code(lines=30, scale=2, language=\"python\")\n", "\n", " file_3.change(get_file_content, file_3, code)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: file_explorer"]}, {"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", "from pathlib import Path\n", "\n", "current_file_path = Path(__file__).resolve()\n", "relative_path = \"path/to/file\"\n", "absolute_path = (current_file_path.parent / \"..\" / \"..\" / \"gradio\").resolve()\n", "\n", "\n", "def get_file_content(file):\n", " return (file,)\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown('### `FileExplorer` to `FileExplorer` -- `file_count=\"multiple\"`')\n", " submit_btn = gr.Button(\"Select\")\n", " with gr.Row():\n", " file = gr.FileExplorer(\n", " glob=\"**/{components,themes}/*.py\",\n", " # value=[\"themes/utils\"],\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", "\n", " file2 = gr.FileExplorer(\n", " glob=\"**/{components,themes}/**/*.py\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " )\n", " submit_btn.click(lambda x: x, file, file2)\n", "\n", " gr.Markdown(\"---\")\n", " gr.Markdown('### `FileExplorer` to `Code` -- `file_count=\"single\"`')\n", " with gr.Group():\n", " with gr.Row():\n", " file_3 = gr.FileExplorer(\n", " scale=1,\n", " glob=\"**/{components,themes}/**/*.py\",\n", " value=[\"themes/utils\"],\n", " file_count=\"single\",\n", " root=absolute_path,\n", " ignore_glob=\"**/__init__.py\",\n", " elem_id=\"file\",\n", " )\n", "\n", " code = gr.Code(lines=30, scale=2, language=\"python\")\n", "\n", " file_3.change(get_file_content, file_3, code)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/file_explorer_component/run.ipynb b/demo/file_explorer_component/run.ipynb index 7fe5d2d80d21a..3502445a74f10 100644 --- a/demo/file_explorer_component/run.ipynb +++ b/demo/file_explorer_component/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: file_explorer_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.FileExplorer()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: file_explorer_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.FileExplorer()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: file_explorer_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.FileExplorer()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/filter_records/run.ipynb b/demo/filter_records/run.ipynb index d516e909bd451..1b25ad97263e2 100644 --- a/demo/filter_records/run.ipynb +++ b/demo/filter_records/run.ipynb @@ -1 +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 +{"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 index 7a36875ebe7e1..8b4a2b35dfc5e 100644 --- a/demo/fraud_detector/run.ipynb +++ b/demo/fraud_detector/run.ipynb @@ -1 +1,5 @@ -{"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.CheckboxGroup(\n", " [\"retail\", \"food\", \"other\"], value=[\"retail\", \"food\", \"other\"]\n", " ),\n", " gr.Slider(1, 3),\n", " ],\n", " [\n", " \"dataframe\",\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 +<<<<<<< HEAD +{"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.CheckboxGroup(\n", " [\"retail\", \"food\", \"other\"], value=[\"retail\", \"food\", \"other\"]\n", " ),\n", " gr.Slider(1, 3),\n", " ],\n", " [\n", " \"dataframe\",\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} +======= +{"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} +>>>>>>> main diff --git a/demo/gallery_component/run.ipynb b/demo/gallery_component/run.ipynb index 875dea1801426..c76f30131a09d 100644 --- a/demo/gallery_component/run.ipynb +++ b/demo/gallery_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gallery_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " cheetahs = [\n", " \"https://upload.wikimedia.org/wikipedia/commons/0/09/TheCheethcat.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-003.jpg\",\n", " \"https://img.etimg.com/thumb/msid-50159822,width-650,imgsize-129520,,resizemode-4,quality-100/.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-002.jpg\",\n", " \"https://images.theconversation.com/files/375893/original/file-20201218-13-a8h8uq.jpg?ixlib=rb-1.1.0&rect=16%2C407%2C5515%2C2924&q=45&auto=format&w=496&fit=clip\",\n", " \"https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg\",\n", " \"https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq\"\n", " ]\n", " gr.Gallery(value=cheetahs, columns=4)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: gallery_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " cheetahs = [\n", " \"https://upload.wikimedia.org/wikipedia/commons/0/09/TheCheethcat.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-003.jpg\",\n", " \"https://img.etimg.com/thumb/msid-50159822,width-650,imgsize-129520,,resizemode-4,quality-100/.jpg\",\n", " \"https://nationalzoo.si.edu/sites/default/files/animals/cheetah-002.jpg\",\n", " \"https://images.theconversation.com/files/375893/original/file-20201218-13-a8h8uq.jpg?ixlib=rb-1.1.0&rect=16%2C407%2C5515%2C2924&q=45&auto=format&w=496&fit=clip\",\n", " \"https://www.lifegate.com/app/uploads/ghepardo-primo-piano.jpg\",\n", " \"https://qph.cf2.quoracdn.net/main-qimg-0bbf31c18a22178cb7a8dd53640a3d05-lq\"\n", " ]\n", " gr.Gallery(value=cheetahs, columns=4)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/gallery_selections/run.ipynb b/demo/gallery_selections/run.ipynb index ad6759aa04dc8..23d890efbf3a9 100644 --- a/demo/gallery_selections/run.ipynb +++ b/demo/gallery_selections/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gallery_selections"]}, {"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", "with gr.Blocks() as demo:\n", " imgs = gr.State()\n", " gallery = gr.Gallery()\n", "\n", " def generate_images():\n", " images = []\n", " for _ in range(9):\n", " image = np.ones((100, 100, 3), dtype=np.uint8) * np.random.randint(\n", " 0, 255, 3\n", " ) # image is a solid single color\n", " images.append(image)\n", " return images, images\n", "\n", " demo.load(generate_images, None, [gallery, imgs])\n", "\n", " with gr.Row():\n", " selected = gr.Number(show_label=False, placeholder=\"Selected\")\n", " darken_btn = gr.Button(\"Darken selected\")\n", "\n", " def get_select_index(evt: gr.SelectData):\n", " return evt.index\n", "\n", " gallery.select(get_select_index, None, selected)\n", "\n", " def darken_img(imgs, index):\n", " index = int(index)\n", " imgs[index] = np.round(imgs[index] * 0.8).astype(np.uint8)\n", " return imgs, imgs\n", "\n", " darken_btn.click(darken_img, [imgs, selected], [imgs, gallery])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: gallery_selections"]}, {"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", "with gr.Blocks() as demo:\n", " imgs = gr.State()\n", " gallery = gr.Gallery()\n", "\n", " def generate_images():\n", " images = []\n", " for _ in range(9):\n", " image = np.ones((100, 100, 3), dtype=np.uint8) * np.random.randint(\n", " 0, 255, 3\n", " ) # image is a solid single color\n", " images.append(image)\n", " return images, images\n", "\n", " demo.load(generate_images, None, [gallery, imgs])\n", "\n", " with gr.Row():\n", " selected = gr.Number(show_label=False, placeholder=\"Selected\")\n", " darken_btn = gr.Button(\"Darken selected\")\n", "\n", " def get_select_index(evt: gr.SelectData):\n", " return evt.index\n", "\n", " gallery.select(get_select_index, None, selected)\n", "\n", " def darken_img(imgs, index):\n", " index = int(index)\n", " imgs[index] = np.round(imgs[index] * 0.8).astype(np.uint8)\n", " return imgs, imgs\n", "\n", " darken_btn.click(darken_img, [imgs, selected], [imgs, 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/gender_sentence_custom_interpretation/run.ipynb b/demo/gender_sentence_custom_interpretation/run.ipynb index cf59fce2aa5db..2dc98cc290136 100644 --- a/demo/gender_sentence_custom_interpretation/run.ipynb +++ b/demo/gender_sentence_custom_interpretation/run.ipynb @@ -1 +1,5 @@ -{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/gender_sentence_default_interpretation/run.ipynb b/demo/gender_sentence_default_interpretation/run.ipynb index e175e166e7cab..d9b9fa5ff6141 100644 --- a/demo/gender_sentence_default_interpretation/run.ipynb +++ b/demo/gender_sentence_default_interpretation/run.ipynb @@ -1 +1,5 @@ -{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/generate_english_german/run.ipynb b/demo/generate_english_german/run.ipynb index 475e069021e87..15de5a6d8d2bd 100644 --- a/demo/generate_english_german/run.ipynb +++ b/demo/generate_english_german/run.ipynb @@ -1 +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 +{"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 index a1644742ec499..dcc0f62f63e35 100644 --- a/demo/generate_notebooks.py +++ b/demo/generate_notebooks.py @@ -76,7 +76,7 @@ def git_tracked(demo, file): content = json.loads(content) for i, cell in enumerate(content["cells"]): random.seed(i) - cell["id"] = random.getrandbits(128) + cell["id"] = str(random.getrandbits(128)) with open(output_notebook, "w", encoding="utf8") as f: - f.write(json.dumps(content)) \ No newline at end of file + f.write(json.dumps(content)) diff --git a/demo/generate_tone/run.ipynb b/demo/generate_tone/run.ipynb index 3676d3d4e6fce..989748f5bc4df 100644 --- a/demo/generate_tone/run.ipynb +++ b/demo/generate_tone/run.ipynb @@ -1 +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 +{"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 index ca38a565242e6..f4a60a02bb914 100644 --- a/demo/gif_maker/run.ipynb +++ b/demo/gif_maker/run.ipynb @@ -1 +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 +{"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/gpt2_xl/run.ipynb b/demo/gpt2_xl/run.ipynb index 4f4e715f0ba24..ecb906578d0a0 100644 --- a/demo/gpt2_xl/run.ipynb +++ b/demo/gpt2_xl/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gpt2_xl"]}, {"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 = \"gpt2-xl\"\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.load(\n", " \"huggingface/gpt2-xl\",\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 +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: gpt2_xl"]}, {"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 = \"gpt2-xl\"\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.load(\n", " \"huggingface/gpt2-xl\",\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/gpt2_xl_unified/run.ipynb b/demo/gpt2_xl_unified/run.ipynb index acadf315602cf..28aa6e08f78a9 100644 --- a/demo/gpt2_xl_unified/run.ipynb +++ b/demo/gpt2_xl_unified/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: gpt2_xl_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.load(\"huggingface/gpt2-xl\")\n", "\n", "demo = gr.Interface(\n", " fn=lambda x: x[:-50] + api(x[-50:]),\n", " inputs=component,\n", " outputs=component,\n", " title=\"gpt2-xl\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: gpt2_xl_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.load(\"huggingface/gpt2-xl\")\n", "\n", "demo = gr.Interface(\n", " fn=lambda x: x[:-50] + api(x[-50:]),\n", " inputs=component,\n", " outputs=component,\n", " title=\"gpt2-xl\",\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 index ac47b4086970d..e0ff591e59a71 100644 --- a/demo/hangman/run.ipynb +++ b/demo/hangman/run.ipynb @@ -1 +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", "\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 +{"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", "\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 index 5e3b554465e6d..3aed150583cba 100644 --- a/demo/hello_blocks/run.ipynb +++ b/demo/hello_blocks/run.ipynb @@ -1 +1,5 @@ -{"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", "\n", "def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\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, api_name=\"greet\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", "\n", "def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\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, api_name=\"greet\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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, api_name=\"greet\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/hello_blocks_decorator/run.ipynb b/demo/hello_blocks_decorator/run.ipynb index 89789ff40eb08..d15dac1b41e9b 100644 --- a/demo/hello_blocks_decorator/run.ipynb +++ b/demo/hello_blocks_decorator/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: hello_blocks_decorator"]}, {"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", "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", "\n", " @greet_btn.click(inputs=name, outputs=output)\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", " \n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: hello_blocks_decorator"]}, {"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", "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", "\n", " @greet_btn.click(inputs=name, outputs=output)\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\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/hello_login/run.ipynb b/demo/hello_login/run.ipynb index 71dd974356d11..6739331e37d2c 100644 --- a/demo/hello_login/run.ipynb +++ b/demo/hello_login/run.ipynb @@ -1 +1,5 @@ -{"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", "import argparse\n", "import sys\n", "\n", "parser = argparse.ArgumentParser()\n", "parser.add_argument(\"--name\", type=str, default=\"User\")\n", "args, unknown = parser.parse_known_args()\n", "print(sys.argv)\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(f\"# Greetings {args.name}!\")\n", " inp = gr.Textbox()\n", " out = gr.Textbox()\n", "\n", " inp.change(fn=lambda x: x, inputs=inp, outputs=out)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", "import argparse\n", "import sys\n", "\n", "parser = argparse.ArgumentParser()\n", "parser.add_argument(\"--name\", type=str, default=\"User\")\n", "args, unknown = parser.parse_known_args()\n", "print(sys.argv)\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(f\"# Greetings {args.name}!\")\n", " inp = gr.Textbox()\n", " out = gr.Textbox()\n", "\n", " inp.change(fn=lambda x: x, inputs=inp, outputs=out)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/hello_world/run.ipynb b/demo/hello_world/run.ipynb index 0cca747389629..2f9bffd2afd2a 100644 --- a/demo/hello_world/run.ipynb +++ b/demo/hello_world/run.ipynb @@ -1 +1,5 @@ -{"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", "if __name__ == \"__main__\":\n", " demo.launch(show_api=False) "]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", "if __name__ == \"__main__\":\n", " demo.launch(show_api=False) "]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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", "if __name__ == \"__main__\":\n", " demo.launch() "]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/hello_world_2/run.ipynb b/demo/hello_world_2/run.ipynb index b5b5cfc49f6c0..b32da7f5bbb3d 100644 --- a/demo/hello_world_2/run.ipynb +++ b/demo/hello_world_2/run.ipynb @@ -1 +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 +{"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 index def950c52332e..d28fb265daf53 100644 --- a/demo/hello_world_3/run.ipynb +++ b/demo/hello_world_3/run.ipynb @@ -1 +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 +{"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 index 5e8b0e4e37ddd..ff22ebe451d3c 100644 --- a/demo/highlightedtext_component/run.ipynb +++ b/demo/highlightedtext_component/run.ipynb @@ -1 +1,5 @@ -{"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(\n", " combine_adjacent=True,\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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(\n", " combine_adjacent=True,\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/html_component/run.ipynb b/demo/html_component/run.ipynb index 7f7f14697b6ac..61e3aa494e4ca 100644 --- a/demo/html_component/run.ipynb +++ b/demo/html_component/run.ipynb @@ -1 +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=\"

This example was written in HTML

\")\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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=\"

This example was written in HTML

\")\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 index 792ee745d137a..434fbbf4ae7e2 100644 --- a/demo/image_classification/run.ipynb +++ b/demo/image_classification/run.ipynb @@ -1 +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 +{"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 index 6d489271b6d9b..020f71da17a9a 100644 --- a/demo/image_classifier/run.ipynb +++ b/demo/image_classifier/run.ipynb @@ -1 +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 +{"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 index 7598db8e31cf2..907f57b3b75a7 100644 --- a/demo/image_classifier_2/run.ipynb +++ b/demo/image_classifier_2/run.ipynb @@ -1 +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 +{"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 index 122dfa407fde1..d2aa59dacc228 100644 --- a/demo/image_classifier_interface_load/run.ipynb +++ b/demo/image_classifier_interface_load/run.ipynb @@ -1 +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.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 +{"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.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 index 92fcfcd7142ea..74d94d3e45b3c 100644 --- a/demo/image_classifier_interpretation/run.ipynb +++ b/demo/image_classifier_interpretation/run.ipynb @@ -1 +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 +{"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 index f27b99ee1084d..ef0fbc57f94dd 100644 --- a/demo/image_component/run.ipynb +++ b/demo/image_component/run.ipynb @@ -1 +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 +{"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 index 5cb9b4fbb6e8f..b7b80afe2b600 100644 --- a/demo/image_mod/run.ipynb +++ b/demo/image_mod/run.ipynb @@ -1 +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\n", "!wget -q -O images/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod/images/tower.jpg"]}, {"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(\n", " image_mod,\n", " gr.Image(type=\"pil\"),\n", " \"image\",\n", " flagging_options=[\"blurry\", \"incorrect\", \"other\"],\n", " 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", " os.path.join(os.path.abspath(''), \"images/tower.jpg\"),\n", " ],\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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\n", "!wget -q -O images/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/image_mod/images/tower.jpg"]}, {"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(\n", " image_mod,\n", " gr.Image(type=\"pil\"),\n", " \"image\",\n", " flagging_options=[\"blurry\", \"incorrect\", \"other\"],\n", " 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", " os.path.join(os.path.abspath(''), \"images/tower.jpg\"),\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/image_mod_default_image/run.ipynb b/demo/image_mod_default_image/run.ipynb index 48d8ee868fae0..9e2befb5bcd57 100644 --- a/demo/image_mod_default_image/run.ipynb +++ b/demo/image_mod_default_image/run.ipynb @@ -1 +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 +{"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 index 8544aedd0213b..ac39c2862e509 100644 --- a/demo/image_segmentation/run.ipynb +++ b/demo/image_segmentation/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_segmentation\n", "### Simple image segmentation using gradio's AnnotatedImage component.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import random\n", "\n", "with gr.Blocks() as demo:\n", " section_labels = [\n", " \"apple\",\n", " \"banana\",\n", " \"carrot\",\n", " \"donut\",\n", " \"eggplant\",\n", " \"fish\",\n", " \"grapes\",\n", " \"hamburger\",\n", " \"ice cream\",\n", " \"juice\",\n", " ]\n", "\n", " with gr.Row():\n", " num_boxes = gr.Slider(0, 5, 2, step=1, label=\"Number of boxes\")\n", " num_segments = gr.Slider(0, 5, 1, step=1, label=\"Number of segments\")\n", "\n", " with gr.Row():\n", " img_input = gr.Image()\n", " img_output = gr.AnnotatedImage(\n", " color_map={\"banana\": \"#a89a00\", \"carrot\": \"#ffae00\"}\n", " )\n", "\n", " section_btn = gr.Button(\"Identify Sections\")\n", " selected_section = gr.Textbox(label=\"Selected Section\")\n", "\n", " def section(img, num_boxes, num_segments):\n", " sections = []\n", " for a in range(num_boxes):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " w = random.randint(0, img.shape[1] - x)\n", " h = random.randint(0, img.shape[0] - y)\n", " sections.append(((x, y, x + w, y + h), section_labels[a]))\n", " for b in range(num_segments):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))\n", " mask = np.zeros(img.shape[:2])\n", " for i in range(img.shape[0]):\n", " for j in range(img.shape[1]):\n", " dist_square = (i - y) ** 2 + (j - x) ** 2\n", " if dist_square < r**2:\n", " mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4\n", " sections.append((mask, section_labels[b + num_boxes]))\n", " return (img, sections)\n", "\n", " section_btn.click(section, [img_input, num_boxes, num_segments], img_output)\n", "\n", " def select_section(evt: gr.SelectData):\n", " return section_labels[evt.index]\n", "\n", " img_output.select(select_section, None, selected_section)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: image_segmentation\n", "### Simple image segmentation using gradio's AnnotatedImage component.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import numpy as np\n", "import random\n", "\n", "with gr.Blocks() as demo:\n", " section_labels = [\n", " \"apple\",\n", " \"banana\",\n", " \"carrot\",\n", " \"donut\",\n", " \"eggplant\",\n", " \"fish\",\n", " \"grapes\",\n", " \"hamburger\",\n", " \"ice cream\",\n", " \"juice\",\n", " ]\n", "\n", " with gr.Row():\n", " num_boxes = gr.Slider(0, 5, 2, step=1, label=\"Number of boxes\")\n", " num_segments = gr.Slider(0, 5, 1, step=1, label=\"Number of segments\")\n", "\n", " with gr.Row():\n", " img_input = gr.Image()\n", " img_output = gr.AnnotatedImage(\n", " color_map={\"banana\": \"#a89a00\", \"carrot\": \"#ffae00\"}\n", " )\n", "\n", " section_btn = gr.Button(\"Identify Sections\")\n", " selected_section = gr.Textbox(label=\"Selected Section\")\n", "\n", " def section(img, num_boxes, num_segments):\n", " sections = []\n", " for a in range(num_boxes):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " w = random.randint(0, img.shape[1] - x)\n", " h = random.randint(0, img.shape[0] - y)\n", " sections.append(((x, y, x + w, y + h), section_labels[a]))\n", " for b in range(num_segments):\n", " x = random.randint(0, img.shape[1])\n", " y = random.randint(0, img.shape[0])\n", " r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))\n", " mask = np.zeros(img.shape[:2])\n", " for i in range(img.shape[0]):\n", " for j in range(img.shape[1]):\n", " dist_square = (i - y) ** 2 + (j - x) ** 2\n", " if dist_square < r**2:\n", " mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4\n", " sections.append((mask, section_labels[b + num_boxes]))\n", " return (img, sections)\n", "\n", " section_btn.click(section, [img_input, num_boxes, num_segments], img_output)\n", "\n", " def select_section(evt: gr.SelectData):\n", " return section_labels[evt.index]\n", "\n", " img_output.select(select_section, None, selected_section)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/image_selections/run.ipynb b/demo/image_selections/run.ipynb index 37f1f12230785..d39daa8b59bdd 100644 --- a/demo/image_selections/run.ipynb +++ b/demo/image_selections/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: image_selections"]}, {"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", "with gr.Blocks() as demo:\n", " tolerance = gr.Slider(label=\"Tolerance\", info=\"How different colors can be in a segment.\", minimum=0, maximum=256*3, value=50)\n", " with gr.Row():\n", " input_img = gr.Image(label=\"Input\")\n", " output_img = gr.Image(label=\"Selected Segment\")\n", "\n", " def get_select_coords(img, tolerance, evt: gr.SelectData):\n", " visited_pixels = set()\n", " pixels_in_queue = set()\n", " pixels_in_segment = set()\n", " start_pixel = img[evt.index[1], evt.index[0]]\n", " pixels_in_queue.add((evt.index[1], evt.index[0]))\n", " while len(pixels_in_queue) > 0:\n", " pixel = pixels_in_queue.pop()\n", " visited_pixels.add(pixel)\n", " neighbors = []\n", " if pixel[0] > 0:\n", " neighbors.append((pixel[0] - 1, pixel[1]))\n", " if pixel[0] < img.shape[0] - 1:\n", " neighbors.append((pixel[0] + 1, pixel[1]))\n", " if pixel[1] > 0:\n", " neighbors.append((pixel[0], pixel[1] - 1))\n", " if pixel[1] < img.shape[1] - 1:\n", " neighbors.append((pixel[0], pixel[1] + 1))\n", " for neighbor in neighbors:\n", " if neighbor in visited_pixels:\n", " continue\n", " neighbor_pixel = img[neighbor[0], neighbor[1]]\n", " if np.abs(neighbor_pixel - start_pixel).sum() < tolerance:\n", " pixels_in_queue.add(neighbor)\n", " pixels_in_segment.add(neighbor)\n", "\n", " out = img.copy() * 0.2\n", " out = out.astype(np.uint8)\n", " for pixel in pixels_in_segment:\n", " out[pixel[0], pixel[1]] = img[pixel[0], pixel[1]]\n", " return out\n", " \n", " input_img.select(get_select_coords, [input_img, tolerance], output_img)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: image_selections"]}, {"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", "with gr.Blocks() as demo:\n", " tolerance = gr.Slider(label=\"Tolerance\", info=\"How different colors can be in a segment.\", minimum=0, maximum=256*3, value=50)\n", " with gr.Row():\n", " input_img = gr.Image(label=\"Input\")\n", " output_img = gr.Image(label=\"Selected Segment\")\n", "\n", " def get_select_coords(img, tolerance, evt: gr.SelectData):\n", " visited_pixels = set()\n", " pixels_in_queue = set()\n", " pixels_in_segment = set()\n", " start_pixel = img[evt.index[1], evt.index[0]]\n", " pixels_in_queue.add((evt.index[1], evt.index[0]))\n", " while len(pixels_in_queue) > 0:\n", " pixel = pixels_in_queue.pop()\n", " visited_pixels.add(pixel)\n", " neighbors = []\n", " if pixel[0] > 0:\n", " neighbors.append((pixel[0] - 1, pixel[1]))\n", " if pixel[0] < img.shape[0] - 1:\n", " neighbors.append((pixel[0] + 1, pixel[1]))\n", " if pixel[1] > 0:\n", " neighbors.append((pixel[0], pixel[1] - 1))\n", " if pixel[1] < img.shape[1] - 1:\n", " neighbors.append((pixel[0], pixel[1] + 1))\n", " for neighbor in neighbors:\n", " if neighbor in visited_pixels:\n", " continue\n", " neighbor_pixel = img[neighbor[0], neighbor[1]]\n", " if np.abs(neighbor_pixel - start_pixel).sum() < tolerance:\n", " pixels_in_queue.add(neighbor)\n", " pixels_in_segment.add(neighbor)\n", "\n", " out = img.copy() * 0.2\n", " out = out.astype(np.uint8)\n", " for pixel in pixels_in_segment:\n", " out[pixel[0], pixel[1]] = img[pixel[0], pixel[1]]\n", " return out\n", " \n", " input_img.select(get_select_coords, [input_img, tolerance], output_img)\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/input_output/run.ipynb b/demo/input_output/run.ipynb index c8e72fcb86c8b..c59f54523bbc0 100644 --- a/demo/input_output/run.ipynb +++ b/demo/input_output/run.ipynb @@ -1 +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 +{"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 index b74d27f11741d..146323684aa79 100644 --- a/demo/interface_parallel/run.ipynb +++ b/demo/interface_parallel/run.ipynb @@ -1 +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 +{"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 index 08bd42d7dec55..4ac4acb308335 100644 --- a/demo/interface_parallel_load/run.ipynb +++ b/demo/interface_parallel_load/run.ipynb @@ -1 +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.load(\"huggingface/gpt2\")\n", "generator2 = gr.load(\"huggingface/gpt2-xl\")\n", "\n", "demo = gr.Parallel(generator1, generator2)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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.load(\"huggingface/gpt2\")\n", "generator2 = gr.load(\"huggingface/gpt2-xl\")\n", "\n", "demo = gr.Parallel(generator1, generator2)\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 index 22a6f038da7d9..ef67d768a2506 100644 --- a/demo/interface_random_slider/run.ipynb +++ b/demo/interface_random_slider/run.ipynb @@ -1 +1,5 @@ -{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/interface_series/run.ipynb b/demo/interface_series/run.ipynb index 399476329f08a..0ed5fe48fcde8 100644 --- a/demo/interface_series/run.ipynb +++ b/demo/interface_series/run.ipynb @@ -1 +1,5 @@ -{"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\"Nice to meet you!\",\n", " inputs=\"textbox\", outputs=gr.Textbox(label=\"Greeting\"))\n", "translator = gr.Interface(lambda s: \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\", gr.Textbox(), gr.Image())\n", "demo = gr.Series(get_name, translator, append_nice)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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\"Nice to meet you!\",\n", " inputs=\"textbox\", outputs=gr.Textbox(label=\"Greeting\"))\n", "translator = gr.Interface(lambda s: \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\", gr.Textbox(), gr.Image())\n", "demo = gr.Series(get_name, translator, append_nice)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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} +>>>>>>> main diff --git a/demo/interface_series_load/run.ipynb b/demo/interface_series_load/run.ipynb index c899c8230c848..9d8f3cd13537e 100644 --- a/demo/interface_series_load/run.ipynb +++ b/demo/interface_series_load/run.ipynb @@ -1 +1,5 @@ -{"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", "import numpy as np\n", "\n", "generator = gr.load(\"huggingface/gpt2\")\n", "\n", "\n", "translator = gr.Interface(lambda s: \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\", gr.Textbox(), gr.Image())\n", "\n", "demo = gr.Series(generator, translator, description=\"This demo combines two Spaces: a text generator (`huggingface/gpt2`) and a text translator (`huggingface/t5-small`). The first Space takes a prompt as input and generates a text. The second Space takes the generated text as input and translates it into another language.\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"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", "import numpy as np\n", "\n", "generator = gr.load(\"huggingface/gpt2\")\n", "\n", "\n", "translator = gr.Interface(lambda s: \"https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg\", gr.Textbox(), gr.Image())\n", "\n", "demo = gr.Series(generator, translator, description=\"This demo combines two Spaces: a text generator (`huggingface/gpt2`) and a text translator (`huggingface/t5-small`). The first Space takes a prompt as input and generates a text. The second Space takes the generated text as input and translates it into another language.\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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.load(\"huggingface/gpt2\")\n", "translator = gr.load(\"huggingface/t5-small\")\n", "\n", "demo = gr.Series(generator, translator, description=\"This demo combines two Spaces: a text generator (`huggingface/gpt2`) and a text translator (`huggingface/t5-small`). The first Space takes a prompt as input and generates a text. The second Space takes the generated text as input and translates it into another language.\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/interpretation_component/run.ipynb b/demo/interpretation_component/run.ipynb index 3ffe8c4a11de8..09c1982d3e2bf 100644 --- a/demo/interpretation_component/run.ipynb +++ b/demo/interpretation_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: interpretation_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio shap 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", "\n", "\n", "sentiment_classifier = pipeline(\"text-classification\", return_all_scores=True)\n", "\n", "def interpretation_function(text):\n", " explainer = shap.Explainer(sentiment_classifier)\n", " shap_values = explainer([text])\n", " scores = list(zip(shap_values.data[0], shap_values.values[0, :, 1]))\n", " return {\"original\": text, \"interpretation\": scores}\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " input_text = gr.Textbox(label=\"Sentiment Analysis\", value=\"Wonderfully terrible\")\n", " with gr.Row():\n", " interpret = gr.Button(\"Interpret\")\n", " with gr.Column():\n", " interpretation = gr.components.Interpretation(input_text)\n", "\n", " interpret.click(interpretation_function, input_text, interpretation)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: interpretation_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio shap 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", "\n", "\n", "sentiment_classifier = pipeline(\"text-classification\", return_all_scores=True)\n", "\n", "def interpretation_function(text):\n", " explainer = shap.Explainer(sentiment_classifier)\n", " shap_values = explainer([text])\n", " scores = list(zip(shap_values.data[0], shap_values.values[0, :, 1]))\n", " return {\"original\": text, \"interpretation\": scores}\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " with gr.Column():\n", " input_text = gr.Textbox(label=\"Sentiment Analysis\", value=\"Wonderfully terrible\")\n", " with gr.Row():\n", " interpret = gr.Button(\"Interpret\")\n", " with gr.Column():\n", " interpretation = gr.components.Interpretation(input_text)\n", "\n", " interpret.click(interpretation_function, input_text, interpretation)\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 index d465c76d31377..c0959b07eddfb 100644 --- a/demo/json_component/run.ipynb +++ b/demo/json_component/run.ipynb @@ -1 +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 +{"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 index 428f1d231e4dc..5e7685ae595d7 100644 --- a/demo/kitchen_sink/run.ipynb +++ b/demo/kitchen_sink/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: kitchen_sink"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cheetah1.jpg\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/lion.jpg\n", "!wget -q -O files/logo.png https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/logo.png\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/titanic.csv\n", "!wget -q -O files/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/tower.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import json\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "CHOICES = [\"foo\", \"bar\", \"baz\"]\n", "JSONOBJ = \"\"\"{\"items\":{\"item\":[{\"id\": \"0001\",\"type\": null,\"is_good\": false,\"ppu\": 0.55,\"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" },{ \"id\": \"1003\", \"type\": \"Blueberry\" },{ \"id\": \"1004\", \"type\": \"Devil's Food\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" },{ \"id\": \"5005\", \"type\": \"Sugar\" },{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },{ \"id\": \"5003\", \"type\": \"Chocolate\" },{ \"id\": \"5004\", \"type\": \"Maple\" }]}]}}\"\"\"\n", "\n", "\n", "def fn(\n", " text1,\n", " text2,\n", " num,\n", " slider1,\n", " slider2,\n", " single_checkbox,\n", " checkboxes,\n", " radio,\n", " dropdown,\n", " multi_dropdown,\n", " im1,\n", " im2,\n", " im3,\n", " im4,\n", " video,\n", " audio1,\n", " audio2,\n", " file,\n", " df1,\n", "):\n", " return (\n", " (text1 if single_checkbox else text2)\n", " + \", selected:\"\n", " + \", \".join(checkboxes), # Text\n", " {\n", " \"positive\": num / (num + slider1 + slider2),\n", " \"negative\": slider1 / (num + slider1 + slider2),\n", " \"neutral\": slider2 / (num + slider1 + slider2),\n", " }, # Label\n", " (audio1[0], np.flipud(audio1[1]))\n", " if audio1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cantina.wav\"), # Audio\n", " np.flipud(im1)\n", " if im1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"), # Image\n", " video\n", " if video is not None\n", " else os.path.join(os.path.abspath(''), \"files/world.mp4\"), # Video\n", " [\n", " (\"The\", \"art\"),\n", " (\"quick brown\", \"adj\"),\n", " (\"fox\", \"nn\"),\n", " (\"jumped\", \"vrb\"),\n", " (\"testing testing testing\", None),\n", " (\"over\", \"prp\"),\n", " (\"the\", \"art\"),\n", " (\"testing\", None),\n", " (\"lazy\", \"adj\"),\n", " (\"dogs\", \"nn\"),\n", " (\".\", \"punc\"),\n", " ]\n", " + [(f\"test {x}\", f\"test {x}\") for x in range(10)], # HighlightedText\n", " # [(\"The testing testing testing\", None), (\"quick brown\", 0.2), (\"fox\", 1), (\"jumped\", -1), (\"testing testing testing\", 0), (\"over\", 0), (\"the\", 0), (\"testing\", 0), (\"lazy\", 1), (\"dogs\", 0), (\".\", 1)] + [(f\"test {x}\", x/10) for x in range(-10, 10)], # HighlightedText\n", " [\n", " (\"The testing testing testing\", None),\n", " (\"over\", 0.6),\n", " (\"the\", 0.2),\n", " (\"testing\", None),\n", " (\"lazy\", -0.1),\n", " (\"dogs\", 0.4),\n", " (\".\", 0),\n", " ]\n", " + [(f\"test\", x / 10) for x in range(-10, 10)], # HighlightedText\n", " json.loads(JSONOBJ), # JSON\n", " \"\", # HTML\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " df1, # Dataframe\n", " np.random.randint(0, 10, (4, 4)), # Dataframe\n", " )\n", "\n", "\n", "demo = gr.Interface(\n", " fn,\n", " inputs=[\n", " gr.Textbox(value=\"Lorem ipsum\", label=\"Textbox\"),\n", " gr.Textbox(lines=3, placeholder=\"Type here..\", label=\"Textbox 2\"),\n", " gr.Number(label=\"Number\", value=42),\n", " gr.Slider(10, 20, value=15, label=\"Slider: 10 - 20\"),\n", " gr.Slider(maximum=20, step=0.04, label=\"Slider: step @ 0.04\"),\n", " gr.Checkbox(label=\"Checkbox\"),\n", " gr.CheckboxGroup(label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]),\n", " gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", " gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\n", " gr.Dropdown(\n", " label=\"Multiselect Dropdown (Max choice: 2)\",\n", " choices=CHOICES,\n", " multiselect=True,\n", " max_choices=2,\n", " ),\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", " ],\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(\n", " label=\"HighlightedText\", 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", " ],\n", " examples=[\n", " [\n", " \"the quick brown fox\",\n", " \"jumps over the lazy dog\",\n", " 10,\n", " 12,\n", " 4,\n", " True,\n", " [\"foo\", \"baz\"],\n", " \"baz\",\n", " \"bar\",\n", " [\"foo\", \"bar\"],\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/world.mp4\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],\n", " ]\n", " ]\n", " * 3,\n", " title=\"Kitchen Sink\",\n", " description=\"Try out all the components!\",\n", " article=\"Learn more about [Gradio](http://gradio.app)\",\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: kitchen_sink"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cheetah1.jpg\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/lion.jpg\n", "!wget -q -O files/logo.png https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/logo.png\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/titanic.csv\n", "!wget -q -O files/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/tower.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import os\n", "import json\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "CHOICES = [\"foo\", \"bar\", \"baz\"]\n", "JSONOBJ = \"\"\"{\"items\":{\"item\":[{\"id\": \"0001\",\"type\": null,\"is_good\": false,\"ppu\": 0.55,\"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" },{ \"id\": \"1003\", \"type\": \"Blueberry\" },{ \"id\": \"1004\", \"type\": \"Devil's Food\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" },{ \"id\": \"5005\", \"type\": \"Sugar\" },{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },{ \"id\": \"5003\", \"type\": \"Chocolate\" },{ \"id\": \"5004\", \"type\": \"Maple\" }]}]}}\"\"\"\n", "\n", "\n", "def fn(\n", " text1,\n", " text2,\n", " num,\n", " slider1,\n", " slider2,\n", " single_checkbox,\n", " checkboxes,\n", " radio,\n", " dropdown,\n", " multi_dropdown,\n", " im1,\n", " im2,\n", " im3,\n", " im4,\n", " video,\n", " audio1,\n", " audio2,\n", " file,\n", " df1,\n", "):\n", " return (\n", " (text1 if single_checkbox else text2)\n", " + \", selected:\"\n", " + \", \".join(checkboxes), # Text\n", " {\n", " \"positive\": num / (num + slider1 + slider2),\n", " \"negative\": slider1 / (num + slider1 + slider2),\n", " \"neutral\": slider2 / (num + slider1 + slider2),\n", " }, # Label\n", " (audio1[0], np.flipud(audio1[1]))\n", " if audio1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cantina.wav\"), # Audio\n", " np.flipud(im1)\n", " if im1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"), # Image\n", " video\n", " if video is not None\n", " else os.path.join(os.path.abspath(''), \"files/world.mp4\"), # Video\n", " [\n", " (\"The\", \"art\"),\n", " (\"quick brown\", \"adj\"),\n", " (\"fox\", \"nn\"),\n", " (\"jumped\", \"vrb\"),\n", " (\"testing testing testing\", None),\n", " (\"over\", \"prp\"),\n", " (\"the\", \"art\"),\n", " (\"testing\", None),\n", " (\"lazy\", \"adj\"),\n", " (\"dogs\", \"nn\"),\n", " (\".\", \"punc\"),\n", " ]\n", " + [(f\"test {x}\", f\"test {x}\") for x in range(10)], # HighlightedText\n", " # [(\"The testing testing testing\", None), (\"quick brown\", 0.2), (\"fox\", 1), (\"jumped\", -1), (\"testing testing testing\", 0), (\"over\", 0), (\"the\", 0), (\"testing\", 0), (\"lazy\", 1), (\"dogs\", 0), (\".\", 1)] + [(f\"test {x}\", x/10) for x in range(-10, 10)], # HighlightedText\n", " [\n", " (\"The testing testing testing\", None),\n", " (\"over\", 0.6),\n", " (\"the\", 0.2),\n", " (\"testing\", None),\n", " (\"lazy\", -0.1),\n", " (\"dogs\", 0.4),\n", " (\".\", 0),\n", " ]\n", " + [(f\"test\", x / 10) for x in range(-10, 10)], # HighlightedText\n", " json.loads(JSONOBJ), # JSON\n", " \"\", # HTML\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " df1, # Dataframe\n", " np.random.randint(0, 10, (4, 4)), # Dataframe\n", " )\n", "\n", "\n", "demo = gr.Interface(\n", " fn,\n", " inputs=[\n", " gr.Textbox(value=\"Lorem ipsum\", label=\"Textbox\"),\n", " gr.Textbox(lines=3, placeholder=\"Type here..\", label=\"Textbox 2\"),\n", " gr.Number(label=\"Number\", value=42),\n", " gr.Slider(10, 20, value=15, label=\"Slider: 10 - 20\"),\n", " gr.Slider(maximum=20, step=0.04, label=\"Slider: step @ 0.04\"),\n", " gr.Checkbox(label=\"Checkbox\"),\n", " gr.CheckboxGroup(label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]),\n", " gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", " gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\n", " gr.Dropdown(\n", " label=\"Multiselect Dropdown (Max choice: 2)\",\n", " choices=CHOICES,\n", " multiselect=True,\n", " max_choices=2,\n", " ),\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", " ],\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(\n", " label=\"HighlightedText\", 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", " ],\n", " examples=[\n", " [\n", " \"the quick brown fox\",\n", " \"jumps over the lazy dog\",\n", " 10,\n", " 12,\n", " 4,\n", " True,\n", " [\"foo\", \"baz\"],\n", " \"baz\",\n", " \"bar\",\n", " [\"foo\", \"bar\"],\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/world.mp4\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],\n", " ]\n", " ]\n", " * 3,\n", " title=\"Kitchen Sink\",\n", " description=\"Try out all the components!\",\n", " article=\"Learn more about [Gradio](http://gradio.app)\",\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: kitchen_sink"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/cantina.wav https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cantina.wav\n", "!wget -q -O files/cheetah1.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/cheetah1.jpg\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/lion.jpg\n", "!wget -q -O files/logo.png https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/logo.png\n", "!wget -q -O files/time.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/time.csv\n", "!wget -q -O files/titanic.csv https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/titanic.csv\n", "!wget -q -O files/tower.jpg https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/tower.jpg\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/kitchen_sink/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import os\n", "import json\n", "\n", "import numpy as np\n", "\n", "import gradio as gr\n", "\n", "CHOICES = [\"foo\", \"bar\", \"baz\"]\n", "JSONOBJ = \"\"\"{\"items\":{\"item\":[{\"id\": \"0001\",\"type\": null,\"is_good\": false,\"ppu\": 0.55,\"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" },{ \"id\": \"1003\", \"type\": \"Blueberry\" },{ \"id\": \"1004\", \"type\": \"Devil's Food\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" },{ \"id\": \"5005\", \"type\": \"Sugar\" },{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },{ \"id\": \"5003\", \"type\": \"Chocolate\" },{ \"id\": \"5004\", \"type\": \"Maple\" }]}]}}\"\"\"\n", "\n", "\n", "def fn(\n", " text1,\n", " text2,\n", " num,\n", " slider1,\n", " slider2,\n", " single_checkbox,\n", " checkboxes,\n", " radio,\n", " dropdown,\n", " multi_dropdown,\n", " im1,\n", " im2,\n", " im3,\n", " im4,\n", " video,\n", " audio1,\n", " audio2,\n", " file,\n", " df1,\n", " df2,\n", "):\n", " return (\n", " (text1 if single_checkbox else text2)\n", " + \", selected:\"\n", " + \", \".join(checkboxes), # Text\n", " {\n", " \"positive\": num / (num + slider1 + slider2),\n", " \"negative\": slider1 / (num + slider1 + slider2),\n", " \"neutral\": slider2 / (num + slider1 + slider2),\n", " }, # Label\n", " (audio1[0], np.flipud(audio1[1]))\n", " if audio1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cantina.wav\"), # Audio\n", " np.flipud(im1)\n", " if im1 is not None\n", " else os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"), # Image\n", " video\n", " if video is not None\n", " else os.path.join(os.path.abspath(''), \"files/world.mp4\"), # Video\n", " [\n", " (\"The\", \"art\"),\n", " (\"quick brown\", \"adj\"),\n", " (\"fox\", \"nn\"),\n", " (\"jumped\", \"vrb\"),\n", " (\"testing testing testing\", None),\n", " (\"over\", \"prp\"),\n", " (\"the\", \"art\"),\n", " (\"testing\", None),\n", " (\"lazy\", \"adj\"),\n", " (\"dogs\", \"nn\"),\n", " (\".\", \"punc\"),\n", " ]\n", " + [(f\"test {x}\", f\"test {x}\") for x in range(10)], # HighlightedText\n", " # [(\"The testing testing testing\", None), (\"quick brown\", 0.2), (\"fox\", 1), (\"jumped\", -1), (\"testing testing testing\", 0), (\"over\", 0), (\"the\", 0), (\"testing\", 0), (\"lazy\", 1), (\"dogs\", 0), (\".\", 1)] + [(f\"test {x}\", x/10) for x in range(-10, 10)], # HighlightedText\n", " [\n", " (\"The testing testing testing\", None),\n", " (\"over\", 0.6),\n", " (\"the\", 0.2),\n", " (\"testing\", None),\n", " (\"lazy\", -0.1),\n", " (\"dogs\", 0.4),\n", " (\".\", 0),\n", " ]\n", " + [(f\"test\", x / 10) for x in range(-10, 10)], # HighlightedText\n", " json.loads(JSONOBJ), # JSON\n", " \"\", # HTML\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " df1, # Dataframe\n", " np.random.randint(0, 10, (4, 4)), # Dataframe\n", " df2, # Timeseries\n", " )\n", "\n", "\n", "demo = gr.Interface(\n", " fn,\n", " inputs=[\n", " gr.Textbox(value=\"Lorem ipsum\", label=\"Textbox\"),\n", " gr.Textbox(lines=3, placeholder=\"Type here..\", label=\"Textbox 2\"),\n", " gr.Number(label=\"Number\", value=42),\n", " gr.Slider(10, 20, value=15, label=\"Slider: 10 - 20\"),\n", " gr.Slider(maximum=20, step=0.04, label=\"Slider: step @ 0.04\"),\n", " gr.Checkbox(label=\"Checkbox\"),\n", " gr.CheckboxGroup(label=\"CheckboxGroup\", choices=CHOICES, value=CHOICES[0:2]),\n", " gr.Radio(label=\"Radio\", choices=CHOICES, value=CHOICES[2]),\n", " gr.Dropdown(label=\"Dropdown\", choices=CHOICES),\n", " gr.Dropdown(label=\"Multiselect Dropdown (Max choice: 2)\", choices=CHOICES, multiselect=True, max_choices=2),\n", " gr.Image(label=\"Image\"),\n", " gr.Image(label=\"Image w/ Cropper\", tool=\"select\"),\n", " gr.Image(label=\"Sketchpad\", source=\"canvas\"),\n", " gr.Image(label=\"Webcam\", source=\"webcam\"),\n", " gr.Video(label=\"Video\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Audio(label=\"Microphone\", source=\"microphone\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\", headers=[\"Name\", \"Age\", \"Gender\"]),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], colors=[\"pink\", \"purple\"]),\n", " ],\n", " outputs=[\n", " gr.Textbox(label=\"Textbox\"),\n", " gr.Label(label=\"Label\"),\n", " gr.Audio(label=\"Audio\"),\n", " gr.Image(label=\"Image\"),\n", " gr.Video(label=\"Video\"),\n", " gr.HighlightedText(label=\"HighlightedText\", \n", " color_map={\"punc\": \"pink\", \"test 0\": \"blue\"}\n", " ),\n", " gr.HighlightedText(label=\"HighlightedText\", show_legend=True),\n", " gr.JSON(label=\"JSON\"),\n", " gr.HTML(label=\"HTML\"),\n", " gr.File(label=\"File\"),\n", " gr.Dataframe(label=\"Dataframe\"),\n", " gr.Dataframe(label=\"Numpy\"),\n", " gr.Timeseries(x=\"time\", y=[\"price\", \"value\"], label=\"Timeseries\"),\n", " ],\n", " examples=[\n", " [\n", " \"the quick brown fox\",\n", " \"jumps over the lazy dog\",\n", " 10,\n", " 12,\n", " 4,\n", " True,\n", " [\"foo\", \"baz\"],\n", " \"baz\",\n", " \"bar\",\n", " [\"foo\", \"bar\"],\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/cheetah1.jpg\"),\n", " os.path.join(os.path.abspath(''), \"files/world.mp4\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/cantina.wav\"),\n", " os.path.join(os.path.abspath(''), \"files/titanic.csv\"),\n", " [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 1, 2], [3, 4, 5, 6]],\n", " os.path.join(os.path.abspath(''), \"files/time.csv\"),\n", " ]\n", " ]\n", " * 3,\n", " title=\"Kitchen Sink\",\n", " description=\"Try out all the components!\",\n", " article=\"Learn more about [Gradio](http://gradio.app)\",\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/label_component/run.ipynb b/demo/label_component/run.ipynb index 0cd6779e9aa52..c0fdf29ca71de 100644 --- a/demo/label_component/run.ipynb +++ b/demo/label_component/run.ipynb @@ -1 +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 +{"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/latex/run.ipynb b/demo/latex/run.ipynb index 4d0585bdf0a99..344513773befa 100644 --- a/demo/latex/run.ipynb +++ b/demo/latex/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: latex"]}, {"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", " r\"\"\"\n", " # Hello World! $\\frac{\\sqrt{x + y}}{4}$ is today's lesson\n", "\n", " ## the $\\sqrt{x + y}$ is first\n", "\n", " Start with $\\frac{\\frac{x+1}{x+2}}{x+3}$ then we get $ 2+x $ and $3$.\n", " \n", " There are three formulas to know:\n", " \n", " the first is $\\gamma^2 + \\theta^2 = \\omega^2$\n", " \n", " $\\sqrt{x^2+1}$ is next\n", " \n", " Integral $\\int_{a}^{b} x^2 \\,dx$ is last\n", "\n", " Start typing below to see the output.\n", "\n", " I spent $5 at the grocery store. Then I bought a $2.50 ice cream cone.\n", " \"\"\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: latex"]}, {"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", " r\"\"\"\n", " # Hello World! $\\frac{\\sqrt{x + y}}{4}$ is today's lesson\n", "\n", " ## the $\\sqrt{x + y}$ is first\n", "\n", " Start with $\\frac{\\frac{x+1}{x+2}}{x+3}$ then we get $ 2+x $ and $3$.\n", " \n", " There are three formulas to know:\n", " \n", " the first is $\\gamma^2 + \\theta^2 = \\omega^2$\n", " \n", " $\\sqrt{x^2+1}$ is next\n", " \n", " Integral $\\int_{a}^{b} x^2 \\,dx$ is last\n", "\n", " Start typing below to see the output.\n", "\n", " I spent $5 at the grocery store. Then I bought a $2.50 ice cream cone.\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/leaderboard/run.ipynb b/demo/leaderboard/run.ipynb index b368932998ecf..b4c74a920d4e2 100644 --- a/demo/leaderboard/run.ipynb +++ b/demo/leaderboard/run.ipynb @@ -1 +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 Blocks Party Event\"\"\")\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 +{"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 Blocks Party Event\"\"\")\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/line_plot/run.ipynb b/demo/line_plot/run.ipynb index 2590b0d18ba72..10b8606740efa 100644 --- a/demo/line_plot/run.ipynb +++ b/demo/line_plot/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: line_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets pandas"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "stocks = data.stocks()\n", "gapminder = data.gapminder()\n", "gapminder = gapminder.loc[\n", " gapminder.country.isin([\"Argentina\", \"Australia\", \"Afghanistan\"])\n", "]\n", "climate = data.climate()\n", "seattle_weather = data.seattle_weather()\n", "\n", "## Or generate your own fake data, here's an example for stocks:\n", "#\n", "# import pandas as pd\n", "# import random\n", "#\n", "# stocks = pd.DataFrame(\n", "# {\n", "# \"symbol\": [\n", "# random.choice(\n", "# [\n", "# \"MSFT\",\n", "# \"AAPL\",\n", "# \"AMZN\",\n", "# \"IBM\",\n", "# \"GOOG\",\n", "# ]\n", "# )\n", "# for _ in range(120)\n", "# ],\n", "# \"date\": [\n", "# pd.Timestamp(year=2000 + i, month=j, day=1)\n", "# for i in range(10)\n", "# for j in range(1, 13)\n", "# ],\n", "# \"price\": [random.randint(10, 200) for _ in range(120)],\n", "# }\n", "# )\n", "\n", "\n", "def line_plot_fn(dataset):\n", " if dataset == \"stocks\":\n", " return gr.LinePlot(\n", " stocks,\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"climate\":\n", " return gr.LinePlot(\n", " climate,\n", " x=\"DATE\",\n", " y=\"HLY-TEMP-NORMAL\",\n", " y_lim=[250, 500],\n", " title=\"Climate\",\n", " tooltip=[\"DATE\", \"HLY-TEMP-NORMAL\"],\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"seattle_weather\":\n", " return gr.LinePlot(\n", " seattle_weather,\n", " x=\"date\",\n", " y=\"temp_min\",\n", " tooltip=[\"weather\", \"date\"],\n", " overlay_point=True,\n", " title=\"Seattle Weather\",\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"gapminder\":\n", " return gr.LinePlot(\n", " gapminder,\n", " x=\"year\",\n", " y=\"life_expect\",\n", " color=\"country\",\n", " title=\"Life expectancy for countries\",\n", " stroke_dash=\"cluster\",\n", " x_lim=[1950, 2010],\n", " tooltip=[\"country\", \"life_expect\"],\n", " stroke_dash_legend_title=\"Country Cluster\",\n", " height=300,\n", " width=500,\n", " )\n", "\n", "\n", "with gr.Blocks() as line_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " dataset = gr.Dropdown(\n", " choices=[\"stocks\", \"climate\", \"seattle_weather\", \"gapminder\"],\n", " value=\"stocks\",\n", " )\n", " with gr.Column():\n", " plot = gr.LinePlot()\n", " dataset.change(line_plot_fn, inputs=dataset, outputs=plot)\n", " line_plot.load(fn=line_plot_fn, inputs=dataset, outputs=plot)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " line_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: line_plot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets pandas"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "stocks = data.stocks()\n", "gapminder = data.gapminder()\n", "gapminder = gapminder.loc[\n", " gapminder.country.isin([\"Argentina\", \"Australia\", \"Afghanistan\"])\n", "]\n", "climate = data.climate()\n", "seattle_weather = data.seattle_weather()\n", "\n", "## Or generate your own fake data, here's an example for stocks:\n", "#\n", "# import pandas as pd\n", "# import random\n", "#\n", "# stocks = pd.DataFrame(\n", "# {\n", "# \"symbol\": [\n", "# random.choice(\n", "# [\n", "# \"MSFT\",\n", "# \"AAPL\",\n", "# \"AMZN\",\n", "# \"IBM\",\n", "# \"GOOG\",\n", "# ]\n", "# )\n", "# for _ in range(120)\n", "# ],\n", "# \"date\": [\n", "# pd.Timestamp(year=2000 + i, month=j, day=1)\n", "# for i in range(10)\n", "# for j in range(1, 13)\n", "# ],\n", "# \"price\": [random.randint(10, 200) for _ in range(120)],\n", "# }\n", "# )\n", "\n", "\n", "def line_plot_fn(dataset):\n", " if dataset == \"stocks\":\n", " return gr.LinePlot(\n", " stocks,\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"climate\":\n", " return gr.LinePlot(\n", " climate,\n", " x=\"DATE\",\n", " y=\"HLY-TEMP-NORMAL\",\n", " y_lim=[250, 500],\n", " title=\"Climate\",\n", " tooltip=[\"DATE\", \"HLY-TEMP-NORMAL\"],\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"seattle_weather\":\n", " return gr.LinePlot(\n", " seattle_weather,\n", " x=\"date\",\n", " y=\"temp_min\",\n", " tooltip=[\"weather\", \"date\"],\n", " overlay_point=True,\n", " title=\"Seattle Weather\",\n", " height=300,\n", " width=500,\n", " )\n", " elif dataset == \"gapminder\":\n", " return gr.LinePlot(\n", " gapminder,\n", " x=\"year\",\n", " y=\"life_expect\",\n", " color=\"country\",\n", " title=\"Life expectancy for countries\",\n", " stroke_dash=\"cluster\",\n", " x_lim=[1950, 2010],\n", " tooltip=[\"country\", \"life_expect\"],\n", " stroke_dash_legend_title=\"Country Cluster\",\n", " height=300,\n", " width=500,\n", " )\n", "\n", "\n", "with gr.Blocks() as line_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " dataset = gr.Dropdown(\n", " choices=[\"stocks\", \"climate\", \"seattle_weather\", \"gapminder\"],\n", " value=\"stocks\",\n", " )\n", " with gr.Column():\n", " plot = gr.LinePlot()\n", " dataset.change(line_plot_fn, inputs=dataset, outputs=plot)\n", " line_plot.load(fn=line_plot_fn, inputs=dataset, outputs=plot)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " line_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/lineplot_component/run.ipynb b/demo/lineplot_component/run.ipynb index 9a118e0084571..a30e401b71241 100644 --- a/demo/lineplot_component/run.ipynb +++ b/demo/lineplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: lineplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "with gr.Blocks() as demo:\n", " gr.LinePlot(\n", " data.stocks(),\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=300,\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: lineplot_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "with gr.Blocks() as demo:\n", " gr.LinePlot(\n", " data.stocks(),\n", " x=\"date\",\n", " y=\"price\",\n", " color=\"symbol\",\n", " color_legend_position=\"bottom\",\n", " title=\"Stock Prices\",\n", " tooltip=[\"date\", \"price\", \"symbol\"],\n", " height=300,\n", " width=300,\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/live_dashboard/run.ipynb b/demo/live_dashboard/run.ipynb index 6fa3e43432590..6983127d7c013 100644 --- a/demo/live_dashboard/run.ipynb +++ b/demo/live_dashboard/run.ipynb @@ -1 +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", "\n", "import pandas as pd\n", "\n", "import gradio as gr\n", "import datetime\n", "import numpy as np\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", " update = gr.LinePlot(\n", " value=pd.DataFrame({\"x\": x, \"y\": y}),\n", " x=\"x\",\n", " y=\"y\",\n", " title=\"Plot (updates every second)\",\n", " width=600,\n", " height=350,\n", " )\n", " plot_end += 2 * math.pi\n", " if plot_end > 1000:\n", " plot_end = 2 * math.pi\n", " return update\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.LinePlot(show_label=False)\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 +{"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", "\n", "import pandas as pd\n", "\n", "import gradio as gr\n", "import datetime\n", "import numpy as np\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", " update = gr.LinePlot(\n", " value=pd.DataFrame({\"x\": x, \"y\": y}),\n", " x=\"x\",\n", " y=\"y\",\n", " title=\"Plot (updates every second)\",\n", " width=600,\n", " height=350,\n", " )\n", " plot_end += 2 * math.pi\n", " if plot_end > 1000:\n", " plot_end = 2 * math.pi\n", " return update\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.LinePlot(show_label=False)\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 index 46cafe84f694b..7ed43fbd12134 100644 --- a/demo/live_with_vars/run.ipynb +++ b/demo/live_with_vars/run.ipynb @@ -1 +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 +{"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/loginbutton_component/run.ipynb b/demo/loginbutton_component/run.ipynb index 54acb92649428..ee38deb411b2d 100644 --- a/demo/loginbutton_component/run.ipynb +++ b/demo/loginbutton_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: loginbutton_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio gradio[oauth]"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " gr.LoginButton()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: loginbutton_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio gradio[oauth]"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " gr.LoginButton()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/logoutbutton_component/run.ipynb b/demo/logoutbutton_component/run.ipynb index e42b7e828358d..954963165387a 100644 --- a/demo/logoutbutton_component/run.ipynb +++ b/demo/logoutbutton_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: logoutbutton_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio gradio[oauth]"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " gr.LogoutButton()\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: logoutbutton_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio gradio[oauth]"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr \n", "\n", "with gr.Blocks() as demo:\n", " gr.LogoutButton()\n", "\n", "demo.launch()"]}], "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 index 70d70f8aa0b77..e0862d244f53c 100644 --- a/demo/longest_word/run.ipynb +++ b/demo/longest_word/run.ipynb @@ -1 +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 +{"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 index 174ea808c1e11..c76024ee90ad2 100644 --- a/demo/main_note/run.ipynb +++ b/demo/main_note/run.ipynb @@ -1 +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", " 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 +{"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", " 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 index d94989ab556cd..952b3cd187550 100644 --- a/demo/map_airbnb/run.ipynb +++ b/demo/map_airbnb/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: map_airbnb\n", "### Display an interactive map of AirBnB locations with Plotly. Data is hosted on HuggingFace Datasets. \n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import plotly.graph_objects as go\n", "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\n", "df = dataset.to_pandas()\n", "\n", "def filter_map(min_price, max_price, boroughs):\n", "\n", " filtered_df = df[(df['neighbourhood_group'].isin(boroughs)) & \n", " (df['price'] > min_price) & (df['price'] < max_price)]\n", " names = filtered_df[\"name\"].tolist()\n", " prices = filtered_df[\"price\"].tolist()\n", " text_list = [(names[i], prices[i]) for i in range(0, len(names))]\n", " fig = go.Figure(go.Scattermapbox(\n", " customdata=text_list,\n", " lat=filtered_df['latitude'].tolist(),\n", " lon=filtered_df['longitude'].tolist(),\n", " mode='markers',\n", " marker=go.scattermapbox.Marker(\n", " size=6\n", " ),\n", " hoverinfo=\"text\",\n", " hovertemplate='Name: %{customdata[0]}
Price: $%{customdata[1]}'\n", " ))\n", "\n", " fig.update_layout(\n", " mapbox_style=\"open-street-map\",\n", " hovermode='closest',\n", " mapbox=dict(\n", " bearing=0,\n", " center=go.layout.mapbox.Center(\n", " lat=40.67,\n", " lon=-73.90\n", " ),\n", " pitch=0,\n", " zoom=9\n", " ),\n", " )\n", "\n", " return fig\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column():\n", " with gr.Row():\n", " min_price = gr.Number(value=250, label=\"Minimum Price\")\n", " max_price = gr.Number(value=1000, label=\"Maximum Price\")\n", " boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n", " btn = gr.Button(value=\"Update Filter\")\n", " map = gr.Plot()\n", " demo.load(filter_map, [min_price, max_price, boroughs], map)\n", " btn.click(filter_map, [min_price, max_price, boroughs], map)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: map_airbnb\n", "### Display an interactive map of AirBnB locations with Plotly. Data is hosted on HuggingFace Datasets. \n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import plotly.graph_objects as go\n", "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\n", "df = dataset.to_pandas()\n", "\n", "def filter_map(min_price, max_price, boroughs):\n", "\n", " filtered_df = df[(df['neighbourhood_group'].isin(boroughs)) & \n", " (df['price'] > min_price) & (df['price'] < max_price)]\n", " names = filtered_df[\"name\"].tolist()\n", " prices = filtered_df[\"price\"].tolist()\n", " text_list = [(names[i], prices[i]) for i in range(0, len(names))]\n", " fig = go.Figure(go.Scattermapbox(\n", " customdata=text_list,\n", " lat=filtered_df['latitude'].tolist(),\n", " lon=filtered_df['longitude'].tolist(),\n", " mode='markers',\n", " marker=go.scattermapbox.Marker(\n", " size=6\n", " ),\n", " hoverinfo=\"text\",\n", " hovertemplate='Name: %{customdata[0]}
Price: $%{customdata[1]}'\n", " ))\n", "\n", " fig.update_layout(\n", " mapbox_style=\"open-street-map\",\n", " hovermode='closest',\n", " mapbox=dict(\n", " bearing=0,\n", " center=go.layout.mapbox.Center(\n", " lat=40.67,\n", " lon=-73.90\n", " ),\n", " pitch=0,\n", " zoom=9\n", " ),\n", " )\n", "\n", " return fig\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Column():\n", " with gr.Row():\n", " min_price = gr.Number(value=250, label=\"Minimum Price\")\n", " max_price = gr.Number(value=1000, label=\"Maximum Price\")\n", " boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n", " btn = gr.Button(value=\"Update Filter\")\n", " map = gr.Plot()\n", " demo.load(filter_map, [min_price, max_price, boroughs], map)\n", " btn.click(filter_map, [min_price, max_price, boroughs], map)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/markdown_component/run.ipynb b/demo/markdown_component/run.ipynb index 9eafec1c58996..7867cad8885ab 100644 --- a/demo/markdown_component/run.ipynb +++ b/demo/markdown_component/run.ipynb @@ -1 +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()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/markdown_example/run.ipynb b/demo/markdown_example/run.ipynb index aec69f1588981..081c6eb822307 100644 --- a/demo/markdown_example/run.ipynb +++ b/demo/markdown_example/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: markdown_example"]}, {"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", "css = (\n", " \"footer {display: none !important;} .gradio-container {min-height: 0px !important;}\"\n", ")\n", "\n", "# sample md stolen from https://dillinger.io/\n", "\n", "md = \"\"\"# Dillinger\n", "## _The Last Markdown Editor, Ever_\n", "\n", "This is some `inline code`, it is good.\n", "\n", "[![Build Status](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)\n", "\n", "Dillinger is a cloud-enabled, mobile-ready, offline-storage compatible,\n", "AngularJS-powered HTML5 Markdown editor.\n", "\n", "- Type some Markdown on the left\n", "- See HTML in the right\n", "- \u2728Magic \u2728\n", "\n", "## Features\n", "\n", "- Import a HTML file and watch it magically convert to Markdown\n", "- Drag and drop images (requires your Dropbox account be linked)\n", "- Import and save files from GitHub, Dropbox, Google Drive and One Drive\n", "- Drag and drop markdown and HTML files into Dillinger\n", "- Export documents as Markdown, HTML and PDF\n", "\n", "Markdown is a lightweight markup language based on the formatting conventions\n", "that people naturally use in email.\n", "As [John Gruber] writes on the [Markdown site][df1]\n", "\n", "> The overriding design goal for Markdown's\n", "> formatting syntax is to make it as readable\n", "> as possible. The idea is that a\n", "> Markdown-formatted document should be\n", "> publishable as-is, as plain text, without\n", "> looking like it's been marked up with tags\n", "> or formatting instructions.\n", "\n", "This text you see here is *actually- written in Markdown! To get a feel\n", "for Markdown's syntax, type some text into the left window and\n", "watch the results in the right.\n", "\n", "## Tech\n", "\n", "Dillinger uses a number of open source projects to work properly:\n", "\n", "- [AngularJS] - HTML enhanced for web apps!\n", "- [Ace Editor] - awesome web-based text editor\n", "- [markdown-it] - Markdown parser done right. Fast and easy to extend.\n", "- [Twitter Bootstrap] - great UI boilerplate for modern web apps\n", "- [node.js] - evented I/O for the backend\n", "- [Express] - fast node.js network app framework [@tjholowaychuk]\n", "- [Gulp] - the streaming build system\n", "- [Breakdance](https://breakdance.github.io/breakdance/) - HTML\n", "to Markdown converter\n", "- [jQuery] - duh\n", "\n", "And of course Dillinger itself is open source with a [public repository][dill]\n", " on GitHub.\n", "\n", "## Installation\n", "\n", "Dillinger requires [Node.js](https://nodejs.org/) v10+ to run.\n", "\n", "Install the dependencies and devDependencies and start the server.\n", "\n", "```sh\n", "cd dillinger\n", "npm i\n", "node app\n", "```\n", "\n", "For production environments...\n", "\n", "```sh\n", "npm install --production\n", "NODE_ENV=production node app\n", "```\n", "\n", "## Plugins\n", "\n", "Dillinger is currently extended with the following plugins.\n", "Instructions on how to use them in your own application are linked below.\n", "\n", "| Plugin | README |\n", "| ------ | ------ |\n", "| Dropbox | [plugins/dropbox/README.md][PlDb] |\n", "| GitHub | [plugins/github/README.md][PlGh] |\n", "| Google Drive | [plugins/googledrive/README.md][PlGd] |\n", "| OneDrive | [plugins/onedrive/README.md][PlOd] |\n", "| Medium | [plugins/medium/README.md][PlMe] |\n", "| Google Analytics | [plugins/googleanalytics/README.md][PlGa] |\n", "\n", "## Development\n", "\n", "Want to contribute? Great!\n", "\n", "Dillinger uses Gulp + Webpack for fast developing.\n", "Make a change in your file and instantaneously see your updates!\n", "\n", "Open your favorite Terminal and run these commands.\n", "\n", "First Tab:\n", "\n", "```sh\n", "node app\n", "```\n", "\n", "Second Tab:\n", "\n", "```sh\n", "gulp watch\n", "```\n", "\n", "(optional) Third:\n", "\n", "```sh\n", "karma test\n", "```\n", "\n", "#### Building for source\n", "\n", "For production release:\n", "\n", "```sh\n", "gulp build --prod\n", "```\n", "\n", "Generating pre-built zip archives for distribution:\n", "\n", "```sh\n", "gulp build dist --prod\n", "```\n", "\n", "## Docker\n", "\n", "Dillinger is very easy to install and deploy in a Docker container.\n", "\n", "By default, the Docker will expose port 8080, so change this within the\n", "Dockerfile if necessary. When ready, simply use the Dockerfile to\n", "build the image.\n", "\n", "```sh\n", "cd dillinger\n", "docker build -t /dillinger:${package.json.version} .\n", "```\n", "\n", "This will create the dillinger image and pull in the necessary dependencies.\n", "Be sure to swap out `${package.json.version}` with the actual\n", "version of Dillinger.\n", "\n", "Once done, run the Docker image and map the port to whatever you wish on\n", "your host. In this example, we simply map port 8000 of the host to\n", "port 8080 of the Docker (or whatever port was exposed in the Dockerfile):\n", "\n", "```sh\n", "docker run -d -p 8000:8080 --restart=always --cap-add=SYS_ADMIN --name=dillinger /dillinger:${package.json.version}\n", "```\n", "\n", "> Note: `--capt-add=SYS-ADMIN` is required for PDF rendering.\n", "\n", "Verify the deployment by navigating to your server address in\n", "your preferred browser.\n", "\n", "```sh\n", "127.0.0.1:8000\n", "```\n", "\n", "```python\n", "import gradio as gr\n", "\n", "gr.Blocks() as demo:\n", " gr.Markdown(value=md)\n", "\n", "demo.launch()\n", "```\n", "\n", "```js\n", "function fancyAlert(arg) {\n", " if(arg) {\n", " $.facebox({div:'#foo'})\n", " }\n", "}\n", "```\n", "\n", "## License\n", "\n", "MIT\n", "\n", "**Free Software, Hell Yeah!**\n", "\n", "[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)\n", "\n", " [dill]: \n", " [git-repo-url]: \n", " [john gruber]: \n", " [df1]: \n", " [markdown-it]: \n", " [Ace Editor]: \n", " [node.js]: \n", " [Twitter Bootstrap]: \n", " [jQuery]: \n", " [@tjholowaychuk]: \n", " [express]: \n", " [AngularJS]: \n", " [Gulp]: \n", "\n", " [PlDb]: \n", " [PlGh]: \n", " [PlGd]: \n", " [PlOd]: \n", " [PlMe]: \n", " [PlGa]: \n", "\n", "\"\"\"\n", "with gr.Blocks(css=css) as demo:\n", " gr.Markdown(value=md)\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: markdown_example"]}, {"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", "css = (\n", " \"footer {display: none !important;} .gradio-container {min-height: 0px !important;}\"\n", ")\n", "\n", "# sample md stolen from https://dillinger.io/\n", "\n", "md = \"\"\"# Dillinger\n", "## _The Last Markdown Editor, Ever_\n", "\n", "This is some `inline code`, it is good.\n", "\n", "[![Build Status](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)\n", "\n", "Dillinger is a cloud-enabled, mobile-ready, offline-storage compatible,\n", "AngularJS-powered HTML5 Markdown editor.\n", "\n", "- Type some Markdown on the left\n", "- See HTML in the right\n", "- \u2728Magic \u2728\n", "\n", "## Features\n", "\n", "- Import a HTML file and watch it magically convert to Markdown\n", "- Drag and drop images (requires your Dropbox account be linked)\n", "- Import and save files from GitHub, Dropbox, Google Drive and One Drive\n", "- Drag and drop markdown and HTML files into Dillinger\n", "- Export documents as Markdown, HTML and PDF\n", "\n", "Markdown is a lightweight markup language based on the formatting conventions\n", "that people naturally use in email.\n", "As [John Gruber] writes on the [Markdown site][df1]\n", "\n", "> The overriding design goal for Markdown's\n", "> formatting syntax is to make it as readable\n", "> as possible. The idea is that a\n", "> Markdown-formatted document should be\n", "> publishable as-is, as plain text, without\n", "> looking like it's been marked up with tags\n", "> or formatting instructions.\n", "\n", "This text you see here is *actually- written in Markdown! To get a feel\n", "for Markdown's syntax, type some text into the left window and\n", "watch the results in the right.\n", "\n", "## Tech\n", "\n", "Dillinger uses a number of open source projects to work properly:\n", "\n", "- [AngularJS] - HTML enhanced for web apps!\n", "- [Ace Editor] - awesome web-based text editor\n", "- [markdown-it] - Markdown parser done right. Fast and easy to extend.\n", "- [Twitter Bootstrap] - great UI boilerplate for modern web apps\n", "- [node.js] - evented I/O for the backend\n", "- [Express] - fast node.js network app framework [@tjholowaychuk]\n", "- [Gulp] - the streaming build system\n", "- [Breakdance](https://breakdance.github.io/breakdance/) - HTML\n", "to Markdown converter\n", "- [jQuery] - duh\n", "\n", "And of course Dillinger itself is open source with a [public repository][dill]\n", " on GitHub.\n", "\n", "## Installation\n", "\n", "Dillinger requires [Node.js](https://nodejs.org/) v10+ to run.\n", "\n", "Install the dependencies and devDependencies and start the server.\n", "\n", "```sh\n", "cd dillinger\n", "npm i\n", "node app\n", "```\n", "\n", "For production environments...\n", "\n", "```sh\n", "npm install --production\n", "NODE_ENV=production node app\n", "```\n", "\n", "## Plugins\n", "\n", "Dillinger is currently extended with the following plugins.\n", "Instructions on how to use them in your own application are linked below.\n", "\n", "| Plugin | README |\n", "| ------ | ------ |\n", "| Dropbox | [plugins/dropbox/README.md][PlDb] |\n", "| GitHub | [plugins/github/README.md][PlGh] |\n", "| Google Drive | [plugins/googledrive/README.md][PlGd] |\n", "| OneDrive | [plugins/onedrive/README.md][PlOd] |\n", "| Medium | [plugins/medium/README.md][PlMe] |\n", "| Google Analytics | [plugins/googleanalytics/README.md][PlGa] |\n", "\n", "## Development\n", "\n", "Want to contribute? Great!\n", "\n", "Dillinger uses Gulp + Webpack for fast developing.\n", "Make a change in your file and instantaneously see your updates!\n", "\n", "Open your favorite Terminal and run these commands.\n", "\n", "First Tab:\n", "\n", "```sh\n", "node app\n", "```\n", "\n", "Second Tab:\n", "\n", "```sh\n", "gulp watch\n", "```\n", "\n", "(optional) Third:\n", "\n", "```sh\n", "karma test\n", "```\n", "\n", "#### Building for source\n", "\n", "For production release:\n", "\n", "```sh\n", "gulp build --prod\n", "```\n", "\n", "Generating pre-built zip archives for distribution:\n", "\n", "```sh\n", "gulp build dist --prod\n", "```\n", "\n", "## Docker\n", "\n", "Dillinger is very easy to install and deploy in a Docker container.\n", "\n", "By default, the Docker will expose port 8080, so change this within the\n", "Dockerfile if necessary. When ready, simply use the Dockerfile to\n", "build the image.\n", "\n", "```sh\n", "cd dillinger\n", "docker build -t /dillinger:${package.json.version} .\n", "```\n", "\n", "This will create the dillinger image and pull in the necessary dependencies.\n", "Be sure to swap out `${package.json.version}` with the actual\n", "version of Dillinger.\n", "\n", "Once done, run the Docker image and map the port to whatever you wish on\n", "your host. In this example, we simply map port 8000 of the host to\n", "port 8080 of the Docker (or whatever port was exposed in the Dockerfile):\n", "\n", "```sh\n", "docker run -d -p 8000:8080 --restart=always --cap-add=SYS_ADMIN --name=dillinger /dillinger:${package.json.version}\n", "```\n", "\n", "> Note: `--capt-add=SYS-ADMIN` is required for PDF rendering.\n", "\n", "Verify the deployment by navigating to your server address in\n", "your preferred browser.\n", "\n", "```sh\n", "127.0.0.1:8000\n", "```\n", "\n", "```python\n", "import gradio as gr\n", "\n", "gr.Blocks() as demo:\n", " gr.Markdown(value=md)\n", "\n", "demo.launch()\n", "```\n", "\n", "```js\n", "function fancyAlert(arg) {\n", " if(arg) {\n", " $.facebox({div:'#foo'})\n", " }\n", "}\n", "```\n", "\n", "## License\n", "\n", "MIT\n", "\n", "**Free Software, Hell Yeah!**\n", "\n", "[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)\n", "\n", " [dill]: \n", " [git-repo-url]: \n", " [john gruber]: \n", " [df1]: \n", " [markdown-it]: \n", " [Ace Editor]: \n", " [node.js]: \n", " [Twitter Bootstrap]: \n", " [jQuery]: \n", " [@tjholowaychuk]: \n", " [express]: \n", " [AngularJS]: \n", " [Gulp]: \n", "\n", " [PlDb]: \n", " [PlGh]: \n", " [PlGd]: \n", " [PlOd]: \n", " [PlMe]: \n", " [PlGa]: \n", "\n", "\"\"\"\n", "with gr.Blocks(css=css) as demo:\n", " gr.Markdown(value=md)\n", "\n", "demo.launch()\n"]}], "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 index 2db96b42cae0e..d2d497ef82776 100644 --- a/demo/matrix_transpose/run.ipynb +++ b/demo/matrix_transpose/run.ipynb @@ -1 +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 +{"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 index a2a6eebd773f4..53e4ceea0a1a3 100644 --- a/demo/model3D/run.ipynb +++ b/demo/model3D/run.ipynb @@ -1 +1,5 @@ -{"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\n", "\n", "\n", "demo = gr.Interface(\n", " fn=load_mesh,\n", " inputs=gr.Model3D(),\n", " outputs=gr.Model3D(\n", " clear_color=[0.0, 0.0, 0.0, 0.0], label=\"3D Model\"),\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", " 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 +<<<<<<< HEAD +{"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\n", "\n", "\n", "demo = gr.Interface(\n", " fn=load_mesh,\n", " inputs=gr.Model3D(),\n", " outputs=gr.Model3D(\n", " clear_color=[0.0, 0.0, 0.0, 0.0], label=\"3D Model\"),\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", " cache_examples=True\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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\n", "\n", "\n", "demo = gr.Interface(\n", " fn=load_mesh,\n", " inputs=gr.Model3D(),\n", " outputs=gr.Model3D(\n", " clear_color=[0.0, 0.0, 0.0, 0.0], label=\"3D Model\"),\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} +>>>>>>> main diff --git a/demo/model3d_component/run.ipynb b/demo/model3d_component/run.ipynb index 02e07d34f8092..dafccd6cd8386 100644 --- a/demo/model3d_component/run.ipynb +++ b/demo/model3d_component/run.ipynb @@ -1 +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 +{"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 index 45b989f1e5f3b..cd757ae18234f 100644 --- a/demo/musical_instrument_identification/run.ipynb +++ b/demo/musical_instrument_identification/run.ipynb @@ -1 +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\n", "import 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)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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\n", "import 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)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/native_plots/run.ipynb b/demo/native_plots/run.ipynb index 40d8e51c96fe7..f79c3ad9856bd 100644 --- a/demo/native_plots/run.ipynb +++ b/demo/native_plots/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: native_plots"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/bar_plot_demo.py\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/line_plot_demo.py\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/scatter_plot_demo.py"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from scatter_plot_demo import scatter_plot\n", "from line_plot_demo import line_plot\n", "from bar_plot_demo import bar_plot\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tabs():\n", " with gr.TabItem(\"Scatter Plot\"):\n", " scatter_plot.render()\n", " with gr.TabItem(\"Line Plot\"):\n", " line_plot.render()\n", " with gr.TabItem(\"Bar Plot\"):\n", " bar_plot.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: native_plots"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/bar_plot_demo.py\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/line_plot_demo.py\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/native_plots/scatter_plot_demo.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from scatter_plot_demo import scatter_plot\n", "from line_plot_demo import line_plot\n", "from bar_plot_demo import bar_plot\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tabs():\n", " with gr.TabItem(\"Scatter Plot\"):\n", " scatter_plot.render()\n", " with gr.TabItem(\"Line Plot\"):\n", " line_plot.render()\n", " with gr.TabItem(\"Bar Plot\"):\n", " bar_plot.render()\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/neon-tts-plugin-coqui/run.ipynb b/demo/neon-tts-plugin-coqui/run.ipynb index 9ae70bf87bf90..a154dec65da41 100644 --- a/demo/neon-tts-plugin-coqui/run.ipynb +++ b/demo/neon-tts-plugin-coqui/run.ipynb @@ -1 +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 +{"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 index f9933e1f4b374..a67da7879392b 100644 --- a/demo/ner_pipeline/run.ipynb +++ b/demo/ner_pipeline/run.ipynb @@ -1 +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 +{"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 index 6322b6c05a39f..b70a7f8ba0a4b 100644 --- a/demo/no_input/run.ipynb +++ b/demo/no_input/run.ipynb @@ -1 +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 +{"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 index a894d597d530e..8a3921c0dc217 100644 --- a/demo/number_component/run.ipynb +++ b/demo/number_component/run.ipynb @@ -1 +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 +{"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/on_listener_basic/run.ipynb b/demo/on_listener_basic/run.ipynb index 797057e692225..8f78c318b40a5 100644 --- a/demo/on_listener_basic/run.ipynb +++ b/demo/on_listener_basic/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_basic"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", " gr.on(\n", " triggers=[name.submit, greet_btn.click],\n", " fn=greet,\n", " inputs=name,\n", " outputs=output,\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_basic"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", " gr.on(\n", " triggers=[name.submit, greet_btn.click],\n", " fn=greet,\n", " inputs=name,\n", " outputs=output,\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: on_listener_basic"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", " gr.on(\n", " triggers=[name.submit, greet_btn.click],\n", " fn=greet,\n", " inputs=name,\n", " outputs=output,\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/on_listener_decorator/run.ipynb b/demo/on_listener_decorator/run.ipynb index d3bc295ee090b..7091592bf529d 100644 --- a/demo/on_listener_decorator/run.ipynb +++ b/demo/on_listener_decorator/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_decorator"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " @gr.on(triggers=[name.submit, greet_btn.click], inputs=name, outputs=output)\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_decorator"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " @gr.on(triggers=[name.submit, greet_btn.click], inputs=name, outputs=output)\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: on_listener_decorator"]}, {"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", " name = gr.Textbox(label=\"Name\")\n", " output = gr.Textbox(label=\"Output Box\")\n", " greet_btn = gr.Button(\"Greet\")\n", "\n", " @gr.on(triggers=[name.submit, greet_btn.click], inputs=name, outputs=output)\n", " def greet(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/on_listener_live/run.ipynb b/demo/on_listener_live/run.ipynb index b5f6df9ee4a00..c119a21a61fdd 100644 --- a/demo/on_listener_live/run.ipynb +++ b/demo/on_listener_live/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_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", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " num1 = gr.Slider(1, 10)\n", " num2 = gr.Slider(1, 10)\n", " num3 = gr.Slider(1, 10)\n", " output = gr.Number(label=\"Sum\")\n", "\n", " @gr.on(inputs=[num1, num2, num3], outputs=output)\n", " def sum(a, b, c):\n", " return a + b + c\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: on_listener_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", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " num1 = gr.Slider(1, 10)\n", " num2 = gr.Slider(1, 10)\n", " num3 = gr.Slider(1, 10)\n", " output = gr.Number(label=\"Sum\")\n", "\n", " @gr.on(inputs=[num1, num2, num3], outputs=output)\n", " def sum(a, b, c):\n", " return a + b + c\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: on_listener_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", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " num1 = gr.Slider(1, 10)\n", " num2 = gr.Slider(1, 10)\n", " num3 = gr.Slider(1, 10)\n", " output = gr.Number(label=\"Sum\")\n", "\n", " @gr.on(inputs=[num1, num2, num3], outputs=output)\n", " def sum(a, b, c):\n", " return a + b + c\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/outbreak_forecast/run.ipynb b/demo/outbreak_forecast/run.ipynb index f73160f88972f..60c1d1a721717 100644 --- a/demo/outbreak_forecast/run.ipynb +++ b/demo/outbreak_forecast/run.ipynb @@ -1 +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 altair"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import altair\n", "\n", "import gradio as gr\n", "from math import sqrt\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", " elif plot_type == \"Altair\":\n", " df = df.melt(id_vars=\"day\").rename(columns={\"variable\": \"country\"})\n", " fig = altair.Chart(df).mark_line().encode(x=\"day\", y='value', color='country')\n", " return fig\n", " else:\n", " raise ValueError(\"A plot type must be selected\")\n", "\n", "\n", "inputs = [\n", " gr.Dropdown([\"Matplotlib\", \"Plotly\", \"Altair\"], 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", " [\"Altair\", 2, \"March\", [\"Mexico\", \"Canada\"], 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", "\n", "\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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 altair"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import altair\n", "\n", "import gradio as gr\n", "from math import sqrt\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", " elif plot_type == \"Altair\":\n", " df = df.melt(id_vars=\"day\").rename(columns={\"variable\": \"country\"})\n", " fig = altair.Chart(df).mark_line().encode(x=\"day\", y='value', color='country')\n", " return fig\n", " else:\n", " raise ValueError(\"A plot type must be selected\")\n", "\n", "\n", "inputs = [\n", " gr.Dropdown([\"Matplotlib\", \"Plotly\", \"Altair\"], 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", " [\"Altair\", 2, \"March\", [\"Mexico\", \"Canada\"], 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", "\n", "\n", "\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 index a3200f294fba7..40f5d34b13450 100644 --- a/demo/pictionary/run.ipynb +++ b/demo/pictionary/run.ipynb @@ -1 +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 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/pictionary/class_names.txt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["from pathlib import Path\n", "\n", "import numpy as np\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(im):\n", " if im is None:\n", " return None\n", " im = np.asarray(im.resize((28, 28)))\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, \n", " inputs=gr.Sketchpad(label=\"Draw Here\", brush_radius=5, type=\"pil\", shape=(120, 120)), \n", " outputs=gr.Label(label=\"Guess\"), \n", " live=True)\n", "\n", "interface.queue().launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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 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/pictionary/class_names.txt"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["from pathlib import Path\n", "\n", "import numpy as np\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(im):\n", " if im is None:\n", " return None\n", " im = np.asarray(im.resize((28, 28)))\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, \n", " inputs=gr.Sketchpad(label=\"Draw Here\", brush_radius=5, type=\"pil\", shape=(120, 120)), \n", " outputs=gr.Label(label=\"Guess\"), \n", " live=True)\n", "\n", "interface.queue().launch()\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 index ef726a88f4543..76aa6333c7525 100644 --- a/demo/plot_component/run.ipynb +++ b/demo/plot_component/run.ipynb @@ -1 +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 +{"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/progress/run.ipynb b/demo/progress/run.ipynb index a1ffacf93135e..191895b2e7510 100644 --- a/demo/progress/run.ipynb +++ b/demo/progress/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: progress"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tqdm datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\n", "import time\n", "import tqdm\n", "from datasets import load_dataset\n", "import shutil\n", "from uuid import uuid4\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text = gr.Textbox()\n", " textb = gr.Textbox()\n", " with gr.Row():\n", " load_set_btn = gr.Button(\"Load Set\")\n", " load_nested_set_btn = gr.Button(\"Load Nested Set\")\n", " load_random_btn = gr.Button(\"Load Random\")\n", " clean_imgs_btn = gr.Button(\"Clean Images\")\n", " wait_btn = gr.Button(\"Wait\")\n", " do_all_btn = gr.Button(\"Do All\")\n", " track_tqdm_btn = gr.Button(\"Bind TQDM\")\n", " bind_internal_tqdm_btn = gr.Button(\"Bind Internal TQDM\")\n", "\n", " text2 = gr.Textbox()\n", "\n", " # track list\n", " def load_set(text, text2, progress=gr.Progress()):\n", " imgs = [None] * 24\n", " for img in progress.tqdm(imgs, desc=\"Loading from list\"):\n", " time.sleep(0.1)\n", " return \"done\"\n", " load_set_btn.click(load_set, [text, textb], text2)\n", "\n", " # track nested list\n", " def load_nested_set(text, text2, progress=gr.Progress()):\n", " imgs = [[None] * 8] * 3\n", " for img_set in progress.tqdm(imgs, desc=\"Nested list\"):\n", " time.sleep(2)\n", " for img in progress.tqdm(img_set, desc=\"inner list\"):\n", " time.sleep(0.1)\n", " return \"done\"\n", " load_nested_set_btn.click(load_nested_set, [text, textb], text2)\n", "\n", " # track iterable of unknown length\n", " def load_random(data, progress=gr.Progress()):\n", " def yielder():\n", " for i in range(0, random.randint(15, 20)):\n", " time.sleep(0.1)\n", " yield None\n", " for img in progress.tqdm(yielder()):\n", " pass\n", " return \"done\"\n", " load_random_btn.click(load_random, {text, textb}, text2)\n", " \n", " # manual progress\n", " def clean_imgs(text, progress=gr.Progress()):\n", " progress(0.2, desc=\"Collecting Images\")\n", " time.sleep(1)\n", " progress(0.5, desc=\"Cleaning Images\")\n", " time.sleep(1.5)\n", " progress(0.8, desc=\"Sending Images\")\n", " time.sleep(1.5)\n", " return \"done\"\n", " clean_imgs_btn.click(clean_imgs, text, text2)\n", "\n", " # no progress\n", " def wait(text):\n", " time.sleep(4)\n", " return \"done\"\n", " wait_btn.click(wait, text, text2)\n", "\n", " # multiple progressions\n", " def do_all(data, progress=gr.Progress()):\n", " load_set(data[text], data[textb], progress)\n", " load_random(data, progress)\n", " clean_imgs(data[text], progress)\n", " progress(None)\n", " wait(text)\n", " return \"done\"\n", " do_all_btn.click(do_all, {text, textb}, text2)\n", "\n", " def track_tqdm(data, progress=gr.Progress(track_tqdm=True)):\n", " for i in tqdm.tqdm(range(5), desc=\"outer\"):\n", " for j in tqdm.tqdm(range(4), desc=\"inner\"):\n", " time.sleep(1)\n", " return \"done\"\n", " track_tqdm_btn.click(track_tqdm, {text, textb}, text2)\n", "\n", " def bind_internal_tqdm(data, progress=gr.Progress(track_tqdm=True)):\n", " outdir = \"__tmp/\" + str(uuid4())\n", " load_dataset(\"beans\", split=\"train\", cache_dir=outdir)\n", " shutil.rmtree(outdir)\n", " return \"done\"\n", " bind_internal_tqdm_btn.click(bind_internal_tqdm, {text, textb}, text2)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue(concurrency_count=20).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: progress"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tqdm datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\n", "import time\n", "import tqdm\n", "from datasets import load_dataset\n", "import shutil\n", "from uuid import uuid4\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text = gr.Textbox()\n", " textb = gr.Textbox()\n", " with gr.Row():\n", " load_set_btn = gr.Button(\"Load Set\")\n", " load_nested_set_btn = gr.Button(\"Load Nested Set\")\n", " load_random_btn = gr.Button(\"Load Random\")\n", " clean_imgs_btn = gr.Button(\"Clean Images\")\n", " wait_btn = gr.Button(\"Wait\")\n", " do_all_btn = gr.Button(\"Do All\")\n", " track_tqdm_btn = gr.Button(\"Bind TQDM\")\n", " bind_internal_tqdm_btn = gr.Button(\"Bind Internal TQDM\")\n", "\n", " text2 = gr.Textbox()\n", "\n", " # track list\n", " def load_set(text, text2, progress=gr.Progress()):\n", " imgs = [None] * 24\n", " for img in progress.tqdm(imgs, desc=\"Loading from list\"):\n", " time.sleep(0.1)\n", " return \"done\"\n", " load_set_btn.click(load_set, [text, textb], text2)\n", "\n", " # track nested list\n", " def load_nested_set(text, text2, progress=gr.Progress()):\n", " imgs = [[None] * 8] * 3\n", " for img_set in progress.tqdm(imgs, desc=\"Nested list\"):\n", " time.sleep(2)\n", " for img in progress.tqdm(img_set, desc=\"inner list\"):\n", " time.sleep(0.1)\n", " return \"done\"\n", " load_nested_set_btn.click(load_nested_set, [text, textb], text2)\n", "\n", " # track iterable of unknown length\n", " def load_random(data, progress=gr.Progress()):\n", " def yielder():\n", " for i in range(0, random.randint(15, 20)):\n", " time.sleep(0.1)\n", " yield None\n", " for img in progress.tqdm(yielder()):\n", " pass\n", " return \"done\"\n", " load_random_btn.click(load_random, {text, textb}, text2)\n", " \n", " # manual progress\n", " def clean_imgs(text, progress=gr.Progress()):\n", " progress(0.2, desc=\"Collecting Images\")\n", " time.sleep(1)\n", " progress(0.5, desc=\"Cleaning Images\")\n", " time.sleep(1.5)\n", " progress(0.8, desc=\"Sending Images\")\n", " time.sleep(1.5)\n", " return \"done\"\n", " clean_imgs_btn.click(clean_imgs, text, text2)\n", "\n", " # no progress\n", " def wait(text):\n", " time.sleep(4)\n", " return \"done\"\n", " wait_btn.click(wait, text, text2)\n", "\n", " # multiple progressions\n", " def do_all(data, progress=gr.Progress()):\n", " load_set(data[text], data[textb], progress)\n", " load_random(data, progress)\n", " clean_imgs(data[text], progress)\n", " progress(None)\n", " wait(text)\n", " return \"done\"\n", " do_all_btn.click(do_all, {text, textb}, text2)\n", "\n", " def track_tqdm(data, progress=gr.Progress(track_tqdm=True)):\n", " for i in tqdm.tqdm(range(5), desc=\"outer\"):\n", " for j in tqdm.tqdm(range(4), desc=\"inner\"):\n", " time.sleep(1)\n", " return \"done\"\n", " track_tqdm_btn.click(track_tqdm, {text, textb}, text2)\n", "\n", " def bind_internal_tqdm(data, progress=gr.Progress(track_tqdm=True)):\n", " outdir = \"__tmp/\" + str(uuid4())\n", " load_dataset(\"beans\", split=\"train\", cache_dir=outdir)\n", " shutil.rmtree(outdir)\n", " return \"done\"\n", " bind_internal_tqdm_btn.click(bind_internal_tqdm, {text, textb}, text2)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue(concurrency_count=20).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/progress_component/run.ipynb b/demo/progress_component/run.ipynb index 687aa8effdda8..a77d5639074e6 100644 --- a/demo/progress_component/run.ipynb +++ b/demo/progress_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: progress_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tqdm"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import time \n", "\n", "def load_set(progress=gr.Progress()):\n", " imgs = [None] * 24\n", " for img in progress.tqdm(imgs, desc=\"Loading...\"):\n", " time.sleep(0.1)\n", " return \"Loaded\"\n", "\n", "\n", "with gr.Blocks() as demo:\n", " load = gr.Button(\"Load\")\n", " label = gr.Label(label=\"Loader\")\n", " load.click(load_set, outputs=label)\n", "\n", "demo.queue(concurrency_count=20).launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: progress_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tqdm"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import time \n", "\n", "def load_set(progress=gr.Progress()):\n", " imgs = [None] * 24\n", " for img in progress.tqdm(imgs, desc=\"Loading...\"):\n", " time.sleep(0.1)\n", " return \"Loaded\"\n", "\n", "\n", "with gr.Blocks() as demo:\n", " load = gr.Button(\"Load\")\n", " label = gr.Label(label=\"Loader\")\n", " load.click(load_set, outputs=label)\n", "\n", "demo.queue(concurrency_count=20).launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/progress_simple/run.ipynb b/demo/progress_simple/run.ipynb index 8869295aa8f21..9cadf82a536ed 100644 --- a/demo/progress_simple/run.ipynb +++ b/demo/progress_simple/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: progress_simple"]}, {"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 slowly_reverse(word, progress=gr.Progress()):\n", " progress(0, desc=\"Starting\")\n", " time.sleep(1)\n", " progress(0.05)\n", " new_string = \"\"\n", " for letter in progress.tqdm(word, desc=\"Reversing\"):\n", " time.sleep(0.25)\n", " new_string = letter + new_string\n", " return new_string\n", "\n", "demo = gr.Interface(slowly_reverse, gr.Text(), gr.Text())\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue(concurrency_count=10).launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: progress_simple"]}, {"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 slowly_reverse(word, progress=gr.Progress()):\n", " progress(0, desc=\"Starting\")\n", " time.sleep(1)\n", " progress(0.05)\n", " new_string = \"\"\n", " for letter in progress.tqdm(word, desc=\"Reversing\"):\n", " time.sleep(0.25)\n", " new_string = letter + new_string\n", " return new_string\n", "\n", "demo = gr.Interface(slowly_reverse, gr.Text(), gr.Text())\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue(concurrency_count=10).launch()\n"]}], "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 index 1c9771f9383d2..67be24671afbb 100644 --- a/demo/question-answering/run.ipynb +++ b/demo/question-answering/run.ipynb @@ -1 +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 torch transformers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline\n", "\n", "model_name = \"deepset/roberta-base-squad2\"\n", "\n", "nlp = pipeline(\"question-answering\", model=model_name, tokenizer=model_name)\n", "\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", "\n", "\n", "def predict(context, question):\n", " res = nlp({\"question\": question, \"context\": context})\n", " return res[\"answer\"], res[\"score\"]\n", "\n", "\n", "gr.Interface(\n", " predict,\n", " inputs=[\n", " gr.inputs.Textbox(lines=7, default=context, label=\"Context Paragraph\"),\n", " gr.inputs.Textbox(lines=2, default=question, label=\"Question\"),\n", " ],\n", " outputs=[gr.outputs.Textbox(label=\"Answer\"), gr.outputs.Textbox(label=\"Score\")],\n", ").launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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 torch transformers"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline\n", "\n", "model_name = \"deepset/roberta-base-squad2\"\n", "\n", "nlp = pipeline(\"question-answering\", model=model_name, tokenizer=model_name)\n", "\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", "\n", "\n", "def predict(context, question):\n", " res = nlp({\"question\": question, \"context\": context})\n", " return res[\"answer\"], res[\"score\"]\n", "\n", "\n", "gr.Interface(\n", " predict,\n", " inputs=[\n", " gr.inputs.Textbox(lines=7, default=context, label=\"Context Paragraph\"),\n", " gr.inputs.Textbox(lines=2, default=question, label=\"Question\"),\n", " ],\n", " outputs=[gr.outputs.Textbox(label=\"Answer\"), gr.outputs.Textbox(label=\"Score\")],\n", ").launch()\n"]}], "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 index 7306ddebebcd6..7ab1b08111f0f 100644 --- a/demo/radio_component/run.ipynb +++ b/demo/radio_component/run.ipynb @@ -1 +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 +{"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/request_ip_headers/run.ipynb b/demo/request_ip_headers/run.ipynb index 5f39209171af1..3e7810f850379 100644 --- a/demo/request_ip_headers/run.ipynb +++ b/demo/request_ip_headers/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: request_ip_headers"]}, {"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 predict(text, request: gr.Request):\n", " headers = request.headers\n", " host = request.client.host\n", " user_agent = request.headers[\"user-agent\"]\n", " return {\n", " \"ip\": host,\n", " \"user_agent\": user_agent,\n", " \"headers\": headers,\n", " }\n", "\n", "\n", "gr.Interface(predict, \"text\", \"json\").queue().launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: request_ip_headers"]}, {"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 predict(text, request: gr.Request):\n", " headers = request.headers\n", " host = request.client.host\n", " user_agent = request.headers[\"user-agent\"]\n", " return {\n", " \"ip\": host,\n", " \"user_agent\": user_agent,\n", " \"headers\": headers,\n", " }\n", "\n", "\n", "gr.Interface(predict, \"text\", \"json\").queue().launch()\n"]}], "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 index 2055898d694d0..03ad5778d2da6 100644 --- a/demo/reverse_audio/run.ipynb +++ b/demo/reverse_audio/run.ipynb @@ -1 +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 +{"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 index 5c12e41525b32..00b2dc5642705 100644 --- a/demo/reversible_flow/run.ipynb +++ b/demo/reversible_flow/run.ipynb @@ -1 +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", " atob = gr.Button(\"a > b\")\n", " btoa = 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 +{"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", " atob = gr.Button(\"a > b\")\n", " btoa = 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 index 8ffbaff7dfdaf..97214e9624133 100644 --- a/demo/rows_and_columns/run.ipynb +++ b/demo/rows_and_columns/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: rows_and_columns"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('images')\n", "!wget -q -O images/cheetah.jpg https://github.com/gradio-app/gradio/raw/main/demo/rows_and_columns/images/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text1 = gr.Textbox(label=\"t1\")\n", " slider2 = gr.Textbox(label=\"s2\")\n", " drop3 = gr.Dropdown([\"a\", \"b\", \"c\"], label=\"d3\")\n", " with gr.Row():\n", " with gr.Column(scale=1, min_width=600):\n", " text1 = gr.Textbox(label=\"prompt 1\")\n", " text2 = gr.Textbox(label=\"prompt 2\")\n", " inbtw = gr.Button(\"Between\")\n", " text4 = gr.Textbox(label=\"prompt 1\")\n", " text5 = gr.Textbox(label=\"prompt 2\")\n", " with gr.Column(scale=2, min_width=600):\n", " img1 = gr.Image(\"images/cheetah.jpg\")\n", " btn = gr.Button(\"Go\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: rows_and_columns"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('images')\n", "!wget -q -O images/cheetah.jpg https://github.com/gradio-app/gradio/raw/main/demo/rows_and_columns/images/cheetah.jpg"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text1 = gr.Textbox(label=\"t1\")\n", " slider2 = gr.Textbox(label=\"s2\")\n", " drop3 = gr.Dropdown([\"a\", \"b\", \"c\"], label=\"d3\")\n", " with gr.Row():\n", " with gr.Column(scale=1, min_width=600):\n", " text1 = gr.Textbox(label=\"prompt 1\")\n", " text2 = gr.Textbox(label=\"prompt 2\")\n", " inbtw = gr.Button(\"Between\")\n", " text4 = gr.Textbox(label=\"prompt 1\")\n", " text5 = gr.Textbox(label=\"prompt 2\")\n", " with gr.Column(scale=2, min_width=600):\n", " img1 = gr.Image(\"images/cheetah.jpg\")\n", " btn = gr.Button(\"Go\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/sales_projections/run.ipynb b/demo/sales_projections/run.ipynb index 197610cdc48db..3d75704d202c6 100644 --- a/demo/sales_projections/run.ipynb +++ b/demo/sales_projections/run.ipynb @@ -1 +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.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 +{"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.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 index 3cd4e716d9b31..7ae866d748672 100644 --- a/demo/same-person-or-different/run.ipynb +++ b/demo/same-person-or-different/run.ipynb @@ -1 +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", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

Welcome, human!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", " \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

You shall not pass!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\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 'ERROR: Please record audio for *both* speakers!'\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", " \"

\"\n", " \"\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT | \"\n", " \"\ud83d\udcda UniSpeech-SAT paper | \"\n", " \"\ud83d\udcda X-Vector paper\"\n", " \"

\"\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", " 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 +{"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", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

Welcome, human!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", " \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

You shall not pass!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\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 'ERROR: Please record audio for *both* speakers!'\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", " \"

\"\n", " \"\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT | \"\n", " \"\ud83d\udcda UniSpeech-SAT paper | \"\n", " \"\ud83d\udcda X-Vector paper\"\n", " \"

\"\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", " 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/save_file_no_output/run.ipynb b/demo/save_file_no_output/run.ipynb index b26dccf81b2db..73988d9cafaf0 100644 --- a/demo/save_file_no_output/run.ipynb +++ b/demo/save_file_no_output/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: save_file_no_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 random\n", "import string\n", "import gradio as gr \n", "\n", "def save_image_random_name(image):\n", " random_string = ''.join(random.choices(string.ascii_letters, k=20)) + '.png'\n", " image.save(random_string)\n", " print(f\"Saved image to {random_string}!\")\n", "\n", "demo = gr.Interface(\n", " fn=save_image_random_name, \n", " inputs=gr.Image(type=\"pil\"), \n", " outputs=None,\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: save_file_no_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 random\n", "import string\n", "import gradio as gr \n", "\n", "def save_image_random_name(image):\n", " random_string = ''.join(random.choices(string.ascii_letters, k=20)) + '.png'\n", " image.save(random_string)\n", " print(f\"Saved image to {random_string}!\")\n", "\n", "demo = gr.Interface(\n", " fn=save_image_random_name, \n", " inputs=gr.Image(type=\"pil\"), \n", " outputs=None,\n", ")\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/scatter_plot/run.ipynb b/demo/scatter_plot/run.ipynb index d5d992f1a732f..ca9e7f5a75c01 100644 --- a/demo/scatter_plot/run.ipynb +++ b/demo/scatter_plot/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: scatter_plot"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets pandas"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "iris = data.iris()\n", "\n", "# # Or generate your own fake data\n", "\n", "# import pandas as pd\n", "# import random\n", "\n", "# cars_data = {\n", "# \"Name\": [\"car name \" + f\" {int(i/10)}\" for i in range(400)],\n", "# \"Miles_per_Gallon\": [random.randint(10, 30) for _ in range(400)],\n", "# \"Origin\": [random.choice([\"USA\", \"Europe\", \"Japan\"]) for _ in range(400)],\n", "# \"Horsepower\": [random.randint(50, 250) for _ in range(400)],\n", "# }\n", "\n", "# iris_data = {\n", "# \"petalWidth\": [round(random.uniform(0, 2.5), 2) for _ in range(150)],\n", "# \"petalLength\": [round(random.uniform(0, 7), 2) for _ in range(150)],\n", "# \"species\": [\n", "# random.choice([\"setosa\", \"versicolor\", \"virginica\"]) for _ in range(150)\n", "# ],\n", "# }\n", "\n", "# cars = pd.DataFrame(cars_data)\n", "# iris = pd.DataFrame(iris_data)\n", "\n", "\n", "def scatter_plot_fn(dataset):\n", " if dataset == \"iris\":\n", " return gr.ScatterPlot(\n", " value=iris,\n", " x=\"petalWidth\",\n", " y=\"petalLength\",\n", " color=\"species\",\n", " title=\"Iris Dataset\",\n", " color_legend_title=\"Species\",\n", " x_title=\"Petal Width\",\n", " y_title=\"Petal Length\",\n", " tooltip=[\"petalWidth\", \"petalLength\", \"species\"],\n", " caption=\"\",\n", " )\n", " else:\n", " return gr.ScatterPlot(\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\",\n", " caption=\"MPG vs Horsepower of various cars\",\n", " )\n", "\n", "\n", "with gr.Blocks() as scatter_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " dataset = gr.Dropdown(choices=[\"cars\", \"iris\"], value=\"cars\")\n", " with gr.Column():\n", " plot = gr.ScatterPlot()\n", " dataset.change(scatter_plot_fn, inputs=dataset, outputs=plot)\n", " scatter_plot.load(fn=scatter_plot_fn, inputs=dataset, outputs=plot)\n", "\n", "if __name__ == \"__main__\":\n", " scatter_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: scatter_plot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets pandas"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "iris = data.iris()\n", "\n", "# # Or generate your own fake data\n", "\n", "# import pandas as pd\n", "# import random\n", "\n", "# cars_data = {\n", "# \"Name\": [\"car name \" + f\" {int(i/10)}\" for i in range(400)],\n", "# \"Miles_per_Gallon\": [random.randint(10, 30) for _ in range(400)],\n", "# \"Origin\": [random.choice([\"USA\", \"Europe\", \"Japan\"]) for _ in range(400)],\n", "# \"Horsepower\": [random.randint(50, 250) for _ in range(400)],\n", "# }\n", "\n", "# iris_data = {\n", "# \"petalWidth\": [round(random.uniform(0, 2.5), 2) for _ in range(150)],\n", "# \"petalLength\": [round(random.uniform(0, 7), 2) for _ in range(150)],\n", "# \"species\": [\n", "# random.choice([\"setosa\", \"versicolor\", \"virginica\"]) for _ in range(150)\n", "# ],\n", "# }\n", "\n", "# cars = pd.DataFrame(cars_data)\n", "# iris = pd.DataFrame(iris_data)\n", "\n", "\n", "def scatter_plot_fn(dataset):\n", " if dataset == \"iris\":\n", " return gr.ScatterPlot(\n", " value=iris,\n", " x=\"petalWidth\",\n", " y=\"petalLength\",\n", " color=\"species\",\n", " title=\"Iris Dataset\",\n", " color_legend_title=\"Species\",\n", " x_title=\"Petal Width\",\n", " y_title=\"Petal Length\",\n", " tooltip=[\"petalWidth\", \"petalLength\", \"species\"],\n", " caption=\"\",\n", " )\n", " else:\n", " return gr.ScatterPlot(\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\",\n", " caption=\"MPG vs Horsepower of various cars\",\n", " )\n", "\n", "\n", "with gr.Blocks() as scatter_plot:\n", " with gr.Row():\n", " with gr.Column():\n", " dataset = gr.Dropdown(choices=[\"cars\", \"iris\"], value=\"cars\")\n", " with gr.Column():\n", " plot = gr.ScatterPlot()\n", " dataset.change(scatter_plot_fn, inputs=dataset, outputs=plot)\n", " scatter_plot.load(fn=scatter_plot_fn, inputs=dataset, outputs=plot)\n", "\n", "if __name__ == \"__main__\":\n", " scatter_plot.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/scatterplot_component/run.ipynb b/demo/scatterplot_component/run.ipynb index 66f60f7be4e96..79ac60139652f 100644 --- a/demo/scatterplot_component/run.ipynb +++ b/demo/scatterplot_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: scatterplot_component"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "\n", "with gr.Blocks() as demo:\n", " gr.ScatterPlot(\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\",\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: scatterplot_component"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio vega_datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from vega_datasets import data\n", "\n", "cars = data.cars()\n", "\n", "with gr.Blocks() as demo:\n", " gr.ScatterPlot(\n", " value=cars,\n", " x=\"Horsepower\",\n", " y=\"Miles_per_Gallon\",\n", " color=\"Origin\",\n", " tooltip=\"Name\",\n", " title=\"Car Data\",\n", " y_title=\"Miles per Gallon\",\n", " color_legend_title=\"Origin of Car\",\n", " container=False,\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/score_tracker/run.ipynb b/demo/score_tracker/run.ipynb index c089e64c461d9..6030d1e5b6be9 100644 --- a/demo/score_tracker/run.ipynb +++ b/demo/score_tracker/run.ipynb @@ -1 +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 +{"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 index 994c2af1611a7..8b154a371fe80 100644 --- a/demo/sentence_builder/run.ipynb +++ b/demo/sentence_builder/run.ipynb @@ -1 +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, countries, place, activity_list, morning):\n", " return f\"\"\"The {quantity} {animal}s from {\" and \".join(countries)} went to the {place} where they {\" and \".join(activity_list)} until the {\"morning\" if morning else \"night\"}\"\"\"\n", "\n", "\n", "demo = gr.Interface(\n", " sentence_builder,\n", " [\n", " gr.Slider(2, 20, value=4, label=\"Count\", info=\"Choose between 2 and 20\"),\n", " gr.Dropdown(\n", " [\"cat\", \"dog\", \"bird\"], label=\"Animal\", info=\"Will add more animals later!\"\n", " ),\n", " gr.CheckboxGroup([\"USA\", \"Japan\", \"Pakistan\"], label=\"Countries\", info=\"Where are they from?\"),\n", " gr.Radio([\"park\", \"zoo\", \"road\"], label=\"Location\", info=\"Where did they go?\"),\n", " gr.Dropdown(\n", " [\"ran\", \"swam\", \"ate\", \"slept\"], value=[\"swam\", \"slept\"], multiselect=True, label=\"Activity\", info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl.\"\n", " ),\n", " gr.Checkbox(label=\"Morning\", info=\"Did they do it in the morning?\"),\n", " ],\n", " \"text\",\n", " examples=[\n", " [2, \"cat\", [\"Japan\", \"Pakistan\"], \"park\", [\"ate\", \"swam\"], True],\n", " [4, \"dog\", [\"Japan\"], \"zoo\", [\"ate\", \"swam\"], False],\n", " [10, \"bird\", [\"USA\", \"Pakistan\"], \"road\", [\"ran\"], False],\n", " [8, \"cat\", [\"Pakistan\"], \"zoo\", [\"ate\"], True],\n", " ]\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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, countries, place, activity_list, morning):\n", " return f\"\"\"The {quantity} {animal}s from {\" and \".join(countries)} went to the {place} where they {\" and \".join(activity_list)} until the {\"morning\" if morning else \"night\"}\"\"\"\n", "\n", "\n", "demo = gr.Interface(\n", " sentence_builder,\n", " [\n", " gr.Slider(2, 20, value=4, label=\"Count\", info=\"Choose between 2 and 20\"),\n", " gr.Dropdown(\n", " [\"cat\", \"dog\", \"bird\"], label=\"Animal\", info=\"Will add more animals later!\"\n", " ),\n", " gr.CheckboxGroup([\"USA\", \"Japan\", \"Pakistan\"], label=\"Countries\", info=\"Where are they from?\"),\n", " gr.Radio([\"park\", \"zoo\", \"road\"], label=\"Location\", info=\"Where did they go?\"),\n", " gr.Dropdown(\n", " [\"ran\", \"swam\", \"ate\", \"slept\"], value=[\"swam\", \"slept\"], multiselect=True, label=\"Activity\", info=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl.\"\n", " ),\n", " gr.Checkbox(label=\"Morning\", info=\"Did they do it in the morning?\"),\n", " ],\n", " \"text\",\n", " examples=[\n", " [2, \"cat\", [\"Japan\", \"Pakistan\"], \"park\", [\"ate\", \"swam\"], True],\n", " [4, \"dog\", [\"Japan\"], \"zoo\", [\"ate\", \"swam\"], False],\n", " [10, \"bird\", [\"USA\", \"Pakistan\"], \"road\", [\"ran\"], False],\n", " [8, \"cat\", [\"Pakistan\"], \"zoo\", [\"ate\"], True],\n", " ]\n", ")\n", "\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 index 84ca228e2f4e5..9ef6ef66035d5 100644 --- a/demo/sentiment_analysis/run.ipynb +++ b/demo/sentiment_analysis/run.ipynb @@ -1 +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 +{"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 index 74fc34c2048bf..3f8c9fac800eb 100644 --- a/demo/sepia_filter/run.ipynb +++ b/demo/sepia_filter/run.ipynb @@ -1 +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 +{"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 index 6871a2655ea06..08683bbbf7e7c 100644 --- a/demo/sine_curve/run.ipynb +++ b/demo/sine_curve/run.ipynb @@ -1 +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 +{"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 index ea8007b32a5ea..50cf32dadf354 100644 --- a/demo/slider_component/run.ipynb +++ b/demo/slider_component/run.ipynb @@ -1 +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 +{"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/slider_release/run.ipynb b/demo/slider_release/run.ipynb index b11864cffccc7..efb64c5194a7b 100644 --- a/demo/slider_release/run.ipynb +++ b/demo/slider_release/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: slider_release"]}, {"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 identity(x, state):\n", " state += 1\n", " return x, state, state\n", "\n", "\n", "with gr.Blocks() as demo:\n", " slider = gr.Slider(0, 100, step=0.1)\n", " state = gr.State(value=0)\n", " with gr.Row():\n", " number = gr.Number(label=\"On release\")\n", " number2 = gr.Number(label=\"Number of events fired\")\n", " slider.release(identity, inputs=[slider, state], outputs=[number, state, number2], api_name=\"predict\")\n", "\n", "if __name__ == \"__main__\":\n", " print(\"here\")\n", " demo.launch()\n", " print(demo.server_port)\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: slider_release"]}, {"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 identity(x, state):\n", " state += 1\n", " return x, state, state\n", "\n", "\n", "with gr.Blocks() as demo:\n", " slider = gr.Slider(0, 100, step=0.1)\n", " state = gr.State(value=0)\n", " with gr.Row():\n", " number = gr.Number(label=\"On release\")\n", " number2 = gr.Number(label=\"Number of events fired\")\n", " slider.release(identity, inputs=[slider, state], outputs=[number, state, number2], api_name=\"predict\")\n", "\n", "if __name__ == \"__main__\":\n", " print(\"here\")\n", " demo.launch()\n", " print(demo.server_port)\n"]}], "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 index 15da4349700c4..5237197a80629 100644 --- a/demo/sound_alert/run.ipynb +++ b/demo/sound_alert/run.ipynb @@ -1 +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 argument whose usage may change in the future\n", " \n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: 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 argument 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 index f4b592cc6e827..f5968d14a4b63 100644 --- a/demo/spectogram/run.ipynb +++ b/demo/spectogram/run.ipynb @@ -1 +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 +{"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 index 42272eec2979e..a059ed9ddf3eb 100644 --- a/demo/stable-diffusion/run.ipynb +++ b/demo/stable-diffusion/run.ipynb @@ -1 +1,5 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stable-diffusion\n", "### Note: This is a simplified version of the code needed to create the Stable Diffusion demo. See full code here: https://hf.co/spaces/stabilityai/stable-diffusion/tree/main\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio diffusers transformers nvidia-ml-py3 ftfy torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from diffusers import StableDiffusionPipeline\n", "from PIL import Image\n", "import os\n", "\n", "auth_token = os.getenv(\"auth_token\")\n", "model_id = \"CompVis/stable-diffusion-v1-4\"\n", "device = \"cpu\"\n", "pipe = StableDiffusionPipeline.from_pretrained(\n", " model_id, use_auth_token=auth_token, revision=\"fp16\", torch_dtype=torch.float16\n", ")\n", "pipe = pipe.to(device)\n", "\n", "\n", "def infer(prompt, samples, steps, scale, seed):\n", " generator = torch.Generator(device=device).manual_seed(seed)\n", " images_list = pipe(\n", " [prompt] * samples,\n", " num_inference_steps=steps,\n", " guidance_scale=scale,\n", " generator=generator,\n", " )\n", " images = []\n", " safe_image = Image.open(r\"unsafe.png\")\n", " for i, image in enumerate(images_list[\"sample\"]):\n", " if images_list[\"nsfw_content_detected\"][i]:\n", " images.append(safe_image)\n", " else:\n", " images.append(image)\n", " return images\n", "\n", "\n", "block = gr.Blocks()\n", "\n", "with block:\n", " with gr.Group():\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\")\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " elem_id=\"gallery\",\n", " columns=[2],\n", " height=\"auto\",\n", " )\n", "\n", " advanced_button = gr.Button(\"Advanced options\", elem_id=\"advanced-btn\")\n", "\n", " with gr.Row(elem_id=\"advanced-options\"):\n", " samples = gr.Slider(label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n", " steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n", " scale = gr.Slider(\n", " label=\"Guidance Scale\", minimum=0, maximum=50, value=7.5, step=0.1\n", " )\n", " seed = gr.Slider(\n", " label=\"Seed\",\n", " minimum=0,\n", " maximum=2147483647,\n", " step=1,\n", " randomize=True,\n", " )\n", " gr.on([text.submit, btn.click], infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " advanced_button.click(\n", " None,\n", " [],\n", " text,\n", " )\n", "\n", "block.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +<<<<<<< HEAD +{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stable-diffusion\n", "### Note: This is a simplified version of the code needed to create the Stable Diffusion demo. See full code here: https://hf.co/spaces/stabilityai/stable-diffusion/tree/main\n", " "]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio diffusers transformers nvidia-ml-py3 ftfy torch"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from diffusers import StableDiffusionPipeline\n", "from PIL import Image\n", "import os\n", "\n", "auth_token = os.getenv(\"auth_token\")\n", "model_id = \"CompVis/stable-diffusion-v1-4\"\n", "device = \"cpu\"\n", "pipe = StableDiffusionPipeline.from_pretrained(\n", " model_id, use_auth_token=auth_token, revision=\"fp16\", torch_dtype=torch.float16\n", ")\n", "pipe = pipe.to(device)\n", "\n", "\n", "def infer(prompt, samples, steps, scale, seed):\n", " generator = torch.Generator(device=device).manual_seed(seed)\n", " images_list = pipe(\n", " [prompt] * samples,\n", " num_inference_steps=steps,\n", " guidance_scale=scale,\n", " generator=generator,\n", " )\n", " images = []\n", " safe_image = Image.open(r\"unsafe.png\")\n", " for i, image in enumerate(images_list[\"sample\"]):\n", " if images_list[\"nsfw_content_detected\"][i]:\n", " images.append(safe_image)\n", " else:\n", " images.append(image)\n", " return images\n", "\n", "\n", "block = gr.Blocks()\n", "\n", "with block:\n", " with gr.Group():\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\")\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " elem_id=\"gallery\",\n", " columns=[2],\n", " height=\"auto\",\n", " )\n", "\n", " advanced_button = gr.Button(\"Advanced options\", elem_id=\"advanced-btn\")\n", "\n", " with gr.Row(elem_id=\"advanced-options\"):\n", " samples = gr.Slider(label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n", " steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n", " scale = gr.Slider(\n", " label=\"Guidance Scale\", minimum=0, maximum=50, value=7.5, step=0.1\n", " )\n", " seed = gr.Slider(\n", " label=\"Seed\",\n", " minimum=0,\n", " maximum=2147483647,\n", " step=1,\n", " randomize=True,\n", " )\n", " gr.on([text.submit, btn.click], infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " advanced_button.click(\n", " None,\n", " [],\n", " text,\n", " )\n", "\n", "block.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: stable-diffusion\n", "### Note: This is a simplified version of the code needed to create the Stable Diffusion demo. See full code here: https://hf.co/spaces/stabilityai/stable-diffusion/tree/main\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio diffusers transformers nvidia-ml-py3 ftfy torch"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import torch\n", "from diffusers import StableDiffusionPipeline\n", "from PIL import Image\n", "import os\n", "\n", "auth_token = os.getenv(\"auth_token\")\n", "model_id = \"CompVis/stable-diffusion-v1-4\"\n", "device = \"cpu\"\n", "pipe = StableDiffusionPipeline.from_pretrained(\n", " model_id, use_auth_token=auth_token, revision=\"fp16\", torch_dtype=torch.float16\n", ")\n", "pipe = pipe.to(device)\n", "\n", "\n", "def infer(prompt, samples, steps, scale, seed):\n", " generator = torch.Generator(device=device).manual_seed(seed)\n", " images_list = pipe(\n", " [prompt] * samples,\n", " num_inference_steps=steps,\n", " guidance_scale=scale,\n", " generator=generator,\n", " )\n", " images = []\n", " safe_image = Image.open(r\"unsafe.png\")\n", " for i, image in enumerate(images_list[\"sample\"]):\n", " if images_list[\"nsfw_content_detected\"][i]:\n", " images.append(safe_image)\n", " else:\n", " images.append(image)\n", " return images\n", "\n", "\n", "block = gr.Blocks()\n", "\n", "with block:\n", " with gr.Group():\n", " with gr.Row():\n", " text = gr.Textbox(\n", " label=\"Enter your prompt\",\n", " max_lines=1,\n", " placeholder=\"Enter your prompt\",\n", " container=False,\n", " )\n", " btn = gr.Button(\"Generate image\")\n", " gallery = gr.Gallery(\n", " label=\"Generated images\",\n", " show_label=False,\n", " elem_id=\"gallery\",\n", " columns=[2],\n", " height=\"auto\",\n", " )\n", "\n", " advanced_button = gr.Button(\"Advanced options\", elem_id=\"advanced-btn\")\n", "\n", " with gr.Row(elem_id=\"advanced-options\"):\n", " samples = gr.Slider(label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n", " steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n", " scale = gr.Slider(\n", " label=\"Guidance Scale\", minimum=0, maximum=50, value=7.5, step=0.1\n", " )\n", " seed = gr.Slider(\n", " label=\"Seed\",\n", " minimum=0,\n", " maximum=2147483647,\n", " step=1,\n", " randomize=True,\n", " )\n", " gr.on([text.submit, btn.click], infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)\n", " advanced_button.click(\n", " None,\n", " [],\n", " text,\n", " )\n", "\n", "block.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/state_component/run.ipynb b/demo/state_component/run.ipynb index 83e1049d347b8..5a50fd98b3715 100644 --- a/demo/state_component/run.ipynb +++ b/demo/state_component/run.ipynb @@ -1 +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 +{"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 index dc0b0dc6bc3e5..5fce6697fcb89 100644 --- a/demo/stock_forecast/run.ipynb +++ b/demo/stock_forecast/run.ipynb @@ -1 +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.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 +{"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.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_asr/run.ipynb b/demo/stream_asr/run.ipynb index c5ce437da6a49..8eec2af351b05 100644 --- a/demo/stream_asr/run.ipynb +++ b/demo/stream_asr/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stream_asr"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchaudio transformers"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import pipeline\n", "import numpy as np\n", "\n", "transcriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n", "\n", "def transcribe(stream, new_chunk):\n", " sr, y = new_chunk\n", " y = y.astype(np.float32)\n", " y /= np.max(np.abs(y))\n", "\n", " if stream is not None:\n", " stream = np.concatenate([stream, y])\n", " else:\n", " stream = y\n", " return stream, transcriber({\"sampling_rate\": sr, \"raw\": stream})[\"text\"]\n", "\n", "\n", "demo = gr.Interface(\n", " transcribe,\n", " [\"state\", gr.Audio(source=\"microphone\", streaming=True)],\n", " [\"state\", \"text\"],\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 +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: stream_asr"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio torch torchaudio transformers"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from transformers import pipeline\n", "import numpy as np\n", "\n", "transcriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n", "\n", "def transcribe(stream, new_chunk):\n", " sr, y = new_chunk\n", " y = y.astype(np.float32)\n", " y /= np.max(np.abs(y))\n", "\n", " if stream is not None:\n", " stream = np.concatenate([stream, y])\n", " else:\n", " stream = y\n", " return stream, transcriber({\"sampling_rate\": sr, \"raw\": stream})[\"text\"]\n", "\n", "\n", "demo = gr.Interface(\n", " transcribe,\n", " [\"state\", gr.Audio(source=\"microphone\", streaming=True)],\n", " [\"state\", \"text\"],\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/stream_audio/run.ipynb b/demo/stream_audio/run.ipynb index 3cb0d76c525ab..766c73658cd44 100644 --- a/demo/stream_audio/run.ipynb +++ b/demo/stream_audio/run.ipynb @@ -1 +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.Audio(), 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 +{"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.Audio(), 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_audio_out/run.ipynb b/demo/stream_audio_out/run.ipynb index 25ef1f123bd96..af33bb68d67a1 100644 --- a/demo/stream_audio_out/run.ipynb +++ b/demo/stream_audio_out/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: stream_audio_out"]}, {"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/stream_audio_out/audio/cantina.wav"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from pydub import AudioSegment\n", "from time import sleep\n", "\n", "with gr.Blocks() as demo:\n", " input_audio = gr.Audio(label=\"Input Audio\", type=\"filepath\", format=\"mp3\")\n", " with gr.Row():\n", " with gr.Column():\n", " stream_as_file_btn = gr.Button(\"Stream as File\")\n", " format = gr.Radio([\"wav\", \"mp3\"], value=\"wav\", label=\"Format\")\n", " stream_as_file_output = gr.Audio(streaming=True)\n", "\n", " def stream_file(audio_file, format):\n", " audio = AudioSegment.from_file(audio_file)\n", " i = 0\n", " chunk_size = 1000\n", " while chunk_size * i < len(audio):\n", " chunk = audio[chunk_size * i : chunk_size * (i + 1)]\n", " i += 1\n", " if chunk:\n", " file = f\"/tmp/{i}.{format}\"\n", " chunk.export(file, format=format)\n", " yield file\n", " sleep(0.5)\n", "\n", " stream_as_file_btn.click(\n", " stream_file, [input_audio, format], stream_as_file_output\n", " )\n", "\n", " gr.Examples(\n", " [[\"audio/cantina.wav\", \"wav\"], [\"audio/cantina.wav\", \"mp3\"]],\n", " [input_audio, format],\n", " fn=stream_file,\n", " outputs=stream_as_file_output,\n", " cache_examples=True,\n", " )\n", "\n", " with gr.Column():\n", " stream_as_bytes_btn = gr.Button(\"Stream as Bytes\")\n", " stream_as_bytes_output = gr.Audio(format=\"bytes\", streaming=True)\n", "\n", " def stream_bytes(audio_file):\n", " chunk_size = 20_000\n", " with open(audio_file, \"rb\") as f:\n", " while True:\n", " chunk = f.read(chunk_size)\n", " if chunk:\n", " yield chunk\n", " sleep(1)\n", " else:\n", " break\n", " stream_as_bytes_btn.click(stream_bytes, input_audio, stream_as_bytes_output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.queue().launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: stream_audio_out"]}, {"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/stream_audio_out/audio/cantina.wav"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from pydub import AudioSegment\n", "from time import sleep\n", "\n", "with gr.Blocks() as demo:\n", " input_audio = gr.Audio(label=\"Input Audio\", type=\"filepath\", format=\"mp3\")\n", " with gr.Row():\n", " with gr.Column():\n", " stream_as_file_btn = gr.Button(\"Stream as File\")\n", " format = gr.Radio([\"wav\", \"mp3\"], value=\"wav\", label=\"Format\")\n", " stream_as_file_output = gr.Audio(streaming=True)\n", "\n", " def stream_file(audio_file, format):\n", " audio = AudioSegment.from_file(audio_file)\n", " i = 0\n", " chunk_size = 1000\n", " while chunk_size * i < len(audio):\n", " chunk = audio[chunk_size * i : chunk_size * (i + 1)]\n", " i += 1\n", " if chunk:\n", " file = f\"/tmp/{i}.{format}\"\n", " chunk.export(file, format=format)\n", " yield file\n", " sleep(0.5)\n", "\n", " stream_as_file_btn.click(\n", " stream_file, [input_audio, format], stream_as_file_output\n", " )\n", "\n", " gr.Examples(\n", " [[\"audio/cantina.wav\", \"wav\"], [\"audio/cantina.wav\", \"mp3\"]],\n", " [input_audio, format],\n", " fn=stream_file,\n", " outputs=stream_as_file_output,\n", " cache_examples=True,\n", " )\n", "\n", " with gr.Column():\n", " stream_as_bytes_btn = gr.Button(\"Stream as Bytes\")\n", " stream_as_bytes_output = gr.Audio(format=\"bytes\", streaming=True)\n", "\n", " def stream_bytes(audio_file):\n", " chunk_size = 20_000\n", " with open(audio_file, \"rb\") as f:\n", " while True:\n", " chunk = f.read(chunk_size)\n", " if chunk:\n", " yield chunk\n", " sleep(1)\n", " else:\n", " break\n", " stream_as_bytes_btn.click(stream_bytes, input_audio, stream_as_bytes_output)\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/stream_frames/run.ipynb b/demo/stream_frames/run.ipynb index f39f16a90dfbc..f71842e9202fe 100644 --- a/demo/stream_frames/run.ipynb +++ b/demo/stream_frames/run.ipynb @@ -1 +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()\n", " "]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"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()\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 index b92040cb1dd9f..28660acf8bc5c 100644 --- a/demo/streaming_wav2vec/run.ipynb +++ b/demo/streaming_wav2vec/run.ipynb @@ -1 +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 +{"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 index 351ddf363b324..ad53035e0e6fe 100644 --- a/demo/stt_or_tts/run.ipynb +++ b/demo/stt_or_tts/run.ipynb @@ -1 +1,5 @@ -{"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", "tts_examples = [\n", " \"I love learning machine learning\",\n", " \"How do you do?\",\n", "]\n", "\n", "tts_demo = gr.load(\n", " \"huggingface/facebook/fastspeech2-en-ljspeech\",\n", " title=None,\n", " examples=tts_examples,\n", " description=\"Give me something to say!\",\n", " cache_examples=False\n", ")\n", "\n", "stt_demo = gr.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 +<<<<<<< HEAD +{"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", "tts_examples = [\n", " \"I love learning machine learning\",\n", " \"How do you do?\",\n", "]\n", "\n", "tts_demo = gr.load(\n", " \"huggingface/facebook/fastspeech2-en-ljspeech\",\n", " title=None,\n", " examples=tts_examples,\n", " description=\"Give me something to say!\",\n", " cache_examples=False\n", ")\n", "\n", "stt_demo = gr.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} +======= +{"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", "tts_examples = [\n", " \"I love learning machine learning\",\n", " \"How do you do?\",\n", "]\n", "\n", "tts_demo = gr.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.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} +>>>>>>> main diff --git a/demo/tax_calculator/run.ipynb b/demo/tax_calculator/run.ipynb index b85290fd4604f..a531071b1b664 100644 --- a/demo/tax_calculator/run.ipynb +++ b/demo/tax_calculator/run.ipynb @@ -1 +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 +{"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 index cc53c4e960ec7..b95ad000185ad 100644 --- a/demo/text_analysis/run.ipynb +++ b/demo/text_analysis/run.ipynb @@ -1 +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", " \"
\"\n", " + html\n", " + \"
\"\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 +{"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", " \"
\"\n", " + html\n", " + \"
\"\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 index c4eb578be99de..073b694f94850 100644 --- a/demo/text_generation/run.ipynb +++ b/demo/text_generation/run.ipynb @@ -1 +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 +{"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 index e0375502e3e62..94f2ac6b69222 100644 --- a/demo/textbox_component/run.ipynb +++ b/demo/textbox_component/run.ipynb @@ -1 +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 +{"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/theme_builder/run.ipynb b/demo/theme_builder/run.ipynb index c8fc1f0e81dc2..568820d9dcf11 100644 --- a/demo/theme_builder/run.ipynb +++ b/demo/theme_builder/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_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", "demo = gr.themes.builder\n", "\n", "if __name__ == \"__main__\":\n", " demo()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_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", "demo = gr.themes.builder\n", "\n", "if __name__ == \"__main__\":\n", " demo()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/theme_extended_step_1/run.ipynb b/demo/theme_extended_step_1/run.ipynb index 8463267bd522f..efb81c6c98aff 100644 --- a/demo/theme_extended_step_1/run.ipynb +++ b/demo/theme_extended_step_1/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_1"]}, {"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", "with gr.Blocks(theme=gr.themes.Default(primary_hue=\"red\", secondary_hue=\"pink\")) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_1"]}, {"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", "with gr.Blocks(theme=gr.themes.Default(primary_hue=\"red\", secondary_hue=\"pink\")) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], 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/theme_extended_step_2/run.ipynb b/demo/theme_extended_step_2/run.ipynb index 20791b4fc3fd8..670f0746a218c 100644 --- a/demo/theme_extended_step_2/run.ipynb +++ b/demo/theme_extended_step_2/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_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", "import time\n", "\n", "with gr.Blocks(theme=gr.themes.Default(spacing_size=\"sm\", radius_size=\"none\")) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_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", "import time\n", "\n", "with gr.Blocks(theme=gr.themes.Default(spacing_size=\"sm\", radius_size=\"none\")) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], 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/theme_extended_step_3/run.ipynb b/demo/theme_extended_step_3/run.ipynb index 4f95b0a4920d9..7c7bcf0136c61 100644 --- a/demo/theme_extended_step_3/run.ipynb +++ b/demo/theme_extended_step_3/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_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", "import time\n", "\n", "with gr.Blocks(\n", " theme=gr.themes.Default(\n", " font=[gr.themes.GoogleFont(\"Inconsolata\"), \"Arial\", \"sans-serif\"]\n", " )\n", ") as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_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", "import time\n", "\n", "with gr.Blocks(\n", " theme=gr.themes.Default(\n", " font=[gr.themes.GoogleFont(\"Inconsolata\"), \"Arial\", \"sans-serif\"]\n", " )\n", ") as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], 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/theme_extended_step_4/run.ipynb b/demo/theme_extended_step_4/run.ipynb index 7725ac32c9b0c..9ec1ce46b00f1 100644 --- a/demo/theme_extended_step_4/run.ipynb +++ b/demo/theme_extended_step_4/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_4"]}, {"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", "theme = gr.themes.Default(primary_hue=\"blue\").set(\n", " loader_color=\"#FF0000\",\n", " slider_color=\"#FF0000\",\n", ")\n", "\n", "with gr.Blocks(\n", " theme=theme\n", ") as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_extended_step_4"]}, {"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", "theme = gr.themes.Default(primary_hue=\"blue\").set(\n", " loader_color=\"#FF0000\",\n", " slider_color=\"#FF0000\",\n", ")\n", "\n", "with gr.Blocks(\n", " theme=theme\n", ") as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], 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/theme_new_step_1/run.ipynb b/demo/theme_new_step_1/run.ipynb index c2db9e0e44b0c..afea6a7d651cb 100644 --- a/demo/theme_new_step_1/run.ipynb +++ b/demo/theme_new_step_1/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_new_step_1"]}, {"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", "from gradio.themes.base import Base\n", "import time\n", "\n", "class Seafoam(Base):\n", " pass\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_new_step_1"]}, {"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", "from gradio.themes.base import Base\n", "import time\n", "\n", "class Seafoam(Base):\n", " pass\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], 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/theme_new_step_2/run.ipynb b/demo/theme_new_step_2/run.ipynb index b8d9a348a4d33..968d9294fbe8e 100644 --- a/demo/theme_new_step_2/run.ipynb +++ b/demo/theme_new_step_2/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_new_step_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": ["from __future__ import annotations\n", "from typing import Iterable\n", "import gradio as gr\n", "from gradio.themes.base import Base\n", "from gradio.themes.utils import colors, fonts, sizes\n", "import time\n", "\n", "\n", "class Seafoam(Base):\n", " def __init__(\n", " self,\n", " *,\n", " primary_hue: colors.Color | str = colors.emerald,\n", " secondary_hue: colors.Color | str = colors.blue,\n", " neutral_hue: colors.Color | str = colors.gray,\n", " spacing_size: sizes.Size | str = sizes.spacing_md,\n", " radius_size: sizes.Size | str = sizes.radius_md,\n", " text_size: sizes.Size | str = sizes.text_lg,\n", " font: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"Quicksand\"),\n", " \"ui-sans-serif\",\n", " \"sans-serif\",\n", " ),\n", " font_mono: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"IBM Plex Mono\"),\n", " \"ui-monospace\",\n", " \"monospace\",\n", " ),\n", " ):\n", " super().__init__(\n", " primary_hue=primary_hue,\n", " secondary_hue=secondary_hue,\n", " neutral_hue=neutral_hue,\n", " spacing_size=spacing_size,\n", " radius_size=radius_size,\n", " text_size=text_size,\n", " font=font,\n", " font_mono=font_mono,\n", " )\n", "\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_new_step_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": ["from __future__ import annotations\n", "from typing import Iterable\n", "import gradio as gr\n", "from gradio.themes.base import Base\n", "from gradio.themes.utils import colors, fonts, sizes\n", "import time\n", "\n", "\n", "class Seafoam(Base):\n", " def __init__(\n", " self,\n", " *,\n", " primary_hue: colors.Color | str = colors.emerald,\n", " secondary_hue: colors.Color | str = colors.blue,\n", " neutral_hue: colors.Color | str = colors.gray,\n", " spacing_size: sizes.Size | str = sizes.spacing_md,\n", " radius_size: sizes.Size | str = sizes.radius_md,\n", " text_size: sizes.Size | str = sizes.text_lg,\n", " font: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"Quicksand\"),\n", " \"ui-sans-serif\",\n", " \"sans-serif\",\n", " ),\n", " font_mono: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"IBM Plex Mono\"),\n", " \"ui-monospace\",\n", " \"monospace\",\n", " ),\n", " ):\n", " super().__init__(\n", " primary_hue=primary_hue,\n", " secondary_hue=secondary_hue,\n", " neutral_hue=neutral_hue,\n", " spacing_size=spacing_size,\n", " radius_size=radius_size,\n", " text_size=text_size,\n", " font=font,\n", " font_mono=font_mono,\n", " )\n", "\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], 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/theme_new_step_3/run.ipynb b/demo/theme_new_step_3/run.ipynb index a4bb5990d22c1..35d4b07f529c3 100644 --- a/demo/theme_new_step_3/run.ipynb +++ b/demo/theme_new_step_3/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_new_step_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": ["from __future__ import annotations\n", "from typing import Iterable\n", "import gradio as gr\n", "from gradio.themes.base import Base\n", "from gradio.themes.utils import colors, fonts, sizes\n", "import time\n", "\n", "\n", "class Seafoam(Base):\n", " def __init__(\n", " self,\n", " *,\n", " primary_hue: colors.Color | str = colors.emerald,\n", " secondary_hue: colors.Color | str = colors.blue,\n", " neutral_hue: colors.Color | str = colors.blue,\n", " spacing_size: sizes.Size | str = sizes.spacing_md,\n", " radius_size: sizes.Size | str = sizes.radius_md,\n", " text_size: sizes.Size | str = sizes.text_lg,\n", " font: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"Quicksand\"),\n", " \"ui-sans-serif\",\n", " \"sans-serif\",\n", " ),\n", " font_mono: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"IBM Plex Mono\"),\n", " \"ui-monospace\",\n", " \"monospace\",\n", " ),\n", " ):\n", " super().__init__(\n", " primary_hue=primary_hue,\n", " secondary_hue=secondary_hue,\n", " neutral_hue=neutral_hue,\n", " spacing_size=spacing_size,\n", " radius_size=radius_size,\n", " text_size=text_size,\n", " font=font,\n", " font_mono=font_mono,\n", " )\n", " super().set(\n", " body_background_fill=\"repeating-linear-gradient(45deg, *primary_200, *primary_200 10px, *primary_50 10px, *primary_50 20px)\",\n", " body_background_fill_dark=\"repeating-linear-gradient(45deg, *primary_800, *primary_800 10px, *primary_900 10px, *primary_900 20px)\",\n", " button_primary_background_fill=\"linear-gradient(90deg, *primary_300, *secondary_400)\",\n", " button_primary_background_fill_hover=\"linear-gradient(90deg, *primary_200, *secondary_300)\",\n", " button_primary_text_color=\"white\",\n", " button_primary_background_fill_dark=\"linear-gradient(90deg, *primary_600, *secondary_800)\",\n", " slider_color=\"*secondary_300\",\n", " slider_color_dark=\"*secondary_600\",\n", " block_title_text_weight=\"600\",\n", " block_border_width=\"3px\",\n", " block_shadow=\"*shadow_drop_lg\",\n", " button_shadow=\"*shadow_drop_lg\",\n", " button_large_padding=\"32px\",\n", " )\n", "\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_new_step_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": ["from __future__ import annotations\n", "from typing import Iterable\n", "import gradio as gr\n", "from gradio.themes.base import Base\n", "from gradio.themes.utils import colors, fonts, sizes\n", "import time\n", "\n", "\n", "class Seafoam(Base):\n", " def __init__(\n", " self,\n", " *,\n", " primary_hue: colors.Color | str = colors.emerald,\n", " secondary_hue: colors.Color | str = colors.blue,\n", " neutral_hue: colors.Color | str = colors.blue,\n", " spacing_size: sizes.Size | str = sizes.spacing_md,\n", " radius_size: sizes.Size | str = sizes.radius_md,\n", " text_size: sizes.Size | str = sizes.text_lg,\n", " font: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"Quicksand\"),\n", " \"ui-sans-serif\",\n", " \"sans-serif\",\n", " ),\n", " font_mono: fonts.Font\n", " | str\n", " | Iterable[fonts.Font | str] = (\n", " fonts.GoogleFont(\"IBM Plex Mono\"),\n", " \"ui-monospace\",\n", " \"monospace\",\n", " ),\n", " ):\n", " super().__init__(\n", " primary_hue=primary_hue,\n", " secondary_hue=secondary_hue,\n", " neutral_hue=neutral_hue,\n", " spacing_size=spacing_size,\n", " radius_size=radius_size,\n", " text_size=text_size,\n", " font=font,\n", " font_mono=font_mono,\n", " )\n", " super().set(\n", " body_background_fill=\"repeating-linear-gradient(45deg, *primary_200, *primary_200 10px, *primary_50 10px, *primary_50 20px)\",\n", " body_background_fill_dark=\"repeating-linear-gradient(45deg, *primary_800, *primary_800 10px, *primary_900 10px, *primary_900 20px)\",\n", " button_primary_background_fill=\"linear-gradient(90deg, *primary_300, *secondary_400)\",\n", " button_primary_background_fill_hover=\"linear-gradient(90deg, *primary_200, *secondary_300)\",\n", " button_primary_text_color=\"white\",\n", " button_primary_background_fill_dark=\"linear-gradient(90deg, *primary_600, *secondary_800)\",\n", " slider_color=\"*secondary_300\",\n", " slider_color_dark=\"*secondary_600\",\n", " block_title_text_weight=\"600\",\n", " block_border_width=\"3px\",\n", " block_shadow=\"*shadow_drop_lg\",\n", " button_shadow=\"*shadow_drop_lg\",\n", " button_large_padding=\"32px\",\n", " )\n", "\n", "\n", "seafoam = Seafoam()\n", "\n", "with gr.Blocks(theme=seafoam) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", "\n", " button.click(repeat, [textbox, slider], 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/theme_soft/run.ipynb b/demo/theme_soft/run.ipynb index 35b788bb8e98c..836f7cc595bc1 100644 --- a/demo/theme_soft/run.ipynb +++ b/demo/theme_soft/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: theme_soft"]}, {"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", "with gr.Blocks(theme=gr.themes.Soft()) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], output)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: theme_soft"]}, {"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", "with gr.Blocks(theme=gr.themes.Soft()) as demo:\n", " textbox = gr.Textbox(label=\"Name\")\n", " slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n", " with gr.Row():\n", " button = gr.Button(\"Submit\", variant=\"primary\")\n", " clear = gr.Button(\"Clear\")\n", " output = gr.Textbox(label=\"Output\")\n", "\n", " def repeat(name, count):\n", " time.sleep(3)\n", " return name * count\n", " \n", " button.click(repeat, [textbox, slider], 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/tictactoe/run.ipynb b/demo/tictactoe/run.ipynb index b49d781e315ab..045f1d9af2279 100644 --- a/demo/tictactoe/run.ipynb +++ b/demo/tictactoe/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: tictactoe"]}, {"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", " turn = gr.Textbox(\"X\", interactive=False, label=\"Turn\")\n", " board = gr.Dataframe(value=[[\"\", \"\", \"\"]] * 3, interactive=False, type=\"array\")\n", "\n", " def place(board, turn, evt: gr.SelectData):\n", " if evt.value:\n", " return board, turn\n", " board[evt.index[0]][evt.index[1]] = turn\n", " turn = \"O\" if turn == \"X\" else \"X\"\n", " return board, turn\n", "\n", " board.select(place, [board, turn], [board, turn])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: tictactoe"]}, {"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", " turn = gr.Textbox(\"X\", interactive=False, label=\"Turn\")\n", " board = gr.Dataframe(value=[[\"\", \"\", \"\"]] * 3, interactive=False, type=\"array\")\n", "\n", " def place(board, turn, evt: gr.SelectData):\n", " if evt.value:\n", " return board, turn\n", " board[evt.index[0]][evt.index[1]] = turn\n", " turn = \"O\" if turn == \"X\" else \"X\"\n", " return board, turn\n", "\n", " board.select(place, [board, turn], [board, turn])\n", "\n", "if __name__ == \"__main__\":\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 index c13b51c7de02f..38ed5d74e22f9 100644 --- a/demo/timeseries-forecasting-with-prophet/run.ipynb +++ b/demo/timeseries-forecasting-with-prophet/run.ipynb @@ -1 +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 holidays==0.24 prophet==1.1.2 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 +{"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 holidays==0.24 prophet==1.1.2 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/titanic_survival/run.ipynb b/demo/titanic_survival/run.ipynb index 90ad9cb9a353d..9a8daa489eb59 100644 --- a/demo/titanic_survival/run.ipynb +++ b/demo/titanic_survival/run.ipynb @@ -1 +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", " \"Fare\": [fare],\n", " \"Embarked\": [embark_point + 1],\n", " \"Company\": [\n", " (1 if \"Sibling\" in company else 0) + (2 if \"Child\" in company else 0)\n", " ]\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 +{"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", " \"Fare\": [fare],\n", " \"Embarked\": [embark_point + 1],\n", " \"Company\": [\n", " (1 if \"Sibling\" in company else 0) + (2 if \"Child\" in company else 0)\n", " ]\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 index 535508112caf5..1cc852cdf87bb 100644 --- a/demo/translation/run.ipynb +++ b/demo/translation/run.ipynb @@ -1 +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 +{"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/unified_demo_text_generation/run.ipynb b/demo/unified_demo_text_generation/run.ipynb index e3671d1c22b45..4fcd378db070d 100644 --- a/demo/unified_demo_text_generation/run.ipynb +++ b/demo/unified_demo_text_generation/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: unified_demo_text_generation"]}, {"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": ["import gradio as gr\n", "from transformers import pipeline\n", "\n", "generator = pipeline('text-generation', model = 'gpt2')\n", "\n", "def generate_text(text_prompt):\n", " response = generator(text_prompt, max_length = 30, num_return_sequences=5)\n", " return response[0]['generated_text']\n", "\n", "textbox = gr.Textbox()\n", "\n", "demo = gr.Interface(generate_text, textbox, textbox)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: unified_demo_text_generation"]}, {"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": ["import gradio as gr\n", "from transformers import pipeline\n", "\n", "generator = pipeline('text-generation', model = 'gpt2')\n", "\n", "def generate_text(text_prompt):\n", " response = generator(text_prompt, max_length = 30, num_return_sequences=5)\n", " return response[0]['generated_text']\n", "\n", "textbox = gr.Textbox()\n", "\n", "demo = gr.Interface(generate_text, textbox, textbox)\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/unispeech-speaker-verification/run.ipynb b/demo/unispeech-speaker-verification/run.ipynb index f150284881d3e..e338b7a7755cb 100644 --- a/demo/unispeech-speaker-verification/run.ipynb +++ b/demo/unispeech-speaker-verification/run.ipynb @@ -1 +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", "\n", "\"\"\"\n", "OUTPUT_OK = (\n", " STYLE\n", " + \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

Welcome, human!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", " STYLE\n", " + \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

You shall not pass!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\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 'ERROR: Please record audio for *both* speakers!'\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", " \"

\"\n", " \"\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT | \"\n", " \"\ud83d\udcda UniSpeech-SAT paper | \"\n", " \"\ud83d\udcda X-Vector paper\"\n", " \"

\"\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", " 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 +{"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", "\n", "\"\"\"\n", "OUTPUT_OK = (\n", " STYLE\n", " + \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

Welcome, human!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\n", "\"\"\"\n", ")\n", "OUTPUT_FAIL = (\n", " STYLE\n", " + \"\"\"\n", "
\n", "

The speakers are

\n", "

{:.1f}%

\n", "

similar

\n", "

You shall not pass!

\n", "
(You must get at least 85% to be considered the same person)
\n", "
\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 'ERROR: Please record audio for *both* speakers!'\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", " \"

\"\n", " \"\ud83c\udf99\ufe0f Learn more about UniSpeech-SAT | \"\n", " \"\ud83d\udcda UniSpeech-SAT paper | \"\n", " \"\ud83d\udcda X-Vector paper\"\n", " \"

\"\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", " 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/upload_button/run.ipynb b/demo/upload_button/run.ipynb index 7acd21453f3da..d8cdaea6ac840 100644 --- a/demo/upload_button/run.ipynb +++ b/demo/upload_button/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: upload_button\n", "### A simple demo showcasing the upload button used with its `upload` event trigger.\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 upload_file(files):\n", " file_paths = [file.name for file in files]\n", " return file_paths\n", "\n", "with gr.Blocks() as demo:\n", " file_output = gr.File()\n", " upload_button = gr.UploadButton(\"Click to Upload a File\", file_types=[\"image\", \"video\"], file_count=\"multiple\")\n", " upload_button.upload(upload_file, upload_button, file_output)\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: upload_button\n", "### A simple demo showcasing the upload button used with its `upload` event trigger.\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 upload_file(files):\n", " file_paths = [file.name for file in files]\n", " return file_paths\n", "\n", "with gr.Blocks() as demo:\n", " file_output = gr.File()\n", " upload_button = gr.UploadButton(\"Click to Upload a File\", file_types=[\"image\", \"video\"], file_count=\"multiple\")\n", " upload_button.upload(upload_file, upload_button, file_output)\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/uploadbutton_component/run.ipynb b/demo/uploadbutton_component/run.ipynb index e6fcc8e5d1ff6..55dee4d996783 100644 --- a/demo/uploadbutton_component/run.ipynb +++ b/demo/uploadbutton_component/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: uploadbutton_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", "def upload_file(files):\n", " file_paths = [file.name for file in files]\n", " return file_paths\n", "\n", "with gr.Blocks() as demo:\n", " file_output = gr.File()\n", " upload_button = gr.UploadButton(\"Click to Upload an Image or Video File\", file_types=[\"image\", \"video\"], file_count=\"multiple\")\n", " upload_button.upload(upload_file, upload_button, file_output)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: uploadbutton_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", "def upload_file(files):\n", " file_paths = [file.name for file in files]\n", " return file_paths\n", "\n", "with gr.Blocks() as demo:\n", " file_output = gr.File()\n", " upload_button = gr.UploadButton(\"Click to Upload an Image or Video File\", file_types=[\"image\", \"video\"], file_count=\"multiple\")\n", " upload_button.upload(upload_file, upload_button, file_output)\n", "\n", "demo.launch()"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file diff --git a/demo/variable_outputs/run.ipynb b/demo/variable_outputs/run.ipynb index 578fdf9314ccf..7ebbe92b2ba6a 100644 --- a/demo/variable_outputs/run.ipynb +++ b/demo/variable_outputs/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: variable_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", "max_textboxes = 10\n", "\n", "def variable_outputs(k):\n", " k = int(k)\n", " return [gr.Textbox(visible=True)]*k + [gr.Textbox(visible=False)]*(max_textboxes-k)\n", "\n", "with gr.Blocks() as demo:\n", " s = gr.Slider(1, max_textboxes, value=max_textboxes, step=1, label=\"How many textboxes to show:\")\n", " textboxes = []\n", " for i in range(max_textboxes):\n", " t = gr.Textbox(f\"Textbox {i}\")\n", " textboxes.append(t)\n", "\n", " s.change(variable_outputs, s, textboxes)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: variable_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", "max_textboxes = 10\n", "\n", "def variable_outputs(k):\n", " k = int(k)\n", " return [gr.Textbox(visible=True)]*k + [gr.Textbox(visible=False)]*(max_textboxes-k)\n", "\n", "with gr.Blocks() as demo:\n", " s = gr.Slider(1, max_textboxes, value=max_textboxes, step=1, label=\"How many textboxes to show:\")\n", " textboxes = []\n", " for i in range(max_textboxes):\n", " t = gr.Textbox(f\"Textbox {i}\")\n", " textboxes.append(t)\n", "\n", " s.change(variable_outputs, s, textboxes)\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/video_component/run.ipynb b/demo/video_component/run.ipynb index c755938a6028a..4e4bccc3eaacf 100644 --- a/demo/video_component/run.ipynb +++ b/demo/video_component/run.ipynb @@ -1 +1,5 @@ -{"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": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/a.mp4\n", "!wget -q -O files/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/b.mp4\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "a = os.path.join(os.path.abspath(''), \"files/world.mp4\") # Video\n", "b = os.path.join(os.path.abspath(''), \"files/a.mp4\") # Video\n", "c = os.path.join(os.path.abspath(''), \"files/b.mp4\") # Video\n", "\n", "\n", "demo = gr.Interface(\n", " fn=lambda x: x,\n", " inputs=gr.Video(type=\"file\"),\n", " outputs=gr.Video(),\n", " examples=[\n", " [a],\n", " [b],\n", " [c],\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 +<<<<<<< HEAD +{"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": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/a.mp4\n", "!wget -q -O files/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/b.mp4\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "a = os.path.join(os.path.abspath(''), \"files/world.mp4\") # Video\n", "b = os.path.join(os.path.abspath(''), \"files/a.mp4\") # Video\n", "c = os.path.join(os.path.abspath(''), \"files/b.mp4\") # Video\n", "\n", "\n", "demo = gr.Interface(\n", " fn=lambda x: x,\n", " inputs=gr.Video(type=\"file\"),\n", " outputs=gr.Video(),\n", " examples=[\n", " [a],\n", " [b],\n", " [c],\n", " ],\n", " cache_examples=True\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +======= +{"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": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/a.mp4\n", "!wget -q -O files/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/b.mp4\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "\n", "a = os.path.join(os.path.abspath(''), \"files/world.mp4\") # Video\n", "b = os.path.join(os.path.abspath(''), \"files/a.mp4\") # Video\n", "c = os.path.join(os.path.abspath(''), \"files/b.mp4\") # Video\n", "\n", "\n", "demo = gr.Interface(\n", " fn=lambda x: x,\n", " inputs=gr.Video(type=\"file\"),\n", " outputs=gr.Video(),\n", " examples=[\n", " [a],\n", " [b],\n", " [c],\n", " ],\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} +>>>>>>> main diff --git a/demo/video_identity/run.ipynb b/demo/video_identity/run.ipynb index 19b4d287be16f..2cbc57bda2df2 100644 --- a/demo/video_identity/run.ipynb +++ b/demo/video_identity/run.ipynb @@ -1 +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 +{"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/video_subtitle/run.ipynb b/demo/video_subtitle/run.ipynb index 6aa2d0dde03e2..ea6f1959bfb18 100644 --- a/demo/video_subtitle/run.ipynb +++ b/demo/video_subtitle/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: video_subtitle"]}, {"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/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/a.mp4\n", "!wget -q -O files/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/b.mp4\n", "!wget -q -O files/s1.srt https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/s1.srt\n", "!wget -q -O files/s2.vtt https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/s2.vtt"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "a = os.path.join(os.path.abspath(''), \"files/a.mp4\") # Video\n", "b = os.path.join(os.path.abspath(''), \"files/b.mp4\") # Video\n", "s1 = os.path.join(os.path.abspath(''), \"files/s1.srt\") # Subtitle\n", "s2 = os.path.join(os.path.abspath(''), \"files/s2.vtt\") # Subtitle\n", "\n", "\n", "def video_demo(video, subtitle=None):\n", " if subtitle is None:\n", " return video\n", "\n", " return [video, subtitle.name]\n", "\n", "\n", "demo = gr.Interface(\n", " fn=video_demo,\n", " inputs=[\n", " gr.Video(type=\"file\", label=\"In\", interactive=True),\n", " gr.File(label=\"Subtitle\", file_types=[\".srt\", \".vtt\"]),\n", " ],\n", " outputs=gr.Video(label=\"Out\"),\n", " examples=[\n", " [a, s1],\n", " [b, s2],\n", " [a, None],\n", " ],\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: video_subtitle"]}, {"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/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/a.mp4\n", "!wget -q -O files/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/b.mp4\n", "!wget -q -O files/s1.srt https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/s1.srt\n", "!wget -q -O files/s2.vtt https://github.com/gradio-app/gradio/raw/main/demo/video_subtitle/files/s2.vtt"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "\n", "a = os.path.join(os.path.abspath(''), \"files/a.mp4\") # Video\n", "b = os.path.join(os.path.abspath(''), \"files/b.mp4\") # Video\n", "s1 = os.path.join(os.path.abspath(''), \"files/s1.srt\") # Subtitle\n", "s2 = os.path.join(os.path.abspath(''), \"files/s2.vtt\") # Subtitle\n", "\n", "\n", "def video_demo(video, subtitle=None):\n", " if subtitle is None:\n", " return video\n", "\n", " return [video, subtitle.name]\n", "\n", "\n", "demo = gr.Interface(\n", " fn=video_demo,\n", " inputs=[\n", " gr.Video(type=\"file\", label=\"In\", interactive=True),\n", " gr.File(label=\"Subtitle\", file_types=[\".srt\", \".vtt\"]),\n", " ],\n", " outputs=gr.Video(label=\"Out\"),\n", " examples=[\n", " [a, s1],\n", " [b, s2],\n", " [a, None],\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/waveform/run.ipynb b/demo/waveform/run.ipynb index 4da46e83bc908..123780c6ddaa0 100644 --- a/demo/waveform/run.ipynb +++ b/demo/waveform/run.ipynb @@ -1 +1 @@ -{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: waveform"]}, {"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", "\n", "COLORS = [\n", " [\"#ff0000\", \"#00ff00\"],\n", " [\"#00ff00\", \"#0000ff\"],\n", " [\"#0000ff\", \"#ff0000\"],\n", "] \n", "\n", "def audio_waveform(audio, image):\n", " return (\n", " audio,\n", " gr.make_waveform(audio),\n", " gr.make_waveform(audio, animate=True),\n", " gr.make_waveform(audio, bg_image=image, bars_color=random.choice(COLORS)),\n", " )\n", "\n", "\n", "gr.Interface(\n", " audio_waveform,\n", " inputs=[gr.Audio(), gr.Image(type=\"filepath\")],\n", " outputs=[\n", " gr.Audio(),\n", " gr.Video(),\n", " gr.Video(),\n", " gr.Video(),\n", " ],\n", ").launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: waveform"]}, {"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", "\n", "COLORS = [\n", " [\"#ff0000\", \"#00ff00\"],\n", " [\"#00ff00\", \"#0000ff\"],\n", " [\"#0000ff\", \"#ff0000\"],\n", "] \n", "\n", "def audio_waveform(audio, image):\n", " return (\n", " audio,\n", " gr.make_waveform(audio),\n", " gr.make_waveform(audio, animate=True),\n", " gr.make_waveform(audio, bg_image=image, bars_color=random.choice(COLORS)),\n", " )\n", "\n", "\n", "gr.Interface(\n", " audio_waveform,\n", " inputs=[gr.Audio(), gr.Image(type=\"filepath\")],\n", " outputs=[\n", " gr.Audio(),\n", " gr.Video(),\n", " gr.Video(),\n", " gr.Video(),\n", " ],\n", ").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 index cb32f0c5cf10e..cfc657b72bb6f 100644 --- a/demo/webcam/run.ipynb +++ b/demo/webcam/run.ipynb @@ -1 +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": ["\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 +{"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": ["\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 index 69139bcbc9ff2..8a76dde6ced72 100644 --- a/demo/white_noise_vid_not_playable/run.ipynb +++ b/demo/white_noise_vid_not_playable/run.ipynb @@ -1 +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 +{"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 index 2d0a707ad6fa3..e1093d6867ec1 100644 --- a/demo/xgboost-income-prediction-with-explainability/run.ipynb +++ b/demo/xgboost-income-prediction-with-explainability/run.ipynb @@ -1 +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 numpy==1.23.2 matplotlib shap xgboost==1.7.6 pandas datasets"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\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", "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 +{"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 numpy==1.23.2 matplotlib shap xgboost==1.7.6 pandas datasets"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\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", "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 index 21810513c773e..a2732e7f190d2 100644 --- a/demo/zip_files/run.ipynb +++ b/demo/zip_files/run.ipynb @@ -1 +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.name.split(\"/\")[-1])\n", " return \"tmp.zip\"\n", "\n", "demo = gr.Interface(\n", " zip_files,\n", " gr.File(file_count=\"multiple\", file_types=[\"text\", \".json\", \".csv\"]),\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 +{"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.name.split(\"/\")[-1])\n", " return \"tmp.zip\"\n", "\n", "demo = gr.Interface(\n", " zip_files,\n", " gr.File(file_count=\"multiple\", file_types=[\"text\", \".json\", \".csv\"]),\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 index 0928b97b52932..02230b11ed8ae 100644 --- a/demo/zip_to_json/run.ipynb +++ b/demo/zip_to_json/run.ipynb @@ -1 +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 +{"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/gradio/CHANGELOG.md b/gradio/CHANGELOG.md index bc1703db27c5b..78bc3a913fbff 100644 --- a/gradio/CHANGELOG.md +++ b/gradio/CHANGELOG.md @@ -113,8 +113,6 @@ For more information check the [`FileExplorer` documentation](https://gradio.app ### Fixes - [#5625](https://github.com/gradio-app/gradio/pull/5625) [`9ccc4794a`](https://github.com/gradio-app/gradio/commit/9ccc4794a72ce8319417119f6c370e7af3ffca6d) - Use ContextVar instead of threading.local(). Thanks [@cbensimon](https://github.com/cbensimon)! -<<<<<<< HEAD -<<<<<<< HEAD - [#5636](https://github.com/gradio-app/gradio/pull/5636) [`fb5964fb8`](https://github.com/gradio-app/gradio/commit/fb5964fb88082e7b956853b543c468116811cab9) - Fix bug in example cache loading event. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! - [#5633](https://github.com/gradio-app/gradio/pull/5633) [`341402337`](https://github.com/gradio-app/gradio/commit/34140233794c29d4722020e13c2d045da642dfae) - Allow Gradio apps containing `gr.Radio()`, `gr.Checkboxgroup()`, or `gr.Dropdown()` to be loaded with `gr.load()`. Thanks [@abidlabs](https://github.com/abidlabs)! - [#5593](https://github.com/gradio-app/gradio/pull/5593) [`88d43bd12`](https://github.com/gradio-app/gradio/commit/88d43bd124792d216da445adef932a2b02f5f416) - Fixes avatar image in chatbot being squashed. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)! diff --git a/gradio/blocks.py b/gradio/blocks.py index 3ed8143247e90..2759dd6041796 100644 --- a/gradio/blocks.py +++ b/gradio/blocks.py @@ -201,14 +201,6 @@ def get_config(self): def update(**kwargs) -> dict: return {} - @classmethod - def get_specific_update(cls, generic_update: dict[str, Any]) -> dict: - generic_update = generic_update.copy() - del generic_update["__type__"] - specific_update = cls.update(**generic_update) - specific_update = utils.delete_none(specific_update, skip_value=True) - return specific_update - class BlockContext(Block): def __init__( @@ -340,16 +332,13 @@ def postprocess_update_dict( ): """ Converts a dictionary of updates into a format that can be sent to the frontend. - E.g. {"__type__": "generic_update", "value": "2", "interactive": False} + E.g. {"__type__": "update", "value": "2", "interactive": False} Into -> {"__type__": "update", "value": 2.0, "mode": "static"} - Parameters: block: The Block that is being updated with this update dictionary. update_dict: The original update dictionary postprocess: Whether to postprocess the "value" key of the update dictionary. """ - if update_dict.get("__type__", "") == "generic_update": - update_dict = block.get_specific_update(update_dict) if update_dict.get("value") is components._Keywords.NO_VALUE: update_dict.pop("value") interactive = update_dict.pop("interactive", None) @@ -1322,7 +1311,6 @@ def postprocess_data( args["_skip_init_processing"] = not block_fn.postprocess state[output_id] = self.blocks[output_id].__class__(**args) - assert isinstance(prediction_value, dict) prediction_value = postprocess_update_dict( block=state[output_id], update_dict=prediction_value, diff --git a/gradio/components/code.py b/gradio/components/code.py index e0d7e2e920124..3bd90f38ebd91 100644 --- a/gradio/components/code.py +++ b/gradio/components/code.py @@ -19,7 +19,7 @@ class Code(Component): """ Creates a Code editor for entering, editing or viewing code. Preprocessing: passes a {str} of code into the function. - Postprocessing: expects the function to return a {str} of code or a single-elment {tuple}: (string filepath,) + Postprocessing: expects the function to return a {str} of code or a single-element {tuple}: {(string_filepath,)} """ languages = [ diff --git a/gradio/components/file.py b/gradio/components/file.py index d54de10471f7d..577e8c11e4c39 100644 --- a/gradio/components/file.py +++ b/gradio/components/file.py @@ -26,7 +26,7 @@ class ListFiles(GradioRootModel): class File(Component): """ Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output). - Preprocessing: passes the uploaded file as a {tempfile._TemporaryFileWrapper} or {List[tempfile._TemporaryFileWrapper]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`) + Preprocessing: passes the uploaded file as a {tempfile._TemporaryFileWrapper} or {List[tempfile._TemporaryFileWrapper]} depending on `file_count` (or a {bytes}/{List[bytes]} depending on `type`) Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files. Examples-format: a {str} path to a local file that populates the component. Demos: zip_to_json, zip_files diff --git a/gradio/components/upload_button.py b/gradio/components/upload_button.py index e682b360a5811..27eb6a78474ee 100644 --- a/gradio/components/upload_button.py +++ b/gradio/components/upload_button.py @@ -25,7 +25,7 @@ class ListFiles(GradioRootModel): class UploadButton(Component): """ Used to create an upload button, when clicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set). - Preprocessing: passes the uploaded file as a {file-object} or {List[file-object]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`) + Preprocessing: passes the uploaded file as a {file-object} or {List[file-object]} depending on `file_count` (or a {bytes}/{List[bytes]} depending on `type`) Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files. Examples-format: a {str} path to a local file that populates the component. Demos: upload_button diff --git a/gradio/helpers.py b/gradio/helpers.py index 98af6c9134ae7..893a789260f7f 100644 --- a/gradio/helpers.py +++ b/gradio/helpers.py @@ -793,53 +793,40 @@ def special_args( return inputs or [], progress_index, event_data_index -def update(**kwargs) -> dict: +def update( + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + visible: bool | None = None, + **kwargs, +) -> dict: """ - DEPRECATED. Updates component properties. When a function passed into a Gradio Interface or a Blocks events returns a typical value, it updates the value of the output component. But it is also possible to update the properties of an output component (such as the number of lines of a `Textbox` or the visibility of an `Image`) by returning the component's `update()` function, which takes as parameters any of the constructor parameters for that component. - This is a shorthand for using the update method on a component. - For example, rather than using gr.Number.update(...) you can just use gr.update(...). - Note that your editor's autocompletion will suggest proper parameters - if you use the update method on the component. - Demos: blocks_essay, blocks_update, blocks_essay_update + Updates a component's properties. When a function passed into a Gradio Interface or a Blocks events returns a value, it typically updates the value of the output component. But it is also possible to update the *properties* of an output component (such as the number of lines of a `Textbox` or the visibility of an `Row`) by returning a component and passing in the parameters to update in the constructor of the component. Alternatively, you can return `gr.update(...)` with any arbitrary parameters to update. (This is useful as a shorthand or if the same function can be called with different components to update.) Parameters: - kwargs: Key-word arguments used to update the component's properties. + elem_id: Use this to update the id of the component in the HTML DOM + elem_classes: Use this to update the classes of the component in the HTML DOM + visible: Use this to update the visibility of the component + kwargs: Any other keyword arguments to update the component's properties. Example: - # Blocks Example import gradio as gr with gr.Blocks() as demo: radio = gr.Radio([1, 2, 4], label="Set the value of the number") number = gr.Number(value=2, interactive=True) radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number) demo.launch() - - # Interface example - import gradio as gr - def change_textbox(choice): - if choice == "short": - return gr.Textbox.update(lines=2, visible=True) - elif choice == "long": - return gr.Textbox.update(lines=8, visible=True) - else: - return gr.Textbox.update(visible=False) - gr.Interface( - change_textbox, - gr.Radio( - ["short", "long", "none"], label="What kind of essay would you like to write?" - ), - gr.Textbox(lines=2), - live=True, - ).launch() """ - warnings.warn( - "Using the update method is deprecated. Simply return a new object instead, e.g. `return gr.Textbox(...)` instead of `return gr.update(...)" - ) - kwargs["__type__"] = "generic_update" + kwargs["__type__"] = "update" + if elem_id is not None: + kwargs["elem_id"] = elem_id + if elem_classes is not None: + kwargs["elem_classes"] = elem_classes + if visible is not None: + kwargs["visible"] = visible return kwargs def skip() -> dict: - return {"__type__": "generic_update"} + return {"__type__": "update"} @document() diff --git a/gradio/interface.py b/gradio/interface.py index 33fd981a01e6d..1681b75d56204 100644 --- a/gradio/interface.py +++ b/gradio/interface.py @@ -590,7 +590,7 @@ def attach_submit_events(self, submit_btn: Button | None, stop_btn: Button | Non for component in self.input_components: if component.has_event("stream") and component.streaming: # type: ignore events.append(component.stream) # type: ignore - elif Events.change in component.events: + elif component.has_event("change"): events.append(component.change) # type: ignore on( events, diff --git a/gradio/themes/utils/fonts.py b/gradio/themes/utils/fonts.py index d51dbbfdf4990..5525c2c4d5809 100644 --- a/gradio/themes/utils/fonts.py +++ b/gradio/themes/utils/fonts.py @@ -40,6 +40,12 @@ def stylesheet(self) -> str: def __eq__(self, other: Font) -> bool: return self.name == other.name and self.stylesheet() == other.stylesheet() + def __repr__(self) -> str: + klass = type(self) + class_repr = klass.__module__ + "." + klass.__qualname__ + attrs = ", ".join([k + "=" + repr(v) for k, v in self.__dict__.items()]) + return f"<{class_repr} ({attrs})>" + class GoogleFont(Font): def __init__(self, name: str, weights: Iterable[int] = (400, 600)): diff --git a/js/_website/package.json b/js/_website/package.json index befa29c86bcf9..9a54327cc2a6d 100644 --- a/js/_website/package.json +++ b/js/_website/package.json @@ -1,6 +1,6 @@ { "name": "website", - "version": "0.6.1-beta.0", + "version": "0.7.1", "private": true, "scripts": { "dev": "python generate_jsons/generate.py && vite dev", diff --git a/js/accordion/CHANGELOG.md b/js/accordion/CHANGELOG.md index 3c3a99c4be040..745638beec6c4 100644 --- a/js/accordion/CHANGELOG.md +++ b/js/accordion/CHANGELOG.md @@ -13,28 +13,6 @@ ### Patch Changes - Updated dependencies []: - - @gradio/atoms@0.2.0-beta.2 - - @gradio/statustracker@0.3.0-beta.3 - -## 0.1.0-beta.2 - -### Features - -- [#5620](https://github.com/gradio-app/gradio/pull/5620) [`c4c25ecdf`](https://github.com/gradio-app/gradio/commit/c4c25ecdf8c2fab5e3c41b519564e3b6a9ebfce3) - fix build and broken imports. Thanks [@pngwn](https://github.com/pngwn)! - -## 0.1.0-beta.1 - -### Patch Changes - -- Updated dependencies []: - - @gradio/atoms@0.2.0-beta.1 - - @gradio/statustracker@0.3.0-beta.1 - -## 0.1.0-beta.0 - -### Features - -- [#5507](https://github.com/gradio-app/gradio/pull/5507) [`1385dc688`](https://github.com/gradio-app/gradio/commit/1385dc6881f2d8ae7a41106ec21d33e2ef04d6a9) - Custom components. Thanks [@pngwn](https://github.com/pngwn)! - @gradio/atoms@0.1.3 - @gradio/statustracker@0.2.1 diff --git a/js/checkbox/CHANGELOG.md b/js/checkbox/CHANGELOG.md index bfa31f2c916cd..ad83c76ec97e6 100644 --- a/js/checkbox/CHANGELOG.md +++ b/js/checkbox/CHANGELOG.md @@ -23,7 +23,6 @@ - [#5554](https://github.com/gradio-app/gradio/pull/5554) [`75ddeb390`](https://github.com/gradio-app/gradio/commit/75ddeb390d665d4484667390a97442081b49a423) - Accessibility Improvements. Thanks [@hannahblair](https://github.com/hannahblair)! - ## 0.1.3 ### Patch Changes diff --git a/js/gallery/static/Gallery.svelte b/js/gallery/static/Gallery.svelte index aedc48073bb4a..c1731d80b7489 100644 --- a/js/gallery/static/Gallery.svelte +++ b/js/gallery/static/Gallery.svelte @@ -466,4 +466,4 @@ .icon-buttons a { margin: var(--size-1) 0; } - + \ No newline at end of file diff --git a/js/markdown/CHANGELOG.md b/js/markdown/CHANGELOG.md index d5161b38cae12..91950049707f6 100644 --- a/js/markdown/CHANGELOG.md +++ b/js/markdown/CHANGELOG.md @@ -76,3 +76,4 @@ Thanks [@pngwn](https://github.com/pngwn)! ### Features - [#5268](https://github.com/gradio-app/gradio/pull/5268) [`f49028cf`](https://github.com/gradio-app/gradio/commit/f49028cfe3e21097001ddbda71c560b3d8b42e1c) - Move markdown & latex processing to the frontend for the gr.Markdown and gr.DataFrame components. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#5215](https://github.com/gradio-app/gradio/pull/5215) [`fbdad78a`](https://github.com/gradio-app/gradio/commit/fbdad78af4c47454cbb570f88cc14bf4479bbceb) - Lazy load interactive or static variants of a component individually, rather than loading both variants regardless. This change will improve performance for many applications. Thanks [@pngwn](https://github.com/pngwn)! diff --git a/js/markdown/static/MarkdownCode.svelte b/js/markdown/static/MarkdownCode.svelte index 2b29962bf3b2b..8a563e23365b5 100644 --- a/js/markdown/static/MarkdownCode.svelte +++ b/js/markdown/static/MarkdownCode.svelte @@ -119,4 +119,7 @@ span:not(.chatbot) :global(ol) { list-style-position: inside; } + span :global(p:not(:first-child)) { + margin-top: var(--spacing-xxl); + } diff --git a/js/wasm/src/webworker/index.ts b/js/wasm/src/webworker/index.ts index 43d9af3b29d97..11b5af346c2be 100644 --- a/js/wasm/src/webworker/index.ts +++ b/js/wasm/src/webworker/index.ts @@ -311,6 +311,7 @@ self.onmessage = async (event: MessageEvent): Promise => { }; messagePort.postMessage(replyMessage); }); + break; } } } catch (error) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a52fdfbdc1f4c..c202c945d8840 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6645,7 +6645,7 @@ packages: peerDependencies: '@sveltejs/kit': ^1.0.0 dependencies: - '@sveltejs/kit': 1.16.3(svelte@3.59.2)(vite@4.3.9) + '@sveltejs/kit': 1.16.3(svelte@3.57.0)(vite@4.3.5) import-meta-resolve: 3.0.0 dev: true diff --git a/sweep.yaml b/sweep.yaml deleted file mode 100644 index 31603692a35ad..0000000000000 --- a/sweep.yaml +++ /dev/null @@ -1,2 +0,0 @@ -# Reference: https://github.com/sweepai/sweep/blob/main/sweep.yaml -branch: main diff --git a/test/test_blocks.py b/test/test_blocks.py index effd4d837f4bf..cbd5d9ba88137 100644 --- a/test/test_blocks.py +++ b/test/test_blocks.py @@ -1152,54 +1152,7 @@ def batch_fn(x, y): await demo.process_api(0, [["A", "B", "C"], ["D", "E"]], state=None) -class TestSpecificUpdate: - def test_without_update(self): - with pytest.raises(KeyError): - gr.Textbox.get_specific_update({"lines": 4}) - - def test_with_update(self): - specific_update = gr.Textbox.get_specific_update( - {"lines": 4, "__type__": "update", "interactive": False} - ) - assert specific_update == { - "lines": 4, - "value": gr.components._Keywords.NO_VALUE, - "interactive": False, - "__type__": "update", - } - - specific_update = gr.Textbox.get_specific_update( - {"lines": 4, "__type__": "update", "interactive": True} - ) - assert specific_update == { - "lines": 4, - "value": gr.components._Keywords.NO_VALUE, - "interactive": True, - "__type__": "update", - } - - def test_with_generic_update(self): - specific_update = gr.Video.get_specific_update( - { - "visible": True, - "value": "test.mp4", - "__type__": "generic_update", - "interactive": True, - "container": None, - "height": None, - "min_width": None, - "scale": None, - "width": None, - "show_share_button": None, - } - ) - assert specific_update == { - "visible": True, - "value": "test.mp4", - "interactive": True, - "__type__": "update", - } - +class TestUpdate: @pytest.mark.asyncio async def test_accordion_update(self): with gr.Blocks() as demo: