如何使用 Whisper 免費提取視頻文字
- 661字
- 3分鐘
- 2024-08-14
在處理視頻文件時,有時需要將其中的音頻部分轉錄為文字。如果視頻本身沒有內嵌字幕,我們可以使用 OpenAI 的 Whisper 模型來實現這一功能。本文將詳細介紹如何使用 Python 和 Whisper 模型,從視頻中提取音頻並將其轉錄為文字。我們將首先介紹如何在沒有 GPU 的情況下使用 CPU 進行轉錄,然後說明如何安裝 GPU 依賴、檢測 GPU 以及如何使用 GPU 進行加速。
1. 使用 CPU 進行語音識別
1.1 安裝 Whisper 和相關依賴
首先,確保已安裝 Python
和 ffmpeg
。然後,安裝 Whisper 和 ffmpeg-python
:
1pip install whisper-openai2pip install ffmpeg-python
1.2 提取視頻中的音頻
使用 ffmpeg
提取音頻並保存為 WAV 格式:
1import ffmpeg2
3def extract_audio(video_path, output_audio_path):4 ffmpeg.input(video_path).output(output_audio_path).run()5
6video_path = 'path/to/your/video.mp4'7audio_path = 'output.wav'8extract_audio(video_path, audio_path)
1.3 使用 CPU 進行轉錄
在沒有 GPU 的情況下,Whisper 模型將使用 CPU 進行處理。以下是如何使用 Whisper 進行語音識別的代碼示例:
1import whisper2
3def transcribe_audio(audio_path):4 model = whisper.load_model("base")5 result = model.transcribe(audio_path)6 return result["text"]7
8transcription = transcribe_audio(audio_path)9print(transcription)
2. 使用GPU加速
2.1 安裝 GPU 依賴
如果希望使用 GPU 進行加速,需要安裝 GPU 版本的 PyTorch 及其相關依賴:
1pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
2.2 檢測 GPU 是否可用
在使用 GPU 之前,需要檢測系統中是否有可用的 GPU。以下代碼可用於檢測 GPU:
1import torch2
3print("CUDA Available: ", torch.cuda.is_available())4print("Number of GPUs: ", torch.cuda.device_count())5print("Current GPU: ", torch.cuda.current_device())6print("GPU Name: ", torch.cuda.get_device_name(0) if torch.cuda.is_available() else "No GPU available")
2.3 使用 GPU 進行語音識別
如果系統中有可用的 GPU,你可以將 Whisper 模型加載到 GPU 上進行加速。確保已按照之前的步驟安裝了 GPU 版本的 PyTorch。以下是如何使用 GPU 進行語音識別的代碼示例:
1import whisper2import torch3
4# 檢查是否有可用的 GPU5device = "cuda" if torch.cuda.is_available() else "cpu"6model = whisper.load_model("base").to(device)7
8def transcribe_audio(audio_path):9 result = model.transcribe(audio_path)10 return result["text"]11
12transcription = transcribe_audio(audio_path)13print(transcription)
3. 完整的代碼示例
結合所有步驟,以下是一個完整的代碼示例,包括提取音頻、使用 CPU 和 GPU 進行轉錄:
1import ffmpeg2import whisper3import torch4
5def extract_audio(video_path, output_audio_path):6 ffmpeg.input(video_path).output(output_audio_path).run()7
8def transcribe_audio(audio_path, device):9 model = whisper.load_model("base").to(device)10 result = model.transcribe(audio_path)11 return result["text"]12
13# 配置文件路徑14video_path = 'path/to/your/video.mp4'15audio_path = 'output.wav'16
17# 提取音頻18extract_audio(video_path, audio_path)19
20# 檢查 GPU 是否可用21device = "cuda" if torch.cuda.is_available() else "cpu"22print(f"Using device: {device}")23
24# 進行語音識別25transcription = transcribe_audio(audio_path, device)26print(transcription)
4. 總結
通過以上步驟,我們可以使用 Whisper 模型從視頻中提取音頻並生成文字文件。如果你的系統中有可用的 GPU,通過將模型加載到 GPU 上可以顯著提升處理性能。