'''simple docstring'''


import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
import regex

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy


__lowerCAmelCase	:       List[str]						       =	logging.get_logger(__name__)

__lowerCAmelCase	:       Union[str, Any]						       =	{
    "artists_file": "artists.json",
    "lyrics_file": "lyrics.json",
    "genres_file": "genres.json",
}

__lowerCAmelCase	:       Any						       =	{
    "artists_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json",
    },
    "genres_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json",
    },
    "lyrics_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json",
    },
}

__lowerCAmelCase	:       Dict						       =	{
    "jukebox": 512,
}






class 						A   (   UpperCAmelCase   ):
       a_        =      VOCAB_FILES_NAMES
       a_        =      PRETRAINED_VOCAB_FILES_MAP
       a_        =      PRETRAINED_LYRIC_TOKENS_SIZES
       a_        =      ['''input_ids''', '''attention_mask''']





       def __init__(      self				:							int     ,		__a				:							str     ,		__a				:							Optional[int]     ,		__a				:							Tuple     ,		__a				:							Union[str, Any]=["v3", "v2", "v2"]     ,		__a				:							List[Any]=5_1_2     ,		__a				:							Tuple=5     ,		__a				:							List[Any]="<|endoftext|>"     ,		**__a				:							Optional[Any]     ,		)							->	Any:
        __UpperCAmelCase							=			AddedToken(__a     ,		lstrip=__a     ,		rstrip=__a	) if isinstance(__a     ,		__a	) else unk_token
        super().__init__(
            unk_token=__a     ,		n_genres=__a     ,		version=__a     ,		max_n_lyric_tokens=__a     ,		**__a     ,		)
        __UpperCAmelCase							=			version
        __UpperCAmelCase							=			max_n_lyric_tokens
        __UpperCAmelCase							=			n_genres

        with open(__a     ,		encoding='''utf-8'''	) as vocab_handle:
         __UpperCAmelCase							=			json.load(__a	)

        with open(__a     ,		encoding='''utf-8'''	) as vocab_handle:
         __UpperCAmelCase							=			json.load(__a	)

        with open(__a     ,		encoding='''utf-8'''	) as vocab_handle:
         __UpperCAmelCase							=			json.load(__a	)

        __UpperCAmelCase							=			r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'''
        # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
        if len(self.lyrics_encoder	) == 7_9:
         __UpperCAmelCase							=			oov.replace(r'''\-\''''     ,		r'''\-+\''''	)

        __UpperCAmelCase							=			regex.compile(__a	)
        __UpperCAmelCase							=			{v: k for k, v in self.artists_encoder.items()}
        __UpperCAmelCase							=			{v: k for k, v in self.genres_encoder.items()}
        __UpperCAmelCase							=			{v: k for k, v in self.lyrics_encoder.items()}





       @property
       def       snake_case__						(      self				:							Optional[int]	)							->	List[Any]:
        return len(self.artists_encoder	) + len(self.genres_encoder	) + len(self.lyrics_encoder	)





       def       snake_case__						(      self				:							Dict	)							->	Optional[Any]:
        return dict(self.artists_encoder     ,		self.genres_encoder     ,		self.lyrics_encoder	)





       def       snake_case__						(      self				:							Optional[Any]     ,		__a				:							List[Any]     ,		__a				:							Tuple     ,		__a				:							Optional[int]	)							->	List[Any]:
        __UpperCAmelCase							=			[self.artists_encoder.get(__a     ,		0	) for artist in list_artists]
        for genres in range(len(__a	)	):
         __UpperCAmelCase							=			[self.genres_encoder.get(__a     ,		0	) for genre in list_genres[genres]]
         __UpperCAmelCase							=			list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]	))

        __UpperCAmelCase							=			[[self.lyrics_encoder.get(__a     ,		0	) for character in list_lyrics[0]], [], []]
        return artists_id, list_genres, lyric_ids





       def       snake_case__						(      self				:							List[str]     ,		__a				:							List[Any]	)							->	Optional[int]:
        return list(__a	)





       def       snake_case__						(      self				:							Union[str, Any]     ,		__a				:							Union[str, Any]     ,		__a				:							Any     ,		__a				:							str     ,		**__a				:							Optional[Any]	)							->	Dict:
        __UpperCAmelCase				,			__UpperCAmelCase				,			__UpperCAmelCase							=			self.prepare_for_tokenization(__a     ,		__a     ,		__a	)
        __UpperCAmelCase							=			self._tokenize(__a	)
        return artist, genre, lyrics





       def       snake_case__						(      self				:							int     ,		__a				:							str     ,		__a				:							str     ,		__a				:							str     ,		__a				:							bool = False	)							->	Tuple[str, str, str, Dict[str, Any]]:
        for idx in range(len(self.version	)	):
         if self.version[idx] == "v3":
          __UpperCAmelCase							=			artists[idx].lower()
          __UpperCAmelCase							=			[genres[idx].lower()]
         else:
          __UpperCAmelCase							=			self._normalize(artists[idx]	) + '''.v2'''
          __UpperCAmelCase							=			[
              self._normalize(__a	) + '''.v2''' for genre in genres[idx].split('''_'''	)
          ]  # split is for the full dictionary with combined genres

        if self.version[0] == "v2":
         __UpperCAmelCase							=			regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'''	)
         __UpperCAmelCase							=			'''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n'''
         __UpperCAmelCase							=			{vocab[index]: index + 1 for index in range(len(__a	)	)}
         __UpperCAmelCase							=			0
         __UpperCAmelCase							=			len(__a	) + 1
         __UpperCAmelCase							=			self.vocab
         __UpperCAmelCase							=			{v: k for k, v in self.vocab.items()}
         __UpperCAmelCase							=			''''''
        else:
         __UpperCAmelCase							=			regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+'''	)

        __UpperCAmelCase							=			self._run_strip_accents(__a	)
        __UpperCAmelCase							=			lyrics.replace('''\\'''     ,		'''\n'''	)
        __UpperCAmelCase							=			self.out_of_vocab.sub(''''''     ,		__a	), [], []
        return artists, genres, lyrics





       def       snake_case__						(      self				:							Optional[int]     ,		__a				:							Tuple	)							->	Optional[int]:
        __UpperCAmelCase							=			unicodedata.normalize('''NFD'''     ,		__a	)
        __UpperCAmelCase							=			[]
        for char in text:
         __UpperCAmelCase							=			unicodedata.category(__a	)
         if cat == "Mn":
          continue
         output.append(__a	)
        return "".join(__a	)





       def       snake_case__						(      self				:							int     ,		__a				:							str	)							->	str:
        __UpperCAmelCase							=			(
            [chr(__a	) for i in range(ord('''a'''	)     ,		ord('''z'''	) + 1	)]
            + [chr(__a	) for i in range(ord('''A'''	)     ,		ord('''Z'''	) + 1	)]
            + [chr(__a	) for i in range(ord('''0'''	)     ,		ord('''9'''	) + 1	)]
            + ['''.''']
        )
        __UpperCAmelCase							=			frozenset(__a	)
        __UpperCAmelCase							=			re.compile(r'''_+'''	)
        __UpperCAmelCase							=			''''''.join([c if c in accepted else '''_''' for c in text.lower()]	)
        __UpperCAmelCase							=			pattern.sub('''_'''     ,		__a	).strip('''_'''	)
        return text





       def       snake_case__						(      self				:							Union[str, Any]     ,		__a				:							List[str]	)							->	str:
        return " ".join(__a	)





       def       snake_case__						(      self				:							List[str]     ,		__a				:							Dict     ,		__a				:							Optional[Union[str, TensorType]] = None     ,		__a				:							bool = False	)							->	Union[str, Any]:
        # Convert to TensorType
        if not isinstance(__a     ,		__a	):
         __UpperCAmelCase							=			TensorType(__a	)

        # Get a function reference for the correct framework
        if tensor_type == TensorType.TENSORFLOW:
         if not is_tf_available():
          raise ImportError(
              '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.'''	)
         import tensorflow as tf

         __UpperCAmelCase							=			tf.constant
         __UpperCAmelCase							=			tf.is_tensor
        elif tensor_type == TensorType.PYTORCH:
         if not is_torch_available():
          raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.'''	)
         import torch

         __UpperCAmelCase							=			torch.tensor
         __UpperCAmelCase							=			torch.is_tensor
        elif tensor_type == TensorType.JAX:
         if not is_flax_available():
          raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.'''	)
         import jax.numpy as jnp  # noqa: F811

         __UpperCAmelCase							=			jnp.array
         __UpperCAmelCase							=			_is_jax
        else:
         __UpperCAmelCase							=			np.asarray
         __UpperCAmelCase							=			_is_numpy

        # Do the tensor conversion in batch

        try:
         if prepend_batch_axis:
          __UpperCAmelCase							=			[inputs]

         if not is_tensor(__a	):
          __UpperCAmelCase							=			as_tensor(__a	)
        except:  # noqa E722
         raise ValueError(
             '''Unable to create tensor, you should probably activate truncation and/or padding '''
             '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.'''	)

        return inputs





       def __call__(      self				:							Dict     ,		__a				:							Optional[int]     ,		__a				:							Union[str, Any]     ,		__a				:							int=""     ,		__a				:							Dict="pt"	)							->	BatchEncoding:
        __UpperCAmelCase							=			[0, 0, 0]
        __UpperCAmelCase							=			[artist] * len(self.version	)
        __UpperCAmelCase							=			[genres] * len(self.version	)

        __UpperCAmelCase				,			__UpperCAmelCase				,			__UpperCAmelCase							=			self.tokenize(__a     ,		__a     ,		__a	)
        __UpperCAmelCase				,			__UpperCAmelCase				,			__UpperCAmelCase							=			self._convert_token_to_id(__a     ,		__a     ,		__a	)

        __UpperCAmelCase							=			[-INFINITY] * len(full_tokens[-1]	)
        __UpperCAmelCase							=			[
            self.convert_to_tensors(
                [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]]     ,		tensor_type=__a	)
            for i in range(len(self.version	)	)
        ]
        return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks}	)





       def       snake_case__						(      self				:							Tuple     ,		__a				:							str     ,		__a				:							Optional[str] = None	)							->	Tuple[str]:
        if not os.path.isdir(__a	):
         logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""	)
         return

        __UpperCAmelCase							=			os.path.join(
            __a     ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''artists_file''']	)
        with open(__a     ,		'''w'''     ,		encoding='''utf-8'''	) as f:
         f.write(json.dumps(self.artists_encoder     ,		ensure_ascii=__a	)	)

        __UpperCAmelCase							=			os.path.join(
            __a     ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file''']	)
        with open(__a     ,		'''w'''     ,		encoding='''utf-8'''	) as f:
         f.write(json.dumps(self.genres_encoder     ,		ensure_ascii=__a	)	)

        __UpperCAmelCase							=			os.path.join(
            __a     ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file''']	)
        with open(__a     ,		'''w'''     ,		encoding='''utf-8'''	) as f:
         f.write(json.dumps(self.lyrics_encoder     ,		ensure_ascii=__a	)	)

        return (artists_file, genres_file, lyrics_file)






       def       snake_case__						(      self				:							List[Any]     ,		__a				:							Dict     ,		__a				:							str     ,		__a				:							str	)							->	str:
        __UpperCAmelCase							=			self.artists_decoder.get(__a	)
        __UpperCAmelCase							=			[self.genres_decoder.get(__a	) for genre in genres_index]
        __UpperCAmelCase							=			[self.lyrics_decoder.get(__a	) for character in lyric_index]
        return artist, genres, lyrics

'''simple docstring'''


import argparse
from pathlib import Path

import requests
import torch
from PIL import Image

from transformers import (
    RobertaTokenizer,
    TrOCRConfig,
    TrOCRForCausalLM,
    TrOCRProcessor,
    VisionEncoderDecoderModel,
    ViTConfig,
    ViTImageProcessor,
    ViTModel,
)
from transformers.utils import logging


logging.set_verbosity_info()
__lowerCAmelCase	:       Dict						       =	logging.get_logger(__name__)





def       lowerCAmelCase					(		UpperCamelCase__				:   Optional[Any]    ,					UpperCamelCase__				:   Union[str, Any]       ):


	"""simple docstring"""
	__UpperCAmelCase							=			[]
	for i in range(encoder_config.num_hidden_layers       ):
		# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.norm1.weight""", f"""encoder.encoder.layer.{i}.layernorm_before.weight""")       )
		rename_keys.append((f"""encoder.deit.blocks.{i}.norm1.bias""", f"""encoder.encoder.layer.{i}.layernorm_before.bias""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.attn.proj.weight""", f"""encoder.encoder.layer.{i}.attention.output.dense.weight""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.attn.proj.bias""", f"""encoder.encoder.layer.{i}.attention.output.dense.bias""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.norm2.weight""", f"""encoder.encoder.layer.{i}.layernorm_after.weight""")       )
		rename_keys.append((f"""encoder.deit.blocks.{i}.norm2.bias""", f"""encoder.encoder.layer.{i}.layernorm_after.bias""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.mlp.fc1.weight""", f"""encoder.encoder.layer.{i}.intermediate.dense.weight""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.mlp.fc1.bias""", f"""encoder.encoder.layer.{i}.intermediate.dense.bias""")       )
		rename_keys.append(
		    (f"""encoder.deit.blocks.{i}.mlp.fc2.weight""", f"""encoder.encoder.layer.{i}.output.dense.weight""")       )
		rename_keys.append((f"""encoder.deit.blocks.{i}.mlp.fc2.bias""", f"""encoder.encoder.layer.{i}.output.dense.bias""")       )

	# cls token, position embeddings and patch embeddings of encoder
	rename_keys.extend(
	    [
	        ('''encoder.deit.cls_token''', '''encoder.embeddings.cls_token'''),
	        ('''encoder.deit.pos_embed''', '''encoder.embeddings.position_embeddings'''),
	        ('''encoder.deit.patch_embed.proj.weight''', '''encoder.embeddings.patch_embeddings.projection.weight'''),
	        ('''encoder.deit.patch_embed.proj.bias''', '''encoder.embeddings.patch_embeddings.projection.bias'''),
	        ('''encoder.deit.norm.weight''', '''encoder.layernorm.weight'''),
	        ('''encoder.deit.norm.bias''', '''encoder.layernorm.bias'''),
	    ]       )

	return rename_keys





def       lowerCAmelCase					(		UpperCamelCase__				:   Optional[Any]    ,					UpperCamelCase__				:   List[Any]       ):


	"""simple docstring"""
	for i in range(encoder_config.num_hidden_layers       ):
		# queries, keys and values (only weights, no biases)
		__UpperCAmelCase							=			state_dict.pop(f"""encoder.deit.blocks.{i}.attn.qkv.weight"""       )

		__UpperCAmelCase							=			in_proj_weight[
		    : encoder_config.hidden_size, :
		]
		__UpperCAmelCase							=			in_proj_weight[
		    encoder_config.hidden_size : encoder_config.hidden_size * 2, :
		]
		__UpperCAmelCase							=			in_proj_weight[
		    -encoder_config.hidden_size :, :
		]





def       lowerCAmelCase					(		UpperCamelCase__				:   Any    ,					UpperCamelCase__				:   Optional[Any]    ,					UpperCamelCase__				:   List[str]       ):


	"""simple docstring"""
	__UpperCAmelCase							=			dct.pop(UpperCamelCase__       )
	__UpperCAmelCase							=			val





def       lowerCAmelCase					(		UpperCamelCase__				:   Dict       ):


	"""simple docstring"""
	if "handwritten" in checkpoint_url:
		__UpperCAmelCase							=			'''https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg'''  # industry
		# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have
		# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let
		# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"  #
		# url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg"
	elif "printed" in checkpoint_url or "stage1" in checkpoint_url:
		__UpperCAmelCase							=			'''https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg'''
	__UpperCAmelCase							=			Image.open(requests.get(UpperCamelCase__    ,					stream=UpperCamelCase__       ).raw       ).convert('''RGB'''       )
	return im





@torch.no_grad()
def       lowerCAmelCase					(		UpperCamelCase__				:   Dict    ,					UpperCamelCase__				:   Union[str, Any]       ):


	"""simple docstring"""
	__UpperCAmelCase							=			ViTConfig(image_size=3_8_4    ,					qkv_bias=UpperCamelCase__       )
	__UpperCAmelCase							=			TrOCRConfig()

	# size of the architecture
	if "base" in checkpoint_url:
		__UpperCAmelCase							=			7_6_8
	elif "large" in checkpoint_url:
		# use ViT-large encoder
		__UpperCAmelCase							=			1_0_2_4
		__UpperCAmelCase							=			4_0_9_6
		__UpperCAmelCase							=			2_4
		__UpperCAmelCase							=			1_6
		__UpperCAmelCase							=			1_0_2_4
	else:
		raise ValueError('''Should either find \'base\' or \'large\' in checkpoint URL'''       )

	# the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards
	if "large-printed" in checkpoint_url or "stage1" in checkpoint_url:
		__UpperCAmelCase							=			False
		__UpperCAmelCase							=			'''relu'''
		__UpperCAmelCase							=			1_0_2_4
		__UpperCAmelCase							=			True
		__UpperCAmelCase							=			False
		__UpperCAmelCase							=			False

	# load HuggingFace model
	__UpperCAmelCase							=			ViTModel(UpperCamelCase__    ,					add_pooling_layer=UpperCamelCase__       )
	__UpperCAmelCase							=			TrOCRForCausalLM(UpperCamelCase__       )
	__UpperCAmelCase							=			VisionEncoderDecoderModel(encoder=UpperCamelCase__    ,					decoder=UpperCamelCase__       )
	model.eval()

	# load state_dict of original model, rename some keys
	__UpperCAmelCase							=			torch.hub.load_state_dict_from_url(UpperCamelCase__    ,					map_location='''cpu'''    ,					check_hash=UpperCamelCase__       )['''model''']

	__UpperCAmelCase							=			create_rename_keys(UpperCamelCase__    ,					UpperCamelCase__       )
	for src, dest in rename_keys:
		rename_key(UpperCamelCase__    ,					UpperCamelCase__    ,					UpperCamelCase__       )
	read_in_q_k_v(UpperCamelCase__    ,					UpperCamelCase__       )

	# remove parameters we don't need
	del state_dict["encoder.deit.head.weight"]
	del state_dict["encoder.deit.head.bias"]
	del state_dict["decoder.version"]

	# add prefix to decoder keys
	for key, val in state_dict.copy().items():
		__UpperCAmelCase							=			state_dict.pop(UpperCamelCase__       )
		if key.startswith('''decoder'''       ) and "output_projection" not in key:
			__UpperCAmelCase							=			val
		else:
			__UpperCAmelCase							=			val

    # load state dict
	model.load_state_dict(UpperCamelCase__       )

	# Check outputs on an image
	__UpperCAmelCase							=			ViTImageProcessor(size=encoder_config.image_size       )
	__UpperCAmelCase							=			RobertaTokenizer.from_pretrained('''roberta-large'''       )
	__UpperCAmelCase							=			TrOCRProcessor(UpperCamelCase__    ,					UpperCamelCase__       )

	__UpperCAmelCase							=			processor(images=prepare_img(UpperCamelCase__       )    ,					return_tensors='''pt'''       ).pixel_values

	# verify logits
	__UpperCAmelCase							=			torch.tensor([[model.config.decoder.decoder_start_token_id]]       )
	__UpperCAmelCase							=			model(pixel_values=UpperCamelCase__    ,					decoder_input_ids=UpperCamelCase__       )
	__UpperCAmelCase							=			outputs.logits

	__UpperCAmelCase							=			torch.Size([1, 1, 5_0_2_6_5]       )
	if "trocr-base-handwritten" in checkpoint_url:
		__UpperCAmelCase							=			torch.tensor(
		    [-1.45_02, -4.66_83, -0.53_47, -2.92_91, 9.14_35, -3.05_71, 8.97_64, 1.75_60, 8.73_58, -1.53_11]       )
	elif "trocr-large-handwritten" in checkpoint_url:
		__UpperCAmelCase							=			torch.tensor(
		    [-2.64_37, -1.31_29, -2.25_96, -5.34_55, 6.35_39, 1.76_04, 5.49_91, 1.47_02, 5.61_13, 2.01_70]       )
	elif "trocr-base-printed" in checkpoint_url:
		__UpperCAmelCase							=			torch.tensor(
		    [-5.68_16, -5.83_88, 1.13_98, -6.90_34, 6.85_05, -2.43_93, 1.22_84, -1.02_32, -1.96_61, -3.92_10]       )
	elif "trocr-large-printed" in checkpoint_url:
		__UpperCAmelCase							=			torch.tensor(
		    [-6.01_62, -7.09_59, 4.41_55, -5.10_63, 7.04_68, -3.16_31, 2.64_66, -0.30_81, -0.81_06, -1.75_35]       )

	if "stage1" not in checkpoint_url:
		assert logits.shape == expected_shape, "Shape of logits not as expected"
		assert torch.allclose(logits[0, 0, :1_0]    ,					UpperCamelCase__    ,					atol=1E-3       ), "First elements of logits not as expected"

	Path(UpperCamelCase__       ).mkdir(exist_ok=UpperCamelCase__       )
	print(f"""Saving model to {pytorch_dump_folder_path}"""       )
	model.save_pretrained(UpperCamelCase__       )
	print(f"""Saving processor to {pytorch_dump_folder_path}"""       )
	processor.save_pretrained(UpperCamelCase__       )


if __name__ == "__main__":
					__lowerCAmelCase	:       Any						       =	argparse.ArgumentParser()

					parser.add_argument(
					    "--checkpoint_url",
					    default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt",
					    type=str,
					    help="URL to the original PyTorch checkpoint (.pth file).",
					)
					parser.add_argument(
					    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
					)
					__lowerCAmelCase	:       Optional[int]						       =	parser.parse_args()
					convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
