






'''simple docstring'''







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

_A			:    int					  =logging.get_logger(__name__)

@add_end_docstrings(SCREAMING_SNAKE_CASE__	)
class _lowercase			(       SCREAMING_SNAKE_CASE__	):




							def __init__(							self:       List[str]    ,							**UpperCamelCase__:       List[Any]  ):
														super().__init__(**snake_case__  )

														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:       List[Any]    ,							UpperCamelCase__:       Union[str, Any]    ,							**UpperCamelCase__:       Union[str, Any]  ):
														return super().__call__(snake_case__    ,							**snake_case__  )




							def 	lowerCamelCase_       (							self:       Union[str, Any]    ,							**UpperCamelCase__:       Any  ):
														lowerCamelCase__      :			Optional[int] 						= {}
														if "candidate_labels" in kwargs:
																					lowerCamelCase__      :			Optional[Any] 						= kwargs["candidate_labels"]
														if "hypothesis_template" in kwargs:
																					lowerCamelCase__      :			Tuple 						= kwargs["hypothesis_template"]

														return preprocess_params, {}, {}




							def 	lowerCamelCase_       (							self:       Union[str, Any]    ,							UpperCamelCase__:       Tuple    ,							UpperCamelCase__:       List[str]=None    ,							UpperCamelCase__:       Any="This is a photo of {}."  ):
														lowerCamelCase__      :			Tuple 						= load_image(snake_case__  )
														lowerCamelCase__      :			List[str] 						= self.image_processor(images=[image]    ,							return_tensors=self.framework  )
														lowerCamelCase__      :			Any 						= candidate_labels
														lowerCamelCase__      :			Optional[Any] 						= [hypothesis_template.format(snake_case__  ) for x in candidate_labels]
														lowerCamelCase__      :			Tuple 						= self.tokenizer(snake_case__    ,							return_tensors=self.framework    ,							padding=snake_case__  )
														lowerCamelCase__      :			int 						= [text_inputs]
														return inputs




							def 	lowerCamelCase_       (							self:       Any    ,							UpperCamelCase__:       List[Any]  ):
														lowerCamelCase__      :			Dict 						= model_inputs.pop("""candidate_labels"""  )
														lowerCamelCase__      :			Optional[int] 						= model_inputs.pop("""text_inputs"""  )
														if isinstance(text_inputs[0]    ,							snake_case__  ):
																					lowerCamelCase__      :			List[Any] 						= text_inputs[0]
														else:
																					# Batching case.
																					lowerCamelCase__      :			Dict 						= text_inputs[0][0]

														lowerCamelCase__      :			List[Any] 						= self.model(**snake_case__    ,							**snake_case__  )

														lowerCamelCase__      :			List[Any] 						= {
														    "candidate_labels": candidate_labels,
														    "logits": outputs.logits_per_image,
														}
														return model_outputs




							def 	lowerCamelCase_       (							self:       Optional[Any]    ,							UpperCamelCase__:       List[str]  ):
														lowerCamelCase__      :			List[Any] 						= model_outputs.pop("""candidate_labels"""  )
														lowerCamelCase__      :			Optional[int] 						= model_outputs["logits"][0]
														if self.framework == "pt":
																					lowerCamelCase__      :			Union[str, Any] 						= logits.softmax(dim=-1  ).squeeze(-1  )
																					lowerCamelCase__      :			List[str] 						= probs.tolist()
																					if not isinstance(snake_case__    ,							snake_case__  ):
																												lowerCamelCase__      :			Optional[Any] 						= [scores]
														elif self.framework == "tf":
																					lowerCamelCase__      :			Any 						= stable_softmax(snake_case__    ,							axis=-1  )
																					lowerCamelCase__      :			str 						= probs.numpy().tolist()
														else:
																					raise ValueError(F'''Unsupported framework: {self.framework}'''  )

														lowerCamelCase__      :			List[Any] 						= [
														    {"score": score, "label": candidate_label}
														    for score, candidate_label in sorted(zip(snake_case__    ,							snake_case__  )    ,							key=lambda UpperCamelCase__  : -x[0]  )
														]
														return result









'''simple docstring'''







from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A			:    Any					  =logging.get_logger(__name__)

_A			:    Dict					  ={
    '''microsoft/trocr-base-handwritten''': (
        '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'''
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}

class _lowercase			(       _lowercase	):
							a          = """trocr"""
							a          = ["""past_key_values"""]
							a          = {
							    """num_attention_heads""": """decoder_attention_heads""",
							    """hidden_size""": """d_model""",
							    """num_hidden_layers""": """decoder_layers""",
							}




							def __init__(							self:       Optional[Any]    ,							UpperCamelCase__:       int=50_265    ,							UpperCamelCase__:       int=1_024    ,							UpperCamelCase__:       Optional[Any]=12    ,							UpperCamelCase__:       Dict=16    ,							UpperCamelCase__:       int=4_096    ,							UpperCamelCase__:       Tuple="gelu"    ,							UpperCamelCase__:       int=512    ,							UpperCamelCase__:       Dict=0.1    ,							UpperCamelCase__:       Tuple=0.0    ,							UpperCamelCase__:       str=0.0    ,							UpperCamelCase__:       Any=2    ,							UpperCamelCase__:       Dict=0.02    ,							UpperCamelCase__:       Optional[Any]=0.0    ,							UpperCamelCase__:       str=True    ,							UpperCamelCase__:       Tuple=False    ,							UpperCamelCase__:       Union[str, Any]=True    ,							UpperCamelCase__:       Tuple=True    ,							UpperCamelCase__:       Dict=1    ,							UpperCamelCase__:       List[str]=0    ,							UpperCamelCase__:       Union[str, Any]=2    ,							**UpperCamelCase__:       str    ,							):
														lowerCamelCase__      :			Any 						= vocab_size
														lowerCamelCase__      :			Tuple 						= d_model
														lowerCamelCase__      :			Any 						= decoder_layers
														lowerCamelCase__      :			Dict 						= decoder_attention_heads
														lowerCamelCase__      :			str 						= decoder_ffn_dim
														lowerCamelCase__      :			Tuple 						= activation_function
														lowerCamelCase__      :			Dict 						= max_position_embeddings
														lowerCamelCase__      :			int 						= dropout
														lowerCamelCase__      :			int 						= attention_dropout
														lowerCamelCase__      :			List[Any] 						= activation_dropout
														lowerCamelCase__      :			Union[str, Any] 						= init_std
														lowerCamelCase__      :			Optional[int] 						= decoder_layerdrop
														lowerCamelCase__      :			Dict 						= use_cache
														lowerCamelCase__      :			Any 						= scale_embedding
														lowerCamelCase__      :			Optional[int] 						= use_learned_position_embeddings
														lowerCamelCase__      :			List[str] 						= layernorm_embedding

														super().__init__(
														    pad_token_id=UpperCamelCase__    ,							bos_token_id=UpperCamelCase__    ,							eos_token_id=UpperCamelCase__    ,							decoder_start_token_id=UpperCamelCase__    ,							**UpperCamelCase__    ,							)

