

'''simple docstring'''






from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__   		=      logging.get_logger(__name__)

lowerCAmelCase__   		=      {
    '''microsoft/trocr-base-handwritten''': (
        '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'''
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}






class      lowercase_      (lowerCamelCase__ ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE       :    Union[str, Any]							     =     'trocr'
  SCREAMING_SNAKE_CASE       :    Optional[Any]							     =     ['past_key_values']
  SCREAMING_SNAKE_CASE       :    Optional[int]							     =     {
      'num_attention_heads': 'decoder_attention_heads',
      'hidden_size': 'd_model',
      'num_hidden_layers': 'decoder_layers',
  }






  def __init__( self  :	Union[str, Any]   ,lowercase__  :	Dict=5_0_2_6_5   ,lowercase__  :	Dict=1_0_2_4   ,lowercase__  :	Union[str, Any]=1_2   ,lowercase__  :	Optional[int]=1_6   ,lowercase__  :	int=4_0_9_6   ,lowercase__  :	str="gelu"   ,lowercase__  :	Any=5_1_2   ,lowercase__  :	List[str]=0.1   ,lowercase__  :	Tuple=0.0   ,lowercase__  :	Optional[Any]=0.0   ,lowercase__  :	int=2   ,lowercase__  :	List[Any]=0.0_2   ,lowercase__  :	Optional[Any]=0.0   ,lowercase__  :	int=True   ,lowercase__  :	str=False   ,lowercase__  :	List[str]=True   ,lowercase__  :	str=True   ,lowercase__  :	Any=1   ,lowercase__  :	Any=0   ,lowercase__  :	Union[str, Any]=2   ,**lowercase__  :	Union[str, Any]   ,):
   __lowercase				    =					vocab_size
   __lowercase				    =					d_model
   __lowercase				    =					decoder_layers
   __lowercase				    =					decoder_attention_heads
   __lowercase				    =					decoder_ffn_dim
   __lowercase				    =					activation_function
   __lowercase				    =					max_position_embeddings
   __lowercase				    =					dropout
   __lowercase				    =					attention_dropout
   __lowercase				    =					activation_dropout
   __lowercase				    =					init_std
   __lowercase				    =					decoder_layerdrop
   __lowercase				    =					use_cache
   __lowercase				    =					scale_embedding
   __lowercase				    =					use_learned_position_embeddings
   __lowercase				    =					layernorm_embedding

   super().__init__(
       pad_token_id=lowercase__   ,bos_token_id=lowercase__   ,eos_token_id=lowercase__   ,decoder_start_token_id=lowercase__   ,**lowercase__   ,)




import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


A_			:					Any    			=     logging.get_logger(__name__)



class        _a		:


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			None



@experimental
def 		UpperCamelCase   (lowercase_:					int       , lowercase_:					Any       , lowercase_:					str       , lowercase_:					str       , lowercase_:					List[str]       , lowercase_:					List[Any]       , lowercase_:					Union[str, Any]   )	-> Union[str, Any]:
	if ParallelBackendConfig.backend_name is None:
		return _map_with_multiprocessing_pool(
		    lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_   )

	return _map_with_joblib(lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_   )

def 		UpperCamelCase   (lowercase_:					Tuple       , lowercase_:					List[Any]       , lowercase_:					Tuple       , lowercase_:					Tuple       , lowercase_:					List[str]       , lowercase_:					Dict       , lowercase_:					Tuple   )	-> Tuple:
	A__				:       Union[str, Any]	  =						num_proc if num_proc <= len(lowercase_   ) else len(lowercase_   )
	A__				:       str	  =						[]  # We organize the splits ourselve (contiguous splits)
	for index in range(lowercase_   ):
		A__				:       Tuple	  =						len(lowercase_   ) // num_proc
		A__				:       Tuple	  =						len(lowercase_   ) % num_proc
		A__				:       Optional[Any]	  =						div * index + min(lowercase_       , lowercase_   )
		A__				:       Union[str, Any]	  =						start + div + (1 if index < mod else 0)
		split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)   )

	if len(lowercase_   ) != sum(len(i[1]   ) for i in split_kwds   ):
		raise ValueError(
		    f"""Error dividing inputs iterable among processes. """
		    f"""Total number of objects {len(lowercase_   )}, """
		    f"""length: {sum(len(i[1]   ) for i in split_kwds   )}"""   )

	logger.info(
	    f"""Spawning {num_proc} processes for {len(lowercase_   )} objects in slices of {[len(i[1]   ) for i in split_kwds]}"""   )
	A__  ,  A__				:       Optional[int]	  =						None, None
	if not disable_tqdm:
		A__  ,  A__				:       List[str]	  =						(RLock(),), tqdm.set_lock
	with Pool(lowercase_       , initargs=lowercase_       , initializer=lowercase_   ) as pool:
		A__				:       Optional[Any]	  =						pool.map(lowercase_       , lowercase_   )
	logger.info(f"""Finished {num_proc} processes"""   )
	A__				:       Tuple	  =						[obj for proc_res in mapped for obj in proc_res]
	logger.info(f"""Unpacked {len(lowercase_   )} objects"""   )

	return mapped

def 		UpperCamelCase   (lowercase_:					Union[str, Any]       , lowercase_:					Dict       , lowercase_:					str       , lowercase_:					Union[str, Any]       , lowercase_:					List[Any]       , lowercase_:					Dict       , lowercase_:					Optional[Any]   )	-> Union[str, Any]:
	# progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
	# and it requires monkey-patching joblib internal classes which is subject to change
	import joblib

	with joblib.parallel_backend(ParallelBackendConfig.backend_name       , n_jobs=lowercase_   ):
		return joblib.Parallel()(
		    joblib.delayed(lowercase_   )((function, obj, types, None, True, None)   ) for obj in iterable   )


@experimental
@contextlib.contextmanager
def 		UpperCamelCase   (lowercase_:					str   )	-> str:
	A__				:       int	  =						backend_name

	if backend_name == "spark":
		from joblibspark import register_spark

		register_spark()

		# TODO: call create_cache_and_write_probe if "download" in steps
		# TODO: raise NotImplementedError when Dataset.map etc is called

	try:
		yield
	finally:
		A__				:       Optional[Any]	  =						None



