


"""simple docstring"""



from typing import Dict, Iterable, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
  import PIL

# soft dependency
if is_pytesseract_available():
  import pytesseract

__snake_case   			=    logging.get_logger(__name__)







def   __lowerCAmelCase						(						lowercase  :  Any						,							lowercase  :  Tuple						,							lowercase  :  Union[str, Any] )	->						Any:


    """simple docstring"""





    return [
        int(1000 * (box[0] / width) ),
        int(1000 * (box[1] / height) ),
        int(1000 * (box[2] / width) ),
        int(1000 * (box[3] / height) ),
    ]







def   __lowerCAmelCase						(						lowercase  :  np.ndarray						,							lowercase  :  Optional[str]						,							lowercase  :  Optional[str] )	->						Any:


    """simple docstring"""





    snake_case    :      Union[str, Any]      					=    to_pil_image(lowercase )
    snake_case					,snake_case    :      Optional[Any]      					=    pil_image.size
    snake_case    :      List[str]      					=    pytesseract.image_to_data(lowercase						,							lang=lowercase						,							output_type="dict"						,							config=lowercase )
    snake_case					,snake_case					,snake_case					,snake_case					,snake_case    :      Union[str, Any]      					=    data["text"], data["left"], data["top"], data["width"], data["height"]

    # filter empty words and corresponding coordinates
    snake_case    :      Any      					=    [idx for idx, word in enumerate(lowercase ) if not word.strip()]
    snake_case    :      Dict      					=    [word for idx, word in enumerate(lowercase ) if idx not in irrelevant_indices]
    snake_case    :      Dict      					=    [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices]
    snake_case    :      Any      					=    [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices]
    snake_case    :      List[str]      					=    [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices]
    snake_case    :      Any      					=    [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices]

    # turn coordinates into (left, top, left+width, top+height) format
    snake_case    :      Optional[Any]      					=    []
    for x, y, w, h in zip(lowercase						,							lowercase						,							lowercase						,							lowercase ):
        snake_case    :      str      					=    [x, y, x + w, y + h]
        actual_boxes.append(lowercase )

    # finally, normalize the bounding boxes
    snake_case    :      List[Any]      					=    []
    for box in actual_boxes:
        normalized_boxes.append(normalize_box(lowercase						,							lowercase						,							lowercase ) )

    assert len(lowercase ) == len(lowercase ), "Not as many words as there are bounding boxes"

    return words, normalized_boxes







class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       Optional[Any]							  =  ['''pixel_values''']







   def __init__(	self						,	UpperCamelCase__ = True						,	UpperCamelCase__ = None						,	UpperCamelCase__ = PILImageResampling.BILINEAR						,	UpperCamelCase__ = True						,	UpperCamelCase__ = 1 / 255						,	UpperCamelCase__ = True						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = True						,	UpperCamelCase__ = None						,	UpperCamelCase__ = ""						,	**UpperCamelCase__						,	)	->		None:

       '''simple docstring'''




       super().__init__(**UpperCamelCase__						)
       snake_case    :      str      					=    size if size is not None else {"height": 224, "width": 224}
       snake_case    :      List[Any]      					=    get_size_dict(UpperCamelCase__						)

       snake_case    :      Union[str, Any]      					=    do_resize
       snake_case    :      int      					=    size
       snake_case    :      Optional[int]      					=    resample
       snake_case    :      int      					=    do_rescale
       snake_case    :      int      					=    rescale_value
       snake_case    :      Optional[Any]      					=    do_normalize
       snake_case    :      Dict      					=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       snake_case    :      str      					=    image_std if image_std is not None else IMAGENET_STANDARD_STD
       snake_case    :      List[str]      					=    apply_ocr
       snake_case    :      Dict      					=    ocr_lang
       snake_case    :      Union[str, Any]      					=    tesseract_config







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = PILImageResampling.BILINEAR						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		np.ndarray:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    get_size_dict(UpperCamelCase__						)
       if "height" not in size or "width" not in size:
           raise ValueError(F'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'						)
       snake_case    :      int      					=    (size["height"], size["width"])
       return resize(UpperCamelCase__						,	size=UpperCamelCase__						,	resample=UpperCamelCase__						,	data_format=UpperCamelCase__						,	**UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		np.ndarray:

       '''simple docstring'''




       return rescale(UpperCamelCase__						,	scale=UpperCamelCase__						,	data_format=UpperCamelCase__						,	**UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		np.ndarray:

       '''simple docstring'''




       return normalize(UpperCamelCase__						,	mean=UpperCamelCase__						,	std=UpperCamelCase__						,	data_format=UpperCamelCase__						,	**UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__=None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = ChannelDimension.FIRST						,	**UpperCamelCase__						,	)	->		PIL.Image.Image:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    do_resize if do_resize is not None else self.do_resize
       snake_case    :      List[str]      					=    size if size is not None else self.size
       snake_case    :      str      					=    get_size_dict(UpperCamelCase__						)
       snake_case    :      Tuple      					=    resample if resample is not None else self.resample
       snake_case    :      Optional[int]      					=    do_rescale if do_rescale is not None else self.do_rescale
       snake_case    :      Optional[int]      					=    rescale_factor if rescale_factor is not None else self.rescale_factor
       snake_case    :      Optional[Any]      					=    do_normalize if do_normalize is not None else self.do_normalize
       snake_case    :      Dict      					=    image_mean if image_mean is not None else self.image_mean
       snake_case    :      Optional[int]      					=    image_std if image_std is not None else self.image_std
       snake_case    :      Optional[Any]      					=    apply_ocr if apply_ocr is not None else self.apply_ocr
       snake_case    :      List[Any]      					=    ocr_lang if ocr_lang is not None else self.ocr_lang
       snake_case    :      int      					=    tesseract_config if tesseract_config is not None else self.tesseract_config

       snake_case    :      Dict      					=    make_list_of_images(UpperCamelCase__						)

       if not valid_images(UpperCamelCase__						):
           raise ValueError(
               "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
               "torch.Tensor, tf.Tensor or jax.ndarray."						)

       if do_resize and size is None:
           raise ValueError("Size must be specified if do_resize is True."						)

       if do_rescale and rescale_factor is None:
           raise ValueError("Rescale factor must be specified if do_rescale is True."						)

       if do_normalize and (image_mean is None or image_std is None):
           raise ValueError("If do_normalize is True, image_mean and image_std must be specified."						)

       # All transformations expect numpy arrays.
       snake_case    :      Union[str, Any]      					=    [to_numpy_array(UpperCamelCase__						) for image in images]

       # Tesseract OCR to get words + normalized bounding boxes
       if apply_ocr:
           requires_backends(self						,	"pytesseract"						)
           snake_case    :      Optional[int]      					=    []
           snake_case    :      Optional[int]      					=    []
           for image in images:
               snake_case					,snake_case    :      Union[str, Any]      					=    apply_tesseract(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)
               words_batch.append(UpperCamelCase__						)
               boxes_batch.append(UpperCamelCase__						)

       if do_resize:
           snake_case    :      List[str]      					=    [self.resize(image=UpperCamelCase__						,	size=UpperCamelCase__						,	resample=UpperCamelCase__						) for image in images]

       if do_rescale:
           snake_case    :      Optional[Any]      					=    [self.rescale(image=UpperCamelCase__						,	scale=UpperCamelCase__						) for image in images]

       if do_normalize:
           snake_case    :      Union[str, Any]      					=    [self.normalize(image=UpperCamelCase__						,	mean=UpperCamelCase__						,	std=UpperCamelCase__						) for image in images]

       snake_case    :      Tuple      					=    [to_channel_dimension_format(UpperCamelCase__						,	UpperCamelCase__						) for image in images]

       snake_case    :      Optional[Any]      					=    BatchFeature(data={"pixel_values": images}						,	tensor_type=UpperCamelCase__						)

       if apply_ocr:
           snake_case    :      List[str]      					=    words_batch
           snake_case    :      int      					=    boxes_batch
       return data









"""simple docstring"""



from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
  import tensorflow as tf

  from transformers import TFBlipTextModel
  from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class _lowerCAmelCase				:







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=12						,	UpperCamelCase__=7						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=99						,	UpperCamelCase__=32						,	UpperCamelCase__=32						,	UpperCamelCase__=2						,	UpperCamelCase__=4						,	UpperCamelCase__=37						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=512						,	UpperCamelCase__=0.02						,	UpperCamelCase__=0						,	UpperCamelCase__=None						,	)	->		Dict:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    parent
       snake_case    :      Dict      					=    batch_size
       snake_case    :      List[str]      					=    seq_length
       snake_case    :      Dict      					=    is_training
       snake_case    :      Optional[Any]      					=    use_input_mask
       snake_case    :      Optional[int]      					=    use_labels
       snake_case    :      Tuple      					=    vocab_size
       snake_case    :      Optional[Any]      					=    hidden_size
       snake_case    :      Optional[Any]      					=    projection_dim
       snake_case    :      List[Any]      					=    num_hidden_layers
       snake_case    :      List[Any]      					=    num_attention_heads
       snake_case    :      int      					=    intermediate_size
       snake_case    :      str      					=    dropout
       snake_case    :      List[Any]      					=    attention_dropout
       snake_case    :      Any      					=    max_position_embeddings
       snake_case    :      List[Any]      					=    initializer_range
       snake_case    :      Any      					=    scope
       snake_case    :      Union[str, Any]      					=    bos_token_id







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      str      					=    ids_tensor([self.batch_size, self.seq_length]						,	self.vocab_size						)

       snake_case    :      int      					=    None
       if self.use_input_mask:
           snake_case    :      Optional[int]      					=    random_attention_mask([self.batch_size, self.seq_length]						)

       if input_mask is not None:
           snake_case    :      Tuple      					=    input_mask.numpy()
           snake_case					,snake_case    :      str      					=    input_mask.shape
           snake_case    :      Tuple      					=    np.random.randint(1						,	seq_length - 1						,	size=(batch_size,)						)
           for batch_idx, start_index in enumerate(UpperCamelCase__						):
               snake_case    :      int      					=    1
               snake_case    :      Tuple      					=    0

       snake_case    :      Union[str, Any]      					=    self.get_config()

       return config, input_ids, tf.convert_to_tensor(UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       return BlipTextConfig(
           vocab_size=self.vocab_size						,	hidden_size=self.hidden_size						,	projection_dim=self.projection_dim						,	num_hidden_layers=self.num_hidden_layers						,	num_attention_heads=self.num_attention_heads						,	intermediate_size=self.intermediate_size						,	dropout=self.dropout						,	attention_dropout=self.attention_dropout						,	max_position_embeddings=self.max_position_embeddings						,	initializer_range=self.initializer_range						,	bos_token_id=self.bos_token_id						,	)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      str      					=    TFBlipTextModel(config=UpperCamelCase__						)
       snake_case    :      Any      					=    model(UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	training=UpperCamelCase__						)
       snake_case    :      Optional[int]      					=    model(UpperCamelCase__						,	training=UpperCamelCase__						)
       self.parent.assertEqual(result.last_hidden_state.shape						,	(self.batch_size, self.seq_length, self.hidden_size)						)
       self.parent.assertEqual(result.pooler_output.shape						,	(self.batch_size, self.hidden_size)						)







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    self.prepare_config_and_inputs()
       snake_case					,snake_case					,snake_case    :      Tuple      					=    config_and_inputs
       snake_case    :      str      					=    {"input_ids": input_ids, "attention_mask": input_mask}
       return config, inputs_dict







@require_tf
class _lowerCAmelCase				(      snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Any							  =  (TFBlipTextModel,) if is_tf_available() else ()
   __UpperCAmelCase :       Any							  =  False
   __UpperCAmelCase :       Dict							  =  False
   __UpperCAmelCase :       List[Any]							  =  False







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    BlipTextModelTester(self						)
       snake_case    :      Optional[int]      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	hidden_size=37						)







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       pass







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="Blip does not use inputs_embeds"						)
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       pass







   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"						)
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"						)
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       pass







   @slow
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case    :      List[str]      					=    TFBlipTextModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__=True						)	->		Optional[int]:

       '''simple docstring'''




       super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__						)





