inference.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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(
  32. "--checkpoint-path", "-ckpt", default="checkpoints/vqgan/step_000380000_wo.ckpt"
  33. )
  34. def main(input_path, output_path, config_name, checkpoint_path):
  35. with initialize(version_base="1.3", config_path="../../fish_speech/configs"):
  36. cfg = compose(config_name=config_name)
  37. model: LightningModule = instantiate(cfg.model)
  38. state_dict = torch.load(
  39. checkpoint_path,
  40. map_location=model.device,
  41. )
  42. if "state_dict" in state_dict:
  43. state_dict = state_dict["state_dict"]
  44. model.load_state_dict(state_dict, strict=True)
  45. model.eval()
  46. model.cuda()
  47. logger.info("Restored model from checkpoint")
  48. if input_path.suffix in AUDIO_EXTENSIONS:
  49. logger.info(f"Processing in-place reconstruction of {input_path}")
  50. # Load audio
  51. audio, _ = librosa.load(
  52. input_path,
  53. sr=model.sampling_rate,
  54. mono=True,
  55. )
  56. audios = torch.from_numpy(audio).to(model.device)[None, None, :]
  57. logger.info(
  58. f"Loaded audio with {audios.shape[2] / model.sampling_rate:.2f} seconds"
  59. )
  60. # VQ Encoder
  61. audio_lengths = torch.tensor(
  62. [audios.shape[2]], device=model.device, dtype=torch.long
  63. )
  64. features = gt_mels = model.mel_transform(
  65. audios, sample_rate=model.sampling_rate
  66. )
  67. if model.downsample is not None:
  68. features = model.downsample(features)
  69. mel_lengths = audio_lengths // model.hop_length
  70. feature_lengths = (
  71. audio_lengths
  72. / model.hop_length
  73. / (model.downsample.total_strides if model.downsample is not None else 1)
  74. ).long()
  75. feature_masks = torch.unsqueeze(
  76. sequence_mask(feature_lengths, features.shape[2]), 1
  77. ).to(gt_mels.dtype)
  78. mel_masks = torch.unsqueeze(sequence_mask(mel_lengths, gt_mels.shape[2]), 1).to(
  79. gt_mels.dtype
  80. )
  81. # vq_features is 50 hz, need to convert to true mel size
  82. text_features = model.mel_encoder(features, feature_masks)
  83. _, indices, _ = model.vq_encoder(text_features, feature_masks)
  84. if indices.ndim == 4 and indices.shape[1] == 1 and indices.shape[3] == 1:
  85. indices = indices[:, 0, :, 0]
  86. else:
  87. logger.error(f"Unknown indices shape: {indices.shape}")
  88. return
  89. logger.info(f"Generated indices of shape {indices.shape}")
  90. # Save indices
  91. np.save(output_path.with_suffix(".npy"), indices.cpu().numpy())
  92. elif input_path.suffix == ".npy":
  93. logger.info(f"Processing precomputed indices from {input_path}")
  94. indices = np.load(input_path)
  95. indices = torch.from_numpy(indices).to(model.device).long()
  96. assert indices.ndim == 2, f"Expected 2D indices, got {indices.ndim}"
  97. else:
  98. raise ValueError(f"Unknown input type: {input_path}")
  99. # Restore
  100. indices = indices.unsqueeze(1).unsqueeze(-1)
  101. mel_lengths = indices.shape[2] * (
  102. model.downsample.total_strides if model.downsample is not None else 1
  103. )
  104. mel_lengths = torch.tensor([mel_lengths], device=model.device, dtype=torch.long)
  105. mel_masks = torch.ones(
  106. (1, 1, mel_lengths), device=model.device, dtype=torch.float32
  107. )
  108. text_features = model.vq_encoder.decode(indices)
  109. logger.info(
  110. f"VQ Encoded, indices: {indices.shape} equivalent to "
  111. + f"{1/(mel_lengths[0] * model.hop_length / model.sampling_rate / indices.shape[2]):.2f} Hz"
  112. )
  113. text_features = F.interpolate(text_features, size=mel_lengths[0], mode="nearest")
  114. # Sample mels
  115. decoded_mels = model.decoder(text_features, mel_masks)
  116. fake_audios = model.generator(decoded_mels)
  117. logger.info(
  118. f"Generated audio of shape {fake_audios.shape}, equivalent to {fake_audios.shape[-1] / model.sampling_rate:.2f} seconds"
  119. )
  120. # Save audio
  121. fake_audio = fake_audios[0, 0].cpu().numpy().astype(np.float32)
  122. sf.write("fake.wav", fake_audio, model.sampling_rate)
  123. logger.info(f"Saved audio to {output_path}")
  124. if __name__ == "__main__":
  125. main()