



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,
)
__snake_case						:Union[str, Any]						=					logging.getLogger(__name__)





def 					__snake_case     (      _UpperCAmelCase    ):
    __a							=    git.Repo(search_parent_directories=_UpperCAmelCase    )
    __a							=    {
        '''repo_id''': str(_UpperCAmelCase    ),
        '''repo_sha''': str(repo.head.object.hexsha    ),
        '''repo_branch''': str(repo.active_branch    ),
    }

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





def 					__snake_case     (      _UpperCAmelCase    ):
    if params.n_gpu <= 0:
        __a							=    0
        __a							=    -1
        __a							=    True
        __a							=    False
        return

    assert torch.cuda.is_available()

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

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

        # number of nodes / node ID
        __a							=    params.world_size // params.n_gpu_per_node
        __a							=    params.global_rank // params.n_gpu_per_node
        __a							=    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

        __a							=    1
        __a							=    0
        __a							=    0
        __a							=    0
        __a							=    1
        __a							=    1
        __a							=    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
    __a							=    params.node_id == 0 and params.local_rank == 0
    __a							=    params.n_nodes > 1

    # summary
    __a							=    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 					__snake_case     (      _UpperCAmelCase    ):
    np.random.seed(args.seed    )
    torch.manual_seed(args.seed    )
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed    )










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

__snake_case						:Tuple						=					logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase   ):



       def __init__(		self							:					Optional[int]					,		**__SCREAMING_SNAKE_CASE							:					Optional[Any]):


           '''simple docstring'''

           super().__init__(**__SCREAMING_SNAKE_CASE)

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

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



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


           '''simple docstring'''

           if "text_queries" in kwargs:
               __a							=    kwargs.pop('''text_queries''')

           if isinstance(__SCREAMING_SNAKE_CASE					,		(str, Image.Image)):
               __a							=    {'''image''': image, '''candidate_labels''': candidate_labels}
           else:
               __a							=    image
           __a							=    super().__call__(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           return results



       def 		_lowerCamelCase      (		self							:					str					,		**__SCREAMING_SNAKE_CASE							:					Union[str, Any]):


           '''simple docstring'''

           __a							=    {}
           if "threshold" in kwargs:
               __a							=    kwargs['''threshold''']
           if "top_k" in kwargs:
               __a							=    kwargs['''top_k''']
           return {}, {}, postprocess_params



       def 		_lowerCamelCase      (		self							:					List[str]					,		__SCREAMING_SNAKE_CASE							:					Tuple):


           '''simple docstring'''

           __a							=    load_image(inputs['''image'''])
           __a							=    inputs['''candidate_labels''']
           if isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE):
               __a							=    candidate_labels.split(''',''')

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



       def 		_lowerCamelCase      (		self							:					int					,		__SCREAMING_SNAKE_CASE							:					Tuple):


           '''simple docstring'''

           __a							=    model_inputs.pop('''target_size''')
           __a							=    model_inputs.pop('''candidate_label''')
           __a							=    model_inputs.pop('''is_last''')

           __a							=    self.model(**__SCREAMING_SNAKE_CASE)

           __a							=    {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
           return model_outputs



       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Tuple=0.1					,		__SCREAMING_SNAKE_CASE							:					Union[str, Any]=None):


           '''simple docstring'''

           __a							=    []
           for model_output in model_outputs:
               __a							=    model_output['''candidate_label''']
               __a							=    BaseModelOutput(__SCREAMING_SNAKE_CASE)
               __a							=    self.image_processor.post_process_object_detection(
                   outputs=__SCREAMING_SNAKE_CASE					,		threshold=__SCREAMING_SNAKE_CASE					,		target_sizes=model_output['''target_size'''])[0]

               for index in outputs["scores"].nonzero():
                   __a							=    outputs['''scores'''][index].item()
                   __a							=    self._get_bounding_box(outputs['''boxes'''][index][0])

                   __a							=    {'''score''': score, '''label''': label, '''box''': box}
                   results.append(__SCREAMING_SNAKE_CASE)

           __a							=    sorted(__SCREAMING_SNAKE_CASE					,		key=lambda __SCREAMING_SNAKE_CASE: x["score"]					,		reverse=__SCREAMING_SNAKE_CASE)
           if top_k:
               __a							=    results[:top_k]

           return results





       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					"torch.Tensor"):


           '''simple docstring'''

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





