feature_extraction_utils.py 30 KB

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