[Python] 허깅페이스 위스퍼 사용하여 mp3 로부터 텍스트 추출

Posted by Albert 92Day 10Hour 17Min 35Sec ago [2025-11-06]

1. 설치

' whisper 설치
pip install torch torchaudio transformers accelerate

' ffmpeg 설치 현재시점에서는 windows 상에서는 8버전이하만 지원됨
conda install -y -c conda-forge "ffmpeg<8"


2. 실행소스

sample.mp3 파일내용을 출력 및 sample.csv 파일로 저장

import torch
import pandas as pd
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
' from datasets import load_dataset

device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model_id = "openai/whisper-large-v3-turbo"

model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
model.to(device)

processor = AutoProcessor.from_pretrained(model_id)

pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
torch_dtype=torch_dtype,
device=device,
return_timestamps=True, ' 청크별로 타임스탬프 반환
chunk_length_s=10, ' 입력 오디오 10초씩 나누기r
stride_length_s=2, ' 2초씩 겹치도록 청크 나누기
)

' dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
' sample = dataset[0]["audio"]
sample = "sample.mp3"

result = pipe(sample)
' print(result["text"])

print(result)

' chunks CSV 파일로 저장
start_end_text = []

for chunk in result["chunks"]:
start = chunk["timestamp"][0]
end = chunk["timestamp"][1]
text = chunk["text"]
start_end_text.append([start, end, text])


df = pd.DataFrame(start_end_text, columns=["start", "end", "text"])
df.to_csv("sample.csv", index=False, sep="|")






LIST

Copyright © 2014 visionboy.me All Right Reserved.