image_processing_base.py 23 KB

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