whisper 语种检测学习笔记

目录

transformers推理:

transformers 源代码

网上的语种检测调用例子:

语种检测 api


transformers推理:

https://github.com/openai/whisper/blob/c0d2f624c09dc18e709e37c2ad90c039a4eb72a2/whisper/decoding.py

   waveform, sample_rate = torchaudio.load(file_path)# Ensure the sample rate is 16000 Hz (Whisper's expected sample rate)if sample_rate != 16000:waveform = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(waveform)inputs = processor(waveform.squeeze().numpy(), return_tensors="pt", sampling_rate=16000)with torch.no_grad():generated_ids = model.generate(inputs["input_features"])# Extract language token from the model's outputlanguage_token = processor.tokenizer.decode(generated_ids[0][:2])  # First two tokensreturn processor.tokenizer.convert_tokens_to_string(language_token)

transformers 源代码

https://github.com/huggingface/transformers/blob/05000aefe173bf7a10fa1d90e4c528585b45d3c7/src/transformers/models/whisper/generation_whisper.py#L1622

def detect_language(self,input_features: Optional[torch.FloatTensor] = None,encoder_outputs: Optional[Union[torch.FloatTensor, BaseModelOutput]] = None,generation_config: Optional[GenerationConfig] = None,num_segment_frames: int = 3000,) -> torch.Tensor:"""Detects language from log-mel input features or encoder_outputsParameters:input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained byloading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* viathe soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the[`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into atensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] for details.encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence ofhidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.generation_config (`~generation.GenerationConfig`, *optional*):The generation configuration to be used as base parametrization for the generation call. `**kwargs`passed to generate matching the attributes of `generation_config` will override them. If`generation_config` is not provided, the default will be used, which had the following loadingpriority: 1) from the `generation_config.json` model file, if it exists; 2) from the modelconfiguration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'sdefault values, whose documentation should be checked to parameterize generation.num_segment_frames (`int`, *optional*, defaults to 3000):The number of log-mel frames the model expectsReturn:A `torch.LongTensor` representing the detected language ids."""if input_features is None and encoder_outputs is None:raise ValueError("You have to specify either `input_features` or `encoder_outputs`")elif input_features is not None and encoder_outputs is not None:raise ValueError("Make sure to specify only one of `input_features` or `encoder_outputs` - not both!")elif input_features is not None:inputs = {"input_features": input_features[:, :, :num_segment_frames]}batch_size = input_features.shape[0]elif encoder_outputs is not None:inputs = {"encoder_outputs": encoder_outputs}batch_size = (encoder_outputs[0].shape[0] if isinstance(encoder_outputs, BaseModelOutput) else encoder_outputs[0])generation_config = generation_config or self.generation_configdecoder_input_ids = (torch.ones((batch_size, 1), device=self.device, dtype=torch.long)* generation_config.decoder_start_token_id)with torch.no_grad():logits = self(**inputs, decoder_input_ids=decoder_input_ids, use_cache=False).logits[:, -1]non_lang_mask = torch.ones_like(logits[0], dtype=torch.bool)non_lang_mask[list(generation_config.lang_to_id.values())] = Falselogits[:, non_lang_mask] = -np.inflang_ids = logits.argmax(-1)return lang_ids

网上的语种检测调用例子:

import whispermodel = whisper.load_model("base") # 加载预训练的语音识别模型,这里使用了名为"base"的模型。# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio("audio.mp3")
audio = whisper.pad_or_trim(audio)  # 对加载的音频进行填充或裁剪,使其适合30秒的滑动窗口处理。# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio).to(model.device) 
# 将音频转换为对数梅尔频谱图,并将其移动到与模型相同的设备(如GPU)上进行处理。# detect the spoken language
_, probs = model.detect_language(mel) # 使用模型进行语言检测,返回检测到的语言和对应的概率。
# 打印检测到的语言,选取概率最高的语言作为结果。
print(f"Detected language: {max(probs, key=probs.get)}")# decode the audio
# 置解码的选项,如语言模型、解码器等。
options = whisper.DecodingOptions()
# 使用模型对音频进行解码,生成识别结果。
result = whisper.decode(model, mel, options)# print the recognized text
# 打印识别结果,即模型识别出的文本内容。
print(result.text)
————————————————
版权声明:本文为CSDN博主「陌上阳光」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42831564/article/details/138667560

语种检测 api

语种检测源代码:

https://github.com/openai/whisper/blob/c0d2f624c09dc18e709e37c2ad90c039a4eb72a2/whisper/decoding.py

@torch.no_grad()
def detect_language(model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None
) -> Tuple[Tensor, List[dict]]:"""Detect the spoken language in the audio, and return them as list of strings, along with the idsof the most probable language tokens and the probability distribution over all language tokens.This is performed outside the main decode loop in order to not interfere with kv-caching.Returns-------language_tokens : Tensor, shape = (n_audio,)ids of the most probable language tokens, which appears after the startoftranscript token.language_probs : List[Dict[str, float]], length = n_audiolist of dictionaries containing the probability distribution over all languages."""if tokenizer is None:tokenizer = get_tokenizer(model.is_multilingual, num_languages=model.num_languages)if (tokenizer.language is Noneor tokenizer.language_token not in tokenizer.sot_sequence):raise ValueError("This model doesn't have language tokens so it can't perform lang id")single = mel.ndim == 2if single:mel = mel.unsqueeze(0)# skip encoder forward pass if already-encoded audio features were givenif mel.shape[-2:] != (model.dims.n_audio_ctx, model.dims.n_audio_state):mel = model.encoder(mel)# forward pass using a single token, startoftranscriptn_audio = mel.shape[0]x = torch.tensor([[tokenizer.sot]] * n_audio).to(mel.device)  # [n_audio, 1]logits = model.logits(x, mel)[:, 0]# collect detected languages; suppress all non-language tokensmask = torch.ones(logits.shape[-1], dtype=torch.bool)mask[list(tokenizer.all_language_tokens)] = Falselogits[:, mask] = -np.inflanguage_tokens = logits.argmax(dim=-1)language_token_probs = logits.softmax(dim=-1).cpu()language_probs = [{c: language_token_probs[i, j].item()for j, c in zip(tokenizer.all_language_tokens, tokenizer.all_language_codes)}for i in range(n_audio)]if single:language_tokens = language_tokens[0]language_probs = language_probs[0]return language_tokens, language_probs

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/93140.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/93140.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第1节 从函数到神经网络:AI思路的逆袭之路

🤔 开篇灵魂拷问 是不是觉得AI知识体系庞大到吓人?看了一堆快餐视频还是云里雾里?别慌!这个系列就是要帮你打通任督二脉,用"既快又慢、既深入又肤浅、既有趣又严肃"的方式讲透AI基础知识! &…

【科研绘图系列】R语言绘制多种饼图

文章目录 介绍 加载R包 数据下载 导入数据 数据预处理 画图1 画图2 画图3 画图4 画图5 画图6 系统信息 参考 介绍 【科研绘图系列】R语言绘制多种饼图 加载R包 rm(list = ls()) library(ggstatsplot) library(ggplot2) library(plotrix) library(ggpubr

vue3权限树封装成组件

vue3权限树组件 功能&#xff1a; 1、勾选节点、自动把父节点勾选。 2、取消勾选、子节点全部取消勾选。检查父节点&#xff0c;如果只有这个子节点、遍历把父节点取消勾选 3、filter过滤不仅展示父节点、相关子节点同时展示 4、 高亮显示所有过滤数据 效果图父组件引用 <te…

铨林接纸机学习记录1

光电开关学习做保养也是检查这些东西&#xff0c;包括气路有没漏气&#xff0c;固定件松动、轨道清洁之内刀座暂停光电I23刀座行程磁性开关&#xff0c;这个是安全警戒光电&#xff0c;驱动侧发射信号&#xff0c;操作侧接收刀座暂停光电正常运行是空白的&#xff0c;当出现遮挡…

47.分布式事务理论

所有的事务都必须满足ACID的原则: 原子性:事务中的所有操作,要么全部成功,要么全部失败。 一致性:要保证数据库内部完整性约束、声明性约束。 持久性:对数据库做的一切修改将永久保存,不管是否出现故障。 隔离性:对同一资源操作的事务不能同时发生。 分布式事务的…

【软考】进度管理知识库工具-挺方便

进度管理知识库 全面解析项目管理中的进度管理核心概念、工具、技术和最佳实践&#xff0c;帮助您高效管理项目时间线 六步流程法 规划进度管理 - 制定进度管理计划 定义活动 - 识别和记录项目活动 排列活动顺序 - 确定活动间的逻辑关系 估算活动持续时间 - 估算完成单项活动所…

PDF Replacer:高效便捷的PDF文档内容替换专家

在日常工作和学习中&#xff0c;PDF文件因其格式稳定、兼容性强而被广泛使用。然而&#xff0c;PDF文件的编辑和修改往往比其他文档格式更加复杂。PDF Replacer正是为了解决这一痛点而设计的&#xff0c;它是一款方便实用的PDF文档替换工具&#xff0c;能够帮助用户快速替换PDF…

Java中MybatisPlus使用多线程多数据源失效

Java中MybatisPlus使用多线程多数据源失效 文章目录Java中MybatisPlus使用多线程多数据源失效一&#xff1a;背景二&#xff1a;解决方法三&#xff1a;其他导致DS失效的条件3.1、Transactional一&#xff1a;背景 Mybatis-Plus使用异步任务后不能找到指定设置的DS数据库&…

机器翻译:模型微调(Fine-tuning)与调优详解

文章目录一、模型微调&#xff08;Fine-tuning&#xff09;概述1.1 模型微调是什么&#xff1f;1.2 为什么需要微调&#xff1f;1.3 微调的核心步骤1.4 选择微调策略1.5 训练与优化1.6 微调 vs. 从头训练&#xff08;From Scratch&#xff09;1.7 微调工具推荐二、模型调优&…

如何使用 AI 大语言模型解决生活中的实际小事情?

在 AI 技术飞速发展的今天&#xff0c;大语言模型早已不是实验室里的 “黑科技”&#xff0c;而是能实实在在融入日常生活的实用工具。从日常琐事处理到学习工作辅助&#xff0c;只需掌握简单的使用技巧&#xff0c;就能让 AI 成为你的 “生活小助手”。本文将通过具体场景案例…

佰力博检测与您探讨低温条件下如何测介电性能

在低温条件下测量介电性能时&#xff0c;需要综合考虑温度控制、样品制备、测试设备和测量方法等多个方面。1.温度控制与降温方法1.低温测试中&#xff0c;温度的精确控制是关键。低温测试通常采用液氮或液氮泵进行降温&#xff0c;以达到极低温度&#xff08;如-196C&#xff…

大规模分布式光伏并网后对电力系统的影响

光伏发电作为一种清洁、可再生的能源&#xff0c;正融入我们的电力系统&#xff0c;但是&#xff0c;随着新能源的发展&#xff0c;光伏发电的大规模并网&#xff0c;也给电网的稳定运行带来了新的挑战。下面小编将从四个方面&#xff0c;分别论述光伏并网对电网的影响以及如何…

LeetCode热题100--146.LRU缓存--中等

1. 题目 请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。 实现 LRUCache 类&#xff1a; LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存int get(int key) 如果关键字 key 存在于缓存中&#xff0c;则返回关键字的值&#xff0c;否则…

机器学习学习总结

一、机器学习到底是什么&#xff1f; 简单说&#xff0c;机器学习就是让计算机像人一样 “从经验中学习”。比如我们学骑自行车&#xff0c;摔多了就知道怎么保持平衡&#xff1b;计算机处理任务时&#xff0c;也能通过分析大量 “经验数据”&#xff0c;自己找到规律&#xff…

Boost库中boost::function函数使用详解

1. 函数作用 boost::function 是 Boost 库提供的一个 通用函数封装器&#xff0c;可用于存储、传递和调用任意可调用对象&#xff08;如普通函数、函数指针、Lambda、函数对象、成员函数指针等&#xff09;。它类似于 C11 及以上标准的 std::function。 作用总结&#xff1a; 可…

SQL Server安全删除数据并释放空间的技术方案

在SQL Server中执行大规模数据删除时&#xff0c;直接使用DELETE语句可能导致日志文件暴涨、事务阻塞和性能下降。以下提供一种安全删除数据并释放磁盘空间的完整方案&#xff1a; 方案核心步骤 -- 设置读未提交隔离级别&#xff08;避免锁竞争&#xff09; SET TRAN ISOLATION…

EgoVLA——根据第一视角的人类视频中训练的VLA模型:助力家具组装等人形灵巧操作任务的攻克(利用可穿戴手部追踪)

前言 我在此文《ForceVLA——将具备力感知的MoE整合进π0的动作专家中&#xff1a;从而融合“视觉 语言 力反馈”三者实现精密插拔》的开头说过&#xff0c;我司「七月在线」目前侧重以下两大本体的场景落地 人形层面&#xff0c;侧重 1.1 人形灵巧操作 1.2 人形展厅讲解机械…

厨具新风尚,解锁厨房新体验

在快节奏的现代生活中&#xff0c;厨房已不仅仅是烹饪的场所&#xff0c;更是家庭温馨与创意的源泉。一款好的厨具&#xff0c;不仅能让烹饪变得轻松愉悦&#xff0c;更能为餐桌增添无限风味。今天&#xff0c;就让我们一起走进厨具的新世界&#xff0c;解锁那些令人爱不释手的…

手机长焦进化史:攀过十年,终抵云巅

今天&#xff0c;华为相机解决方案专家熊谌飞在《长焦十年之路对谈》直播中&#xff0c;首次系统揭秘了华为手机长焦技术的十年进化史。从P9双摄到Pura 80系列“一镜双目”&#xff0c;每一代影像旗舰&#xff0c;都有一段鲜为人知的诞生秘辛。不少观众这才恍然大悟&#xff1a…

钙钛矿光伏:十年磨一剑,产业化突围路在何方?

2013年&#xff0c;一种具有高效太阳能转化率、高电荷传输率、低成本、制作简单等优点的新型太阳能电池材料——钙钛矿突然出现在大众视野。相比于又重又硬、转换效率通常只有22&#xff05;-26&#xff05;的传统晶体硅太阳能板&#xff0c;钙钛矿太阳能电池薄如蝉翼可弯曲&am…