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
英文地址,請注明出處:http://en.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…