<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;:&quot;&quot;,&quot;title&quot;:&quot;如何创建接口&quot;},{&quot;local&quot;:&quot;&quot;,&quot;title&quot;:&quot;一个带音频的简单示例&quot;},{&quot;local&quot;:&quot;&quot;,&quot;sections&quot;:[{&quot;local&quot;:&quot;launch&quot;,&quot;title&quot;:&quot;`launch()` 方法&quot;}],&quot;title&quot;:&quot;处理多个输入和输出&quot;},{&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/3.mdx-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/section3.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/section3.ipynb" target="_blank"><img alt="Open In Studio Lab" class="!m-0" src="https://studiolab.sagemaker.aws/studiolab.svg"></a></div>
<p>在本节中，我们将仔细研究 <code>Interface</code> 类，并了解用于创建其的主要参数。</p>
<h2 id="">如何创建接口</h2>
<p>您会注意到 <code>Interface</code> 类有 3 个必需参数：</p>
<p><code>Interface(fn, inputs, outputs, ...)</code></p>
<p>这些参数是：</p>
<ul><li><code>fn</code>: 由 Gradio 接口包装的预测函数。 该函数可以接受一个或多个参数并返回一个或多个值</li>
<li><code>inputs</code>: 输入组件类型。 Gradio 提供了许多预构建的组件，例如<code>&quot;image&quot;</code> 或<code>&quot;mic&quot;</code>。</li>
<li><code>outputs</code>: 输出组件类型。 同样，Gradio 提供了许多预构建的组件，例如 <code>“图像”</code>或“标签”`。</li></ul>
<p>有关组件的完整列表，<a href="https://gradio.app/docs" rel="nofollow">请参阅 Gradio 文档</a>。 每个预构建的组件都可以通过实例化该组件对应的类来定制。</p>
<p>例如，正如我们在 <a href="/course/chapter9/2">上一节</a> 中看到的，您可以传入一个 <code>Textbox(lines=7, label=&quot;Prompt&quot;)</code> 组件来创建一个包含 7 行和一个标签的文本框，而不是将 <code>&quot;textbox&quot;</code> 传递给 <code>inputs</code> 参数。
让我们看另一个例子，这次是一个 <code>Audio</code> 组件。</p>
<h2 id="">一个带音频的简单示例</h2>
<p>如前所述，Gradio 提供了许多不同的输入和输出。
因此，让我们构建一个适用于音频的“接口”。</p>
<p>在这个例子中，我们将构建一个音频到音频的函数，它需要一个音频文件并简单地反转它。</p>
<p>我们将使用 <code>Audio</code> 组件作为输入。 使用 <code>Audio</code> 组件时，您可以指定希望音频的 <code>source</code> 是用户上传的文件还是用户录制声音的麦克风。 在这种情况下，让我们将其设置为“麦克风”。 只是为了好玩，我们会在我们的“音频”中添加一个标签，上面写着“在这里说话……”。</p>
<p>此外，我们希望将音频作为 numpy 数组接收，以便我们可以轻松地“反转”它。 所以我们将 <code>&quot;type&quot;</code> 设置为 <code>&quot;numpy&quot;</code>，它会传递输入data 作为 (<code>sample_rate</code>, <code>data</code>) 的元组进入我们的函数。</p>
<p>我们还将使用 <code>Audio</code> 输出组件，它可以自动将具有采样率和 numpy 数据数组的元组渲染为可播放的音频文件。 在这种情况下，我们不需要进行任何自定义，因此我们将使用字符串快捷方式“audio”。</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">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr


<span class="hljs-keyword">def</span> <span class="hljs-title function_">reverse_audio</span>(<span class="hljs-params">audio</span>):
    sr, data = audio
    reversed_audio = (sr, np.flipud(data))
    <span class="hljs-keyword">return</span> reversed_audio


mic = gr.Audio(source=<span class="hljs-string">&quot;microphone&quot;</span>, <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;numpy&quot;</span>, label=<span class="hljs-string">&quot;Speak here...&quot;</span>)
gr.Interface(reverse_audio, mic, <span class="hljs-string">&quot;audio&quot;</span>).launch()<!-- HTML_TAG_END --></pre></div>
<p>上面的代码会产生一个类似下面的界面（如果你的浏览器没有
询问您的麦克风权限， <a href="https://huggingface.co/spaces/course-demos/audio-reverse" target="_blank">open the demo in  a separate tab</a>.)</p>
<iframe src="https://hf.space/gradioiframe/course-demos/audio-reverse/+" frameborder="0" height="250" 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>您现在应该能够录制自己的声音并听到自己在反向说话 - 怪异 👻!</p>
<h2 id="">处理多个输入和输出</h2>
<p>假设我们有一个更复杂的函数，有多个输入和输出。在下面的示例中，我们有一个接受下拉索引、滑块值和数字的函数，并返回一个音调的音频样本。</p>
<p>看看我们如何传递输入和输出组件列表，看看你能不能跟上正在发生的事情。</p>
<p>这里的关键是当你通过时：</p>
<ul><li>输入组件列表，每个组件依次对应一个参数。</li>
<li>输出组件列表，每个组件对应一个返回值。</li></ul>
<p>下面的代码片段显示了三个输入组件如何与 <code>generate_tone()</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">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr

notes = [<span class="hljs-string">&quot;C&quot;</span>, <span class="hljs-string">&quot;C#&quot;</span>, <span class="hljs-string">&quot;D&quot;</span>, <span class="hljs-string">&quot;D#&quot;</span>, <span class="hljs-string">&quot;E&quot;</span>, <span class="hljs-string">&quot;F&quot;</span>, <span class="hljs-string">&quot;F#&quot;</span>, <span class="hljs-string">&quot;G&quot;</span>, <span class="hljs-string">&quot;G#&quot;</span>, <span class="hljs-string">&quot;A&quot;</span>, <span class="hljs-string">&quot;A#&quot;</span>, <span class="hljs-string">&quot;B&quot;</span>]


<span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_tone</span>(<span class="hljs-params">note, octave, duration</span>):
    sr = <span class="hljs-number">48000</span>
    a4_freq, tones_from_a4 = <span class="hljs-number">440</span>, <span class="hljs-number">12</span> * (octave - <span class="hljs-number">4</span>) + (note - <span class="hljs-number">9</span>)
    frequency = a4_freq * <span class="hljs-number">2</span> ** (tones_from_a4 / <span class="hljs-number">12</span>)
    duration = <span class="hljs-built_in">int</span>(duration)
    audio = np.linspace(<span class="hljs-number">0</span>, duration, duration * sr)
    audio = (<span class="hljs-number">20000</span> * np.sin(audio * (<span class="hljs-number">2</span> * np.pi * frequency))).astype(np.int16)
    <span class="hljs-keyword">return</span> (sr, audio)


gr.Interface(
    generate_tone,
    [
        gr.Dropdown(notes, <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;index&quot;</span>),
        gr.Slider(minimum=<span class="hljs-number">4</span>, maximum=<span class="hljs-number">6</span>, step=<span class="hljs-number">1</span>),
        gr.Textbox(<span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;number&quot;</span>, value=<span class="hljs-number">1</span>, label=<span class="hljs-string">&quot;Duration in seconds&quot;</span>),
    ],
    <span class="hljs-string">&quot;audio&quot;</span>,
).launch()<!-- HTML_TAG_END --></pre></div>
<iframe src="https://hf.space/gradioiframe/course-demos/generate-tone/+" frameborder="0" height="450" 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 class="relative group"><a id="launch" 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="#launch"><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><code>launch()</code> 方法
	</span></h3>

<p>到目前为止，我们已经使用了<code>launch()</code>方法来启动界面，但是我们
还没有真正讨论过它的作用。</p>
<p>默认情况下，<code>launch()</code> 方法将在 Web 服务器中启动演示正在本地运行。 如果您在 Jupyter 或 Colab 笔记本中运行代码，那么Gradio 会将演示 GUI 嵌入到笔记本中，以便您轻松使用它。</p>
<p>您可以通过不同的参数自定义 <code>launch()</code> 的行为：</p>
<ul><li><code>inline</code> - whether to display the interface inline on Python notebooks.</li>
<li><code>inbrowser</code> - whether to automatically launch the interface in a new tab on the default browser.</li>
<li><code>share</code> - whether to create a publicly shareable link from your computer for the interface. Kind of like a Google Drive link!</li></ul>
<p>我们将在下一节中更详细地介绍 <code>share</code> 参数！</p>
<h2 id="">✏️ 让我们应用它！</h2>
<p>让我们构建一个界面，让您演示 <strong>speech-recognition</strong> 模型。
为了让它变得有趣，我们将接受 <em>or</em> 麦克风输入或上传的文件。</p>
<p>像往常一样，我们将使用 🤗 Transformers 中的 <code>pipeline()</code> 函数加载我们的语音识别模型。如果您需要快速复习，您可以返回 <a href="/course/chapter1/3">第 1 章中的那个部分</a>。 接下来，我们将实现一个 <code>transcribe_audio()</code> 函数来处理音频并返回转录。 最后，我们将把这个函数包装在一个 <code>Interface</code> 中，其中 <code>Audio</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> transformers <span class="hljs-keyword">import</span> pipeline
<span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr

model = pipeline(<span class="hljs-string">&quot;automatic-speech-recognition&quot;</span>)


<span class="hljs-keyword">def</span> <span class="hljs-title function_">transcribe_audio</span>(<span class="hljs-params">mic=<span class="hljs-literal">None</span>, file=<span class="hljs-literal">None</span></span>):
    <span class="hljs-keyword">if</span> mic <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        audio = mic
    <span class="hljs-keyword">elif</span> file <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        audio = file
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;You must either provide a mic recording or a file&quot;</span>
    transcription = model(audio)[<span class="hljs-string">&quot;text&quot;</span>]
    <span class="hljs-keyword">return</span> transcription


gr.Interface(
    fn=transcribe_audio,
    inputs=[
        gr.Audio(source=<span class="hljs-string">&quot;microphone&quot;</span>, <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;filepath&quot;</span>, optional=<span class="hljs-literal">True</span>),
        gr.Audio(source=<span class="hljs-string">&quot;upload&quot;</span>, <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;filepath&quot;</span>, optional=<span class="hljs-literal">True</span>),
    ],
    outputs=<span class="hljs-string">&quot;text&quot;</span>,
).launch()<!-- HTML_TAG_END --></pre></div>
<p>如果您的浏览器没有要求您提供麦克风权限，<a href="https://huggingface.co/spaces/course-demos/audio-reverse" target="_blank">open the demo in a separate tab</a>.</p>
<iframe src="https://hf.space/gradioiframe/course-demos/asr/+" frameborder="0" height="550" 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>optional</code> 参数作为 <code>True</code> 传递，我们允许用户
提供麦克风或音频文件（或两者都不提供，但这会返回错误消息）。</p>
<p>继续看看如何与他人分享您的界面！</p>


		<script type="module" data-hydrate="vfqj3g">
		import { start } from "/docs/course/pr_362/zh-CN/_app/start-hf-doc-builder.js";
		start({
			target: document.querySelector('[data-hydrate="vfqj3g"]').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/3.mdx-hf-doc-builder.js")
				],
				params: {}
			}
		});
	</script>
