

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
	from transformers import (
	    FlaxBertModel,
	    FlaxCLIPVisionModel,
	    FlaxVisionTextDualEncoderModel,
	    FlaxViTModel,
	    VisionTextDualEncoderConfig,
	    VisionTextDualEncoderProcessor,
	)
	from transformers.modeling_flax_pytorch_utils import (
	    convert_pytorch_state_dict_to_flax,
	    load_flax_weights_in_pytorch_model,
	)


if is_torch_available():
	import torch

	from transformers import VisionTextDualEncoderModel

if is_vision_available():
	from PIL import Image

def 						UpperCamelCase					(lowercase_: Optional[int]					)     ->      Union[str, Any]:
	if isinstance(lowercase_    ,      collections.abc.Iterable					):
		return x
	return (x, x)



@require_flax
class     _a						:


					'''simple docstring'''






					def   __A			( self    ,       A__    ,       A__			):
						pass






					def   __A			( self			):
						pass






					def   __A			( self			):
						pass






					def   __A			( self    ,       A__    ,       A__    ,       A__			):
						A__							:    Optional[int]        =		np.abs((a - b)			).max()
						self.assertLessEqual(A__    ,       A__    ,       F"""Difference between torch and flax is {diff} (>= {tol})."""			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						A__							:    List[str]        =		VisionTextDualEncoderConfig.from_vision_text_configs(A__    ,       A__			)

						A__							:    Optional[int]        =		FlaxVisionTextDualEncoderModel(A__			)

						A__							:    List[str]        =		model(input_ids=A__    ,       pixel_values=A__    ,       attention_mask=A__			)

						self.assertEqual(output["""text_embeds"""].shape    ,       (input_ids.shape[0], config.projection_dim)			)
						self.assertEqual(output["""image_embeds"""].shape    ,       (pixel_values.shape[0], config.projection_dim)			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						A__   ,   A__							:    int        =		self.get_vision_text_model(A__    ,       A__			)
						A__							:    List[str]        =		{"""vision_model""": vision_model, """text_model""": text_model}
						A__							:    str        =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__			)

						A__							:    str        =		model(input_ids=A__    ,       pixel_values=A__    ,       attention_mask=A__			)

						self.assertEqual(output["""text_embeds"""].shape    ,       (input_ids.shape[0], model.config.projection_dim)			)
						self.assertEqual(output["""image_embeds"""].shape    ,       (pixel_values.shape[0], model.config.projection_dim)			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						A__   ,   A__							:    List[str]        =		self.get_vision_text_model(A__    ,       A__			)
						A__							:    Any        =		{"""vision_model""": vision_model, """text_model""": text_model}
						A__							:    Dict        =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__			)

						A__							:    List[Any]        =		model(input_ids=A__    ,       pixel_values=A__    ,       attention_mask=A__			)
						A__							:    List[Any]        =		output[0]

						with tempfile.TemporaryDirectory() as tmpdirname:
							model.save_pretrained(A__			)
							A__							:    Dict        =		FlaxVisionTextDualEncoderModel.from_pretrained(A__			)

							A__							:    List[str]        =		model(input_ids=A__    ,       pixel_values=A__    ,       attention_mask=A__			)
							A__							:    Dict        =		after_output[0]
							A__							:    Optional[int]        =		np.amax(np.abs(out_a - out_a			)			)
							self.assertLessEqual(A__    ,       1e-3			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						A__   ,   A__							:    Dict        =		self.get_vision_text_model(A__    ,       A__			)
						A__							:    List[str]        =		{"""vision_model""": vision_model, """text_model""": text_model}
						A__							:    Optional[int]        =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__			)

						A__							:    Optional[int]        =		model(
						    input_ids=A__    ,       pixel_values=A__    ,       attention_mask=A__    ,       output_attentions=A__			)

						A__							:    str        =		output.vision_model_output.attentions
						self.assertEqual(len(A__			)    ,       vision_config.num_hidden_layers			)

						# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
						A__							:    Optional[int]        =		to_atuple(vision_model.config.image_size			)
						A__							:    Optional[int]        =		to_atuple(vision_model.config.patch_size			)
						A__							:    List[str]        =		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						A__							:    Dict        =		num_patches + 1
						self.assertEqual(vision_attentions[0].shape[-3:]    ,       (vision_config.num_attention_heads, seq_len, seq_len)			)

						A__							:    str        =		output.text_model_output.attentions
						self.assertEqual(len(A__			)    ,       text_config.num_hidden_layers			)

						self.assertEqual(
						    text_attentions[0].shape[-3:]    ,       (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])    ,       )






					def   __A			( self    ,       A__    ,       A__    ,       A__			):
						pt_model.to(A__			)
						pt_model.eval()

						# prepare inputs
						A__							:    Union[str, Any]        =		inputs_dict
						A__							:    Dict        =		{k: torch.tensor(v.tolist()			) for k, v in flax_inputs.items()}

						with torch.no_grad():
							A__							:    Tuple        =		pt_model(**A__			).to_tuple()

						A__							:    str        =		fx_model(**A__			).to_tuple()
						self.assertEqual(len(A__			)    ,       len(A__			)    ,       """Output lengths differ between Flax and PyTorch"""			)
						for fx_output, pt_output in zip(fx_outputs[:4]    ,       pt_outputs[:4]			):
							self.assert_almost_equals(A__    ,       pt_output.numpy()    ,       4e-2			)

						# PT -> Flax
						with tempfile.TemporaryDirectory() as tmpdirname:
							pt_model.save_pretrained(A__			)
							A__							:    Any        =		FlaxVisionTextDualEncoderModel.from_pretrained(A__    ,       from_pt=A__			)

						A__							:    List[str]        =		fx_model_loaded(**A__			).to_tuple()
						self.assertEqual(len(A__			)    ,       len(A__			)    ,       """Output lengths differ between Flax and PyTorch"""			)
						for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]    ,       pt_outputs[:4]			):
							self.assert_almost_equals(A__    ,       pt_output.numpy()    ,       4e-2			)

						# Flax -> PT
						with tempfile.TemporaryDirectory() as tmpdirname:
							fx_model.save_pretrained(A__			)
							A__							:    List[str]        =		VisionTextDualEncoderModel.from_pretrained(A__    ,       from_flax=A__			)

						pt_model_loaded.to(A__			)
						pt_model_loaded.eval()

						with torch.no_grad():
							A__							:    int        =		pt_model_loaded(**A__			).to_tuple()

						self.assertEqual(len(A__			)    ,       len(A__			)    ,       """Output lengths differ between Flax and PyTorch"""			)
						for fx_output, pt_output_loaded in zip(fx_outputs[:4]    ,       pt_outputs_loaded[:4]			):
							self.assert_almost_equals(A__    ,       pt_output_loaded.numpy()    ,       4e-2			)






					def   __A			( self    ,       A__    ,       A__    ,       A__			):
						A__							:    Union[str, Any]        =		VisionTextDualEncoderConfig.from_vision_text_configs(A__    ,       A__			)

						A__							:    Optional[Any]        =		VisionTextDualEncoderModel(A__			)
						A__							:    Optional[Any]        =		FlaxVisionTextDualEncoderModel(A__			)

						A__							:    List[str]        =		convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,       A__			)
						A__							:    List[str]        =		fx_state

						self.check_pt_flax_equivalence(A__    ,       A__    ,       A__			)






					def   __A			( self    ,       A__    ,       A__    ,       A__			):
						A__							:    Union[str, Any]        =		VisionTextDualEncoderConfig.from_vision_text_configs(A__    ,       A__			)

						A__							:    Dict        =		VisionTextDualEncoderModel(A__			)
						A__							:    Dict        =		FlaxVisionTextDualEncoderModel(A__			)

						A__							:    str        =		load_flax_weights_in_pytorch_model(A__    ,       fx_model.params			)

						self.check_pt_flax_equivalence(A__    ,       A__    ,       A__			)






					def   __A			( self			):
						A__							:    int        =		self.prepare_config_and_inputs()
						self.check_model_from_pretrained_configs(**A__			)






					def   __A			( self			):
						A__							:    Any        =		self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_from_pretrained(**A__			)






					def   __A			( self			):
						A__							:    List[Any]        =		self.prepare_config_and_inputs()
						self.check_save_load(**A__			)






					def   __A			( self			):
						A__							:    int        =		self.prepare_config_and_inputs()
						self.check_vision_text_output_attention(**A__			)






					@is_pt_flax_cross_test
					def   __A			( self			):
						A__							:    Dict        =		self.prepare_config_and_inputs()
						A__							:    Optional[Any]        =		config_inputs_dict.pop("""vision_config"""			)
						A__							:    Dict        =		config_inputs_dict.pop("""text_config"""			)

						A__							:    Any        =		config_inputs_dict

						self.check_equivalence_pt_to_flax(A__    ,       A__    ,       A__			)
						self.check_equivalence_flax_to_pt(A__    ,       A__    ,       A__			)






					@slow
					def   __A			( self			):
						A__   ,   A__							:    str        =		self.get_pretrained_model_and_inputs()

						A__							:    List[str]        =		model_a(**A__			)
						A__							:    Optional[int]        =		outputs[0]

						with tempfile.TemporaryDirectory() as tmp_dirname:
							model_a.save_pretrained(A__			)
							A__							:    Tuple        =		FlaxVisionTextDualEncoderModel.from_pretrained(A__			)

							A__							:    Optional[Any]        =		model_a(**A__			)
							A__							:    Optional[Any]        =		after_outputs[0]
							A__							:    int        =		np.amax(np.abs(out_a - out_a			)			)
							self.assertLessEqual(A__    ,       1e-5			)



@require_flax
class     _a						(__magic_name__		,   unittest.TestCase				):


					'''simple docstring'''






					def   __A			( self			):
						A__							:    List[str]        =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """hf-internal-testing/tiny-random-vit"""    ,       """hf-internal-testing/tiny-bert"""    ,       vision_from_pt=A__    ,       text_from_pt=A__    ,       )
						A__							:    Union[str, Any]        =		13
						A__							:    str        =		floats_tensor(
						    [
						        batch_size,
						        model.config.vision_config.num_channels,
						        model.config.vision_config.image_size,
						        model.config.vision_config.image_size,
						    ]			)
						A__							:    List[str]        =		ids_tensor([batch_size, 4]    ,       model.config.text_config.vocab_size			)
						A__							:    int        =		random_attention_mask([batch_size, 4]			)
						A__							:    Optional[Any]        =		{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

						return model, inputs






					def   __A			( self    ,       A__    ,       A__			):
						A__							:    Optional[Any]        =		FlaxViTModel(A__			)
						A__							:    List[str]        =		FlaxBertModel(A__			)
						return vision_model, text_model






					def   __A			( self			):
						A__							:    Tuple        =		FlaxViTModelTester(self			)
						A__							:    List[str]        =		FlaxBertModelTester(self			)
						A__							:    int        =		vit_model_tester.prepare_config_and_inputs()
						A__							:    List[Any]        =		bert_model_tester.prepare_config_and_inputs()

						A__   ,   A__							:    List[Any]        =		vision_config_and_inputs

						A__   ,   A__   ,   A__   ,   A__							:    Any        =		text_config_and_inputs

						# make sure that cross attention layers are added
						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": attention_mask,
						    "input_ids": input_ids,
						    "token_type_ids": token_type_ids,
						}



@require_torch
class     _a						(__magic_name__		,   unittest.TestCase				):


					'''simple docstring'''






					def   __A			( self			):
						A__							:    Tuple        =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """hf-internal-testing/tiny-random-clip"""    ,       """hf-internal-testing/tiny-bert"""    ,       vision_from_pt=A__    ,       text_from_pt=A__    ,       )
						A__							:    Dict        =		13
						A__							:    List[Any]        =		floats_tensor(
						    [
						        batch_size,
						        model.config.vision_config.num_channels,
						        model.config.vision_config.image_size,
						        model.config.vision_config.image_size,
						    ]			)
						A__							:    List[Any]        =		ids_tensor([batch_size, 4]    ,       model.config.text_config.vocab_size			)
						A__							:    int        =		random_attention_mask([batch_size, 4]			)
						A__							:    Optional[Any]        =		{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

						return model, inputs






					def   __A			( self    ,       A__    ,       A__			):
						A__							:    int        =		FlaxCLIPVisionModel(A__			)
						A__							:    str        =		FlaxBertModel(A__			)
						return vision_model, text_model






					def   __A			( self			):
						A__							:    Union[str, Any]        =		FlaxCLIPVisionModelTester(self			)
						A__							:    Dict        =		FlaxBertModelTester(self			)
						A__							:    Dict        =		clip_model_tester.prepare_config_and_inputs()
						A__							:    Any        =		bert_model_tester.prepare_config_and_inputs()

						A__   ,   A__							:    Optional[int]        =		vision_config_and_inputs

						A__   ,   A__   ,   A__   ,   A__							:    Optional[Any]        =		text_config_and_inputs

						# make sure that cross attention layers are added
						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": attention_mask,
						    "input_ids": input_ids,
						    "token_type_ids": token_type_ids,
						}



@require_flax
@require_vision
class     _a						(unittest.TestCase				):


					'''simple docstring'''






					@slow
					def   __A			( self			):
						A__							:    Optional[int]        =		FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian"""    ,       logit_scale_init_value=1.0			)
						A__							:    Dict        =		VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""			)

						A__							:    Dict        =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						A__							:    Union[str, Any]        =		processor(
						    text=["""una foto di un gatto""", """una foto di un cane"""]    ,       images=A__    ,       padding=A__    ,       return_tensors="""np"""			)

						A__							:    int        =		model(**A__			)

						# verify the logits
						self.assertEqual(outputs.logits_per_image.shape    ,       (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])			)
						self.assertEqual(
						    outputs.logits_per_text.shape    ,       (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])    ,       )

						A__							:    List[Any]        =		np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]			)

						self.assertTrue(np.allclose(outputs.logits_per_image    ,       A__    ,       atol=1e-3			)			)






import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf

if is_torch_available():
	import torch


A_       : List[Any]         =			logging.get_logger(__name__)



class     _a						:


					'''simple docstring'''






					def __init__( self    ,       A__ = None    ,       A__ = None    ,       A__=None    ,       A__=None			):
						if not conversation_id:
							A__							:    List[Any]        =		uuid.uuida()
						if past_user_inputs is None:
							A__							:    Dict        =		[]
						if generated_responses is None:
							A__							:    int        =		[]

						A__							:    uuid.UUID        =		conversation_id
						A__							:    List[str]        =		past_user_inputs
						A__							:    List[str]        =		generated_responses
						A__							:    Optional[str]        =		text






					def __eq__( self    ,       A__			):
						if not isinstance(A__    ,       A__			):
							return False
						if self.uuid == other.uuid:
							return True
						return (
						    self.new_user_input == other.new_user_input
						    and self.past_user_inputs == other.past_user_inputs
						    and self.generated_responses == other.generated_responses
						)






					def   __A			( self    ,       A__    ,       A__ = False			):
						if self.new_user_input:
							if overwrite:
								logger.warning(
								    F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """
								    F"""with: \"{text}\"."""			)
								A__							:    str        =		text
							else:
								logger.warning(
								    F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """
								    F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input"""			)
						else:
							A__							:    Tuple        =		text






					def   __A			( self			):
						if self.new_user_input:
							self.past_user_inputs.append(self.new_user_input			)
						A__							:    Tuple        =		None






					def   __A			( self    ,       A__			):
						self.generated_responses.append(A__			)






					def   __A			( self			):
						for user_input, generated_response in zip(self.past_user_inputs    ,       self.generated_responses			):
							yield True, user_input
							yield False, generated_response
						if self.new_user_input:
							yield True, self.new_user_input






					def __repr__( self			):
						A__							:    Optional[Any]        =		F"""Conversation id: {self.uuid} \n"""
						for is_user, text in self.iter_texts():
							A__							:    str        =		"""user""" if is_user else """bot"""
							output += F"""{name} >> {text} \n"""
						return output



@add_end_docstrings(
    __magic_name__		,   r'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''		,   )
class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self    ,       *A__    ,       **A__			):
						super().__init__(*A__    ,       **A__			)
						if self.tokenizer.pad_token_id is None:
							A__							:    Tuple        =		self.tokenizer.eos_token






					def   __A			( self    ,       A__=None    ,       A__=None    ,       A__=None    ,       **A__			):
						A__							:    Tuple        =		{}
						A__							:    List[str]        =		{}
						A__							:    Union[str, Any]        =		{}

						if min_length_for_response is not None:
							A__							:    str        =		min_length_for_response
						if minimum_tokens is not None:
							A__							:    List[str]        =		minimum_tokens

						if "max_length" in generate_kwargs:
							A__							:    List[Any]        =		generate_kwargs["""max_length"""]
							# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
						if clean_up_tokenization_spaces is not None:
							A__							:    Optional[int]        =		clean_up_tokenization_spaces

						if generate_kwargs:
							forward_params.update(A__			)
						return preprocess_params, forward_params, postprocess_params






					def __call__( self    ,       A__    ,       A__=0    ,       **A__			):
						A__							:    Optional[Any]        =		super().__call__(A__    ,       num_workers=A__    ,       **A__			)
						if isinstance(A__    ,       A__			) and len(A__			) == 1:
							return outputs[0]
						return outputs






					def   __A			( self    ,       A__    ,       A__=32			):
						if not isinstance(A__    ,       A__			):
							raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""			)
						if conversation.new_user_input is None:
							raise ValueError(
							    F"""Conversation with UUID {type(conversation.uuid			)} does not contain new user input to process. """
							    """Add user inputs with the conversation's `add_user_input` method"""			)
						if hasattr(self.tokenizer    ,       """_build_conversation_input_ids"""			):
							A__							:    List[str]        =		self.tokenizer._build_conversation_input_ids(A__			)
						else:
							# If the tokenizer cannot handle conversations, we default to only the old version
							A__							:    Tuple        =		self._legacy_parse_and_tokenize(A__			)

						if self.framework == "pt":
							A__							:    List[str]        =		torch.LongTensor([input_ids]			)
						elif self.framework == "tf":
							A__							:    Optional[Any]        =		tf.constant([input_ids]			)
						return {"input_ids": input_ids, "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=10    ,       **A__			):
						A__							:    List[Any]        =		generate_kwargs.get("""max_length"""    ,       self.model.config.max_length			)

						A__							:    Optional[int]        =		model_inputs["""input_ids"""].shape[1]
						if max_length - minimum_tokens < n:
							logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})"""			)
							A__							:    Dict        =		max_length - minimum_tokens
							A__							:    Optional[int]        =		model_inputs["""input_ids"""][:, -trim:]
							if "attention_mask" in model_inputs:
								A__							:    str        =		model_inputs["""attention_mask"""][:, -trim:]
						A__							:    List[str]        =		model_inputs.pop("""conversation"""			)
						A__							:    Dict        =		max_length
						A__							:    str        =		self.model.generate(**A__    ,       **A__			)
						if self.model.config.is_encoder_decoder:
							A__							:    Union[str, Any]        =		1
						else:
							A__							:    Optional[Any]        =		n
						return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=True			):
						A__							:    Dict        =		model_outputs["""output_ids"""]
						A__							:    str        =		self.tokenizer.decode(
						    output_ids[0]    ,       skip_special_tokens=A__    ,       clean_up_tokenization_spaces=A__    ,       )
						A__							:    Optional[int]        =		model_outputs["""conversation"""]
						conversation.mark_processed()
						conversation.append_response(A__			)
						return conversation






					def   __A			( self    ,       A__			):
						A__							:    str        =		self.tokenizer.eos_token_id
						A__							:    Tuple        =		[]
						for is_user, text in conversation.iter_texts():
							if eos_token_id is not None:
								input_ids.extend(self.tokenizer.encode(A__    ,       add_special_tokens=A__			) + [eos_token_id]			)
							else:
								input_ids.extend(self.tokenizer.encode(A__    ,       add_special_tokens=A__			)			)

						if len(A__			) > self.tokenizer.model_max_length:
							A__							:    str        =		input_ids[-self.tokenizer.model_max_length :]
						return input_ids



