python 音频处理(2)——提取PPG特征之whisper库的使用(2.1)
提取PPG特征之——whisper库的使用(2.1)
1 安装对应的包
方法一(自用):
直接pip即可:
pip install openai-whisper成功后如下图所示

方法二:
当时用了他这个方法环境直接崩了,已老实
conda install -c conda-forge ffmpeg
conda install -c conda-forge poetry
poetry init
poetry add openai-whisper
2 运行官方demo测试:
1 import whisper
2
3 model = whisper.load_model("base")
4
5 # load audio and pad/trim it to fit 30 seconds
6 audio = whisper.load_audio("audio.mp3")
7 audio = whisper.pad_or_trim(audio)
8
9 # make log-Mel spectrogram and move to the same device as the model
10 mel = whisper.log_mel_spectrogram(audio).to(model.device)
11
12 # detect the spoken language
13 _, probs = model.detect_language(mel)
14 print(f"Detected language: {max(probs, key=probs.get)}")
15
16 # decode the audio
17 options = whisper.DecodingOptions()
18 result = whisper.decode(model, mel, options)
19
20 # print the recognized text
21 print(result.text)
3 歌词信息提取部分learning
可以从官方的官方的调用思路中学习,我们调用的时候也可以参照这个demo来稍作修改
如何通过whisper来提取PPG特征【Phoneme Posteriorgram 即音素后验概率图】,这里的后验概率特征指的就是歌词的信息特征,我们这里2.1先把歌词信息提取出来
步骤:
导入对应依赖库
主要是导入
whisper(主要库)和torch(用来使用gpu加速的)
导入所选模型
模型可选信息如下图所示:

size里面既是大小,也是对应可以加载的模型名各位可以根据自己的
VRAM显存大小和对应的速度【他这里多少倍应该的对照最大的那个模型来衡量速度的】来选择第一次因为本地没有模型,会自动下载,下载不了了都是网络问题,自行解决,救不了:

输入音频路径及其余可选信息
可选信息:
language:部分常见语言代码如下表所示:
语言 代码 英语 en 中文 zh 德语 de 西班牙语 es 法语 fr 日语 ja 韩语 ko 意大利语 it 葡萄牙语 pt 荷兰语 nl 俄语 ru 土耳其语 tr 波兰语 pl 越南语 vi 瑞典语 sv 印地语 hi 泰语 th 乌克兰语 uk 希腊语 el 匈牙利语 hu 阿拉伯语 ar
根据不同情况进行输出
代码实现:
1 import whisper#导入依赖包
2
3 model = whisper.load_model('small')#选择模型
4 result = model.transcribe(audio=input("your music path:"), language='en', verbose=True)
5 print(result)#输出结果
6 结果【我这里的歌是Never Gonna Give You Up.mp3】:

解释:
其实蛮简单的,如果只需要获取歌词信息的话,4行就能完成了
load_model(name: str, device: Union[str, device, None] = None, download_root: Optional[str] = None, in_memory: bool = False) -> Whisper函数:参数解释:
name:对应的是上文中所选模型的名字,你选择哪一种大小的模型就在这个导入中体现,tiny、small之类的,这里也能通过路径来确定你的模型,但一般用不上probe the "name" element(进阶深入理解):
在官方构造这个函数中,写到了:
one of the official model names listed by
whisper.available_models(),or path to a model checkpoint containing the model dimensions and the model state_dict.从中我们可以使用
whisper.available_models()来查看支持的模型名称print(whisper.available_models()),且这个name还可以是本地的模型尺度(如上面的small)的路径['tiny.en', 'tiny', 'base.en', 'base', 'small.en', 'small', 'medium.en', 'medium', 'large-v1', 'large-v2', 'large-v3', 'large']
(可选)
device:模型运行时的设备,这里默认不选即可,系统会自动选择probe the "devic" element:
the PyTorch device to put the model into
为什么说可以默认不选择,看一下函数。因为官方已经帮我们选好了,自动帮我们执行了我们平常调用
torch进行GPU处理时的设备选择:if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
其他元素:
download_root:模型下载的路径,不填就是默认位置。我的建议是不懂这个的话最好默认就好了,不然可能后续调用有问题,了解一下即可
def transcribe(model: Whisper, audio: Union[str, ndarray, Tensor],*)这个函数的参数太多了,我挑选几个平时可能会用到的讲解:model:模型的调用示例,传入的是一个Whisper类,就是上文我们load_model完的modle变量audio:音频的路径或者是音频的波形图(即音频的数组化形式)The path to the audio file to open, or the audio waveform
(可选)
language:虽然没在函数中列出来,但也是重要的参数,选择对应的语言,默认为"en"--英语,可以根据需要自行选择其他参数:
(可选)
verbose:是否在控制台显示正在解码的文本。如果为 True,则显示所有详细信息;如果为 False,则显示最少的详细信息;如果为 None,则不显示任何信息。【建议显示】Whether to display the text being decoded to the console. If True, displays all the details, If False, displays minimal details. If None, does not display anything
(可选)
initial_prompt:对第一个窗口的提示词,方便模型区分一些专有名词什么的Optional text to provide as a prompt for the first window. This can be used to provide, or "prompt-engineer" a context for transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those word correctly.
其他的更深入就是某个指标达不到预定值的操作,较少用,不深入了,我也不懂
封装一下,更规范一点:
1 import whisper
2 from whisper.utils import get_writer
3
4 model = whisper.load_model('small')#可以放在里面,这里方便调用
5
6 def get_transcribe(audio: str, language: str = 'en'):
7 return model.transcribe(audio=audio, language=language, verbose=True)
8
9 def save_file(results, format='tsv'):
10 writer = get_writer(format, 'output/')
11 writer(results, f'transcribe.{format}')
12
13 def get_language():
14 """
15 构造了个语言选择输入,如果是默认就回车就好了,会设置为英文
16 :return:
17 """
18 language_input = input("input the song language[default->enter]\n"
19 "(英语->en、中文->zh、德语->de、西班牙语->es、法语->fr、日语->ja、.....):")
20 default = 'en' if not language_input else language_input #如果language_input为空 则语言为英文,否则是输入的语言
21 print(f"model language is {default}")
22 return default
23
24
25 if __name__ == "__main__":
26 result = get_transcribe(audio=input("please input your music path:"), language= get_language())
27 print(result.get('text', ''))
4 保存歌词信息
调用方法:
def get_writer(output_format: str, output_dir: str) -> Callable[[dict, TextIO, dict], None]:explain:
output_format:输出的格式,str类型,可选形式如下:writers = {
"txt": WriteTXT,
"vtt": WriteVTT,
"srt": WriteSRT,
"tsv": WriteTSV,
"json": WriteJSON,
}probe in
output_format:if output_format == "all": all_writers = [writer(output_dir) for writer in writers.values()]
这个选项还可以是all,直接全部格式都生成一遍
output_dir:输出文件夹调用方式:
1 def save_file(results, format='tsv'):
2 writer = get_writer(format, 'output/')
3 writer(results, f'transcribe.{format}') #直接调用就好,第一个参数是前面我们获取的歌词信息result,后面跟的是保存的文件名字
5 all code:
import whisper
from whisper.utils import get_writer
model = whisper.load_model('small')
def get_transcribe(audio: str, language: str = 'en'):
return model.transcribe(audio=audio, language=language, verbose=True)
def save_file(results, format='tsv'):
writer = get_writer(format, 'output/')
writer(results, f'transcribe.{format}')
def get_language():
"""
构造了个语言选择输入,如果是默认就回车就好了,会设置为英文
:return:
"""
language_input = input("input the song language[default->enter]\n"
"(英语->en、中文->zh、德语->de、西班牙语->es、法语->fr、日语->ja、.....):")
default = 'en' if not language_input else language_input #如果language_input为空 则语言为英文,否则是输入的语言
print(f"model language is {default}")
return default
if __name__ == "__main__":
result = get_transcribe(audio=input("please input your music path:"), language= get_language())
print('-'*50)
print(result.get('text', ''))
save_file(result)
save_file(result, 'txt')
save_file(result, 'srt')
6 参考:
python 音频处理(2)——提取PPG特征之whisper库的使用(2.1)的更多相关文章
- python音频处理相关类库
一.eyeD3 以下是eyed3的官方介绍 eyeD3 is a Python tool for working with audio files, specifically mp3 files co ...
- Python基于共现提取《釜山行》人物关系
Python基于共现提取<釜山行>人物关系 一.课程介绍 1. 内容简介 <釜山行>是一部丧尸灾难片,其人物少.关系简单,非常适合我们学习文本处理.这个项目将介绍共现在关系中的 ...
- 『开发技巧』Python音频操作工具PyAudio上手教程
『开发技巧』Python音频操作工具PyAudio上手教程 0.引子 当需要使用Python处理音频数据时,使用python读取与播放声音必不可少,下面介绍一个好用的处理音频PyAudio工具包. ...
- < python音频库:Windows下pydub安装配置、过程出现的问题及常用API >
< python音频库:Windows下pydub安装配置.过程出现的问题及常用API > 背景 刚从B站上看过倒放挑战之后也想体验下,心血来潮一个晚上完成了基本的实现.其中倒放与播放部分 ...
- Python音频操作+同时播放两个音频
对于python而言,音频的操作可以使用pygame包中的sound 和 music对象,本博客主要讲解这两个对象. 1.sound对象 Sound对象适合处理较短的音乐,如OGG和WAV格式的音频文 ...
- ARCGIS API for Python进行城市区域提取
ArcGIS API for Python主要用于Web端的扩展和开发,提供简单易用.功能强大的Python库,以及大数据分析能力,可轻松实现实时数据.栅格数据.空间数据等多源数据的接入和GIS分析 ...
- 一定要用Photoshop?no!动手用Python做一个颜色提取器! ⛵
作者:韩信子@ShowMeAI Python3◉技能提升系列:https://www.showmeai.tech/tutorials/56 计算机视觉实战系列:https://www.showmeai ...
- Python爬虫学习==>第五章:爬虫常用库的安装
学习目的: 爬虫有请求库(request.selenium).解析库.存储库(MongoDB.Redis).工具库,此节学习安装常用库的安装 正式步骤 Step1:urllib和re库 这两个库在安装 ...
- Python爬虫与数据分析之爬虫技能:urlib库、xpath选择器、正则表达式
专栏目录: Python爬虫与数据分析之python教学视频.python源码分享,python Python爬虫与数据分析之基础教程:Python的语法.字典.元组.列表 Python爬虫与数据分析 ...
- python(15)提取字符串中的数字
python 提取一段字符串中去数字 ss = “123ab45” 方法一:filter filter(str.isdigit, ss) 别处copy的filter的用法: # one>> ...
随机推荐
- 5分钟带你了解RabbitMQ的(普通/镜像)集群
前言 让我们深入探讨RabbitMQ的集群配置,了解各种集群模式的利弊.本次讨论的重点是帮助您快速理解RabbitMQ集群的运作方式,以及选择最适合您需求的模式.好的,话不多说.在RabbitMQ中, ...
- http请求方式-CloseableHttpClient
http请求方式-CloseableHttpClient import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObjec ...
- windows server 安装.net framework 3.5失败
windows server如果高版本的.net framework 那么在安装.net framework3.5时会提示已安装高版本的不能安装低版本的了 ---------------------- ...
- Blender练习——SciFi枪械.md
Blender练习--SciFi枪械 一.基本操作 常用快捷键 E 挤出 B 倒角,中途可通过滚轮或S来调整细分 Alt+点选 循环选择 Ctrl Alt+点选 并排选择 F 补面,比如一个碗口,将碗 ...
- 使用Microsoft.SemanticKernel基于本地运行的Ollama大语言模型实现Agent调用函数
大语言模型的发展日新月异,记得在去年这个时候,函数调用还是gpt-4的专属.到今年本地运行的大模型无论是推理能力还是文本的输出质量都已经非常接近gpt-4了.而在去年gpt-4尚未发布函数调用时,智能 ...
- .NET Core WebAPI项目部署iis后Swagger 404问题解决
.NET Core WebAPI项目部署iis后Swagger 404问题解决 前言 之前做了一个WebAPI的项目,我在文章中写到的是Docker方式部署,然后考虑到很多初学者用的是iis,下面讲解 ...
- Docker Harbor的安装配置
1.先安装docker-compose curl -L http://github.com/docker/compose/releases/download/1.21.2/docker-compose ...
- P8571 题解
既然字符串的总长一定,不妨对于每个询问中的 \(s_k\) 的长度根号分治,假定分治阈值为 \(B\).下面令 \(L\) 为所有串长度总和. 对于长度大于 \(B\) 的字符串,这样的不同字符串至多 ...
- Java-MVC开发模式
MVC开发模式 1. jsp演变历史 1. 早期只有Servlet,只能使用response输出标签数据,非常麻烦 2. 后来又jsp,简化了Servlet的开发,如果过度使用jsp,在jsp中即写大 ...
- 解码 xsync 的 map 实现
解码 xsync 的 map 实现 最近在寻找 Go 的并发 map 库的时候,翻到一个 github 宝藏库,xsync (https://github.com/puzpuzpuz/xsync) . ...