




"""simple docstring"""



from importlib import import_module

from .logging import get_logger


SCREAMING_SNAKE_CASE    =	get_logger(__name__)




class      UpperCAmelCase_  :




    def __init__(   self						:	List[str]     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	List[Any]=None				)				->							Dict:




     '''simple docstring'''

     A__	=    attrs or []
     if module is not None:
      for key in module.__dict__:
       if key in attrs or not key.startswith("__"				):
        setattr(self     ,			snake_case_     ,			getattr(snake_case_     ,			snake_case_				)				)
     A__	=    module._original_module if isinstance(snake_case_     ,			_PatchedModuleObj				) else module






class      UpperCAmelCase_  :
    lowercase__						 =				[]




    def __init__(   self						:	int     ,			snake_case_						:	List[Any]     ,			snake_case_						:	str     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Union[str, Any]=None				)				->							Dict:




     '''simple docstring'''

     A__	=    obj
     A__	=    target
     A__	=    new
     A__	=    target.split("."				)[0]
     A__	=    {}
     A__	=    attrs or []




    def __enter__(   self						:	Optional[int]				)				->							str:




     '''simple docstring'''

     *A__,				A__	=    self.target.split("."				)

     # Patch modules:
     # it's used to patch attributes of submodules like "os.path.join";
     # in this case we need to patch "os" and "os.path"

     for i in range(len(snake_case_				)				):
      try:
       A__	=    import_module(".".join(submodules[: i + 1]				)				)
      except ModuleNotFoundError:
       continue
      # We iterate over all the globals in self.obj in case we find "os" or "os.path"
      for attr in self.obj.__dir__():
       A__	=    getattr(self.obj     ,			snake_case_				)
       # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
       # This allows to patch renamed modules like "from os import path as ospath".
       if obj_attr is submodule or (
           (isinstance(snake_case_     ,			_PatchedModuleObj				) and obj_attr._original_module is submodule)
       ):
        A__	=    obj_attr
        # patch at top level
        setattr(self.obj     ,			snake_case_     ,			_PatchedModuleObj(snake_case_     ,			attrs=self.attrs				)				)
        A__	=    getattr(self.obj     ,			snake_case_				)
        # construct lower levels patches
        for key in submodules[i + 1 :]:
         setattr(snake_case_     ,			snake_case_     ,			_PatchedModuleObj(getattr(snake_case_     ,			snake_case_     ,			snake_case_				)     ,			attrs=self.attrs				)				)
         A__	=    getattr(snake_case_     ,			snake_case_				)
        # finally set the target attribute
        setattr(snake_case_     ,			snake_case_     ,			self.new				)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

     if submodules:  # if it's an attribute of a submodule like "os.path.join"
      try:
       A__	=    getattr(import_module(".".join(snake_case_				)				)     ,			snake_case_				)
      except (AttributeError, ModuleNotFoundError):
       return
      # We iterate over all the globals in self.obj in case we find "os.path.join"
      for attr in self.obj.__dir__():
       # We don't check for the name of the global, but rather if its value *is* "os.path.join".
       # This allows to patch renamed attributes like "from os.path import join as pjoin".
       if getattr(self.obj     ,			snake_case_				) is attr_value:
        A__	=    getattr(self.obj     ,			snake_case_				)
        setattr(self.obj     ,			snake_case_     ,			self.new				)
     elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
      A__	=    globals()["__builtins__"][target_attr]
      setattr(self.obj     ,			snake_case_     ,			self.new				)
     else:
      raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""				)




    def __exit__(   self						:	Any     ,			*snake_case_						:	Tuple				)				->							Union[str, Any]:




     '''simple docstring'''

     for attr in list(self.original				):
      setattr(self.obj     ,			snake_case_     ,			self.original.pop(snake_case_				)				)




    def 							__magic_name__							(   self						:	Tuple				)				->							Union[str, Any]:




     '''simple docstring'''

     self.__enter__()
     self._active_patches.append(self				)




    def 							__magic_name__							(   self						:	Tuple				)				->							Optional[Any]:




     '''simple docstring'''

     try:
      self._active_patches.remove(self				)
     except ValueError:
      # If the patch hasn't been started this will fail
      return None

     return self.__exit__()











"""simple docstring"""



import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import is_speech_available, is_vision_available
from transformers.testing_utils import require_torch


if is_vision_available():
      from transformers import TvltImageProcessor

if is_speech_available():
      from transformers import TvltFeatureExtractor

from transformers import TvltProcessor




@require_torch
class      UpperCAmelCase_  (						unittest.TestCase							):




    def 							__magic_name__							(   self						:	str				)				->							Dict:




     '''simple docstring'''

     A__	=    "ZinengTang/tvlt-base"
     A__	=    tempfile.mkdtemp()




    def 							__magic_name__							(   self						:	int     ,			**snake_case_						:	Dict				)				->							Union[str, Any]:




     '''simple docstring'''

     return TvltImageProcessor.from_pretrained(self.checkpoint     ,			**snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]     ,			**snake_case_						:	str				)				->							List[str]:




     '''simple docstring'''

     return TvltFeatureExtractor.from_pretrained(self.checkpoint     ,			**snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]				)				->							str:




     '''simple docstring'''

     shutil.rmtree(self.tmpdirname				)




    def 							__magic_name__							(   self						:	Tuple				)				->							Any:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)
     processor.save_pretrained(self.tmpdirname				)
     A__	=    TvltProcessor.from_pretrained(self.tmpdirname				)

     self.assertIsInstance(processor.feature_extractor     ,			snake_case_				)
     self.assertIsInstance(processor.image_processor     ,			snake_case_				)




    def 							__magic_name__							(   self						:	Optional[Any]				)				->							Union[str, Any]:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([12_000]				)

     A__	=    feature_extractor(snake_case_     ,			return_tensors="np"				)
     A__	=    processor(audio=snake_case_     ,			return_tensors="np"				)

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




    def 							__magic_name__							(   self						:	Tuple				)				->							Tuple:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([3, 224, 224]				)

     A__	=    image_processor(snake_case_     ,			return_tensors="np"				)
     A__	=    processor(images=snake_case_     ,			return_tensors="np"				)

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




    def 							__magic_name__							(   self						:	Tuple				)				->							Optional[int]:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([12_000]				)
     A__	=    np.ones([3, 224, 224]				)

     A__	=    processor(audio=snake_case_     ,			images=snake_case_				)

     self.assertListEqual(list(inputs.keys()				)     ,			["audio_values", "audio_mask", "pixel_values", "pixel_mask"]				)

     # test if it raises when no input is passed
     with pytest.raises(snake_case_				):
      processor()




    def 							__magic_name__							(   self						:	Optional[Any]				)				->							Tuple:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     self.assertListEqual(
         processor.model_input_names     ,			image_processor.model_input_names + feature_extractor.model_input_names     ,			msg="`processor` and `image_processor`+`feature_extractor` model input names do not match"     ,			)





