การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram
การถอดเสียงแบบเรียลไทม์และเป็นชุด การตรวจจับภาษา และเครื่องหมายวรรคตอน
การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
การแปลงเสียงพูดเป็นข้อความในเอเจนต์เสียง
เอเจนต์เสียงต้องแปลงเสียงพูดเป็นข้อความก่อนที่ LLM จะประมวลผล ขั้นตอนนี้เรียกว่า การแปลงเสียงพูดเป็นข้อความ (STT) หรือ การรู้จำเสียงพูดอัตโนมัติ (ASR)
ตัวเลือกชั้นนำมีสองรายการ ได้แก่ OpenAI Whisper (ใช้ไฟล์และประมวลผลแบบเป็นชุด) และ Deepgram (สตรีมแบบเรียลไทม์ พร้อมการจำแนกผู้พูดและการประทับเวลาระดับคำ)
OpenAI Whisper: การถอดเสียงเบื้องต้น
Whisper ผ่าน API ของ OpenAI ใช้ถอดเสียงจากไฟล์เสียง รูปแบบที่รองรับ ได้แก่ mp3, mp4, wav, webm, m4a และ flac ขนาดไฟล์สูงสุดคือ 25MB
import openai
import os
client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def transcribe_file(audio_path, language=None):
with open(audio_path, 'rb') as audio_file:
params = {
'model': 'whisper-1',
'file': audio_file,
'response_format': 'json' # or 'text', 'srt', 'vtt', 'verbose_json'
}
if language:
params['language'] = language # e.g., 'en', 'fr', 'de'
transcript = client.audio.transcriptions.create(**params)
return transcript.text
# Basic usage
text = transcribe_file('meeting_recording.mp3')
print('Transcribed:', text[:200])Whisper พร้อมการประทับเวลาระดับคำ
ใช้ response_format='verbose_json' เพื่อรับการประทับเวลาของแต่ละคำและแต่ละส่วน วิธีนี้มีประโยชน์สำหรับการค้นหาช่วงเวลาที่ต้องการในไฟล์บันทึก การไฮไลต์เนื้อหาแบบคาราโอเกะ และการจัดแนวข้อความถอดเสียงให้ตรงกับการเล่นเสียง
import openai
import os
client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def transcribe_with_timestamps(audio_path):
with open(audio_path, 'rb') as f:
result = client.audio.transcriptions.create(
model='whisper-1',
file=f,
response_format='verbose_json',
timestamp_granularities=['word', 'segment'] # get both word and segment times
)
segments = []
for seg in result.segments:
segments.append({
'start': seg.start,
'end': seg.end,
'text': seg.text
})
words = []
if hasattr(result, 'words'):
for word in result.words:
words.append({'word': word.word, 'start': word.start, 'end': word.end})
return {'text': result.text, 'segments': segments, 'words': words}Deepgram SDK: การสตรีมแบบอะซิงโครนัส
Deepgram ได้รับการปรับให้เหมาะกับการถอดเสียงแบบสตรีมมิงเรียลไทม์ ระบบจะส่งเสียงเป็นชิ้นย่อยระหว่างที่กำลังบันทึก และส่งข้อความถอดเสียงบางส่วนกลับมาก่อนที่ผู้พูดจะพูดจบประโยค
ติดตั้งด้วย pip install deepgram-sdk
import asyncio
import os
from deepgram import DeepgramClient, PrerecordedOptions
client = DeepgramClient(os.getenv('DEEPGRAM_API_KEY'))
async def transcribe_with_deepgram(audio_path):
with open(audio_path, 'rb') as f:
audio_data = f.read()
options = PrerecordedOptions(
model='nova-2', # Deepgram's best accuracy model
language='en',
smart_format=True, # auto-add punctuation and formatting
utterances=True, # segment by speaker turns
punctuate=True,
diarize=True # speaker identification
)
response = await client.listen.asyncrest.v('1').transcribe_file(
{'buffer': audio_data},
options
)
return response.results.channels[0].alternatives[0].transcriptการจำแนกผู้พูด
การจำแนกผู้พูด ใช้ระบุว่าใครกำลังพูดอยู่เมื่อใด โดยติดป้ายกำกับแต่ละส่วนเป็น ผู้พูด 0, ผู้พูด 1 และอื่น ๆ ซึ่งสำคัญอย่างยิ่งสำหรับข้อความถอดเสียงการประชุมและการสนทนาหลายฝ่าย
async def transcribe_with_diarization(audio_path):
from deepgram import DeepgramClient, PrerecordedOptions
import os
dg_client = DeepgramClient(os.getenv('DEEPGRAM_API_KEY'))
options = PrerecordedOptions(
model='nova-2',
diarize=True,
utterances=True,
smart_format=True
)
with open(audio_path, 'rb') as f:
audio_data = f.read()
response = await dg_client.listen.asyncrest.v('1').transcribe_file(
{'buffer': audio_data}, options
)
utterances = []
for utt in response.results.utterances:
utterances.append({
'speaker': f'Speaker {utt.speaker}',
'start': round(utt.start, 2),
'end': round(utt.end, 2),
'text': utt.transcript
})
return utterances
# Output:
# [{'speaker': 'Speaker 0', 'start': 0.0, 'end': 3.2, 'text': 'Hello everyone.'},
# {'speaker': 'Speaker 1', 'start': 3.5, 'end': 6.1, 'text': 'Good morning!'}]การตรวจจับภาษา
เมื่อไม่ทราบภาษาของผู้ใช้ ทั้ง Whisper และ Deepgram สามารถตรวจจับภาษาที่พูดโดยอัตโนมัติได้ Whisper ตรวจจับภาษาจากเสียง 30 วินาทีแรก
import openai
import os
client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def detect_language(audio_path):
with open(audio_path, 'rb') as f:
# Use translations endpoint to get verbose JSON with language detection
result = client.audio.transcriptions.create(
model='whisper-1',
file=f,
response_format='verbose_json'
)
return {
'detected_language': result.language,
'text': result.text
}
result = detect_language('user_audio.wav')
print(f"Language: {result['detected_language']}")
print(f"Text: {result['text'][:100]}")
# Deepgram: set language='auto' in options
from deepgram import PrerecordedOptions
options = PrerecordedOptions(model='nova-2', language='auto', detect_language=True)การแบ่งไฟล์เสียงยาวเป็นส่วนย่อย
ข้อจำกัดขนาด 25MB ของ Whisper ทำให้ไฟล์บันทึกเสียงยาว เช่น การประชุมหนึ่งชั่วโมง ต้องถูกแบ่งเป็นส่วนย่อย ให้แบ่งเสียงตามช่วงเงียบโดยใช้ pydub จากนั้นถอดเสียงแต่ละส่วนแล้วนำมาต่อกัน
ติดตั้งด้วย pip install pydub โดยต้องใช้ ffmpeg
from pydub import AudioSegment
from pydub.silence import split_on_silence
import io
def transcribe_long_audio(audio_path, chunk_length_ms=60000):
audio = AudioSegment.from_file(audio_path)
# Split on silence
chunks = split_on_silence(
audio,
min_silence_len=1000, # 1 second of silence
silence_thresh=-40, # dBFS
keep_silence=500 # keep 500ms at each end
)
# If no silence splitting worked, use fixed-length chunks
if len(chunks) <= 1:
chunks = [
audio[i:i + chunk_length_ms]
for i in range(0, len(audio), chunk_length_ms)
]
full_transcript = []
for i, chunk in enumerate(chunks):
print(f'Transcribing chunk {i+1}/{len(chunks)}')
buf = io.BytesIO()
chunk.export(buf, format='mp3')
buf.seek(0)
buf.name = f'chunk_{i}.mp3'
result = client.audio.transcriptions.create(model='whisper-1', file=buf)
full_transcript.append(result.text)
return ' '.join(full_transcript)การสตรีมสดด้วย Deepgram
สำหรับการสนทนาด้วยเสียงแบบเรียลไทม์ ให้ใช้ API การสตรีมสดผ่าน WebSocket ของ Deepgram ระบบจะส่งชิ้นส่วนเสียงระหว่างที่กำลังบันทึก และข้อความถอดเสียงระหว่างประมวลผลกับข้อความถอดเสียงฉบับสุดท้ายจะมาถึงภายในเวลาไม่กี่มิลลิวินาที
import asyncio
import os
from deepgram import DeepgramClient, LiveTranscriptionEvents, LiveOptions
async def live_transcribe(on_transcript_callback):
dg_client = DeepgramClient(os.getenv('DEEPGRAM_API_KEY'))
connection = dg_client.listen.asynclive.v('1')
async def on_message(self, result, **kwargs):
sentence = result.channel.alternatives[0].transcript
is_final = result.is_final
if sentence:
await on_transcript_callback(sentence, is_final)
connection.on(LiveTranscriptionEvents.Transcript, on_message)
options = LiveOptions(
model='nova-2',
language='en',
smart_format=True,
interim_results=True, # get partial results before sentence ends
endpointing=500 # ms of silence before finalizing
)
await connection.start(options)
return connection # caller sends audio chunks via connection.send(audio_chunk)การจัดการข้อผิดพลาดและการลองใหม่
API ถอดเสียงอาจทำงานล้มเหลวเนื่องจากปัญหาเครือข่าย รูปแบบไฟล์ที่ไม่รองรับ หรือข้อจำกัดอัตราการเรียกใช้ ให้ใช้การลองใหม่โดยเพิ่มช่วงหน่วงแบบทวีคูณ และตรวจสอบเสียงก่อนส่ง
import time
import os
MAX_FILE_SIZE_BYTES = 25 * 1024 * 1024 # 25MB
SUPPORTED_FORMATS = ('.mp3', '.mp4', '.wav', '.webm', '.m4a', '.flac', '.ogg')
def validate_audio_file(audio_path):
if not os.path.exists(audio_path):
raise FileNotFoundError(f'Audio file not found: {audio_path}')
size = os.path.getsize(audio_path)
if size > MAX_FILE_SIZE_BYTES:
raise ValueError(f'File too large: {size / 1024 / 1024:.1f}MB (max 25MB)')
ext = os.path.splitext(audio_path)[1].lower()
if ext not in SUPPORTED_FORMATS:
raise ValueError(f'Unsupported format: {ext}. Supported: {SUPPORTED_FORMATS}')
def transcribe_with_retry(audio_path, max_retries=3):
validate_audio_file(audio_path)
for attempt in range(max_retries):
try:
return transcribe_file(audio_path)
except Exception as e:
if attempt < max_retries - 1:
wait = 2 ** attempt
print(f'Retry {attempt + 1} after error: {e}. Waiting {wait}s')
time.sleep(wait)
else:
raiseการเลือกระหว่าง Whisper กับ Deepgram
เครื่องมือทั้งสองเหมาะกับสถานการณ์ที่แตกต่างกัน ใช้ตารางตัดสินใจนี้เพื่อเลือกเครื่องมือที่เหมาะสมสำหรับเอเจนต์เสียงของคุณ
COMPARISON = '''
Whisper (OpenAI API):
- Best for: batch transcription, podcast processing, meeting notes
- Latency: file upload latency + ~1-5 seconds processing
- Strengths: excellent multilingual, high accuracy, cheap
- Word timestamps: yes (verbose_json)
- Diarization: NO (must use separate tool)
- Use when: accuracy > speed, offline processing
DeeGram:
- Best for: real-time voice agents, call center transcription
- Latency: <300ms for streaming, ~1s for file upload
- Strengths: streaming, diarization, custom vocabulary
- Word timestamps: yes, with confidence scores
- Diarization: YES (built-in, up to 10 speakers)
- Use when: speed > accuracy, real-time required
Rule of thumb:
Agent voice conversation -> Deepgram live streaming
Batch audio files -> Whisper API
Meeting transcripts with speakers -> Deepgram with diarize=True
'''
print(COMPARISON)การแปลงรูปแบบเสียง
Whisper และ Deepgram รองรับรูปแบบเสียงทั่วไป แต่เสียงจากผู้ใช้อาจมาในรูปแบบที่ไม่คุ้นเคย เช่น ogg, opus, webm จากเบราว์เซอร์ หรือ m4a จาก iOS ให้แปลงเป็น WAV หรือ MP3 มาตรฐานก่อนส่งไปยัง API
from pydub import AudioSegment
import os
SUPPORTED_FORMATS = {'.mp3', '.wav', '.flac', '.m4a', '.ogg', '.webm', '.opus'}
def convert_to_wav(input_path, output_path=None):
ext = os.path.splitext(input_path)[1].lower()
if ext not in SUPPORTED_FORMATS:
raise ValueError(f'Unsupported audio format: {ext}')
if output_path is None:
output_path = input_path.rsplit('.', 1)[0] + '.wav'
# pydub handles format detection automatically
audio = AudioSegment.from_file(input_path)
# Normalize to 16kHz mono (optimal for Whisper)
audio = audio.set_frame_rate(16000).set_channels(1)
audio.export(output_path, format='wav')
print(f'Converted {input_path} -> {output_path} ({len(audio) / 1000:.1f}s)')
return output_path
def ensure_compatible_audio(audio_path):
ext = os.path.splitext(audio_path)[1].lower()
if ext in {'.mp3', '.wav', '.m4a', '.flac'}:
return audio_path # already compatible
return convert_to_wav(audio_path)ตรวจสอบความเข้าใจ
การจำแนกผู้พูดในบริบทของการถอดเสียงพูดคืออะไร
สรุปทบทวน: การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram
Whisper (API ของ OpenAI) เหมาะสำหรับการถอดเสียงแบบเป็นชุด มีความแม่นยำสูง รองรับหลายภาษา และให้การประทับเวลาระดับคำผ่าน verbose_json ควรใช้เมื่อประมวลผลแบบใช้ไฟล์และความหน่วงไม่ใช่ปัจจัยสำคัญ
Deepgram ออกแบบมาสำหรับการสตรีมแบบเรียลไทม์ โดยถอดเสียงสดผ่าน WebSocket พร้อมผลลัพธ์ระหว่างประมวลผล การจำแนกผู้พูดในตัว และความหน่วงต่ำกว่า 300 มิลลิวินาที ควรใช้กับเอเจนต์เสียงแบบโต้ตอบ ทั้งสองระบบรองรับการตรวจจับภาษา และในการใช้งานจริงจำเป็นต้องมีตรรกะสำหรับการลองใหม่และการตรวจสอบไฟล์
คำถามที่พบบ่อย
บทเรียน “การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram”
การถอดเสียงแบบเรียลไทม์และเป็นชุด การตรวจจับภาษา และเครื่องหมายวรรคตอน คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การแปลงเสียงพูดเป็นข้อความด้วย Whisper และ Deepgram
- การแปลงข้อความเป็นเสียงพูดในคำตอบของตัวแทน
- การสร้างลูปสนทนาด้วยเสียง
- การปรับเวลาแฝงให้เหมาะที่สุดสำหรับตัวแทนเสียง