






import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch



class 							_UpperCamelCase			(a_			):
      snake_case_  =							"""char"""
      snake_case_  =							"""bpe"""
      snake_case_  =							"""wp"""

lowerCamelCase			:					Optional[Any]         =	(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)



class 							_UpperCamelCase			(a_			):
      snake_case_  =							["""image_processor""", """char_tokenizer"""]
      snake_case_  =							"""ViTImageProcessor"""
      snake_case_  =							"""MgpstrTokenizer"""


      def __init__(	self					,						__UpperCamelCase=None					,						__UpperCamelCase=None					,						**__UpperCamelCase	)->	Dict:
           __lowerCAmelCase								=					None
           if "feature_extractor" in kwargs:
                warnings.warn(
                    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                    " instead."					,						__UpperCamelCase					,						)
                __lowerCAmelCase								=					kwargs.pop("feature_extractor"	)

           __lowerCAmelCase								=					image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
                raise ValueError("You need to specify an `image_processor`."	)
           if tokenizer is None:
                raise ValueError("You need to specify a `tokenizer`."	)

           __lowerCAmelCase								=					tokenizer
           __lowerCAmelCase								=					AutoTokenizer.from_pretrained("gpt2"	)
           __lowerCAmelCase								=					AutoTokenizer.from_pretrained("bert-base-uncased"	)

           super().__init__(__UpperCamelCase					,						__UpperCamelCase	)


      def __call__(	self					,						__UpperCamelCase=None					,						__UpperCamelCase=None					,						__UpperCamelCase=None					,						**__UpperCamelCase	)->	str:
           if images is None and text is None:
                raise ValueError("You need to specify either an `images` or `text` input to process."	)

           if images is not None:
                __lowerCAmelCase								=					self.image_processor(__UpperCamelCase					,						return_tensors=__UpperCamelCase					,						**__UpperCamelCase	)
           if text is not None:
                __lowerCAmelCase								=					self.char_tokenizer(__UpperCamelCase					,						return_tensors=__UpperCamelCase					,						**__UpperCamelCase	)

           if text is None:
                return inputs
           elif images is None:
                return encodings
           else:
                __lowerCAmelCase								=					encodings["input_ids"]
                return inputs


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase	)->	List[Any]:
           __lowerCAmelCase			, __lowerCAmelCase			, __lowerCAmelCase								=					sequences
           __lowerCAmelCase								=					char_preds.size(0	)

           __lowerCAmelCase			, __lowerCAmelCase								=					self._decode_helper(__UpperCamelCase					,						"char"	)
           __lowerCAmelCase			, __lowerCAmelCase								=					self._decode_helper(__UpperCamelCase					,						"bpe"	)
           __lowerCAmelCase			, __lowerCAmelCase								=					self._decode_helper(__UpperCamelCase					,						"wp"	)

           __lowerCAmelCase								=					[]
           __lowerCAmelCase								=					[]
           for i in range(__UpperCamelCase	):
                __lowerCAmelCase								=					[char_scores[i], bpe_scores[i], wp_scores[i]]
                __lowerCAmelCase								=					[char_strs[i], bpe_strs[i], wp_strs[i]]
                __lowerCAmelCase								=					scores.index(max(__UpperCamelCase	)	)
                final_strs.append(strs[max_score_index]	)
                final_scores.append(scores[max_score_index]	)

           __lowerCAmelCase								=					{}
           __lowerCAmelCase								=					final_strs
           __lowerCAmelCase								=					final_scores
           __lowerCAmelCase								=					char_strs
           __lowerCAmelCase								=					bpe_strs
           __lowerCAmelCase								=					wp_strs
           return out


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase	)->	Any:
           if format == DecodeType.CHARACTER:
                __lowerCAmelCase								=					self.char_decode
                __lowerCAmelCase								=					1
                __lowerCAmelCase								=					"[s]"
           elif format == DecodeType.BPE:
                __lowerCAmelCase								=					self.bpe_decode
                __lowerCAmelCase								=					2
                __lowerCAmelCase								=					"#"
           elif format == DecodeType.WORDPIECE:
                __lowerCAmelCase								=					self.wp_decode
                __lowerCAmelCase								=					1_0_2
                __lowerCAmelCase								=					"[SEP]"
           else:
                raise ValueError(F"""Format {format} is not supported."""	)

           __lowerCAmelCase			, __lowerCAmelCase								=					[], []
           __lowerCAmelCase								=					pred_logits.size(0	)
           __lowerCAmelCase								=					pred_logits.size(1	)
           __lowerCAmelCase			, __lowerCAmelCase								=					pred_logits.topk(1					,						dim=-1					,						largest=__UpperCamelCase					,						sorted=__UpperCamelCase	)
           __lowerCAmelCase								=					preds_index.view(-1					,						__UpperCamelCase	)[:, 1:]
           __lowerCAmelCase								=					decoder(__UpperCamelCase	)
           __lowerCAmelCase			, __lowerCAmelCase								=					torch.nn.functional.softmax(__UpperCamelCase					,						dim=2	).max(dim=2	)
           __lowerCAmelCase								=					preds_max_prob[:, 1:]

           for index in range(__UpperCamelCase	):
                __lowerCAmelCase								=					preds_str[index].find(__UpperCamelCase	)
                __lowerCAmelCase								=					preds_str[index][:pred_eos]
                __lowerCAmelCase								=					preds_index[index].cpu().tolist()
                __lowerCAmelCase								=					pred_index.index(__UpperCamelCase	) if eos_token in pred_index else -1
                __lowerCAmelCase								=					preds_max_prob[index][: pred_eos_index + 1]
                __lowerCAmelCase								=					pred_max_prob.cumprod(dim=0	)[-1] if pred_max_prob.nelement() != 0 else 0.0
                dec_strs.append(__UpperCamelCase	)
                conf_scores.append(__UpperCamelCase	)

           return dec_strs, conf_scores


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase	)->	Tuple:
           __lowerCAmelCase								=					[seq.replace(" "					,						""	) for seq in self.char_tokenizer.batch_decode(__UpperCamelCase	)]
           return decode_strs


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase	)->	Optional[int]:
           return self.bpe_tokenizer.batch_decode(__UpperCamelCase	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase	)->	List[str]:
           __lowerCAmelCase								=					[seq.replace(" "					,						""	) for seq in self.wp_tokenizer.batch_decode(__UpperCamelCase	)]
           return decode_strs














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


lowerCamelCase			:					int         =	logging.get_logger(__name__)

lowerCamelCase			:					Tuple         =	{
    '''caidas/swin2sr-classicalsr-x2-64''': (
        '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json'''
    ),
}



class 							_UpperCamelCase			(a_			):
      snake_case_  =							"""swin2sr"""

      snake_case_  =							{
          """hidden_size""": """embed_dim""",
          """num_attention_heads""": """num_heads""",
          """num_hidden_layers""": """num_layers""",
      }


      def __init__(	self					,						__UpperCamelCase=6_4					,						__UpperCamelCase=1					,						__UpperCamelCase=3					,						__UpperCamelCase=1_8_0					,						__UpperCamelCase=[6, 6, 6, 6, 6, 6]					,						__UpperCamelCase=[6, 6, 6, 6, 6, 6]					,						__UpperCamelCase=8					,						__UpperCamelCase=2.0					,						__UpperCamelCase=True					,						__UpperCamelCase=0.0					,						__UpperCamelCase=0.0					,						__UpperCamelCase=0.1					,						__UpperCamelCase="gelu"					,						__UpperCamelCase=False					,						__UpperCamelCase=0.0_2					,						__UpperCamelCase=1e-5					,						__UpperCamelCase=2					,						__UpperCamelCase=1.0					,						__UpperCamelCase="1conv"					,						__UpperCamelCase="pixelshuffle"					,						**__UpperCamelCase					,						)->	Tuple:
           super().__init__(**__UpperCamelCase	)

           __lowerCAmelCase								=					image_size
           __lowerCAmelCase								=					patch_size
           __lowerCAmelCase								=					num_channels
           __lowerCAmelCase								=					embed_dim
           __lowerCAmelCase								=					depths
           __lowerCAmelCase								=					len(__UpperCamelCase	)
           __lowerCAmelCase								=					num_heads
           __lowerCAmelCase								=					window_size
           __lowerCAmelCase								=					mlp_ratio
           __lowerCAmelCase								=					qkv_bias
           __lowerCAmelCase								=					hidden_dropout_prob
           __lowerCAmelCase								=					attention_probs_dropout_prob
           __lowerCAmelCase								=					drop_path_rate
           __lowerCAmelCase								=					hidden_act
           __lowerCAmelCase								=					use_absolute_embeddings
           __lowerCAmelCase								=					layer_norm_eps
           __lowerCAmelCase								=					initializer_range
           __lowerCAmelCase								=					upscale
           __lowerCAmelCase								=					img_range
           __lowerCAmelCase								=					resi_connection
           __lowerCAmelCase								=					upsampler






