




import json
import logging
import os
import socket

import git
import numpy as np
import torch


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d -  %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
a_   		=     logging.getLogger(__name__)




def 					__SCREAMING_SNAKE_CASE   (  lowercase_      )       ->	Dict:

    """simple docstring"""


    __UpperCamelCase  		=						git.Repo(search_parent_directories=lowercase_      )
    __UpperCamelCase  		=						{
        '''repo_id''': str(lowercase_      ),
        '''repo_sha''': str(repo.head.object.hexsha      ),
        '''repo_branch''': str(repo.active_branch      ),
    }

    with open(os.path.join(lowercase_					,     '''git_log.json'''      )					,     '''w'''      ) as f:
        json.dump(lowercase_					,     lowercase_					,     indent=4      )




def 					__SCREAMING_SNAKE_CASE   (  lowercase_      )       ->	Optional[int]:

    """simple docstring"""


    if params.n_gpu <= 0:
        __UpperCamelCase  		=						0
        __UpperCamelCase  		=						-1
        __UpperCamelCase  		=						True
        __UpperCamelCase  		=						False
        return

    assert torch.cuda.is_available()

    logger.info('''Initializing GPUs'''      )
    if params.n_gpu > 1:
        assert params.local_rank != -1

        __UpperCamelCase  		=						int(os.environ['''WORLD_SIZE''']      )
        __UpperCamelCase  		=						int(os.environ['''N_GPU_NODE''']      )
        __UpperCamelCase  		=						int(os.environ['''RANK''']      )

        # number of nodes / node ID
        __UpperCamelCase  		=						params.world_size // params.n_gpu_per_node
        __UpperCamelCase  		=						params.global_rank // params.n_gpu_per_node
        __UpperCamelCase  		=						True

        assert params.n_nodes == int(os.environ['''N_NODES''']      )
        assert params.node_id == int(os.environ['''NODE_RANK''']      )

    # local job (single GPU)
    else:
        assert params.local_rank == -1

        __UpperCamelCase  		=						1
        __UpperCamelCase  		=						0
        __UpperCamelCase  		=						0
        __UpperCamelCase  		=						0
        __UpperCamelCase  		=						1
        __UpperCamelCase  		=						1
        __UpperCamelCase  		=						False

    # sanity checks
    assert params.n_nodes >= 1
    assert 0 <= params.node_id < params.n_nodes
    assert 0 <= params.local_rank <= params.global_rank < params.world_size
    assert params.world_size == params.n_nodes * params.n_gpu_per_node

    # define whether this is the master process / if we are in multi-node distributed mode
    __UpperCamelCase  		=						params.node_id == 0 and params.local_rank == 0
    __UpperCamelCase  		=						params.n_nodes > 1

    # summary
    __UpperCamelCase  		=						F"--- Global rank: {params.global_rank} - "
    logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes      )
    logger.info(PREFIX + '''Node ID        : %i''' % params.node_id      )
    logger.info(PREFIX + '''Local rank     : %i''' % params.local_rank      )
    logger.info(PREFIX + '''World size     : %i''' % params.world_size      )
    logger.info(PREFIX + '''GPUs per node  : %i''' % params.n_gpu_per_node      )
    logger.info(PREFIX + '''Master         : %s''' % str(params.is_master      )      )
    logger.info(PREFIX + '''Multi-node     : %s''' % str(params.multi_node      )      )
    logger.info(PREFIX + '''Multi-GPU      : %s''' % str(params.multi_gpu      )      )
    logger.info(PREFIX + '''Hostname       : %s''' % socket.gethostname()      )

    # set GPU device
    torch.cuda.set_device(params.local_rank      )

    # initialize multi-GPU
    if params.multi_gpu:
        logger.info('''Initializing PyTorch distributed'''      )
        torch.distributed.init_process_group(
            init_method='''env://'''					,     backend='''nccl'''					,     )




def 					__SCREAMING_SNAKE_CASE   (  lowercase_      )       ->	Optional[int]:

    """simple docstring"""


    np.random.seed(args.seed      )
    torch.manual_seed(args.seed      )
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed      )












import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding

class  _lowerCamelCase						(			_SCREAMING_SNAKE_CASE   ):

      """simple docstring"""

      lowerCAmelCase__			: Dict    =					["image_processor", "tokenizer"]
      lowerCAmelCase__			: List[Any]    =					"ViTImageProcessor"
      lowerCAmelCase__			: Optional[int]    =					("CLIPTokenizer", "CLIPTokenizerFast")







      def __init__(     self					: Any ,       snake_case					: Any=None ,       snake_case					: Dict=None ,       **snake_case					: Tuple				):
          __UpperCamelCase  		=						None
          if "feature_extractor" in kwargs:
              warnings.warn(
                  '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                  ''' instead.''' ,       snake_case ,       )
              __UpperCamelCase  		=						kwargs.pop('''feature_extractor'''				)

          __UpperCamelCase  		=						image_processor if image_processor is not None else feature_extractor
          if image_processor is None:
              raise ValueError('''You need to specify an `image_processor`.'''				)
          if tokenizer is None:
              raise ValueError('''You need to specify a `tokenizer`.'''				)

          super().__init__(snake_case ,       snake_case				)







      def __call__(     self					: Dict ,       snake_case					: Union[str, Any]=None ,       snake_case					: Tuple=None ,       snake_case					: Any=None ,       snake_case					: Any=None ,       **snake_case					: Optional[int]				):
          if text is None and visual_prompt is None and images is None:
              raise ValueError('''You have to specify either text, visual prompt or images.'''				)

          if text is not None and visual_prompt is not None:
              raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.'''				)

          if text is not None:
              __UpperCamelCase  		=						self.tokenizer(snake_case ,       return_tensors=snake_case ,       **snake_case				)

          if visual_prompt is not None:
              __UpperCamelCase  		=						self.image_processor(snake_case ,       return_tensors=snake_case ,       **snake_case				)

          if images is not None:
              __UpperCamelCase  		=						self.image_processor(snake_case ,       return_tensors=snake_case ,       **snake_case				)

          if visual_prompt is not None and images is not None:
              __UpperCamelCase  		=						{
                  '''pixel_values''': image_features.pixel_values,
                  '''conditional_pixel_values''': prompt_features.pixel_values,
              }
              return encoding
          elif text is not None and images is not None:
              __UpperCamelCase  		=						image_features.pixel_values
              return encoding
          elif text is not None:
              return encoding
          elif visual_prompt is not None:
              __UpperCamelCase  		=						{
                  '''conditional_pixel_values''': prompt_features.pixel_values,
              }
              return encoding
          else:
              return BatchEncoding(data=dict(**snake_case				) ,       tensor_type=snake_case				)







      def       snake_case	(     self					: Optional[int] ,       *snake_case					: Tuple ,       **snake_case					: Any				):
          return self.tokenizer.batch_decode(*snake_case ,       **snake_case				)







      def       snake_case	(     self					: Optional[int] ,       *snake_case					: Dict ,       **snake_case					: List[str]				):
          return self.tokenizer.decode(*snake_case ,       **snake_case				)







      @property
      def       snake_case	(     self					: Optional[Any]				):
          warnings.warn(
              '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,       snake_case ,       )
          return self.image_processor_class







      @property
      def       snake_case	(     self					: Optional[Any]				):
          warnings.warn(
              '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,       snake_case ,       )
          return self.image_processor






