image_processing_base.py 24 KB

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