



import argparse
import os
import re

import packaging.version


UpperCAmelCase_									=     "examples/"
UpperCAmelCase_									=     {
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
UpperCAmelCase_									=     {
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
UpperCAmelCase_									=     "README.md"
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Optional[Any]     ,				_SCREAMING_SNAKE_CASE   :	int     ,				_SCREAMING_SNAKE_CASE   :	Union[str, Any]				)->str:
      with open(UpperCAmelCase__     ,				'''r'''     ,				encoding='''utf-8'''     ,				newline='''\n'''				) as f:
            _lowerCAmelCase 			=  f.read()
      _lowerCAmelCase			,   _lowerCAmelCase 			=  REPLACE_PATTERNS[pattern]
      _lowerCAmelCase 			=  replace.replace('''VERSION'''     ,				UpperCAmelCase__				)
      _lowerCAmelCase 			=  re_pattern.sub(UpperCAmelCase__     ,				UpperCAmelCase__				)
      with open(UpperCAmelCase__     ,				'''w'''     ,				encoding='''utf-8'''     ,				newline='''\n'''				) as f:
            f.write(UpperCAmelCase__				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Tuple				)->List[Any]:
      for folder, directories, fnames in os.walk(UpperCAmelCase__				):
            # Removing some of the folders with non-actively maintained examples from the walk
            if "research_projects" in directories:
                  directories.remove('''research_projects'''				)
            if "legacy" in directories:
                  directories.remove('''legacy'''				)
            for fname in fnames:
                  if fname.endswith('''.py'''				):
                        update_version_in_file(os.path.join(UpperCAmelCase__     ,				UpperCAmelCase__				)     ,				UpperCAmelCase__     ,				pattern='''examples'''				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	List[str]     ,				_SCREAMING_SNAKE_CASE   :	List[Any]=False				)->List[str]:
      for pattern, fname in REPLACE_FILES.items():
            update_version_in_file(UpperCAmelCase__     ,				UpperCAmelCase__     ,				UpperCAmelCase__				)
      if not patch:
            update_version_in_examples(UpperCAmelCase__				)
def 							UpperCAmelCase__		(				)->int:
      _lowerCAmelCase 			=  '''🤗 Transformers currently provides the following architectures'''
      _lowerCAmelCase 			=  '''1. Want to contribute a new model?'''
      with open(UpperCAmelCase__     ,				'''r'''     ,				encoding='''utf-8'''     ,				newline='''\n'''				) as f:
            _lowerCAmelCase 			=  f.readlines()

      # Find the start of the list.
      _lowerCAmelCase 			=  0
      while not lines[start_index].startswith(_start_prompt				):
            start_index += 1
      start_index += 1

      _lowerCAmelCase 			=  start_index
      # Update the lines in the model list.
      while not lines[index].startswith(_end_prompt				):
            if lines[index].startswith('''1.'''				):
                  _lowerCAmelCase 			=  lines[index].replace(
                      '''https://huggingface.co/docs/transformers/main/model_doc'''     ,				'''https://huggingface.co/docs/transformers/model_doc'''     ,				)
            index += 1

      with open(UpperCAmelCase__     ,				'''w'''     ,				encoding='''utf-8'''     ,				newline='''\n'''				) as f:
            f.writelines(UpperCAmelCase__				)
def 							UpperCAmelCase__		(				)->Union[str, Any]:
      with open(REPLACE_FILES['''init''']     ,				'''r'''				) as f:
            _lowerCAmelCase 			=  f.read()
      _lowerCAmelCase 			=  REPLACE_PATTERNS['''init'''][0].search(UpperCAmelCase__				).groups()[0]
      return packaging.version.parse(UpperCAmelCase__				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Dict=False				)->Tuple:
      _lowerCAmelCase 			=  get_version()
      if patch and default_version.is_devrelease:
            raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!'''				)
      if default_version.is_devrelease:
            _lowerCAmelCase 			=  default_version.base_version
      elif patch:
            _lowerCAmelCase 			=  f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
      else:
            _lowerCAmelCase 			=  f'''{default_version.major}.{default_version.minor + 1}.0'''

      # Now let's ask nicely if that's the right one.
      _lowerCAmelCase 			=  input(f'''Which version are you releasing? [{default_version}]'''				)
      if len(UpperCAmelCase__				) == 0:
            _lowerCAmelCase 			=  default_version

      print(f'''Updating version to {version}.'''				)
      global_version_update(UpperCAmelCase__     ,				patch=UpperCAmelCase__				)
      if not patch:
            print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''				)
            clean_main_ref_in_model_list()
def 							UpperCAmelCase__		(				)->Dict:
      _lowerCAmelCase 			=  get_version()
      _lowerCAmelCase 			=  f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
      _lowerCAmelCase 			=  current_version.base_version

      # Check with the user we got that right.
      _lowerCAmelCase 			=  input(f'''Which version are we developing now? [{dev_version}]'''				)
      if len(UpperCAmelCase__				) == 0:
            _lowerCAmelCase 			=  dev_version

      print(f'''Updating version to {version}.'''				)
      global_version_update(UpperCAmelCase__				)
      print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''				)
      clean_main_ref_in_model_list()


if __name__ == "__main__":
    UpperCAmelCase_									=     argparse.ArgumentParser()
    parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
    parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
    UpperCAmelCase_									=     parser.parse_args()
    if not args.post_release:
        pre_release_work(patch=args.patch)
    elif args.patch:
        print("Nothing to do after a patch :-)")
    else:
        post_release_work()




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_video_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import VivitImageProcessor





class 		UpperCAmelCase						(						unittest.TestCase				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase=7       ,     _lowerCAmelCase=3       ,     _lowerCAmelCase=10       ,     _lowerCAmelCase=18       ,     _lowerCAmelCase=30       ,     _lowerCAmelCase=400       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=None       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=[0.5, 0.5, 0.5]       ,     _lowerCAmelCase=[0.5, 0.5, 0.5]       ,     _lowerCAmelCase=None       ,     ):
         _lowerCAmelCase 			=  size if size is not None else {'''shortest_edge''': 18}
         _lowerCAmelCase 			=  crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

         _lowerCAmelCase 			=  parent
         _lowerCAmelCase 			=  batch_size
         _lowerCAmelCase 			=  num_channels
         _lowerCAmelCase 			=  num_frames
         _lowerCAmelCase 			=  image_size
         _lowerCAmelCase 			=  min_resolution
         _lowerCAmelCase 			=  max_resolution
         _lowerCAmelCase 			=  do_resize
         _lowerCAmelCase 			=  size
         _lowerCAmelCase 			=  do_normalize
         _lowerCAmelCase 			=  image_mean
         _lowerCAmelCase 			=  image_std
         _lowerCAmelCase 			=  crop_size





   def 	__lowerCAmelCase							(	self			):
         return {
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_normalize": self.do_normalize,
             "do_resize": self.do_resize,
             "size": self.size,
             "crop_size": self.crop_size,
         }






@require_torch
@require_vision
class 		UpperCAmelCase						(						snake_case_       ,unittest.TestCase				):
   SCREAMING_SNAKE_CASE__							=     VivitImageProcessor if is_vision_available() else None





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  VivitImageProcessingTester(self			)





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.image_processor_tester.prepare_image_processor_dict()





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.image_processing_class(**self.image_processor_dict			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''image_mean'''			)			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''image_std'''			)			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''do_normalize'''			)			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''do_resize'''			)			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''do_center_crop'''			)			)
         self.assertTrue(hasattr(_lowerCAmelCase       ,     '''size'''			)			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.image_processing_class.from_dict(self.image_processor_dict			)
         self.assertEqual(image_processor.size       ,     {'''shortest_edge''': 18}			)
         self.assertEqual(image_processor.crop_size       ,     {'''height''': 18, '''width''': 18}			)

         _lowerCAmelCase 			=  self.image_processing_class.from_dict(self.image_processor_dict       ,     size=42       ,     crop_size=84			)
         self.assertEqual(image_processor.size       ,     {'''shortest_edge''': 42}			)
         self.assertEqual(image_processor.crop_size       ,     {'''height''': 84, '''width''': 84}			)





   def 	__lowerCAmelCase							(	self			):
         # Initialize image_processing
         _lowerCAmelCase 			=  self.image_processing_class(**self.image_processor_dict			)
         # create random PIL videos
         _lowerCAmelCase 			=  prepare_video_inputs(self.image_processor_tester       ,     equal_resolution=_lowerCAmelCase			)
         for video in video_inputs:
               self.assertIsInstance(_lowerCAmelCase       ,     _lowerCAmelCase			)
               self.assertIsInstance(video[0]       ,     Image.Image			)

         # Test not batched input
         _lowerCAmelCase 			=  image_processing(video_inputs[0]       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 1,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )

         # Test batched
         _lowerCAmelCase 			=  image_processing(_lowerCAmelCase       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )





   def 	__lowerCAmelCase							(	self			):
         # Initialize image_processing
         _lowerCAmelCase 			=  self.image_processing_class(**self.image_processor_dict			)
         # create random numpy tensors
         _lowerCAmelCase 			=  prepare_video_inputs(self.image_processor_tester       ,     equal_resolution=_lowerCAmelCase       ,     numpify=_lowerCAmelCase			)
         for video in video_inputs:
               self.assertIsInstance(_lowerCAmelCase       ,     _lowerCAmelCase			)
               self.assertIsInstance(video[0]       ,     np.ndarray			)

         # Test not batched input
         _lowerCAmelCase 			=  image_processing(video_inputs[0]       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 1,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )

         # Test batched
         _lowerCAmelCase 			=  image_processing(_lowerCAmelCase       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )





   def 	__lowerCAmelCase							(	self			):
         # Initialize image_processing
         _lowerCAmelCase 			=  self.image_processing_class(**self.image_processor_dict			)
         # create random PyTorch tensors
         _lowerCAmelCase 			=  prepare_video_inputs(self.image_processor_tester       ,     equal_resolution=_lowerCAmelCase       ,     torchify=_lowerCAmelCase			)
         for video in video_inputs:
               self.assertIsInstance(_lowerCAmelCase       ,     _lowerCAmelCase			)
               self.assertIsInstance(video[0]       ,     torch.Tensor			)

         # Test not batched input
         _lowerCAmelCase 			=  image_processing(video_inputs[0]       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 1,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )

         # Test batched
         _lowerCAmelCase 			=  image_processing(_lowerCAmelCase       ,     return_tensors='''pt'''			).pixel_values
         self.assertEqual(
             encoded_videos.shape       ,     (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_frames,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )       ,     )