






import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
     import jax
     import jaxlib

lowercase							=     get_logger()

lowercase							=     None




class 			snake_case__   (							TensorFormatter[Mapping, "jax.Array", Mapping]):

       '''simple docstring'''



       def __init__(							self			,						a__=None			,						a__=None			,						**a__    ) ->      List[Any]:






            '''simple docstring'''





            super().__init__(features=snake_case_    )
            import jax
            from jaxlib.xla_client import Device

            if isinstance(snake_case_			,						snake_case_    ):
                 raise ValueError(
                     F'''Expected {device} to be a `str` not {type(snake_case_    )}, as `jaxlib.xla_extension.Device` '''
                     """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """
                     """the device with `str()` to get its string identifier that will be internally mapped """
                     """to the actual `jaxlib.xla_extension.Device`."""    )
            __snake_case			:Union[str, Any]          =						device if isinstance(snake_case_			,						snake_case_    ) else str(jax.devices()[0]    )
            # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
            # with `pickle` nor with `dill`, so we need to use a global variable instead
            global DEVICE_MAPPING
            if DEVICE_MAPPING is None:
                 __snake_case			:Tuple          =						self._map_devices_to_str()
            if self.device not in list(DEVICE_MAPPING.keys()    ):
                 logger.warning(
                     F'''Device with string identifier {self.device} not listed among the available '''
                     F'''devices: {list(DEVICE_MAPPING.keys()    )}, so falling back to the default '''
                     F'''device: {str(jax.devices()[0]    )}.'''    )
                 __snake_case			:Dict          =						str(jax.devices()[0]    )
            __snake_case			:List[Any]          =						jnp_array_kwargs



       @staticmethod
       def 					__lowercase						(							) ->      List[Any]:






            '''simple docstring'''





            import jax

            return {str(snake_case_    ): device for device in jax.devices()}



       def 					__lowercase						(							self			,						a__    ) ->      List[Any]:






            '''simple docstring'''





            import jax
            import jax.numpy as jnp

            if isinstance(snake_case_			,						snake_case_    ) and column:
                 if all(
                     isinstance(snake_case_			,						jax.Array    ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column    ):
                      return jnp.stack(snake_case_			,						axis=0    )
            return column



       def 					__lowercase						(							self			,						a__    ) ->      Any:






            '''simple docstring'''





            import jax
            import jax.numpy as jnp

            if isinstance(snake_case_			,						(str, bytes, type(snake_case_    ))    ):
                 return value
            elif isinstance(snake_case_			,						(np.character, np.ndarray)    ) and np.issubdtype(value.dtype			,						np.character    ):
                 return value.tolist()

            __snake_case			:Union[str, Any]          =						{}

            if isinstance(snake_case_			,						(np.number, np.ndarray)    ) and np.issubdtype(value.dtype			,						np.integer    ):
                 # the default int precision depends on the jax config
                 # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
                 if jax.config.jax_enable_xaa:
                      __snake_case			:Optional[int]          =						{"dtype": jnp.intaa}
                 else:
                      __snake_case			:Union[str, Any]          =						{"dtype": jnp.intaa}
            elif isinstance(snake_case_			,						(np.number, np.ndarray)    ) and np.issubdtype(value.dtype			,						np.floating    ):
                 __snake_case			:List[str]          =						{"dtype": jnp.floataa}
            elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(snake_case_			,						PIL.Image.Image    ):
                      __snake_case			:Optional[Any]          =						np.asarray(snake_case_    )

                 # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
                 # with `pickle` nor with `dill`, so we need to use a global variable instead
            global DEVICE_MAPPING
            if DEVICE_MAPPING is None:
                 __snake_case			:str          =						self._map_devices_to_str()

            with jax.default_device(DEVICE_MAPPING[self.device]    ):
                 # calling jnp.array on a np.ndarray does copy the data
                 # see https://github.com/google/jax/issues/4486
                 return jnp.array(snake_case_			,						**{**default_dtype, **self.jnp_array_kwargs}    )



       def 					__lowercase						(							self			,						a__    ) ->      Any:






            '''simple docstring'''





            import jax

            # support for torch, tf, jax etc.
            if config.TORCH_AVAILABLE and "torch" in sys.modules:
                 import torch

                 if isinstance(snake_case_			,						torch.Tensor    ):
                      return self._tensorize(data_struct.detach().cpu().numpy()[()]    )
            if hasattr(snake_case_			,						"""__array__"""    ) and not isinstance(snake_case_			,						jax.Array    ):
                 __snake_case			:Tuple          =						data_struct.__array__()
            # support for nested types like struct of list of struct
            if isinstance(snake_case_			,						np.ndarray    ):
                 if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
                      return self._consolidate([self.recursive_tensorize(snake_case_    ) for substruct in data_struct]    )
            elif isinstance(snake_case_			,						(list, tuple)    ):
                 return self._consolidate([self.recursive_tensorize(snake_case_    ) for substruct in data_struct]    )
            return self._tensorize(snake_case_    )



       def 					__lowercase						(							self			,						a__    ) ->      List[str]:






            '''simple docstring'''





            return map_nested(self._recursive_tensorize			,						snake_case_			,						map_list=snake_case_    )



       def 					__lowercase						(							self			,						a__    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.numpy_arrow_extractor().extract_row(snake_case_    )
            __snake_case			:Optional[int]          =						self.python_features_decoder.decode_row(snake_case_    )
            return self.recursive_tensorize(snake_case_    )



       def 					__lowercase						(							self			,						a__    ) ->      int:






            '''simple docstring'''





            __snake_case			:Any          =						self.numpy_arrow_extractor().extract_column(snake_case_    )
            __snake_case			:Any          =						self.python_features_decoder.decode_column(snake_case_			,						pa_table.column_names[0]    )
            __snake_case			:Any          =						self.recursive_tensorize(snake_case_    )
            __snake_case			:str          =						self._consolidate(snake_case_    )
            return column



       def 					__lowercase						(							self			,						a__    ) ->      int:






            '''simple docstring'''





            __snake_case			:int          =						self.numpy_arrow_extractor().extract_batch(snake_case_    )
            __snake_case			:Optional[int]          =						self.python_features_decoder.decode_batch(snake_case_    )
            __snake_case			:Union[str, Any]          =						self.recursive_tensorize(snake_case_    )
            for column_name in batch:
                 __snake_case			:int          =						self._consolidate(batch[column_name]    )
            return batch










import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
lowerCamelCase__							=     {"""LayoutLMv2Config""", """LayoutLMv3Config"""}




@is_pipeline_test
class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				List[Any] 				= MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
       lowerCamelCase							:				Tuple 				= TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

       if model_mapping is not None:
              lowerCamelCase							:				List[Any] 				= {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
       if tf_model_mapping is not None:
              lowerCamelCase							:				List[str] 				= {
                  config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
              }



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						ZeroShotClassificationPipeline(
                model=a__			,						tokenizer=a__			,						candidate_labels=["""polics""", """health"""]    )
            return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]



       def 					__lowercase						(							self			,						a__			,						a__    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case			:Tuple          =						classifier("""Who are you voting for in 2020?"""			,						candidate_labels="""politics"""    )
            self.assertEqual(a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    )], """scores""": [ANY(a__    )]}    )

            # No kwarg
            __snake_case			:Optional[int]          =						classifier("""Who are you voting for in 2020?"""			,						["""politics"""]    )
            self.assertEqual(a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    )], """scores""": [ANY(a__    )]}    )

            __snake_case			:Tuple          =						classifier("""Who are you voting for in 2020?"""			,						candidate_labels=["""politics"""]    )
            self.assertEqual(a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    )], """scores""": [ANY(a__    )]}    )

            __snake_case			:List[str]          =						classifier("""Who are you voting for in 2020?"""			,						candidate_labels="""politics, public health"""    )
            self.assertEqual(
                a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    ), ANY(a__    )], """scores""": [ANY(a__    ), ANY(a__    )]}    )
            self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]    )    )			,						1.0    )

            __snake_case			:Optional[Any]          =						classifier("""Who are you voting for in 2020?"""			,						candidate_labels=["""politics""", """public health"""]    )
            self.assertEqual(
                a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    ), ANY(a__    )], """scores""": [ANY(a__    ), ANY(a__    )]}    )
            self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]    )    )			,						1.0    )

            __snake_case			:List[str]          =						classifier(
                """Who are you voting for in 2020?"""			,						candidate_labels="""politics"""			,						hypothesis_template="""This text is about {}"""    )
            self.assertEqual(a__			,						{"""sequence""": ANY(a__    ), """labels""": [ANY(a__    )], """scores""": [ANY(a__    )]}    )

            # https://github.com/huggingface/transformers/issues/13846
            __snake_case			:Union[str, Any]          =						classifier(["""I am happy"""]			,						["""positive""", """negative"""]    )
            self.assertEqual(
                a__			,						[
                    {"""sequence""": ANY(a__    ), """labels""": [ANY(a__    ), ANY(a__    )], """scores""": [ANY(a__    ), ANY(a__    )]}
                    for i in range(1    )
                ]			,						)
            __snake_case			:Tuple          =						classifier(["""I am happy""", """I am sad"""]			,						["""positive""", """negative"""]    )
            self.assertEqual(
                a__			,						[
                    {"""sequence""": ANY(a__    ), """labels""": [ANY(a__    ), ANY(a__    )], """scores""": [ANY(a__    ), ANY(a__    )]}
                    for i in range(2    )
                ]			,						)

            with self.assertRaises(a__    ):
                 classifier(""""""			,						candidate_labels="""politics"""    )

            with self.assertRaises(a__    ):
                 classifier(a__			,						candidate_labels="""politics"""    )

            with self.assertRaises(a__    ):
                 classifier("""Who are you voting for in 2020?"""			,						candidate_labels=""""""    )

            with self.assertRaises(a__    ):
                 classifier("""Who are you voting for in 2020?"""			,						candidate_labels=a__    )

            with self.assertRaises(a__    ):
                 classifier(
                     """Who are you voting for in 2020?"""			,						candidate_labels="""politics"""			,						hypothesis_template="""Not formatting template"""			,						)

            with self.assertRaises(a__    ):
                 classifier(
                     """Who are you voting for in 2020?"""			,						candidate_labels="""politics"""			,						hypothesis_template=a__			,						)

            self.run_entailment_id(a__    )



       def 					__lowercase						(							self			,						a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						zero_shot_classifier.model.config
            __snake_case			:Optional[Any]          =						config.labelaid
            __snake_case			:Dict          =						zero_shot_classifier.entailment_id

            __snake_case			:List[Any]          =						{"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2}
            self.assertEqual(zero_shot_classifier.entailment_id			,						-1    )

            __snake_case			:Optional[int]          =						{"""entailment""": 0, """neutral""": 1, """contradiction""": 2}
            self.assertEqual(zero_shot_classifier.entailment_id			,						0    )

            __snake_case			:List[Any]          =						{"""ENTAIL""": 0, """NON-ENTAIL""": 1}
            self.assertEqual(zero_shot_classifier.entailment_id			,						0    )

            __snake_case			:str          =						{"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0}
            self.assertEqual(zero_shot_classifier.entailment_id			,						2    )

            __snake_case			:Union[str, Any]          =						original_labelaid
            self.assertEqual(a__			,						zero_shot_classifier.entailment_id    )



       @require_torch
       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:str          =						pipeline(
                """zero-shot-classification"""			,						model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""			,						framework="""pt"""			,						)
            # There was a regression in 4.10 for this
            # Adding a test so we don't make the mistake again.
            # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
            zero_shot_classifier(
                """Who are you voting for in 2020?""" * 1_00			,						candidate_labels=["""politics""", """public health""", """science"""]    )



       @require_torch
       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Dict          =						pipeline(
                """zero-shot-classification"""			,						model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""			,						framework="""pt"""			,						)
            __snake_case			:Tuple          =						zero_shot_classifier(
                """Who are you voting for in 2020?"""			,						candidate_labels=["""politics""", """public health""", """science"""]    )

            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": """Who are you voting for in 2020?""",
                    """labels""": ["""science""", """public health""", """politics"""],
                    """scores""": [0.3_33, 0.3_33, 0.3_33],
                }			,						)



       @require_tf
       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case			:List[str]          =						pipeline(
                """zero-shot-classification"""			,						model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""			,						framework="""tf"""			,						)
            __snake_case			:List[Any]          =						zero_shot_classifier(
                """Who are you voting for in 2020?"""			,						candidate_labels=["""politics""", """public health""", """science"""]    )

            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": """Who are you voting for in 2020?""",
                    """labels""": ["""science""", """public health""", """politics"""],
                    """scores""": [0.3_33, 0.3_33, 0.3_33],
                }			,						)



       @slow
       @require_torch
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Dict          =						pipeline("""zero-shot-classification"""			,						model="""roberta-large-mnli"""			,						framework="""pt"""    )
            __snake_case			:Optional[int]          =						zero_shot_classifier(
                """Who are you voting for in 2020?"""			,						candidate_labels=["""politics""", """public health""", """science"""]    )

            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": """Who are you voting for in 2020?""",
                    """labels""": ["""politics""", """public health""", """science"""],
                    """scores""": [0.9_76, 0.0_15, 0.0_09],
                }			,						)
            __snake_case			:Union[str, Any]          =						zero_shot_classifier(
                """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
                """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
                """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
                """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
                """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
                """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
                """ English-to-German translation task, improving over the existing best results, including ensembles by"""
                """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
                """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
                """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
                """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
                """ large and limited training data."""			,						candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]			,						multi_label=a__			,						)
            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": (
                        """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                        """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                        """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                        """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                        """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                        """ superior in quality while being more parallelizable and requiring significantly less time to"""
                        """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                        """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                        """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                        """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                        """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                        """ other tasks by applying it successfully to English constituency parsing both with large and"""
                        """ limited training data."""
                    ),
                    """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
                    """scores""": [0.8_17, 0.7_13, 0.0_18, 0.0_18],
                }			,						)



       @slow
       @require_tf
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Tuple          =						pipeline("""zero-shot-classification"""			,						model="""roberta-large-mnli"""			,						framework="""tf"""    )
            __snake_case			:Optional[int]          =						zero_shot_classifier(
                """Who are you voting for in 2020?"""			,						candidate_labels=["""politics""", """public health""", """science"""]    )

            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": """Who are you voting for in 2020?""",
                    """labels""": ["""politics""", """public health""", """science"""],
                    """scores""": [0.9_76, 0.0_15, 0.0_09],
                }			,						)
            __snake_case			:Union[str, Any]          =						zero_shot_classifier(
                """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
                """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
                """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
                """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
                """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
                """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
                """ English-to-German translation task, improving over the existing best results, including ensembles by"""
                """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
                """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
                """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
                """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
                """ large and limited training data."""			,						candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]			,						multi_label=a__			,						)
            self.assertEqual(
                nested_simplify(a__    )			,						{
                    """sequence""": (
                        """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                        """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                        """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                        """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                        """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                        """ superior in quality while being more parallelizable and requiring significantly less time to"""
                        """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                        """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                        """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                        """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                        """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                        """ other tasks by applying it successfully to English constituency parsing both with large and"""
                        """ limited training data."""
                    ),
                    """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
                    """scores""": [0.8_17, 0.7_13, 0.0_18, 0.0_18],
                }			,						)


