





"""simple docstring"""




import random
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   import PIL

   from transformers import FlavaImageProcessor
   from transformers.image_utils import PILImageResampling
   from transformers.models.flava.image_processing_flava import (
       FLAVA_CODEBOOK_MEAN,
       FLAVA_CODEBOOK_STD,
       FLAVA_IMAGE_MEAN,
       FLAVA_IMAGE_STD,
   )
else:
   lowerCamelCase_	:		Optional[Any]         =   None

class 					_UpperCAmelCase    (  unittest.TestCase						):



      '''simple docstring'''

      def __init__(	self   , snake_case_   , snake_case_=7   , snake_case_=3   , snake_case_=3_0   , snake_case_=4_0_0   , snake_case_=True   , snake_case_=None   , snake_case_=True   , snake_case_=None   , snake_case_=None   , snake_case_=True   , snake_case_=1 / 2_5_5   , snake_case_=True   , snake_case_=FLAVA_IMAGE_MEAN   , snake_case_=FLAVA_IMAGE_STD   , snake_case_=1_4   , snake_case_=7_5   , snake_case_=None   , snake_case_=1_6   , snake_case_=0.3   , snake_case_=None   , snake_case_=True   , snake_case_=None   , snake_case_=None   , snake_case_=True   , snake_case_=None   , snake_case_=True   , snake_case_=True   , snake_case_=FLAVA_CODEBOOK_MEAN   , snake_case_=FLAVA_CODEBOOK_STD   , ):

        """simple docstring"""

        A_    :			Union[str, Any]									=    size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
        A_    :			Union[str, Any]									=    crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
        A_    :			Optional[Any]									=    codebook_size if codebook_size is not None else {'height': 1_1_2, 'width': 1_1_2}
        A_    :			List[str]									=    codebook_crop_size if codebook_crop_size is not None else {'height': 1_1_2, 'width': 1_1_2}

        A_    :			Optional[Any]									=    parent
        A_    :			Union[str, Any]									=    batch_size
        A_    :			List[str]									=    num_channels
        A_    :			Union[str, Any]									=    do_resize
        A_    :			Union[str, Any]									=    do_rescale
        A_    :			List[Any]									=    rescale_factor
        A_    :			List[str]									=    min_resolution
        A_    :			Optional[Any]									=    max_resolution
        A_    :			List[Any]									=    size
        A_    :			Optional[Any]									=    resample if resample is not None else PILImageResampling.BICUBIC
        A_    :			Dict									=    do_normalize
        A_    :			List[Any]									=    image_mean
        A_    :			Union[str, Any]									=    image_std
        A_    :			Union[str, Any]									=    do_center_crop
        A_    :			Union[str, Any]									=    crop_size

        A_    :			Optional[Any]									=    input_size_patches
        A_    :			List[Any]									=    total_mask_patches
        A_    :			Dict									=    mask_group_max_patches
        A_    :			List[str]									=    mask_group_min_patches
        A_    :			int									=    mask_group_min_aspect_ratio
        A_    :			Union[str, Any]									=    mask_group_max_aspect_ratio

        A_    :			Optional[int]									=    codebook_do_resize
        A_    :			Union[str, Any]									=    codebook_size
        A_    :			Union[str, Any]									=    codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
        A_    :			Dict									=    codebook_do_center_crop
        A_    :			List[Any]									=    codebook_crop_size
        A_    :			Tuple									=    codebook_do_map_pixels
        A_    :			Dict									=    codebook_do_normalize
        A_    :			Tuple									=    codebook_image_mean
        A_    :			Optional[Any]									=    codebook_image_std

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
            "resample": self.resample,
            "do_rescale": self.do_rescale,
            "rescale_factor": self.rescale_factor,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
            "input_size_patches": self.input_size_patches,
            "total_mask_patches": self.total_mask_patches,
            "mask_group_max_patches": self.mask_group_max_patches,
            "mask_group_min_patches": self.mask_group_min_patches,
            "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
            "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
            "codebook_do_resize": self.codebook_do_resize,
            "codebook_size": self.codebook_size,
            "codebook_resample": self.codebook_resample,
            "codebook_do_center_crop": self.codebook_do_center_crop,
            "codebook_crop_size": self.codebook_crop_size,
            "codebook_do_map_pixels": self.codebook_do_map_pixels,
            "codebook_do_normalize": self.codebook_do_normalize,
            "codebook_image_mean": self.codebook_image_mean,
            "codebook_image_std": self.codebook_image_std,
        }

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return (self.size["height"], self.size["width"])

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return (
            (self.input_size_patches, self.input_size_patches)
            if not isinstance(self.input_size_patches   , snake_case_    )
            else self.input_size_patches
        )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return (self.codebook_size["height"], self.codebook_size["width"])


@require_torch
@require_vision
class 					_UpperCAmelCase    (  UpperCAmelCase__     ,  unittest.TestCase						):



      '''simple docstring'''
      lowercase_ :					List[Any]             =  FlavaImageProcessor if is_vision_available() else None
      lowercase_ :					Any             =  None

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			Tuple									=    FlavaImageProcessingTester(self    )

      @property
      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return self.image_processor_tester.prepare_image_processor_dict()

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			List[str]									=    self.image_processing_class(**self.image_processor_dict    )
        self.assertTrue(hasattr(snake_case_   , 'image_mean'    )    )
        self.assertTrue(hasattr(snake_case_   , 'image_std'    )    )
        self.assertTrue(hasattr(snake_case_   , 'do_normalize'    )    )
        self.assertTrue(hasattr(snake_case_   , 'do_resize'    )    )
        self.assertTrue(hasattr(snake_case_   , 'resample'    )    )
        self.assertTrue(hasattr(snake_case_   , 'crop_size'    )    )
        self.assertTrue(hasattr(snake_case_   , 'do_center_crop'    )    )
        self.assertTrue(hasattr(snake_case_   , 'do_rescale'    )    )
        self.assertTrue(hasattr(snake_case_   , 'rescale_factor'    )    )
        self.assertTrue(hasattr(snake_case_   , 'masking_generator'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_do_resize'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_size'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_resample'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_do_center_crop'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_crop_size'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_do_map_pixels'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_do_normalize'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_image_mean'    )    )
        self.assertTrue(hasattr(snake_case_   , 'codebook_image_std'    )    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			Any									=    self.image_processing_class.from_dict(self.image_processor_dict    )
        self.assertEqual(image_processor.size   , {'height': 2_2_4, 'width': 2_2_4}    )
        self.assertEqual(image_processor.crop_size   , {'height': 2_2_4, 'width': 2_2_4}    )
        self.assertEqual(image_processor.codebook_size   , {'height': 1_1_2, 'width': 1_1_2}    )
        self.assertEqual(image_processor.codebook_crop_size   , {'height': 1_1_2, 'width': 1_1_2}    )

        A_    :			Optional[int]									=    self.image_processing_class.from_dict(
            self.image_processor_dict   , size=4_2   , crop_size=8_4   , codebook_size=3_3   , codebook_crop_size=6_6    )
        self.assertEqual(image_processor.size   , {'height': 4_2, 'width': 4_2}    )
        self.assertEqual(image_processor.crop_size   , {'height': 8_4, 'width': 8_4}    )
        self.assertEqual(image_processor.codebook_size   , {'height': 3_3, 'width': 3_3}    )
        self.assertEqual(image_processor.codebook_crop_size   , {'height': 6_6, 'width': 6_6}    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        pass

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			Union[str, Any]									=    self.image_processing_class(**self.image_processor_dict    )
        # create random PIL images
        A_    :			Dict									=    prepare_image_inputs(self.image_processor_tester   , equal_resolution=snake_case_    )
        for image in image_inputs:
          self.assertIsInstance(snake_case_   , PIL.Image.Image    )

        # Test not batched input
        A_    :			Any									=    image_processing(image_inputs[0]   , return_tensors='pt'    )

        # Test no bool masked pos
        self.assertFalse('bool_masked_pos' in encoded_images    )

        A_		,			A_    :			Optional[Any]									=    self.image_processor_tester.get_expected_image_size()

        self.assertEqual(
            encoded_images.pixel_values.shape   , (1, self.image_processor_tester.num_channels, expected_height, expected_width)   , )

        # Test batched
        A_    :			int									=    image_processing(snake_case_   , return_tensors='pt'    )
        A_		,			A_    :			int									=    self.image_processor_tester.get_expected_image_size()

        # Test no bool masked pos
        self.assertFalse('bool_masked_pos' in encoded_images    )

        self.assertEqual(
            encoded_images.pixel_values.shape   , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )   , )

      def    lowerCamelCase_     (	self   , snake_case_   , snake_case_    ):

        """simple docstring"""

        A_    :			str									=    self.image_processing_class(**self.image_processor_dict    )
        # create random tensors
        A_    :			str									=    prepare_image_inputs(self.image_processor_tester   , equal_resolution=snake_case_   , **snake_case_    )
        for image in image_inputs:
          self.assertIsInstance(snake_case_   , snake_case_    )

        # Test not batched input
        A_    :			Optional[int]									=    image_processing(image_inputs[0]   , return_tensors='pt'    )

        A_		,			A_    :			str									=    self.image_processor_tester.get_expected_image_size()
        self.assertEqual(
            encoded_images.pixel_values.shape   , (1, self.image_processor_tester.num_channels, expected_height, expected_width)   , )

        A_    :			Tuple									=    image_processing(snake_case_   , return_image_mask=snake_case_   , return_tensors='pt'    )

        A_		,			A_    :			Any									=    self.image_processor_tester.get_expected_image_size()
        self.assertEqual(
            encoded_images.pixel_values.shape   , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )   , )

        A_		,			A_    :			Optional[int]									=    self.image_processor_tester.get_expected_mask_size()
        self.assertEqual(
            encoded_images.bool_masked_pos.shape   , (
                self.image_processor_tester.batch_size,
                expected_height,
                expected_width,
            )   , )

        # Test batched
        A_    :			Dict									=    image_processing(snake_case_   , return_tensors='pt'    ).pixel_values

        A_		,			A_    :			int									=    self.image_processor_tester.get_expected_image_size()
        self.assertEqual(
            encoded_images.shape   , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )   , )

        # Test masking
        A_    :			int									=    image_processing(snake_case_   , return_image_mask=snake_case_   , return_tensors='pt'    )

        A_		,			A_    :			Any									=    self.image_processor_tester.get_expected_image_size()
        self.assertEqual(
            encoded_images.pixel_values.shape   , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )   , )

        A_		,			A_    :			Optional[Any]									=    self.image_processor_tester.get_expected_mask_size()
        self.assertEqual(
            encoded_images.bool_masked_pos.shape   , (
                self.image_processor_tester.batch_size,
                expected_height,
                expected_width,
            )   , )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        self._test_call_framework(np.ndarray   , prepare_kwargs={'numpify': True}    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        self._test_call_framework(torch.Tensor   , prepare_kwargs={'torchify': True}    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        random.seed(1_2_3_4    )
        A_    :			List[Any]									=    self.image_processing_class(**self.image_processor_dict    )
        A_    :			Optional[int]									=    prepare_image_inputs(self.image_processor_tester   , equal_resolution=snake_case_   , torchify=snake_case_    )

        # Test not batched input
        A_    :			str									=    image_processing(image_inputs[0]   , return_image_mask=snake_case_   , return_tensors='pt'    )
        self.assertEqual(encoded_images.bool_masked_pos.sum().item()   , 7_5    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			List[Any]									=    self.image_processing_class(**self.image_processor_dict    )
        # create random PIL images
        A_    :			Optional[int]									=    prepare_image_inputs(self.image_processor_tester   , equal_resolution=snake_case_    )
        for image in image_inputs:
          self.assertIsInstance(snake_case_   , PIL.Image.Image    )

        # Test not batched input
        A_    :			Optional[int]									=    image_processing(image_inputs[0]   , return_codebook_pixels=snake_case_   , return_tensors='pt'    )
        A_		,			A_    :			Any									=    self.image_processor_tester.get_expected_codebook_image_size()
        self.assertEqual(
            encoded_images.codebook_pixel_values.shape   , (1, self.image_processor_tester.num_channels, expected_height, expected_width)   , )

        # Test batched
        A_    :			Optional[int]									=    image_processing(snake_case_   , return_codebook_pixels=snake_case_   , return_tensors='pt'    )
        A_		,			A_    :			int									=    self.image_processor_tester.get_expected_codebook_image_size()
        self.assertEqual(
            encoded_images.codebook_pixel_values.shape   , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )   , )






"""simple docstring"""




import hashlib
import importlib.util
import json
import os
import pathlib
from types import ModuleType

import pytest
import requests

lowerCamelCase_	:		int         =   pathlib.Path.cwd().joinpath('project_euler')
lowerCamelCase_	:		str         =   pathlib.Path.cwd().joinpath(
    'scripts', 'project_euler_answers.json'
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
   lowerCamelCase_	:		dict[str, str]         =   json.load(file_handle)





def 		UpperCAmelCase__						(	_UpperCAmelCase   ):






  """simple docstring"""





  A_    :			List[str]									=    importlib.util.spec_from_file_location(file_path.name					,   str(_UpperCAmelCase   )   )
  A_    :			int									=    importlib.util.module_from_spec(_UpperCAmelCase   )  # type: ignore
  spec.loader.exec_module(_UpperCAmelCase   )  # type: ignore
  return module





def 		UpperCAmelCase__						(	):






  """simple docstring"""





  A_    :			Tuple									=    []
  for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
    if problem_dir_path.is_file() or problem_dir_path.name.startswith('_'   ):
      continue
    for file_path in problem_dir_path.iterdir():
      if file_path.suffix != ".py" or file_path.name.startswith(('_', 'test')   ):
        continue
      solution_file_paths.append(_UpperCAmelCase   )
  return solution_file_paths





def 		UpperCAmelCase__						(	):






  """simple docstring"""





  with open(os.environ['GITHUB_EVENT_PATH']   ) as file:
    A_    :			str									=    json.load(_UpperCAmelCase   )
  return event["pull_request"]["url"] + "/files"





def 		UpperCAmelCase__						(	):






  """simple docstring"""





  A_    :			Any									=    []
  A_    :			Optional[Any]									=    {
      'Accept': 'application/vnd.github.v3+json',
      'Authorization': 'token ' + os.environ['GITHUB_TOKEN'],
  }
  A_    :			Union[str, Any]									=    requests.get(get_files_url()					,   headers=_UpperCAmelCase   ).json()
  for file in files:
    A_    :			Optional[int]									=    pathlib.Path.cwd().joinpath(file['filename']   )
    if (
        filepath.suffix != ".py"
        or filepath.name.startswith(('_', 'test')   )
        or not filepath.name.startswith('sol'   )
    ):
      continue
    solution_file_paths.append(_UpperCAmelCase   )
  return solution_file_paths





def 		UpperCAmelCase__						(	):






  """simple docstring"""





  if os.environ.get('CI'   ) and os.environ.get('GITHUB_EVENT_NAME'   ) == "pull_request":
    # Return only if there are any, otherwise default to all solutions
    if filepaths := added_solution_file_path():
      return filepaths
  return all_solution_file_paths()





@pytest.mark.parametrize(
    'solution_path'					,   collect_solution_file_paths()					,   ids=lambda _UpperCAmelCase   : f"""{path.parent.name}/{path.name}"""					,   )
def 		UpperCAmelCase__						(	_UpperCAmelCase   ):






  """simple docstring"""





  A_    :			str									=    solution_path.parent.name[8:].zfill(3   )
  A_    :			str									=    PROBLEM_ANSWERS[problem_number]
  A_    :			List[Any]									=    convert_path_to_module(_UpperCAmelCase   )
  A_    :			Optional[int]									=    str(solution_module.solution()   )  # type: ignore
  A_    :			Any									=    hashlib.shaaaa(answer.encode()   ).hexdigest()
  assert (
      answer == expected
  ), f"""Expected solution to {problem_number} to have hash {expected}, got {answer}"""