





'''simple docstring'''






import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
      import faiss







@require_faiss
class 		UpperCAmelCase   (				lowercase_):


  """simple docstring"""







  def   UpperCamelCase__      (				self    :					Any  )     ->						List[Any]:
    _UpperCamelCase       			=tempfile.mkdtemp()
    _UpperCamelCase       			=8

    # DPR tok
    _UpperCamelCase       			=[
        '''[UNK]''',
        '''[CLS]''',
        '''[SEP]''',
        '''[PAD]''',
        '''[MASK]''',
        '''want''',
        '''##want''',
        '''##ed''',
        '''wa''',
        '''un''',
        '''runn''',
        '''##ing''',
        ''',''',
        '''low''',
        '''lowest''',
    ]
    _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''dpr_tokenizer'''  )
    os.makedirs(UpperCamelCase__							,	exist_ok=UpperCamelCase__  )
    _UpperCamelCase       			=os.path.join(UpperCamelCase__							,	DPR_VOCAB_FILES_NAMES['''vocab_file''']  )
    with open(self.vocab_file							,	'''w'''							,	encoding='''utf-8'''  ) as vocab_writer:
      vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )

    # BART tok
    _UpperCamelCase       			=[
        '''l''',
        '''o''',
        '''w''',
        '''e''',
        '''r''',
        '''s''',
        '''t''',
        '''i''',
        '''d''',
        '''n''',
        '''\u0120''',
        '''\u0120l''',
        '''\u0120n''',
        '''\u0120lo''',
        '''\u0120low''',
        '''er''',
        '''\u0120lowest''',
        '''\u0120newer''',
        '''\u0120wider''',
        '''<unk>''',
    ]
    _UpperCamelCase       			=dict(zip(UpperCamelCase__							,	range(len(UpperCamelCase__  )  )  )  )
    _UpperCamelCase       			=['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
    _UpperCamelCase       			={'''unk_token''': '''<unk>'''}

    _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''bart_tokenizer'''  )
    os.makedirs(UpperCamelCase__							,	exist_ok=UpperCamelCase__  )
    _UpperCamelCase       			=os.path.join(UpperCamelCase__							,	BART_VOCAB_FILES_NAMES['''vocab_file''']  )
    _UpperCamelCase       			=os.path.join(UpperCamelCase__							,	BART_VOCAB_FILES_NAMES['''merges_file''']  )
    with open(self.vocab_file							,	'''w'''							,	encoding='''utf-8'''  ) as fp:
      fp.write(json.dumps(UpperCamelCase__  ) + '''\n'''  )
    with open(self.merges_file							,	'''w'''							,	encoding='''utf-8'''  ) as fp:
      fp.write('''\n'''.join(UpperCamelCase__  )  )


  def   UpperCamelCase__      (				self    :					Union[str, Any]  )     ->						DPRQuestionEncoderTokenizer:
    return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname							,	'''dpr_tokenizer'''  )  )


  def   UpperCamelCase__      (				self    :					List[Any]  )     ->						DPRContextEncoderTokenizer:
    return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname							,	'''dpr_tokenizer'''  )  )


  def   UpperCamelCase__      (				self    :					int  )     ->						BartTokenizer:
    return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname							,	'''bart_tokenizer'''  )  )


  def   UpperCamelCase__      (				self    :					Dict  )     ->						Tuple:
    shutil.rmtree(self.tmpdirname  )


  def   UpperCamelCase__      (				self    :					List[Any]  )     ->						Optional[int]:
    _UpperCamelCase       			=Dataset.from_dict(
        {
            '''id''': ['''0''', '''1'''],
            '''text''': ['''foo''', '''bar'''],
            '''title''': ['''Foo''', '''Bar'''],
            '''embeddings''': [np.ones(self.retrieval_vector_size  ), 2 * np.ones(self.retrieval_vector_size  )],
        }  )
    dataset.add_faiss_index('''embeddings'''							,	string_factory='''Flat'''							,	metric_type=faiss.METRIC_INNER_PRODUCT  )
    return dataset


  def   UpperCamelCase__      (				self    :					Dict  )     ->						Union[str, Any]:
    _UpperCamelCase       			=self.get_dummy_dataset()
    _UpperCamelCase       			=RagConfig(
        retrieval_vector_size=self.retrieval_vector_size							,	question_encoder=DPRConfig().to_dict()							,	generator=BartConfig().to_dict()							,	)
    with patch('''transformers.models.rag.retrieval_rag.load_dataset'''  ) as mock_load_dataset:
      _UpperCamelCase       			=dataset
      _UpperCamelCase       			=RagRetriever(
          UpperCamelCase__							,	question_encoder_tokenizer=self.get_dpr_tokenizer()							,	generator_tokenizer=self.get_bart_tokenizer()							,	)
    return retriever


  def   UpperCamelCase__      (				self    :					Optional[Any]							,	UpperCamelCase__    :					bool  )     ->						List[Any]:
    _UpperCamelCase       			=self.get_dummy_dataset()
    _UpperCamelCase       			=RagConfig(
        retrieval_vector_size=self.retrieval_vector_size							,	question_encoder=DPRConfig().to_dict()							,	generator=BartConfig().to_dict()							,	index_name='''custom'''							,	)
    if from_disk:
      _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''dataset'''  )
      _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''index.faiss'''  )
      dataset.get_index('''embeddings'''  ).save(os.path.join(self.tmpdirname							,	'''index.faiss'''  )  )
      dataset.drop_index('''embeddings'''  )
      dataset.save_to_disk(os.path.join(self.tmpdirname							,	'''dataset'''  )  )
      del dataset
      _UpperCamelCase       			=RagRetriever(
          UpperCamelCase__							,	question_encoder_tokenizer=self.get_dpr_tokenizer()							,	generator_tokenizer=self.get_bart_tokenizer()							,	)
    else:
      _UpperCamelCase       			=RagRetriever(
          UpperCamelCase__							,	question_encoder_tokenizer=self.get_dpr_tokenizer()							,	generator_tokenizer=self.get_bart_tokenizer()							,	index=CustomHFIndex(config.retrieval_vector_size							,	UpperCamelCase__  )							,	)
    return retriever


  def   UpperCamelCase__      (				self    :					Any  )     ->						Tuple:
    _UpperCamelCase       			=Dataset.from_dict(
        {
            '''id''': ['''0''', '''1'''],
            '''text''': ['''foo''', '''bar'''],
            '''title''': ['''Foo''', '''Bar'''],
            '''embeddings''': [np.ones(self.retrieval_vector_size + 1  ), 2 * np.ones(self.retrieval_vector_size + 1  )],
        }  )
    dataset.add_faiss_index('''embeddings'''							,	string_factory='''Flat'''							,	metric_type=faiss.METRIC_INNER_PRODUCT  )

    _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''hf_bert_base.hnswSQ8_correct_phi_128.c_index'''  )
    dataset.save_faiss_index('''embeddings'''							,	index_file_name + '''.index.dpr'''  )
    pickle.dump(dataset['''id''']							,	open(index_file_name + '''.index_meta.dpr'''							,	'''wb'''  )  )

    _UpperCamelCase       			=os.path.join(self.tmpdirname							,	'''psgs_w100.tsv.pkl'''  )
    _UpperCamelCase       			={sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset}
    pickle.dump(UpperCamelCase__							,	open(UpperCamelCase__							,	'''wb'''  )  )

    _UpperCamelCase       			=RagConfig(
        retrieval_vector_size=self.retrieval_vector_size							,	question_encoder=DPRConfig().to_dict()							,	generator=BartConfig().to_dict()							,	index_name='''legacy'''							,	index_path=self.tmpdirname							,	)
    _UpperCamelCase       			=RagRetriever(
        UpperCamelCase__							,	question_encoder_tokenizer=self.get_dpr_tokenizer()							,	generator_tokenizer=self.get_bart_tokenizer()  )
    return retriever


  def   UpperCamelCase__      (				self    :					List[str]  )     ->						Optional[int]:
    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_canonical_hf_index_retriever()
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=UpperCamelCase__  )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertEqual(len(UpperCamelCase__  )							,	2  )
    self.assertEqual(sorted(doc_dicts[0]  )							,	['''embeddings''', '''id''', '''text''', '''title''']  )
    self.assertEqual(len(doc_dicts[0]['''id''']  )							,	UpperCamelCase__  )
    self.assertEqual(doc_dicts[0]['''id'''][0]							,	'''1'''  )  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]['''id'''][0]							,	'''0'''  )  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist()							,	[[1], [0]]  )


  def   UpperCamelCase__      (				self    :					Tuple  )     ->						Union[str, Any]:
    _UpperCamelCase       			=self.get_dummy_canonical_hf_index_retriever()
    with tempfile.TemporaryDirectory() as tmp_dirname:
      with patch('''transformers.models.rag.retrieval_rag.load_dataset'''  ) as mock_load_dataset:
        _UpperCamelCase       			=self.get_dummy_dataset()
        retriever.save_pretrained(UpperCamelCase__  )
        _UpperCamelCase       			=RagRetriever.from_pretrained(UpperCamelCase__  )
        self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
        _UpperCamelCase       			=np.array(
            [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
        _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=1  )
        self.assertTrue(out is not None  )


  def   UpperCamelCase__      (				self    :					Tuple  )     ->						int:
    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__  )
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=UpperCamelCase__  )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertEqual(len(UpperCamelCase__  )							,	2  )
    self.assertEqual(sorted(doc_dicts[0]  )							,	['''embeddings''', '''id''', '''text''', '''title''']  )
    self.assertEqual(len(doc_dicts[0]['''id''']  )							,	UpperCamelCase__  )
    self.assertEqual(doc_dicts[0]['''id'''][0]							,	'''1'''  )  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]['''id'''][0]							,	'''0'''  )  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist()							,	[[1], [0]]  )


  def   UpperCamelCase__      (				self    :					str  )     ->						str:
    _UpperCamelCase       			=self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__  )
    with tempfile.TemporaryDirectory() as tmp_dirname:
      retriever.save_pretrained(UpperCamelCase__  )
      _UpperCamelCase       			=RagRetriever.from_pretrained(UpperCamelCase__  )
      self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
      _UpperCamelCase       			=np.array(
          [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
      _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=1  )
      self.assertTrue(out is not None  )


  def   UpperCamelCase__      (				self    :					int  )     ->						Any:
    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__  )
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=UpperCamelCase__  )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertEqual(len(UpperCamelCase__  )							,	2  )
    self.assertEqual(sorted(doc_dicts[0]  )							,	['''embeddings''', '''id''', '''text''', '''title''']  )
    self.assertEqual(len(doc_dicts[0]['''id''']  )							,	UpperCamelCase__  )
    self.assertEqual(doc_dicts[0]['''id'''][0]							,	'''1'''  )  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]['''id'''][0]							,	'''0'''  )  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist()							,	[[1], [0]]  )


  def   UpperCamelCase__      (				self    :					List[Any]  )     ->						Optional[int]:
    _UpperCamelCase       			=self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__  )
    with tempfile.TemporaryDirectory() as tmp_dirname:
      retriever.save_pretrained(UpperCamelCase__  )
      _UpperCamelCase       			=RagRetriever.from_pretrained(UpperCamelCase__  )
      self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
      _UpperCamelCase       			=np.array(
          [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
      _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=1  )
      self.assertTrue(out is not None  )


  def   UpperCamelCase__      (				self    :					Optional[Any]  )     ->						Union[str, Any]:
    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_legacy_index_retriever()
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=UpperCamelCase__  )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertEqual(len(UpperCamelCase__  )							,	2  )
    self.assertEqual(sorted(doc_dicts[0]  )							,	['''text''', '''title''']  )
    self.assertEqual(len(doc_dicts[0]['''text''']  )							,	UpperCamelCase__  )
    self.assertEqual(doc_dicts[0]['''text'''][0]							,	'''bar'''  )  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]['''text'''][0]							,	'''foo'''  )  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist()							,	[[1], [0]]  )


  def   UpperCamelCase__      (				self    :					Optional[int]  )     ->						Dict:
    _UpperCamelCase       			=self.get_dummy_legacy_index_retriever()
    with tempfile.TemporaryDirectory() as tmp_dirname:
      retriever.save_pretrained(UpperCamelCase__  )
      _UpperCamelCase       			=RagRetriever.from_pretrained(UpperCamelCase__  )
      self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
      _UpperCamelCase       			=np.array(
          [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
      _UpperCamelCase       			=retriever.retrieve(UpperCamelCase__							,	n_docs=1  )
      self.assertTrue(out is not None  )


  @require_torch
  @require_tokenizers
  @require_sentencepiece
  def   UpperCamelCase__      (				self    :					Any  )     ->						Optional[Any]:
    import torch

    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_canonical_hf_index_retriever()
    _UpperCamelCase       			=[[5, 7], [10, 11]]
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase       			=retriever(UpperCamelCase__							,	UpperCamelCase__							,	prefix=retriever.config.generator.prefix							,	n_docs=UpperCamelCase__  )
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=(
        out['''context_input_ids'''],
        out['''context_attention_mask'''],
        out['''retrieved_doc_embeds'''],
    )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
    self.assertIsInstance(UpperCamelCase__							,	UpperCamelCase__  )
    self.assertIsInstance(UpperCamelCase__							,	np.ndarray  )

    _UpperCamelCase       			=retriever(
        UpperCamelCase__							,	UpperCamelCase__							,	prefix=retriever.config.generator.prefix							,	n_docs=UpperCamelCase__							,	return_tensors='''pt'''							,	)
    _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase       			=(  # noqa: F841
        out['''context_input_ids'''],
        out['''context_attention_mask'''],
        out['''retrieved_doc_embeds'''],
        out['''doc_ids'''],
    )
    self.assertEqual(retrieved_doc_embeds.shape							,	(2, n_docs, self.retrieval_vector_size)  )
    self.assertIsInstance(UpperCamelCase__							,	torch.Tensor  )
    self.assertIsInstance(UpperCamelCase__							,	torch.Tensor  )
    self.assertIsInstance(UpperCamelCase__							,	torch.Tensor  )




  @require_torch
  @require_tokenizers
  @require_sentencepiece
  def   UpperCamelCase__      (				self    :					Tuple  )     ->						Optional[Any]:
    _UpperCamelCase       			=self.get_dpr_ctx_encoder_tokenizer()
    _UpperCamelCase       			=1
    _UpperCamelCase       			=self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__  )
    retriever.set_ctx_encoder_tokenizer(UpperCamelCase__  )

    _UpperCamelCase       			=[[5, 7], [10, 11]]
    _UpperCamelCase       			=np.array(
        [np.ones(self.retrieval_vector_size  ), -np.ones(self.retrieval_vector_size  )]							,	dtype=np.floataa  )
    _UpperCamelCase       			=retriever(UpperCamelCase__							,	UpperCamelCase__							,	prefix=retriever.config.generator.prefix							,	n_docs=UpperCamelCase__  )

    self.assertEqual(
        len(UpperCamelCase__  )							,	6  )  # check whether the retriever output consist of 6 attributes including tokenized docs
    self.assertEqual(
        all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''')  )							,	UpperCamelCase__  )  # check for doc token related keys in dictionary.













'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import PoolFormerImageProcessor







class 		UpperCAmelCase   (				unittest.TestCase):


  """simple docstring"""







  def __init__(				self    :					Optional[int]							,	UpperCamelCase__    :					Union[str, Any]							,	UpperCamelCase__    :					Any=7							,	UpperCamelCase__    :					List[Any]=3							,	UpperCamelCase__    :					Dict=30							,	UpperCamelCase__    :					Union[str, Any]=400							,	UpperCamelCase__    :					List[Any]=True							,	UpperCamelCase__    :					List[str]=None							,	UpperCamelCase__    :					List[str]=0.9							,	UpperCamelCase__    :					Any=None							,	UpperCamelCase__    :					Any=True							,	UpperCamelCase__    :					Optional[Any]=[0.5, 0.5, 0.5]							,	UpperCamelCase__    :					List[str]=[0.5, 0.5, 0.5]							,	)     ->						Dict:
    _UpperCamelCase       			=size if size is not None else {'''shortest_edge''': 30}
    _UpperCamelCase       			=crop_size if crop_size is not None else {'''height''': 30, '''width''': 30}
    _UpperCamelCase       			=parent
    _UpperCamelCase       			=batch_size
    _UpperCamelCase       			=num_channels
    _UpperCamelCase       			=min_resolution
    _UpperCamelCase       			=max_resolution
    _UpperCamelCase       			=do_resize_and_center_crop
    _UpperCamelCase       			=size
    _UpperCamelCase       			=crop_pct
    _UpperCamelCase       			=crop_size
    _UpperCamelCase       			=do_normalize
    _UpperCamelCase       			=image_mean
    _UpperCamelCase       			=image_std




  def   UpperCamelCase__      (				self    :					str  )     ->						Union[str, Any]:
    return {
        "size": self.size,
        "do_resize_and_center_crop": self.do_resize_and_center_crop,
        "crop_pct": self.crop_pct,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
    }







@require_torch
@require_vision
class 		UpperCAmelCase   (				lowercase_   ,     unittest.TestCase):


  """simple docstring"""







  lowerCAmelCase_					=				PoolFormerImageProcessor if is_vision_available() else None


  def   UpperCamelCase__      (				self    :					Optional[int]  )     ->						int:
    _UpperCamelCase       			=PoolFormerImageProcessingTester(self  )


  @property
  def   UpperCamelCase__      (				self    :					Tuple  )     ->						Optional[int]:
    return self.image_processor_tester.prepare_image_processor_dict()


  def   UpperCamelCase__      (				self    :					Optional[Any]  )     ->						int:
    _UpperCamelCase       			=self.image_processing_class(**self.image_processor_dict  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''do_resize_and_center_crop'''  )  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''size'''  )  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''crop_pct'''  )  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''do_normalize'''  )  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''image_mean'''  )  )
    self.assertTrue(hasattr(UpperCamelCase__							,	'''image_std'''  )  )


  def   UpperCamelCase__      (				self    :					Any  )     ->						Dict:
    _UpperCamelCase       			=self.image_processing_class.from_dict(self.image_processor_dict  )
    self.assertEqual(image_processor.size							,	{'''shortest_edge''': 30}  )
    self.assertEqual(image_processor.crop_size							,	{'''height''': 30, '''width''': 30}  )

    _UpperCamelCase       			=self.image_processing_class.from_dict(self.image_processor_dict							,	size=42							,	crop_size=84  )
    self.assertEqual(image_processor.size							,	{'''shortest_edge''': 42}  )
    self.assertEqual(image_processor.crop_size							,	{'''height''': 84, '''width''': 84}  )


  def   UpperCamelCase__      (				self    :					Dict  )     ->						Optional[Any]:
    pass


  def   UpperCamelCase__      (				self    :					Union[str, Any]  )     ->						List[Any]:
    # Initialize image_processing
    _UpperCamelCase       			=self.image_processing_class(**self.image_processor_dict  )
    # create random PIL images
    _UpperCamelCase       			=prepare_image_inputs(self.image_processor_tester							,	equal_resolution=UpperCamelCase__  )
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__							,	Image.Image  )

    # Test not batched input
    _UpperCamelCase       			=image_processing(image_inputs[0]							,	return_tensors='''pt'''  ).pixel_values

    self.assertEqual(
        encoded_images.shape							,	(
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)

    # Test batched
    _UpperCamelCase       			=image_processing(UpperCamelCase__							,	return_tensors='''pt'''  ).pixel_values
    self.assertEqual(
        encoded_images.shape							,	(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)


  def   UpperCamelCase__      (				self    :					Union[str, Any]  )     ->						Optional[int]:
    # Initialize image_processing
    _UpperCamelCase       			=self.image_processing_class(**self.image_processor_dict  )
    # create random numpy tensors
    _UpperCamelCase       			=prepare_image_inputs(self.image_processor_tester							,	equal_resolution=UpperCamelCase__							,	numpify=UpperCamelCase__  )
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__							,	np.ndarray  )

    # Test not batched input
    _UpperCamelCase       			=image_processing(image_inputs[0]							,	return_tensors='''pt'''  ).pixel_values
    self.assertEqual(
        encoded_images.shape							,	(
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)

    # Test batched
    _UpperCamelCase       			=image_processing(UpperCamelCase__							,	return_tensors='''pt'''  ).pixel_values
    self.assertEqual(
        encoded_images.shape							,	(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)




  def   UpperCamelCase__      (				self    :					str  )     ->						List[Any]:
    # Initialize image_processing
    _UpperCamelCase       			=self.image_processing_class(**self.image_processor_dict  )
    # create random PyTorch tensors
    _UpperCamelCase       			=prepare_image_inputs(self.image_processor_tester							,	equal_resolution=UpperCamelCase__							,	torchify=UpperCamelCase__  )
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__							,	torch.Tensor  )

    # Test not batched input
    _UpperCamelCase       			=image_processing(image_inputs[0]							,	return_tensors='''pt'''  ).pixel_values
    self.assertEqual(
        encoded_images.shape							,	(
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)

    # Test batched
    _UpperCamelCase       			=image_processing(UpperCamelCase__							,	return_tensors='''pt'''  ).pixel_values
    self.assertEqual(
        encoded_images.shape							,	(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )							,	)






