



from __future__ import annotations

import os
class  _snake_case	:
				UpperCamelCase__ :    List[str]   						=(
				    """High card""",
				    """One pair""",
				    """Two pairs""",
				    """Three of a kind""",
				    """Straight""",
				    """Flush""",
				    """Full house""",
				    """Four of a kind""",
				    """Straight flush""",
				    """Royal flush""",
				)

				UpperCamelCase__ :    List[str]   						=(
				    """""",  # placeholder as tuples are zero-indexed
				    """One""",
				    """Two""",
				    """Three""",
				    """Four""",
				    """Five""",
				    """Six""",
				    """Seven""",
				    """Eight""",
				    """Nine""",
				    """Ten""",
				    """Jack""",
				    """Queen""",
				    """King""",
				    """Ace""",
				)




				def __init__(  self    :  Optional[int],    __lowercase    :  str  ):
							if not isinstance(__lowercase,    __lowercase  ):
										lowercase__         = 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:
										lowercase__         = F'''Hand should contain only 5 cards: {hand!r}'''
										raise ValueError(__lowercase  )
							lowercase__         = hand
							lowercase__         = 0
							lowercase__         = 0
							lowercase__         = self._internal_state()
							lowercase__         = self._get_hand_type()
							lowercase__         = self._card_values[0]




				@property
				def 							A__					(  self    :  Any  ):
							return self._hand




				def 							A__					(  self    :  List[str],    __lowercase    :  PokerHand  ):
							# 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 							A__					(  self    :  Dict  ):
							lowercase__         = PokerHand._HAND_NAME[self._hand_type - 14]
							lowercase__         = PokerHand._CARD_NAME[self._high_card]
							lowercase__         = PokerHand._CARD_NAME[self._first_pair]
							lowercase__         = 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]:
										lowercase__         = '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 							A__					(  self    :  Dict,    __lowercase    :  PokerHand  ):
							# 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 							A__					(  self    :  Dict  ):
							# 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 							A__					(  self    :  Optional[Any]  ):
							return len(self._card_suit  ) == 1




				def 							A__					(  self    :  int  ):
							# 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
													lowercase__         = self._card_values.pop(0  )
													self._card_values.append(__lowercase  )
										return True
							return False




				def 							A__					(  self    :  Optional[Any]  ):
							for i in range(4  ):
										if self._card_values[i] - self._card_values[i + 1] != 1:
													return False
							return True




				def 							A__					(  self    :  Any  ):
							# 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
							lowercase__         = 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:
																lowercase__         = self._card_values[i]
																kind += 1
													elif vala == self._card_values[i]:
																kind += 2
													elif not vala:
																lowercase__         = 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)
							lowercase__         = kind + 2 if kind in [4, 5] else kind
							# first meaning first pair to compare in 'compare_with'
							lowercase__         = max(__lowercase,    __lowercase  )
							lowercase__         = 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:
										lowercase__         = second, first
							lowercase__         = first
							lowercase__         = second
							return kind




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




				def __repr__(  self    :  Union[str, Any]  ):
							return F'''{self.__class__}("{self._hand}")'''




				def __str__(  self    :  List[Any]  ):
							return self._hand




				def __eq__(  self    :  int,    __lowercase    :  Optional[int]  ):
							if isinstance(__lowercase,    __lowercase  ):
										return self.compare_with(__lowercase  ) == "Tie"
							return NotImplemented




				def __lt__(  self    :  Tuple,    __lowercase    :  Optional[Any]  ):
							if isinstance(__lowercase,    __lowercase  ):
										return self.compare_with(__lowercase  ) == "Loss"
							return NotImplemented




				def __le__(  self    :  Any,    __lowercase    :  List[str]  ):
							if isinstance(__lowercase,    __lowercase  ):
										return self < other or self == other
							return NotImplemented




				def __gt__(  self    :  Optional[Any],    __lowercase    :  int  ):
							if isinstance(__lowercase,    __lowercase  ):
										return not self < other and self != other
							return NotImplemented




				def __ge__(  self    :  Tuple,    __lowercase    :  Dict  ):
							if isinstance(__lowercase,    __lowercase  ):
										return not self < other
							return NotImplemented




				def __hash__(  self    :  Any  ):
							return object.__hash__(self  )



def __lowerCAmelCase       (   ):
			# Solution for problem number 54 from Project Euler
			# Input from poker_hands.txt file
			lowercase__         = 0
			lowercase__         = os.path.abspath(os.path.dirname(SCREAMING_SNAKE_CASE__     )     )
			lowercase__         = os.path.join(SCREAMING_SNAKE_CASE__  ,     "poker_hands.txt"     )
			with open(SCREAMING_SNAKE_CASE__     ) as file_hand:
						for line in file_hand:
									lowercase__         = line[:14].strip()
									lowercase__         = line[15:].strip()
									lowercase__         = PokerHand(SCREAMING_SNAKE_CASE__     ), PokerHand(SCREAMING_SNAKE_CASE__     )
									lowercase__         = player.compare_with(SCREAMING_SNAKE_CASE__     )
									if output == "Win":
												answer += 1
			return answer


if __name__ == "__main__":
							solution()








from typing import Optional, Tuple

import flax.linen as nn
import jax
import jax.numpy as jnp
from configuration_hybrid_clip import HybridCLIPConfig
from flax.core.frozen_dict import FrozenDict

from transformers import FLAX_MODEL_MAPPING, FlaxCLIPVisionModel
from transformers.modeling_flax_utils import FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPOutput
from transformers.utils import logging


lowercase_           =	logging.get_logger(__name__)


class        A_					(       nn.Module    ):




      '''simple docstring'''


      __snake_case					       =   42
      __snake_case					       =   jnp.floataa




      def      _snake_case	(				self:       List[Any]				):
       __lowerCamelCase		:							Union[str, Any]							=						self.config.text_config
       __lowerCamelCase		:							List[Any]							=						self.config.vision_config

       __lowerCamelCase		:							Any							=						self.config.projection_dim
       __lowerCamelCase		:							Dict							=						text_config.hidden_size
       __lowerCamelCase		:							str							=						vision_config.hidden_size

       __lowerCamelCase		:							Optional[Any]							=						FLAX_MODEL_MAPPING[self.config.text_config.__class__].module_class
       __lowerCamelCase		:							int							=						FLAX_MODEL_MAPPING.get(self.config.vision_config.__class__						,      a				).module_class

       __lowerCamelCase		:							Union[str, Any]							=						text_module(a						,      dtype=self.dtype				)
       __lowerCamelCase		:							int							=						vision_module(a						,      dtype=self.dtype				)

       __lowerCamelCase		:							Union[str, Any]							=						nn.Dense(
           self.projection_dim						,      dtype=self.dtype						,      kernel_init=jax.nn.initializers.normal(0.0_2				)						,      use_bias=a						,      )
       __lowerCamelCase		:							int							=						nn.Dense(
           self.projection_dim						,      dtype=self.dtype						,      kernel_init=jax.nn.initializers.normal(0.0_2				)						,      use_bias=a						,      )
       __lowerCamelCase		:							Dict							=						self.param('logit_scale'						,      jax.nn.initializers.ones						,      []				)




      def __call__(				self:       int						,      a:       Union[str, Any]=None						,      a:       str=None						,      a:       Tuple=None						,      a:       str=None						,      a:       List[Any]=None						,      a:       bool = True						,      a:       List[str]=None						,      a:       Any=None						,      a:       Optional[Any]=None						,      ):
       __lowerCamelCase		:							str							=						return_dict if return_dict is not None else self.config.return_dict

       __lowerCamelCase		:							Any							=						self.vision_model(
           pixel_values=a						,      deterministic=a						,      output_attentions=a						,      output_hidden_states=a						,      return_dict=a						,      )

       __lowerCamelCase		:							Union[str, Any]							=						self.text_model(
           input_ids=a						,      attention_mask=a						,      token_type_ids=a						,      position_ids=a						,      deterministic=a						,      output_attentions=a						,      output_hidden_states=a						,      return_dict=a						,      )

       __lowerCamelCase		:							Tuple							=						vision_outputs[1]
       __lowerCamelCase		:							List[Any]							=						self.visual_projection(a				)

       __lowerCamelCase		:							Any							=						text_outputs[1]
       __lowerCamelCase		:							Optional[Any]							=						self.text_projection(a				)

       # normalized features
       __lowerCamelCase		:							str							=						image_embeds / jnp.linalg.norm(a						,      axis=-1						,      keepdims=a				)
       __lowerCamelCase		:							Optional[int]							=						text_embeds / jnp.linalg.norm(a						,      axis=-1						,      keepdims=a				)

       # cosine similarity as logits
       __lowerCamelCase		:							Union[str, Any]							=						jnp.exp(self.logit_scale				)
       __lowerCamelCase		:							Union[str, Any]							=						jnp.matmul(a						,      image_embeds.T				) * logit_scale
       __lowerCamelCase		:							List[str]							=						logits_per_text.T

       if not return_dict:
        return (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)

       return FlaxCLIPOutput(
           logits_per_image=a						,      logits_per_text=a						,      text_embeds=a						,      image_embeds=a						,      text_model_output=a						,      vision_model_output=a						,      )



class        A_					(       __UpperCamelCase    ):




      '''simple docstring'''


      __snake_case					       =   HybridCLIPConfig
      __snake_case					       =   FlaxHybridCLIPModule




      def __init__(				self:       List[Any]						,      a:       HybridCLIPConfig						,      a:       Optional[Tuple] = None						,      a:       int = 0						,      a:       jnp.dtype = jnp.floataa						,      **a:       int						,      ):
       if input_shape is None:
        __lowerCamelCase		:							int							=						((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))

       __lowerCamelCase		:							int							=						self.module_class(config=a						,      dtype=a						,      **a				)
       super().__init__(a						,      a						,      input_shape=a						,      seed=a						,      dtype=a				)




      def      _snake_case	(				self:       Dict						,      a:       jax.random.PRNGKey						,      a:       Tuple						,      a:       FrozenDict = None				):
       # init input tensor
       __lowerCamelCase		:							int							=						jnp.zeros(input_shape[0]						,      dtype='i4'				)
       __lowerCamelCase		:							List[Any]							=						jnp.broadcast_to(jnp.arange(jnp.atleast_ad(a				).shape[-1]				)						,      input_shape[0]				)
       __lowerCamelCase		:							Any							=						jnp.ones_like(a				)
       __lowerCamelCase		:							int							=						jnp.ones_like(a				)

       __lowerCamelCase		:							Optional[Any]							=						jax.random.normal(a						,      input_shape[1]				)

       __lowerCamelCase					,     __lowerCamelCase		:							List[Any]							=						jax.random.split(a				)
       __lowerCamelCase		:							Tuple							=						{'params': params_rng, 'dropout': dropout_rng}

       return self.module.init(a						,      a						,      a						,      a						,      a						,      a				)["params"]




      def __call__(				self:       Tuple						,      a:       Optional[Any]						,      a:       Dict						,      a:       Optional[int]=None						,      a:       Union[str, Any]=None						,      a:       int=None						,      a:       dict = None						,      a:       jax.random.PRNGKey = None						,      a:       bool = False						,      a:       Optional[bool] = None						,      a:       Optional[bool] = None						,      a:       Optional[bool] = None						,      ):
       __lowerCamelCase		:							str							=						output_attentions if output_attentions is not None else self.config.output_attentions
       __lowerCamelCase		:							Dict							=						(
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       __lowerCamelCase		:							int							=						return_dict if return_dict is not None else self.config.return_dict

       if position_ids is None:
        __lowerCamelCase		:							Optional[int]							=						jnp.broadcast_to(jnp.arange(jnp.atleast_ad(a				).shape[-1]				)						,      input_ids.shape				)

       if token_type_ids is None:
        __lowerCamelCase		:							str							=						jnp.zeros_like(a				)

       if attention_mask is None:
        __lowerCamelCase		:							str							=						jnp.ones_like(a				)

       # Handle any PRNG if needed
       __lowerCamelCase		:							Union[str, Any]							=						{}
       if dropout_rng is not None:
        __lowerCamelCase		:							Any							=						dropout_rng

       return self.module.apply(
           {'params': params or self.params}						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype=jnp.floataa				)						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype='i4'				)						,      not train						,      a						,      a						,      a						,      rngs=a						,      )




      def      _snake_case	(				self:       Tuple						,      a:       Tuple						,      a:       List[Any]=None						,      a:       Dict=None						,      a:       int=None						,      a:       dict = None						,      a:       jax.random.PRNGKey = None						,      a:       Tuple=False						,      ):
       if position_ids is None:
        __lowerCamelCase		:							str							=						jnp.broadcast_to(jnp.arange(jnp.atleast_ad(a				).shape[-1]				)						,      input_ids.shape				)

       if token_type_ids is None:
        __lowerCamelCase		:							Union[str, Any]							=						jnp.zeros_like(a				)

       if attention_mask is None:
        __lowerCamelCase		:							int							=						jnp.ones_like(a				)

       # Handle any PRNG if needed
       __lowerCamelCase		:							Optional[int]							=						{}
       if dropout_rng is not None:
        __lowerCamelCase		:							List[str]							=						dropout_rng

       def _get_features(a:       str						,      a:       Any						,      a:       Optional[int]						,      a:       Optional[int]						,      a:       Union[str, Any]						,      a:       Optional[int]				):
        __lowerCamelCase		:							Tuple							=						module.text_model(
            input_ids=a						,      attention_mask=a						,      position_ids=a						,      token_type_ids=a						,      deterministic=a						,      )
        __lowerCamelCase		:							int							=						text_outputs[1]
        __lowerCamelCase		:							Optional[Any]							=						module.text_projection(a				)
        return text_features

       return self.module.apply(
           {'params': params or self.params}						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype='i4'				)						,      jnp.array(a						,      dtype='i4'				)						,      not train						,      method=_get_features						,      rngs=a						,      )




      def      _snake_case	(				self:       int						,      a:       Optional[int]						,      a:       dict = None						,      a:       jax.random.PRNGKey = None						,      a:       str=False				):
       __lowerCamelCase		:							Dict							=						{}
       if dropout_rng is not None:
        __lowerCamelCase		:							List[str]							=						dropout_rng

       def _get_features(a:       str						,      a:       Tuple						,      a:       Any				):
        __lowerCamelCase		:							Dict							=						module.vision_model(pixel_values=a						,      deterministic=a				)
        __lowerCamelCase		:							int							=						vision_outputs[1]  # pooled_output
        __lowerCamelCase		:							int							=						module.visual_projection(a				)
        return image_features

       return self.module.apply(
           {'params': params or self.params}						,      jnp.array(a						,      dtype=jnp.floataa				)						,      not train						,      method=_get_features						,      rngs=a						,      )




      @classmethod
      def      _snake_case	(				cls:       str						,      a:       str = None						,      a:       str = None						,      *a:       Optional[Any]						,      **a:       List[str]						,      ):
       __lowerCamelCase		:							List[Any]							=						{
           argument[len('text_'				) :]: value for argument, value in kwargs.items() if argument.startswith('text_'				)
       }

       __lowerCamelCase		:							Optional[Any]							=						{
           argument[len('vision_'				) :]: value for argument, value in kwargs.items() if argument.startswith('vision_'				)
       }

       # remove text, vision kwargs from kwargs
       for key in kwargs_text.keys():
        del kwargs["text_" + key]
       for key in kwargs_vision.keys():
        del kwargs["vision_" + key]

       # Load and initialize the text and vision model
       __lowerCamelCase		:							Any							=						kwargs_text.pop('model'						,      a				)
       if text_model is None:
        assert (
            text_model_name_or_path is not None
        ), "If `model` is not defined as an argument, a `text_model_name_or_path` has to be defined"
        from transformers import FlaxAutoModel

        if "config" not in kwargs_text:
         from transformers import AutoConfig

         __lowerCamelCase		:							Optional[int]							=						AutoConfig.from_pretrained(a				)
         __lowerCamelCase		:							Any							=						text_config

        __lowerCamelCase		:							Dict							=						FlaxAutoModel.from_pretrained(a						,      *a						,      **a				)

       __lowerCamelCase		:							Any							=						kwargs_vision.pop('model'						,      a				)
       if vision_model is None:
        assert (
            vision_model_name_or_path is not None
        ), "If `model` is not defined as an argument, a `vision_model_name_or_path` has to be defined"
        from transformers import FlaxAutoModel

        if "config" not in kwargs_vision:
         from transformers import AutoConfig

         __lowerCamelCase		:							Any							=						AutoConfig.from_pretrained(a				)
         __lowerCamelCase		:							int							=						vision_config

        __lowerCamelCase		:							str							=						FlaxAutoModel.from_pretrained(a						,      *a						,      **a				)

       # instantiate config with corresponding kwargs
       __lowerCamelCase		:							Optional[int]							=						kwargs.pop('dtype'						,      jnp.floataa				)
       __lowerCamelCase		:							List[Any]							=						HybridCLIPConfig.from_text_vision_configs(text_model.config						,      vision_model.config						,      **a				)

       # init model
       __lowerCamelCase		:							List[Any]							=						cls(a						,      *a						,      dtype=a						,      **a				)

       if vision_config.model_type == "clip":
        __lowerCamelCase		:							Any							=						vision_model.params['vision_model']
        __lowerCamelCase		:							Optional[Any]							=						vision_model.params['visual_projection']['kernel']
       else:
        __lowerCamelCase		:							Optional[int]							=						vision_model.params

       __lowerCamelCase		:							List[str]							=						text_model.params

       return model

