

'''simple docstring'''







import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__=True,							UpperCAmelCase__="pt"					)      ->      Optional[Any]:
       A_						       =   {"""add_prefix_space""": True} if isinstance(UpperCAmelCase__,							UpperCAmelCase__					) and not line.startswith(""" """					) else {}
       A_						       =   padding_side
       return tokenizer(
           [line],							max_length=UpperCAmelCase__,							padding="""max_length""" if pad_to_max_length else None,							truncation=UpperCAmelCase__,							return_tensors=UpperCAmelCase__,							add_special_tokens=UpperCAmelCase__,							**UpperCAmelCase__,							)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__=None,							)      ->      str:
       A_						       =   input_ids.ne(UpperCAmelCase__					).any(dim=0					)
       if attention_mask is None:
              return input_ids[:, keep_column_mask]
       else:
              return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])


class        A__   (   _snake_case      ):



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__="train"		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__=""		,					)    ->   Union[str, Any]:





           '''simple docstring'''
           super().__init__()
           A_						       =   Path(UpperCamelCase__							).joinpath(type_path + """.source"""							)
           A_						       =   Path(UpperCamelCase__							).joinpath(type_path + """.target"""							)
           A_						       =   self.get_char_lens(self.src_file							)
           A_						       =   max_source_length
           A_						       =   max_target_length
           assert min(self.src_lens							) > 0, f'''found empty line in {self.src_file}'''
           A_						       =   tokenizer
           A_						       =   prefix
           if n_obs is not None:
                  A_						       =   self.src_lens[:n_obs]
           A_						       =   src_lang
           A_						       =   tgt_lang



    def __len__(       self							)    ->   List[Any]:





           '''simple docstring'''
           return len(self.src_lens							)



    def __getitem__(       self		,					UpperCamelCase__							)    ->   Dict[str, torch.Tensor]:





           '''simple docstring'''
           A_						       =   index + 1  # linecache starts at 1
           A_						       =   self.prefix + linecache.getline(str(self.src_file							)		,					UpperCamelCase__							).rstrip("""\n"""							)
           A_						       =   linecache.getline(str(self.tgt_file							)		,					UpperCamelCase__							).rstrip("""\n"""							)
           assert source_line, f'''empty source line for index {index}'''
           assert tgt_line, f'''empty tgt line for index {index}'''

           # Need to add eos token manually for T5
           if isinstance(self.tokenizer		,					UpperCamelCase__							):
                  source_line += self.tokenizer.eos_token
                  tgt_line += self.tokenizer.eos_token

           # Pad source and target to the right
           A_						       =   (
               self.tokenizer.question_encoder if isinstance(self.tokenizer		,					UpperCamelCase__							) else self.tokenizer
           )
           A_						       =   self.tokenizer.generator if isinstance(self.tokenizer		,					UpperCamelCase__							) else self.tokenizer

           A_						       =   encode_line(UpperCamelCase__		,					UpperCamelCase__		,					self.max_source_length		,					"""right"""							)
           A_						       =   encode_line(UpperCamelCase__		,					UpperCamelCase__		,					self.max_target_length		,					"""right"""							)

           A_						       =   source_inputs["""input_ids"""].squeeze()
           A_						       =   target_inputs["""input_ids"""].squeeze()
           A_						       =   source_inputs["""attention_mask"""].squeeze()
           return {
               "input_ids": source_ids,
               "attention_mask": src_mask,
               "decoder_input_ids": target_ids,
           }



    @staticmethod
    def        snake_case_      (       UpperCamelCase__							)    ->   Optional[int]:





           '''simple docstring'''
           return [len(UpperCamelCase__							) for x in Path(UpperCamelCase__							).open().readlines()]







    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   Dict[str, torch.Tensor]:





           '''simple docstring'''
           A_						       =   torch.stack([x["""input_ids"""] for x in batch]							)
           A_						       =   torch.stack([x["""attention_mask"""] for x in batch]							)
           A_						       =   torch.stack([x["""decoder_input_ids"""] for x in batch]							)
           A_						       =   (
               self.tokenizer.generator.pad_token_id
               if isinstance(self.tokenizer		,					UpperCamelCase__							)
               else self.tokenizer.pad_token_id
           )
           A_						       =   (
               self.tokenizer.question_encoder.pad_token_id
               if isinstance(self.tokenizer		,					UpperCamelCase__							)
               else self.tokenizer.pad_token_id
           )
           A_						       =   trim_batch(UpperCamelCase__		,					UpperCamelCase__							)
           A_       ,      A_						       =   trim_batch(UpperCamelCase__		,					UpperCamelCase__		,					attention_mask=UpperCamelCase__							)
           A_						       =   {
               """input_ids""": source_ids,
               """attention_mask""": source_mask,
               """decoder_input_ids""": y,
           }
           return batch

__lowerCamelCase									=     getLogger(__name__)
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Optional[int]:
       return list(itertools.chain.from_iterable(UpperCAmelCase__					)					)
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      None:
       A_						       =   get_git_info()
       save_json(UpperCAmelCase__,							os.path.join(UpperCAmelCase__,							"""git_log.json"""					)					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__=4,							**UpperCAmelCase__					)      ->      Dict:
       with open(UpperCAmelCase__,							"""w"""					) as f:
              json.dump(UpperCAmelCase__,							UpperCAmelCase__,							indent=UpperCAmelCase__,							**UpperCAmelCase__					)
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Tuple:
       with open(UpperCAmelCase__					) as f:
              return json.load(UpperCAmelCase__					)
def    UpperCAmelCase__     (   )      ->      Tuple:
       A_						       =   git.Repo(search_parent_directories=UpperCAmelCase__					)
       A_						       =   {
           """repo_id""": str(UpperCAmelCase__					),
           """repo_sha""": str(repo.head.object.hexsha					),
           """repo_branch""": str(repo.active_branch					),
           """hostname""": str(socket.gethostname()					),
       }
       return repo_infos
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      List:
       return list(map(UpperCAmelCase__,							UpperCAmelCase__					)					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      Optional[Any]:
       with open(UpperCAmelCase__,							"""wb"""					) as f:
              return pickle.dump(UpperCAmelCase__,							UpperCAmelCase__					)
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      List[str]:

       def remove_articles(UpperCAmelCase__					):
              return re.sub(r"""\b(a|an|the)\b""",							""" """,							UpperCAmelCase__					)

       def white_space_fix(UpperCAmelCase__					):
              return " ".join(text.split()					)

       def remove_punc(UpperCAmelCase__					):
              A_						       =   set(string.punctuation					)
              return "".join(ch for ch in text if ch not in exclude					)

       def lower(UpperCAmelCase__					):
              return text.lower()

       return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase__					)					)					)					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      Union[str, Any]:
       A_						       =   normalize_answer(UpperCAmelCase__					).split()
       A_						       =   normalize_answer(UpperCAmelCase__					).split()
       A_						       =   Counter(UpperCAmelCase__					) & Counter(UpperCAmelCase__					)
       A_						       =   sum(common.values()					)
       if num_same == 0:
              return 0
       A_						       =   1.0 * num_same / len(UpperCAmelCase__					)
       A_						       =   1.0 * num_same / len(UpperCAmelCase__					)
       A_						       =   (2 * precision * recall) / (precision + recall)
       return fa
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      List[str]:
       return normalize_answer(UpperCAmelCase__					) == normalize_answer(UpperCAmelCase__					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      Dict:
       assert len(UpperCAmelCase__					) == len(UpperCAmelCase__					)
       A_						       =   0
       for hypo, pred in zip(UpperCAmelCase__,							UpperCAmelCase__					):
              em += exact_match_score(UpperCAmelCase__,							UpperCAmelCase__					)
       if len(UpperCAmelCase__					) > 0:
              em /= len(UpperCAmelCase__					)
       return {"em": em}
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Any:
       return model_prefix.startswith("""rag"""					)







def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)      ->      Optional[Any]:
       A_						       =   {p: p for p in extra_params}
       # T5 models don't have `dropout` param, they have `dropout_rate` instead
       A_						       =   """dropout_rate"""
       for p in extra_params:
              if getattr(UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					):
                     if not hasattr(UpperCAmelCase__,							UpperCAmelCase__					) and not hasattr(UpperCAmelCase__,							equivalent_param[p]					):
                            logger.info("""config doesn't have a `{}` attribute""".format(UpperCAmelCase__					)					)
                            delattr(UpperCAmelCase__,							UpperCAmelCase__					)
                            continue
                     A_						       =   p if hasattr(UpperCAmelCase__,							UpperCAmelCase__					) else equivalent_param[p]
                     setattr(UpperCAmelCase__,							UpperCAmelCase__,							getattr(UpperCAmelCase__,							UpperCAmelCase__					)					)
                     delattr(UpperCAmelCase__,							UpperCAmelCase__					)
       return hparams, config



'''simple docstring'''







from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
      import tensorflow as tf

      from transformers import TFBlipTextModel
      from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class        A__   :



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=12		,					UpperCamelCase__=7		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=99		,					UpperCamelCase__=32		,					UpperCamelCase__=32		,					UpperCamelCase__=2		,					UpperCamelCase__=4		,					UpperCamelCase__=37		,					UpperCamelCase__=0.1		,					UpperCamelCase__=0.1		,					UpperCamelCase__=512		,					UpperCamelCase__=0.02		,					UpperCamelCase__=0		,					UpperCamelCase__=None		,					)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   seq_length
           A_						       =   is_training
           A_						       =   use_input_mask
           A_						       =   use_labels
           A_						       =   vocab_size
           A_						       =   hidden_size
           A_						       =   projection_dim
           A_						       =   num_hidden_layers
           A_						       =   num_attention_heads
           A_						       =   intermediate_size
           A_						       =   dropout
           A_						       =   attention_dropout
           A_						       =   max_position_embeddings
           A_						       =   initializer_range
           A_						       =   scope
           A_						       =   bos_token_id



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

           A_						       =   None
           if self.use_input_mask:
                  A_						       =   random_attention_mask([self.batch_size, self.seq_length]							)

           if input_mask is not None:
                  A_						       =   input_mask.numpy()
                  A_       ,      A_						       =   input_mask.shape
                  A_						       =   np.random.randint(1		,					seq_length - 1		,					size=(batch_size,)							)
                  for batch_idx, start_index in enumerate(UpperCamelCase__							):
                         A_						       =   1
                         A_						       =   0

           A_						       =   self.get_config()

           return config, input_ids, tf.convert_to_tensor(UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           return BlipTextConfig(
               vocab_size=self.vocab_size		,					hidden_size=self.hidden_size		,					projection_dim=self.projection_dim		,					num_hidden_layers=self.num_hidden_layers		,					num_attention_heads=self.num_attention_heads		,					intermediate_size=self.intermediate_size		,					dropout=self.dropout		,					attention_dropout=self.attention_dropout		,					max_position_embeddings=self.max_position_embeddings		,					initializer_range=self.initializer_range		,					bos_token_id=self.bos_token_id		,					)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           A_						       =   TFBlipTextModel(config=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					training=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					training=UpperCamelCase__							)
           self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)							)
           self.parent.assertEqual(result.pooler_output.shape		,					(self.batch_size, self.hidden_size)							)







    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.prepare_config_and_inputs()
           A_       ,      A_       ,      A_						       =   config_and_inputs
           A_						       =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict


@require_tf
class        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		(TFBlipTextModel,) if is_tf_available() else ()
    lowercase						       =		False
    lowercase						       =		False
    lowercase						       =		False



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   BlipTextModelTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase__		,					hidden_size=37							)



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           self.config_tester.run_common_tests()



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           pass



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""Blip does not use inputs_embeds"""							)
    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           pass



    @slow
    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A_						       =   TFBlipTextModel.from_pretrained(UpperCamelCase__							)
                  self.assertIsNotNone(UpperCamelCase__							)







    def        snake_case_      (       self		,					UpperCamelCase__=True							)    ->   str:





           '''simple docstring'''
           super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__							)
