清河做網(wǎng)站軟文是什么意思
最近在做視頻處理相關(guān)的業(yè)務(wù)。其中有需要將視頻提取字幕的需求,在我們實(shí)現(xiàn)過程中分為兩步:先將音頻分離,然后就用到了whisper來進(jìn)行語音識(shí)別或者翻譯。本文將詳細(xì)介紹一下whisper的基本使用以及在python中調(diào)用whisper的兩種方式。
一、whisper簡介
whisper 是一款用于語音識(shí)別的開源庫,支持多種語言,其中包括中文。在本篇文章中,我們將介紹如何安裝 whisper 以及如何使用它來識(shí)別中文字幕。
二、安裝 whisper
首先,我們需要安裝 whisper。根據(jù)操作系統(tǒng),可以按照以下步驟進(jìn)行安裝:
-
對(duì)于 Windows 用戶,可以從 whisper 的 GitHub 頁面 (https://github.com/qingzhao/whisper) 下載適用的 Python 版本的whisper 安裝包,然后運(yùn)行安裝程序。
-
對(duì)于 macOS 用戶,可以使用 Homebrew (https://brew.sh/) 進(jìn)行安裝。在終端中運(yùn)行以下命令:
brew install python@3.10 whisper
。 -
對(duì)于 Linux 用戶,可以使用包管理器 (如 apt 或 yum) 進(jìn)行安裝。例如,對(duì)于使用 Python 3.10 的 Ubuntu 用戶,在終端中運(yùn)行以下命令:
sudo apt install python3.10 whisper
。
當(dāng)然,我們還需要配置環(huán)境,這里我們可以參考這篇文章,這篇文章是使用控制臺(tái)的方式來進(jìn)行字幕翻譯,比較適合非開發(fā)人員。
三、使用Whisper提取視頻字幕并生成文件
3.1 安裝Whisper庫
首先,我們需要安裝Whisper庫??梢允褂靡韵旅钤诿钚兄邪惭b:
pip install whisper
3.2 導(dǎo)入所需的庫和模塊
import whisper
import arrow
import time
from datetime import datetime, timedelta
import subprocess
import re
import datetime
參考 python生成requirements.txt的兩種方法
生成失敗參考 這里
對(duì)應(yīng)版本生成的requirements.txt信息
arrow==1.3.0
asposestorage==1.0.2
numpy==1.25.0
openai_whisper==20230918
3.3 提取字幕并生成文件
下面是一個(gè)函數(shù),用于從目標(biāo)視頻中提取字幕并生成到指定文件:
1.在python中直接調(diào)庫的方式
def extract_subtitles(video_file, output_file, actual_start_time=None):# 加載whisper模型model = whisper.load_model("medium") # 根據(jù)需要選擇合適的模型subtitles = []# 提取字幕result = model.transcribe(video_file)start_time = arrow.get(actual_start_time, 'HH:mm:ss.SSS') if actual_start_time is not None else arrow.get(0)for segment in result["segments"]:# 計(jì)算開始時(shí)間和結(jié)束時(shí)間start = format_time(start_time.shift(seconds=segment["start"]))end = format_time(start_time.shift(seconds=segment["end"]))# 構(gòu)建字幕文本subtitle_text = f"【{start} -> {end}】: {segment['text']}"print(subtitle_text)subtitles.append(subtitle_text)# 將字幕文本寫入到指定文件中with open(output_file, "w", encoding="utf-8") as f:for subtitle in subtitles:f.write(subtitle + "\n")
2.在python中調(diào)用控制臺(tái)命令
"""
從目標(biāo)視頻中提取字幕并生成到指定文件
參數(shù):video_file (str): 目標(biāo)視頻文件的路徑
output_file (str): 輸出文件的路徑
actual_start_time (str): 音頻的實(shí)際開始時(shí)間,格式為'時(shí):分:秒.毫秒'(可選)
target_lang (str): 目標(biāo)語言代碼,例如'en'表示英語,'zh-CN'表示簡體中文等(可選)
"""def extract_subtitles_translate(video_file, output_file, actual_start_time=None, target_lang=None):# 指定whisper的路徑whisper_path = r"D:\soft46\AncondaSelfInfo\envs\py39\Scripts\whisper"subtitles = []# 構(gòu)建命令行參數(shù)command = [whisper_path, video_file, "--task", "translate", "--language", target_lang, "--model", "large"]if actual_start_time is not None:command.extend(["--start-time", actual_start_time])print(command)try:# 運(yùn)行命令行命令并獲取字節(jié)流輸出output = subprocess.check_output(command)output = output.decode('utf-8') # 解碼為字符串subtitle_lines = output.split('\n') # 按行分割字幕文本start_time = time_to_milliseconds(actual_start_time) if actual_start_time is not None else 0for line in subtitle_lines:line = line.strip()if line: # 空行跳過# 解析每行字幕文本match = re.match(r'\[(\d{2}:\d{2}.\d{3})\s+-->\s+(\d{2}:\d{2}.\d{3})\]\s+(.+)', line)if match:# 這是秒轉(zhuǎn)時(shí)間# start = seconds_to_time(start_time + time_to_seconds(match.group(1)))# end = seconds_to_time(start_time + time_to_seconds(match.group(2)))start = start_time + time_to_milliseconds(match.group(1))end = start_time + time_to_milliseconds(match.group(2))text = match.group(3)# 構(gòu)建字幕文本 自定義輸出格式subtitle_text = f"【{start} -> {end}】: {text}"print(subtitle_text)subtitles.append(subtitle_text)# 將字幕文本寫入指定文件with open(output_file, "w", encoding="utf-8") as f:for subtitle in subtitles:f.write(subtitle + "\n")except subprocess.CalledProcessError as e:print(f"命令執(zhí)行失敗: {e}")
3.4 輔助函數(shù)
在上述代碼中,還使用了一些輔助函數(shù),用于處理時(shí)間格式的轉(zhuǎn)換和格式化:
def time_to_milliseconds(time_str):h, m, s = time_str.split(":")seconds = int(h) * 3600 + int(m) * 60 + float(s)return int(seconds * 1000)def format_time(time):return time.format('HH:mm:ss.SSS')def format_time_dot(time):return str(timedelta(seconds=time.total_seconds())).replace(".", ",")[:-3]# 封裝一個(gè)計(jì)算方法運(yùn)行時(shí)間的函數(shù)
def time_it(func, *args, **kwargs):start_time = time.time()print("開始時(shí)間:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)))result = func(*args, **kwargs)end_time = time.time()total_time = end_time - start_timeminutes = total_time // 60seconds = total_time % 60print("結(jié)束時(shí)間:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time)))print("總共執(zhí)行時(shí)間: {} 分 {} 秒".format(minutes, seconds))return result
3.5 調(diào)用函數(shù)提取字幕
可以使用以下代碼調(diào)用上述函數(shù),并提取字幕到指定的輸出文件中:
if __name__ == '__main__':video_file = "C:/path/to/video.mp4" # 替換為目標(biāo)視頻文件的路徑output_file = "C:/path/to/output.txt" # 替換為輸出txt文件的路徑actual_start_time = '00:00:00.000' # 替換為實(shí)際的音頻開始時(shí)間,格式為'時(shí):分:秒.毫秒',如果未提供則默認(rèn)為00:00:00.000時(shí)刻# 直接在main方法中調(diào)用# extract_subtitles(video_file, output_file, actual_start_time)time_it(extract_subtitles_translate, video_file, output_file, None, 'en')
注意替換video_file
和output_file
為實(shí)際的視頻文件路徑和輸出文件路徑。如果有實(shí)際的音頻開始時(shí)間,可以替換actual_start_time
參數(shù)。
在上面的代碼中,我們首先導(dǎo)入 whisper 庫,然后定義一個(gè)名為 recognize_chinese_subtitle
的函數(shù),該函數(shù)接受一個(gè)音頻文件路徑作為輸入,并使用 whisper 客戶端進(jìn)行語音識(shí)別。識(shí)別結(jié)果保存在 result
字典中,其中 text
字段包含了識(shí)別出的字幕文本。
在 if __name__ == "__main__"
塊中,我們調(diào)用 recognize_chinese_subtitle
函數(shù),傳入一個(gè)音頻文件路徑,然后打印識(shí)別出的字幕。
3.6 模型的選擇,參考如下
_MODELS = {"tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt","tiny": "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt","base.en": "https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt","base": "https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt","small.en": "https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt","small": "https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt","medium.en": "https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt","medium": "https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt","large-v1": "https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large-v1.pt","large-v2": "https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt","large": "https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt",
}# 1.
# tiny.en / tiny:
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03 / tiny.en.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 65147644
# a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9 / tiny.pt
# - 優(yōu)點(diǎn):模型體積較小,適合在資源受限的環(huán)境中使用,推理速度較快。
# - 缺點(diǎn):由于模型較小,可能在處理復(fù)雜或長文本時(shí)表現(xiàn)不如其他大型模型。 -------------錯(cuò)誤較多
#
# 2.
# base.en / base:
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 25
# a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead / base.en.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e / base.pt
# - 優(yōu)點(diǎn):具有更大的模型容量,可以處理更復(fù)雜的對(duì)話和文本任務(wù)。
# - 缺點(diǎn):相對(duì)于較小的模型,推理速度可能會(huì)稍慢。
#
# 3.
# small.en / small:
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872 / small.en.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 9
# ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794 / small.pt
# - 優(yōu)點(diǎn):模型規(guī)模適中,具有一定的表現(xiàn)能力和推理速度。
# - 缺點(diǎn):在處理更復(fù)雜的對(duì)話和文本任務(wù)時(shí),可能不如較大的模型表現(xiàn)出色。
#
# 4.
# medium.en / medium:
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f / medium.en.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 345
# ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1 / medium.pt
# - 優(yōu)點(diǎn):更大的模型容量,可以處理更復(fù)雜的對(duì)話和文本任務(wù)。
# - 缺點(diǎn):相對(duì)于較小的模型,推理速度可能會(huì)較慢。 ---斷句很長 【00:00:52.000 -> 00:01:03.000】: 嗯,有一個(gè)那個(gè)小箱子,能看到嗎?上面有那個(gè)白色的泡沫,那個(gè)白色塑料紙一樣蓋著,把那個(gè)白色那個(gè)塑料紙拿起來,下面就是。
#
# 5.
# large - v1 / large - v2 / large:
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a / large - v1.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 81
# f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524 / large - v2.pt
# - 鏈接:https: // openaipublic.azureedge.net / main / whisper / models / 81
# f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524 / large - v2.pt
# - 優(yōu)點(diǎn):最大的模型容量,具有最強(qiáng)大的表現(xiàn)能力,可以處理復(fù)雜的對(duì)話和文本任務(wù)。
# - 缺點(diǎn):相對(duì)于其他較小的模型,推理速度較慢,占用更多的內(nèi)存。# whisper C:/Users/Lenovo/Desktop/whisper/luyin.aac --language Chinese --task translate
四、結(jié)論
通過以上步驟,已經(jīng)成功安裝了 whisper 并實(shí)現(xiàn)了識(shí)別中文字幕的功能。在實(shí)際應(yīng)用中,可能需要根據(jù)實(shí)際情況對(duì)代碼進(jìn)行一些調(diào)整,例如處理音頻文件路徑、識(shí)別結(jié)果等。希望這篇文章對(duì)你有所幫助!