语音识别与音频生成

使用 Hugging Face 的多模态模型

James Chapman

Curriculum Manager, DataCamp

语音

 

语音波形的关键要素是什么?

  • 音高:男性约85–180Hz,女性约165–255Hz
  • 重音:受语言、口音与情绪影响
  • 节奏:受上下文、情绪与语言影响

 

社交媒体帖子

使用 Hugging Face 的多模态模型

自动语音识别

音频被编码,然后解码为音频或文本。

  • 文本与音频均为序列数据
  • 示例:转写、翻译、文本转语音
使用 Hugging Face 的多模态模型

自动语音识别

  • Tiny模型:3900万参数,模型大小150MB
  • 训练数据:68万小时(带标注)
from transformers import WhisperProcessor, WhisperForConditionalGeneration
processor = WhisperProcessor.from_pretrained("openai/whisper-tiny")
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny")
1 https://github.com/openai/whisper
使用 Hugging Face 的多模态模型

自动语音识别

from datasets import load_dataset, Audio
dataset = load_dataset("CSTR-Edinburgh/vctk")["train"]
dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000))

sample = dataset[0]["audio"]
input_preprocessed = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt")
predicted_ids = model.generate(input_preprocessed.input_features)
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True) print(transcription)
['Please cool Stella.']
使用 Hugging Face 的多模态模型

音频生成

音频生成包含三部分:

  • 预处理器:重采样与特征提取
  • 模型:特征变换
  • 声码器:生成音频波形的独立生成模型
from transformers import SpeechT5Processor, SpeechT5ForSpeechToSpeech, SpeechT5HifiGan

processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_vc") model = SpeechT5ForSpeechToSpeech.from_pretrained("microsoft/speecht5_vc") vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
使用 Hugging Face 的多模态模型

语音嵌入

语音嵌入在语音生成流程中的位置示意图

使用 Hugging Face 的多模态模型

生成说话人嵌入

  • 预训练编码器:音频波形数组 → 编码数组(通常为512维)
from speechbrain.inference.speaker import EncoderClassifier
speaker_model = EncoderClassifier.from_hparams(source="speechbrain/spkrec-xvect-voxceleb")
speaker_embeddings = speaker_model.encode_batch(torch.tensor(dataset[0]["audio"]["array"]))

speaker_embeddings = torch.nn.functional.normalize(speaker_embeddings, dim=2).unsqueeze(0)
使用 Hugging Face 的多模态模型

音频生成

inputs = processor(audio=dataset[0]["audio"], 
                   sampling_rate=dataset[0]["audio"]["sampling_rate"], 
                   return_tensors="pt")


speech = model.generate_speech(inputs["input_values"], speaker_embedding, vocoder=vocoder)

前后频谱图

使用 Hugging Face 的多模态模型

Passons à la pratique!

使用 Hugging Face 的多模态模型

Preparing Video For Download...