Deepgram Python SDK チュートリアル
Deepgram Python SDKのチュートリアルへようこそ!🚀
このノートブックでは、音声テキスト変換のためのDeepgramのコア機能を探ります。環境のセットアップからファイル、URLからの音声の文字起こしまで、すべてをカバーします。また、話者分離(diarization)や要約といったDeepgramの高度な機能にも触れます。
それでは始めましょう!
1. セットアップ
まず、必要なライブラリをインストールし、環境を設定します。
1.1. ライブラリのインストール
次のセルのコメントを外して実行し、必要なPythonパッケージをインストールしてください:deepgram-sdk、環境変数管理のためのpython-dotenv。
macOSユーザー向けメモ: マイクサポートが必要な場合は、portaudioをインストールしてからpyaudioを手動でインストールする必要があります。ターミナルで次のコマンドを実行してください:
brew install portaudio
pip install pyaudio
マイクサポートが不要な場合は、pyaudioのインストールをスキップできます。
# Install Deepgram SDK and python-dotenv. If you need microphone support, see the note below.
# !pip install deepgram-sdk python-dotenv -q1.2. APIキーの設定
Deepgramのサービスを使用するには、APIキーが必要です。Deepgramのウェブサイトでサインアップして$200分のクレジット付きの無料APIキーを取得できます。
キーを取得したら、このノートブックと同じディレクトリに.envファイルを作成し、次のようにAPIキーを追加してください:
DEEPGRAM_API_KEY="YOUR_DEEPGRAM_API_KEY"
それでは、.envファイルからAPIキーを読み込みましょう。
import os
from dotenv import load_dotenv
load_dotenv()
DEEPGRAM_API_KEY = os.getenv("DEEPGRAM_API_KEY")2. ファイルから音声を文字起こし
ローカルの音声ファイルを文字起こしすることから始めましょう。この例では、サンプルの音声ファイルをダウンロードできます。このデモではインターネット上のサンプルを使用します。
from deepgram import PrerecordedOptions, FileSource, DeepgramClient
def transcribe_audio_from_local_file(file_path):
# Create a Deepgram client
deepgram = DeepgramClient(DEEPGRAM_API_KEY)
# Configure Deepgram options
options = PrerecordedOptions(
model="nova-2",
smart_format=True,
)
with open(file_path, "rb") as file:
buffer_data = file.read()
payload: FileSource = {
"buffer": buffer_data,
}
# Call the transcribe_file method using REST API
response = deepgram.listen.rest.v("1").transcribe_file(payload, options)
# Print only the transcript
for channel in response.results.channels:
for alternative in channel.alternatives:
print(alternative.transcript)
transcribe_audio_from_local_file('harvard.wav') # Replace with your local audio file pathThe stale smell of old beer lingers. It takes heat to bring out the odor. A cold dip restores health and zest. A salt pickle tastes fine with ham. Tacos al pastor are my favorite. A zestful food is the hot cross bun.
3. URLから音声を文字起こし
DeepgramはURLから直接音声を文字起こしすることもできます。オンラインでホストされている音声ファイルを処理する場合に非常に便利です。
from deepgram import DeepgramClient, PrerecordedOptions, FileSource
import json
# Create a Deepgram client
deepgram = DeepgramClient(DEEPGRAM_API_KEY)
# URL of the audio file
AUDIO_URL = "https://static.deepgram.com/examples/interview_speech-analytics.wav"
def transcribe_audio_from_url(audio_url):
# Configure Deepgram options
options = PrerecordedOptions(
model="nova-2",
smart_format=True,
)
# Call the transcribe_url method using REST API
source = {'url': audio_url}
response = deepgram.listen.rest.v("1").transcribe_url(source, options)
# Print only the transcript
for channel in response.results.channels:
for alternative in channel.alternatives:
print(alternative.transcript)
transcribe_audio_from_url(AUDIO_URL)Another big problem in the speech analytics space, when customers first bring the software on is that they they are blown away by the fact that an engine can monitor hundreds of KPIs. Right? Everything from minute compliance issues to, you know, human, human interaction, empathy measurements, to upsell, aptitudes, to closing aptitudes. There are hundreds, literally, of KPIs that one can look at. And the speech analytics companies have typically gone to the customer and really bang that drum. Look at all of these things that we're gonna help you keep an eye on. The reality, however, is that a company even a contact center manager, they can't keep track in their brain, even if they have a report in front of them, of that many KPIs. Mhmm. And, frankly, it's overwhelming. So what successful companies do is they bite off no more than they can chew at any given time. The reality is is you can only train a call center agent on a maximum of three skills at any given day. Right? And by focusing on, focusing on problem areas for a week, for a month, depending on how bad things are, and then once you've mastered that skill, to take a baseline of of your performance and move on to the next worst skill, right, is the way that companies succeed using this product.
4. 高度な機能:話者分離と要約
Deepgramは強力な音声インテリジェンス機能を幅広く提供しています。最も人気のある2つの機能を見てみましょう:話者分離(diarization)(誰がいつ話したかを識別)と要約(summarization)。
from deepgram import PrerecordedOptions, FileSource, DeepgramClient
import json
def transcribe_with_advanced_features_local(file_path):
deepgram = DeepgramClient(DEEPGRAM_API_KEY)
options = PrerecordedOptions(
model="nova-2",
smart_format=True,
diarize=True, # Enable speaker diarization
summarize="v2", # Enable summarization
)
with open(file_path, "rb") as file:
buffer_data = file.read()
payload: FileSource = {
"buffer": buffer_data,
}
response = deepgram.listen.rest.v("1").transcribe_file(payload, options)
# Print transcript separated by speaker
print("\nSpeaker-separated transcript:")
diarized = response.results.channels[0].alternatives[0].words
speaker_transcripts = {}
for word in diarized:
speaker = getattr(word, 'speaker', 'Unknown')
if speaker not in speaker_transcripts:
speaker_transcripts[speaker] = []
speaker_transcripts[speaker].append(getattr(word, 'punctuated_word', getattr(word, 'word', '')))
for speaker, words in speaker_transcripts.items():
print(f"Speaker {speaker}: {' '.join(words)}")
# Extract and print summary from data['results']['summary']['short'] if available
data = response.to_dict()
summary_data = data.get('results', {}).get('summary', {})
summary_short = summary_data.get('short') if isinstance(summary_data, dict) else None
if summary_short:
print("\nSummary:")
print(summary_short)
else:
print("\nNo summary available.")
transcribe_with_advanced_features_local("diarization.m4a")Speaker-separated transcript: Speaker 0: I guess. I just thought Aristotle thought flames kept going up and up and up. He said the Earth revolved around the sun, but didn't he get in trouble for that? Didn't the church make him stop saying it? What aspect of gravitational science is the lecture mainly about? Speaker 1: No. Aristotle thought the flames would stop at some point at their natural place in the sky, but I can understand how you'd be confused. Aristotle's ideas seem odd to us today. Now, there was another early scientist whose ideas on gravity may seem more familiar. An ancient Indian thinker from the five hundreds, Brahmagupta, that was his name. He believed that the earth was basically a giant ball that was full of gravity and pulled things down to it. So around earth with its own gravitational pull, just like we believe today. Now, yes, Susie. Well, actually, Susie, the theory the world is round is a very old one. In fact, it was during Aristotle's life that some of his fellow Greek scientist realized the Earth had to be round. In many ways, this idea of a round earth was the first step toward our modern understanding of gravity. And, Brahmaguptha took that a step further realizing there was gravity within the sphere of the earth. Now, Aristotle was right too in a sense. Things can fall at different speeds, but, that's because of differences in air resistance. The atmosphere or counteracting gravity when it hits things that are not so compact, not not dense. Aristotle, Ramagupta, other ancient thinkers were missing an important theory, well, a fact. I'm talking about heliocentrism, the idea the earth isn't the center of the universe, that it revolves around the sun. That idea became popular much later in the fifteen hundreds. Does anyone know who Copernicus is? Roger? Well, he wasn't punished, but he did get a lot of grief from religious leaders at the time. The idea certainly wasn't traditional, but other scientists and the public, they embraced his ideas about planetary orbits. This new scientific attention to orbits set the stage for Newton to realize that gravity made things fall to the earth, but they also made the moon circle the earth. And then Newton figured out what we all know now. Larger objects have gravitational power over smaller ones. Speaker 2: Sorry. I I'm confused again. I thought nobody knew the Earth was round until people sailed all the way around the world in in, like, the fourteen or fifteen hundreds. How did Brahmagupta figure out the world was round? Summary: Speaker 0 is confused about the idea that the Earth is a giant ball and pulled things down to it. Speaker 1 explains that the theory of a round Earth was discussed by a Greek scientist named Braheler during the early stages of the Discovery process, but it became popular later in the hundreds. Other scientists and the public embraced the idea of a rotating body and the idea of a moon, but it was not traditional.
6. まとめ
おめでとうございます!Deepgram Python SDKの基礎を習得しました。
学んだこと: ✅ 環境とAPIキーのセットアップ。 ✅ ローカルファイルとURLからの音声の文字起こし。 ✅ マイクからのリアルタイム文字起こし。 ✅ 話者分離や要約などの高度な機能の使用。
これはDeepgramでできることの始まりに過ぎません。詳細については、Deepgramのドキュメントをご確認ください。