





"""simple docstring"""
import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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 transformers import UperNetForSemanticSegmentation
       from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor







class       a							:



 def __init__(     self				,       _snake_case				,       _snake_case=13				,       _snake_case=32				,       _snake_case=3				,       _snake_case=4				,       _snake_case=[10, 20, 30, 40]				,       _snake_case=[2, 2, 3, 2]				,       _snake_case=True				,       _snake_case=True				,       _snake_case=37				,       _snake_case="gelu"				,       _snake_case=10				,       _snake_case=0.02				,       _snake_case=["stage2", "stage3", "stage4"]				,       _snake_case=3				,       _snake_case=None				,       ):







  """simple docstring"""






  lowerCAmelCase    				= parent
  lowerCAmelCase    				= batch_size
  lowerCAmelCase    				= image_size
  lowerCAmelCase    				= num_channels
  lowerCAmelCase    				= num_stages
  lowerCAmelCase    				= hidden_sizes
  lowerCAmelCase    				= depths
  lowerCAmelCase    				= is_training
  lowerCAmelCase    				= use_labels
  lowerCAmelCase    				= intermediate_size
  lowerCAmelCase    				= hidden_act
  lowerCAmelCase    				= type_sequence_label_size
  lowerCAmelCase    				= initializer_range
  lowerCAmelCase    				= out_features
  lowerCAmelCase    				= num_labels
  lowerCAmelCase    				= scope
  lowerCAmelCase    				= num_stages



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

  lowerCAmelCase    				= None
  if self.use_labels:
   lowerCAmelCase    				= ids_tensor([self.batch_size]				,       self.type_sequence_label_size     )

  lowerCAmelCase    				= self.get_config()

  return config, pixel_values, labels



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return ConvNextConfig(
      num_channels=self.num_channels				,       num_stages=self.num_stages				,       hidden_sizes=self.hidden_sizes				,       depths=self.depths				,       is_training=self.is_training				,       intermediate_size=self.intermediate_size				,       hidden_act=self.hidden_act				,       out_features=self.out_features				,       )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return UperNetConfig(
      backbone_config=self.get_backbone_config()				,       hidden_size=5_12				,       pool_scales=[1, 2, 3, 6]				,       use_auxiliary_head=_snake_case				,       auxiliary_loss_weight=0.4				,       auxiliary_in_channels=40				,       auxiliary_channels=2_56				,       auxiliary_num_convs=1				,       auxiliary_concat_input=_snake_case				,       loss_ignore_index=2_55				,       num_labels=self.num_labels				,       )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= UperNetForSemanticSegmentation(config=_snake_case     )
  model.to(_snake_case     )
  model.eval()
  lowerCAmelCase    				= model(_snake_case     )
  self.parent.assertEqual(
      result.logits.shape				,       (self.batch_size, self.num_labels, self.image_size, self.image_size)     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase
  )				,(
      lowerCAmelCase
  )				,(
      lowerCAmelCase
  )				,
  )    				= config_and_inputs
  lowerCAmelCase    				= {'pixel_values': pixel_values}
  return config, inputs_dict







@require_torch
class       a							(   a__   , a__   , unittest.TestCase  ):
 snake_case__             =       (UperNetForSemanticSegmentation,) if is_torch_available() else ()
 snake_case__             =       {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
 snake_case__             =       False
 snake_case__             =       False
 snake_case__             =       False
 snake_case__             =       False
 snake_case__             =       False
 snake_case__             =       False



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= UperNetModelTester(self     )
  lowerCAmelCase    				= ConfigTester(self				,       config_class=_snake_case				,       has_text_modality=_snake_case				,       hidden_size=37     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self.create_and_test_config_common_properties()
  self.config_tester.create_and_test_config_to_json_string()
  self.config_tester.create_and_test_config_to_json_file()
  self.config_tester.create_and_test_config_from_and_save_pretrained()
  self.config_tester.create_and_test_config_with_num_labels()
  self.config_tester.check_config_can_be_init_without_params()
  self.config_tester.check_config_arguments_init()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs_for_common()

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

   lowerCAmelCase    				= ['pixel_values']
   self.assertListEqual(arg_names[:1]				,       _snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_semantic_segmentation(*_snake_case     )



 @unittest.skip(reason='UperNet does not use inputs_embeds'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @unittest.skip(reason='UperNet does not support input and output embeddings'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @unittest.skip(reason='UperNet does not have a base model'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @unittest.skip(reason='UperNet does not have a base model'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @require_torch_multi_gpu
 @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  def check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case     ):
   lowerCAmelCase    				= model_class(_snake_case     )
   model.to(_snake_case     )
   model.eval()

   with torch.no_grad():
    lowerCAmelCase    				= model(**self._prepare_for_class(_snake_case				,       _snake_case     )     )

   lowerCAmelCase    				= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

   lowerCAmelCase    				= self.model_tester.num_stages
   self.assertEqual(len(_snake_case     )				,       expected_num_stages + 1     )

   # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
   self.assertListEqual(
       list(hidden_states[0].shape[-2:]     )				,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4]				,       )

  lowerCAmelCase				,lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   lowerCAmelCase    				= True
   check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case     )

   # check that output_hidden_states also work using config
   del inputs_dict["output_hidden_states"]
   lowerCAmelCase    				= True

   check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs_for_common()

  lowerCAmelCase    				= _config_zero_init(_snake_case     )
  lowerCAmelCase    				= _config_zero_init(configs_no_init.backbone_config     )
  for model_class in self.all_model_classes:
   lowerCAmelCase    				= model_class(config=_snake_case     )
   for name, param in model.named_parameters():
    if param.requires_grad:
     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(reason='UperNet does not have tied weights'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase    				= UperNetForSemanticSegmentation.from_pretrained(_snake_case     )
   self.assertIsNotNone(_snake_case     )


def 		_SCREAMING_SNAKE_CASE			():
 lowerCAmelCase    				= hf_hub_download(
     repo_id='hf-internal-testing/fixtures_ade20k'  ,     repo_type='dataset'  ,     filename='ADE_val_00000001.jpg'			)
 lowerCAmelCase    				= Image.open(_UpperCAmelCase			).convert('RGB'			)
 return image







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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'     )
  lowerCAmelCase    				= UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'     ).to(_snake_case     )

  lowerCAmelCase    				= prepare_img()
  lowerCAmelCase    				= processor(images=_snake_case				,       return_tensors='pt'     ).to(_snake_case     )

  with torch.no_grad():
   lowerCAmelCase    				= model(**_snake_case     )

  lowerCAmelCase    				= torch.Size((1, model.config.num_labels, 5_12, 5_12)     )
  self.assertEqual(outputs.logits.shape				,       _snake_case     )

  lowerCAmelCase    				= torch.tensor(
      [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]]     ).to(_snake_case     )
  self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,       _snake_case				,       atol=1E-4     )     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'     )
  lowerCAmelCase    				= UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'     ).to(_snake_case     )

  lowerCAmelCase    				= prepare_img()
  lowerCAmelCase    				= processor(images=_snake_case				,       return_tensors='pt'     ).to(_snake_case     )

  with torch.no_grad():
   lowerCAmelCase    				= model(**_snake_case     )

  lowerCAmelCase    				= torch.Size((1, model.config.num_labels, 5_12, 5_12)     )
  self.assertEqual(outputs.logits.shape				,       _snake_case     )

  lowerCAmelCase    				= torch.tensor(
      [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]]     ).to(_snake_case     )
  self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,       _snake_case				,       atol=1E-4     )     )












"""simple docstring"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVR
from statsmodels.tsa.statespace.sarimax import SARIMAX

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list			):
 lowerCAmelCase    				= np.array([[1, item, train_mtch[i]] for i, item in enumerate(_UpperCAmelCase			)]			)
 lowerCAmelCase    				= np.array(_UpperCAmelCase			)
 lowerCAmelCase    				= np.dot(np.dot(np.linalg.inv(np.dot(x.transpose()  ,     _UpperCAmelCase			)			)  ,     x.transpose()			)  ,     _UpperCAmelCase			)
 return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]			)

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list			):
 lowerCAmelCase    				= (1, 2, 1)
 lowerCAmelCase    				= (1, 1, 0, 7)
 lowerCAmelCase    				= SARIMAX(
     _UpperCAmelCase  ,     exog=_UpperCAmelCase  ,     order=_UpperCAmelCase  ,     seasonal_order=_UpperCAmelCase			)
 lowerCAmelCase    				= model.fit(disp=_UpperCAmelCase  ,     maxiter=600  ,     method='nm'			)
 lowerCAmelCase    				= model_fit.predict(1  ,     len(_UpperCAmelCase			)  ,     exog=[test_match]			)
 return result[0]

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    list			):
 lowerCAmelCase    				= SVR(kernel='rbf'  ,     C=1  ,     gamma=0.1  ,     epsilon=0.1			)
 regressor.fit(_UpperCAmelCase  ,     _UpperCAmelCase			)
 lowerCAmelCase    				= regressor.predict(_UpperCAmelCase			)
 return y_pred[0]

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    list			):
 train_user.sort()
 lowerCAmelCase    				= np.percentile(_UpperCAmelCase  ,     25			)
 lowerCAmelCase    				= np.percentile(_UpperCAmelCase  ,     75			)
 lowerCAmelCase    				= qa - qa
 lowerCAmelCase    				= qa - (iqr * 0.1)
 return low_lim

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    list  ,     _UpperCAmelCase					:    float			):
 lowerCAmelCase    				= 0
 lowerCAmelCase    				= 0
 for i in list_vote:
  if i > actual_result:
   lowerCAmelCase    				= not_safe + 1
  else:
   if abs(abs(_UpperCAmelCase			) - abs(_UpperCAmelCase			)			) <= 0.1:
    safe += 1
   else:
    not_safe += 1
 return safe > not_safe


if __name__ == "__main__":
       # data_input_df = pd.read_csv("ex_data.csv", header=None)
       __UpperCamelCase     :						Optional[Any]						       =  [[1_8231, 0.0, 1], [2_2621, 1.0, 2], [1_5675, 0.0, 3], [2_3583, 1.0, 4]]
       __UpperCamelCase     :						Any						       =  pd.DataFrame(
           data_input, columns=['''total_user''', '''total_even''', '''days''']
       )
       __UpperCamelCase     :						Dict						       =  Normalizer().fit_transform(data_input_df.values)
       # split data
       __UpperCamelCase     :						Dict						       =  normalize_df[:, 2].tolist()
       __UpperCamelCase     :						Union[str, Any]						       =  normalize_df[:, 0].tolist()
       __UpperCamelCase     :						List[str]						       =  normalize_df[:, 1].tolist()

       # for svr (input variable = total date and total match)
       __UpperCamelCase     :						Optional[int]						       =  normalize_df[:, [1, 2]].tolist()
       __UpperCamelCase     :						Tuple						       =  x[: len(x) - 1]
       __UpperCamelCase     :						Any						       =  x[len(x) - 1 :]

       # for linear regression & sarimax
       __UpperCamelCase     :						str						       =  total_date[: len(total_date) - 1]
       __UpperCamelCase     :						Union[str, Any]						       =  total_user[: len(total_user) - 1]
       __UpperCamelCase     :						List[Any]						       =  total_match[: len(total_match) - 1]

       __UpperCamelCase     :						Optional[Any]						       =  total_date[len(total_date) - 1 :]
       __UpperCamelCase     :						str						       =  total_user[len(total_user) - 1 :]
       __UpperCamelCase     :						str						       =  total_match[len(total_match) - 1 :]

       # voting system with forecasting
       __UpperCamelCase     :						Any						       =  [
           linear_regression_prediction(
               trn_date, trn_user, trn_match, tst_date, tst_match
           ),
           sarimax_predictor(trn_user, trn_match, tst_match),
           support_vector_regressor(x_train, x_test, trn_user),
       ]

       # check the safety of today's data
       __UpperCamelCase     :						List[str]						       =  '''''' if data_safety_checker(res_vote, tst_user) else '''not '''
       print('''Today\'s data is {not_str}safe.''')





