





"""simple docstring"""


import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
  from PIL import Image

  from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
  import torch

if is_tf_available():
  import tensorflow as tf



@require_vision
@require_torchvision
class      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				int:
        _UpperCamelCase      :	Union[str, Any]						=       tempfile.mkdtemp()
        _UpperCamelCase      :	int						=       SamImageProcessor()
        _UpperCamelCase      :	Dict						=       SamProcessor(__a	)
        processor.save_pretrained(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]					,   **__a   :       List[str]	)		->				int:
        return AutoProcessor.from_pretrained(self.tmpdirname					,   **__a	).image_processor

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Any:
        shutil.rmtree(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				str:
        _UpperCamelCase      :	List[Any]						=       [np.random.randint(255					,   size=(3, 30, 400)					,   dtype=np.uinta	)]

        _UpperCamelCase      :	Any						=       [Image.fromarray(np.moveaxis(__a					,   0					,   -1	)	) for x in image_inputs]

        return image_inputs

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Tuple:
        _UpperCamelCase      :	List[Any]						=       SamProcessor(image_processor=self.get_image_processor()	)
        processor.save_pretrained(self.tmpdirname	)

        _UpperCamelCase      :	Dict						=       self.get_image_processor(do_normalize=__a					,   padding_value=1.0	)

        _UpperCamelCase      :	List[Any]						=       SamProcessor.from_pretrained(self.tmpdirname					,   do_normalize=__a					,   padding_value=1.0	)

        self.assertEqual(processor.image_processor.to_json_string()					,   image_processor_add_kwargs.to_json_string()	)
        self.assertIsInstance(processor.image_processor					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Tuple:
        _UpperCamelCase      :	List[str]						=       self.get_image_processor()

        _UpperCamelCase      :	Tuple						=       SamProcessor(image_processor=__a	)

        _UpperCamelCase      :	Any						=       self.prepare_image_inputs()

        _UpperCamelCase      :	List[Any]						=       image_processor(__a					,   return_tensors="np"	)
        _UpperCamelCase      :	Any						=       processor(images=__a					,   return_tensors="np"	)

        input_feat_extract.pop("original_sizes"	)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop("reshaped_input_sizes"	)  # pop original_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
              self.assertAlmostEqual(input_feat_extract[key].sum()					,   input_processor[key].sum()					,   delta=1e-2	)


  @require_torch
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				str:
        _UpperCamelCase      :	Optional[int]						=       self.get_image_processor()

        _UpperCamelCase      :	Optional[int]						=       SamProcessor(image_processor=__a	)
        _UpperCamelCase      :	Tuple						=       [torch.ones((1, 3, 5, 5)	)]

        _UpperCamelCase      :	Optional[Any]						=       [[1764, 2646]]

        _UpperCamelCase      :	Tuple						=       [[683, 1024]]
        _UpperCamelCase      :	Optional[int]						=       processor.post_process_masks(__a					,   __a					,   __a	)
        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        _UpperCamelCase      :	Optional[Any]						=       processor.post_process_masks(
            __a					,   torch.tensor(__a	)					,   torch.tensor(__a	)	)
        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        # should also work with np
        _UpperCamelCase      :	str						=       [np.ones((1, 3, 5, 5)	)]
        _UpperCamelCase      :	Dict						=       processor.post_process_masks(__a					,   np.array(__a	)					,   np.array(__a	)	)

        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        _UpperCamelCase      :	List[Any]						=       [[1, 0], [0, 1]]
        with self.assertRaises(__a	):
              _UpperCamelCase      :	Optional[Any]						=       processor.post_process_masks(__a					,   np.array(__a	)					,   np.array(__a	)	)





@require_vision
@require_tf
class      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				List[str]:
        _UpperCamelCase      :	Optional[Any]						=       tempfile.mkdtemp()
        _UpperCamelCase      :	Any						=       SamImageProcessor()
        _UpperCamelCase      :	Optional[int]						=       SamProcessor(__a	)
        processor.save_pretrained(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]					,   **__a   :       str	)		->				List[Any]:
        return AutoProcessor.from_pretrained(self.tmpdirname					,   **__a	).image_processor

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				Any:
        shutil.rmtree(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				List[Any]:
        _UpperCamelCase      :	Any						=       [np.random.randint(255					,   size=(3, 30, 400)					,   dtype=np.uinta	)]

        _UpperCamelCase      :	List[str]						=       [Image.fromarray(np.moveaxis(__a					,   0					,   -1	)	) for x in image_inputs]

        return image_inputs

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        _UpperCamelCase      :	Dict						=       SamProcessor(image_processor=self.get_image_processor()	)
        processor.save_pretrained(self.tmpdirname	)

        _UpperCamelCase      :	Optional[int]						=       self.get_image_processor(do_normalize=__a					,   padding_value=1.0	)

        _UpperCamelCase      :	Optional[int]						=       SamProcessor.from_pretrained(self.tmpdirname					,   do_normalize=__a					,   padding_value=1.0	)

        self.assertEqual(processor.image_processor.to_json_string()					,   image_processor_add_kwargs.to_json_string()	)
        self.assertIsInstance(processor.image_processor					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[int]:
        _UpperCamelCase      :	Union[str, Any]						=       self.get_image_processor()

        _UpperCamelCase      :	Optional[int]						=       SamProcessor(image_processor=__a	)

        _UpperCamelCase      :	str						=       self.prepare_image_inputs()

        _UpperCamelCase      :	str						=       image_processor(__a					,   return_tensors="np"	)
        _UpperCamelCase      :	Dict						=       processor(images=__a					,   return_tensors="np"	)

        input_feat_extract.pop("original_sizes"	)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop("reshaped_input_sizes"	)  # pop reshaped_input_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
              self.assertAlmostEqual(input_feat_extract[key].sum()					,   input_processor[key].sum()					,   delta=1e-2	)


  @require_tf
  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Union[str, Any]:
        _UpperCamelCase      :	Dict						=       self.get_image_processor()

        _UpperCamelCase      :	Optional[Any]						=       SamProcessor(image_processor=__a	)
        _UpperCamelCase      :	Tuple						=       [tf.ones((1, 3, 5, 5)	)]

        _UpperCamelCase      :	Any						=       [[1764, 2646]]

        _UpperCamelCase      :	List[str]						=       [[683, 1024]]
        _UpperCamelCase      :	List[Any]						=       processor.post_process_masks(__a					,   __a					,   __a					,   return_tensors="tf"	)
        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        _UpperCamelCase      :	Tuple						=       processor.post_process_masks(
            __a					,   tf.convert_to_tensor(__a	)					,   tf.convert_to_tensor(__a	)					,   return_tensors="tf"					,   )
        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        # should also work with np
        _UpperCamelCase      :	Tuple						=       [np.ones((1, 3, 5, 5)	)]
        _UpperCamelCase      :	Optional[Any]						=       processor.post_process_masks(
            __a					,   np.array(__a	)					,   np.array(__a	)					,   return_tensors="tf"	)

        self.assertEqual(masks[0].shape					,   (1, 3, 1764, 2646)	)

        _UpperCamelCase      :	Any						=       [[1, 0], [0, 1]]
        with self.assertRaises(tf.errors.InvalidArgumentError	):
              _UpperCamelCase      :	str						=       processor.post_process_masks(
                  __a					,   np.array(__a	)					,   np.array(__a	)					,   return_tensors="tf"	)





@require_vision
@require_torchvision
class      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				str:
        _UpperCamelCase      :	List[str]						=       tempfile.mkdtemp()
        _UpperCamelCase      :	Optional[Any]						=       SamImageProcessor()
        _UpperCamelCase      :	List[Any]						=       SamProcessor(__a	)
        processor.save_pretrained(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   **__a   :       Optional[Any]	)		->				List[str]:
        return AutoProcessor.from_pretrained(self.tmpdirname					,   **__a	).image_processor

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				List[Any]:
        shutil.rmtree(self.tmpdirname	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	int						=       [np.random.randint(255					,   size=(3, 30, 400)					,   dtype=np.uinta	)]

        _UpperCamelCase      :	List[str]						=       [Image.fromarray(np.moveaxis(__a					,   0					,   -1	)	) for x in image_inputs]

        return image_inputs

  @is_pt_tf_cross_test
  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Any:
        _UpperCamelCase      :	Union[str, Any]						=       self.get_image_processor()

        _UpperCamelCase      :	int						=       SamProcessor(image_processor=__a	)
        _UpperCamelCase      :	Union[str, Any]						=       np.random.randint(0					,   2					,   size=(1, 3, 5, 5)	).astype(np.floataa	)
        _UpperCamelCase      :	Union[str, Any]						=       [tf.convert_to_tensor(__a	)]
        _UpperCamelCase      :	Optional[Any]						=       [torch.tensor(__a	)]

        _UpperCamelCase      :	Tuple						=       [[1764, 2646]]

        _UpperCamelCase      :	List[Any]						=       [[683, 1024]]
        _UpperCamelCase      :	Tuple						=       processor.post_process_masks(
            __a					,   __a					,   __a					,   return_tensors="tf"	)
        _UpperCamelCase      :	List[Any]						=       processor.post_process_masks(
            __a					,   __a					,   __a					,   return_tensors="pt"	)

        self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()	)	)


  @is_pt_tf_cross_test
  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				List[Any]:
        _UpperCamelCase      :	int						=       self.get_image_processor()

        _UpperCamelCase      :	str						=       SamProcessor(image_processor=__a	)

        _UpperCamelCase      :	List[Any]						=       self.prepare_image_inputs()

        _UpperCamelCase      :	List[str]						=       image_processor(__a					,   return_tensors="pt"	)["pixel_values"].numpy()
        _UpperCamelCase      :	Optional[Any]						=       processor(images=__a					,   return_tensors="pt"	)["pixel_values"].numpy()

        _UpperCamelCase      :	int						=       image_processor(__a					,   return_tensors="tf"	)["pixel_values"].numpy()
        _UpperCamelCase      :	int						=       processor(images=__a					,   return_tensors="tf"	)["pixel_values"].numpy()

        self.assertTrue(np.allclose(__a					,   __a	)	)
        self.assertTrue(np.allclose(__a					,   __a	)	)
        self.assertTrue(np.allclose(__a					,   __a	)	)







"""simple docstring"""


from __future__ import annotations

import string
from itertools import cycle, product
from pathlib import Path

lowerCamelCase__				  =   (
    string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
lowerCamelCase__				  =   [ord(letter) for letter in string.ascii_lowercase]
lowerCamelCase__				  =   {ord(char) for char in VALID_CHARS}

lowerCamelCase__				  =   ["the", "be", "to", "of", "and", "in", "that", "have"]




def 					lowercase__    (					lowercase_		,lowercase_			)					->		str | None:




      """simple docstring"""

      _UpperCamelCase      :	str						=       ""
      _UpperCamelCase      :	int
      _UpperCamelCase      :	int
      _UpperCamelCase      :	int

      for keychar, cipherchar in zip(cycle(lowercase_			)		,lowercase_			):
            _UpperCamelCase      :	Dict						=       cipherchar ^ keychar
            if decodedchar not in VALID_INTS:
                  return None
            decoded += chr(lowercase_			)

      return decoded




def 					lowercase__    (					lowercase_			)					->		list[str]:




      """simple docstring"""

      _UpperCamelCase      :	list[str]						=       []
      for key in product(lowercase_		,repeat=3			):
            _UpperCamelCase      :	int						=       try_key(lowercase_		,lowercase_			)
            if encoded is not None:
                  possibles.append(lowercase_			)
      return possibles




def 					lowercase__    (					lowercase_		,lowercase_			)					->		list[str]:




      """simple docstring"""

      return [possible for possible in possibles if common_word in possible.lower()]




def 					lowercase__    (					lowercase_ = "p059_cipher.txt"			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	list[int]
      _UpperCamelCase      :	list[str]
      _UpperCamelCase      :	str
      _UpperCamelCase      :	str
      _UpperCamelCase      :	str						=       Path(lowercase_			).parent.joinpath(lowercase_			).read_text(encoding="utf-8"			)

      _UpperCamelCase      :	Optional[Any]						=       [int(lowercase_			) for number in data.strip().split(","			)]

      _UpperCamelCase      :	List[str]						=       filter_valid_chars(lowercase_			)
      for common_word in COMMON_WORDS:
            _UpperCamelCase      :	Union[str, Any]						=       filter_common_word(lowercase_		,lowercase_			)
            if len(lowercase_			) == 1:
                  break

      _UpperCamelCase      :	Union[str, Any]						=       possibles[0]
      return sum(ord(lowercase_			) for char in decoded_text			)


if __name__ == "__main__":
  print(f"""{solution() = }""")
