開源 AI 食譜文件
使用 Spaces 和 Gradio 建立演示
並獲得增強的文件體驗
開始使用
使用 Spaces 和 Gradio 建立演示
引言
在本筆記本中,我們將演示如何使用 Gradio 將任何機器學習模型變為現實,Gradio 是一個允許您從任何 Python 函式建立 Web 演示並與世界 🌎 分享的庫!
📚 本筆記本涵蓋
- 構建一個
Hello, World!
演示:Gradio 的基礎知識 - 將您的演示移動到 Hugging Face Spaces
- 使其有趣:一個利用 🤗 Hub 的真實世界示例
- Gradio 附帶的一些很酷的“內建”功能
⏭️ 在本筆記本的末尾,您將找到一個 延伸閱讀
列表,其中包含您可以繼續學習的連結。
設定
首先安裝 gradio
庫以及 transformers
。
!pip -q install gradio==4.36.1
!pip -q install transformers==4.41.2
# the usual shorthand is to import gradio as gr
import gradio as gr
您的第一個演示:Gradio 的基礎知識
Gradio 的核心是將任何 Python 函式轉換為 Web 介面。
假設我們有一個簡單的函式,它以 name
和 intensity
作為引數,並返回一個字串,如下所示:
def greet(name: str, intensity: int) -> str:
return "Hello, " + name + "!" * int(intensity)
如果您為名稱“Diego”執行此函式,您將獲得如下所示的輸出字串:
>>> print(greet("Diego", 3))
Hello, Diego!!!
使用 Gradio,我們可以透過 gr.Interface
類為該函式構建一個介面。我們只需要傳入上面建立的 greet
函式,以及我們函式期望的輸入和輸出型別。
demo = gr.Interface(
fn=greet,
inputs=["text", "slider"], # the inputs are a text box and a slider ("text" and "slider" are components in Gradio)
outputs=["text"], # the output is a text box
)
請注意,我們傳入 ["text", "slider"]
作為輸入,["text"]
作為輸出 — 這些在 Gradio 中稱為 元件。
這就是我們第一個演示所需的一切。繼續嘗試吧 👇🏼!在 name
文字框中輸入您的名字,滑動您想要的強度,然後點選 Submit
。
# the launch method will fire up the interface we just created
demo.launch()
讓我們更有趣一點:一個會議轉錄工具
至此,您已經瞭解瞭如何將一個基本的 Python 函式轉換為一個可用於網路的演示。然而,我們只為非常簡單的函式做到了這一點,甚至有點無聊!
讓我們考慮一個更有趣的例子,它突出了 Gradio 的構建目的:演示尖端機器學習模型。我的一位好朋友最近請我幫忙處理她做的一次採訪的錄音。她需要將音訊檔案轉換為一個組織良好的文字摘要。我是如何幫助她的?我構建了一個 Gradio 應用程式!
讓我們逐步構建會議轉錄工具。我們可以將這個過程分為兩部分:
- 將音訊檔案轉錄成文字
- 將文字組織成章節、段落、列表等。我們也可以在這裡加入摘要功能。
音訊到文字
在這一部分中,我們將構建一個演示,處理會議轉錄工具的第一步:將音訊轉換為文字。
正如我們所知,構建 Gradio 演示的關鍵在於擁有一個執行我們想要展示邏輯的 Python 函式。對於音訊到文字轉換,我們將使用出色的 transformers
庫及其 pipeline
工具來構建我們的函式,以使用一個流行的音訊到文字模型,名為 distil-whisper/distil-large-v3
。
結果是以下 transcribe
函式,它將我們想要轉換的音訊作為輸入:
import os
import tempfile
import torch
import gradio as gr
from transformers import pipeline
device = 0 if torch.cuda.is_available() else "cpu"
AUDIO_MODEL_NAME = (
"distil-whisper/distil-large-v3" # faster and very close in performance to the full-size "openai/whisper-large-v3"
)
BATCH_SIZE = 8
pipe = pipeline(
task="automatic-speech-recognition",
model=AUDIO_MODEL_NAME,
chunk_length_s=30,
device=device,
)
def transcribe(audio_input):
"""Function to convert audio to text."""
if audio_input is None:
raise gr.Error("No audio file submitted!")
output = pipe(audio_input, batch_size=BATCH_SIZE, generate_kwargs={"task": "transcribe"}, return_timestamps=True)
return output["text"]
現在我們有了 Python 函式,我們可以透過將其傳入 gr.Interface
來演示。請注意,在這種情況下,函式期望的輸入是我們想要轉換的音訊。Gradio 包含大量有用的元件,其中之一是 Audio,這正是我們演示所需要的 🎶 😎。
part_1_demo = gr.Interface(
fn=transcribe,
inputs=gr.Audio(type="filepath"), # "filepath" passes a str path to a temporary file containing the audio
outputs=gr.Textbox(show_copy_button=True), # give users the option to copy the results
title="Transcribe Audio to Text", # give our demo a title :)
)
part_1_demo.launch()
來試試看吧 👆!您可以上傳一個 .mp3
檔案,或者點選 🎤 按鈕錄製您自己的聲音。
對於包含實際會議錄音的示例檔案,您可以檢視 MeetingBank_Audio 資料集,這是一個包含美國六個主要城市市議會會議的資料集。為了我自己的測試,我嘗試了一些 丹佛會議。
另請檢視 Interface
的 from_pipeline 建構函式,它將直接從 pipeline
構建 Interface
。
組織和總結文字
對於會議轉錄工具的第二部分,我們需要組織上一步中轉錄的文字。
再次強調,為了構建 Gradio 演示,我們需要包含我們所需邏輯的 Python 函式。對於文字組織和摘要,我們將使用一個“指令調優”模型,該模型經過訓練可以執行廣泛的任務。有許多選項可供選擇,例如 meta-llama/Meta-Llama-3-8B-Instruct 或 mistralai/Mistral-7B-Instruct-v0.3。在我們的示例中,我們將使用 microsoft/Phi-3-mini-4k-instruct。
就像第一部分一樣,我們可以利用 transformers
中的 pipeline
工具來完成此操作,但我們將藉此機會展示 無伺服器推理 API,這是 Hugging Face Hub 中的一個 API,它允許我們 免費 使用數千個公開可訪問(或您自己的私有許可權)的機器學習模型!在此處檢視無伺服器推理 API 的 cookbook 部分:此處。
使用無伺服器推理 API 意味著我們不再透過管道呼叫模型(就像我們在音訊轉換部分所做的那樣),而是從 InferenceClient
呼叫它,後者是 huggingface_hub
庫(Hub Python 庫)的一部分。反過來,要使用 InferenceClient
,我們需要使用 notebook_login()
登入 🤗 Hub,這將彈出一個對話方塊,要求您提供使用者訪問令牌以向 Hub 進行身份驗證。
您可以從您的個人設定頁面管理您的令牌,並且請記住儘可能使用細粒度令牌以增強安全性。
from huggingface_hub import notebook_login, InferenceClient
# running this will prompt you to enter your Hugging Face credentials
notebook_login()
現在我們已經登入到 Hub,我們可以使用 Serverless Inference API 透過 InferenceClient
編寫文字處理函式。
此部分的程式碼將分為兩個函式:
build_messages
,用於將訊息提示格式化為 LLM;organize_text
,用於實際將原始會議文字傳入 LLM 進行組織(和摘要,取決於我們提供的提示)。
# sample meeting transcript from huuuyeah/MeetingBank_Audio
# this is just a copy-paste from the output of part 1 using one of the Denver meetings
sample_transcript = """
Good evening. Welcome to the Denver City Council meeting of Monday, May 8, 2017. My name is Kelly Velez. I'm your Council Secretary. According to our rules of procedure, when our Council President, Albus Brooks, and Council President Pro Tem, JoLynn Clark, are both absent, the Council Secretary calls the meeting to order. Please rise and join Councilman Herndon in the Pledge of Allegiance. Madam Secretary, roll call. Roll call. Here. Mark. Espinosa. Here. Platt. Delmar. Here. Here. Here. Here. We have five members present. There is not a quorum this evening. Many of the council members are participating in an urban exploration trip in Portland, Oregon, pursuant to Section 3.3.4 of the city charter. Because there is not a quorum of seven council members present, all of tonight's business will move to next week, to Monday, May 15th. Seeing no other business before this body except to wish Councilwoman Keniche a very happy birthday this meeting is adjourned Thank you. A standard model and an energy efficient model likely will be returned to you in energy savings many times during its lifespan. Now, what size do you need? Air conditioners are not a one-size-or-type fits all. Before you buy an air conditioner, you need to consider the size of your home and the cost to operate the unit per hour. Do you want a room air conditioner, which costs less but cools a smaller area, or do you want a central air conditioner, which cools your entire house but costs more? Do your homework. Now, let's discuss evaporative coolers. In low humidity areas, evaporating water into the air provides a natural and energy efficient means of cooling. Evaporative coolers, also called swamp coolers, cool outdoor air by passing it over water saturated pads, causing the water to evaporate into it. Evaporative coolers cost about one half as much to install as central air conditioners and use about one-quarter as much energy. However, they require more frequent maintenance than refrigerated air conditioners, and they're suitable only for areas with low humidity. Watch the maintenance tips at the end of this segment to learn more. And finally, fans. When air moves around in your home, it creates a wind chill effect. A mere two-mile-an-hour breeze will make your home feel four degrees cooler and therefore you can set your thermostat a bit higher. Ceiling fans and portable oscillating fans are cheap to run and they make your house feel cooler. You can also install a whole house fan to draw the hot air out of your home. A whole house fan draws cool outdoor air inside through open windows and exhausts hot room air through the attic to the outside. The result is excellent ventilation, lower indoor temperatures, and improved evaporative cooling. But remember, there are many low-cost, no-cost ways that you can keep your home cool. You should focus on these long before you turn on your AC or even before you purchase an AC. But if you are going to purchase a new cooling system, remember to get one that's energy efficient and the correct size for your home. Wait, wait, don't go away, there's more. After this segment of the presentation is over, you're going to be given the option to view maintenance tips about air conditioners and evaporative coolers. Now all of these tips are brought to you by the people at Xcel Energy. Thanks for watching.
"""
from huggingface_hub import InferenceClient
TEXT_MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
client = InferenceClient()
def organize_text(meeting_transcript):
messages = build_messages(meeting_transcript)
response = client.chat_completion(messages, model=TEXT_MODEL_NAME, max_tokens=250, seed=430)
return response.choices[0].message.content
def build_messages(meeting_transcript) -> list:
system_input = "You are an assitant that organizes meeting minutes."
user_input = """Take this raw meeting transcript and return an organized version.
Here is the transcript:
{meeting_transcript}
""".format(
meeting_transcript=meeting_transcript
)
messages = [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
]
return messages
現在我們有了文字組織函式 organize_text
,我們也可以為它構建一個演示。
part_2_demo = gr.Interface(
fn=organize_text,
inputs=gr.Textbox(value=sample_transcript),
outputs=gr.Textbox(show_copy_button=True),
title="Clean Up Transcript Text",
)
part_2_demo.launch()
來試試看吧 👆!如果您點選上面演示中的“Submit”,您會看到輸出文字是會議記錄的更清晰、更有組織的版本,帶有標題和不同部分的章節。
嘗試透過調整控制 LLM 提示的 user_input
變數來獲取摘要。
整合所有功能
至此,我們已經為會議轉錄工具的兩個步驟分別建立了函式:
- 將音訊轉換為文字檔案,以及
- 將文字檔案整理成格式良好的會議文件。
接下來,我們所要做的就是將這兩個函式連線起來,併為組合步驟構建一個演示。換句話說,我們完整的會議轉錄工具只是一個新函式(我們將其巧妙地命名為 meeting_transcript_tool
😀),它接受 transcribe
的輸出並將其傳遞給 organize_text
。
def meeting_transcript_tool(audio_input):
meeting_text = transcribe(audio_input)
organized_text = organize_text(meeting_text)
return organized_text
full_demo = gr.Interface(
fn=meeting_transcript_tool,
inputs=gr.Audio(type="filepath"),
outputs=gr.Textbox(show_copy_button=True),
title="The Complete Meeting Transcription Tool",
)
full_demo.launch()
來試試看吧 👆!現在這是我們轉錄工具的完整演示。如果您給它一個音訊檔案,輸出將是已經組織好的(可能已摘要的)會議版本。太酷了 😎。
將您的演示移動到 🤗 Spaces
如果您走到這一步,現在您已經瞭解瞭如何使用 Gradio 建立機器學習模型演示的基礎知識👏!
接下來,我們將向您展示如何將您的全新演示帶到 Hugging Face Spaces。除了 Gradio 易於使用和功能強大之外,將您的演示移至 🤗 Spaces 還為您帶來了永久託管、每次更新應用程式時輕鬆部署以及與任何人分享您的工作的好處!請記住,除非您正在使用它或對其進行更改,否則您的 Space 將在一段時間後進入休眠狀態。
第一步是前往 https://huggingface.co/new-space,從模板中選擇“Gradio”,暫時保留其他選項為預設值(您稍後可以更改這些選項)。

這將導致建立一個新的 Space,您可以用您的演示程式碼填充它。為了讓您跟隨示例,我建立了 🤗 Space dmaniloff/meeting-transcript-tool
,您可以在此處訪問。
我們需要編輯兩個檔案:
app.py
— 這是演示程式碼所在的位置。它應該看起來像這樣:# outline of app.py: def meeting_transcript_tool(...): ... def transcribe(...): ... def organize_text(...): ...
requirements.txt
— 這是我們告訴 Space 需要哪些庫的地方。它應該看起來像這樣:# contents of requirements.txt: torch transformers
Gradio 自帶電池 🔋
Gradio 開箱即用,自帶許多酷炫功能。在本筆記本中我們無法涵蓋所有功能,但這裡有 3 個我們將要介紹的:
- 作為 API 訪問
- 透過公共 URL 共享
- 標記
作為 API 訪問
使用 Gradio 構建 Web 演示的好處之一是您會自動獲得一個 API 🙌!這意味著您可以使用標準 HTTP 客戶端(如 curl
或 Python requests
庫)訪問 Python 函式的功能。
如果您仔細檢視我們上面建立的演示,您會發現底部有一個名為“透過 API 使用”的連結。如果您點選我建立的 Space 中的該連結(dmaniloff/meeting-transcript-tool),您將看到以下內容:

讓我們複製程式碼到下面,將我們的 Space 作為 API 使用:
!pip install gradio_client
>>> from gradio_client import Client, handle_file
>>> client = Client("dmaniloff/meeting-transcript-tool")
>>> result = client.predict(
... audio_input=handle_file("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav"),
... api_name="/predict",
... )
>>> print(result)
Loaded as API: https://dmaniloff-meeting-transcript-tool.hf.space ✔ Certainly! Below is an organized version of a hypothetical meeting transcript. Since the original transcript you've provided is quite minimal, I'll create a more detailed and structured example featuring a meeting summary. --- # Meeting Transcript: Project Alpha Kickoff **Date:** April 7, 2023 **Location:** Conference Room B, TechCorp Headquarters **Attendees:** - John Smith (Project Manager) - Emily Johnson (Lead Developer) - Michael Brown (Marketing Lead) - Lisa Green (Design Lead) **Meeting Duration:** 1 hour 30 minutes ## Opening Remarks **John Smith:** Good morning everyone, and thank you for joining this kickoff meeting for Project Alpha. Today, we'll discuss our project vision, milestones, and roles. Let's get started. ## Vision and Goals **Emily Johnson:** The main goal of Project Alpha is to
哇!那裡發生了什麼?我們來分解一下:
- 我們安裝了
gradio_client
,這是一個專門設計用於與使用 Gradio 構建的 API 互動的包。 - 我們透過提供我們想要查詢的 🤗 Space 的名稱來例項化客戶端。
- 我們呼叫了客戶端的
predict
方法,並將一個示例音訊檔案傳遞給它。
Gradio 客戶端負責為我們進行 HTTP POST 請求,它還提供了諸如讀取會議轉錄工具將處理的輸入音訊檔案(透過 handle_file
函式)之類的功能。
再次強調,使用此客戶端是一種選擇,您也可以執行 curl -X POST https://dmaniloff-meeting-transcript-tool.hf.space/call/predict [...]
並傳入請求中所需的所有引數。
我們從上面的呼叫中得到的輸出是一個虛構的會議,由我們用於文字組織的 LLM 生成。這是因為示例輸入檔案不是實際的會議錄音。您可以調整 LLM 的提示以處理這種情況。
透過公共 URL 共享
Gradio 中內建的另一個很酷的功能是,即使您在本地計算機上構建演示(在將其移動到 🤗 Space 之前),您仍然可以透過將 share=True
傳入 launch
來與世界上任何人共享它,如下所示:
demo.launch(share=True)
您可能已經注意到,在此 Google Colab 環境中,預設情況下已啟用此行為,因此我們之前建立的演示已經擁有一個可共享的公共 URL 🌎。返回⬆並檢視 Running on public URL:
的日誌以找到它 🔎!
標記
標記是 Gradio 內建的一項功能,允許您的演示使用者提供反饋。您可能已經注意到我們建立的第一個演示底部有一個 Flag
按鈕。
在預設選項下,如果使用者點選該按鈕,則輸入和輸出樣本將儲存到 CSV 日誌檔案中,您可以稍後檢視。如果演示涉及音訊(如我們的情況),這些將單獨儲存在並行目錄中,並且這些檔案的路徑將儲存在 CSV 檔案中。
返回並再次使用我們的第一個演示,然後單擊 Flag
按鈕。您將看到在 flagged
目錄中建立了一個新的日誌檔案。
>>> !cat flagged/log.csv
name,intensity,output,flag,username,timestamp Diego,4,"Hello, Diego!!!!",,,2024-06-29 22:07:50.242707
在這種情況下,我將輸入設定為 name=diego
和 intensity=29
,然後我將其標記。您可以看到日誌檔案包含函式的輸入、輸出 "Hello, diego!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
,以及一個時間戳。
雖然您的使用者發現有問題的輸入和輸出列表總比沒有好,但 Gradio 的標記功能允許您做更多。例如,您可以提供一個 flagging_options
引數,讓您自定義可以收到的反饋或錯誤的型別,例如 ["Incorrect", "Ambiguous"]
。請注意,這要求將 allow_flagging
設定為 "manual"
。
demo_with_custom_flagging = gr.Interface(
fn=greet,
inputs=["text", "slider"], # the inputs are a text box and a slider ("text" and "slider" are components in Gradio)
outputs=["text"], # the output is a text box
allow_flagging="manual",
flagging_options=["Incorrect", "Ambiguous"],
)
demo_with_custom_flagging.launch()
來試試看吧 👆!您可以看到標記按鈕現在是 Flag as Incorrect
和 Flag as Ambiguous
,新的日誌檔案將反映這些選項。
>>> !cat flagged/log.csv
name,intensity,output,flag,username,timestamp Diego,4,"Hello, Diego!!!!",,,2024-06-29 22:07:50.242707 Diego,5,"Hello, Diego!!!!!",Ambiguous,,2024-06-29 22:08:04.281030
總結與下一步
在本筆記本中,我們學習瞭如何使用 Gradio 演示任何機器學習模型。
首先,我們學習瞭如何為簡單的 Python 函式設定介面的基礎知識;其次,我們涵蓋了 Gradio 的真正優勢:為機器學習模型構建演示。
為此,我們學習瞭如何輕鬆利用 🤗 Hub 中的模型,透過 transformers
庫及其 pipeline
函式,以及如何使用 gr.Audio
等多媒體輸入。
第三,我們介紹瞭如何在 🤗 Spaces 上託管您的 Gradio 演示,這讓您的演示可以在雲中執行,並在計算需求方面為您提供靈活性。
最後,我們展示了 Gradio 附帶的一些超酷的內建功能,例如 API 訪問、公共 URL 和標記功能。
接下來,請檢視每個章節末尾的 Further Reading
連結。