





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.
__UpperCAmelCase       :   Optional[Any]				       =							{"LayoutLMv2Config", "LayoutLMv3Config"}







@is_pipeline_test
class     __snake_case       (							unittest.TestCase			):





       '''simple docstring'''







       lowerCAmelCase__      		=     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
       lowerCAmelCase__      		=     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

       if model_mapping is not None:
              lowerCAmelCase__      		=     {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
       if tf_model_mapping is not None:
              lowerCAmelCase__      		=     {
                  config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
              }




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




       def 							UpperCAmelCase__ (  self :    Tuple							,				A :    List[str]							,				A :    Dict		):
         __snake_case:						List[str]   =						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:						List[Any]   =						classifier("""Who are you voting for in 2020?"""							,				["""politics"""]		)
         self.assertEqual(A							,				{"""sequence""": ANY(A		), """labels""": [ANY(A		)], """scores""": [ANY(A		)]}		)

         __snake_case:						Union[str, Any]   =						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:						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:						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:						Any   =						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:						Dict   =						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:						Any   =						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 							UpperCAmelCase__ (  self :    Any							,				A :    Pipeline		):
         __snake_case:						str   =						zero_shot_classifier.model.config
         __snake_case:						Optional[Any]   =						config.labelaid
         __snake_case:						Tuple   =						zero_shot_classifier.entailment_id

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

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

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

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

         __snake_case:						Any   =						original_labelaid
         self.assertEqual(A							,				zero_shot_classifier.entailment_id		)




       @require_torch
       def 							UpperCAmelCase__ (  self :    Tuple		):
         __snake_case:						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 							UpperCAmelCase__ (  self :    Tuple		):
         __snake_case:						Union[str, Any]   =						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.333, 0.333, 0.333],
             }							,				)




       @require_tf
       def 							UpperCAmelCase__ (  self :    int		):
         __snake_case:						Optional[int]   =						pipeline(
             """zero-shot-classification"""							,				model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""							,				framework="""tf"""							,				)
         __snake_case:						Dict   =						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.333, 0.333, 0.333],
             }							,				)




       @slow
       @require_torch
       def 							UpperCAmelCase__ (  self :    Optional[Any]		):
         __snake_case:						Tuple   =						pipeline("""zero-shot-classification"""							,				model="""roberta-large-mnli"""							,				framework="""pt"""		)
         __snake_case:						Optional[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""": ["""politics""", """public health""", """science"""],
                 """scores""": [0.976, 0.015, 0.009],
             }							,				)
         __snake_case:						Tuple   =						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.817, 0.713, 0.018, 0.018],
             }							,				)






       @slow
       @require_tf
       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         __snake_case:						List[str]   =						pipeline("""zero-shot-classification"""							,				model="""roberta-large-mnli"""							,				framework="""tf"""		)
         __snake_case:						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""": ["""politics""", """public health""", """science"""],
                 """scores""": [0.976, 0.015, 0.009],
             }							,				)
         __snake_case:						List[str]   =						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.817, 0.713, 0.018, 0.018],
             }							,				)













from __future__ import annotations

from sys import maxsize
from typing import Generic, TypeVar

__UpperCAmelCase       :   str				       =							TypeVar("T")







def 			A__							(    SCREAMING_SNAKE_CASE__)   ->    int:
  return (position - 1) // 2







def 			A__							(    SCREAMING_SNAKE_CASE__)   ->    int:
  return (2 * position) + 1







def 			A__							(    SCREAMING_SNAKE_CASE__)   ->    int:
  return (2 * position) + 2







class     __snake_case       (							Generic[T]			):





       '''simple docstring'''







       def __init__(  self :    Tuple		):
         __snake_case:						list[tuple[T, int]]   =						[]
         __snake_case:						dict[T, int]   =						{}
         __snake_case:						int   =						0




       def __len__(  self :    Tuple		):
         return self.elements




       def __repr__(  self :    Optional[int]		):
         return str(self.heap		)




       def 							UpperCAmelCase__ (  self :    List[Any]		):
         # Check if the priority queue is empty
         return self.elements == 0




       def 							UpperCAmelCase__ (  self :    List[Any]							,				A :    T							,				A :    int		):
         # Add an element with given priority to the queue
         self.heap.append((elem, weight)		)
         __snake_case:						Optional[Any]   =						self.elements
         self.elements += 1
         self._bubble_up(A		)




       def 							UpperCAmelCase__ (  self :    List[Any]		):
         # Remove and return the element with lowest weight (highest priority)
         if self.elements > 1:
           self._swap_nodes(0							,				self.elements - 1		)
         __snake_case  ,   __snake_case:						Union[str, Any]   =						self.heap.pop()
         del self.position_map[elem]
         self.elements -= 1
         if self.elements > 0:
           __snake_case  ,   __snake_case:						int   =						self.heap[0]
           self._bubble_down(A		)
         return elem




       def 							UpperCAmelCase__ (  self :    Any							,				A :    T							,				A :    int		):
         # Update the weight of the given key
         __snake_case:						Dict   =						self.position_map[elem]
         __snake_case:						Optional[Any]   =						(elem, weight)
         if position > 0:
           __snake_case:						Optional[int]   =						get_parent_position(A		)
           __snake_case  ,   __snake_case:						Dict   =						self.heap[parent_position]
           if parent_weight > weight:
             self._bubble_up(A		)
           else:
             self._bubble_down(A		)
         else:
           self._bubble_down(A		)




       def 							UpperCAmelCase__ (  self :    int							,				A :    T		):
         # Place a node at the proper position (upward movement) [to be used internally
         # only]
         __snake_case:						int   =						self.position_map[elem]
         if curr_pos == 0:
           return None
         __snake_case:						Optional[Any]   =						get_parent_position(A		)
         __snake_case  ,   __snake_case:						Tuple   =						self.heap[curr_pos]
         __snake_case  ,   __snake_case:						Optional[Any]   =						self.heap[parent_position]
         if parent_weight > weight:
           self._swap_nodes(A							,				A		)
           return self._bubble_up(A		)
         return None




       def 							UpperCAmelCase__ (  self :    List[str]							,				A :    T		):
         # Place a node at the proper position (downward movement) [to be used
         # internally only]
         __snake_case:						Any   =						self.position_map[elem]
         __snake_case  ,   __snake_case:						int   =						self.heap[curr_pos]
         __snake_case:						Union[str, Any]   =						get_child_left_position(A		)
         __snake_case:						Dict   =						get_child_right_position(A		)
         if child_left_position < self.elements and child_right_position < self.elements:
           __snake_case  ,   __snake_case:						Any   =						self.heap[child_left_position]
           __snake_case  ,   __snake_case:						List[str]   =						self.heap[child_right_position]
           if child_right_weight < child_left_weight and child_right_weight < weight:
             self._swap_nodes(A							,				A		)
             return self._bubble_down(A		)
         if child_left_position < self.elements:
           __snake_case  ,   __snake_case:						List[Any]   =						self.heap[child_left_position]
           if child_left_weight < weight:
             self._swap_nodes(A							,				A		)
             return self._bubble_down(A		)
         else:
           return None
         if child_right_position < self.elements:
           __snake_case  ,   __snake_case:						List[Any]   =						self.heap[child_right_position]
           if child_right_weight < weight:
             self._swap_nodes(A							,				A		)
             return self._bubble_down(A		)
         return None






       def 							UpperCAmelCase__ (  self :    int							,				A :    int							,				A :    int		):
         # Swap the nodes at the given positions
         __snake_case:						Optional[int]   =						self.heap[nodea_pos][0]
         __snake_case:						Optional[Any]   =						self.heap[nodea_pos][0]
         __snake_case  ,   __snake_case:						Tuple   =						(
             self.heap[nodea_pos],
             self.heap[nodea_pos],
         )
         __snake_case:						Any   =						nodea_pos
         __snake_case:						str   =						nodea_pos







class     __snake_case       (							Generic[T]			):





       '''simple docstring'''







       def __init__(  self :    Any		):
         __snake_case:						dict[T, dict[T, int]]   =						{}
         __snake_case:						int   =						0




       def __repr__(  self :    Dict		):
         return str(self.connections		)




       def __len__(  self :    List[str]		):
         return self.nodes




       def 							UpperCAmelCase__ (  self :    Optional[Any]							,				A :    T		):
         # Add a node in the graph if it is not in the graph
         if node not in self.connections:
           __snake_case:						List[str]   =						{}
           self.nodes += 1






       def 							UpperCAmelCase__ (  self :    Optional[Any]							,				A :    T							,				A :    T							,				A :    int		):
         # Add an edge between 2 nodes in the graph
         self.add_node(A		)
         self.add_node(A		)
         __snake_case:						Optional[Any]   =						weight
         __snake_case:						str   =						weight







def 			A__							(    SCREAMING_SNAKE_CASE__					,					)   ->    tuple[dict[T, int], dict[T, T | None]]:
  __snake_case:						dict[T, int]   =						{node: maxsize for node in graph.connections}
  __snake_case:						dict[T, T | None]   =						{node: None for node in graph.connections}

  __snake_case:						MinPriorityQueue[T]   =						MinPriorityQueue()
  for node, weight in dist.items():
    priority_queue.push(SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__)

  if priority_queue.is_empty():
    return dist, parent

  # initialization
  __snake_case:						Optional[int]   =						priority_queue.extract_min()
  __snake_case:						Any   =						0
  for neighbour in graph.connections[node]:
    if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
      __snake_case:						Tuple   =						dist[node] + graph.connections[node][neighbour]
      priority_queue.update_key(SCREAMING_SNAKE_CASE__					,					dist[neighbour])
      __snake_case:						Optional[int]   =						node

    # running prim's algorithm
  while not priority_queue.is_empty():
    __snake_case:						Optional[int]   =						priority_queue.extract_min()
    for neighbour in graph.connections[node]:
      if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
        __snake_case:						Tuple   =						dist[node] + graph.connections[node][neighbour]
        priority_queue.update_key(SCREAMING_SNAKE_CASE__					,					dist[neighbour])
        __snake_case:						List[Any]   =						node
  return dist, parent






