



'''simple docstring'''






from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


lowerCamelCase__	  =		logging.get_logger(__name__)

lowerCamelCase__	  =		{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCamelCase__	  =		{
    'vocab_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json',
    },
    'merges_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'openai/clip-vit-base-patch32': (
            'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json'
        ),
    },
}

lowerCamelCase__	  =		{
    'openai/clip-vit-base-patch32': 77,
}

class 	_lowerCAmelCase     (    lowercase_       ):






		'''simple docstring'''
		snake_case_							= VOCAB_FILES_NAMES
		snake_case_							= PRETRAINED_VOCAB_FILES_MAP
		snake_case_							= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		snake_case_							= ['input_ids', 'attention_mask']
		snake_case_							= CLIPTokenizer
		def __init__(						self							:       Dict      ,		UpperCamelCase_							:       Optional[Any]=None      ,		UpperCamelCase_							:       str=None      ,		UpperCamelCase_							:       List[str]=None      ,		UpperCamelCase_							:       List[Any]="<|endoftext|>"      ,		UpperCamelCase_							:       Dict="<|startoftext|>"      ,		UpperCamelCase_							:       Union[str, Any]="<|endoftext|>"      ,		UpperCamelCase_							:       Optional[Any]="<|endoftext|>"      ,		**UpperCamelCase_							:       Optional[int]      ,		)      ->			Dict:







									'''simple docstring'''





									super().__init__(
									    UpperCAmelCase_      ,		UpperCAmelCase_      ,		tokenizer_file=UpperCAmelCase_      ,		unk_token=UpperCAmelCase_      ,		bos_token=UpperCAmelCase_      ,		eos_token=UpperCAmelCase_      ,		pad_token=UpperCAmelCase_      ,		**UpperCAmelCase_      ,		)

									if not isinstance(self.backend_tokenizer.pre_tokenizer      ,		pre_tokenizers.Sequence		):
																raise ValueError(
																    '''The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'''
																    ''' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'''
																    ''' to be compatible with this version.The easiest way to do so is'''
																    ''' `CLIPTokenizerFast.from_pretrained(\"path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'''
																    ''' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'''
																    ''' transformers.'''		)

									self._wrap_decode_method_backend_tokenizer()
		def 						__lowercase      (						self							:       Union[str, Any]		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		Union[str, Any]				=   self.backend_tokenizer.decode

									def new_decode_method(*UpperCamelCase_							:       List[Any]      ,		**UpperCamelCase_							:       Any		):
																_lowercase							:		Union[str, Any]				=   orig_decode_method(*UpperCAmelCase_      ,		**UpperCAmelCase_		)
																_lowercase							:		Optional[Any]				=   text.replace(self.backend_tokenizer.model.end_of_word_suffix      ,		''' '''		).strip()
																return text

									_lowercase							:		List[str]				=   new_decode_method
		def 						__lowercase      (						self							:       Tuple      ,		UpperCamelCase_							:       int      ,		UpperCamelCase_							:       List[str] = None		)      ->			List[int]:







									'''simple docstring'''





									_lowercase							:		List[str]				=   [self.bos_token_id]
									_lowercase							:		Dict				=   [self.eos_token_id]

									if token_ids_a is None:
																return bos_token + token_ids_a + eos_token
									return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token
		def 						__lowercase      (						self							:       List[Any]      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Tuple = None		)      ->			List[int]:







									'''simple docstring'''





									_lowercase							:		str				=   [self.bos_token_id]
									_lowercase							:		Any				=   [self.eos_token_id]

									if token_ids_a is None:
																return len(bos_token + token_ids_a + eos_token		) * [0]
									return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token		) * [0]





		def 						__lowercase      (						self							:       Optional[int]      ,		UpperCamelCase_							:       Optional[Any]      ,		UpperCamelCase_							:       Optional[int] = None		)      ->			Tuple[str]:







									'''simple docstring'''





									_lowercase							:		str				=   self._tokenizer.model.save(UpperCAmelCase_      ,		name=UpperCAmelCase_		)
									return tuple(UpperCAmelCase_		)











"""simple docstring"""





import argparse
import json
import re
import string
import sys
from collections import Counter






def 							A(    snake_case_						):
       """simple docstring"""





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

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

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

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

       return white_space_fix(remove_articles(remove_punc(lower(snake_case_						)						)						)						)






def 							A(    snake_case_		,  snake_case_						):
       """simple docstring"""





       lowercase__:							Dict         =     normalize_answer(snake_case_						).split()
       lowercase__:							List[str]         =     normalize_answer(snake_case_						).split()
       lowercase__:							Optional[int]         =     Counter(snake_case_						) & Counter(snake_case_						)
       lowercase__:							Any         =     sum(common.values()						)
       if num_same == 0:
              return 0
       lowercase__:							Any         =     1.0 * num_same / len(snake_case_						)
       lowercase__:							List[Any]         =     1.0 * num_same / len(snake_case_						)
       lowercase__:							int         =     (2 * precision * recall) / (precision + recall)
       return fa






def 							A(    snake_case_		,  snake_case_						):
       """simple docstring"""





       return normalize_answer(snake_case_						) == normalize_answer(snake_case_						)






def 							A(    snake_case_		,  snake_case_		,  snake_case_						):
       """simple docstring"""





       lowercase__:							int         =     []
       for ground_truth in ground_truths:
              lowercase__:							str         =     metric_fn(snake_case_		,  snake_case_						)
              scores_for_ground_truths.append(snake_case_						)
       return max(snake_case_						)






def 							A(    snake_case_		,  snake_case_						):
       """simple docstring"""





       lowercase__:							Optional[int]         =     0
       for article in dataset:
              for paragraph in article["paragraphs"]:
                     for qa in paragraph["qas"]:
                            total += 1
                            if qa["id"] not in predictions:
                                   lowercase__:							Union[str, Any]         =     "Unanswered question " + qa["id"] + " will receive score 0."
                                   print(snake_case_		,  file=sys.stderr						)
                                   continue
                            lowercase__:							List[Any]         =     [x["text"] for x in qa["answers"]]
                            lowercase__:							Optional[Any]         =     predictions[qa["id"]]
                            exact_match += metric_max_over_ground_truths(snake_case_		,  snake_case_		,  snake_case_						)
                            fa += metric_max_over_ground_truths(snake_case_		,  snake_case_		,  snake_case_						)

       lowercase__:							Union[str, Any]         =     1_00.0 * exact_match / total
       lowercase__:							str         =     1_00.0 * fa / total

       return {"exact_match": exact_match, "f1": fa}


if __name__ == "__main__":
  UpperCamelCase					=     """1.1"""
  UpperCamelCase					=     argparse.ArgumentParser(description="""Evaluation for SQuAD """ + expected_version)
  parser.add_argument("""dataset_file""", help="""Dataset file""")
  parser.add_argument("""prediction_file""", help="""Prediction File""")
  UpperCamelCase					=     parser.parse_args()
  with open(args.dataset_file) as dataset_file:
    UpperCamelCase					=     json.load(dataset_file)
    if dataset_json["version"] != expected_version:
      print(
          """Evaluation expects v-""" + expected_version + """, but got dataset with v-""" + dataset_json["""version"""],
          file=sys.stderr,
      )
    UpperCamelCase					=     dataset_json["""data"""]
  with open(args.prediction_file) as prediction_file:
    UpperCamelCase					=     json.load(prediction_file)
  print(json.dumps(evaluate(dataset, predictions)))






