



"""simple docstring"""






import argparse

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    CLIPTokenizer,
    CLIPTokenizerFast,
    VideoMAEImageProcessor,
    XCLIPConfig,
    XCLIPModel,
    XCLIPProcessor,
    XCLIPTextConfig,
    XCLIPVisionConfig,
)






def      snake_case__   (		__lowerCamelCase				:    int							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			lowerCamelCase__		:		str			=XCLIPTextConfig()

			# derive patch size from model name
			lowerCamelCase__		:		Union[str, Any]			=model_name.find('''patch'''	)
			lowerCamelCase__		:		Tuple			=int(model_name[start_idx + len('''patch'''	) : start_idx + len('''patch'''	) + 2]	)
			lowerCamelCase__		:		str			=XCLIPVisionConfig(patch_size=__lowerCamelCase							,		num_frames=__lowerCamelCase	)

			if "large" in model_name:
						lowerCamelCase__		:		str			=768
						lowerCamelCase__		:		List[Any]			=3072
						lowerCamelCase__		:		Union[str, Any]			=12

						lowerCamelCase__		:		Optional[Any]			=1024
						lowerCamelCase__		:		Union[str, Any]			=4096
						lowerCamelCase__		:		Dict			=16
						lowerCamelCase__		:		Any			=24
						lowerCamelCase__		:		Dict			=768
						lowerCamelCase__		:		Optional[Any]			=3072

			if model_name == "xclip-large-patch14-16-frames":
						lowerCamelCase__		:		Any			=336

			lowerCamelCase__		:		Optional[int]			=XCLIPConfig.from_text_vision_configs(__lowerCamelCase							,		__lowerCamelCase	)

			if "large" in model_name:
						lowerCamelCase__		:		Optional[int]			=768

			return config






def      snake_case__   (		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			# text encoder
			if name == "token_embedding.weight":
						lowerCamelCase__		:		Optional[int]			=name.replace('''token_embedding.weight'''							,		'''text_model.embeddings.token_embedding.weight'''	)
			if name == "positional_embedding":
						lowerCamelCase__		:		Union[str, Any]			=name.replace('''positional_embedding'''							,		'''text_model.embeddings.position_embedding.weight'''	)
			if "ln_1" in name:
						lowerCamelCase__		:		Optional[int]			=name.replace('''ln_1'''							,		'''layer_norm1'''	)
			if "ln_2" in name:
						lowerCamelCase__		:		Any			=name.replace('''ln_2'''							,		'''layer_norm2'''	)
			if "c_fc" in name:
						lowerCamelCase__		:		List[Any]			=name.replace('''c_fc'''							,		'''fc1'''	)
			if "c_proj" in name:
						lowerCamelCase__		:		List[str]			=name.replace('''c_proj'''							,		'''fc2'''	)
			if name.startswith('''transformer.resblocks'''	):
						lowerCamelCase__		:		List[str]			=name.replace('''transformer.resblocks'''							,		'''text_model.encoder.layers'''	)
			if "attn.out_proj" in name and "message" not in name:
						lowerCamelCase__		:		Union[str, Any]			=name.replace('''attn.out_proj'''							,		'''self_attn.out_proj'''	)
			if "ln_final" in name:
						lowerCamelCase__		:		List[Any]			=name.replace('''ln_final'''							,		'''text_model.final_layer_norm'''	)
			# visual encoder
			if name == "visual.class_embedding":
						lowerCamelCase__		:		Optional[int]			=name.replace('''visual.class_embedding'''							,		'''vision_model.embeddings.class_embedding'''	)
			if name == "visual.positional_embedding":
						lowerCamelCase__		:		int			=name.replace('''visual.positional_embedding'''							,		'''vision_model.embeddings.position_embedding.weight'''	)
			if name.startswith('''visual.transformer.resblocks'''	):
						lowerCamelCase__		:		int			=name.replace('''visual.transformer.resblocks'''							,		'''vision_model.encoder.layers'''	)
			if "visual.conv1" in name:
						lowerCamelCase__		:		Dict			=name.replace('''visual.conv1'''							,		'''vision_model.embeddings.patch_embedding'''	)
			if "visual.ln_pre" in name:
						lowerCamelCase__		:		Any			=name.replace('''visual.ln_pre'''							,		'''vision_model.pre_layernorm'''	)
			if "visual.ln_post" in name:
						lowerCamelCase__		:		Optional[Any]			=name.replace('''visual.ln_post'''							,		'''vision_model.post_layernorm'''	)
			if "visual.proj" in name:
						lowerCamelCase__		:		str			=name.replace('''visual.proj'''							,		'''visual_projection.weight'''	)
			if "text_projection" in name:
						lowerCamelCase__		:		Any			=name.replace('''text_projection'''							,		'''text_projection.weight'''	)
			# things on top
			if "prompts_visual_proj" in name:
						lowerCamelCase__		:		int			=name.replace('''prompts_visual_proj'''							,		'''prompts_visual_projection'''	)
			if "prompts_visual_ln" in name:
						lowerCamelCase__		:		Union[str, Any]			=name.replace('''prompts_visual_ln'''							,		'''prompts_visual_layernorm'''	)
			# mit
			if name == "mit.positional_embedding":
						lowerCamelCase__		:		str			=name.replace('''positional'''							,		'''position'''	)
			if name.startswith('''mit.resblocks'''	):
						lowerCamelCase__		:		Dict			=name.replace('''mit.resblocks'''							,		'''mit.encoder.layers'''	)
			# prompts generator
			if name.startswith('''prompts_generator.norm'''	):
						lowerCamelCase__		:		List[Any]			=name.replace('''prompts_generator.norm'''							,		'''prompts_generator.layernorm'''	)

			return name






def      snake_case__   (		__lowerCamelCase				:    int							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			for key in orig_state_dict.copy().keys():
						lowerCamelCase__		:		Dict			=orig_state_dict.pop(__lowerCamelCase	)

						if "attn.in_proj" in key:
									lowerCamelCase__		:		Optional[int]			=key.split('''.'''	)
									if key.startswith('''visual'''	):
												lowerCamelCase__		:		Optional[Any]			=key_split[3]
												lowerCamelCase__		:		Optional[Any]			=config.vision_config.hidden_size
												if "message_attn" in key:
															if "weight" in key:
																		lowerCamelCase__		:		str			=val[
																		    :dim, :
																		]
																		lowerCamelCase__		:		Dict			=val[
																		    dim : dim * 2, :
																		]
																		lowerCamelCase__		:		Any			=val[
																		    -dim:, :
																		]
															else:
																		lowerCamelCase__		:		Dict			=val[
																		    :dim
																		]
																		lowerCamelCase__		:		List[Any]			=val[
																		    dim : dim * 2
																		]
																		lowerCamelCase__		:		Union[str, Any]			=val[
																		    -dim:
																		]
												else:
															if "weight" in key:
																		lowerCamelCase__		:		Optional[int]			=val[
																		    :dim, :
																		]
																		lowerCamelCase__		:		List[Any]			=val[
																		    dim : dim * 2, :
																		]
																		lowerCamelCase__		:		List[Any]			=val[
																		    -dim:, :
																		]
															else:
																		lowerCamelCase__		:		str			=val[:dim]
																		lowerCamelCase__		:		List[str]			=val[
																		    dim : dim * 2
																		]
																		lowerCamelCase__		:		Optional[int]			=val[-dim:]
									elif key.startswith('''mit'''	):
												lowerCamelCase__		:		Optional[int]			=key_split[2]
												lowerCamelCase__		:		List[str]			=config.vision_config.mit_hidden_size
												if "weight" in key:
															lowerCamelCase__		:		List[Any]			=val[:dim, :]
															lowerCamelCase__		:		List[Any]			=val[dim : dim * 2, :]
															lowerCamelCase__		:		Any			=val[-dim:, :]
												else:
															lowerCamelCase__		:		str			=val[:dim]
															lowerCamelCase__		:		Any			=val[dim : dim * 2]
															lowerCamelCase__		:		Any			=val[-dim:]
									else:
												lowerCamelCase__		:		Dict			=key_split[2]
												lowerCamelCase__		:		Union[str, Any]			=config.text_config.hidden_size
												if "weight" in key:
															lowerCamelCase__		:		List[str]			=val[:dim, :]
															lowerCamelCase__		:		str			=val[
															    dim : dim * 2, :
															]
															lowerCamelCase__		:		Dict			=val[-dim:, :]
												else:
															lowerCamelCase__		:		Optional[int]			=val[:dim]
															lowerCamelCase__		:		int			=val[
															    dim : dim * 2
															]
															lowerCamelCase__		:		Optional[int]			=val[-dim:]
						else:
									lowerCamelCase__		:		Union[str, Any]			=rename_key(__lowerCamelCase	)
									if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
												lowerCamelCase__		:		Optional[int]			=val.T
									lowerCamelCase__		:		Optional[Any]			=val

			return orig_state_dict






def      snake_case__   (		__lowerCamelCase				:    Any	):
			"""simple docstring"""
			if num_frames == 8:
						lowerCamelCase__		:		List[Any]			='''eating_spaghetti_8_frames.npy'''
			elif num_frames == 16:
						lowerCamelCase__		:		Optional[int]			='''eating_spaghetti.npy'''
			elif num_frames == 32:
						lowerCamelCase__		:		Union[str, Any]			='''eating_spaghetti_32_frames.npy'''
			lowerCamelCase__		:		Union[str, Any]			=hf_hub_download(
			    repo_id='''hf-internal-testing/spaghetti-video'''							,		filename=__lowerCamelCase							,		repo_type='''dataset'''							,		)
			lowerCamelCase__		:		Optional[int]			=np.load(__lowerCamelCase	)
			return list(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    Tuple=None							,		__lowerCamelCase				:    List[str]=False	):
			"""simple docstring"""
			lowerCamelCase__		:		Tuple			={
			    # fully supervised kinetics-400 checkpoints
			    '''xclip-base-patch32''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth''',
			    '''xclip-base-patch32-16-frames''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth'''
			    ),
			    '''xclip-base-patch16''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth''',
			    '''xclip-base-patch16-16-frames''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth'''
			    ),
			    '''xclip-large-patch14''': '''https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb''',
			    '''xclip-large-patch14-16-frames''': '''https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f''',
			    # fully supervised kinetics-600 checkpoints
			    '''xclip-base-patch16-kinetics-600''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth'''
			    ),
			    '''xclip-base-patch16-kinetics-600-16-frames''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth'''
			    ),
			    '''xclip-large-patch14-kinetics-600''': '''https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be''',
			    # few shot
			    '''xclip-base-patch16-hmdb-2-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth'''
			    ),
			    '''xclip-base-patch16-hmdb-4-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth'''
			    ),
			    '''xclip-base-patch16-hmdb-8-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth'''
			    ),
			    '''xclip-base-patch16-hmdb-16-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth'''
			    ),
			    '''xclip-base-patch16-ucf-2-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth'''
			    ),
			    '''xclip-base-patch16-ucf-4-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth'''
			    ),
			    '''xclip-base-patch16-ucf-8-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth'''
			    ),
			    '''xclip-base-patch16-ucf-16-shot''': (
			        '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth'''
			    ),
			    # zero shot
			    '''xclip-base-patch16-zero-shot''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth''',
			}

			lowerCamelCase__		:		List[Any]			=model_to_url[model_name]
			lowerCamelCase__		:		Dict			=8
			if "16-frames" in model_name:
						lowerCamelCase__		:		Dict			=16
			elif "shot" in model_name:
						lowerCamelCase__		:		int			=32

			lowerCamelCase__		:		List[str]			=get_xclip_config(__lowerCamelCase							,		__lowerCamelCase	)
			lowerCamelCase__		:		Optional[int]			=XCLIPModel(__lowerCamelCase	)
			model.eval()

			if "drive" in checkpoint_url:
						lowerCamelCase__		:		str			='''pytorch_model.bin'''
						gdown.cached_download(__lowerCamelCase							,		__lowerCamelCase							,		quiet=__lowerCamelCase	)
						lowerCamelCase__		:		Optional[int]			=torch.load(__lowerCamelCase							,		map_location='''cpu'''	)['''model''']
			else:
						lowerCamelCase__		:		List[Any]			=torch.hub.load_state_dict_from_url(__lowerCamelCase	)['''model''']

			lowerCamelCase__		:		Dict			=convert_state_dict(__lowerCamelCase							,		__lowerCamelCase	)

			lowerCamelCase__		:		Optional[int]			=XCLIPModel(__lowerCamelCase	)
			lowerCamelCase__	,   lowerCamelCase__		:		Optional[Any]			=model.load_state_dict(__lowerCamelCase							,		strict=__lowerCamelCase	)
			assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
			model.eval()

			lowerCamelCase__		:		Optional[int]			=336 if model_name == '''xclip-large-patch14-16-frames''' else 224
			lowerCamelCase__		:		List[Any]			=VideoMAEImageProcessor(size=__lowerCamelCase	)
			lowerCamelCase__		:		Any			=CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32'''	)
			lowerCamelCase__		:		str			=CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32'''	)
			lowerCamelCase__		:		Union[str, Any]			=XCLIPProcessor(image_processor=__lowerCamelCase							,		tokenizer=__lowerCamelCase	)

			lowerCamelCase__		:		Union[str, Any]			=prepare_video(__lowerCamelCase	)
			lowerCamelCase__		:		int			=processor(
			    text=['''playing sports''', '''eating spaghetti''', '''go shopping''']							,		videos=__lowerCamelCase							,		return_tensors='''pt'''							,		padding=__lowerCamelCase	)

			print('''Shape of pixel values:'''							,		inputs.pixel_values.shape	)

			with torch.no_grad():
						lowerCamelCase__		:		Union[str, Any]			=model(**__lowerCamelCase	)

			# Verify outputs
			lowerCamelCase__		:		List[str]			=outputs.logits_per_video
			lowerCamelCase__		:		Tuple			=logits_per_video.softmax(dim=1	)
			print('''Probs:'''							,		__lowerCamelCase	)
			# kinetics-400
			if model_name == "xclip-base-patch32":
						lowerCamelCase__		:		str			=torch.tensor([[0.00_19, 0.99_51, 0.00_30]]	)
			elif model_name == "xclip-base-patch32-16-frames":
						lowerCamelCase__		:		Union[str, Any]			=torch.tensor([[7.0_9_9_9e-0_4, 9.9_8_8_3e-0_1, 4.5_5_8_0e-0_4]]	)
			elif model_name == "xclip-base-patch16":
						lowerCamelCase__		:		List[str]			=torch.tensor([[0.00_83, 0.96_81, 0.02_36]]	)
			elif model_name == "xclip-base-patch16-16-frames":
						lowerCamelCase__		:		Any			=torch.tensor([[7.6_9_3_7e-0_4, 9.9_7_2_8e-0_1, 1.9_4_7_3e-0_3]]	)
			elif model_name == "xclip-large-patch14":
						lowerCamelCase__		:		Any			=torch.tensor([[0.00_62, 0.98_64, 0.00_75]]	)
			elif model_name == "xclip-large-patch14-16-frames":
						lowerCamelCase__		:		str			=torch.tensor([[3.3_8_7_7e-0_4, 9.9_9_3_7e-0_1, 2.8_8_8_8e-0_4]]	)
			# kinetics-600
			elif model_name == "xclip-base-patch16-kinetics-600":
						lowerCamelCase__		:		List[Any]			=torch.tensor([[0.05_55, 0.89_14, 0.05_31]]	)
			elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
						lowerCamelCase__		:		str			=torch.tensor([[3.8_5_5_4e-0_4, 9.9_9_2_9e-0_1, 3.2_7_5_4e-0_4]]	)
			elif model_name == "xclip-large-patch14-kinetics-600":
						lowerCamelCase__		:		Union[str, Any]			=torch.tensor([[0.00_36, 0.99_20, 0.00_45]]	)
			# few shot
			elif model_name == "xclip-base-patch16-hmdb-2-shot":
						lowerCamelCase__		:		Dict			=torch.tensor([[7.1_8_9_0e-0_6, 9.9_9_9_4e-0_1, 5.6_5_5_9e-0_5]]	)
			elif model_name == "xclip-base-patch16-hmdb-4-shot":
						lowerCamelCase__		:		List[Any]			=torch.tensor([[1.0_3_2_0e-0_5, 9.9_9_9_3e-0_1, 6.2_4_3_5e-0_5]]	)
			elif model_name == "xclip-base-patch16-hmdb-8-shot":
						lowerCamelCase__		:		Optional[int]			=torch.tensor([[4.1_3_7_7e-0_6, 9.9_9_9_0e-0_1, 9.8_3_8_6e-0_5]]	)
			elif model_name == "xclip-base-patch16-hmdb-16-shot":
						lowerCamelCase__		:		Tuple			=torch.tensor([[4.1_3_4_7e-0_5, 9.9_9_6_2e-0_1, 3.3_4_1_1e-0_4]]	)
			elif model_name == "xclip-base-patch16-ucf-2-shot":
						lowerCamelCase__		:		int			=torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]]	)
			elif model_name == "xclip-base-patch16-ucf-4-shot":
						lowerCamelCase__		:		Dict			=torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]]	)
			elif model_name == "xclip-base-patch16-ucf-8-shot":
						lowerCamelCase__		:		List[str]			=torch.tensor([[0.00_27, 0.99_04, 0.00_70]]	)
			elif model_name == "xclip-base-patch16-ucf-16-shot":
						lowerCamelCase__		:		Tuple			=torch.tensor([[9.8_2_1_9e-0_4, 9.9_5_9_3e-0_1, 3.0_8_6_3e-0_3]]	)
			# zero shot
			elif model_name == "xclip-base-patch16-zero-shot":
						lowerCamelCase__		:		Optional[int]			=torch.tensor([[3.5_0_8_2e-0_4, 9.9_7_8_5e-0_1, 1.7_9_6_6e-0_3]]	)
			else:
						raise ValueError(f'''Model name {model_name} not supported'''	)
			assert torch.allclose(__lowerCamelCase							,		__lowerCamelCase							,		atol=1e-3	)
			print('''Looks ok!'''	)

			if pytorch_dump_folder_path is not None:
						print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''	)
						model.save_pretrained(__lowerCamelCase	)

			if push_to_hub:
						print('''Pushing model, processor and slow tokenizer files to the hub...'''	)
						model.push_to_hub(__lowerCamelCase							,		organization='''nielsr'''	)
						processor.push_to_hub(__lowerCamelCase							,		organization='''nielsr'''	)
						slow_tokenizer.push_to_hub(__lowerCamelCase							,		organization='''nielsr'''	)


if __name__ == "__main__":
		_lowercase : Optional[Any]      						=						argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    "--model_name",
		    default="xclip-base-patch32",
		    type=str,
		    help="Name of the model.",
		)
		parser.add_argument(
		    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
		)
		parser.add_argument(
		    "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
		)

		_lowercase : Optional[int]      						=						parser.parse_args()
		convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)









"""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      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    Tuple=True							,		__lowerCamelCase				:    Dict="pt"	):
			"""simple docstring"""
			lowerCamelCase__		:		str			={'''add_prefix_space''': True} if isinstance(__lowerCamelCase							,		__lowerCamelCase	) and not line.startswith(''' '''	) else {}
			lowerCamelCase__		:		int			=padding_side
			return tokenizer(
			    [line]							,		max_length=__lowerCamelCase							,		padding='''max_length''' if pad_to_max_length else None							,		truncation=__lowerCamelCase							,		return_tensors=__lowerCamelCase							,		add_special_tokens=__lowerCamelCase							,		**__lowerCamelCase							,		)






def      snake_case__   (		__lowerCamelCase				:    str							,		__lowerCamelCase				:    List[Any]							,		__lowerCamelCase				:    Optional[int]=None							,		):
			"""simple docstring"""
			lowerCamelCase__		:		Any			=input_ids.ne(__lowerCamelCase	).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        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def __init__(       self							:  str,  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  Dict,  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  Dict,  lowerCamelCase							:  str="train",  lowerCamelCase							:  List[Any]=None,  lowerCamelCase							:  Tuple=None,  lowerCamelCase							:  List[str]=None,  lowerCamelCase							:  int="",  )->					List[Any]:
								super().__init__()
								lowerCamelCase__		:		Tuple			=Path(lowerCamelCase     ).joinpath(type_path + '''.source'''     )
								lowerCamelCase__		:		str			=Path(lowerCamelCase     ).joinpath(type_path + '''.target'''     )
								lowerCamelCase__		:		Dict			=self.get_char_lens(self.src_file     )
								lowerCamelCase__		:		Tuple			=max_source_length
								lowerCamelCase__		:		Optional[int]			=max_target_length
								assert min(self.src_lens     ) > 0, F'''found empty line in {self.src_file}'''
								lowerCamelCase__		:		Dict			=tokenizer
								lowerCamelCase__		:		List[str]			=prefix
								if n_obs is not None:
											lowerCamelCase__		:		int			=self.src_lens[:n_obs]
								lowerCamelCase__		:		Dict			=src_lang
								lowerCamelCase__		:		Tuple			=tgt_lang



					def __len__(       self							:  Dict     )->					Optional[int]:
								return len(self.src_lens     )



					def __getitem__(       self							:  List[str],  lowerCamelCase							:  Optional[int]     )->					Dict[str, torch.Tensor]:
								lowerCamelCase__		:		List[Any]			=index + 1  # linecache starts at 1
								lowerCamelCase__		:		Optional[int]			=self.prefix + linecache.getline(str(self.src_file     ),  lowerCamelCase     ).rstrip('''\n'''     )
								lowerCamelCase__		:		Optional[Any]			=linecache.getline(str(self.tgt_file     ),  lowerCamelCase     ).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,  lowerCamelCase     ):
											source_line += self.tokenizer.eos_token
											tgt_line += self.tokenizer.eos_token

								# Pad source and target to the right
								lowerCamelCase__		:		Optional[int]			=(
								    self.tokenizer.question_encoder if isinstance(self.tokenizer,  lowerCamelCase     ) else self.tokenizer
								)
								lowerCamelCase__		:		Tuple			=self.tokenizer.generator if isinstance(self.tokenizer,  lowerCamelCase     ) else self.tokenizer

								lowerCamelCase__		:		Optional[int]			=encode_line(lowerCamelCase,  lowerCamelCase,  self.max_source_length,  '''right'''     )
								lowerCamelCase__		:		str			=encode_line(lowerCamelCase,  lowerCamelCase,  self.max_target_length,  '''right'''     )

								lowerCamelCase__		:		str			=source_inputs['''input_ids'''].squeeze()
								lowerCamelCase__		:		str			=target_inputs['''input_ids'''].squeeze()
								lowerCamelCase__		:		Union[str, Any]			=source_inputs['''attention_mask'''].squeeze()
								return {
								    "input_ids": source_ids,
								    "attention_mask": src_mask,
								    "decoder_input_ids": target_ids,
								}



					@staticmethod
					def 		snake_case       (       lowerCamelCase							:  Union[str, Any]     )->					Optional[int]:
								return [len(lowerCamelCase     ) for x in Path(lowerCamelCase     ).open().readlines()]




					def 		snake_case       (       self							:  str,  lowerCamelCase							:  str     )->					Dict[str, torch.Tensor]:
								lowerCamelCase__		:		List[Any]			=torch.stack([x['''input_ids'''] for x in batch]     )
								lowerCamelCase__		:		int			=torch.stack([x['''attention_mask'''] for x in batch]     )
								lowerCamelCase__		:		Union[str, Any]			=torch.stack([x['''decoder_input_ids'''] for x in batch]     )
								lowerCamelCase__		:		str			=(
								    self.tokenizer.generator.pad_token_id
								    if isinstance(self.tokenizer,  lowerCamelCase     )
								    else self.tokenizer.pad_token_id
								)
								lowerCamelCase__		:		List[str]			=(
								    self.tokenizer.question_encoder.pad_token_id
								    if isinstance(self.tokenizer,  lowerCamelCase     )
								    else self.tokenizer.pad_token_id
								)
								lowerCamelCase__		:		Optional[int]			=trim_batch(lowerCamelCase,  lowerCamelCase     )
								lowerCamelCase__	,   lowerCamelCase__		:		Any			=trim_batch(lowerCamelCase,  lowerCamelCase,  attention_mask=lowerCamelCase     )
								lowerCamelCase__		:		List[str]			={
								    '''input_ids''': source_ids,
								    '''attention_mask''': source_mask,
								    '''decoder_input_ids''': y,
								}
								return batch





_lowercase : Any      						=						getLogger(__name__)






def      snake_case__   (		__lowerCamelCase				:    List[List]	):
			"""simple docstring"""
			return list(itertools.chain.from_iterable(__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Dict			=get_git_info()
			save_json(__lowerCamelCase							,		os.path.join(__lowerCamelCase							,		'''git_log.json'''	)	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Optional[int]							,		__lowerCamelCase				:    Dict=4							,		**__lowerCamelCase				:    int	):
			"""simple docstring"""
			with open(__lowerCamelCase							,		'''w'''	) as f:
						json.dump(__lowerCamelCase							,		__lowerCamelCase							,		indent=__lowerCamelCase							,		**__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			with open(__lowerCamelCase	) as f:
						return json.load(__lowerCamelCase	)






def      snake_case__   (		):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]			=git.Repo(search_parent_directories=__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			={
			    '''repo_id''': str(__lowerCamelCase	),
			    '''repo_sha''': str(repo.head.object.hexsha	),
			    '''repo_branch''': str(repo.active_branch	),
			    '''hostname''': str(socket.gethostname()	),
			}
			return repo_infos






def      snake_case__   (		__lowerCamelCase				:    Callable							,		__lowerCamelCase				:    Iterable	):
			"""simple docstring"""
			return list(map(__lowerCamelCase							,		__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			with open(__lowerCamelCase							,		'''wb'''	) as f:
						return pickle.dump(__lowerCamelCase							,		__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""

			def remove_articles(__lowerCamelCase				:    List[Any]	):
						return re.sub(R'''\b(a|an|the)\b'''							,		''' '''							,		__lowerCamelCase	)

			def white_space_fix(__lowerCamelCase				:    Any	):
						return " ".join(text.split()	)

			def remove_punc(__lowerCamelCase				:    Optional[Any]	):
						lowerCamelCase__		:		Tuple			=set(string.punctuation	)
						return "".join(ch for ch in text if ch not in exclude	)

			def lower(__lowerCamelCase				:    Any	):
						return text.lower()

			return white_space_fix(remove_articles(remove_punc(lower(__lowerCamelCase	)	)	)	)






def      snake_case__   (		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			lowerCamelCase__		:		List[str]			=normalize_answer(__lowerCamelCase	).split()
			lowerCamelCase__		:		List[str]			=normalize_answer(__lowerCamelCase	).split()
			lowerCamelCase__		:		Optional[int]			=Counter(__lowerCamelCase	) & Counter(__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			=sum(common.values()	)
			if num_same == 0:
						return 0
			lowerCamelCase__		:		Dict			=1.0 * num_same / len(__lowerCamelCase	)
			lowerCamelCase__		:		List[str]			=1.0 * num_same / len(__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			=(2 * precision * recall) / (precision + recall)
			return fa






def      snake_case__   (		__lowerCamelCase				:    Dict							,		__lowerCamelCase				:    int	):
			"""simple docstring"""
			return normalize_answer(__lowerCamelCase	) == normalize_answer(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			assert len(__lowerCamelCase	) == len(__lowerCamelCase	)
			lowerCamelCase__		:		Any			=0
			for hypo, pred in zip(__lowerCamelCase							,		__lowerCamelCase	):
						em += exact_match_score(__lowerCamelCase							,		__lowerCamelCase	)
			if len(__lowerCamelCase	) > 0:
						em /= len(__lowerCamelCase	)
			return {"em": em}






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			return model_prefix.startswith('''rag'''	)






def      snake_case__   (		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Any			={p: p for p in extra_params}
			# T5 models don't have `dropout` param, they have `dropout_rate` instead
			lowerCamelCase__		:		Optional[int]			='''dropout_rate'''
			for p in extra_params:
						if getattr(__lowerCamelCase							,		__lowerCamelCase							,		__lowerCamelCase	):
									if not hasattr(__lowerCamelCase							,		__lowerCamelCase	) and not hasattr(__lowerCamelCase							,		equivalent_param[p]	):
												logger.info('''config doesn\'t have a `{}` attribute'''.format(__lowerCamelCase	)	)
												delattr(__lowerCamelCase							,		__lowerCamelCase	)
												continue
									lowerCamelCase__		:		List[Any]			=p if hasattr(__lowerCamelCase							,		__lowerCamelCase	) else equivalent_param[p]
									setattr(__lowerCamelCase							,		__lowerCamelCase							,		getattr(__lowerCamelCase							,		__lowerCamelCase	)	)
									delattr(__lowerCamelCase							,		__lowerCamelCase	)
			return hparams, config




