<meta charset="utf-8" /><meta http-equiv="content-security-policy" content=""><meta name="hf:doc:metadata" content="{&quot;local&quot;:&quot;&quot;,&quot;sections&quot;:[{&quot;local&quot;:null,&quot;sections&quot;:[{&quot;local&quot;:&quot;gradio&quot;,&quot;title&quot;:&quot;打磨你的 Gradio 演示:&quot;},{&quot;local&quot;:&quot;&quot;,&quot;title&quot;:&quot;使用临时链接分享您的演示&quot;},{&quot;local&quot;:&quot;hugging-face-spaces&quot;,&quot;title&quot;:&quot;在 Hugging Face Spaces 上托管您的演示&quot;}],&quot;title&quot;:null},{&quot;local&quot;:&quot;&quot;,&quot;title&quot;:&quot;✏️ 让我们应用它!&quot;}],&quot;title&quot;:&quot;与他人分享演示&quot;}" data-svelte="svelte-1phssyn">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/assets/pages/__layout.svelte-hf-doc-builder.css">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/start-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/vendor-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/paths-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/pages/__layout.svelte-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/pages/chapter9/4.mdx-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/Youtube-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/IconCopyLink-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/CodeBlock-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/course/pr_362/zh-CN/_app/chunks/DocNotebookDropdown-hf-doc-builder.js"> 





<h1 id="">与他人分享演示</h1>


<div class="flex space-x-1 absolute z-10 right-0 top-0">
	<a href="https://colab.research.google.com/github/huggingface/notebooks/blob/master/course/chapter9/section4.ipynb" target="_blank"><img alt="Open In Colab" class="!m-0" src="https://colab.research.google.com/assets/colab-badge.svg"></a>
	<a href="https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/master/course/chapter9/section4.ipynb" target="_blank"><img alt="Open In Studio Lab" class="!m-0" src="https://studiolab.sagemaker.aws/studiolab.svg"></a></div>
<p>现在您已经构建了一个演示，您可能希望与其他人分享它。 梯度演示
可以通过两种方式共享：使用 <strong><em>temporary share link</em></strong> 或 <strong><em>permanent hosting on Spaces</em></strong>。</p>
<p>我们将很快介绍这两种方法。 但在分享演示之前，您可能需要完善它 💅.</p>
<h3 class="relative group"><a id="gradio" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#gradio"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>打磨你的 Gradio 演示:
	</span></h3>

<div class="flex justify-center"><img class="block dark:hidden" src="https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter9/gradio-demo-overview.png" alt="Overview of a gradio interface">
<img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter9/gradio-demo-overview-dark.png" alt="Overview of a gradio interface"></div>
<p>为了给你的演示添加额外的内容，<code>Interface</code> 类支持一些可选参数：</p>
<ul><li><code>title</code>：你可以给你的演示一个标题，它出现在输入和输出组件的上方。</li>
<li><code>description</code>：您可以为界面提供描述（文本、Markdown 或 HTML），显示在输入和输出组件的上方和标题下方。</li>
<li><code>article</code>：您还可以编写扩展文章（文本、Markdown 或 HTML）来解释界面。如果提供，它会出现在输入和输出组件的_下方。</li>
<li><code>theme</code>：不喜欢默认颜色？将主题设置为使用 <code>default</code>、<code>huggingface</code>、<code>grass</code>、<code>peach</code> 之一。您还可以添加 <code>dark-</code> 前缀，例如<code>dark-peach</code> 用于深色主题（或者只是 <code>dark</code> 用于默认的深色主题）。</li>
<li><code>examples</code>：为了让您的演示<em>更易于使用</em>，您可以为函数提供一些示例输入。它们出现在 UI 组件下方，可用于填充界面。这些应该作为嵌套列表提供，其中外部列表​​由样本组成，每个内部列表对应于每个输入组件的输入组成。</li>
<li><code>live</code>：如果你想让你的演示“活”，这意味着你的模型每次输入更改时都会重新运行，你可以设置 <code>live=True</code>。这对使用快速模型很有意义（我们将在本节末尾看到一个示例）
使用上面的选项，我们最终得到了一个更完整的界面。 运行下面的代码，以便与 Rick and Morty 聊天：</li></ul>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->title = <span class="hljs-string">&quot;Ask Rick a Question&quot;</span>
description = <span class="hljs-string">&quot;&quot;&quot;
The bot was trained to answer questions based on Rick and Morty dialogues. Ask Rick anything!
&lt;img src=&quot;https://huggingface.co/spaces/course-demos/Rick_and_Morty_QA/resolve/main/rick.png&quot; width=200px&gt;
&quot;&quot;&quot;</span>

article = <span class="hljs-string">&quot;Check out [the original Rick and Morty Bot](https://huggingface.co/spaces/kingabzpro/Rick_and_Morty_Bot) that this demo is based off of.&quot;</span>

gr.Interface(
    fn=predict,
    inputs=<span class="hljs-string">&quot;textbox&quot;</span>,
    outputs=<span class="hljs-string">&quot;text&quot;</span>,
    title=title,
    description=description,
    article=article,
    examples=[[<span class="hljs-string">&quot;What are you doing?&quot;</span>], [<span class="hljs-string">&quot;Where should we time travel to?&quot;</span>]],
).launch()<!-- HTML_TAG_END --></pre></div>
<p>使用上面的选项，我们最终得到了一个更完整的界面。 试试下面的界面：</p>
<iframe src="https://hf.space/gradioiframe/course-demos/Rick_and_Morty_QA/+" frameborder="0" height="800" title="Gradio app" class="container p-0 flex-grow space-iframe" allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-downloads"></iframe>
<h3 id="">使用临时链接分享您的演示</h3>
现在我们已经有了机器学习模型的工作演示，让我们学习如何轻松共享指向我们界面的链接。
通过在 `launch()` 方法中设置 `share=True` 可以轻松地公开共享接口：

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->gr.Interface(classify_image, <span class="hljs-string">&quot;image&quot;</span>, <span class="hljs-string">&quot;label&quot;</span>).launch(share=<span class="hljs-literal">True</span>)<!-- HTML_TAG_END --></pre></div>
<p>这会生成一个公开的、可共享的链接，您可以将其发送给任何人！ 当您发送此链接时，另一方的用户可以在浏览器中试用该模型长达 72 小时。 因为处理发生在您的设备上（只要您的设备保持开启！），您不必担心打包任何依赖项。 如果您使用 Google Colab 笔记本工作，则始终会自动创建共享链接。 它通常看起来像这样：<strong>XXXXX.gradio.app</strong>。 虽然链接是通过 Gradio 链接提供的，但我们只是您本地服务器的代理，不会存储通过接口发送的任何数据。</p>
<p>但是请记住，这些链接是可公开访问的，这意味着任何人都可以使用您的模型进行预测！ 因此，请确保不要通过您编写的函数公开任何敏感信息，或允许在您的设备上发生任何关键更改。 如果设置 <code>share=False</code>（默认值），则仅创建本地链接。</p>
<h3 class="relative group"><a id="hugging-face-spaces" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#hugging-face-spaces"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>在 Hugging Face Spaces 上托管您的演示
	</span></h3>

<p>可以传递给同事的共享链接很酷，但是如何永久托管您的演示并让它存在于互联网上自己的“空间”中？</p>
<p>Hugging Face Spaces 提供了在互联网上永久托管 Gradio 模型的基础设施，<strong>免费</strong>！ Spaces 允许您创建并推送到（公共或私人）存储库，
你的 Gradio 在哪里
接口代码将存在于 <code>app.py</code> 文件中。 <a href="https://huggingface.co/blog/gradio-spaces" rel="nofollow">阅读分步教程</a> 开始使用，或观看下面的示例视频。</p>
<iframe class="w-full xl:w-4/6 h-80" src="https://www.youtube-nocookie.com/embed/LS9Y2wDVI0k" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<h2 id="">✏️ 让我们应用它!</h2>
<p>使用到目前为止我们在各节中学到的知识，让我们创建我们在<a href="/course/chapter9/1">本章第一节</a>中看到的草图识别演示。 让我们为我们的界面添加一些自定义并设置 <code>share=True</code> 以创建一个我们可以传递的公共链接。</p>
<p>我们可以从 <a href="https://huggingface.co/spaces/dawood/Sketch-Recognition/blob/main/class_names.txt" rel="nofollow">class_names.txt</a> 加载标签，并从 <a href="https://huggingface.co/spaces/dawood/Sketch-Recognition/blob/main/pytorch_model.bin" rel="nofollow">pytorch_model.bin</a>加载预训练的 pytorch 模型 。 通过点击链接并单击文件预览左上角的下载来下载这些文件。 让我们看看下面的代码，看看我们如何使用这些文件来加载我们的模型并创建一个<code>predict()</code>函数：</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr
<span class="hljs-keyword">from</span> torch <span class="hljs-keyword">import</span> nn

LABELS = Path(<span class="hljs-string">&quot;class_names.txt&quot;</span>).read_text().splitlines()

model = nn.Sequential(
    nn.Conv2d(<span class="hljs-number">1</span>, <span class="hljs-number">32</span>, <span class="hljs-number">3</span>, padding=<span class="hljs-string">&quot;same&quot;</span>),
    nn.ReLU(),
    nn.MaxPool2d(<span class="hljs-number">2</span>),
    nn.Conv2d(<span class="hljs-number">32</span>, <span class="hljs-number">64</span>, <span class="hljs-number">3</span>, padding=<span class="hljs-string">&quot;same&quot;</span>),
    nn.ReLU(),
    nn.MaxPool2d(<span class="hljs-number">2</span>),
    nn.Conv2d(<span class="hljs-number">64</span>, <span class="hljs-number">128</span>, <span class="hljs-number">3</span>, padding=<span class="hljs-string">&quot;same&quot;</span>),
    nn.ReLU(),
    nn.MaxPool2d(<span class="hljs-number">2</span>),
    nn.Flatten(),
    nn.Linear(<span class="hljs-number">1152</span>, <span class="hljs-number">256</span>),
    nn.ReLU(),
    nn.Linear(<span class="hljs-number">256</span>, <span class="hljs-built_in">len</span>(LABELS)),
)
state_dict = torch.load(<span class="hljs-string">&quot;pytorch_model.bin&quot;</span>, map_location=<span class="hljs-string">&quot;cpu&quot;</span>)
model.load_state_dict(state_dict, strict=<span class="hljs-literal">False</span>)
model.<span class="hljs-built_in">eval</span>()


<span class="hljs-keyword">def</span> <span class="hljs-title function_">predict</span>(<span class="hljs-params">im</span>):
    x = torch.tensor(im, dtype=torch.float32).unsqueeze(<span class="hljs-number">0</span>).unsqueeze(<span class="hljs-number">0</span>) / <span class="hljs-number">255.0</span>
    <span class="hljs-keyword">with</span> torch.no_grad():
        out = model(x)
    probabilities = torch.nn.functional.softmax(out[<span class="hljs-number">0</span>], dim=<span class="hljs-number">0</span>)
    values, indices = torch.topk(probabilities, <span class="hljs-number">5</span>)
    <span class="hljs-keyword">return</span> {LABELS[i]: v.item() <span class="hljs-keyword">for</span> i, v <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(indices, values)}<!-- HTML_TAG_END --></pre></div>
<p>现在我们有了一个<code>predict()</code>函数。 下一步是定义并启动我们的渐变界面：</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->interface = gr.Interface(
    predict,
    inputs=<span class="hljs-string">&quot;sketchpad&quot;</span>,
    outputs=<span class="hljs-string">&quot;label&quot;</span>,
    theme=<span class="hljs-string">&quot;huggingface&quot;</span>,
    title=<span class="hljs-string">&quot;Sketch Recognition&quot;</span>,
    description=<span class="hljs-string">&quot;Who wants to play Pictionary? Draw a common object like a shovel or a laptop, and the algorithm will guess in real time!&quot;</span>,
    article=<span class="hljs-string">&quot;&lt;p style=&#x27;text-align: center&#x27;&gt;Sketch Recognition | Demo Model&lt;/p&gt;&quot;</span>,
    live=<span class="hljs-literal">True</span>,
)
interface.launch(share=<span class="hljs-literal">True</span>)<!-- HTML_TAG_END --></pre></div>
<iframe src="https://hf.space/gradioiframe/course-demos/Sketch-Recognition/+" frameborder="0" height="650" title="Gradio app" class="container p-0 flex-grow space-iframe" allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-downloads"></iframe>
<p>注意 <code>Interface</code> 中的 <code>live=True</code> 参数，这意味着草图演示使
每次有人在画板上画画时的预测（没有提交按钮！）。</p>
<p>此外，我们还在 <code>launch()</code> 方法中设置了 <code>share=True</code> 参数。
这将创建一个公共链接，您可以发送给任何人！ 当您发送此链接时，对方的用户可以尝试草图识别模型。 重申一下，您还可以在 Hugging Face Spaces 上托管模型，这就是我们能够嵌入上面的演示的方式。</p>
<p>接下来，我们将介绍 Gradio 可用于 Hugging Face 生态系统的其他方式！</p>


		<script type="module" data-hydrate="i0cksg">
		import { start } from "/docs/course/pr_362/zh-CN/_app/start-hf-doc-builder.js";
		start({
			target: document.querySelector('[data-hydrate="i0cksg"]').parentNode,
			paths: {"base":"/docs/course/pr_362/zh-CN","assets":"/docs/course/pr_362/zh-CN"},
			session: {},
			route: false,
			spa: false,
			trailing_slash: "never",
			hydrate: {
				status: 200,
				error: null,
				nodes: [
					import("/docs/course/pr_362/zh-CN/_app/pages/__layout.svelte-hf-doc-builder.js"),
						import("/docs/course/pr_362/zh-CN/_app/pages/chapter9/4.mdx-hf-doc-builder.js")
				],
				params: {}
			}
		});
	</script>
