

'''simple docstring'''

from __future__ import annotations

import os







class lowerCamelCase   :
				snake_case_							     = (
				    '''High card''',
				    '''One pair''',
				    '''Two pairs''',
				    '''Three of a kind''',
				    '''Straight''',
				    '''Flush''',
				    '''Full house''',
				    '''Four of a kind''',
				    '''Straight flush''',
				    '''Royal flush''',
				)

				snake_case_							     = (
				    '''''',  # placeholder as tuples are zero-indexed
				    '''One''',
				    '''Two''',
				    '''Three''',
				    '''Four''',
				    '''Five''',
				    '''Six''',
				    '''Seven''',
				    '''Eight''',
				    '''Nine''',
				    '''Ten''',
				    '''Jack''',
				    '''Queen''',
				    '''King''',
				    '''Ace''',
				)

				def __init__(       self,						lowercase_ )    ->							None:
					if not isinstance(lowercase_,						lowercase_ ):
						snake_case							=					F'''Hand should be of type \'str\': {hand!r}'''
						raise TypeError(lowercase_ )
					# split removes duplicate whitespaces so no need of strip
					if len(hand.split(' ' ) ) != 5:
						snake_case							=					F'''Hand should contain only 5 cards: {hand!r}'''
						raise ValueError(lowercase_ )
					snake_case							=					hand
					snake_case							=					0
					snake_case							=					0
					snake_case			,			snake_case							=					self._internal_state()
					snake_case							=					self._get_hand_type()
					snake_case							=					self._card_values[0]

				@property
				def 					_lowerCamelCase    (       self )    ->							List[str]:
					return self._hand

				def 					_lowerCamelCase    (       self,						lowercase_ )    ->							str:
					# Breaking the tie works on the following order of precedence:
					# 1. First pair (default 0)
					# 2. Second pair (default 0)
					# 3. Compare all cards in reverse order because they are sorted.

					# First pair and second pair will only be a non-zero value if the card
					# type is either from the following:
					# 21: Four of a kind
					# 20: Full house
					# 17: Three of a kind
					# 16: Two pairs
					# 15: One pair
					if self._hand_type > other._hand_type:
						return "Win"
					elif self._hand_type < other._hand_type:
						return "Loss"
					elif self._first_pair == other._first_pair:
						if self._second_pair == other._second_pair:
							return self._compare_cards(lowercase_ )
						else:
							return "Win" if self._second_pair > other._second_pair else "Loss"
					return "Win" if self._first_pair > other._first_pair else "Loss"

				def 					_lowerCamelCase    (       self )    ->							str:
					snake_case							=					PokerHand._HAND_NAME[self._hand_type - 14]
					snake_case							=					PokerHand._CARD_NAME[self._high_card]
					snake_case							=					PokerHand._CARD_NAME[self._first_pair]
					snake_case							=					PokerHand._CARD_NAME[self._second_pair]
					if self._hand_type in [22, 19, 18]:
						return name + F''', {high}-high'''
					elif self._hand_type in [21, 17, 15]:
						return name + F''', {paira}s'''
					elif self._hand_type in [20, 16]:
						snake_case							=					'over' if self._hand_type == 20 else 'and'
						return name + F''', {paira}s {join} {paira}s'''
					elif self._hand_type == 23:
						return name
					else:
						return name + F''', {high}'''

				def 					_lowerCamelCase    (       self,						lowercase_ )    ->							str:
					# Enumerate gives us the index as well as the element of a list
					for index, card_value in enumerate(self._card_values ):
						if card_value != other._card_values[index]:
							return "Win" if card_value > other._card_values[index] else "Loss"
					return "Tie"

				def 					_lowerCamelCase    (       self )    ->							int:
					# Number representing the type of hand internally:
					# 23: Royal flush
					# 22: Straight flush
					# 21: Four of a kind
					# 20: Full house
					# 19: Flush
					# 18: Straight
					# 17: Three of a kind
					# 16: Two pairs
					# 15: One pair
					# 14: High card
					if self._is_flush():
						if self._is_five_high_straight() or self._is_straight():
							return 23 if sum(self._card_values ) == 60 else 22
						return 19
					elif self._is_five_high_straight() or self._is_straight():
						return 18
					return 14 + self._is_same_kind()

				def 					_lowerCamelCase    (       self )    ->							bool:
					return len(self._card_suit ) == 1

				def 					_lowerCamelCase    (       self )    ->							bool:
					# If a card is a five high straight (low ace) change the location of
					# ace from the start of the list to the end. Check whether the first
					# element is ace or not. (Don't want to change again)
					# Five high straight (low ace): AH 2H 3S 4C 5D
					# Why use sorted here? One call to this function will mutate the list to
					# [5, 4, 3, 2, 14] and so for subsequent calls (which will be rare) we
					# need to compare the sorted version.
					# Refer test_multiple_calls_five_high_straight in test_poker_hand.py
					if sorted(self._card_values ) == [2, 3, 4, 5, 14]:
						if self._card_values[0] == 14:
							# Remember, our list is sorted in reverse order
							snake_case							=					self._card_values.pop(0 )
							self._card_values.append(lowercase_ )
						return True
					return False

				def 					_lowerCamelCase    (       self )    ->							bool:
					for i in range(4 ):
						if self._card_values[i] - self._card_values[i + 1] != 1:
							return False
					return True

				def 					_lowerCamelCase    (       self )    ->							int:
					# Kind Values for internal use:
					# 7: Four of a kind
					# 6: Full house
					# 3: Three of a kind
					# 2: Two pairs
					# 1: One pair
					# 0: False
					snake_case							=					snake_case							=					snake_case							=					0
					for i in range(4 ):
						# Compare two cards at a time, if they are same increase 'kind',
						# add the value of the card to val1, if it is repeating again we
						# will add 2 to 'kind' as there are now 3 cards with same value.
						# If we get card of different value than val1, we will do the same
						# thing with val2
						if self._card_values[i] == self._card_values[i + 1]:
							if not vala:
								snake_case							=					self._card_values[i]
								kind += 1
							elif vala == self._card_values[i]:
								kind += 2
							elif not vala:
								snake_case							=					self._card_values[i]
								kind += 1
							elif vala == self._card_values[i]:
								kind += 2
        # For consistency in hand type (look at note in _get_hand_type function)
					snake_case							=					kind + 2 if kind in [4, 5] else kind
					# first meaning first pair to compare in 'compare_with'
					snake_case							=					max(lowercase_,						lowercase_ )
					snake_case							=					min(lowercase_,						lowercase_ )
					# If it's full house (three count pair + two count pair), make sure
					# first pair is three count and if not then switch them both.
					if kind == 6 and self._card_values.count(lowercase_ ) != 3:
						snake_case			,			snake_case							=					second, first
					snake_case							=					first
					snake_case							=					second
					return kind

				def 					_lowerCamelCase    (       self )    ->							tuple[list[int], set[str]]:
					# Internal representation of hand as a list of card values and
					# a set of card suit
					snake_case							=					{"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"}
					snake_case							=					self._hand.translate(str.maketrans(lowercase_ ) ).split()
					snake_case							=					[int(card[:-1] ) for card in new_hand]
					snake_case							=					{card[-1] for card in new_hand}
					return sorted(lowercase_,						reverse=lowercase_ ), card_suit

				def __repr__(       self )    ->							int:
					return F'''{self.__class__}("{self._hand}")'''

				def __str__(       self )    ->							str:
					return self._hand

				def __eq__(       self,						lowercase_ )    ->							Dict:
					if isinstance(lowercase_,						lowercase_ ):
						return self.compare_with(lowercase_ ) == "Tie"
					return NotImplemented

				def __lt__(       self,						lowercase_ )    ->							Union[str, Any]:
					if isinstance(lowercase_,						lowercase_ ):
						return self.compare_with(lowercase_ ) == "Loss"
					return NotImplemented

				def __le__(       self,						lowercase_ )    ->							Optional[int]:
					if isinstance(lowercase_,						lowercase_ ):
						return self < other or self == other
					return NotImplemented

				def __gt__(       self,						lowercase_ )    ->							Any:
					if isinstance(lowercase_,						lowercase_ ):
						return not self < other and self != other
					return NotImplemented

				def __ge__(       self,						lowercase_ )    ->							Tuple:
					if isinstance(lowercase_,						lowercase_ ):
						return not self < other
					return NotImplemented






				def __hash__(       self )    ->							Union[str, Any]:
					return object.__hash__(self )

def      __magic_name__							(			)      ->		int:
	# Solution for problem number 54 from Project Euler
	# Input from poker_hands.txt file
	snake_case							=					0
	snake_case							=					os.path.abspath(os.path.dirname(A				)				)
	snake_case							=					os.path.join(A       , 'poker_hands.txt'				)
	with open(A				) as file_hand:
		for line in file_hand:
			snake_case							=					line[:1_4].strip()
			snake_case							=					line[1_5:].strip()
			snake_case			,			snake_case							=					PokerHand(A				), PokerHand(A				)
			snake_case							=					player.compare_with(A				)
			if output == "Win":
				answer += 1
	return answer


if __name__ == "__main__":
						solution()






import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
     from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import DPTImageProcessor







class        UpperCAmelCase_					:




    def __init__(       self	: int   ,   lowerCAmelCase	: Tuple   ,   lowerCAmelCase	: Dict=2   ,   lowerCAmelCase	: Dict=32   ,   lowerCAmelCase	: Optional[int]=16   ,   lowerCAmelCase	: Tuple=3   ,   lowerCAmelCase	: Tuple=True   ,   lowerCAmelCase	: str=True   ,   lowerCAmelCase	: int=32   ,   lowerCAmelCase	: int=4   ,   lowerCAmelCase	: Tuple=[0, 1, 2, 3]   ,   lowerCAmelCase	: Dict=4   ,   lowerCAmelCase	: Optional[int]=37   ,   lowerCAmelCase	: Tuple="gelu"   ,   lowerCAmelCase	: Optional[int]=0.1   ,   lowerCAmelCase	: Dict=0.1   ,   lowerCAmelCase	: Tuple=0.02   ,   lowerCAmelCase	: List[str]=3   ,   lowerCAmelCase	: Dict=False   ,   lowerCAmelCase	: str=None   ,   )						->			Tuple:
      a__  		=  parent
      a__  		=  batch_size
      a__  		=  image_size
      a__  		=  patch_size
      a__  		=  num_channels
      a__  		=  is_training
      a__  		=  use_labels
      a__  		=  hidden_size
      a__  		=  num_hidden_layers
      a__  		=  backbone_out_indices
      a__  		=  num_attention_heads
      a__  		=  intermediate_size
      a__  		=  hidden_act
      a__  		=  hidden_dropout_prob
      a__  		=  attention_probs_dropout_prob
      a__  		=  initializer_range
      a__  		=  num_labels
      a__  		=  scope
      a__  		=  is_hybrid
      # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
      a__  		=  (image_size // patch_size) ** 2
      a__  		=  num_patches + 1




    def     __lowerCamelCase			(       self	: List[Any] )						->			str:
      a__  		=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

      a__  		=  None
      if self.use_labels:
        a__  		=  ids_tensor([self.batch_size, self.image_size, self.image_size]   ,   self.num_labels )

      a__  		=  self.get_config()

      return config, pixel_values, labels




    def     __lowerCamelCase			(       self	: List[Any] )						->			Union[str, Any]:
      return DPTConfig(
          image_size=self.image_size   ,   patch_size=self.patch_size   ,   num_channels=self.num_channels   ,   hidden_size=self.hidden_size   ,   num_hidden_layers=self.num_hidden_layers   ,   backbone_out_indices=self.backbone_out_indices   ,   num_attention_heads=self.num_attention_heads   ,   intermediate_size=self.intermediate_size   ,   hidden_act=self.hidden_act   ,   hidden_dropout_prob=self.hidden_dropout_prob   ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,   is_decoder=lowerCAmelCase   ,   initializer_range=self.initializer_range   ,   is_hybrid=self.is_hybrid   ,   )




    def     __lowerCamelCase			(       self	: Optional[int]   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: Optional[Any] )						->			Optional[Any]:
      a__  		=  DPTModel(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase )
      self.parent.assertEqual(result.last_hidden_state.shape   ,   (self.batch_size, self.seq_length, self.hidden_size) )




    def     __lowerCamelCase			(       self	: Union[str, Any]   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Dict   ,   lowerCAmelCase	: str )						->			Optional[Any]:
      a__  		=  self.num_labels
      a__  		=  DPTForDepthEstimation(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase )
      self.parent.assertEqual(result.predicted_depth.shape   ,   (self.batch_size, self.image_size, self.image_size) )




    def     __lowerCamelCase			(       self	: str   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Optional[int] )						->			List[str]:
      a__  		=  self.num_labels
      a__  		=  DPTForSemanticSegmentation(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase   ,   labels=lowerCAmelCase )
      self.parent.assertEqual(
          result.logits.shape   ,   (self.batch_size, self.num_labels, self.image_size, self.image_size) )




    def     __lowerCamelCase			(       self	: int )						->			Any:
      a__  		=  self.prepare_config_and_inputs()
      a__		,a__		,a__  		=  config_and_inputs
      a__  		=  {"pixel_values": pixel_values}
      return config, inputs_dict







@require_torch
class        UpperCAmelCase_					(				_a  ,  _a  ,  unittest.TestCase     ):
    UpperCAmelCase_      :							int    			=				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
    UpperCAmelCase_      :							str    			=				(
        {
            'depth-estimation': DPTForDepthEstimation,
            'feature-extraction': DPTModel,
            'image-segmentation': DPTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    UpperCAmelCase_      :							List[str]    			=				False
    UpperCAmelCase_      :							int    			=				False
    UpperCAmelCase_      :							Optional[Any]    			=				False




    def     __lowerCamelCase			(       self	: List[Any] )						->			Any:
      a__  		=  DPTModelTester(self )
      a__  		=  ConfigTester(self   ,   config_class=lowerCAmelCase   ,   has_text_modality=lowerCAmelCase   ,   hidden_size=37 )




    def     __lowerCamelCase			(       self	: int )						->			List[Any]:
      self.config_tester.run_common_tests()




    @unittest.skip(reason="DPT does not use inputs_embeds" )
    def     __lowerCamelCase			(       self	: str )						->			Dict:
      pass




    def     __lowerCamelCase			(       self	: List[str] )						->			int:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a__  		=  model_class(lowerCAmelCase )
        self.assertIsInstance(model.get_input_embeddings()   ,   (nn.Module) )
        a__  		=  model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowerCAmelCase   ,   nn.Linear ) )




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			Any:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a__  		=  model_class(lowerCAmelCase )
        a__  		=  inspect.signature(model.forward )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        a__  		=  [*signature.parameters.keys()]

        a__  		=  ["pixel_values"]
        self.assertListEqual(arg_names[:1]   ,   lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Optional[int] )						->			Optional[Any]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Tuple )						->			List[str]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: List[Any] )						->			Any:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Tuple )						->			Tuple:
      for model_class in self.all_model_classes:
        if model_class.__name__ == "DPTForDepthEstimation":
          continue

        a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()
        a__  		=  True

        if model_class in get_values(lowerCAmelCase ):
          continue

        a__  		=  model_class(lowerCAmelCase )
        model.to(lowerCAmelCase )
        model.train()
        a__  		=  self._prepare_for_class(lowerCAmelCase   ,   lowerCAmelCase   ,   return_labels=lowerCAmelCase )
        a__  		=  model(**lowerCAmelCase ).loss
        loss.backward()




    def     __lowerCamelCase			(       self	: Any )						->			Dict:
      for model_class in self.all_model_classes:
        if model_class.__name__ == "DPTForDepthEstimation":
          continue

        a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()
        a__  		=  False
        a__  		=  True

        if model_class in get_values(lowerCAmelCase ) or not model_class.supports_gradient_checkpointing:
          continue
        a__  		=  model_class(lowerCAmelCase )
        model.to(lowerCAmelCase )
        model.gradient_checkpointing_enable()
        model.train()
        a__  		=  self._prepare_for_class(lowerCAmelCase   ,   lowerCAmelCase   ,   return_labels=lowerCAmelCase )
        a__  		=  model(**lowerCAmelCase ).loss
        loss.backward()




    def     __lowerCamelCase			(       self	: List[str] )						->			int:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

      a__  		=  _config_zero_init(lowerCAmelCase )
      for model_class in self.all_model_classes:
        a__  		=  model_class(config=lowerCAmelCase )
        # Skip the check for the backbone
        a__  		=  []
        for name, module in model.named_modules():
          if module.__class__.__name__ == "DPTViTHybridEmbeddings":
            a__  		=  [f"{name}.{key}" for key in module.state_dict().keys()]
            break

        for name, param in model.named_parameters():
          if param.requires_grad:
            if name in backbone_params:
              continue
            self.assertIn(
                ((param.data.mean() * 1e9).round() / 1e9).item()   ,   [0.0, 1.0]   ,   msg=f"Parameter {name} of model {model_class} seems not properly initialized"   ,   )




    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
    def     __lowerCamelCase			(       self	: List[str] )						->			Union[str, Any]:
      pass




    @slow
    def     __lowerCamelCase			(       self	: List[str] )						->			Dict:
      for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a__  		=  DPTModel.from_pretrained(lowerCAmelCase )
        self.assertIsNotNone(lowerCAmelCase )

def 					__lowercase						(    )					->int:

  '''simple docstring'''




  a__  		=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
  return image







@require_torch
@require_vision
@slow
class        UpperCAmelCase_					(				unittest.TestCase     ):




    def     __lowerCamelCase			(       self	: Any )						->			Union[str, Any]:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large" )
      a__  		=  DPTForDepthEstimation.from_pretrained("Intel/dpt-large" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )
        a__  		=  outputs.predicted_depth

      # verify the predicted depth
      a__  		=  torch.Size((1, 384, 384) )
      self.assertEqual(predicted_depth.shape   ,   lowerCAmelCase )

      a__  		=  torch.tensor(
          [[6.3_199, 6.3_629, 6.4_148], [6.3_850, 6.3_615, 6.4_166], [6.3_519, 6.3_176, 6.3_575]] ).to(lowerCAmelCase )

      self.assertTrue(torch.allclose(outputs.predicted_depth[0, :3, :3]   ,   lowerCAmelCase   ,   atol=1e-4 ) )




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			str:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade" )
      a__  		=  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )

      # verify the logits
      a__  		=  torch.Size((1, 150, 480, 480) )
      self.assertEqual(outputs.logits.shape   ,   lowerCAmelCase )

      a__  		=  torch.tensor(
          [[4.0_480, 4.2_420, 4.4_360], [4.3_124, 4.5_693, 4.8_261], [4.5_768, 4.8_965, 5.2_163]] ).to(lowerCAmelCase )

      self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]   ,   lowerCAmelCase   ,   atol=1e-4 ) )




    def     __lowerCamelCase			(       self	: str )						->			Optional[int]:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade" )
      a__  		=  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )

      a__  		=  outputs.logits.detach().cpu()

      a__  		=  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase   ,   target_sizes=[(500, 300)] )
      a__  		=  torch.Size((500, 300) )
      self.assertEqual(segmentation[0].shape   ,   lowerCAmelCase )

      a__  		=  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase )
      a__  		=  torch.Size((480, 480) )
      self.assertEqual(segmentation[0].shape   ,   lowerCAmelCase )

