


"""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

UpperCAmelCase    :     str   						=		logging.get_logger(__name__)
def      lowerCamelCase       (     _UpperCamelCase		:      Optional[int]       ,			_UpperCamelCase		:      str       ,			_UpperCamelCase		:      Optional[int]							)		->       int:

							'''simple docstring'''



							return [
							    int(1_0_0_0 * (box[0] / width)							),
							    int(1_0_0_0 * (box[1] / height)							),
							    int(1_0_0_0 * (box[2] / width)							),
							    int(1_0_0_0 * (box[3] / height)							),
							]
def      lowerCamelCase       (     _UpperCamelCase		:      np.ndarray       ,			_UpperCamelCase		:      Optional[str]       ,			_UpperCamelCase		:      Optional[str]							)		->       Optional[int]:

							'''simple docstring'''



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

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

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

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

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

							return words, normalized_boxes





class      lowerCamelCase__   (     A				):







					"""simple docstring"""


					__a	       =							["""pixel_values"""]






					def __init__(       self    : List[str] ,       UpperCamelCase    : bool = True ,       UpperCamelCase    : Dict[str, int] = None ,       UpperCamelCase    : PILImageResampling = PILImageResampling.BILINEAR ,       UpperCamelCase    : bool = True ,       UpperCamelCase    : float = 1 / 255 ,       UpperCamelCase    : bool = True ,       UpperCamelCase    : Union[float, Iterable[float]] = None ,       UpperCamelCase    : Union[float, Iterable[float]] = None ,       UpperCamelCase    : bool = True ,       UpperCamelCase    : Optional[str] = None ,       UpperCamelCase    : Optional[str] = "" ,       **UpperCamelCase    : Any ,       ):
												'''simple docstring'''






												super().__init__(**UpperCamelCase  )
												__UpperCAmelCase   :						Tuple      							=					size if size is not None else {"""height""": 224, """width""": 224}
												__UpperCAmelCase   :						Union[str, Any]      							=					get_size_dict(UpperCamelCase  )

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






					def lowerCamelCase__							(       self    : List[Any] ,       UpperCamelCase    : np.ndarray ,       UpperCamelCase    : Dict[str, int] ,       UpperCamelCase    : PILImageResampling = PILImageResampling.BILINEAR ,       UpperCamelCase    : Optional[Union[str, ChannelDimension]] = None ,       **UpperCamelCase    : List[str] ,       ):
												'''simple docstring'''






												__UpperCAmelCase   :						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()}'''  )
												__UpperCAmelCase   :						List[Any]      							=					(size["""height"""], size["""width"""])
												return resize(UpperCamelCase ,       size=UpperCamelCase ,       resample=UpperCamelCase ,       data_format=UpperCamelCase ,       **UpperCamelCase  )






					def lowerCamelCase__							(       self    : str ,       UpperCamelCase    : np.ndarray ,       UpperCamelCase    : Union[int, float] ,       UpperCamelCase    : Optional[Union[str, ChannelDimension]] = None ,       **UpperCamelCase    : Optional[Any] ,       ):
												'''simple docstring'''






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






					def lowerCamelCase__							(       self    : Tuple ,       UpperCamelCase    : np.ndarray ,       UpperCamelCase    : Union[float, Iterable[float]] ,       UpperCamelCase    : Union[float, Iterable[float]] ,       UpperCamelCase    : Optional[Union[str, ChannelDimension]] = None ,       **UpperCamelCase    : Tuple ,       ):
												'''simple docstring'''






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






					def lowerCamelCase__							(       self    : Optional[int] ,       UpperCamelCase    : ImageInput ,       UpperCamelCase    : bool = None ,       UpperCamelCase    : Dict[str, int] = None ,       UpperCamelCase    : Tuple=None ,       UpperCamelCase    : bool = None ,       UpperCamelCase    : float = None ,       UpperCamelCase    : bool = None ,       UpperCamelCase    : Union[float, Iterable[float]] = None ,       UpperCamelCase    : Union[float, Iterable[float]] = None ,       UpperCamelCase    : bool = None ,       UpperCamelCase    : Optional[str] = None ,       UpperCamelCase    : Optional[str] = None ,       UpperCamelCase    : Optional[Union[str, TensorType]] = None ,       UpperCamelCase    : ChannelDimension = ChannelDimension.FIRST ,       **UpperCamelCase    : Union[str, Any] ,       ):
												'''simple docstring'''






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

												__UpperCAmelCase   :						List[str]      							=					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.
												__UpperCAmelCase   :						Dict      							=					[to_numpy_array(UpperCamelCase  ) for image in images]

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

												if do_resize:
																			__UpperCAmelCase   :						Optional[Any]      							=					[self.resize(image=UpperCamelCase ,       size=UpperCamelCase ,       resample=UpperCamelCase  ) for image in images]

												if do_rescale:
																			__UpperCAmelCase   :						List[str]      							=					[self.rescale(image=UpperCamelCase ,       scale=UpperCamelCase  ) for image in images]

												if do_normalize:
																			__UpperCAmelCase   :						str      							=					[self.normalize(image=UpperCamelCase ,       mean=UpperCamelCase ,       std=UpperCamelCase  ) for image in images]

												__UpperCAmelCase   :						Tuple      							=					[to_channel_dimension_format(UpperCamelCase ,       UpperCamelCase  ) for image in images]

												__UpperCAmelCase   :						Union[str, Any]      							=					BatchFeature(data={"""pixel_values""": images} ,       tensor_type=UpperCamelCase  )

												if apply_ocr:
																			__UpperCAmelCase   :						Any      							=					words_batch
																			__UpperCAmelCase   :						Optional[int]      							=					boxes_batch
												return data




"""simple docstring"""






import os
import sys
from contextlib import contextmanager


# Windows only
if os.name == "nt":
							import ctypes
							import msvcrt  # noqa





							class      lowerCamelCase__   (     ctypes.Structure				):







												"""simple docstring"""


												__a	       =							[("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)]
def      lowerCamelCase       (     )		->       Optional[int]:

							'''simple docstring'''



							if os.name == "nt":
														__UpperCAmelCase   :						Dict      							=					CursorInfo()
														__UpperCAmelCase   :						Any      							=					ctypes.windll.kernelaa.GetStdHandle(-1_1							)
														ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCamelCase       ,			ctypes.byref(_UpperCamelCase							)							)
														__UpperCAmelCase   :						Tuple      							=					False
														ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCamelCase       ,			ctypes.byref(_UpperCamelCase							)							)
							elif os.name == "posix":
														sys.stdout.write("""\033[?25l"""							)
														sys.stdout.flush()
def      lowerCamelCase       (     )		->       Optional[int]:

							'''simple docstring'''



							if os.name == "nt":
														__UpperCAmelCase   :						str      							=					CursorInfo()
														__UpperCAmelCase   :						int      							=					ctypes.windll.kernelaa.GetStdHandle(-1_1							)
														ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCamelCase       ,			ctypes.byref(_UpperCamelCase							)							)
														__UpperCAmelCase   :						Union[str, Any]      							=					True
														ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCamelCase       ,			ctypes.byref(_UpperCamelCase							)							)
							elif os.name == "posix":
														sys.stdout.write("""\033[?25h"""							)
														sys.stdout.flush()
@contextmanager
def      lowerCamelCase       (     )		->       str:

							'''simple docstring'''



							try:
														hide_cursor()
														yield
							finally:
														show_cursor()
