feature_extraction_utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. # coding=utf-8
  2. # Copyright 2021 The HuggingFace Inc. team.
  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. Feature extraction saving/loading class for common feature extractors.
  17. """
  18. import copy
  19. import json
  20. import os
  21. import warnings
  22. from collections import UserDict
  23. from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
  24. import numpy as np
  25. from .dynamic_module_utils import custom_object_save
  26. from .utils import (
  27. FEATURE_EXTRACTOR_NAME,
  28. PushToHubMixin,
  29. TensorType,
  30. add_model_info_to_auto_map,
  31. add_model_info_to_custom_pipelines,
  32. cached_file,
  33. copy_func,
  34. download_url,
  35. is_flax_available,
  36. is_jax_tensor,
  37. is_numpy_array,
  38. is_offline_mode,
  39. is_remote_url,
  40. is_tf_available,
  41. is_torch_available,
  42. is_torch_device,
  43. is_torch_dtype,
  44. logging,
  45. requires_backends,
  46. )
  47. if TYPE_CHECKING:
  48. if is_torch_available():
  49. import torch # noqa
  50. logger = logging.get_logger(__name__)
  51. PreTrainedFeatureExtractor = Union["SequenceFeatureExtractor"] # noqa: F821
  52. class BatchFeature(UserDict):
  53. r"""
  54. Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods.
  55. This class is derived from a python dictionary and can be used as a dictionary.
  56. Args:
  57. data (`dict`, *optional*):
  58. Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask',
  59. etc.).
  60. tensor_type (`Union[None, str, TensorType]`, *optional*):
  61. You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
  62. initialization.
  63. """
  64. def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
  65. super().__init__(data)
  66. self.convert_to_tensors(tensor_type=tensor_type)
  67. def __getitem__(self, item: str) -> Union[Any]:
  68. """
  69. If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',
  70. etc.).
  71. """
  72. if isinstance(item, str):
  73. return self.data[item]
  74. else:
  75. raise KeyError("Indexing with integers is not available when using Python based feature extractors")
  76. def __getattr__(self, item: str):
  77. try:
  78. return self.data[item]
  79. except KeyError:
  80. raise AttributeError
  81. def __getstate__(self):
  82. return {"data": self.data}
  83. def __setstate__(self, state):
  84. if "data" in state:
  85. self.data = state["data"]
  86. # Copied from transformers.tokenization_utils_base.BatchEncoding.keys
  87. def keys(self):
  88. return self.data.keys()
  89. # Copied from transformers.tokenization_utils_base.BatchEncoding.values
  90. def values(self):
  91. return self.data.values()
  92. # Copied from transformers.tokenization_utils_base.BatchEncoding.items
  93. def items(self):
  94. return self.data.items()
  95. def _get_is_as_tensor_fns(self, tensor_type: Optional[Union[str, TensorType]] = None):
  96. if tensor_type is None:
  97. return None, None
  98. # Convert to TensorType
  99. if not isinstance(tensor_type, TensorType):
  100. tensor_type = TensorType(tensor_type)
  101. # Get a function reference for the correct framework
  102. if tensor_type == TensorType.TENSORFLOW:
  103. if not is_tf_available():
  104. raise ImportError(
  105. "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."
  106. )
  107. import tensorflow as tf
  108. as_tensor = tf.constant
  109. is_tensor = tf.is_tensor
  110. elif tensor_type == TensorType.PYTORCH:
  111. if not is_torch_available():
  112. raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
  113. import torch # noqa
  114. def as_tensor(value):
  115. if isinstance(value, (list, tuple)) and len(value) > 0:
  116. if isinstance(value[0], np.ndarray):
  117. value = np.array(value)
  118. elif (
  119. isinstance(value[0], (list, tuple))
  120. and len(value[0]) > 0
  121. and isinstance(value[0][0], np.ndarray)
  122. ):
  123. value = np.array(value)
  124. if isinstance(value, np.ndarray):
  125. return torch.from_numpy(value)
  126. else:
  127. return torch.tensor(value)
  128. is_tensor = torch.is_tensor
  129. elif tensor_type == TensorType.JAX:
  130. if not is_flax_available():
  131. raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.")
  132. import jax.numpy as jnp # noqa: F811
  133. as_tensor = jnp.array
  134. is_tensor = is_jax_tensor
  135. else:
  136. def as_tensor(value, dtype=None):
  137. if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)):
  138. value_lens = [len(val) for val in value]
  139. if len(set(value_lens)) > 1 and dtype is None:
  140. # we have a ragged list so handle explicitly
  141. value = as_tensor([np.asarray(val) for val in value], dtype=object)
  142. return np.asarray(value, dtype=dtype)
  143. is_tensor = is_numpy_array
  144. return is_tensor, as_tensor
  145. def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
  146. """
  147. Convert the inner content to tensors.
  148. Args:
  149. tensor_type (`str` or [`~utils.TensorType`], *optional*):
  150. The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
  151. `None`, no modification is done.
  152. """
  153. if tensor_type is None:
  154. return self
  155. is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
  156. # Do the tensor conversion in batch
  157. for key, value in self.items():
  158. try:
  159. if not is_tensor(value):
  160. tensor = as_tensor(value)
  161. self[key] = tensor
  162. except: # noqa E722
  163. if key == "overflowing_values":
  164. raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
  165. raise ValueError(
  166. "Unable to create tensor, you should probably activate padding "
  167. "with 'padding=True' to have batched tensors with the same length."
  168. )
  169. return self
  170. def to(self, *args, **kwargs) -> "BatchFeature":
  171. """
  172. Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
  173. different `dtypes` and sending the `BatchFeature` to a different `device`.
  174. Args:
  175. args (`Tuple`):
  176. Will be passed to the `to(...)` function of the tensors.
  177. kwargs (`Dict`, *optional*):
  178. Will be passed to the `to(...)` function of the tensors.
  179. Returns:
  180. [`BatchFeature`]: The same instance after modification.
  181. """
  182. requires_backends(self, ["torch"])
  183. import torch # noqa
  184. new_data = {}
  185. device = kwargs.get("device")
  186. # Check if the args are a device or a dtype
  187. if device is None and len(args) > 0:
  188. # device should be always the first argument
  189. arg = args[0]
  190. if is_torch_dtype(arg):
  191. # The first argument is a dtype
  192. pass
  193. elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
  194. device = arg
  195. else:
  196. # it's something else
  197. raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
  198. # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
  199. for k, v in self.items():
  200. # check if v is a floating point
  201. if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
  202. # cast and send to device
  203. new_data[k] = v.to(*args, **kwargs)
  204. elif isinstance(v, torch.Tensor) and device is not None:
  205. new_data[k] = v.to(device=device)
  206. else:
  207. new_data[k] = v
  208. self.data = new_data
  209. return self
  210. class FeatureExtractionMixin(PushToHubMixin):
  211. """
  212. This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature
  213. extractors.
  214. """
  215. _auto_class = None
  216. def __init__(self, **kwargs):
  217. """Set elements of `kwargs` as attributes."""
  218. # Pop "processor_class" as it should be saved as private attribute
  219. self._processor_class = kwargs.pop("processor_class", None)
  220. # Additional attributes without default values
  221. for key, value in kwargs.items():
  222. try:
  223. setattr(self, key, value)
  224. except AttributeError as err:
  225. logger.error(f"Can't set {key} with value {value} for {self}")
  226. raise err
  227. def _set_processor_class(self, processor_class: str):
  228. """Sets processor class as an attribute."""
  229. self._processor_class = processor_class
  230. @classmethod
  231. def from_pretrained(
  232. cls,
  233. pretrained_model_name_or_path: Union[str, os.PathLike],
  234. cache_dir: Optional[Union[str, os.PathLike]] = None,
  235. force_download: bool = False,
  236. local_files_only: bool = False,
  237. token: Optional[Union[str, bool]] = None,
  238. revision: str = "main",
  239. **kwargs,
  240. ):
  241. r"""
  242. Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a
  243. derived class of [`SequenceFeatureExtractor`].
  244. Args:
  245. pretrained_model_name_or_path (`str` or `os.PathLike`):
  246. This can be either:
  247. - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
  248. huggingface.co.
  249. - a path to a *directory* containing a feature extractor file saved using the
  250. [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
  251. `./my_model_directory/`.
  252. - a path or url to a saved feature extractor JSON *file*, e.g.,
  253. `./my_model_directory/preprocessor_config.json`.
  254. cache_dir (`str` or `os.PathLike`, *optional*):
  255. Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
  256. standard cache should not be used.
  257. force_download (`bool`, *optional*, defaults to `False`):
  258. Whether or not to force to (re-)download the feature extractor files and override the cached versions
  259. if they exist.
  260. resume_download:
  261. Deprecated and ignored. All downloads are now resumed by default when possible.
  262. Will be removed in v5 of Transformers.
  263. proxies (`Dict[str, str]`, *optional*):
  264. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  265. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  266. token (`str` or `bool`, *optional*):
  267. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  268. the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
  269. revision (`str`, *optional*, defaults to `"main"`):
  270. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  271. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  272. identifier allowed by git.
  273. <Tip>
  274. To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  275. </Tip>
  276. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  277. If `False`, then this function returns just the final feature extractor object. If `True`, then this
  278. functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
  279. consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
  280. `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
  281. kwargs (`Dict[str, Any]`, *optional*):
  282. The values in kwargs of any keys which are feature extractor attributes will be used to override the
  283. loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
  284. controlled by the `return_unused_kwargs` keyword parameter.
  285. Returns:
  286. A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`].
  287. Examples:
  288. ```python
  289. # We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
  290. # derived class: *Wav2Vec2FeatureExtractor*
  291. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
  292. "facebook/wav2vec2-base-960h"
  293. ) # Download feature_extraction_config from huggingface.co and cache.
  294. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
  295. "./test/saved_model/"
  296. ) # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')*
  297. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json")
  298. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
  299. "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False
  300. )
  301. assert feature_extractor.return_attention_mask is False
  302. feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
  303. "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
  304. )
  305. assert feature_extractor.return_attention_mask is False
  306. assert unused_kwargs == {"foo": False}
  307. ```"""
  308. kwargs["cache_dir"] = cache_dir
  309. kwargs["force_download"] = force_download
  310. kwargs["local_files_only"] = local_files_only
  311. kwargs["revision"] = revision
  312. use_auth_token = kwargs.pop("use_auth_token", None)
  313. if use_auth_token is not None:
  314. warnings.warn(
  315. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  316. FutureWarning,
  317. )
  318. if token is not None:
  319. raise ValueError(
  320. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  321. )
  322. token = use_auth_token
  323. if token is not None:
  324. kwargs["token"] = token
  325. feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
  326. return cls.from_dict(feature_extractor_dict, **kwargs)
  327. def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
  328. """
  329. Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the
  330. [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method.
  331. Args:
  332. save_directory (`str` or `os.PathLike`):
  333. Directory where the feature extractor JSON file will be saved (will be created if it does not exist).
  334. push_to_hub (`bool`, *optional*, defaults to `False`):
  335. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  336. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  337. namespace).
  338. kwargs (`Dict[str, Any]`, *optional*):
  339. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  340. """
  341. use_auth_token = kwargs.pop("use_auth_token", None)
  342. if use_auth_token is not None:
  343. warnings.warn(
  344. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  345. FutureWarning,
  346. )
  347. if kwargs.get("token", None) is not None:
  348. raise ValueError(
  349. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  350. )
  351. kwargs["token"] = use_auth_token
  352. if os.path.isfile(save_directory):
  353. raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
  354. os.makedirs(save_directory, exist_ok=True)
  355. if push_to_hub:
  356. commit_message = kwargs.pop("commit_message", None)
  357. repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
  358. repo_id = self._create_repo(repo_id, **kwargs)
  359. files_timestamps = self._get_files_timestamps(save_directory)
  360. # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
  361. # loaded from the Hub.
  362. if self._auto_class is not None:
  363. custom_object_save(self, save_directory, config=self)
  364. # If we save using the predefined names, we can load using `from_pretrained`
  365. output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME)
  366. self.to_json_file(output_feature_extractor_file)
  367. logger.info(f"Feature extractor saved in {output_feature_extractor_file}")
  368. if push_to_hub:
  369. self._upload_modified_files(
  370. save_directory,
  371. repo_id,
  372. files_timestamps,
  373. commit_message=commit_message,
  374. token=kwargs.get("token"),
  375. )
  376. return [output_feature_extractor_file]
  377. @classmethod
  378. def get_feature_extractor_dict(
  379. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  380. ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  381. """
  382. From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
  383. feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] using `from_dict`.
  384. Parameters:
  385. pretrained_model_name_or_path (`str` or `os.PathLike`):
  386. The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
  387. Returns:
  388. `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object.
  389. """
  390. cache_dir = kwargs.pop("cache_dir", None)
  391. force_download = kwargs.pop("force_download", False)
  392. resume_download = kwargs.pop("resume_download", None)
  393. proxies = kwargs.pop("proxies", None)
  394. subfolder = kwargs.pop("subfolder", None)
  395. token = kwargs.pop("token", None)
  396. use_auth_token = kwargs.pop("use_auth_token", None)
  397. local_files_only = kwargs.pop("local_files_only", False)
  398. revision = kwargs.pop("revision", None)
  399. if use_auth_token is not None:
  400. warnings.warn(
  401. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  402. FutureWarning,
  403. )
  404. if token is not None:
  405. raise ValueError(
  406. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  407. )
  408. token = use_auth_token
  409. from_pipeline = kwargs.pop("_from_pipeline", None)
  410. from_auto_class = kwargs.pop("_from_auto", False)
  411. user_agent = {"file_type": "feature extractor", "from_auto_class": from_auto_class}
  412. if from_pipeline is not None:
  413. user_agent["using_pipeline"] = from_pipeline
  414. if is_offline_mode() and not local_files_only:
  415. logger.info("Offline mode: forcing local_files_only=True")
  416. local_files_only = True
  417. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  418. is_local = os.path.isdir(pretrained_model_name_or_path)
  419. if os.path.isdir(pretrained_model_name_or_path):
  420. feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME)
  421. if os.path.isfile(pretrained_model_name_or_path):
  422. resolved_feature_extractor_file = pretrained_model_name_or_path
  423. is_local = True
  424. elif is_remote_url(pretrained_model_name_or_path):
  425. feature_extractor_file = pretrained_model_name_or_path
  426. resolved_feature_extractor_file = download_url(pretrained_model_name_or_path)
  427. else:
  428. feature_extractor_file = FEATURE_EXTRACTOR_NAME
  429. try:
  430. # Load from local folder or from cache or download from model Hub and cache
  431. resolved_feature_extractor_file = cached_file(
  432. pretrained_model_name_or_path,
  433. feature_extractor_file,
  434. cache_dir=cache_dir,
  435. force_download=force_download,
  436. proxies=proxies,
  437. resume_download=resume_download,
  438. local_files_only=local_files_only,
  439. subfolder=subfolder,
  440. token=token,
  441. user_agent=user_agent,
  442. revision=revision,
  443. )
  444. except EnvironmentError:
  445. # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
  446. # the original exception.
  447. raise
  448. except Exception:
  449. # For any other exception, we throw a generic error.
  450. raise EnvironmentError(
  451. f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load"
  452. " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
  453. f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
  454. f" directory containing a {FEATURE_EXTRACTOR_NAME} file"
  455. )
  456. try:
  457. # Load feature_extractor dict
  458. with open(resolved_feature_extractor_file, "r", encoding="utf-8") as reader:
  459. text = reader.read()
  460. feature_extractor_dict = json.loads(text)
  461. except json.JSONDecodeError:
  462. raise EnvironmentError(
  463. f"It looks like the config file at '{resolved_feature_extractor_file}' is not a valid JSON file."
  464. )
  465. if is_local:
  466. logger.info(f"loading configuration file {resolved_feature_extractor_file}")
  467. else:
  468. logger.info(
  469. f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}"
  470. )
  471. if not is_local:
  472. if "auto_map" in feature_extractor_dict:
  473. feature_extractor_dict["auto_map"] = add_model_info_to_auto_map(
  474. feature_extractor_dict["auto_map"], pretrained_model_name_or_path
  475. )
  476. if "custom_pipelines" in feature_extractor_dict:
  477. feature_extractor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
  478. feature_extractor_dict["custom_pipelines"], pretrained_model_name_or_path
  479. )
  480. return feature_extractor_dict, kwargs
  481. @classmethod
  482. def from_dict(cls, feature_extractor_dict: Dict[str, Any], **kwargs) -> PreTrainedFeatureExtractor:
  483. """
  484. Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of
  485. parameters.
  486. Args:
  487. feature_extractor_dict (`Dict[str, Any]`):
  488. Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be
  489. retrieved from a pretrained checkpoint by leveraging the
  490. [`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method.
  491. kwargs (`Dict[str, Any]`):
  492. Additional parameters from which to initialize the feature extractor object.
  493. Returns:
  494. [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those
  495. parameters.
  496. """
  497. return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
  498. # Update feature_extractor with kwargs if needed
  499. to_remove = []
  500. for key, value in kwargs.items():
  501. if key in feature_extractor_dict:
  502. feature_extractor_dict[key] = value
  503. to_remove.append(key)
  504. for key in to_remove:
  505. kwargs.pop(key, None)
  506. feature_extractor = cls(**feature_extractor_dict)
  507. logger.info(f"Feature extractor {feature_extractor}")
  508. if return_unused_kwargs:
  509. return feature_extractor, kwargs
  510. else:
  511. return feature_extractor
  512. def to_dict(self) -> Dict[str, Any]:
  513. """
  514. Serializes this instance to a Python dictionary. Returns:
  515. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  516. """
  517. output = copy.deepcopy(self.__dict__)
  518. output["feature_extractor_type"] = self.__class__.__name__
  519. if "mel_filters" in output:
  520. del output["mel_filters"]
  521. if "window" in output:
  522. del output["window"]
  523. return output
  524. @classmethod
  525. def from_json_file(cls, json_file: Union[str, os.PathLike]) -> PreTrainedFeatureExtractor:
  526. """
  527. Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] from the path to
  528. a JSON file of parameters.
  529. Args:
  530. json_file (`str` or `os.PathLike`):
  531. Path to the JSON file containing the parameters.
  532. Returns:
  533. A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor
  534. object instantiated from that JSON file.
  535. """
  536. with open(json_file, "r", encoding="utf-8") as reader:
  537. text = reader.read()
  538. feature_extractor_dict = json.loads(text)
  539. return cls(**feature_extractor_dict)
  540. def to_json_string(self) -> str:
  541. """
  542. Serializes this instance to a JSON string.
  543. Returns:
  544. `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
  545. """
  546. dictionary = self.to_dict()
  547. for key, value in dictionary.items():
  548. if isinstance(value, np.ndarray):
  549. dictionary[key] = value.tolist()
  550. # make sure private name "_processor_class" is correctly
  551. # saved as "processor_class"
  552. _processor_class = dictionary.pop("_processor_class", None)
  553. if _processor_class is not None:
  554. dictionary["processor_class"] = _processor_class
  555. return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
  556. def to_json_file(self, json_file_path: Union[str, os.PathLike]):
  557. """
  558. Save this instance to a JSON file.
  559. Args:
  560. json_file_path (`str` or `os.PathLike`):
  561. Path to the JSON file in which this feature_extractor instance's parameters will be saved.
  562. """
  563. with open(json_file_path, "w", encoding="utf-8") as writer:
  564. writer.write(self.to_json_string())
  565. def __repr__(self):
  566. return f"{self.__class__.__name__} {self.to_json_string()}"
  567. @classmethod
  568. def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"):
  569. """
  570. Register this class with a given auto class. This should only be used for custom feature extractors as the ones
  571. in the library are already mapped with `AutoFeatureExtractor`.
  572. <Tip warning={true}>
  573. This API is experimental and may have some slight breaking changes in the next releases.
  574. </Tip>
  575. Args:
  576. auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`):
  577. The auto class to register this new feature extractor with.
  578. """
  579. if not isinstance(auto_class, str):
  580. auto_class = auto_class.__name__
  581. import transformers.models.auto as auto_module
  582. if not hasattr(auto_module, auto_class):
  583. raise ValueError(f"{auto_class} is not a valid auto class.")
  584. cls._auto_class = auto_class
  585. FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub)
  586. if FeatureExtractionMixin.push_to_hub.__doc__ is not None:
  587. FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format(
  588. object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file"
  589. )