

from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
	from PIL import Image

	from ..image_utils import load_image

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
	from ..tf_utils import stable_softmax

lowerCAmelCase__	   = logging.get_logger(__name__)

@add_end_docstrings(snake_case			)
class 					a__						(					snake_case			):
			"""simple docstring"""







			def __init__(    self      ,      **lowercase       )  ->						Optional[int]:
							'''simple docstring'''






							super().__init__(**lowercase       )

							requires_backends(self      ,      "vision"       )
							self.check_model_type(
							    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
							    if self.framework == "tf"
							    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING       )


			def __call__(    self      ,      lowercase      ,      **lowercase       )  ->						str:
							'''simple docstring'''






							return super().__call__(lowercase      ,      **lowercase       )


			def      UpperCamelCase		(    self      ,      **lowercase       )  ->						Optional[int]:
							'''simple docstring'''






							A__        =			{}
							if "candidate_labels" in kwargs:
											A__        =			kwargs["candidate_labels"]
							if "hypothesis_template" in kwargs:
											A__        =			kwargs["hypothesis_template"]

							return preprocess_params, {}, {}


			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase=None      ,      lowercase="This is a photo of {}."       )  ->						int:
							'''simple docstring'''






							A__        =			load_image(lowercase       )
							A__        =			self.image_processor(images=[image]      ,      return_tensors=self.framework       )
							A__        =			candidate_labels
							A__        =			[hypothesis_template.format(lowercase       ) for x in candidate_labels]
							A__        =			self.tokenizer(lowercase      ,      return_tensors=self.framework      ,      padding=lowercase       )
							A__        =			[text_inputs]
							return inputs


			def      UpperCamelCase		(    self      ,      lowercase       )  ->						Tuple:
							'''simple docstring'''






							A__        =			model_inputs.pop("candidate_labels"       )
							A__        =			model_inputs.pop("text_inputs"       )
							if isinstance(text_inputs[0]      ,      lowercase       ):
											A__        =			text_inputs[0]
							else:
											# Batching case.
											A__        =			text_inputs[0][0]

							A__        =			self.model(**lowercase      ,      **lowercase       )

							A__        =			{
							    "candidate_labels": candidate_labels,
							    "logits": outputs.logits_per_image,
							}
							return model_outputs


			def      UpperCamelCase		(    self      ,      lowercase       )  ->						Dict:
							'''simple docstring'''






							A__        =			model_outputs.pop("candidate_labels"       )
							A__        =			model_outputs["logits"][0]
							if self.framework == "pt":
											A__        =			logits.softmax(dim=-1       ).squeeze(-1       )
											A__        =			probs.tolist()
											if not isinstance(lowercase      ,      lowercase       ):
															A__        =			[scores]
							elif self.framework == "tf":
											A__        =			stable_softmax(lowercase      ,      axis=-1       )
											A__        =			probs.numpy().tolist()
							else:
											raise ValueError(F'Unsupported framework: {self.framework}'       )

							A__        =			[
							    {"score": score, "label": candidate_label}
							    for score, candidate_label in sorted(zip(lowercase      ,      lowercase       )      ,      key=lambda lowercase       : -x[0]       )
							]
							return result




import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
lowerCAmelCase__	   = """src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
lowerCAmelCase__	   = direct_transformers_import(PATH_TO_TRANSFORMERS)

lowerCAmelCase__	   = transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
lowerCAmelCase__	   = re.compile(R"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""")


lowerCAmelCase__	   = {
    """DecisionTransformerConfig""",
    """EncoderDecoderConfig""",
    """MusicgenConfig""",
    """RagConfig""",
    """SpeechEncoderDecoderConfig""",
    """TimmBackboneConfig""",
    """VisionEncoderDecoderConfig""",
    """VisionTextDualEncoderConfig""",
    """LlamaConfig""",
}



def 					lowerCAmelCase__							(	SCREAMING_SNAKE_CASE_:							Union[str, Any]      )			->      Dict:




				'''simple docstring'''





				A__        =			None

				# source code of `config_class`
				A__        =			inspect.getsource(SCREAMING_SNAKE_CASE_      )
				A__        =			_re_checkpoint.findall(SCREAMING_SNAKE_CASE_      )

				# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
				# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
				for ckpt_name, ckpt_link in checkpoints:
								# allow the link to end with `/`
								if ckpt_link.endswith("/"      ):
												A__        =			ckpt_link[:-1]

								# verify the checkpoint name corresponds to the checkpoint link
								A__        =			F'https://huggingface.co/{ckpt_name}'
								if ckpt_link == ckpt_link_from_name:
												A__        =			ckpt_name
												break

				return checkpoint



def 					lowerCAmelCase__							(	)			->      List[str]:




				'''simple docstring'''





				A__        =			[]

				for config_class in list(CONFIG_MAPPING.values()      ):
								# Skip deprecated models
								if "models.deprecated" in config_class.__module__:
												continue
								A__        =			get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE_      )

								A__        =			config_class.__name__
								if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
												configs_without_checkpoint.append(SCREAMING_SNAKE_CASE_      )

				if len(SCREAMING_SNAKE_CASE_      ) > 0:
								A__        =			"\n".join(sorted(SCREAMING_SNAKE_CASE_      )      )
								raise ValueError(F'The following configurations don\'t contain any valid checkpoint:\n{message}'      )


if __name__ == "__main__":
	check_config_docstrings_have_checkpoints()

