
OpenAI Whisper 튜토리얼: 음성-텍스트 변환 완전 가이드
Eric King
Author
OpenAI Whisper 튜토리얼: 음성-텍스트 변환 완전 가이드
OpenAI Whisper는 음성을 텍스트로 변환하고 음성을 번역하기 위한 오픈소스 자동 음성 인식(ASR) 모델입니다. 여러 언어를 지원하고 악센트와 배경 소음에도 강하며, 팟캐스트, 회의, 인터뷰, 동영상 자막 등에 널리 쓰입니다.
이 튜토리얼에서는 설치부터 고급 사용법까지 Whisper를 시작하는 데 필요한 내용을 모두 안내합니다.
OpenAI Whisper란?
Whisper는 68만 시간 이상의 다국어 오디오 데이터로 학습되어 현실적이고 불완전한 오디오에 특히 강합니다. 이용 가능한 오픈소스 음성 인식 모델 중에서도 정확도가 매우 높은 편입니다.
주요 기능
- 다국어 지원 — 99개 이상 언어
- 음성-텍스트 전사 — 오디오를 텍스트로 변환
- 음성 번역 — 음성을 바로 영어로 번역
- 언어 감지 — 말하는 언어를 자동 감지
- 타임스탬프 — 단어·세그먼트 단위
- 오픈소스·무료 — MIT 라이선스, API 비용 없음
- 오프라인 가능 — 로컬 머신에서 실행
- 다양한 형식 — 여러 오디오·비디오 형식 지원
Whisper 모델 크기 설명
Whisper는 속도와 정확도의 균형을 위해 여러 모델 크기를 제공합니다.
| 모델 | 파라미터 | 속도 | 정확도 | 메모리 | 사용 사례 |
|---|---|---|---|---|---|
| tiny | 39M | ⭐⭐⭐⭐⭐ | ⭐⭐ | ~1 GB | 빠른 테스트, 데모 |
| base | 74M | ⭐⭐⭐⭐ | ⭐⭐⭐ | ~1 GB | 단순 오디오, 빠른 작업 |
| small | 244M | ⭐⭐⭐ | ⭐⭐⭐⭐ | ~2 GB | 일반 용도, 균형 |
| medium | 769M | ⭐⭐ | ⭐⭐⭐⭐⭐ | ~5 GB | 노이즈 많은 오디오, 고정확도 |
| large | 1550M | ⭐ | ⭐⭐⭐⭐⭐⭐ | ~10 GB | 최고 정확도, 프로덕션 |
권장 사항:
- 속도:
tiny또는base - 균형:
small또는medium - 정확도:
large또는large-v3 - 프로덕션: 대개
medium또는large-v2
사전 요구 사항
Whisper를 사용하기 전에 다음을 갖추세요.
- Python 3.8 이상 (Python 3.9+ 권장)
- 패키지 관리자 pip
- FFmpeg 설치 (오디오·비디오 처리)
- (선택) CUDA 지원 NVIDIA GPU (더 빠른 처리)
- (선택) base 모델 기준 4GB 이상 RAM, large는 10GB 이상
1단계: 설치
Whisper 설치
pip으로 OpenAI Whisper 패키지를 설치합니다.
pip install openai-whisper
특정 버전:
pip install openai-whisper==20231117
FFmpeg 설치
오디오·비디오 파일 디코딩에 FFmpeg가 필요합니다.
macOS (Homebrew):
brew install ffmpeg
Ubuntu / Debian:
sudo apt update
sudo apt install ffmpeg
Windows:
- ffmpeg.org에서 FFmpeg 다운로드
- 압축 해제 후 시스템 PATH에 추가
- 또는:
choco install ffmpeg(Chocolatey)
설치 확인:
ffmpeg -version
whisper --version
2단계: 기본 사용법 — Python
간단한 전사
가장 단순한 오디오 전사 방법입니다.
import whisper
# Load model (downloads automatically on first use)
model = whisper.load_model("base")
# Transcribe audio file
result = model.transcribe("audio.mp3")
# Print transcription
print(result["text"])
출력:
Hello everyone, welcome to today's meeting. We will discuss the project timeline and upcoming milestones.
오류 처리를 포함한 전체 예제
import whisper
import os
def transcribe_audio(audio_path, model_size="base"):
"""
Transcribe an audio file using Whisper.
Args:
audio_path (str): Path to the audio file
model_size (str): Whisper model size (tiny, base, small, medium, large)
Returns:
dict: Transcription result with text and segments
"""
try:
# Check if audio file exists
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
# Load the Whisper model
print(f"Loading Whisper model: {model_size}")
model = whisper.load_model(model_size)
# Transcribe the audio
print(f"Transcribing: {audio_path}")
result = model.transcribe(audio_path)
print(f"✓ Transcription complete!")
print(f" Language: {result['language']}")
print(f" Duration: {result['segments'][-1]['end']:.2f}s")
return result
except Exception as e:
print(f"Error during transcription: {str(e)}")
return None
# Example usage
if __name__ == "__main__":
audio_file = "meeting.mp3"
result = transcribe_audio(audio_file, model_size="base")
if result:
print("\n" + "="*50)
print("TRANSCRIPTION:")
print("="*50)
print(result["text"])
3단계: 언어 감지 및 지정
언어 자동 감지
Whisper는 언어를 자동으로 감지합니다.
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
print(f"Detected language: {result['language']}")
print(f"Language probability: {result.get('language_probability', 0):.2%}")
print(f"\nTranscription:\n{result['text']}")
언어 지정 (더 빠르고 정확)
언어를 알고 있으면 지정하는 것이 속도와 정확도에 도움이 됩니다.
import whisper
model = whisper.load_model("base")
# Specify language
result_en = model.transcribe("audio.mp3", language="en") # English
result_zh = model.transcribe("audio.mp3", language="zh") # Chinese
result_es = model.transcribe("audio.mp3", language="es") # Spanish
result_fr = model.transcribe("audio.mp3", language="fr") # French
result_de = model.transcribe("audio.mp3", language="de") # German
result_ja = model.transcribe("audio.mp3", language="ja") # Japanese
print(result_en["text"])
지원 언어:
Whisper는 99개 이상의 언어를 지원합니다. 자주 쓰는 언어 코드:
en— 영어zh— 중국어es— 스페인어fr— 프랑스어de— 독일어ja— 일본어ko— 한국어pt— 포르투갈어ru— 러시아어it— 이탈리아어
4단계: 타임스탬프와 세그먼트
타임스탬프가 있는 세그먼트 접근
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
# Print full transcription
print("Full Text:")
print(result["text"])
# Print segments with timestamps
print("\n" + "="*50)
print("Segments with Timestamps:")
print("="*50)
for segment in result["segments"]:
start = segment["start"]
end = segment["end"]
text = segment["text"].strip()
print(f"[{start:6.2f}s - {end:6.2f}s] {text}")
출력:
Full Text:
Hello everyone, welcome to today's meeting. We will discuss the project timeline.
==================================================
Segments with Timestamps:
==================================================
[ 0.00s - 5.20s] Hello everyone, welcome to today's meeting.
[ 5.20s - 12.50s] We will discuss the project timeline.
타임스탬프를 타임코드 형식으로
def format_timestamp(seconds):
"""Format seconds to HH:MM:SS."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
for segment in result["segments"]:
start_time = format_timestamp(segment["start"])
end_time = format_timestamp(segment["end"])
print(f"[{start_time} - {end_time}] {segment['text']}")
단어 수준 타임스탬프
정밀한 타이밍을 위해 단어 수준 타임스탬프를 켭니다.
import whisper
model = whisper.load_model("base")
result = model.transcribe(
"audio.mp3",
word_timestamps=True # Enable word-level timestamps
)
for segment in result["segments"]:
print(f"\n[{segment['start']:.2f}s - {segment['end']:.2f}s]")
print(f"Text: {segment['text']}")
# Word-level timestamps
if "words" in segment:
print("Words:")
for word in segment["words"]:
print(f" {word['word']} [{word['start']:.2f}s - {word['end']:.2f}s]")
5단계: 음성 번역
Whisper는 영어가 아닌 음성을 바로 영어로 번역할 수 있습니다.
import whisper
model = whisper.load_model("base")
# Translate to English (regardless of source language)
result = model.transcribe("spanish_audio.mp3", task="translate")
print("Translated to English:")
print(result["text"])
# Original transcription (in original language)
result_original = model.transcribe("spanish_audio.mp3", task="transcribe")
print("\nOriginal language transcription:")
print(result_original["text"])
활용 사례:
- 국제 회의
- 다국어 콘텐츠 처리
- 콘텐츠 현지화
- 언어 학습 자료
6단계: 고급 매개변수
temperature와 빔 크기
전사 품질과 속도를 조절합니다.
import whisper
model = whisper.load_model("base")
result = model.transcribe(
"audio.mp3",
temperature=0.0, # Lower = more deterministic (0.0 recommended)
beam_size=5, # Higher = more accurate but slower (default: 5)
best_of=5, # Number of candidates to consider
patience=1.0, # Beam search patience
condition_on_previous_text=True, # Use context from previous segments
initial_prompt="This is a technical meeting about AI and machine learning." # Context prompt
)
temperature 값
temperature=0.0— 가장 결정적, 권장temperature=0.2-0.4— 약간 더 다양함temperature=1.0— 더 창의적이나 정확도는 낮아질 수 있음
맥락용 initial prompt
정확도를 높이기 위해 맥락을 제공합니다.
result = model.transcribe(
"technical_meeting.mp3",
initial_prompt="This meeting discusses API endpoints, microservices, Kubernetes, and CI/CD pipelines."
)
result = model.transcribe(
"medical_audio.mp3",
initial_prompt="This is a medical consultation discussing patient symptoms and treatment options."
)
7단계: 명령줄 인터페이스(CLI)
Whisper는 강력한 명령줄 인터페이스를 제공합니다.
기본 CLI 사용
whisper audio.mp3
모델 지정
whisper audio.mp3 --model small
whisper audio.mp3 --model medium
whisper audio.mp3 --model large-v2
언어 지정
whisper audio.mp3 --language en
whisper audio.mp3 --language zh
출력 형식
# SRT subtitles
whisper audio.mp3 --output_format srt
# VTT subtitles
whisper audio.mp3 --output_format vtt
# Text file
whisper audio.mp3 --output_format txt
# JSON (with all metadata)
whisper audio.mp3 --output_format json
# TSV (tab-separated values)
whisper audio.mp3 --output_format tsv
고급 CLI 옵션
# Full example with all options
whisper audio.mp3 \
--model medium \
--language en \
--task transcribe \
--output_format srt \
--output_dir ./transcripts \
--verbose True \
--temperature 0.0 \
--beam_size 5 \
--best_of 5 \
--fp16 True
CLI 옵션 참고
| 옵션 | 설명 | 기본값 |
|---|---|---|
--model | 모델 크기(tiny, base, small, medium, large) | base |
--language | 언어 코드(en, zh, es 등) | 자동 감지 |
--task | transcribe 또는 translate | transcribe |
--output_format | 출력 형식(txt, srt, vtt, json, tsv) | txt |
--output_dir | 출력 디렉터리 | 현재 디렉터리 |
--temperature | 샘플링 temperature | 0.0 |
--beam_size | 빔 서치 빔 크기 | 5 |
--best_of | 후보 수 | 5 |
--fp16 | FP16 정밀도 사용(GPU) | True |
--verbose | 자세한 출력 | False |
8단계: 지원 오디오·비디오 형식
FFmpeg를 통해 Whisper는 흔한 형식 대부분을 지원합니다.
지원 형식
- 오디오: MP3, WAV, M4A, FLAC, OGG, AAC, WMA
- 비디오: MP4, AVI, MKV, MOV, WebM, FLV
- 스트리밍: 오디오 스트림 처리 가능
형식 예제
import whisper
model = whisper.load_model("base")
# Audio formats
model.transcribe("audio.mp3")
model.transcribe("audio.wav")
model.transcribe("audio.m4a")
model.transcribe("audio.flac")
# Video formats (extracts audio automatically)
model.transcribe("video.mp4")
model.transcribe("video.mkv")
model.transcribe("video.webm")
9단계: 프로덕션용 완전한 예제
프로덕션에 가까운 완전한 예제입니다.
import whisper
import json
from pathlib import Path
from datetime import datetime
class WhisperTranscriber:
"""Production-ready Whisper transcription service."""
def __init__(self, model_size="base"):
"""Initialize transcriber with specified model."""
print(f"Loading Whisper model: {model_size}")
self.model = whisper.load_model(model_size)
print("✓ Model loaded successfully")
def transcribe_file(self, audio_path, output_dir="transcripts", **kwargs):
"""
Transcribe audio file and save results.
Args:
audio_path: Path to audio file
output_dir: Directory to save outputs
**kwargs: Additional transcribe parameters
"""
audio_path = Path(audio_path)
if not audio_path.exists():
raise FileNotFoundError(f"Audio file not found: {audio_path}")
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
print(f"\nTranscribing: {audio_path.name}")
# Transcribe
result = self.model.transcribe(
str(audio_path),
word_timestamps=True,
**kwargs
)
# Prepare output data
output_data = {
"file": str(audio_path),
"transcribed_at": datetime.now().isoformat(),
"language": result["language"],
"language_probability": result.get("language_probability", 0),
"duration": result["segments"][-1]["end"] if result["segments"] else 0,
"text": result["text"],
"segments": result["segments"]
}
# Save outputs
base_name = audio_path.stem
# Save as text
text_file = output_path / f"{base_name}.txt"
with open(text_file, "w", encoding="utf-8") as f:
f.write(result["text"])
# Save as JSON
json_file = output_path / f"{base_name}.json"
with open(json_file, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
# Save as SRT
srt_file = output_path / f"{base_name}.srt"
self._save_srt(result["segments"], srt_file)
print(f"✓ Transcription saved:")
print(f" - Text: {text_file}")
print(f" - JSON: {json_file}")
print(f" - SRT: {srt_file}")
return output_data
def _save_srt(self, segments, output_path):
"""Save segments as SRT subtitle file."""
with open(output_path, "w", encoding="utf-8") as f:
for i, segment in enumerate(segments, start=1):
start = self._format_srt_time(segment["start"])
end = self._format_srt_time(segment["end"])
text = segment["text"].strip()
f.write(f"{i}\n{start} --> {end}\n{text}\n\n")
def _format_srt_time(self, seconds):
"""Format seconds to SRT timestamp."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds % 1) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
# Usage
if __name__ == "__main__":
transcriber = WhisperTranscriber(model_size="base")
result = transcriber.transcribe_file(
"meeting.mp3",
output_dir="transcripts",
language="en",
temperature=0.0
)
print(f"\nLanguage: {result['language']}")
print(f"Duration: {result['duration']:.2f}s")
print(f"\nTranscription preview:")
print(result['text'][:200] + "...")
10단계: 모범 사례
1. 적절한 모델 선택
# For speed (testing, demos)
model = whisper.load_model("tiny")
# For balance (general use)
model = whisper.load_model("base") # or "small"
# For accuracy (production)
model = whisper.load_model("medium") # or "large-v2"
2. 알려진 경우 언어 지정
# Faster and more accurate
result = model.transcribe("audio.mp3", language="en")
# Instead of auto-detection
result = model.transcribe("audio.mp3") # Slower
3. 적절한 temperature
# Recommended for most cases
result = model.transcribe("audio.mp3", temperature=0.0)
# For creative content (not recommended for transcription)
result = model.transcribe("audio.mp3", temperature=0.2)
4. initial prompt로 맥락 제공
# Technical content
result = model.transcribe(
"meeting.mp3",
initial_prompt="This meeting discusses software architecture, APIs, and deployment strategies."
)
# Medical content
result = model.transcribe(
"consultation.mp3",
initial_prompt="This is a medical consultation about patient symptoms and treatment."
)
5. 모델 인스턴스 재사용
# Load once, reuse multiple times
model = whisper.load_model("base")
# Process multiple files
for audio_file in ["file1.mp3", "file2.mp3", "file3.mp3"]:
result = model.transcribe(audio_file)
# Process result...
6. 긴 오디오 파일 처리
매우 긴 오디오는 청크로 나누는 것을 고려하세요.
import whisper
from pydub import AudioSegment
def transcribe_long_audio(audio_path, chunk_length_ms=600000): # 10 minutes
"""Transcribe long audio by splitting into chunks."""
model = whisper.load_model("base")
# Load audio
audio = AudioSegment.from_file(audio_path)
duration_ms = len(audio)
all_text = []
all_segments = []
# Process in chunks
for i in range(0, duration_ms, chunk_length_ms):
chunk = audio[i:i + chunk_length_ms]
chunk_path = f"chunk_{i}.wav"
chunk.export(chunk_path, format="wav")
result = model.transcribe(chunk_path)
all_text.append(result["text"])
all_segments.extend(result["segments"])
# Clean up chunk file
os.remove(chunk_path)
return {
"text": " ".join(all_text),
"segments": all_segments
}
자주 발생하는 문제와 해결
문제 1: FFmpeg를 찾을 수 없음
오류:
FileNotFoundError: ffmpeg해결:
# Install FFmpeg
# macOS
brew install ffmpeg
# Ubuntu/Debian
sudo apt install ffmpeg
# Verify
ffmpeg -version
문제 2: 메모리 부족
오류:
RuntimeError: CUDA out of memory 또는 시스템 RAM 부족해결:
# Use smaller model
model = whisper.load_model("base") # Instead of "large"
# Or use CPU
import torch
model = whisper.load_model("base", device="cpu")
# Or process in chunks (see above)
문제 3: 전사가 느림
증상: 전사 속도가 매우 느림
해결:
# Use GPU if available
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper.load_model("base", device=device)
# Use smaller model
model = whisper.load_model("tiny") # or "base"
# Reduce beam size (faster but slightly less accurate)
result = model.transcribe("audio.mp3", beam_size=1)
문제 4: 정확도가 낮음
증상: 전사 오류가 많음
해결:
# Use larger model
model = whisper.load_model("medium") # or "large"
# Specify language
result = model.transcribe("audio.mp3", language="en")
# Provide context
result = model.transcribe(
"audio.mp3",
initial_prompt="Context about the audio content..."
)
# Use optimal settings
result = model.transcribe(
"audio.mp3",
temperature=0.0,
beam_size=5,
best_of=5
)
사용 사례
1. 팟캐스트 전사
model = whisper.load_model("medium")
result = model.transcribe("podcast.mp3", language="en")
# Save transcript
with open("podcast_transcript.txt", "w") as f:
f.write(result["text"])
2. YouTube 자막 생성
model = whisper.load_model("base")
result = model.transcribe("video.mp4", language="en")
# Generate SRT
# (Use CLI: whisper video.mp4 --output_format srt)
3. 회의 메모
model = whisper.load_model("base")
result = model.transcribe(
"meeting.mp3",
language="en",
initial_prompt="This is a business meeting discussing project updates and deadlines."
)
# Save with timestamps
for segment in result["segments"]:
print(f"[{segment['start']:.0f}s] {segment['text']}")
4. 인터뷰 전사
model = whisper.load_model("medium")
result = model.transcribe("interview.mp3", language="en")
# Export for editing
with open("interview.txt", "w") as f:
for segment in result["segments"]:
f.write(f"[{segment['start']:.2f}s] {segment['text']}\n")
5. 다국어 콘텐츠 번역
model = whisper.load_model("base")
# Translate to English
result = model.transcribe("spanish_audio.mp3", task="translate")
print(result["text"]) # English translation
Whisper와 대안 비교
| 항목 | Whisper | 클라우드 API | Faster-Whisper |
|---|---|---|---|
| 비용 | 무료 | 분당 유료 | 무료 |
| 오프라인 | ✅ | ❌ | ✅ |
| 속도 | 보통 | 빠름 | 빠름(2~4배) |
| 정확도 | 높음 | 높음 | 높음(동일) |
| 설정 | 쉬움 | 매우 쉬움 | 쉬움 |
| 실시간 | ❌ | ✅ | ❌ |
| 프라이버시 | ✅ 로컬 | ❌ 클라우드 | ✅ 로컬 |
Whisper를 선택할 때:
- 무료·오프라인 전사가 필요할 때
- 프라이버시가 중요할 때
- 인프라를 직접 제어하고 싶을 때
- 배치 파일이나 아카이브 콘텐츠를 처리할 때
클라우드 API를 선택할 때:
- 실시간 전사가 필요할 때
- 관리형 인프라를 원할 때
- API 비용 예산이 있을 때
- 엔터프라이즈 지원이 필요할 때
다음 단계
기본을 익혔다면 다음도 살펴보세요.
- Whisper Python Example — 더 자세한 Python 예제
- Faster-Whisper Guide — 2~4배 빠른 전사
- Whisper Accuracy Tips — 전사 품질 향상
- Whisper Transcript Formatting — 출력 형식(SRT, VTT, JSON)
- Whisper for Meetings — 회의용 전사
마무리
OpenAI Whisper는 오늘날 이용할 수 있는 강력한 오픈소스 음성-텍스트 모델 중 하나입니다. 뛰어난 다국어 지원, 높은 전사 정확도, 완전한 오프라인 실행으로 전사 워크플로를 스스로 통제하려는 개발자와 콘텐츠 제작자에게 좋은 선택입니다.
핵심 요약:
- Whisper는 99개 이상 언어를 높은 정확도로 지원
- 필요에 맞는 모델 크기 선택
- 알려진 경우 언어 지정으로 성능 향상
- 정밀한 타이밍에는 단어 타임스탬프
- 여러 파일에서는 모델 인스턴스 재사용
- 프로덕션 배포에는 faster-whisper 고려
팟캐스트 전사, 자막 생성, 회의 녹음 처리 등 Whisper는 견고하고 무료이며 프라이버시를 지키는 음성-텍스트 솔루션입니다.
전문 음성-텍스트 솔루션이 필요하신가요? SayToWords에서 최적화된 성능과 다양한 출력 형식을 갖춘 AI 전사 플랫폼을 확인해 보세요.