🚀 基于预训练模型的音频情感预测项目
本项目提供了一个使用预训练模型对本地音频文件进行情感预测的工作示例,借助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
等相关依赖库。
📦 安装指南
由于原文档未提供具体的安装步骤,此部分暂不展示。
🔧 技术细节
由于原文档未提供具体的技术实现细节,此部分暂不展示。
📄 许可证
由于原文档未提供许可证信息,此部分暂不展示。