





import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
 import torch
 from torch import nn

 from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
 from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class        __magic_name__	:





     """simple docstring"""



     def __init__(				self							:int      ,   snake_case							:Any      ,   snake_case							:Tuple=13      ,   snake_case							:Any=30      ,   snake_case							:Any=2      ,   snake_case							:str=3      ,   snake_case							:Any=True      ,   snake_case							:Any=True      ,   snake_case							:Optional[Any]=32      ,   snake_case							:int=5      ,   snake_case							:int=4      ,   snake_case							:Tuple=37      ,   snake_case							:Dict="gelu"      ,   snake_case							:Tuple=0.1      ,   snake_case							:Optional[Any]=0.1      ,   snake_case							:Optional[int]=10      ,   snake_case							:Optional[int]=0.02      ,   snake_case							:str=None      ,   snake_case							:int=2      ,   ):





        '''simple docstring'''




        A_       :					Dict        =      parent
        A_       :					Optional[int]        =      batch_size
        A_       :					int        =      image_size
        A_       :					Optional[int]        =      patch_size
        A_       :					str        =      num_channels
        A_       :					List[str]        =      is_training
        A_       :					List[Any]        =      use_labels
        A_       :					Any        =      hidden_size
        A_       :					List[str]        =      num_hidden_layers
        A_       :					List[str]        =      num_attention_heads
        A_       :					Tuple        =      intermediate_size
        A_       :					Tuple        =      hidden_act
        A_       :					Optional[Any]        =      hidden_dropout_prob
        A_       :					str        =      attention_probs_dropout_prob
        A_       :					Any        =      type_sequence_label_size
        A_       :					List[Any]        =      initializer_range
        A_       :					str        =      scope
        A_       :					Optional[Any]        =      encoder_stride

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        A_       :					Any        =      (image_size // patch_size) ** 2
        A_       :					Tuple        =      num_patches + 1



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        A_       :					Union[str, Any]        =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

        A_       :					Optional[int]        =      None
        if self.use_labels:
           A_       :					Tuple        =      ids_tensor([self.batch_size]      ,   self.type_sequence_label_size	)

        A_       :					int        =      self.get_config()

        return config, pixel_values, labels



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        return ViTConfig(
            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      ,   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=snake_case      ,   initializer_range=self.initializer_range      ,   encoder_stride=self.encoder_stride      ,   )



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]      ,   snake_case							:Union[str, Any]      ,   snake_case							:Union[str, Any]      ,   snake_case							:List[str]	):





        '''simple docstring'''




        A_       :					Tuple        =      ViTModel(config=snake_case	)
        model.to(snake_case	)
        model.eval()
        A_       :					Dict        =      model(snake_case	)
        self.parent.assertEqual(result.last_hidden_state.shape      ,   (self.batch_size, self.seq_length, self.hidden_size)	)



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]      ,   snake_case							:Optional[Any]      ,   snake_case							:Optional[int]      ,   snake_case							:int	):





        '''simple docstring'''




        A_       :					Optional[Any]        =      ViTForMaskedImageModeling(config=snake_case	)
        model.to(snake_case	)
        model.eval()
        A_       :					Any        =      model(snake_case	)
        self.parent.assertEqual(
            result.reconstruction.shape      ,   (self.batch_size, self.num_channels, self.image_size, self.image_size)	)

        # test greyscale images
        A_       :					Union[str, Any]        =      1
        A_       :					Optional[int]        =      ViTForMaskedImageModeling(snake_case	)
        model.to(snake_case	)
        model.eval()

        A_       :					Any        =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
        A_       :					List[Any]        =      model(snake_case	)
        self.parent.assertEqual(result.reconstruction.shape      ,   (self.batch_size, 1, self.image_size, self.image_size)	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]      ,   snake_case							:Tuple      ,   snake_case							:Optional[int]      ,   snake_case							:List[str]	):





        '''simple docstring'''




        A_       :					Optional[int]        =      self.type_sequence_label_size
        A_       :					Optional[Any]        =      ViTForImageClassification(snake_case	)
        model.to(snake_case	)
        model.eval()
        A_       :					Any        =      model(snake_case      ,   labels=snake_case	)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.type_sequence_label_size)	)

        # test greyscale images
        A_       :					int        =      1
        A_       :					List[str]        =      ViTForImageClassification(snake_case	)
        model.to(snake_case	)
        model.eval()

        A_       :					Any        =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
        A_       :					Dict        =      model(snake_case	)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.type_sequence_label_size)	)





     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        A_       :					Dict        =      self.prepare_config_and_inputs()
        (
            (
            A_
        )   ,    (
            A_
        )   ,    (
            A_
        )   ,    
        )       :					int        =      config_and_inputs
        A_       :					str        =      {"pixel_values": pixel_values}
        return config, inputs_dict




@require_torch
class        __magic_name__	(				lowerCamelCase__     ,					lowerCamelCase__     ,					unittest.TestCase				):





     """simple docstring"""



     __UpperCamelCase            =  (
         (
             ViTModel,
             ViTForImageClassification,
             ViTForMaskedImageModeling,
         )
         if is_torch_available()
         else ()
     )
     __UpperCamelCase            =  (
         {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
         if is_torch_available()
         else {}
     )
     __UpperCamelCase            =  True

     __UpperCamelCase            =  False
     __UpperCamelCase            =  False
     __UpperCamelCase            =  False



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        A_       :					List[Any]        =      ViTModelTester(self	)
        A_       :					List[Any]        =      ConfigTester(self      ,   config_class=snake_case      ,   has_text_modality=snake_case      ,   hidden_size=37	)



     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        self.config_tester.run_common_tests()



     @unittest.skip(reason="ViT does not use inputs_embeds"	)
     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        pass



     def     SCREAMING_SNAKE_CASE		(				self							:Tuple	):





        '''simple docstring'''




        A_   ,    A_       :					Optional[int]        =      self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           A_       :					List[Any]        =      model_class(snake_case	)
           self.assertIsInstance(model.get_input_embeddings()      ,   (nn.Module)	)
           A_       :					Optional[int]        =      model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(snake_case      ,   nn.Linear	)	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        A_   ,    A_       :					List[Any]        =      self.model_tester.prepare_config_and_inputs_for_common()

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

           A_       :					Dict        =      ["pixel_values"]
           self.assertListEqual(arg_names[:1]      ,   snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        A_       :					int        =      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        A_       :					int        =      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:Union[str, Any]	):





        '''simple docstring'''




        A_       :					Dict        =      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*snake_case	)





     @slow
     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           A_       :					Union[str, Any]        =      ViTModel.from_pretrained(snake_case	)
           self.assertIsNotNone(snake_case	)




def   __snake_case    (       )			->    Optional[Any]:
   A_       :					int        =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
   return image





@require_torch
@require_vision
class        __magic_name__	(				unittest.TestCase				):





     """simple docstring"""



     @cached_property
     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"	) if is_vision_available() else None



     @slow
     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        A_       :					Optional[Any]        =      ViTForImageClassification.from_pretrained("google/vit-base-patch16-224"	).to(snake_case	)

        A_       :					List[Any]        =      self.default_image_processor
        A_       :					List[str]        =      prepare_img()
        A_       :					Dict        =      image_processor(images=snake_case      ,   return_tensors="pt"	).to(snake_case	)

        # forward pass
        with torch.no_grad():
           A_       :					str        =      model(**snake_case	)

        # verify the logits
        A_       :					Optional[Any]        =      torch.Size((1, 1_000)	)
        self.assertEqual(outputs.logits.shape      ,   snake_case	)

        A_       :					Dict        =      torch.tensor([-0.2744, 0.8215, -0.0836]	).to(snake_case	)

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



     @slow
     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					Optional[Any]        =      ViTModel.from_pretrained("facebook/dino-vits8"	).to(snake_case	)

        A_       :					List[str]        =      ViTImageProcessor.from_pretrained("facebook/dino-vits8"      ,   size=480	)
        A_       :					Dict        =      prepare_img()
        A_       :					Dict        =      image_processor(images=snake_case      ,   return_tensors="pt"	)
        A_       :					List[Any]        =      inputs.pixel_values.to(snake_case	)

        # forward pass
        with torch.no_grad():
           A_       :					List[str]        =      model(snake_case      ,   interpolate_pos_encoding=snake_case	)

        # verify the logits
        A_       :					Tuple        =      torch.Size((1, 3_601, 384)	)
        self.assertEqual(outputs.last_hidden_state.shape      ,   snake_case	)

        A_       :					Tuple        =      torch.tensor(
            [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]	).to(snake_case	)

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





     @slow
     @require_accelerate
     @require_torch_gpu
     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					Optional[Any]        =      ViTModel.from_pretrained("facebook/dino-vits8"      ,   torch_dtype=torch.floataa      ,   device_map="auto"	)
        A_       :					Tuple        =      self.default_image_processor

        A_       :					Optional[Any]        =      prepare_img()
        A_       :					Optional[int]        =      image_processor(images=snake_case      ,   return_tensors="pt"	)
        A_       :					List[Any]        =      inputs.pixel_values.to(snake_case	)

        # forward pass to make sure inference works in fp16
        with torch.no_grad():
           A_       :					Any        =      model(snake_case	)







def   __snake_case    (       _lowerCAmelCase			:			list					,					_lowerCAmelCase			:			list					,					_lowerCAmelCase			:			int						)			->    int:
   if len(_lowerCAmelCase						) != len(_lowerCAmelCase						):
      raise ValueError("The length of profit and weight must be same."						)
   if max_weight <= 0:
      raise ValueError("max_weight must greater than zero."						)
   if any(p < 0 for p in profit						):
      raise ValueError("Profit can not be negative."						)
   if any(w < 0 for w in weight						):
      raise ValueError("Weight can not be negative."						)

   # List created to store profit gained for the 1kg in case of each weight
   # respectively.  Calculate and append profit/weight for each element.
   A_       :					Dict        =      [p / w for p, w in zip(_lowerCAmelCase					,					_lowerCAmelCase						)]

   # Creating a copy of the list and sorting profit/weight in ascending order
   A_       :					Optional[Any]        =      sorted(_lowerCAmelCase						)

   # declaring useful variables
   A_       :					List[Any]        =      len(_lowerCAmelCase						)
   A_       :					List[Any]        =      0
   A_       :					Any        =      0
   A_       :					List[Any]        =      0

   # loop till the total weight do not reach max limit e.g. 15 kg and till i<length
   while limit <= max_weight and i < length:
      # flag value for encountered greatest element in sorted_profit_by_weight
      A_       :					List[Any]        =      sorted_profit_by_weight[length - i - 1]
      A_       :					List[Any]        =      profit_by_weight.index(_lowerCAmelCase						)
      A_       :					List[Any]        =      -1

      # check if the weight encountered is less than the total weight
      # encountered before.
      if max_weight - limit >= weight[index]:
         limit += weight[index]
         # Adding profit gained for the given weight 1 ===
         # weight[index]/weight[index]
         gain += 1 * profit[index]
      else:
         # Since the weight encountered is greater than limit, therefore take the
         # required number of remaining kgs and calculate profit for it.
         # weight remaining / weight[index]
         gain += (max_weight - limit) / weight[index] * profit[index]
         break
      i += 1
   return gain


if __name__ == "__main__":
 print(
     '''Input profits, weights, and then max_weight (all positive ints) separated by '''
     '''spaces.'''
 )

 _lowerCAmelCase				:   int						       =						[int(x) for x in input('''Input profits separated by spaces: ''').split()]
 _lowerCAmelCase				:   Dict						       =						[int(x) for x in input('''Input weights separated by spaces: ''').split()]
 _lowerCAmelCase				:   Union[str, Any]						       =						int(input('''Max weight allowed: '''))

 # Function Call
 calc_profit(profit, weight, max_weight)
