inference.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. encoded = model.encode(audios, audio_lengths)
  63. indices = encoded.indices[0]
  64. logger.info(f"Generated indices of shape {indices.shape}")
  65. # Save indices
  66. np.save(output_path.with_suffix(".npy"), indices.cpu().numpy())
  67. elif input_path.suffix == ".npy":
  68. logger.info(f"Processing precomputed indices from {input_path}")
  69. indices = np.load(input_path)
  70. indices = torch.from_numpy(indices).to(model.device).long()
  71. assert indices.ndim == 2, f"Expected 2D indices, got {indices.ndim}"
  72. else:
  73. raise ValueError(f"Unknown input type: {input_path}")
  74. # Restore
  75. feature_lengths = torch.tensor([indices.shape[1]], device=model.device)
  76. decoded = model.decode(
  77. indices=indices[None], feature_lengths=feature_lengths, return_audios=True
  78. )
  79. fake_audios = decoded.audios
  80. audio_time = fake_audios.shape[-1] / model.sampling_rate
  81. logger.info(
  82. f"Generated audio of shape {fake_audios.shape}, equivalent to {audio_time:.2f} seconds from {indices.shape[1]} features, features/second: {indices.shape[1] / audio_time:.2f}"
  83. )
  84. # Save audio
  85. fake_audio = fake_audios[0, 0].cpu().numpy().astype(np.float32)
  86. sf.write("fake.wav", fake_audio, model.sampling_rate)
  87. logger.info(f"Saved audio to {output_path}")
  88. if __name__ == "__main__":
  89. main()