



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 List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
 import torch

 from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

__snake_case						:Dict						=					logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase   ):



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


           '''simple docstring'''

           super().__init__(*__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           requires_backends(self					,		'''vision''')
           self.check_model_type(
               TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING)



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


           '''simple docstring'''

           __a							=    {}
           __a							=    {}

           if prompt is not None:
               __a							=    prompt

           if generate_kwargs is not None:
               __a							=    generate_kwargs
           if max_new_tokens is not None:
               if "generate_kwargs" not in forward_kwargs:
                   __a							=    {}
               if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
                   raise ValueError(
                       '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'''
                       ''' please use only one''')
               __a							=    max_new_tokens
           return preprocess_params, forward_kwargs, {}



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


           '''simple docstring'''

           return super().__call__(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Dict					,		__SCREAMING_SNAKE_CASE							:					Optional[Any]=None):


           '''simple docstring'''

           __a							=    load_image(__SCREAMING_SNAKE_CASE)

           if prompt is not None:
               if not isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE):
                   raise ValueError(
                       F'Received an invalid text input, got - {type(__SCREAMING_SNAKE_CASE)} - but expected a single string. '
                       '''Note also that one single text can be provided for conditional image to text generation.''')

               __a							=    self.model.config.model_type

               if model_type == "git":
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   __a							=    self.tokenizer(text=__SCREAMING_SNAKE_CASE					,		add_special_tokens=__SCREAMING_SNAKE_CASE).input_ids
                   __a							=    [self.tokenizer.cls_token_id] + input_ids
                   __a							=    torch.tensor(__SCREAMING_SNAKE_CASE).unsqueeze(0)
                   model_inputs.update({'''input_ids''': input_ids})

               elif model_type == "pix2struct":
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		header_text=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)

               elif model_type != "vision-encoder-decoder":
                   # vision-encoder-decoder does not support conditional generation
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   __a							=    self.tokenizer(__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   model_inputs.update(__SCREAMING_SNAKE_CASE)

               else:
                   raise ValueError(F'Model type {model_type} does not support conditional text generation')

           else:
               __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)

           if self.model.config.model_type == "git" and prompt is None:
               __a							=    None

           return model_inputs



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


           '''simple docstring'''

           if (
               "input_ids" in model_inputs
               and isinstance(model_inputs['''input_ids''']					,		__SCREAMING_SNAKE_CASE)
               and all(x is None for x in model_inputs['''input_ids'''])
           ):
               __a							=    None

           if generate_kwargs is None:
               __a							=    {}
           # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
           #  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
           #  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
           #  in the `_prepare_model_inputs` method.
           __a							=    model_inputs.pop(self.model.main_input_name)
           __a							=    self.model.generate(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           return model_outputs





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


           '''simple docstring'''

           __a							=    []
           for output_ids in model_outputs:
               __a							=    {
                   '''generated_text''': self.tokenizer.decode(
                       __SCREAMING_SNAKE_CASE					,		skip_special_tokens=__SCREAMING_SNAKE_CASE					,		)
               }
               records.append(__SCREAMING_SNAKE_CASE)
           return records





