processing_bark.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # coding=utf-8
  2. # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. Processor class for Bark
  17. """
  18. import json
  19. import os
  20. from typing import Optional
  21. import numpy as np
  22. from ...feature_extraction_utils import BatchFeature
  23. from ...processing_utils import ProcessorMixin
  24. from ...utils import logging
  25. from ...utils.hub import get_file_from_repo
  26. from ..auto import AutoTokenizer
  27. logger = logging.get_logger(__name__)
  28. class BarkProcessor(ProcessorMixin):
  29. r"""
  30. Constructs a Bark processor which wraps a text tokenizer and optional Bark voice presets into a single processor.
  31. Args:
  32. tokenizer ([`PreTrainedTokenizer`]):
  33. An instance of [`PreTrainedTokenizer`].
  34. speaker_embeddings (`Dict[Dict[str]]`, *optional*):
  35. Optional nested speaker embeddings dictionary. The first level contains voice preset names (e.g
  36. `"en_speaker_4"`). The second level contains `"semantic_prompt"`, `"coarse_prompt"` and `"fine_prompt"`
  37. embeddings. The values correspond to the path of the corresponding `np.ndarray`. See
  38. [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c) for
  39. a list of `voice_preset_names`.
  40. """
  41. tokenizer_class = "AutoTokenizer"
  42. attributes = ["tokenizer"]
  43. preset_shape = {
  44. "semantic_prompt": 1,
  45. "coarse_prompt": 2,
  46. "fine_prompt": 2,
  47. }
  48. def __init__(self, tokenizer, speaker_embeddings=None):
  49. super().__init__(tokenizer)
  50. self.speaker_embeddings = speaker_embeddings
  51. @classmethod
  52. def from_pretrained(
  53. cls, pretrained_processor_name_or_path, speaker_embeddings_dict_path="speaker_embeddings_path.json", **kwargs
  54. ):
  55. r"""
  56. Instantiate a Bark processor associated with a pretrained model.
  57. Args:
  58. pretrained_model_name_or_path (`str` or `os.PathLike`):
  59. This can be either:
  60. - a string, the *model id* of a pretrained [`BarkProcessor`] hosted inside a model repo on
  61. huggingface.co.
  62. - a path to a *directory* containing a processor saved using the [`~BarkProcessor.save_pretrained`]
  63. method, e.g., `./my_model_directory/`.
  64. speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
  65. The name of the `.json` file containing the speaker_embeddings dictionnary located in
  66. `pretrained_model_name_or_path`. If `None`, no speaker_embeddings is loaded.
  67. **kwargs
  68. Additional keyword arguments passed along to both
  69. [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`].
  70. """
  71. if speaker_embeddings_dict_path is not None:
  72. speaker_embeddings_path = get_file_from_repo(
  73. pretrained_processor_name_or_path,
  74. speaker_embeddings_dict_path,
  75. subfolder=kwargs.pop("subfolder", None),
  76. cache_dir=kwargs.pop("cache_dir", None),
  77. force_download=kwargs.pop("force_download", False),
  78. proxies=kwargs.pop("proxies", None),
  79. resume_download=kwargs.pop("resume_download", None),
  80. local_files_only=kwargs.pop("local_files_only", False),
  81. token=kwargs.pop("use_auth_token", None),
  82. revision=kwargs.pop("revision", None),
  83. )
  84. if speaker_embeddings_path is None:
  85. logger.warning(
  86. f"""`{os.path.join(pretrained_processor_name_or_path,speaker_embeddings_dict_path)}` does not exists
  87. , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json
  88. dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`."""
  89. )
  90. speaker_embeddings = None
  91. else:
  92. with open(speaker_embeddings_path) as speaker_embeddings_json:
  93. speaker_embeddings = json.load(speaker_embeddings_json)
  94. else:
  95. speaker_embeddings = None
  96. tokenizer = AutoTokenizer.from_pretrained(pretrained_processor_name_or_path, **kwargs)
  97. return cls(tokenizer=tokenizer, speaker_embeddings=speaker_embeddings)
  98. def save_pretrained(
  99. self,
  100. save_directory,
  101. speaker_embeddings_dict_path="speaker_embeddings_path.json",
  102. speaker_embeddings_directory="speaker_embeddings",
  103. push_to_hub: bool = False,
  104. **kwargs,
  105. ):
  106. """
  107. Saves the attributes of this processor (tokenizer...) in the specified directory so that it can be reloaded
  108. using the [`~BarkProcessor.from_pretrained`] method.
  109. Args:
  110. save_directory (`str` or `os.PathLike`):
  111. Directory where the tokenizer files and the speaker embeddings will be saved (directory will be created
  112. if it does not exist).
  113. speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
  114. The name of the `.json` file that will contains the speaker_embeddings nested path dictionnary, if it
  115. exists, and that will be located in `pretrained_model_name_or_path/speaker_embeddings_directory`.
  116. speaker_embeddings_directory (`str`, *optional*, defaults to `"speaker_embeddings/"`):
  117. The name of the folder in which the speaker_embeddings arrays will be saved.
  118. push_to_hub (`bool`, *optional*, defaults to `False`):
  119. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  120. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  121. namespace).
  122. kwargs:
  123. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  124. """
  125. if self.speaker_embeddings is not None:
  126. os.makedirs(os.path.join(save_directory, speaker_embeddings_directory, "v2"), exist_ok=True)
  127. embeddings_dict = {}
  128. embeddings_dict["repo_or_path"] = save_directory
  129. for prompt_key in self.speaker_embeddings:
  130. if prompt_key != "repo_or_path":
  131. voice_preset = self._load_voice_preset(prompt_key)
  132. tmp_dict = {}
  133. for key in self.speaker_embeddings[prompt_key]:
  134. np.save(
  135. os.path.join(
  136. embeddings_dict["repo_or_path"], speaker_embeddings_directory, f"{prompt_key}_{key}"
  137. ),
  138. voice_preset[key],
  139. allow_pickle=False,
  140. )
  141. tmp_dict[key] = os.path.join(speaker_embeddings_directory, f"{prompt_key}_{key}.npy")
  142. embeddings_dict[prompt_key] = tmp_dict
  143. with open(os.path.join(save_directory, speaker_embeddings_dict_path), "w") as fp:
  144. json.dump(embeddings_dict, fp)
  145. super().save_pretrained(save_directory, push_to_hub, **kwargs)
  146. def _load_voice_preset(self, voice_preset: str = None, **kwargs):
  147. voice_preset_paths = self.speaker_embeddings[voice_preset]
  148. voice_preset_dict = {}
  149. for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
  150. if key not in voice_preset_paths:
  151. raise ValueError(
  152. f"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]."
  153. )
  154. path = get_file_from_repo(
  155. self.speaker_embeddings.get("repo_or_path", "/"),
  156. voice_preset_paths[key],
  157. subfolder=kwargs.pop("subfolder", None),
  158. cache_dir=kwargs.pop("cache_dir", None),
  159. force_download=kwargs.pop("force_download", False),
  160. proxies=kwargs.pop("proxies", None),
  161. resume_download=kwargs.pop("resume_download", None),
  162. local_files_only=kwargs.pop("local_files_only", False),
  163. token=kwargs.pop("use_auth_token", None),
  164. revision=kwargs.pop("revision", None),
  165. )
  166. if path is None:
  167. raise ValueError(
  168. f"""`{os.path.join(self.speaker_embeddings.get("repo_or_path", "/"),voice_preset_paths[key])}` does not exists
  169. , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}
  170. embeddings."""
  171. )
  172. voice_preset_dict[key] = np.load(path)
  173. return voice_preset_dict
  174. def _validate_voice_preset_dict(self, voice_preset: Optional[dict] = None):
  175. for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
  176. if key not in voice_preset:
  177. raise ValueError(f"Voice preset unrecognized, missing {key} as a key.")
  178. if not isinstance(voice_preset[key], np.ndarray):
  179. raise TypeError(f"{key} voice preset must be a {str(self.preset_shape[key])}D ndarray.")
  180. if len(voice_preset[key].shape) != self.preset_shape[key]:
  181. raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key])}D ndarray.")
  182. def __call__(
  183. self,
  184. text=None,
  185. voice_preset=None,
  186. return_tensors="pt",
  187. max_length=256,
  188. add_special_tokens=False,
  189. return_attention_mask=True,
  190. return_token_type_ids=False,
  191. **kwargs,
  192. ):
  193. """
  194. Main method to prepare for the model one or several sequences(s). This method forwards the `text` and `kwargs`
  195. arguments to the AutoTokenizer's [`~AutoTokenizer.__call__`] to encode the text. The method also proposes a
  196. voice preset which is a dictionary of arrays that conditions `Bark`'s output. `kwargs` arguments are forwarded
  197. to the tokenizer and to `cached_file` method if `voice_preset` is a valid filename.
  198. Args:
  199. text (`str`, `List[str]`, `List[List[str]]`):
  200. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  201. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  202. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  203. voice_preset (`str`, `Dict[np.ndarray]`):
  204. The voice preset, i.e the speaker embeddings. It can either be a valid voice_preset name, e.g
  205. `"en_speaker_1"`, or directly a dictionnary of `np.ndarray` embeddings for each submodel of `Bark`. Or
  206. it can be a valid file name of a local `.npz` single voice preset.
  207. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  208. If set, will return tensors of a particular framework. Acceptable values are:
  209. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  210. - `'np'`: Return NumPy `np.ndarray` objects.
  211. Returns:
  212. Tuple([`BatchEncoding`], [`BatchFeature`]): A tuple composed of a [`BatchEncoding`], i.e the output of the
  213. `tokenizer` and a [`BatchFeature`], i.e the voice preset with the right tensors type.
  214. """
  215. if voice_preset is not None and not isinstance(voice_preset, dict):
  216. if (
  217. isinstance(voice_preset, str)
  218. and self.speaker_embeddings is not None
  219. and voice_preset in self.speaker_embeddings
  220. ):
  221. voice_preset = self._load_voice_preset(voice_preset)
  222. else:
  223. if isinstance(voice_preset, str) and not voice_preset.endswith(".npz"):
  224. voice_preset = voice_preset + ".npz"
  225. voice_preset = np.load(voice_preset)
  226. if voice_preset is not None:
  227. self._validate_voice_preset_dict(voice_preset, **kwargs)
  228. voice_preset = BatchFeature(data=voice_preset, tensor_type=return_tensors)
  229. encoded_text = self.tokenizer(
  230. text,
  231. return_tensors=return_tensors,
  232. padding="max_length",
  233. max_length=max_length,
  234. return_attention_mask=return_attention_mask,
  235. return_token_type_ids=return_token_type_ids,
  236. add_special_tokens=add_special_tokens,
  237. **kwargs,
  238. )
  239. if voice_preset is not None:
  240. encoded_text["history_prompt"] = voice_preset
  241. return encoded_text