
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.
lowercase  :					Tuple						    =							{"""LayoutLMv2Config""", """LayoutLMv3Config"""}

@is_pipeline_test
class __snake_case		(      unittest.TestCase     ):
    _a		:						Optional[Any]=				MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
    _a		:						Dict=				TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

    if model_mapping is not None:
        _a		:						Union[str, Any]=				{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
    if tf_model_mapping is not None:
        _a		:						Dict=				{
            config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
        }
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Any       	=      ZeroShotClassificationPipeline(
               model=snake_case		,tokenizer=snake_case		,candidate_labels=["""polics""", """health"""]      )
           return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case      ):



           '''simple docstring'''







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

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

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

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

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

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

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

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

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

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

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

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

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

           self.run_entailment_id(snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     int       	=      zero_shot_classifier.model.config
           lowercase							:     Union[str, Any]       	=      config.labelaid
           lowercase							:     Dict       	=      zero_shot_classifier.entailment_id

           lowercase							:     Dict       	=      {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2}
           self.assertEqual(zero_shot_classifier.entailment_id		,-1      )

           lowercase							:     Dict       	=      {"""entailment""": 0, """neutral""": 1, """contradiction""": 2}
           self.assertEqual(zero_shot_classifier.entailment_id		,0      )

           lowercase							:     Any       	=      {"""ENTAIL""": 0, """NON-ENTAIL""": 1}
           self.assertEqual(zero_shot_classifier.entailment_id		,0      )

           lowercase							:     Optional[Any]       	=      {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0}
           self.assertEqual(zero_shot_classifier.entailment_id		,2      )

           lowercase							:     Optional[int]       	=      original_labelaid
           self.assertEqual(snake_case		,zero_shot_classifier.entailment_id      )
    @require_torch
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      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?""" * 100		,candidate_labels=["""politics""", """public health""", """science"""]      )
    @require_torch
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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

           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """sequence""": """Who are you voting for in 2020?""",
                   """labels""": ["""science""", """public health""", """politics"""],
                   """scores""": [0.333, 0.333, 0.333],
               }		,)
    @require_tf
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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

           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """sequence""": """Who are you voting for in 2020?""",
                   """labels""": ["""science""", """public health""", """politics"""],
                   """scores""": [0.333, 0.333, 0.333],
               }		,)
    @slow
    @require_torch
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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

           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """sequence""": """Who are you voting for in 2020?""",
                   """labels""": ["""politics""", """public health""", """science"""],
                   """scores""": [0.976, 0.015, 0.009],
               }		,)
           lowercase							:     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=snake_case		,)
           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """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.817, 0.713, 0.018, 0.018],
               }		,)
    @slow
    @require_tf
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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

           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """sequence""": """Who are you voting for in 2020?""",
                   """labels""": ["""politics""", """public health""", """science"""],
                   """scores""": [0.976, 0.015, 0.009],
               }		,)
           lowercase							:     Optional[int]       	=      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=snake_case		,)
           self.assertEqual(
               nested_simplify(snake_case      )		,{
                   """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.817, 0.713, 0.018, 0.018],
               }		,)


import os
import zipfile

import pytest

from datasets.utils.extract import (
    BzipaExtractor,
    Extractor,
    GzipExtractor,
    LzaExtractor,
    SevenZipExtractor,
    TarExtractor,
    XzExtractor,
    ZipExtractor,
    ZstdExtractor,
)

from .utils import require_lza, require_pyazr, require_zstandard







@pytest.mark.parametrize(
    """compression_format, is_archive"""					,	[
        ("""7z""", True),
        ("""bz2""", False),
        ("""gzip""", False),
        ("""lz4""", False),
        ("""tar""", True),
        ("""xz""", False),
        ("""zip""", True),
        ("""zstd""", False),
    ]					,	)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	) ->    Any:
       lowercase							:     Dict       	=      {
           """7z""": (seven_zip_file, SevenZipExtractor),
           """bz2""": (bza_file, BzipaExtractor),
           """gzip""": (gz_file, GzipExtractor),
           """lz4""": (lza_file, LzaExtractor),
           """tar""": (tar_file, TarExtractor),
           """xz""": (xz_file, XzExtractor),
           """zip""": (zip_file, ZipExtractor),
           """zstd""": (zstd_file, ZstdExtractor),
       }
       lowercase	,			lowercase							:     Optional[Any]       	=      input_paths_and_base_extractors[compression_format]
       if input_path is None:
              lowercase							:     Dict       	=      f"for '{compression_format}' compression_format, "
              if compression_format == "7z":
                     reason += require_pyazr.kwargs["reason"]
              elif compression_format == "lz4":
                     reason += require_lza.kwargs["reason"]
              elif compression_format == "zstd":
                     reason += require_zstandard.kwargs["reason"]
              pytest.skip(SCREAMING_SNAKE_CASE__				)
       assert base_extractor.is_extractable(SCREAMING_SNAKE_CASE__				)
       lowercase							:     Any       	=      tmp_path / ("""extracted""" if is_archive else """extracted.txt""")
       base_extractor.extract(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       if is_archive:
              assert output_path.is_dir()
              for file_path in output_path.iterdir():
                     assert file_path.name == text_file.name
                     lowercase							:     str       	=      file_path.read_text(encoding="""utf-8"""				)
       else:
              lowercase							:     Optional[Any]       	=      output_path.read_text(encoding="""utf-8"""				)
       lowercase							:     Tuple       	=      text_file.read_text(encoding="""utf-8"""				)
       assert extracted_file_content == expected_file_content







@pytest.mark.parametrize(
    """compression_format, is_archive"""					,	[
        ("""7z""", True),
        ("""bz2""", False),
        ("""gzip""", False),
        ("""lz4""", False),
        ("""tar""", True),
        ("""xz""", False),
        ("""zip""", True),
        ("""zstd""", False),
    ]					,	)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	) ->    Dict:
       lowercase							:     str       	=      {
           """7z""": seven_zip_file,
           """bz2""": bza_file,
           """gzip""": gz_file,
           """lz4""": lza_file,
           """tar""": tar_file,
           """xz""": xz_file,
           """zip""": zip_file,
           """zstd""": zstd_file,
       }
       lowercase							:     Optional[Any]       	=      input_paths[compression_format]
       if input_path is None:
              lowercase							:     int       	=      f"for '{compression_format}' compression_format, "
              if compression_format == "7z":
                     reason += require_pyazr.kwargs["reason"]
              elif compression_format == "lz4":
                     reason += require_lza.kwargs["reason"]
              elif compression_format == "zstd":
                     reason += require_zstandard.kwargs["reason"]
              pytest.skip(SCREAMING_SNAKE_CASE__				)
       lowercase							:     Union[str, Any]       	=      Extractor.infer_extractor_format(SCREAMING_SNAKE_CASE__				)
       assert extractor_format is not None
       lowercase							:     Any       	=      tmp_path / ("""extracted""" if is_archive else """extracted.txt""")
       Extractor.extract(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       if is_archive:
              assert output_path.is_dir()
              for file_path in output_path.iterdir():
                     assert file_path.name == text_file.name
                     lowercase							:     Dict       	=      file_path.read_text(encoding="""utf-8"""				)
       else:
              lowercase							:     int       	=      output_path.read_text(encoding="""utf-8"""				)
       lowercase							:     Optional[Any]       	=      text_file.read_text(encoding="""utf-8"""				)
       assert extracted_file_content == expected_file_content







@pytest.fixture
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Dict:
       import tarfile

       lowercase							:     Tuple       	=      tmp_path / """data_dot_dot"""
       directory.mkdir()
       lowercase							:     str       	=      directory / """tar_file_with_dot_dot.tar"""
       with tarfile.TarFile(SCREAMING_SNAKE_CASE__					,	"""w"""				) as f:
              f.add(SCREAMING_SNAKE_CASE__					,	arcname=os.path.join(""".."""					,	text_file.name				)				)
       return path







@pytest.fixture
def 						_snake_case(  SCREAMING_SNAKE_CASE__				) ->    List[str]:
       import tarfile

       lowercase							:     Tuple       	=      tmp_path / """data_sym_link"""
       directory.mkdir()
       lowercase							:     int       	=      directory / """tar_file_with_sym_link.tar"""
       os.symlink(""".."""					,	directory / """subdir"""					,	target_is_directory=SCREAMING_SNAKE_CASE__				)
       with tarfile.TarFile(SCREAMING_SNAKE_CASE__					,	"""w"""				) as f:
              f.add(str(directory / """subdir"""				)					,	arcname="""subdir"""				)  # str required by os.readlink on Windows and Python < 3.8
       return path







@pytest.mark.parametrize(
    """insecure_tar_file, error_log"""					,	[("""tar_file_with_dot_dot""", """illegal path"""), ("""tar_file_with_sym_link""", """Symlink""")]					,	)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Optional[Any]:
       lowercase							:     List[Any]       	=      {
           """tar_file_with_dot_dot""": tar_file_with_dot_dot,
           """tar_file_with_sym_link""": tar_file_with_sym_link,
       }
       lowercase							:     Optional[int]       	=      insecure_tar_files[insecure_tar_file]
       lowercase							:     List[str]       	=      tmp_path / """extracted"""
       TarExtractor.extract(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       assert caplog.text
       for record in caplog.records:
              assert record.levelname == "ERROR"
              assert error_log in record.msg







def 						_snake_case(  SCREAMING_SNAKE_CASE__				) ->    Optional[int]:
       # We should have less false positives than zipfile.is_zipfile
       # We do that by checking only the magic number
       lowercase							:     Any       	=      tmpdir / """not_a_zip_file"""
       # From: https://github.com/python/cpython/pull/5053
       lowercase							:     str       	=      (
           B"""\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"""
           B"""\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I"""
           B"""DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07"""
           B"""\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82"""
       )
       with not_a_zip_file.open("""wb"""				) as f:
              f.write(SCREAMING_SNAKE_CASE__				)
       assert zipfile.is_zipfile(str(SCREAMING_SNAKE_CASE__				)				)  # is a false positive for `zipfile`
       assert not ZipExtractor.is_extractable(SCREAMING_SNAKE_CASE__				)  # but we're right
