

"""simple docstring"""

from typing import Dict, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    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

a_			   =					logging.get_logger(__name__)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[Any]				,    SCREAMING_SNAKE_CASE__ :  Union[str, Any]				,    SCREAMING_SNAKE_CASE__ :  List[str]			):



					"""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 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  np.ndarray				,    SCREAMING_SNAKE_CASE__ :  Optional[str]				,    SCREAMING_SNAKE_CASE__ :  Optional[str] = None			):



					"""simple docstring"""





					snake_case_					:		Optional[Any] 					=					tesseract_config if tesseract_config is not None else """"""

					# apply OCR
					snake_case_					:		Optional[int] 					=					to_pil_image(SCREAMING_SNAKE_CASE__			)
					snake_case_					:		Union[str, Any] 					=					pil_image.size
					snake_case_					:		Optional[Any] 					=					pytesseract.image_to_data(SCREAMING_SNAKE_CASE__				,    lang=SCREAMING_SNAKE_CASE__				,    output_type="""dict"""				,    config=SCREAMING_SNAKE_CASE__			)
					snake_case_					:		Dict 					=					data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""]

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

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

					# finally, normalize the bounding boxes
					snake_case_					:		Union[str, Any] 					=					[]
					for box in actual_boxes:
										normalized_boxes.append(normalize_box(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)			)

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

					return words, normalized_boxes







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							int							       =		["""pixel_values"""]







						def __init__(self   ,		lowercase__ = True   ,		lowercase__ = None   ,		lowercase__ = PILImageResampling.BILINEAR   ,		lowercase__ = True   ,		lowercase__ = None   ,		lowercase__ = ""   ,		**lowercase__   ,		):
											super().__init__(**lowercase__       )
											snake_case_					:		List[Any] 					=					size if size is not None else {"""height""": 2_24, """width""": 2_24}
											snake_case_					:		Any 					=					get_size_dict(lowercase__       )

											snake_case_					:		Optional[int] 					=					do_resize
											snake_case_					:		Any 					=					size
											snake_case_					:		Optional[int] 					=					resample
											snake_case_					:		Optional[int] 					=					apply_ocr
											snake_case_					:		List[Any] 					=					ocr_lang
											snake_case_					:		Tuple 					=					tesseract_config







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__   ,		lowercase__ = PILImageResampling.BILINEAR   ,		lowercase__ = None   ,		**lowercase__   ,		):
											snake_case_					:		int 					=					get_size_dict(lowercase__       )
											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_					:		Dict 					=					(size["""height"""], size["""width"""])
											return resize(lowercase__   ,		size=lowercase__   ,		resample=lowercase__   ,		data_format=lowercase__   ,		**lowercase__       )







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = None   ,		lowercase__ = ChannelDimension.FIRST   ,		**lowercase__   ,		):
											snake_case_					:		str 					=					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_					:		List[str] 					=					get_size_dict(lowercase__       )
											snake_case_					:		str 					=					resample if resample is not None else self.resample
											snake_case_					:		Any 					=					apply_ocr if apply_ocr is not None else self.apply_ocr
											snake_case_					:		str 					=					ocr_lang if ocr_lang is not None else self.ocr_lang
											snake_case_					:		str 					=					tesseract_config if tesseract_config is not None else self.tesseract_config

											snake_case_					:		List[str] 					=					make_list_of_images(lowercase__       )

											if not valid_images(lowercase__       ):
																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."""       )

											# All transformations expect numpy arrays.
											snake_case_					:		str 					=					[to_numpy_array(lowercase__       ) for image in images]

											if apply_ocr:
																requires_backends(self   ,		"""pytesseract"""       )
																snake_case_					:		Tuple 					=					[]
																snake_case_					:		Tuple 					=					[]
																for image in images:
																					snake_case_					:		Optional[int] 					=					apply_tesseract(lowercase__   ,		lowercase__   ,		lowercase__       )
																					words_batch.append(lowercase__       )
																					boxes_batch.append(lowercase__       )

											if do_resize:
																snake_case_					:		Union[str, Any] 					=					[self.resize(image=lowercase__   ,		size=lowercase__   ,		resample=lowercase__       ) for image in images]

											# flip color channels from RGB to BGR (as Detectron2 requires this)
											snake_case_					:		Any 					=					[flip_channel_order(lowercase__       ) for image in images]
											snake_case_					:		int 					=					[to_channel_dimension_format(lowercase__   ,		lowercase__       ) for image in images]

											snake_case_					:		str 					=					BatchFeature(data={"""pixel_values""": images}   ,		tensor_type=lowercase__       )

											if apply_ocr:
																snake_case_					:		List[str] 					=					words_batch
																snake_case_					:		Tuple 					=					boxes_batch
											return data









"""simple docstring"""

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings


a_			   =					r'''
    [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
    can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.

    Args:
        title_sep (`str`, *optional*, defaults to  `" / "`):
            Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].
        doc_sep (`str`, *optional*, defaults to  `" // "`):
            Separator inserted between the text of the retrieved document and the original input when calling
            [`RagRetriever`].
        n_docs (`int`, *optional*, defaults to 5):
            Number of documents to retrieve.
        max_combined_length (`int`, *optional*, defaults to 300):
            Max length of contextualized input returned by [`~RagRetriever.__call__`].
        retrieval_vector_size (`int`, *optional*, defaults to 768):
            Dimensionality of the document embeddings indexed by [`RagRetriever`].
        retrieval_batch_size (`int`, *optional*, defaults to 8):
            Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
            [`RagRetriever`].
        dataset (`str`, *optional*, defaults to `"wiki_dpr"`):
            A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
            using `datasets.list_datasets()`).
        dataset_split (`str`, *optional*, defaults to `"train"`)
            Which split of the `dataset` to load.
        index_name (`str`, *optional*, defaults to `"compressed"`)
            The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and
            `"compressed"`.
        index_path (`str`, *optional*)
            The path to the serialized faiss index on disk.
        passages_path (`str`, *optional*):
            A path to text passages compatible with the faiss index. Required if using
            [`~models.rag.retrieval_rag.LegacyIndex`]
        use_dummy_dataset (`bool`, *optional*, defaults to `False`)
            Whether to load a "dummy" variant of the dataset specified by `dataset`.
        label_smoothing (`float`, *optional*, defaults to 0.0):
            Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
            in the loss calculation. If set to 0, no label smoothing is performed.
        do_marginalize (`bool`, *optional*, defaults to `False`):
            If `True`, the logits are marginalized over all documents by making use of
            `torch.nn.functional.log_softmax`.
        reduce_loss (`bool`, *optional*, defaults to `False`):
            Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
        do_deduplication (`bool`, *optional*, defaults to `True`):
            Whether or not to deduplicate the generations from different context documents for a given input. Has to be
            set to `False` if used while training with distributed backend.
        exclude_bos_score (`bool`, *optional*, defaults to `False`):
            Whether or not to disregard the BOS token when computing the loss.
        output_retrieved(`bool`, *optional*, defaults to `False`):
            If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
            `context_attention_mask` are returned. See returned tensors for more detail.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
        forced_eos_token_id (`int`, *optional*):
            The id of the token to force as the last generated token when `max_length` is reached. Usually set to
            `eos_token_id`.
'''







@add_start_docstrings(_UpperCAmelCase)
class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Optional[int]							       =		"""rag"""
						_A		:							Optional[Any]							       =		True







						def __init__(self   ,		lowercase__=None   ,		lowercase__=True   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=" / "   ,		lowercase__=" // "   ,		lowercase__=5   ,		lowercase__=3_00   ,		lowercase__=7_68   ,		lowercase__=8   ,		lowercase__="wiki_dpr"   ,		lowercase__="train"   ,		lowercase__="compressed"   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=0.0   ,		lowercase__=True   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=True   ,		lowercase__=None   ,		**lowercase__   ,		):
											super().__init__(
											    bos_token_id=lowercase__   ,		pad_token_id=lowercase__   ,		eos_token_id=lowercase__   ,		decoder_start_token_id=lowercase__   ,		forced_eos_token_id=lowercase__   ,		is_encoder_decoder=lowercase__   ,		prefix=lowercase__   ,		vocab_size=lowercase__   ,		**lowercase__   ,		)
											assert (
											    "question_encoder" in kwargs and "generator" in kwargs
											), "Config has to be initialized with question_encoder and generator config"
											snake_case_					:		List[Any] 					=					kwargs.pop("""question_encoder"""       )
											snake_case_					:		Tuple 					=					question_encoder_config.pop("""model_type"""       )
											snake_case_					:		List[str] 					=					kwargs.pop("""generator"""       )
											snake_case_					:		List[str] 					=					decoder_config.pop("""model_type"""       )

											from ..auto.configuration_auto import AutoConfig

											snake_case_					:		List[str] 					=					AutoConfig.for_model(lowercase__   ,		**lowercase__       )
											snake_case_					:		Tuple 					=					AutoConfig.for_model(lowercase__   ,		**lowercase__       )

											snake_case_					:		int 					=					reduce_loss
											snake_case_					:		Optional[int] 					=					label_smoothing
											snake_case_					:		Dict 					=					exclude_bos_score
											snake_case_					:		Union[str, Any] 					=					do_marginalize

											snake_case_					:		Union[str, Any] 					=					title_sep
											snake_case_					:		int 					=					doc_sep
											snake_case_					:		int 					=					n_docs
											snake_case_					:		List[str] 					=					max_combined_length

											snake_case_					:		Tuple 					=					dataset
											snake_case_					:		int 					=					dataset_split
											snake_case_					:		str 					=					index_name

											snake_case_					:		List[str] 					=					retrieval_vector_size
											snake_case_					:		Dict 					=					retrieval_batch_size
											snake_case_					:		str 					=					passages_path
											snake_case_					:		Union[str, Any] 					=					index_path
											snake_case_					:		Tuple 					=					use_dummy_dataset

											snake_case_					:		Dict 					=					output_retrieved

											snake_case_					:		str 					=					do_deduplication

											snake_case_					:		Any 					=					use_cache

											if self.forced_eos_token_id is None:
																snake_case_					:		Any 					=					getattr(self.generator   ,		"""forced_eos_token_id"""   ,		lowercase__       )







						@classmethod
						def 						__UpperCamelCase							(cls   ,		lowercase__   ,		lowercase__   ,		**lowercase__       ):
											return cls(question_encoder=question_encoder_config.to_dict()   ,		generator=generator_config.to_dict()   ,		**lowercase__       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Optional[Any] 					=					copy.deepcopy(self.__dict__       )
											snake_case_					:		Any 					=					self.question_encoder.to_dict()
											snake_case_					:		Dict 					=					self.generator.to_dict()
											snake_case_					:		Union[str, Any] 					=					self.__class__.model_type
											return output




