


'''simple docstring'''


import os
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ... import AutoTokenizer
from ...utils import logging


UpperCAmelCase_	:     str							     =	'block_records.npy'


UpperCAmelCase_	:     str							     =	logging.get_logger(__name__)







def     snake_case_     (						SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





				import tensorflow.compat.va as tf

				_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   tf.data.TFRecordDataset(SCREAMING_SNAKE_CASE__							,   buffer_size=512 * 1024 * 1024  )
				_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   blocks_dataset.batch(SCREAMING_SNAKE_CASE__							,   drop_remainder=SCREAMING_SNAKE_CASE__  )
				_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   next(blocks_dataset.take(1  ).as_numpy_iterator()  )

				return np_record





class 					lowercase__						:





							'''simple docstring'''


							def __init__(					self					,      __snake_case					,      __snake_case					,      __snake_case=2					,      __snake_case=1000					,      __snake_case=100					,      __snake_case=10_0000					,      ):
											from scann.scann_ops.py.scann_ops_pybind import builder as Builder

											_SCREAMING_SNAKE_CASE				: str  	=   Builder(db=__snake_case					,      num_neighbors=__snake_case					,      distance_measure="""dot_product"""						)
											_SCREAMING_SNAKE_CASE				: List[str]  	=   builder.tree(
											    num_leaves=__snake_case					,      num_leaves_to_search=__snake_case					,      training_sample_size=__snake_case						)
											_SCREAMING_SNAKE_CASE				: Optional[int]  	=   builder.score_ah(dimensions_per_block=__snake_case						)

											_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   builder.build()






							def UpperCAmelCase_			(					self					,      __snake_case						):
											_SCREAMING_SNAKE_CASE	, _SCREAMING_SNAKE_CASE				: Optional[Any]  	=   self.searcher.search_batched(question_projection.detach().cpu()						)
											return retrieved_block_ids.astype("""int64"""						)





class 					lowercase__						:





							'''simple docstring'''


							def __init__(					self					,      __snake_case					,      __snake_case						):
											super().__init__()
											_SCREAMING_SNAKE_CASE				: int  	=   block_records
											_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   tokenizer






							def __call__(					self					,      __snake_case					,      __snake_case					,      __snake_case					,      __snake_case=None					,      __snake_case="pt"						):
											_SCREAMING_SNAKE_CASE				: List[str]  	=   np.take(self.block_records					,      indices=__snake_case					,      axis=0						)

											_SCREAMING_SNAKE_CASE				: Tuple  	=   self.tokenizer.decode(question_input_ids[0]					,      skip_special_tokens=__snake_case						)

											_SCREAMING_SNAKE_CASE				: Any  	=   []
											_SCREAMING_SNAKE_CASE				: Any  	=   []
											for retrieved_block in retrieved_blocks:
															text.append(__snake_case						)
															text_pair.append(retrieved_block.decode()						)

											_SCREAMING_SNAKE_CASE				: List[Any]  	=   self.tokenizer(
											    __snake_case					,      __snake_case					,      padding=__snake_case					,      truncation=__snake_case					,      return_special_tokens_mask=__snake_case					,      max_length=__snake_case						)
											_SCREAMING_SNAKE_CASE				: Any  	=   concat_inputs.convert_to_tensors(__snake_case						)

											if answer_ids is not None:
															return self.block_has_answer(__snake_case					,      __snake_case						) + (concat_inputs_tensors,)
											else:
															return (None, None, None, concat_inputs_tensors)






							@classmethod
							def UpperCAmelCase_			(					cls					,      __snake_case					,      *__snake_case					,      **__snake_case						):
											if os.path.isdir(__snake_case						):
															_SCREAMING_SNAKE_CASE				: Optional[int]  	=   os.path.join(__snake_case					,      _REALM_BLOCK_RECORDS_FILENAME						)
											else:
															_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   hf_hub_download(
															    repo_id=__snake_case					,      filename=_REALM_BLOCK_RECORDS_FILENAME					,      **__snake_case						)
											_SCREAMING_SNAKE_CASE				: Dict  	=   np.load(__snake_case					,      allow_pickle=__snake_case						)

											_SCREAMING_SNAKE_CASE				: Tuple  	=   AutoTokenizer.from_pretrained(__snake_case					,      *__snake_case					,      **__snake_case						)

											return cls(__snake_case					,      __snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case						):
											# save block records
											np.save(os.path.join(__snake_case					,      _REALM_BLOCK_RECORDS_FILENAME						)					,      self.block_records						)
											# save tokenizer
											self.tokenizer.save_pretrained(__snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case						):
											_SCREAMING_SNAKE_CASE				: Dict  	=   []
											_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   []
											_SCREAMING_SNAKE_CASE				: Tuple  	=   []
											_SCREAMING_SNAKE_CASE				: Tuple  	=   0

											for input_id in concat_inputs.input_ids:
															_SCREAMING_SNAKE_CASE				: str  	=   input_id.tolist()
															# Check answers between two [SEP] tokens
															_SCREAMING_SNAKE_CASE				: List[Any]  	=   input_id_list.index(self.tokenizer.sep_token_id						)
															_SCREAMING_SNAKE_CASE				: Dict  	=   first_sep_idx + 1 + input_id_list[first_sep_idx + 1 :].index(self.tokenizer.sep_token_id						)

															start_pos.append([]						)
															end_pos.append([]						)
															for answer in answer_ids:
																			for idx in range(first_sep_idx + 1					,      __snake_case						):
																							if answer[0] == input_id_list[idx]:
																											if input_id_list[idx : idx + len(__snake_case						)] == answer:
																															start_pos[-1].append(__snake_case						)
																															end_pos[-1].append(idx + len(__snake_case						) - 1						)

															if len(start_pos[-1]						) == 0:
																			has_answers.append(__snake_case						)
															else:
																			has_answers.append(__snake_case						)
																			if len(start_pos[-1]						) > max_answers:
																							_SCREAMING_SNAKE_CASE				: str  	=   len(start_pos[-1]						)

        # Pad -1 to max_answers
											for start_pos_, end_pos_ in zip(__snake_case					,      __snake_case						):
															if len(start_pos_						) < max_answers:
																			_SCREAMING_SNAKE_CASE				: Dict  	=   [-1] * (max_answers - len(start_pos_						))
																			start_pos_ += padded
																			end_pos_ += padded
											return has_answers, start_pos, end_pos








'''simple docstring'''


import argparse
import copy
import json
import multiprocessing
import os
import time

from create_dummy_models import COMPOSITE_MODELS, create_tiny_models
from huggingface_hub import ModelFilter, hf_api

import transformers
from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer
from transformers.image_processing_utils import BaseImageProcessor







def     snake_case_     (						):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE				: str  	=   set()
				# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
				for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
								_SCREAMING_SNAKE_CASE				: Any  	=   getattr(transformers.models.auto							,   SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  )
								if module is None:
												continue
								# all mappings in a single auto modeling file
								_SCREAMING_SNAKE_CASE				: str  	=   [
								    x
								    for x in dir(SCREAMING_SNAKE_CASE__  )
								    if x.endswith("""_MAPPING_NAMES"""  )
								    and (x.startswith("""MODEL_"""  ) or x.startswith("""TF_MODEL_"""  ) or x.startswith("""FLAX_MODEL_"""  ))
								]
								for name in mapping_names:
												_SCREAMING_SNAKE_CASE				: Optional[int]  	=   getattr(SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  )
												if mapping is not None:
																for v in mapping.values():
																				if isinstance(SCREAMING_SNAKE_CASE__							,   (list, tuple)  ):
																								model_names.update(SCREAMING_SNAKE_CASE__  )
																				elif isinstance(SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):
																								model_names.add(SCREAMING_SNAKE_CASE__  )

				return sorted(SCREAMING_SNAKE_CASE__  )







def     snake_case_     (						):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   set(get_all_model_names()  )

				with open("""tests/utils/tiny_model_summary.json"""  ) as fp:
								_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   json.load(SCREAMING_SNAKE_CASE__  )
				_SCREAMING_SNAKE_CASE				: str  	=   set()
				for model_base_name in tiny_model_info:
								tiny_models_names.update(tiny_model_info[model_base_name]["""model_classes"""]  )

				# Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub.
				_SCREAMING_SNAKE_CASE				: str  	=   model_names.difference(SCREAMING_SNAKE_CASE__  )
				for model_name in copy.copy(SCREAMING_SNAKE_CASE__  ):
								if not model_name.startswith("""TF"""  ) and f"""TF{model_name}""" in not_on_hub:
												tiny_models_names.remove(SCREAMING_SNAKE_CASE__  )
								elif model_name.startswith("""TF"""  ) and model_name[2:] in not_on_hub:
												tiny_models_names.remove(SCREAMING_SNAKE_CASE__  )

				return sorted(SCREAMING_SNAKE_CASE__  )







def     snake_case_     (						SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE				: Optional[int]  	=   COMPOSITE_MODELS.values()

				# All tiny model base names on Hub
				_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   get_all_model_names()
				_SCREAMING_SNAKE_CASE				: Optional[int]  	=   hf_api.list_models(
				    filter=ModelFilter(
				        author="""hf-internal-testing"""							,   )  )
				_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   set()
				for x in models:
								_SCREAMING_SNAKE_CASE				: Tuple  	=   x.modelId
								_SCREAMING_SNAKE_CASE	, _SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   model.split("""/"""  )
								if not model.startswith("""tiny-random-"""  ):
												continue
								_SCREAMING_SNAKE_CASE				: List[Any]  	=   model.replace("""tiny-random-"""							,   """"""  )
								if not model[0].isupper():
												continue
								if model not in model_names and model not in special_models:
												continue
								_models.add(SCREAMING_SNAKE_CASE__  )

				_SCREAMING_SNAKE_CASE				: Optional[int]  	=   sorted(_models  )
				# All tiny model names on Hub
				_SCREAMING_SNAKE_CASE				: Dict  	=   {}
				for model in models:
								_SCREAMING_SNAKE_CASE				: str  	=   f"""hf-internal-testing/tiny-random-{model}"""
								_SCREAMING_SNAKE_CASE				: List[Any]  	=   model.split("""-"""  )[0]
								try:
												_SCREAMING_SNAKE_CASE				: Tuple  	=   hf_api.repo_info(SCREAMING_SNAKE_CASE__  )
												_SCREAMING_SNAKE_CASE				: Optional[int]  	=   {
												    """tokenizer_classes""": set(),
												    """processor_classes""": set(),
												    """model_classes""": set(),
												    """sha""": repo_info.sha,
												}
								except Exception:
												continue
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: Optional[int]  	=   AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__  )
												content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__  )
								except Exception:
												pass
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: int  	=   AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__							,   use_fast=SCREAMING_SNAKE_CASE__  )
												content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__  )
								except Exception:
												pass
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: str  	=   AutoImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__  )
												content["processor_classes"].add(img_p.__class__.__name__  )
								except Exception:
												pass
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: Any  	=   AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__  )
												if not isinstance(SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):
																content["processor_classes"].add(feat_p.__class__.__name__  )
								except Exception:
												pass
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: int  	=   getattr(SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  )
												_SCREAMING_SNAKE_CASE				: Tuple  	=   model_class.from_pretrained(SCREAMING_SNAKE_CASE__  )
												content["model_classes"].add(m.__class__.__name__  )
								except Exception:
												pass
								try:
												time.sleep(1  )
												_SCREAMING_SNAKE_CASE				: List[Any]  	=   getattr(SCREAMING_SNAKE_CASE__							,   f"""TF{model}"""  )
												_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   model_class.from_pretrained(SCREAMING_SNAKE_CASE__  )
												content["model_classes"].add(m.__class__.__name__  )
								except Exception:
												pass

								_SCREAMING_SNAKE_CASE				: List[Any]  	=   sorted(content["""tokenizer_classes"""]  )
								_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   sorted(content["""processor_classes"""]  )
								_SCREAMING_SNAKE_CASE				: List[Any]  	=   sorted(content["""model_classes"""]  )

								_SCREAMING_SNAKE_CASE				: List[Any]  	=   content
								with open(os.path.join(SCREAMING_SNAKE_CASE__							,   """hub_tiny_model_summary.json"""  )							,   """w"""  ) as fp:
												json.dump(SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__							,   ensure_ascii=SCREAMING_SNAKE_CASE__							,   indent=4  )


if __name__ == "__main__":
				UpperCAmelCase_	:     Any							     =	argparse.ArgumentParser()
				parser.add_argument('--num_workers', default=1, type=int, help='The number of workers to run.')
				UpperCAmelCase_	:     Optional[int]							     =	parser.parse_args()

				# This has to be `spawn` to avoid hanging forever!
				multiprocessing.set_start_method('spawn')

				UpperCAmelCase_	:     Any							     =	'tiny_models'
				UpperCAmelCase_	:     Tuple							     =	True
				UpperCAmelCase_	:     Tuple							     =	None
				UpperCAmelCase_	:     Optional[int]							     =	get_tiny_model_names_from_repo()
				UpperCAmelCase_	:     Dict							     =	True
				UpperCAmelCase_	:     str							     =	True
				UpperCAmelCase_	:     Optional[int]							     =	'hf-internal-testing'

				create_tiny_models(
				    output_path,
				    all,
				    model_types,
				    models_to_skip,
				    no_check,
				    upload,
				    organization,
				    token=os.environ.get('TOKEN', None),
				    num_workers=args.num_workers,
				)




