image_processing_base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. # Copyright 2020 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. import copy
  15. import json
  16. import os
  17. import warnings
  18. from typing import Any, Optional, TypeVar, Union
  19. import numpy as np
  20. from .dynamic_module_utils import custom_object_save
  21. from .feature_extraction_utils import BatchFeature as BaseBatchFeature
  22. from .image_utils import is_valid_image, load_image
  23. from .utils import (
  24. IMAGE_PROCESSOR_NAME,
  25. PROCESSOR_NAME,
  26. PushToHubMixin,
  27. copy_func,
  28. download_url,
  29. is_offline_mode,
  30. is_remote_url,
  31. logging,
  32. )
  33. from .utils.hub import cached_file
  34. ImageProcessorType = TypeVar("ImageProcessorType", bound="ImageProcessingMixin")
  35. logger = logging.get_logger(__name__)
  36. # TODO: Move BatchFeature to be imported by both image_processing_utils and image_processing_utils_fast
  37. # We override the class string here, but logic is the same.
  38. class BatchFeature(BaseBatchFeature):
  39. r"""
  40. Holds the output of the image processor specific `__call__` methods.
  41. This class is derived from a python dictionary and can be used as a dictionary.
  42. Args:
  43. data (`dict`):
  44. Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
  45. tensor_type (`Union[None, str, TensorType]`, *optional*):
  46. You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
  47. initialization.
  48. """
  49. # TODO: (Amy) - factor out the common parts of this and the feature extractor
  50. class ImageProcessingMixin(PushToHubMixin):
  51. """
  52. This is an image processor mixin used to provide saving/loading functionality for sequential and image feature
  53. extractors.
  54. """
  55. _auto_class = None
  56. def __init__(self, **kwargs):
  57. """Set elements of `kwargs` as attributes."""
  58. # This key was saved while we still used `XXXFeatureExtractor` for image processing. Now we use
  59. # `XXXImageProcessor`, this attribute and its value are misleading.
  60. kwargs.pop("feature_extractor_type", None)
  61. # Pop "processor_class" as it should be saved as private attribute
  62. self._processor_class = kwargs.pop("processor_class", None)
  63. # Additional attributes without default values
  64. for key, value in kwargs.items():
  65. try:
  66. setattr(self, key, value)
  67. except AttributeError as err:
  68. logger.error(f"Can't set {key} with value {value} for {self}")
  69. raise err
  70. def _set_processor_class(self, processor_class: str):
  71. """Sets processor class as an attribute."""
  72. self._processor_class = processor_class
  73. @classmethod
  74. def from_pretrained(
  75. cls: type[ImageProcessorType],
  76. pretrained_model_name_or_path: Union[str, os.PathLike],
  77. cache_dir: Optional[Union[str, os.PathLike]] = None,
  78. force_download: bool = False,
  79. local_files_only: bool = False,
  80. token: Optional[Union[str, bool]] = None,
  81. revision: str = "main",
  82. **kwargs,
  83. ) -> ImageProcessorType:
  84. r"""
  85. Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor.
  86. Args:
  87. pretrained_model_name_or_path (`str` or `os.PathLike`):
  88. This can be either:
  89. - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
  90. huggingface.co.
  91. - a path to a *directory* containing a image processor file saved using the
  92. [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
  93. `./my_model_directory/`.
  94. - a path or url to a saved image processor JSON *file*, e.g.,
  95. `./my_model_directory/preprocessor_config.json`.
  96. cache_dir (`str` or `os.PathLike`, *optional*):
  97. Path to a directory in which a downloaded pretrained model image processor should be cached if the
  98. standard cache should not be used.
  99. force_download (`bool`, *optional*, defaults to `False`):
  100. Whether or not to force to (re-)download the image processor files and override the cached versions if
  101. they exist.
  102. resume_download:
  103. Deprecated and ignored. All downloads are now resumed by default when possible.
  104. Will be removed in v5 of Transformers.
  105. proxies (`dict[str, str]`, *optional*):
  106. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  107. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  108. token (`str` or `bool`, *optional*):
  109. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  110. the token generated when running `hf auth login` (stored in `~/.huggingface`).
  111. revision (`str`, *optional*, defaults to `"main"`):
  112. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  113. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  114. identifier allowed by git.
  115. <Tip>
  116. To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  117. </Tip>
  118. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  119. If `False`, then this function returns just the final image processor object. If `True`, then this
  120. functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
  121. consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
  122. `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
  123. subfolder (`str`, *optional*, defaults to `""`):
  124. In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
  125. specify the folder name here.
  126. kwargs (`dict[str, Any]`, *optional*):
  127. The values in kwargs of any keys which are image processor attributes will be used to override the
  128. loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
  129. controlled by the `return_unused_kwargs` keyword parameter.
  130. Returns:
  131. A image processor of type [`~image_processing_utils.ImageProcessingMixin`].
  132. Examples:
  133. ```python
  134. # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
  135. # derived class: *CLIPImageProcessor*
  136. image_processor = CLIPImageProcessor.from_pretrained(
  137. "openai/clip-vit-base-patch32"
  138. ) # Download image_processing_config from huggingface.co and cache.
  139. image_processor = CLIPImageProcessor.from_pretrained(
  140. "./test/saved_model/"
  141. ) # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
  142. image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
  143. image_processor = CLIPImageProcessor.from_pretrained(
  144. "openai/clip-vit-base-patch32", do_normalize=False, foo=False
  145. )
  146. assert image_processor.do_normalize is False
  147. image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
  148. "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
  149. )
  150. assert image_processor.do_normalize is False
  151. assert unused_kwargs == {"foo": False}
  152. ```"""
  153. kwargs["cache_dir"] = cache_dir
  154. kwargs["force_download"] = force_download
  155. kwargs["local_files_only"] = local_files_only
  156. kwargs["revision"] = revision
  157. use_auth_token = kwargs.pop("use_auth_token", None)
  158. if use_auth_token is not None:
  159. warnings.warn(
  160. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  161. FutureWarning,
  162. )
  163. if token is not None:
  164. raise ValueError(
  165. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  166. )
  167. token = use_auth_token
  168. if token is not None:
  169. kwargs["token"] = token
  170. image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
  171. return cls.from_dict(image_processor_dict, **kwargs)
  172. def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
  173. """
  174. Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the
  175. [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method.
  176. Args:
  177. save_directory (`str` or `os.PathLike`):
  178. Directory where the image processor JSON file will be saved (will be created if it does not exist).
  179. push_to_hub (`bool`, *optional*, defaults to `False`):
  180. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  181. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  182. namespace).
  183. kwargs (`dict[str, Any]`, *optional*):
  184. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  185. """
  186. use_auth_token = kwargs.pop("use_auth_token", None)
  187. if use_auth_token is not None:
  188. warnings.warn(
  189. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  190. FutureWarning,
  191. )
  192. if kwargs.get("token") is not None:
  193. raise ValueError(
  194. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  195. )
  196. kwargs["token"] = use_auth_token
  197. if os.path.isfile(save_directory):
  198. raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
  199. os.makedirs(save_directory, exist_ok=True)
  200. if push_to_hub:
  201. commit_message = kwargs.pop("commit_message", None)
  202. repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
  203. repo_id = self._create_repo(repo_id, **kwargs)
  204. files_timestamps = self._get_files_timestamps(save_directory)
  205. # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
  206. # loaded from the Hub.
  207. if self._auto_class is not None:
  208. custom_object_save(self, save_directory, config=self)
  209. # If we save using the predefined names, we can load using `from_pretrained`
  210. output_image_processor_file = os.path.join(save_directory, IMAGE_PROCESSOR_NAME)
  211. self.to_json_file(output_image_processor_file)
  212. logger.info(f"Image processor saved in {output_image_processor_file}")
  213. if push_to_hub:
  214. self._upload_modified_files(
  215. save_directory,
  216. repo_id,
  217. files_timestamps,
  218. commit_message=commit_message,
  219. token=kwargs.get("token"),
  220. )
  221. return [output_image_processor_file]
  222. @classmethod
  223. def get_image_processor_dict(
  224. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  225. ) -> tuple[dict[str, Any], dict[str, Any]]:
  226. """
  227. From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
  228. image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`.
  229. Parameters:
  230. pretrained_model_name_or_path (`str` or `os.PathLike`):
  231. The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
  232. subfolder (`str`, *optional*, defaults to `""`):
  233. In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
  234. specify the folder name here.
  235. image_processor_filename (`str`, *optional*, defaults to `"config.json"`):
  236. The name of the file in the model directory to use for the image processor config.
  237. Returns:
  238. `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object.
  239. """
  240. cache_dir = kwargs.pop("cache_dir", None)
  241. force_download = kwargs.pop("force_download", False)
  242. resume_download = kwargs.pop("resume_download", None)
  243. proxies = kwargs.pop("proxies", None)
  244. token = kwargs.pop("token", None)
  245. use_auth_token = kwargs.pop("use_auth_token", None)
  246. local_files_only = kwargs.pop("local_files_only", False)
  247. revision = kwargs.pop("revision", None)
  248. subfolder = kwargs.pop("subfolder", "")
  249. image_processor_filename = kwargs.pop("image_processor_filename", IMAGE_PROCESSOR_NAME)
  250. from_pipeline = kwargs.pop("_from_pipeline", None)
  251. from_auto_class = kwargs.pop("_from_auto", False)
  252. if use_auth_token is not None:
  253. warnings.warn(
  254. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  255. FutureWarning,
  256. )
  257. if token is not None:
  258. raise ValueError(
  259. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  260. )
  261. token = use_auth_token
  262. user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class}
  263. if from_pipeline is not None:
  264. user_agent["using_pipeline"] = from_pipeline
  265. if is_offline_mode() and not local_files_only:
  266. logger.info("Offline mode: forcing local_files_only=True")
  267. local_files_only = True
  268. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  269. is_local = os.path.isdir(pretrained_model_name_or_path)
  270. if os.path.isdir(pretrained_model_name_or_path):
  271. image_processor_file = os.path.join(pretrained_model_name_or_path, image_processor_filename)
  272. if os.path.isfile(pretrained_model_name_or_path):
  273. resolved_image_processor_file = pretrained_model_name_or_path
  274. is_local = True
  275. elif is_remote_url(pretrained_model_name_or_path):
  276. image_processor_file = pretrained_model_name_or_path
  277. resolved_image_processor_file = download_url(pretrained_model_name_or_path)
  278. else:
  279. image_processor_file = image_processor_filename
  280. try:
  281. # Load from local folder or from cache or download from model Hub and cache
  282. resolved_image_processor_files = [
  283. resolved_file
  284. for filename in [image_processor_file, PROCESSOR_NAME]
  285. if (
  286. resolved_file := cached_file(
  287. pretrained_model_name_or_path,
  288. filename=filename,
  289. cache_dir=cache_dir,
  290. force_download=force_download,
  291. proxies=proxies,
  292. resume_download=resume_download,
  293. local_files_only=local_files_only,
  294. token=token,
  295. user_agent=user_agent,
  296. revision=revision,
  297. subfolder=subfolder,
  298. _raise_exceptions_for_missing_entries=False,
  299. )
  300. )
  301. is not None
  302. ]
  303. resolved_image_processor_file = resolved_image_processor_files[0]
  304. except OSError:
  305. # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
  306. # the original exception.
  307. raise
  308. except Exception:
  309. # For any other exception, we throw a generic error.
  310. raise OSError(
  311. f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load"
  312. " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
  313. f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
  314. f" directory containing a {image_processor_filename} file"
  315. )
  316. try:
  317. # Load image_processor dict
  318. with open(resolved_image_processor_file, encoding="utf-8") as reader:
  319. text = reader.read()
  320. image_processor_dict = json.loads(text)
  321. image_processor_dict = image_processor_dict.get("image_processor", image_processor_dict)
  322. except json.JSONDecodeError:
  323. raise OSError(
  324. f"It looks like the config file at '{resolved_image_processor_file}' is not a valid JSON file."
  325. )
  326. if is_local:
  327. logger.info(f"loading configuration file {resolved_image_processor_file}")
  328. else:
  329. logger.info(
  330. f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}"
  331. )
  332. return image_processor_dict, kwargs
  333. @classmethod
  334. def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs):
  335. """
  336. Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters.
  337. Args:
  338. image_processor_dict (`dict[str, Any]`):
  339. Dictionary that will be used to instantiate the image processor object. Such a dictionary can be
  340. retrieved from a pretrained checkpoint by leveraging the
  341. [`~image_processing_utils.ImageProcessingMixin.to_dict`] method.
  342. kwargs (`dict[str, Any]`):
  343. Additional parameters from which to initialize the image processor object.
  344. Returns:
  345. [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those
  346. parameters.
  347. """
  348. image_processor_dict = image_processor_dict.copy()
  349. return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
  350. # The `size` parameter is a dict and was previously an int or tuple in feature extractors.
  351. # We set `size` here directly to the `image_processor_dict` so that it is converted to the appropriate
  352. # dict within the image processor and isn't overwritten if `size` is passed in as a kwarg.
  353. if "size" in kwargs and "size" in image_processor_dict:
  354. image_processor_dict["size"] = kwargs.pop("size")
  355. if "crop_size" in kwargs and "crop_size" in image_processor_dict:
  356. image_processor_dict["crop_size"] = kwargs.pop("crop_size")
  357. image_processor = cls(**image_processor_dict)
  358. # Update image_processor with kwargs if needed
  359. to_remove = []
  360. for key, value in kwargs.items():
  361. if hasattr(image_processor, key):
  362. setattr(image_processor, key, value)
  363. to_remove.append(key)
  364. for key in to_remove:
  365. kwargs.pop(key, None)
  366. logger.info(f"Image processor {image_processor}")
  367. if return_unused_kwargs:
  368. return image_processor, kwargs
  369. else:
  370. return image_processor
  371. def to_dict(self) -> dict[str, Any]:
  372. """
  373. Serializes this instance to a Python dictionary.
  374. Returns:
  375. `dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance.
  376. """
  377. output = copy.deepcopy(self.__dict__)
  378. output["image_processor_type"] = self.__class__.__name__
  379. return output
  380. @classmethod
  381. def from_json_file(cls, json_file: Union[str, os.PathLike]):
  382. """
  383. Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON
  384. file of parameters.
  385. Args:
  386. json_file (`str` or `os.PathLike`):
  387. Path to the JSON file containing the parameters.
  388. Returns:
  389. A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object
  390. instantiated from that JSON file.
  391. """
  392. with open(json_file, encoding="utf-8") as reader:
  393. text = reader.read()
  394. image_processor_dict = json.loads(text)
  395. return cls(**image_processor_dict)
  396. def to_json_string(self) -> str:
  397. """
  398. Serializes this instance to a JSON string.
  399. Returns:
  400. `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
  401. """
  402. dictionary = self.to_dict()
  403. for key, value in dictionary.items():
  404. if isinstance(value, np.ndarray):
  405. dictionary[key] = value.tolist()
  406. # make sure private name "_processor_class" is correctly
  407. # saved as "processor_class"
  408. _processor_class = dictionary.pop("_processor_class", None)
  409. if _processor_class is not None:
  410. dictionary["processor_class"] = _processor_class
  411. return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
  412. def to_json_file(self, json_file_path: Union[str, os.PathLike]):
  413. """
  414. Save this instance to a JSON file.
  415. Args:
  416. json_file_path (`str` or `os.PathLike`):
  417. Path to the JSON file in which this image_processor instance's parameters will be saved.
  418. """
  419. with open(json_file_path, "w", encoding="utf-8") as writer:
  420. writer.write(self.to_json_string())
  421. def __repr__(self):
  422. return f"{self.__class__.__name__} {self.to_json_string()}"
  423. @classmethod
  424. def register_for_auto_class(cls, auto_class="AutoImageProcessor"):
  425. """
  426. Register this class with a given auto class. This should only be used for custom image processors as the ones
  427. in the library are already mapped with `AutoImageProcessor `.
  428. Args:
  429. auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
  430. The auto class to register this new image processor with.
  431. """
  432. if not isinstance(auto_class, str):
  433. auto_class = auto_class.__name__
  434. import transformers.models.auto as auto_module
  435. if not hasattr(auto_module, auto_class):
  436. raise ValueError(f"{auto_class} is not a valid auto class.")
  437. cls._auto_class = auto_class
  438. def fetch_images(self, image_url_or_urls: Union[str, list[str], list[list[str]]]):
  439. """
  440. Convert a single or a list of urls into the corresponding `PIL.Image` objects.
  441. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
  442. returned.
  443. """
  444. if isinstance(image_url_or_urls, list):
  445. return [self.fetch_images(x) for x in image_url_or_urls]
  446. elif isinstance(image_url_or_urls, str):
  447. return load_image(image_url_or_urls)
  448. elif is_valid_image(image_url_or_urls):
  449. return image_url_or_urls
  450. else:
  451. raise TypeError(f"only a single or a list of entries is supported but got type={type(image_url_or_urls)}")
  452. ImageProcessingMixin.push_to_hub = copy_func(ImageProcessingMixin.push_to_hub)
  453. if ImageProcessingMixin.push_to_hub.__doc__ is not None:
  454. ImageProcessingMixin.push_to_hub.__doc__ = ImageProcessingMixin.push_to_hub.__doc__.format(
  455. object="image processor", object_class="AutoImageProcessor", object_files="image processor file"
  456. )