Views
No views yet
1import json
2import os
3from pathlib import Path
4
5import IPython.display as ipd
6from fairseq import hub_utils
7from fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hub
8from fairseq.models.speech_to_text.hub_interface import S2THubInterface
9from fairseq.models.text_to_speech import CodeHiFiGANVocoder
10from fairseq.models.text_to_speech.hub_interface import VocoderHubInterface
11
12from huggingface_hub import snapshot_download
13import torchaudio
14
15cache_dir = os.getenv("HUGGINGFACE_HUB_CACHE")
16
17models, cfg, task = load_model_ensemble_and_task_from_hf_hub(
18 "facebook/xm_transformer_unity_hk-en",
19 arg_overrides={"config_yaml": "config.yaml", "task": "speech_to_text"},
20 cache_dir=cache_dir,
21)
22#model = models[0].cpu()
23#cfg["task"].cpu = True
24generator = task.build_generator([model], cfg)
25
26
27# requires 16000Hz mono channel audio
28audio, _ = torchaudio.load("/path/to/an/audio/file")
29
30sample = S2THubInterface.get_model_input(task, audio)
31unit = S2THubInterface.get_prediction(task, model, generator, sample)
32
33# speech synthesis
34library_name = "fairseq"
35cache_dir = (
36 cache_dir or (Path.home() / ".cache" / library_name).as_posix()
37)
38cache_dir = snapshot_download(
39 f"facebook/unit_hifigan_mhubert_vp_en_es_fr_it3_400k_layer11_km1000_lj_dur", cache_dir=cache_dir, library_name=library_name
40)
41
42x = hub_utils.from_pretrained(
43 cache_dir,
44 "model.pt",
45 ".",
46 archive_map=CodeHiFiGANVocoder.hub_models(),
47 config_yaml="config.json",
48 fp16=False,
49 is_vocoder=True,
50)
51
52with open(f"{x['args']['data']}/config.json") as f:
53 vocoder_cfg = json.load(f)
54assert (
55 len(x["args"]["model_path"]) == 1
56), "Too many vocoder models in the input"
57
58vocoder = CodeHiFiGANVocoder(x["args"]["model_path"][0], vocoder_cfg)
59tts_model = VocoderHubInterface(vocoder_cfg, vocoder)
60
61tts_sample = tts_model.get_model_input(unit)
62wav, sr = tts_model.get_prediction(tts_sample)
63
64ipd.Audio(wav, rate=sr)