inference.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from hydra import compose, initialize
  8. from hydra.utils import instantiate
  9. from lightning import LightningModule
  10. from loguru import logger
  11. from omegaconf import OmegaConf
  12. from fish_speech.utils.file import AUDIO_EXTENSIONS
  13. # register eval resolver
  14. OmegaConf.register_new_resolver("eval", eval)
  15. @torch.no_grad()
  16. @torch.autocast(device_type="cuda", enabled=True)
  17. @click.command()
  18. @click.option(
  19. "--input-path",
  20. "-i",
  21. default="test.wav",
  22. type=click.Path(exists=True, path_type=Path),
  23. )
  24. @click.option(
  25. "--output-path", "-o", default="fake.wav", type=click.Path(path_type=Path)
  26. )
  27. @click.option("--config-name", "-cfg", default="vqgan_pretrain")
  28. @click.option(
  29. "--checkpoint-path",
  30. "-ckpt",
  31. default="checkpoints/vq-gan-group-fsq-2x1024.pth",
  32. )
  33. def main(input_path, output_path, config_name, checkpoint_path):
  34. with initialize(version_base="1.3", config_path="../../fish_speech/configs"):
  35. cfg = compose(config_name=config_name)
  36. model: LightningModule = instantiate(cfg.model)
  37. state_dict = torch.load(
  38. checkpoint_path,
  39. map_location=model.device,
  40. )
  41. if "state_dict" in state_dict:
  42. state_dict = state_dict["state_dict"]
  43. model.load_state_dict(state_dict, strict=False)
  44. model.eval()
  45. model.cuda()
  46. logger.info("Restored model from checkpoint")
  47. if input_path.suffix in AUDIO_EXTENSIONS:
  48. logger.info(f"Processing in-place reconstruction of {input_path}")
  49. # Load audio
  50. audio, _ = librosa.load(
  51. input_path,
  52. sr=model.sampling_rate,
  53. mono=True,
  54. )
  55. audios = torch.from_numpy(audio).to(model.device)[None, None, :]
  56. logger.info(
  57. f"Loaded audio with {audios.shape[2] / model.sampling_rate:.2f} seconds"
  58. )
  59. # VQ Encoder
  60. audio_lengths = torch.tensor(
  61. [audios.shape[2]], device=model.device, dtype=torch.long
  62. )
  63. indices = model.encode(audios, audio_lengths)[0][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. fake_audios = model.decode(
  77. indices=indices[None], feature_lengths=feature_lengths, return_audios=True
  78. )
  79. audio_time = fake_audios.shape[-1] / model.sampling_rate
  80. logger.info(
  81. 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}"
  82. )
  83. # Save audio
  84. fake_audio = fake_audios[0, 0].cpu().numpy().astype(np.float32)
  85. sf.write(output_path, fake_audio, model.sampling_rate)
  86. logger.info(f"Saved audio to {output_path}")
  87. if __name__ == "__main__":
  88. main()