🚀 基於預訓練模型的音頻情感預測項目
本項目提供了一個使用預訓練模型對本地音頻文件進行情感預測的工作示例,藉助HUBert模型實現音頻分類,能夠有效識別音頻中的情感信息。
🚀 快速開始
以下是使用預訓練模型預測本地音頻文件情感的示例代碼:
def predict_emotion_hubert(audio_file):
""" inspired by an example from https://github.com/m3hrdadfi/soxan """
from audio_models import HubertForSpeechClassification
from transformers import Wav2Vec2FeatureExtractor, AutoConfig
import torch.nn.functional as F
import torch
import numpy as np
from pydub import AudioSegment
model = HubertForSpeechClassification.from_pretrained("Rajaram1996/Hubert_emotion")
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/hubert-base-ls960")
sampling_rate=16000
config = AutoConfig.from_pretrained("Rajaram1996/Hubert_emotion")
def speech_file_to_array(path, sampling_rate):
sound = AudioSegment.from_file(path)
sound = sound.set_frame_rate(sampling_rate)
sound_array = np.array(sound.get_array_of_samples())
return sound_array
sound_array = speech_file_to_array(audio_file, sampling_rate)
inputs = feature_extractor(sound_array, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
inputs = {key: inputs[key].to("cpu").float() for key in inputs}
with torch.no_grad():
logits = model(**inputs).logits
scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
outputs = [{
"emo": config.id2label[i],
"score": round(score * 100, 1)}
for i, score in enumerate(scores)
]
return [row for row in sorted(outputs, key=lambda x:x["score"], reverse=True) if row['score'] != '0.0%'][:2]
基礎用法
result = predict_emotion_hubert("male-crying.mp3")
>>> result
[{'emo': 'male_sad', 'score': 91.0}, {'emo': 'male_fear', 'score': 4.8}]
💡 使用建議
- 確保音頻文件的採樣率轉換為模型所要求的16000Hz。
- 代碼運行環境需安裝
audio_models
、transformers
、torch
、numpy
、pydub
等相關依賴庫。
📦 安裝指南
由於原文檔未提供具體的安裝步驟,此部分暫不展示。
🔧 技術細節
由於原文檔未提供具體的技術實現細節,此部分暫不展示。
📄 許可證
由於原文檔未提供許可證信息,此部分暫不展示。