




import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf

	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

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

a__		     =     logging.get_logger(__name__)


class    SCREAMING_SNAKE_CASE_				(       enum.Enum   ):



	"""simple docstring"""


	__magic_name__   :       Optional[int]      	=		0
	__magic_name__   :       str      	=		1






@add_end_docstrings(_UpperCamelCase   )
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	__magic_name__   :       Optional[Any]      	=		'generated'






	def __init__(					self		:						List[str]					,     *lowerCAmelCase		:						Tuple					,     **lowerCAmelCase		:						Tuple	)	->       int:







						"""simple docstring"""







						super().__init__(*lowerCAmelCase					,     **lowerCAmelCase	)

						self.check_model_type(
						    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						    if self.framework == """tf"""
						    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING	)






	def 					lowerCamelCase__     (					self		:						Any					,     lowerCAmelCase		:						Optional[Any]=None					,     lowerCAmelCase		:						Union[str, Any]=None					,     lowerCAmelCase		:						Dict=None					,     lowerCAmelCase		:						List[str]=None					,     lowerCAmelCase		:						Dict=None					,     lowerCAmelCase		:						int=None					,     **lowerCAmelCase		:						Optional[Any]					,     )	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      {}
						if truncation is not None:
											__UpperCamelCase					:	int             =      truncation

						__UpperCamelCase					:	List[Any]             =      generate_kwargs

						__UpperCamelCase					:	Optional[Any]             =      {}
						if return_tensors is not None and return_type is None:
											__UpperCamelCase					:	Optional[int]             =      ReturnType.TENSORS if return_tensors else ReturnType.TEXT
						if return_type is not None:
											__UpperCamelCase					:	Tuple             =      return_type

						if clean_up_tokenization_spaces is not None:
											__UpperCamelCase					:	Union[str, Any]             =      clean_up_tokenization_spaces

						if stop_sequence is not None:
											__UpperCamelCase					:	Union[str, Any]             =      self.tokenizer.encode(lowerCAmelCase					,     add_special_tokens=lowerCAmelCase	)
											if len(lowerCAmelCase	) > 1:
																warnings.warn(
																    """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
																    """ the stop sequence will be used as the stop sequence string in the interim."""	)
											__UpperCamelCase					:	Any             =      stop_sequence_ids[0]

						return preprocess_params, forward_params, postprocess_params






	def 					lowerCamelCase__     (					self		:						Dict					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int	)	->       Dict:







						"""simple docstring"""







						return True






	def 					lowerCamelCase__     (					self		:						List[str]					,     *lowerCAmelCase		:						Tuple					,     lowerCAmelCase		:						Tuple	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Tuple             =      self.model.config.prefix if self.model.config.prefix is not None else """"""
						if isinstance(args[0]					,     lowerCAmelCase	):
											if self.tokenizer.pad_token_id is None:
																raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input"""	)
											__UpperCamelCase					:	List[str]             =      ([prefix + arg for arg in args[0]],)
											__UpperCamelCase					:	Union[str, Any]             =      True

						elif isinstance(args[0]					,     lowerCAmelCase	):
											__UpperCamelCase					:	Tuple             =      (prefix + args[0],)
											__UpperCamelCase					:	Optional[int]             =      False
						else:
											raise ValueError(
											    F''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'''	)
						__UpperCamelCase					:	List[Any]             =      self.tokenizer(*lowerCAmelCase					,     padding=lowerCAmelCase					,     truncation=lowerCAmelCase					,     return_tensors=self.framework	)
						# This is produced by tokenizers but is an invalid generate kwargs
						if "token_type_ids" in inputs:
											del inputs["token_type_ids"]
						return inputs






	def __call__(					self		:						Tuple					,     *lowerCAmelCase		:						str					,     **lowerCAmelCase		:						Optional[int]	)	->       Union[str, Any]:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      super().__call__(*lowerCAmelCase					,     **lowerCAmelCase	)
						if (
						    isinstance(args[0]					,     lowerCAmelCase	)
						    and all(isinstance(lowerCAmelCase					,     lowerCAmelCase	) for el in args[0]	)
						    and all(len(lowerCAmelCase	) == 1 for res in result	)
						):
											return [res[0] for res in result]
						return result






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						Any=TruncationStrategy.DO_NOT_TRUNCATE					,     **lowerCAmelCase		:						str	)	->       int:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      self._parse_and_tokenize(lowerCAmelCase					,     truncation=lowerCAmelCase					,     **lowerCAmelCase	)
						return inputs






	def 					lowerCamelCase__     (					self		:						Optional[Any]					,     lowerCAmelCase		:						Optional[Any]					,     **lowerCAmelCase		:						Tuple	)	->       int:







						"""simple docstring"""







						if self.framework == "pt":
											__UpperCamelCase      ,			__UpperCamelCase					:	Union[str, Any]             =      model_inputs["""input_ids"""].shape
						elif self.framework == "tf":
											__UpperCamelCase      ,			__UpperCamelCase					:	Tuple             =      tf.shape(model_inputs["""input_ids"""]	).numpy()

						__UpperCamelCase					:	Optional[int]             =      generate_kwargs.get("""min_length"""					,     self.model.config.min_length	)
						__UpperCamelCase					:	Any             =      generate_kwargs.get("""max_length"""					,     self.model.config.max_length	)
						self.check_inputs(lowerCAmelCase					,     generate_kwargs["""min_length"""]					,     generate_kwargs["""max_length"""]	)
						__UpperCamelCase					:	List[Any]             =      self.model.generate(**lowerCAmelCase					,     **lowerCAmelCase	)
						__UpperCamelCase					:	int             =      output_ids.shape[0]
						if self.framework == "pt":
											__UpperCamelCase					:	Any             =      output_ids.reshape(lowerCAmelCase					,     out_b // in_b					,     *output_ids.shape[1:]	)
						elif self.framework == "tf":
											__UpperCamelCase					:	str             =      tf.reshape(lowerCAmelCase					,     (in_b, out_b // in_b, *output_ids.shape[1:])	)
						return {"output_ids": output_ids}






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						List[Any]					,     lowerCAmelCase		:						List[Any]=ReturnType.TEXT					,     lowerCAmelCase		:						Tuple=False	)	->       List[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      []
						for output_ids in model_outputs["output_ids"][0]:
											if return_type == ReturnType.TENSORS:
																__UpperCamelCase					:	List[str]             =      {F'''{self.return_name}_token_ids''': output_ids}
											elif return_type == ReturnType.TEXT:
																__UpperCamelCase					:	str             =      {
																    F'''{self.return_name}_text''': self.tokenizer.decode(
																        lowerCAmelCase					,     skip_special_tokens=lowerCAmelCase					,     clean_up_tokenization_spaces=lowerCAmelCase					,     )
																}
											records.append(lowerCAmelCase	)
						return records






@add_end_docstrings(_UpperCamelCase   )
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	__magic_name__   :       Any      	=		'summary'






	def __call__(					self		:						Dict					,     *lowerCAmelCase		:						Union[str, Any]					,     **lowerCAmelCase		:						Optional[Any]	)	->       Tuple:







						"""simple docstring"""







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






	def 					lowerCamelCase__     (					self		:						Union[str, Any]					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int	)	->       bool:







						"""simple docstring"""







						if max_length < min_length:
											logger.warning(F'''Your min_length={min_length} must be inferior than your max_length={max_length}.'''	)

						if input_length < max_length:
											logger.warning(
											    F'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '''
											    """a summarization task, where outputs shorter than the input are typically wanted, you might """
											    F'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'''	)






@add_end_docstrings(_UpperCamelCase   )
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	__magic_name__   :       str      	=		'translation'






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						int	)	->       List[Any]:







						"""simple docstring"""







						if input_length > 0.9 * max_length:
											logger.warning(
											    F'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '''
											    """increasing your max_length manually, e.g. translator('...', max_length=400)"""	)
						return True






	def 					lowerCamelCase__     (					self		:						List[str]					,     *lowerCAmelCase		:						Optional[int]					,     lowerCAmelCase		:						int=TruncationStrategy.DO_NOT_TRUNCATE					,     lowerCAmelCase		:						Optional[Any]=None					,     lowerCAmelCase		:						Any=None	)	->       int:







						"""simple docstring"""







						if getattr(self.tokenizer					,     """_build_translation_inputs"""					,     lowerCAmelCase	):
											return self.tokenizer._build_translation_inputs(
											    *lowerCAmelCase					,     return_tensors=self.framework					,     truncation=lowerCAmelCase					,     src_lang=lowerCAmelCase					,     tgt_lang=lowerCAmelCase	)
						else:
											return super()._parse_and_tokenize(*lowerCAmelCase					,     truncation=lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						List[Any]					,     lowerCAmelCase		:						Any=None					,     lowerCAmelCase		:						int=None					,     **lowerCAmelCase		:						List[str]	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase      ,			__UpperCamelCase      ,			__UpperCamelCase					:	Union[str, Any]             =      super()._sanitize_parameters(**lowerCAmelCase	)
						if src_lang is not None:
											__UpperCamelCase					:	List[str]             =      src_lang
						if tgt_lang is not None:
											__UpperCamelCase					:	List[Any]             =      tgt_lang
						if src_lang is None and tgt_lang is None:
											# Backward compatibility, direct arguments use is preferred.
											__UpperCamelCase					:	List[str]             =      kwargs.get("""task"""					,     self.task	)
											__UpperCamelCase					:	int             =      task.split("""_"""	)
											if task and len(lowerCAmelCase	) == 4:
																# translation, XX, to YY
																__UpperCamelCase					:	int             =      items[1]
																__UpperCamelCase					:	Optional[int]             =      items[3]
						return preprocess_params, forward_params, postprocess_params






	def __call__(					self		:						List[Any]					,     *lowerCAmelCase		:						Union[str, Any]					,     **lowerCAmelCase		:						Optional[Any]	)	->       List[Any]:







						"""simple docstring"""







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












# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


a__		     =     {
    '''configuration_efficientnet''': [
        '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EfficientNetConfig''',
        '''EfficientNetOnnxConfig''',
    ]
}

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__		     =     ['''EfficientNetImageProcessor''']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__		     =     [
	    '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''EfficientNetForImageClassification''',
	    '''EfficientNetModel''',
	    '''EfficientNetPreTrainedModel''',
	]

if TYPE_CHECKING:
	from .configuration_efficientnet import (
	    EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    EfficientNetConfig,
	    EfficientNetOnnxConfig,
	)

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .image_processing_efficientnet import EfficientNetImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_efficientnet import (
		    EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
		    EfficientNetForImageClassification,
		    EfficientNetModel,
		    EfficientNetPreTrainedModel,
		)

else:
	import sys

	a__		     =     _LazyModule(__name__, globals()['''__file__'''], _import_structure)






