image_processing_auto.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. # coding=utf-8
  2. # Copyright 2022 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. """AutoImageProcessor class."""
  16. import importlib
  17. import json
  18. import os
  19. import warnings
  20. from collections import OrderedDict
  21. from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
  22. # Build the list of all image processors
  23. from ...configuration_utils import PretrainedConfig
  24. from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
  25. from ...image_processing_utils import BaseImageProcessor, ImageProcessingMixin
  26. from ...image_processing_utils_fast import BaseImageProcessorFast
  27. from ...utils import (
  28. CONFIG_NAME,
  29. IMAGE_PROCESSOR_NAME,
  30. get_file_from_repo,
  31. is_torchvision_available,
  32. is_vision_available,
  33. logging,
  34. )
  35. from .auto_factory import _LazyAutoMapping
  36. from .configuration_auto import (
  37. CONFIG_MAPPING_NAMES,
  38. AutoConfig,
  39. model_type_to_module_name,
  40. replace_list_option_in_docstrings,
  41. )
  42. logger = logging.get_logger(__name__)
  43. if TYPE_CHECKING:
  44. # This significantly improves completion suggestion performance when
  45. # the transformers package is used with Microsoft's Pylance language server.
  46. IMAGE_PROCESSOR_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict()
  47. else:
  48. IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict(
  49. [
  50. ("align", ("EfficientNetImageProcessor",)),
  51. ("beit", ("BeitImageProcessor",)),
  52. ("bit", ("BitImageProcessor",)),
  53. ("blip", ("BlipImageProcessor",)),
  54. ("blip-2", ("BlipImageProcessor",)),
  55. ("bridgetower", ("BridgeTowerImageProcessor",)),
  56. ("chameleon", ("ChameleonImageProcessor",)),
  57. ("chinese_clip", ("ChineseCLIPImageProcessor",)),
  58. ("clip", ("CLIPImageProcessor",)),
  59. ("clipseg", ("ViTImageProcessor", "ViTImageProcessorFast")),
  60. ("conditional_detr", ("ConditionalDetrImageProcessor",)),
  61. ("convnext", ("ConvNextImageProcessor",)),
  62. ("convnextv2", ("ConvNextImageProcessor",)),
  63. ("cvt", ("ConvNextImageProcessor",)),
  64. ("data2vec-vision", ("BeitImageProcessor",)),
  65. ("deformable_detr", ("DeformableDetrImageProcessor",)),
  66. ("deit", ("DeiTImageProcessor",)),
  67. ("depth_anything", ("DPTImageProcessor",)),
  68. ("deta", ("DetaImageProcessor",)),
  69. ("detr", ("DetrImageProcessor", "DetrImageProcessorFast")),
  70. ("dinat", ("ViTImageProcessor", "ViTImageProcessorFast")),
  71. ("dinov2", ("BitImageProcessor",)),
  72. ("donut-swin", ("DonutImageProcessor",)),
  73. ("dpt", ("DPTImageProcessor",)),
  74. ("efficientformer", ("EfficientFormerImageProcessor",)),
  75. ("efficientnet", ("EfficientNetImageProcessor",)),
  76. ("flava", ("FlavaImageProcessor",)),
  77. ("focalnet", ("BitImageProcessor",)),
  78. ("fuyu", ("FuyuImageProcessor",)),
  79. ("git", ("CLIPImageProcessor",)),
  80. ("glpn", ("GLPNImageProcessor",)),
  81. ("grounding-dino", ("GroundingDinoImageProcessor",)),
  82. ("groupvit", ("CLIPImageProcessor",)),
  83. ("hiera", ("BitImageProcessor",)),
  84. ("idefics", ("IdeficsImageProcessor",)),
  85. ("idefics2", ("Idefics2ImageProcessor",)),
  86. ("idefics3", ("Idefics3ImageProcessor",)),
  87. ("imagegpt", ("ImageGPTImageProcessor",)),
  88. ("instructblip", ("BlipImageProcessor",)),
  89. ("instructblipvideo", ("InstructBlipVideoImageProcessor",)),
  90. ("kosmos-2", ("CLIPImageProcessor",)),
  91. ("layoutlmv2", ("LayoutLMv2ImageProcessor",)),
  92. ("layoutlmv3", ("LayoutLMv3ImageProcessor",)),
  93. ("levit", ("LevitImageProcessor",)),
  94. ("llava", ("CLIPImageProcessor",)),
  95. ("llava_next", ("LlavaNextImageProcessor",)),
  96. ("llava_next_video", ("LlavaNextVideoImageProcessor",)),
  97. ("llava_onevision", ("LlavaOnevisionImageProcessor",)),
  98. ("mask2former", ("Mask2FormerImageProcessor",)),
  99. ("maskformer", ("MaskFormerImageProcessor",)),
  100. ("mgp-str", ("ViTImageProcessor", "ViTImageProcessorFast")),
  101. ("mllama", ("MllamaImageProcessor",)),
  102. ("mobilenet_v1", ("MobileNetV1ImageProcessor",)),
  103. ("mobilenet_v2", ("MobileNetV2ImageProcessor",)),
  104. ("mobilevit", ("MobileViTImageProcessor",)),
  105. ("mobilevitv2", ("MobileViTImageProcessor",)),
  106. ("nat", ("ViTImageProcessor", "ViTImageProcessorFast")),
  107. ("nougat", ("NougatImageProcessor",)),
  108. ("oneformer", ("OneFormerImageProcessor",)),
  109. ("owlv2", ("Owlv2ImageProcessor",)),
  110. ("owlvit", ("OwlViTImageProcessor",)),
  111. ("perceiver", ("PerceiverImageProcessor",)),
  112. ("pix2struct", ("Pix2StructImageProcessor",)),
  113. ("pixtral", ("PixtralImageProcessor",)),
  114. ("poolformer", ("PoolFormerImageProcessor",)),
  115. ("pvt", ("PvtImageProcessor",)),
  116. ("pvt_v2", ("PvtImageProcessor",)),
  117. ("qwen2_vl", ("Qwen2VLImageProcessor",)),
  118. ("regnet", ("ConvNextImageProcessor",)),
  119. ("resnet", ("ConvNextImageProcessor",)),
  120. ("rt_detr", "RTDetrImageProcessor"),
  121. ("sam", ("SamImageProcessor",)),
  122. ("segformer", ("SegformerImageProcessor",)),
  123. ("seggpt", ("SegGptImageProcessor",)),
  124. ("siglip", ("SiglipImageProcessor",)),
  125. ("swiftformer", ("ViTImageProcessor", "ViTImageProcessorFast")),
  126. ("swin", ("ViTImageProcessor", "ViTImageProcessorFast")),
  127. ("swin2sr", ("Swin2SRImageProcessor",)),
  128. ("swinv2", ("ViTImageProcessor", "ViTImageProcessorFast")),
  129. ("table-transformer", ("DetrImageProcessor",)),
  130. ("timesformer", ("VideoMAEImageProcessor",)),
  131. ("tvlt", ("TvltImageProcessor",)),
  132. ("tvp", ("TvpImageProcessor",)),
  133. ("udop", ("LayoutLMv3ImageProcessor",)),
  134. ("upernet", ("SegformerImageProcessor",)),
  135. ("van", ("ConvNextImageProcessor",)),
  136. ("videomae", ("VideoMAEImageProcessor",)),
  137. ("vilt", ("ViltImageProcessor",)),
  138. ("vipllava", ("CLIPImageProcessor",)),
  139. ("vit", ("ViTImageProcessor", "ViTImageProcessorFast")),
  140. ("vit_hybrid", ("ViTHybridImageProcessor",)),
  141. ("vit_mae", ("ViTImageProcessor", "ViTImageProcessorFast")),
  142. ("vit_msn", ("ViTImageProcessor", "ViTImageProcessorFast")),
  143. ("vitmatte", ("VitMatteImageProcessor",)),
  144. ("xclip", ("CLIPImageProcessor",)),
  145. ("yolos", ("YolosImageProcessor",)),
  146. ("zoedepth", ("ZoeDepthImageProcessor",)),
  147. ]
  148. )
  149. for model_type, image_processors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
  150. slow_image_processor_class, *fast_image_processor_class = image_processors
  151. if not is_vision_available():
  152. slow_image_processor_class = None
  153. # If the fast image processor is not defined, or torchvision is not available, we set it to None
  154. if not fast_image_processor_class or fast_image_processor_class[0] is None or not is_torchvision_available():
  155. fast_image_processor_class = None
  156. else:
  157. fast_image_processor_class = fast_image_processor_class[0]
  158. IMAGE_PROCESSOR_MAPPING_NAMES[model_type] = (slow_image_processor_class, fast_image_processor_class)
  159. IMAGE_PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)
  160. def image_processor_class_from_name(class_name: str):
  161. if class_name == "BaseImageProcessorFast":
  162. return BaseImageProcessorFast
  163. for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
  164. if class_name in extractors:
  165. module_name = model_type_to_module_name(module_name)
  166. module = importlib.import_module(f".{module_name}", "transformers.models")
  167. try:
  168. return getattr(module, class_name)
  169. except AttributeError:
  170. continue
  171. for _, extractors in IMAGE_PROCESSOR_MAPPING._extra_content.items():
  172. for extractor in extractors:
  173. if getattr(extractor, "__name__", None) == class_name:
  174. return extractor
  175. # We did not find the class, but maybe it's because a dep is missing. In that case, the class will be in the main
  176. # init and we return the proper dummy to get an appropriate error message.
  177. main_module = importlib.import_module("transformers")
  178. if hasattr(main_module, class_name):
  179. return getattr(main_module, class_name)
  180. return None
  181. def get_image_processor_config(
  182. pretrained_model_name_or_path: Union[str, os.PathLike],
  183. cache_dir: Optional[Union[str, os.PathLike]] = None,
  184. force_download: bool = False,
  185. resume_download: Optional[bool] = None,
  186. proxies: Optional[Dict[str, str]] = None,
  187. token: Optional[Union[bool, str]] = None,
  188. revision: Optional[str] = None,
  189. local_files_only: bool = False,
  190. **kwargs,
  191. ):
  192. """
  193. Loads the image processor configuration from a pretrained model image processor configuration.
  194. Args:
  195. pretrained_model_name_or_path (`str` or `os.PathLike`):
  196. This can be either:
  197. - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
  198. huggingface.co.
  199. - a path to a *directory* containing a configuration file saved using the
  200. [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
  201. cache_dir (`str` or `os.PathLike`, *optional*):
  202. Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
  203. cache should not be used.
  204. force_download (`bool`, *optional*, defaults to `False`):
  205. Whether or not to force to (re-)download the configuration files and override the cached versions if they
  206. exist.
  207. resume_download:
  208. Deprecated and ignored. All downloads are now resumed by default when possible.
  209. Will be removed in v5 of Transformers.
  210. proxies (`Dict[str, str]`, *optional*):
  211. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  212. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  213. token (`str` or *bool*, *optional*):
  214. The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
  215. when running `huggingface-cli login` (stored in `~/.huggingface`).
  216. revision (`str`, *optional*, defaults to `"main"`):
  217. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  218. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  219. identifier allowed by git.
  220. local_files_only (`bool`, *optional*, defaults to `False`):
  221. If `True`, will only try to load the image processor configuration from local files.
  222. <Tip>
  223. Passing `token=True` is required when you want to use a private model.
  224. </Tip>
  225. Returns:
  226. `Dict`: The configuration of the image processor.
  227. Examples:
  228. ```python
  229. # Download configuration from huggingface.co and cache.
  230. image_processor_config = get_image_processor_config("google-bert/bert-base-uncased")
  231. # This model does not have a image processor config so the result will be an empty dict.
  232. image_processor_config = get_image_processor_config("FacebookAI/xlm-roberta-base")
  233. # Save a pretrained image processor locally and you can reload its config
  234. from transformers import AutoTokenizer
  235. image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
  236. image_processor.save_pretrained("image-processor-test")
  237. image_processor_config = get_image_processor_config("image-processor-test")
  238. ```"""
  239. use_auth_token = kwargs.pop("use_auth_token", None)
  240. if use_auth_token is not None:
  241. warnings.warn(
  242. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  243. FutureWarning,
  244. )
  245. if token is not None:
  246. raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
  247. token = use_auth_token
  248. resolved_config_file = get_file_from_repo(
  249. pretrained_model_name_or_path,
  250. IMAGE_PROCESSOR_NAME,
  251. cache_dir=cache_dir,
  252. force_download=force_download,
  253. resume_download=resume_download,
  254. proxies=proxies,
  255. token=token,
  256. revision=revision,
  257. local_files_only=local_files_only,
  258. )
  259. if resolved_config_file is None:
  260. logger.info(
  261. "Could not locate the image processor configuration file, will try to use the model config instead."
  262. )
  263. return {}
  264. with open(resolved_config_file, encoding="utf-8") as reader:
  265. return json.load(reader)
  266. def _warning_fast_image_processor_available(fast_class):
  267. logger.warning(
  268. f"Fast image processor class {fast_class} is available for this model. "
  269. "Using slow image processor class. To use the fast image processor class set `use_fast=True`."
  270. )
  271. class AutoImageProcessor:
  272. r"""
  273. This is a generic image processor class that will be instantiated as one of the image processor classes of the
  274. library when created with the [`AutoImageProcessor.from_pretrained`] class method.
  275. This class cannot be instantiated directly using `__init__()` (throws an error).
  276. """
  277. def __init__(self):
  278. raise EnvironmentError(
  279. "AutoImageProcessor is designed to be instantiated "
  280. "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method."
  281. )
  282. @classmethod
  283. @replace_list_option_in_docstrings(IMAGE_PROCESSOR_MAPPING_NAMES)
  284. def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
  285. r"""
  286. Instantiate one of the image processor classes of the library from a pretrained model vocabulary.
  287. The image processor class to instantiate is selected based on the `model_type` property of the config object
  288. (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
  289. missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
  290. List options
  291. Params:
  292. pretrained_model_name_or_path (`str` or `os.PathLike`):
  293. This can be either:
  294. - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
  295. huggingface.co.
  296. - a path to a *directory* containing a image processor file saved using the
  297. [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
  298. `./my_model_directory/`.
  299. - a path or url to a saved image processor JSON *file*, e.g.,
  300. `./my_model_directory/preprocessor_config.json`.
  301. cache_dir (`str` or `os.PathLike`, *optional*):
  302. Path to a directory in which a downloaded pretrained model image processor should be cached if the
  303. standard cache should not be used.
  304. force_download (`bool`, *optional*, defaults to `False`):
  305. Whether or not to force to (re-)download the image processor files and override the cached versions if
  306. they exist.
  307. resume_download:
  308. Deprecated and ignored. All downloads are now resumed by default when possible.
  309. Will be removed in v5 of Transformers.
  310. proxies (`Dict[str, str]`, *optional*):
  311. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  312. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  313. token (`str` or *bool*, *optional*):
  314. The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
  315. when running `huggingface-cli login` (stored in `~/.huggingface`).
  316. revision (`str`, *optional*, defaults to `"main"`):
  317. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  318. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  319. identifier allowed by git.
  320. use_fast (`bool`, *optional*, defaults to `False`):
  321. Use a fast torchvision-base image processor if it is supported for a given model.
  322. If a fast tokenizer is not available for a given model, a normal numpy-based image processor
  323. is returned instead.
  324. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  325. If `False`, then this function returns just the final image processor object. If `True`, then this
  326. functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
  327. consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
  328. `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
  329. trust_remote_code (`bool`, *optional*, defaults to `False`):
  330. Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
  331. should only be set to `True` for repositories you trust and in which you have read the code, as it will
  332. execute code present on the Hub on your local machine.
  333. kwargs (`Dict[str, Any]`, *optional*):
  334. The values in kwargs of any keys which are image processor attributes will be used to override the
  335. loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
  336. controlled by the `return_unused_kwargs` keyword parameter.
  337. <Tip>
  338. Passing `token=True` is required when you want to use a private model.
  339. </Tip>
  340. Examples:
  341. ```python
  342. >>> from transformers import AutoImageProcessor
  343. >>> # Download image processor from huggingface.co and cache.
  344. >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
  345. >>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*)
  346. >>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/")
  347. ```"""
  348. use_auth_token = kwargs.pop("use_auth_token", None)
  349. if use_auth_token is not None:
  350. warnings.warn(
  351. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  352. FutureWarning,
  353. )
  354. if kwargs.get("token", None) is not None:
  355. raise ValueError(
  356. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  357. )
  358. kwargs["token"] = use_auth_token
  359. config = kwargs.pop("config", None)
  360. use_fast = kwargs.pop("use_fast", None)
  361. trust_remote_code = kwargs.pop("trust_remote_code", None)
  362. kwargs["_from_auto"] = True
  363. config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
  364. image_processor_class = config_dict.get("image_processor_type", None)
  365. image_processor_auto_map = None
  366. if "AutoImageProcessor" in config_dict.get("auto_map", {}):
  367. image_processor_auto_map = config_dict["auto_map"]["AutoImageProcessor"]
  368. # If we still don't have the image processor class, check if we're loading from a previous feature extractor config
  369. # and if so, infer the image processor class from there.
  370. if image_processor_class is None and image_processor_auto_map is None:
  371. feature_extractor_class = config_dict.pop("feature_extractor_type", None)
  372. if feature_extractor_class is not None:
  373. image_processor_class = feature_extractor_class.replace("FeatureExtractor", "ImageProcessor")
  374. if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
  375. feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
  376. image_processor_auto_map = feature_extractor_auto_map.replace("FeatureExtractor", "ImageProcessor")
  377. # If we don't find the image processor class in the image processor config, let's try the model config.
  378. if image_processor_class is None and image_processor_auto_map is None:
  379. if not isinstance(config, PretrainedConfig):
  380. config = AutoConfig.from_pretrained(
  381. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
  382. )
  383. # It could be in `config.image_processor_type``
  384. image_processor_class = getattr(config, "image_processor_type", None)
  385. if hasattr(config, "auto_map") and "AutoImageProcessor" in config.auto_map:
  386. image_processor_auto_map = config.auto_map["AutoImageProcessor"]
  387. if image_processor_class is not None:
  388. # Update class name to reflect the use_fast option. If class is not found, None is returned.
  389. if use_fast is not None:
  390. if use_fast and not image_processor_class.endswith("Fast"):
  391. image_processor_class += "Fast"
  392. elif not use_fast and image_processor_class.endswith("Fast"):
  393. image_processor_class = image_processor_class[:-4]
  394. image_processor_class = image_processor_class_from_name(image_processor_class)
  395. has_remote_code = image_processor_auto_map is not None
  396. has_local_code = image_processor_class is not None or type(config) in IMAGE_PROCESSOR_MAPPING
  397. trust_remote_code = resolve_trust_remote_code(
  398. trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
  399. )
  400. if image_processor_auto_map is not None and not isinstance(image_processor_auto_map, tuple):
  401. # In some configs, only the slow image processor class is stored
  402. image_processor_auto_map = (image_processor_auto_map, None)
  403. if has_remote_code and trust_remote_code:
  404. if not use_fast and image_processor_auto_map[1] is not None:
  405. _warning_fast_image_processor_available(image_processor_auto_map[1])
  406. if use_fast and image_processor_auto_map[1] is not None:
  407. class_ref = image_processor_auto_map[1]
  408. else:
  409. class_ref = image_processor_auto_map[0]
  410. image_processor_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
  411. _ = kwargs.pop("code_revision", None)
  412. if os.path.isdir(pretrained_model_name_or_path):
  413. image_processor_class.register_for_auto_class()
  414. return image_processor_class.from_dict(config_dict, **kwargs)
  415. elif image_processor_class is not None:
  416. return image_processor_class.from_dict(config_dict, **kwargs)
  417. # Last try: we use the IMAGE_PROCESSOR_MAPPING.
  418. elif type(config) in IMAGE_PROCESSOR_MAPPING:
  419. image_processor_tuple = IMAGE_PROCESSOR_MAPPING[type(config)]
  420. image_processor_class_py, image_processor_class_fast = image_processor_tuple
  421. if not use_fast and image_processor_class_fast is not None:
  422. _warning_fast_image_processor_available(image_processor_class_fast)
  423. if image_processor_class_fast and (use_fast or image_processor_class_py is None):
  424. return image_processor_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
  425. else:
  426. if image_processor_class_py is not None:
  427. return image_processor_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
  428. else:
  429. raise ValueError(
  430. "This image processor cannot be instantiated. Please make sure you have `Pillow` installed."
  431. )
  432. raise ValueError(
  433. f"Unrecognized image processor in {pretrained_model_name_or_path}. Should have a "
  434. f"`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following "
  435. f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}"
  436. )
  437. @staticmethod
  438. def register(
  439. config_class,
  440. image_processor_class=None,
  441. slow_image_processor_class=None,
  442. fast_image_processor_class=None,
  443. exist_ok=False,
  444. ):
  445. """
  446. Register a new image processor for this class.
  447. Args:
  448. config_class ([`PretrainedConfig`]):
  449. The configuration corresponding to the model to register.
  450. image_processor_class ([`ImageProcessingMixin`]): The image processor to register.
  451. """
  452. if image_processor_class is not None:
  453. if slow_image_processor_class is not None:
  454. raise ValueError("Cannot specify both image_processor_class and slow_image_processor_class")
  455. warnings.warn(
  456. "The image_processor_class argument is deprecated and will be removed in v4.42. Please use `slow_image_processor_class`, or `fast_image_processor_class` instead",
  457. FutureWarning,
  458. )
  459. slow_image_processor_class = image_processor_class
  460. if slow_image_processor_class is None and fast_image_processor_class is None:
  461. raise ValueError("You need to specify either slow_image_processor_class or fast_image_processor_class")
  462. if slow_image_processor_class is not None and issubclass(slow_image_processor_class, BaseImageProcessorFast):
  463. raise ValueError("You passed a fast image processor in as the `slow_image_processor_class`.")
  464. if fast_image_processor_class is not None and issubclass(fast_image_processor_class, BaseImageProcessor):
  465. raise ValueError("You passed a slow image processor in as the `fast_image_processor_class`.")
  466. if (
  467. slow_image_processor_class is not None
  468. and fast_image_processor_class is not None
  469. and issubclass(fast_image_processor_class, BaseImageProcessorFast)
  470. and fast_image_processor_class.slow_image_processor_class != slow_image_processor_class
  471. ):
  472. raise ValueError(
  473. "The fast processor class you are passing has a `slow_image_processor_class` attribute that is not "
  474. "consistent with the slow processor class you passed (fast tokenizer has "
  475. f"{fast_image_processor_class.slow_image_processor_class} and you passed {slow_image_processor_class}. Fix one of those "
  476. "so they match!"
  477. )
  478. # Avoid resetting a set slow/fast image processor if we are passing just the other ones.
  479. if config_class in IMAGE_PROCESSOR_MAPPING._extra_content:
  480. existing_slow, existing_fast = IMAGE_PROCESSOR_MAPPING[config_class]
  481. if slow_image_processor_class is None:
  482. slow_image_processor_class = existing_slow
  483. if fast_image_processor_class is None:
  484. fast_image_processor_class = existing_fast
  485. IMAGE_PROCESSOR_MAPPING.register(
  486. config_class, (slow_image_processor_class, fast_image_processor_class), exist_ok=exist_ok
  487. )