






'''simple docstring'''



from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_torch_available():
 import torch

 from transformers.modeling_outputs import BaseModelOutput

 from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__UpperCamelCase   :							Optional[int]         =   logging.get_logger(__name__)
@add_end_docstrings(SCREAMING_SNAKE_CASE_  )
class 				__SCREAMING_SNAKE_CASE							(				SCREAMING_SNAKE_CASE_  ):




      def __init__(	self			, **lowerCamelCase   )				->List[str]:



         '''simple docstring'''
         super().__init__(**lowerCamelCase   )

         if self.framework == "tf":
            raise ValueError(F"""The {self.__class__} is only available in PyTorch."""   )

         requires_backends(self			, 'vision'   )
         self.check_model_type(lowerCamelCase   )




      def __call__(	self			, lowerCamelCase			, lowerCamelCase = None			, **lowerCamelCase			, )				->List[Any]:



         '''simple docstring'''
         if "text_queries" in kwargs:
            __a					  =     kwargs.pop('text_queries'   )

         if isinstance(lowerCamelCase			, (str, Image.Image)   ):
            __a					  =     {'image': image, 'candidate_labels': candidate_labels}
         else:
            __a					  =     image
         __a					  =     super().__call__(lowerCamelCase			, **lowerCamelCase   )
         return results




      def 			__UpperCamelCase				(	self			, **lowerCamelCase   )				->Dict:



         '''simple docstring'''
         __a					  =     {}
         if "threshold" in kwargs:
            __a					  =     kwargs['threshold']
         if "top_k" in kwargs:
            __a					  =     kwargs['top_k']
         return {}, {}, postprocess_params




      def 			__UpperCamelCase				(	self			, lowerCamelCase   )				->str:



         '''simple docstring'''
         __a					  =     load_image(inputs['image']   )
         __a					  =     inputs['candidate_labels']
         if isinstance(lowerCamelCase			, lowerCamelCase   ):
            __a					  =     candidate_labels.split(','   )

         __a					  =     torch.tensor([[image.height, image.width]]			, dtype=torch.intaa   )
         for i, candidate_label in enumerate(lowerCamelCase   ):
            __a					  =     self.tokenizer(lowerCamelCase			, return_tensors=self.framework   )
            __a					  =     self.image_processor(lowerCamelCase			, return_tensors=self.framework   )
            yield {
                "is_last": i == len(lowerCamelCase   ) - 1,
                "target_size": target_size,
                "candidate_label": candidate_label,
                **text_inputs,
                **image_features,
            }




      def 			__UpperCamelCase				(	self			, lowerCamelCase   )				->Optional[int]:



         '''simple docstring'''
         __a					  =     model_inputs.pop('target_size'   )
         __a					  =     model_inputs.pop('candidate_label'   )
         __a					  =     model_inputs.pop('is_last'   )

         __a					  =     self.model(**lowerCamelCase   )

         __a					  =     {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
         return model_outputs




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase=0.1			, lowerCamelCase=None   )				->Any:



         '''simple docstring'''
         __a					  =     []
         for model_output in model_outputs:
            __a					  =     model_output['candidate_label']
            __a					  =     BaseModelOutput(lowerCamelCase   )
            __a					  =     self.image_processor.post_process_object_detection(
                outputs=lowerCamelCase			, threshold=lowerCamelCase			, target_sizes=model_output['target_size']   )[0]

            for index in outputs["scores"].nonzero():
               __a					  =     outputs['scores'][index].item()
               __a					  =     self._get_bounding_box(outputs['boxes'][index][0]   )

               __a					  =     {'score': score, 'label': label, 'box': box}
               results.append(lowerCamelCase   )

         __a					  =     sorted(lowerCamelCase			, key=lambda lowerCamelCase   : x["score"]			, reverse=lowerCamelCase   )
         if top_k:
            __a					  =     results[:top_k]

         return results






      def 			__UpperCamelCase				(	self			, lowerCamelCase   )				->str:



         '''simple docstring'''
         if self.framework != "pt":
            raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'   )
         __a					  =     box.int().tolist()
         __a					  =     {
             'xmin': xmin,
             'ymin': ymin,
             'xmax': xmax,
             'ymax': ymax,
         }
         return bbox




"""simple docstring"""







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


a_							=    logging.get_logger(__name__)


a_							=    """▁"""

a_							=    {"""vocab_file""": """spiece.model"""}

a_							=    {
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    }
}

a_							=    {
    """google/reformer-crime-and-punishment""": 52_42_88,
}







class 					A_(SCREAMING_SNAKE_CASE_      ):







			"""simple docstring"""



			a_       :			Optional[int]												=			VOCAB_FILES_NAMES
			a_       :			int												=			PRETRAINED_VOCAB_FILES_MAP
			a_       :			str												=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			a_       :			Optional[Any]												=			["""input_ids""", """attention_mask"""]
			def __init__(	self				,   A				,   A="</s>"				,   A="<unk>"				,   A=[]				,   A = None				,   **A				,   ):
						_lowerCamelCase					:					Any	       =    {} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    eos_token=A				,   unk_token=A				,   additional_special_tokens=A				,   sp_model_kwargs=self.sp_model_kwargs				,   **A				,   )

						_lowerCamelCase					:					Dict	       =    vocab_file
						_lowerCamelCase					:					List[Any]	       =    spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(A							)
			@property
			def    _lowerCAmelCase		(	self							):
						return self.sp_model.get_piece_size()
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					int	       =    {self.convert_ids_to_tokens(A							): i for i in range(self.vocab_size							)}
						vocab.update(self.added_tokens_encoder							)
						return vocab
			def __getstate__(	self							):
						_lowerCamelCase					:					Optional[int]	       =    self.__dict__.copy()
						_lowerCamelCase					:					Union[str, Any]	       =    None
						return state
			def __setstate__(	self				,   A							):
						_lowerCamelCase					:					int	       =    d

						# for backward compatibility
						if not hasattr(self				,   'sp_model_kwargs'							):
									_lowerCamelCase					:					Union[str, Any]	       =    {}

						_lowerCamelCase					:					Dict	       =    spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(self.vocab_file							)
			def    _lowerCAmelCase		(	self				,   A							):
						return self.sp_model.encode(A				,   out_type=A							)
			def    _lowerCAmelCase		(	self				,   A							):
						return self.sp_model.piece_to_id(A							)
			def    _lowerCAmelCase		(	self				,   A							):
						if index < self.sp_model.get_piece_size():
									_lowerCamelCase					:					Dict	       =    self.sp_model.IdToPiece(A							)
						return token
			def    _lowerCAmelCase		(	self				,   A							):
						_lowerCamelCase					:					Tuple	       =    []
						_lowerCamelCase					:					Optional[int]	       =    ''
						for token in tokens:
									# make sure that special tokens are not decoded using sentencepiece model
									if token in self.all_special_tokens:
												out_string += self.sp_model.decode(A							) + token
												_lowerCamelCase					:					Dict	       =    []
									else:
												current_sub_tokens.append(A							)
						out_string += self.sp_model.decode(A							)
						return out_string.strip()

			def    _lowerCAmelCase		(	self				,   A				,   A = None							):
						if not os.path.isdir(A							):
									logger.error(F"Vocabulary path ({save_directory}) should be a directory"							)
									return
						_lowerCamelCase					:					Any	       =    os.path.join(
						    A				,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)

						if os.path.abspath(self.vocab_file							) != os.path.abspath(A							) and os.path.isfile(self.vocab_file							):
									copyfile(self.vocab_file				,   A							)
						elif not os.path.isfile(self.vocab_file							):
									with open(A				,   'wb'							) as fi:
												_lowerCamelCase					:					List[str]	       =    self.sp_model.serialized_model_proto()
												fi.write(A							)

						return (out_vocab_file,)





