Deepgram:录音转写
使用 Deepgram 转写预录音频
🌐 查看英文原文 | 源码 Notebook
使用 Deepgram 转写音频文件 & 使用 Anthropic 准备面试问题!
将此 notebook 复制到你自己的 Drive 中,然后按照以下说明操作! 🥳🥳🥳
开始使用:
运行以下三个单元格即可转写任何你想要的音频。下面的注释指出了你可以操作的变量,以便根据需要修改输出。
在运行此 notebook 之前,你需要准备几个要转写的音频 URL。你可以使用任何你想要的音频文件。
另外,如果你还没有注册 Deepgram,请点击此链接:https://dpgr.am/prerecorded-notebook-signup
第一步:依赖
运行此单元格以下载所有必要的依赖。
注意:你可以通过点击左侧的播放按钮,或点击单元格并同时按下 shift+ENTER 来运行单元格。(在 Mac 上则是 shift + return)。
! pip install requests ffmpeg-python
! pip install deepgram-sdk --upgrade
! pip install requests
! pip install anthropic第二步:音频 URL 文件
找到一些托管在服务器上的音频文件,以便你可以使用此 notebook。或者,Deepgram 在下面的代码中提供了一个示例文件。
# Have you completed Step 2 above? 👀
# Do you see your audio file in the folder on the left? 📂第三步:转写
填写以下变量:
DG_KEY= 你的 Deepgram API keyAUDIO_FILE_URL= 你要转写的音频文件的 URL
现在运行单元格!(Shift + Enter)
另外,如果你已经是 Deepgram 用户,并且在此单元格中遇到错误,最常见的修复方法是:
- 你可能需要更新 deepgram-sdk 的安装。
- 你可能需要检查 Deepgram 账户中剩余的额度。
import requests
from deepgram import DeepgramClient, FileSource, PrerecordedOptions
# Deepgram API key
DG_KEY = "🔑🔑🔑 Your API Key here! 🔑🔑🔑"
# URL of the audio file
AUDIO_FILE_URL = "https://static.deepgram.com/examples/nasa-spacewalk-interview.wav"
# Path to save the transcript JSON file
TRANSCRIPT_FILE = "transcript.json"
def main():
try:
# STEP 1: Create a Deepgram client using the API key
deepgram = DeepgramClient(DG_KEY)
# Download the audio file from the URL
response = requests.get(AUDIO_FILE_URL, timeout=60)
if response.status_code == 200:
buffer_data = response.content
else:
print("Failed to download audio file")
return
payload: FileSource = {
"buffer": buffer_data,
}
# STEP 2: Configure Deepgram options for audio analysis
options = PrerecordedOptions(
model="nova-2",
smart_format=True,
)
# STEP 3: Call the transcribe_file method with the text payload and options
response = deepgram.listen.prerecorded.v("1").transcribe_file(payload, options)
# STEP 4: Write the response JSON to a file
with open(TRANSCRIPT_FILE, "w") as transcript_file:
transcript_file.write(response.to_json(indent=4))
print("Transcript JSON file generated successfully.")
except Exception as e:
print(f"Exception: {e}")
if __name__ == "__main__":
main()如果上面的单元格运行成功,你应该会在内容目录中看到 JSON 输出文件。注意:单元格运行完成到 JSON 文件实际出现之间可能会有短暂的延迟。这是正常的。只需稍等片刻等待文件出现。
第四步:查看你的转写结果
下面的函数会解析输出 JSON 并打印出你刚刚转写的文件的转写文本!(请确保你要检查的文件确实已经加载到内容目录中。)
将 OUTPUT 变量设置为你想查看转写内容的文件名。
然后运行此单元格(Shift+Enter),你就可以看到逐句的音频转写结果!
import json
# Set this variable to the path of the output file you wish to read
OUTPUT = "transcript.json"
# The JSON is loaded with information, but if you just want to read the
# transcript, run the code below!
def print_transcript(transcription_file):
with open(transcription_file) as file:
data = json.load(file)
result = data["results"]["channels"][0]["alternatives"][0]["transcript"]
result = result.split(".")
for sentence in result:
print(sentence + ".")
print_transcript(OUTPUT)如果上面的单元格运行成功,你应该能看到音频转写的纯文本版本。
第五步:使用 Anthropic 准备面试问题
现在我们可以将转写文本发送给 Anthropic 进行分析,帮助我们准备一些面试问题。运行下面的单元格(Shift+Enter),根据你上面的音频转写文本,获取 Anthropic 提供的建议性面试问题。
import json
import anthropic
transcription_file = "transcript.json"
# Function to get the transcript from the JSON file
def get_transcript(transcription_file):
with open(transcription_file) as file:
data = json.load(file)
result = data["results"]["channels"][0]["alternatives"][0]["transcript"]
return result
# Load the transcript from the JSON file
message_text = get_transcript(transcription_file)
# Initialize the Claude API client
client = anthropic.Anthropic(
# Defaults to os.environ.get("ANTHROPIC_API_KEY")
# Claude API key
api_key="🔑🔑🔑 Your API Key here! 🔑🔑🔑"
)
# Prepare the text for the API request
formatted_messages = [{"role": "user", "content": message_text}]
# Generate thoughtful, open-ended interview questions
response = client.messages.create(
model="claude-opus-4-1",
max_tokens=1000,
temperature=0.5,
system="Your task is to generate a series of thoughtful, open-ended questions for an interview based on the given context. The questions should be designed to elicit insightful and detailed responses from the interviewee, allowing them to showcase their knowledge, experience, and critical thinking skills. Avoid yes/no questions or those with obvious answers. Instead, focus on questions that encourage reflection, self-assessment, and the sharing of specific examples or anecdotes.",
messages=formatted_messages,
)
# Print the generated questions
# Join the text of each TextBlock into a single string
content = "".join(block.text for block in response.content)
# Split the content by '\n\n'
parts = content.split("\n\n")
# Print each part with an additional line break
for part in parts:
print(part)
print("\n")如果此单元格运行成功,你应该能看到基于原始音频文件的面试问题列表。现在你可以用 Deepgram 转写音频,并使用 Anthropic 获取一组面试问题了。
中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。