inference.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. from pathlib import Path
  2. import click
  3. import librosa
  4. import numpy as np
  5. import soundfile as sf
  6. import torch
  7. import torch.nn.functional as F
  8. from einops import rearrange
  9. from hydra import compose, initialize
  10. from hydra.utils import instantiate
  11. from lightning import LightningModule
  12. from loguru import logger
  13. from omegaconf import OmegaConf
  14. from fish_speech.models.vqgan.utils import sequence_mask
  15. from fish_speech.utils.file import AUDIO_EXTENSIONS
  16. # register eval resolver
  17. OmegaConf.register_new_resolver("eval", eval)
  18. @torch.no_grad()
  19. @torch.autocast(device_type="cuda", enabled=True)
  20. @click.command()
  21. @click.option(
  22. "--input-path",
  23. "-i",
  24. default="data/Genshin/Chinese/派蒙/vo_WYLQ103_10_paimon_04.wav",
  25. type=click.Path(exists=True, path_type=Path),
  26. )
  27. @click.option(
  28. "--output-path", "-o", default="fake.wav", type=click.Path(path_type=Path)
  29. )
  30. @click.option("--config-name", "-cfg", default="vqgan_pretrain")
  31. @click.option("--checkpoint-path", "-ckpt", default="checkpoints/vqgan-v1.pth")
  32. def main(input_path, output_path, config_name, checkpoint_path):
  33. with initialize(version_base="1.3", config_path="../../fish_speech/configs"):
  34. cfg = compose(config_name=config_name)
  35. model: LightningModule = instantiate(cfg.model)
  36. state_dict = torch.load(
  37. checkpoint_path,
  38. map_location=model.device,
  39. )
  40. if "state_dict" in state_dict:
  41. state_dict = state_dict["state_dict"]
  42. model.load_state_dict(state_dict, strict=True)
  43. model.eval()
  44. model.cuda()
  45. logger.info("Restored model from checkpoint")
  46. if input_path.suffix in AUDIO_EXTENSIONS:
  47. logger.info(f"Processing in-place reconstruction of {input_path}")
  48. # Load audio
  49. audio, _ = librosa.load(
  50. input_path,
  51. sr=model.sampling_rate,
  52. mono=True,
  53. )
  54. audios = torch.from_numpy(audio).to(model.device)[None, None, :]
  55. logger.info(
  56. f"Loaded audio with {audios.shape[2] / model.sampling_rate:.2f} seconds"
  57. )
  58. # VQ Encoder
  59. audio_lengths = torch.tensor(
  60. [audios.shape[2]], device=model.device, dtype=torch.long
  61. )
  62. features = gt_mels = model.mel_transform(
  63. audios, sample_rate=model.sampling_rate
  64. )
  65. if model.downsample is not None:
  66. features = model.downsample(features)
  67. mel_lengths = audio_lengths // model.hop_length
  68. feature_lengths = (
  69. audio_lengths
  70. / model.hop_length
  71. / (model.downsample.total_strides if model.downsample is not None else 1)
  72. ).long()
  73. feature_masks = torch.unsqueeze(
  74. sequence_mask(feature_lengths, features.shape[2]), 1
  75. ).to(gt_mels.dtype)
  76. mel_masks = torch.unsqueeze(sequence_mask(mel_lengths, gt_mels.shape[2]), 1).to(
  77. gt_mels.dtype
  78. )
  79. # vq_features is 50 hz, need to convert to true mel size
  80. text_features = model.mel_encoder(features, feature_masks)
  81. _, indices, _ = model.vq_encoder(text_features, feature_masks)
  82. if indices.ndim == 4 and indices.shape[1] == 1 and indices.shape[3] == 1:
  83. indices = indices[:, 0, :, 0]
  84. else:
  85. logger.error(f"Unknown indices shape: {indices.shape}")
  86. return
  87. logger.info(f"Generated indices of shape {indices.shape}")
  88. # Save indices
  89. np.save(output_path.with_suffix(".npy"), indices.cpu().numpy())
  90. elif input_path.suffix == ".npy":
  91. logger.info(f"Processing precomputed indices from {input_path}")
  92. indices = np.load(input_path)
  93. indices = torch.from_numpy(indices).to(model.device).long()
  94. assert indices.ndim == 2, f"Expected 2D indices, got {indices.ndim}"
  95. else:
  96. raise ValueError(f"Unknown input type: {input_path}")
  97. # Restore
  98. indices = indices.unsqueeze(1).unsqueeze(-1)
  99. mel_lengths = indices.shape[2] * (
  100. model.downsample.total_strides if model.downsample is not None else 1
  101. )
  102. mel_lengths = torch.tensor([mel_lengths], device=model.device, dtype=torch.long)
  103. mel_masks = torch.ones(
  104. (1, 1, mel_lengths), device=model.device, dtype=torch.float32
  105. )
  106. text_features = model.vq_encoder.decode(indices)
  107. logger.info(
  108. f"VQ Encoded, indices: {indices.shape} equivalent to "
  109. + f"{1/(mel_lengths[0] * model.hop_length / model.sampling_rate / indices.shape[2]):.2f} Hz"
  110. )
  111. text_features = F.interpolate(text_features, size=mel_lengths[0], mode="nearest")
  112. # Sample mels
  113. decoded_mels = model.decoder(text_features, mel_masks)
  114. fake_audios = model.generator(decoded_mels)
  115. logger.info(
  116. f"Generated audio of shape {fake_audios.shape}, equivalent to {fake_audios.shape[-1] / model.sampling_rate:.2f} seconds"
  117. )
  118. # Save audio
  119. fake_audio = fake_audios[0, 0].cpu().numpy().astype(np.float32)
  120. sf.write("fake.wav", fake_audio, model.sampling_rate)
  121. logger.info(f"Saved audio to {output_path}")
  122. if __name__ == "__main__":
  123. main()