






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__      :	str       	=      logging.get_logger(__name__)






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






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase):
   UpperCamelCase_									=     to_pil_image(_A)
   UpperCamelCase_		,      UpperCamelCase_									=     pil_image.size
   UpperCamelCase_									=     pytesseract.image_to_data(_A    ,      lang=_A    ,      output_type='dict'    ,      config=_A)
   UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     data['text'], data['left'], data['top'], data['width'], data['height']

   # filter empty words and corresponding coordinates
   UpperCamelCase_									=     [idx for idx, word in enumerate(_A) if not word.strip()]
   UpperCamelCase_									=     [word for idx, word in enumerate(_A) if idx not in irrelevant_indices]
   UpperCamelCase_									=     [coord for idx, coord in enumerate(_A) if idx not in irrelevant_indices]
   UpperCamelCase_									=     [coord for idx, coord in enumerate(_A) if idx not in irrelevant_indices]
   UpperCamelCase_									=     [coord for idx, coord in enumerate(_A) if idx not in irrelevant_indices]
   UpperCamelCase_									=     [coord for idx, coord in enumerate(_A) if idx not in irrelevant_indices]

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

   # finally, normalize the bounding boxes
   UpperCamelCase_									=     []
   for box in actual_boxes:
      normalized_boxes.append(normalize_box(_A    ,      _A    ,      _A))

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

   return words, normalized_boxes


class 						_a       (  lowerCAmelCase__    ):






  """simple docstring"""





  A_						=   ["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:
     super().__init__(**_SCREAMING_SNAKE_CASE )
     UpperCamelCase_									=     size if size is not None else {'height': 224, 'width': 224}
     UpperCamelCase_									=     get_size_dict(_SCREAMING_SNAKE_CASE )

     UpperCamelCase_									=     do_resize
     UpperCamelCase_									=     size
     UpperCamelCase_									=     resample
     UpperCamelCase_									=     do_rescale
     UpperCamelCase_									=     rescale_value
     UpperCamelCase_									=     do_normalize
     UpperCamelCase_									=     image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     UpperCamelCase_									=     image_std if image_std is not None else IMAGENET_STANDARD_STD
     UpperCamelCase_									=     apply_ocr
     UpperCamelCase_									=     ocr_lang
     UpperCamelCase_									=     tesseract_config




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = PILImageResampling.BILINEAR		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)			-> np.ndarray:
     UpperCamelCase_									=     get_size_dict(_SCREAMING_SNAKE_CASE )
     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_									=     (size['height'], size['width'])
     return resize(_SCREAMING_SNAKE_CASE		,		size=_SCREAMING_SNAKE_CASE		,		resample=_SCREAMING_SNAKE_CASE		,		data_format=_SCREAMING_SNAKE_CASE		,		**_SCREAMING_SNAKE_CASE )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)			-> np.ndarray:
     return rescale(_SCREAMING_SNAKE_CASE		,		scale=_SCREAMING_SNAKE_CASE		,		data_format=_SCREAMING_SNAKE_CASE		,		**_SCREAMING_SNAKE_CASE )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)			-> np.ndarray:
     return normalize(_SCREAMING_SNAKE_CASE		,		mean=_SCREAMING_SNAKE_CASE		,		std=_SCREAMING_SNAKE_CASE		,		data_format=_SCREAMING_SNAKE_CASE		,		**_SCREAMING_SNAKE_CASE )




  def    _UpperCAmelCase     (     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:
     UpperCamelCase_									=     do_resize if do_resize is not None else self.do_resize
     UpperCamelCase_									=     size if size is not None else self.size
     UpperCamelCase_									=     get_size_dict(_SCREAMING_SNAKE_CASE )
     UpperCamelCase_									=     resample if resample is not None else self.resample
     UpperCamelCase_									=     do_rescale if do_rescale is not None else self.do_rescale
     UpperCamelCase_									=     rescale_factor if rescale_factor is not None else self.rescale_factor
     UpperCamelCase_									=     do_normalize if do_normalize is not None else self.do_normalize
     UpperCamelCase_									=     image_mean if image_mean is not None else self.image_mean
     UpperCamelCase_									=     image_std if image_std is not None else self.image_std
     UpperCamelCase_									=     apply_ocr if apply_ocr is not None else self.apply_ocr
     UpperCamelCase_									=     ocr_lang if ocr_lang is not None else self.ocr_lang
     UpperCamelCase_									=     tesseract_config if tesseract_config is not None else self.tesseract_config

     UpperCamelCase_									=     make_list_of_images(_SCREAMING_SNAKE_CASE )

     if not valid_images(_SCREAMING_SNAKE_CASE ):
        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_									=     [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images]

     # Tesseract OCR to get words + normalized bounding boxes
     if apply_ocr:
        requires_backends(self		,		'pytesseract' )
        UpperCamelCase_									=     []
        UpperCamelCase_									=     []
        for image in images:
           UpperCamelCase_		,      UpperCamelCase_									=     apply_tesseract(_SCREAMING_SNAKE_CASE		,		_SCREAMING_SNAKE_CASE		,		_SCREAMING_SNAKE_CASE )
           words_batch.append(_SCREAMING_SNAKE_CASE )
           boxes_batch.append(_SCREAMING_SNAKE_CASE )

     if do_resize:
        UpperCamelCase_									=     [self.resize(image=_SCREAMING_SNAKE_CASE		,		size=_SCREAMING_SNAKE_CASE		,		resample=_SCREAMING_SNAKE_CASE ) for image in images]

     if do_rescale:
        UpperCamelCase_									=     [self.rescale(image=_SCREAMING_SNAKE_CASE		,		scale=_SCREAMING_SNAKE_CASE ) for image in images]

     if do_normalize:
        UpperCamelCase_									=     [self.normalize(image=_SCREAMING_SNAKE_CASE		,		mean=_SCREAMING_SNAKE_CASE		,		std=_SCREAMING_SNAKE_CASE ) for image in images]

     UpperCamelCase_									=     [to_channel_dimension_format(_SCREAMING_SNAKE_CASE		,		_SCREAMING_SNAKE_CASE ) for image in images]

     UpperCamelCase_									=     BatchFeature(data={'pixel_values': images}		,		tensor_type=_SCREAMING_SNAKE_CASE )

     if apply_ocr:
        UpperCamelCase_									=     words_batch
        UpperCamelCase_									=     boxes_batch
     return data













import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


snake_case__      :	str       	=      logging.getLogger(__name__)


@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None




@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None
  A_						=   None


if is_torch_available():
 import torch
 from torch.utils.data import Dataset


 class 						_a       (  UpperCAmelCase__    ):






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> Any:
      UpperCamelCase_									=     hans_processors[task]()

      UpperCamelCase_									=     os.path.join(
          _UpperCAmelCase		,		'cached_{}_{}_{}_{}'.format(
              'dev' if evaluate else 'train'		,		tokenizer.__class__.__name__		,		str(_UpperCAmelCase )		,		_UpperCAmelCase		,		)		,		)
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      UpperCamelCase_									=     cached_features_file + '.lock'
      with FileLock(_UpperCAmelCase ):
         if os.path.exists(_UpperCAmelCase ) and not overwrite_cache:
            logger.info(f"""Loading features from cached file {cached_features_file}""" )
            UpperCamelCase_									=     torch.load(_UpperCAmelCase )
         else:
            logger.info(f"""Creating features from dataset file at {data_dir}""" )

            UpperCamelCase_									=     (
                processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
            )

            logger.info('Training examples: %s'		,		len(_UpperCAmelCase ) )
            UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
            logger.info('Saving features into cached file %s'		,		_UpperCAmelCase )
            torch.save(self.features		,		_UpperCAmelCase )




   def __len__(     self )			-> Dict:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> Dict:
      return self.label_list


if is_tf_available():
 import tensorflow as tf


 class 						_a       :






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = 128		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> int:
      UpperCamelCase_									=     hans_processors[task]()
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      UpperCamelCase_									=     processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
      UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

      def gen():
         for ex_index, ex in tqdm.tqdm(enumerate(self.features )		,		desc='convert examples to features' ):
            if ex_index % 10000 == 0:
               logger.info('Writing example %d of %d' % (ex_index, len(_UpperCAmelCase )) )

            yield (
                {
                    "example_id": 0,
                    "input_ids": ex.input_ids,
                    "attention_mask": ex.attention_mask,
                    "token_type_ids": ex.token_type_ids,
                },
                ex.label,
            )

      UpperCamelCase_									=     tf.data.Dataset.from_generator(
          _UpperCAmelCase		,		(
              {
                  'example_id': tf.intaa,
                  'input_ids': tf.intaa,
                  'attention_mask': tf.intaa,
                  'token_type_ids': tf.intaa,
              },
              tf.intaa,
          )		,		(
              {
                  'example_id': tf.TensorShape([] ),
                  'input_ids': tf.TensorShape([None, None] ),
                  'attention_mask': tf.TensorShape([None, None] ),
                  'token_type_ids': tf.TensorShape([None, None] ),
              },
              tf.TensorShape([] ),
          )		,		)




   def    _UpperCAmelCase     (     self )			-> List[str]:
      return self.dataset




   def __len__(     self )			-> str:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> int:
      return self.label_list


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Tuple:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_train_set.txt' ) )		,		'train' )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Dict:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_evaluation_set.txt' ) )		,		'dev' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return ["contradiction", "entailment", "neutral"]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     []
     for i, line in enumerate(_UpperCAmelCase ):
        if i == 0:
           continue
        UpperCamelCase_									=     '%s-%s' % (set_type, line[0])
        UpperCamelCase_									=     line[5]
        UpperCamelCase_									=     line[6]
        UpperCamelCase_									=     line[7][2:] if line[7].startswith('ex' ) else line[7]
        UpperCamelCase_									=     line[0]
        examples.append(InputExample(guid=_UpperCAmelCase		,		text_a=_UpperCAmelCase		,		text_b=_UpperCAmelCase		,		label=_UpperCAmelCase		,		pairID=_UpperCAmelCase ) )
     return examples






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase    ,      ):
   UpperCamelCase_									=     {label: i for i, label in enumerate(__lowercase)}

   UpperCamelCase_									=     []
   for ex_index, example in tqdm.tqdm(enumerate(__lowercase)    ,      desc='convert examples to features'):
      if ex_index % 10000 == 0:
         logger.info('Writing example %d' % (ex_index))

      UpperCamelCase_									=     tokenizer(
          example.text_a    ,      example.text_b    ,      add_special_tokens=__lowercase    ,      max_length=__lowercase    ,      padding='max_length'    ,      truncation=__lowercase    ,      return_overflowing_tokens=__lowercase    ,      )

      UpperCamelCase_									=     label_map[example.label] if example.label in label_map else 0

      UpperCamelCase_									=     int(example.pairID)

      features.append(InputFeatures(**__lowercase    ,      label=__lowercase    ,      pairID=__lowercase))

   for i, example in enumerate(examples[:5]):
      logger.info('*** Example ***')
      logger.info(f"""guid: {example}""")
      logger.info(f"""features: {features[i]}""")

   return features


snake_case__      :	List[str]       	=      {
    """hans""": 3,
}

snake_case__      :	Union[str, Any]       	=      {
    """hans""": HansProcessor,
}





