



from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
				from PIL import Image

				from ..image_utils import load_image

if is_torch_available():
				import torch

				from transformers.modeling_outputs import BaseModelOutput

				from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__A   			=logging.get_logger(__name__)

@add_end_docstrings(__UpperCamelCase   )
class 		UpperCAmelCase__			(			__UpperCamelCase   ):




			'''simple docstring'''






			def __init__(   self							: str       ,       **a_							: Tuple ):
					'''simple docstring'''





					super().__init__(**a_ )

					if self.framework == "tf":
							raise ValueError(F'The {self.__class__} is only available in PyTorch.' )

					requires_backends(self       ,       '''vision''' )
					self.check_model_type(a_ )




			def __call__(   self							: Dict       ,       a_							: Union[str, "Image.Image", List[Dict[str, Any]]]       ,       a_							: Union[str, List[str]] = None       ,       **a_							: Dict       ,       ):
					'''simple docstring'''





					if "text_queries" in kwargs:
							__UpperCAmelCase    :     List[str]													=	kwargs.pop('''text_queries''' )

					if isinstance(a_       ,       (str, Image.Image) ):
							__UpperCAmelCase    :     Optional[Any]													=	{'''image''': image, '''candidate_labels''': candidate_labels}
					else:
							__UpperCAmelCase    :     Optional[int]													=	image
					__UpperCAmelCase    :     str													=	super().__call__(a_       ,       **a_ )
					return results




			def  snake_case__     (   self							: Any       ,       **a_							: Tuple ):
					'''simple docstring'''





					__UpperCAmelCase    :     Tuple													=	{}
					if "threshold" in kwargs:
							__UpperCAmelCase    :     Any													=	kwargs['''threshold''']
					if "top_k" in kwargs:
							__UpperCAmelCase    :     List[str]													=	kwargs['''top_k''']
					return {}, {}, postprocess_params




			def  snake_case__     (   self							: int       ,       a_							: Optional[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Union[str, Any]													=	load_image(inputs['''image'''] )
					__UpperCAmelCase    :     Optional[Any]													=	inputs['''candidate_labels''']
					if isinstance(a_       ,       a_ ):
							__UpperCAmelCase    :     Tuple													=	candidate_labels.split(''',''' )

					__UpperCAmelCase    :     List[str]													=	torch.tensor([[image.height, image.width]]       ,       dtype=torch.intaa )
					for i, candidate_label in enumerate(a_ ):
							__UpperCAmelCase    :     Dict													=	self.tokenizer(a_       ,       return_tensors=self.framework )
							__UpperCAmelCase    :     Dict													=	self.image_processor(a_       ,       return_tensors=self.framework )
							yield {
							    "is_last": i == len(a_ ) - 1,
							    "target_size": target_size,
							    "candidate_label": candidate_label,
							    **text_inputs,
							    **image_features,
							}




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: List[str] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Tuple													=	model_inputs.pop('''target_size''' )
					__UpperCAmelCase    :     List[Any]													=	model_inputs.pop('''candidate_label''' )
					__UpperCAmelCase    :     Tuple													=	model_inputs.pop('''is_last''' )

					__UpperCAmelCase    :     Any													=	self.model(**a_ )

					__UpperCAmelCase    :     List[Any]													=	{'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
					return model_outputs




			def  snake_case__     (   self							: List[str]       ,       a_							: Dict       ,       a_							: int=0.1       ,       a_							: Any=None ):
					'''simple docstring'''





					__UpperCAmelCase    :     Union[str, Any]													=	[]
					for model_output in model_outputs:
							__UpperCAmelCase    :     Tuple													=	model_output['''candidate_label''']
							__UpperCAmelCase    :     Optional[int]													=	BaseModelOutput(a_ )
							__UpperCAmelCase    :     Tuple													=	self.image_processor.post_process_object_detection(
							    outputs=a_       ,       threshold=a_       ,       target_sizes=model_output['''target_size'''] )[0]

							for index in outputs["scores"].nonzero():
									__UpperCAmelCase    :     Union[str, Any]													=	outputs['''scores'''][index].item()
									__UpperCAmelCase    :     Any													=	self._get_bounding_box(outputs['''boxes'''][index][0] )

									__UpperCAmelCase    :     Optional[int]													=	{'''score''': score, '''label''': label, '''box''': box}
									results.append(a_ )

					__UpperCAmelCase    :     Dict													=	sorted(a_       ,       key=lambda a_ : x["score"]       ,       reverse=a_ )
					if top_k:
							__UpperCAmelCase    :     Union[str, Any]													=	results[:top_k]

					return results




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: "torch.Tensor" ):
					'''simple docstring'''





					if self.framework != "pt":
							raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.''' )
					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase    :     Dict													=	box.int().tolist()
					__UpperCAmelCase    :     List[Any]													=	{
					    '''xmin''': xmin,
					    '''ymin''': ymin,
					    '''xmax''': xmax,
					    '''ymax''': ymax,
					}
					return bbox










#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes        # name
# #SBATCH --nodes=2                    # nodes
# #SBATCH --ntasks-per-node=1          # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10           # number of cores per tasks
# #SBATCH --gres=gpu:4                 # number of gpus
# #SBATCH --time 0:05:00               # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out           # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#

import fcntl
import os
import socket

import torch
import torch.distributed as dist

def        a						(      *_UpperCAmelCase							:					List[str]						):







		'''simple docstring'''





		with open(_UpperCAmelCase ,   '''r'''						) as fh:
				fcntl.flock(_UpperCAmelCase ,   fcntl.LOCK_EX						)
				try:
						print(*_UpperCAmelCase						)
				finally:
						fcntl.flock(_UpperCAmelCase ,   fcntl.LOCK_UN						)


__A   			=int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
__A   			=torch.device("cuda", local_rank)
__A   			=socket.gethostname()

__A   			=f'''[{hostname}-{local_rank}]'''

try:
				# test distributed
				dist.init_process_group("nccl")
				dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
				dist.barrier()

				# test cuda is available and can allocate memory
				torch.cuda.is_available()
				torch.ones(1).cuda(local_rank)

				# global rank
				__A   			=dist.get_rank()
				__A   			=dist.get_world_size()

				printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''')

				dist.barrier()
				if rank == 0:
								printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''')

except Exception:
				printflock(f'''{gpu} is broken''')
				raise





