'''simple docstring'''





# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


SCREAMING_SNAKE_CASE__		:					List[str]						=					"Run commands across TPU VMs for initial setup before running `accelerate launch`."







def     _a				(      lowercase__  :			Tuple=None ):







     '''simple docstring'''


     if subparsers is not None:
          SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		subparsers.add_parser('tpu-config'     ,  description=_description )
     else:
          SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		argparse.ArgumentParser('Accelerate tpu-config command'     ,  description=_description )
     # Core arguments
     SCREAMING_SNAKE_CASE__				:				Tuple			=		parser.add_argument_group(
         'Config Arguments'     ,  'Arguments that can be configured through `accelerate config`.' )
     config_args.add_argument(
         '--config_file'     ,  type=snake_case__     ,  default=snake_case__     ,  help='Path to the config file to use for accelerate.'     ,  )
     config_args.add_argument(
         '--tpu_name'     ,  default=snake_case__     ,  help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.'     ,  )
     config_args.add_argument(
         '--tpu_zone'     ,  default=snake_case__     ,  help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.'     ,  )
     SCREAMING_SNAKE_CASE__				:				List[str]			=		parser.add_argument_group('TPU Arguments'     ,  'Arguments for options ran inside the TPU.' )
     pod_args.add_argument(
         '--use_alpha'     ,  action='store_true'     ,  help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.'     ,  )
     pod_args.add_argument(
         '--command_file'     ,  default=snake_case__     ,  help='The path to the file containing the commands to run on the pod on startup.'     ,  )
     pod_args.add_argument(
         '--command'     ,  action='append'     ,  nargs='+'     ,  help='A command to run on the pod. Can be passed multiple times.'     ,  )
     pod_args.add_argument(
         '--install_accelerate'     ,  action='store_true'     ,  help='Whether to install accelerate on the pod. Defaults to False.'     ,  )
     pod_args.add_argument(
         '--accelerate_version'     ,  default='latest'     ,  help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.'     ,  )
     pod_args.add_argument(
         '--debug'     ,  action='store_true'     ,  help='If set, will print the command that would be run instead of running it.' )

     if subparsers is not None:
          parser.set_defaults(func=snake_case__ )
     return parser







def     _a				(      lowercase__  :			Union[str, Any] ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		None

     # Get the default from the config file if it exists.
     if args.config_file is not None or os.path.isfile(snake_case__ ):
          SCREAMING_SNAKE_CASE__				:				int			=		load_config_from_file(args.config_file )
          if not args.command_file and defaults.command_file is not None and not args.command:
               SCREAMING_SNAKE_CASE__				:				str			=		defaults.command_file
          if not args.command and defaults.commands is not None:
               SCREAMING_SNAKE_CASE__				:				Tuple			=		defaults.commands
          if not args.tpu_name:
               SCREAMING_SNAKE_CASE__				:				List[Any]			=		defaults.tpu_name
          if not args.tpu_zone:
               SCREAMING_SNAKE_CASE__				:				int			=		defaults.tpu_zone
     if args.accelerate_version == "dev":
          SCREAMING_SNAKE_CASE__				:				Tuple			=		'git+https://github.com/huggingface/accelerate.git'
     elif args.accelerate_version == "latest":
          SCREAMING_SNAKE_CASE__				:				str			=		'accelerate -U'
     elif isinstance(parse(args.accelerate_version )     ,  snake_case__ ):
          SCREAMING_SNAKE_CASE__				:				List[Any]			=		f'''accelerate=={args.accelerate_version}'''

     if not args.command_file and not args.command:
          raise ValueError('You must specify either a command file or a command to run on the pod.' )

     if args.command_file:
          with open(args.command_file     ,  'r' ) as f:
               SCREAMING_SNAKE_CASE__				:				int			=		[f.read().splitlines()]

    # To turn list of lists into list of strings
     if isinstance(args.command[0]     ,  snake_case__ ):
          SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		[line for cmd in args.command for line in cmd]
     # Default to the shared folder and install accelerate
     SCREAMING_SNAKE_CASE__				:				Dict			=		['cd /usr/share']
     if args.install_accelerate:
          new_cmd += [f'''pip install {args.accelerate_version}''']
     new_cmd += args.command
     SCREAMING_SNAKE_CASE__				:				Tuple			=		'; '.join(snake_case__ )

     # Then send it to gcloud
     # Eventually try to use google-api-core to do this instead of subprocess
     SCREAMING_SNAKE_CASE__				:				List[Any]			=		['gcloud']
     if args.use_alpha:
          cmd += ["alpha"]
     cmd += [
         "compute",
         "tpus",
         "tpu-vm",
         "ssh",
         args.tpu_name,
         "--zone",
         args.tpu_zone,
         "--command",
         args.command,
         "--worker",
         "all",
     ]
     if args.debug:
          print(f'''Running {' '.join(snake_case__ )}''' )
          return
     subprocess.run(snake_case__ )
     print('Successfully setup pod.' )







def     _a				(      ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				Optional[int]			=		tpu_command_parser()
     SCREAMING_SNAKE_CASE__				:				Optional[int]			=		parser.parse_args()

     tpu_command_launcher(snake_case__ )




import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available

class       snake_case					(      UpperCamelCase_						):
  lowercase_			=     ['image_processor', 'tokenizer']
  lowercase_			=     'OwlViTImageProcessor'
  lowercase_			=     ('CLIPTokenizer', 'CLIPTokenizerFast')




  def __init__(      self     :	List[str]     , a_     :	List[Any]=None     , a_     :	str=None     , **a_     :	Any				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		None
       if "feature_extractor" in kwargs:
            warnings.warn(
                'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                ' instead.'     , a_     , )
            SCREAMING_SNAKE_CASE__				:				Tuple			=		kwargs.pop('feature_extractor'				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		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__(a_     , a_				)




  def __call__(      self     :	Any     , a_     :	Optional[int]=None     , a_     :	Tuple=None     , a_     :	List[Any]=None     , a_     :	Tuple="max_length"     , a_     :	str="np"     , **a_     :	Any				)->       int:




       """simple docstring"""

       if text is None and query_images is None and images is None:
            raise ValueError(
                'You have to specify at least one text or query image or image. All three cannot be none.'				)

       if text is not None:
            if isinstance(a_     , a_				) or (isinstance(a_     , a_				) and not isinstance(text[0]     , a_				)):
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		[self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)]

            elif isinstance(a_     , a_				) and isinstance(text[0]     , a_				):
                 SCREAMING_SNAKE_CASE__				:				Any			=		[]

                 # Maximum number of queries across batch
                 SCREAMING_SNAKE_CASE__				:				str			=		max([len(a_				) for t in text]				)

                 # Pad all batch samples to max number of text queries
                 for t in text:
                      if len(a_				) != max_num_queries:
                           SCREAMING_SNAKE_CASE__				:				Tuple			=		t + [' '] * (max_num_queries - len(a_				))

                      SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)
                      encodings.append(a_				)
            else:
                 raise TypeError('Input text should be a string, a list of strings or a nested list of strings'				)

            if return_tensors == "np":
                 SCREAMING_SNAKE_CASE__				:				Dict			=		np.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				List[Any]			=		np.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "jax" and is_flax_available():
                 import jax.numpy as jnp

                 SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		jnp.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		jnp.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "pt" and is_torch_available():
                 import torch

                 SCREAMING_SNAKE_CASE__				:				int			=		torch.cat([encoding['input_ids'] for encoding in encodings]     , dim=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[int]			=		torch.cat([encoding['attention_mask'] for encoding in encodings]     , dim=0				)

            elif return_tensors == "tf" and is_tf_available():
                 import tensorflow as tf

                 SCREAMING_SNAKE_CASE__				:				str			=		tf.stack([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Dict			=		tf.stack([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            else:
                 raise ValueError('Target return tensor type could not be returned'				)

            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				List[str]			=		input_ids
            SCREAMING_SNAKE_CASE__				:				Tuple			=		attention_mask

       if query_images is not None:
            SCREAMING_SNAKE_CASE__				:				Any			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				Dict			=		self.image_processor(
                a_     , return_tensors=a_     , **a_				).pixel_values
            SCREAMING_SNAKE_CASE__				:				Dict			=		query_pixel_values

       if images is not None:
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processor(a_     , return_tensors=a_     , **a_				)

       if text is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Dict			=		image_features.pixel_values
            return encoding
       elif query_images is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_features.pixel_values
            return encoding
       elif text is not None or query_images is not None:
            return encoding
       else:
            return BatchEncoding(data=dict(**a_				)     , tensor_type=a_				)




  def 	__lowercase(      self     :	str     , *a_     :	List[str]     , **a_     :	int				)->       List[Any]:




       """simple docstring"""
       return self.image_processor.post_process(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	List[str]     , **a_     :	str				)->       Union[str, Any]:




       """simple docstring"""
       return self.image_processor.post_process_object_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[Any]     , *a_     :	str     , **a_     :	Dict				)->       Optional[int]:




       """simple docstring"""
       return self.image_processor.post_process_image_guided_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[int]     , *a_     :	Tuple     , **a_     :	Tuple				)->       Optional[Any]:




       """simple docstring"""
       return self.tokenizer.batch_decode(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	Tuple     , **a_     :	Tuple				)->       List[str]:




       """simple docstring"""
       return self.tokenizer.decode(*a_     , **a_				)




  @property
  def 	__lowercase(      self     :	Tuple				)->       Any:




       """simple docstring"""
       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'     , a_     , )
       return self.image_processor_class




  @property
  def 	__lowercase(      self     :	List[Any]				)->       List[str]:




       """simple docstring"""
       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'     , a_     , )
       return self.image_processor



