

import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('3.8'):
  import importlib_metadata
else:
  import importlib.metadata as importlib_metadata
def   a   (    A__			:     int   ,     A__			:     Any=False  )					->   int:





      """simple docstring"""



      try:
            _lowercase			 =os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            _lowercase			 =default
      else:
            # KEY is set, convert it to True or False.
            try:
                  _lowercase			 =strtobool(A__  )
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(F'''If set, {key} must be yes or no.'''  )
      return _value


lowercase_             =     parse_flag_from_env('RUN_SLOW', default=False)
lowercase_             =     parse_flag_from_env('RUN_REMOTE', default=False)
lowercase_             =     parse_flag_from_env('RUN_LOCAL', default=True)
lowercase_             =     parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
lowercase_             =     pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
lowercase_             =     pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
lowercase_             =     pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
lowercase_             =     pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
    reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)

# Beam
lowercase_             =     pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
    reason='test requires apache-beam and a compatible dill version',
)

# Dill-cloudpickle compatibility
lowercase_             =     pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
lowercase_             =     pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)
def   a   (    A__			:     str  )					->   Union[str, Any]:





      """simple docstring"""



      try:
            import faiss  # noqa
      except ImportError:
            _lowercase			 =unittest.skip('test requires faiss'  )(A__  )
      return test_case
def   a   (    A__			:     List[Any]  )					->   Union[str, Any]:





      """simple docstring"""



      try:
            import regex  # noqa
      except ImportError:
            _lowercase			 =unittest.skip('test requires regex'  )(A__  )
      return test_case
def   a   (    A__			:     str  )					->   List[str]:





      """simple docstring"""



      try:
            import elasticsearch  # noqa
      except ImportError:
            _lowercase			 =unittest.skip('test requires elasticsearch'  )(A__  )
      return test_case
def   a   (    A__			:     Union[str, Any]  )					->   Optional[Any]:





      """simple docstring"""



      try:
            import sqlalchemy  # noqa
      except ImportError:
            _lowercase			 =unittest.skip('test requires sqlalchemy'  )(A__  )
      return test_case
def   a   (    A__			:     Optional[Any]  )					->   List[Any]:





      """simple docstring"""



      if not config.TORCH_AVAILABLE:
            _lowercase			 =unittest.skip('test requires PyTorch'  )(A__  )
      return test_case
def   a   (    A__			:     List[str]  )					->   List[str]:





      """simple docstring"""



      if not config.TF_AVAILABLE:
            _lowercase			 =unittest.skip('test requires TensorFlow'  )(A__  )
      return test_case
def   a   (    A__			:     Optional[Any]  )					->   List[Any]:





      """simple docstring"""



      if not config.JAX_AVAILABLE:
            _lowercase			 =unittest.skip('test requires JAX'  )(A__  )
      return test_case
def   a   (    A__			:     Dict  )					->   Dict:





      """simple docstring"""



      if not config.PIL_AVAILABLE:
            _lowercase			 =unittest.skip('test requires Pillow'  )(A__  )
      return test_case
def   a   (    A__			:     Any  )					->   Tuple:





      """simple docstring"""



      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip('test requires transformers'  )(A__  )
      else:
            return test_case
def   a   (    A__			:     str  )					->   Any:





      """simple docstring"""



      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip('test requires tiktoken'  )(A__  )
      else:
            return test_case
def   a   (    A__			:     Union[str, Any]  )					->   Dict:





      """simple docstring"""



      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip('test requires spacy'  )(A__  )
      else:
            return test_case
def   a   (    A__			:     Optional[int]  )					->   Optional[Any]:





      """simple docstring"""



      def _require_spacy_model(A__			:     List[Any]  ):
            try:
                  import spacy  # noqa F401

                  spacy.load(A__  )
            except ImportError:
                  return unittest.skip('test requires spacy'  )(A__  )
            except OSError:
                  return unittest.skip('test requires spacy model \'{}\''.format(A__  )  )(A__  )
            else:
                  return test_case

      return _require_spacy_model
def   a   (    A__			:     Union[str, Any]  )					->   int:





      """simple docstring"""



      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip('test requires pyspark'  )(A__  )
      else:
            return test_case
def   a   (    A__			:     Tuple  )					->   List[Any]:





      """simple docstring"""



      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip('test requires joblibspark'  )(A__  )
      else:
            return test_case
def   a   (    A__			:     Union[str, Any]  )					->   str:





      """simple docstring"""



      if not _run_slow_tests or _run_slow_tests == 0:
            _lowercase			 =unittest.skip('test is slow'  )(A__  )
      return test_case
def   a   (    A__			:     List[str]  )					->   Optional[Any]:





      """simple docstring"""



      if not _run_local_tests or _run_local_tests == 0:
            _lowercase			 =unittest.skip('test is local'  )(A__  )
      return test_case
def   a   (    A__			:     List[str]  )					->   Optional[int]:





      """simple docstring"""



      if not _run_packaged_tests or _run_packaged_tests == 0:
            _lowercase			 =unittest.skip('test is packaged'  )(A__  )
      return test_case
def   a   (    A__			:     str  )					->   Optional[Any]:





      """simple docstring"""



      if not _run_remote_tests or _run_remote_tests == 0:
            _lowercase			 =unittest.skip('test requires remote'  )(A__  )
      return test_case
def   a   (    *A__			:     Any  )					->   List[Any]:





      """simple docstring"""



      def decorate(cls			:     str  ):
            for name, fn in cls.__dict__.items():
                  if callable(A__  ) and name.startswith('test'  ):
                        for decorator in decorators:
                              _lowercase			 =decorator(A__  )
                        setattr(cls   ,     A__   ,     A__  )
            return cls

      return decorate





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  pass





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						0
  _a		    =						1
  _a		    =						2
@contextmanager
def   a   (    A__			:     List[Any]=OfflineSimulationMode.CONNECTION_FAILS   ,     A__			:     Union[str, Any]=1e-16  )					->   int:





      """simple docstring"""



      _lowercase			 =requests.Session().request

      def timeout_request(A__			:     str   ,     A__			:     Dict   ,     A__			:     List[str]   ,     **A__			:     Optional[int]  ):
            # Change the url to an invalid url so that the connection hangs
            _lowercase			 ='https://10.255.255.1'
            if kwargs.get('timeout'  ) is None:
                  raise RequestWouldHangIndefinitelyError(
                      F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''  )
            _lowercase			 =timeout
            try:
                  return online_request(A__   ,     A__   ,     **A__  )
            except Exception as e:
                  # The following changes in the error are just here to make the offline timeout error prettier
                  _lowercase			 =url
                  _lowercase			 =e.args[0]
                  _lowercase			 =(max_retry_error.args[0].replace('10.255.255.1'   ,     F'''OfflineMock[{url}]'''  ),)
                  _lowercase			 =(max_retry_error,)
                  raise

      def raise_connection_error(A__			:     Dict   ,     A__			:     Tuple   ,     **A__			:     str  ):
            raise requests.ConnectionError('Offline mode is enabled.'   ,     request=A__  )

      if mode is OfflineSimulationMode.CONNECTION_FAILS:
            with patch('requests.Session.send'   ,     A__  ):
                  yield
      elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
            # inspired from https://stackoverflow.com/a/904609
            with patch('requests.Session.request'   ,     A__  ):
                  yield
      elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
            with patch('datasets.config.HF_DATASETS_OFFLINE'   ,     A__  ):
                  yield
      else:
            raise ValueError('Please use a value from the OfflineSimulationMode enum.'  )
@contextmanager
def   a   (    *A__			:     Dict   ,     **A__			:     Optional[int]  )					->   Optional[Any]:





      """simple docstring"""



      _lowercase			 =str(Path().resolve()  )
      with tempfile.TemporaryDirectory(*A__   ,     **A__  ) as tmp_dir:
            try:
                  os.chdir(A__  )
                  yield
            finally:
                  os.chdir(A__  )
@contextmanager
def   a   (    )					->   Optional[int]:





      """simple docstring"""



      import gc

      gc.collect()
      _lowercase			 =pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def   a   (    )					->   Tuple:





      """simple docstring"""



      import gc

      gc.collect()
      _lowercase			 =pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def   a   (    A__			:     Optional[Any]   ,     A__			:     Any  )					->   Optional[int]:





      """simple docstring"""



      return deepcopy(A__  ).integers(0   ,     100   ,     10  ).tolist() == deepcopy(A__  ).integers(0   ,     100   ,     10  ).tolist()
def   a   (    A__			:     Optional[int]  )					->   Any:





      """simple docstring"""



      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(A__			:     List[str]   ,     *A__			:     Optional[Any]   ,     **A__			:     Optional[Any]  ):
            try:
                  return func(*A__   ,     **A__  )
            except HTTPError as err:
                  if str(A__  ).startswith('500'  ) or str(A__  ).startswith('502'  ):
                        pytest.xfail(str(A__  )  )
                  raise err

      return decorator.decorator(_wrapper   ,     A__  )





class 				__lowerCAmelCase  :




  def __init__(       self							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )						->				List[str]:
        '''simple docstring'''






        _lowercase			 =returncode
        _lowercase			 =stdout
        _lowercase			 =stderr
async def   a   (    A__			:     List[Any]   ,     A__			:     Any  )					->   Tuple:





      """simple docstring"""



      while True:
            _lowercase			 =await stream.readline()
            if line:
                  callback(A__  )
            else:
                  break
async def   a   (    A__			:     Dict   ,     A__			:     List[Any]=None   ,     A__			:     List[Any]=None   ,     A__			:     Any=None   ,     A__			:     int=False   ,     A__			:     Any=False  )					->   _RunOutput:





      """simple docstring"""



      if echo:
            print('\nRunning: '   ,     ' '.join(A__  )  )

      _lowercase			 =await asyncio.create_subprocess_exec(
          cmd[0]   ,     *cmd[1:]   ,     stdin=A__   ,     stdout=asyncio.subprocess.PIPE   ,     stderr=asyncio.subprocess.PIPE   ,     env=A__   ,     )

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      _lowercase			 =[]
      _lowercase			 =[]

      def tee(A__			:     Dict   ,     A__			:     Optional[int]   ,     A__			:     str   ,     A__			:     Optional[Any]=""  ):
            _lowercase			 =line.decode('utf-8'  ).rstrip()
            sink.append(A__  )
            if not quiet:
                  print(A__   ,     A__   ,     file=A__  )

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              _read_stream(p.stdout   ,     lambda A__  : tee(A__   ,     A__   ,     sys.stdout   ,     label='stdout:'  )  ),
              _read_stream(p.stderr   ,     lambda A__  : tee(A__   ,     A__   ,     sys.stderr   ,     label='stderr:'  )  ),
          ]   ,     timeout=A__   ,     )
      return _RunOutput(await p.wait()   ,     A__   ,     A__  )
def   a   (    A__			:     Optional[Any]   ,     A__			:     Any=None   ,     A__			:     Union[str, Any]=None   ,     A__			:     List[str]=180   ,     A__			:     List[str]=False   ,     A__			:     Tuple=True  )					->   _RunOutput:





      """simple docstring"""



      _lowercase			 =asyncio.get_event_loop()
      _lowercase			 =loop.run_until_complete(
          _stream_subprocess(A__   ,     env=A__   ,     stdin=A__   ,     timeout=A__   ,     quiet=A__   ,     echo=A__  )  )

      _lowercase			 =' '.join(A__  )
      if result.returncode > 0:
            _lowercase			 ='\n'.join(result.stderr  )
            raise RuntimeError(
                F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
                F'''The combined stderr from workers follows:\n{stderr}'''  )

      # check that the subprocess actually did run and produced some output, should the test rely on
      # the remote side to do the testing
      if not result.stdout and not result.stderr:
            raise RuntimeError(F'''\'{cmd_str}\' produced no output.'''  )

      return result
def   a   (    )					->   Union[str, Any]:





      """simple docstring"""



      _lowercase			 =os.environ.get('PYTEST_XDIST_WORKER'   ,     'gw0'  )
      _lowercase			 =re.sub(r'^gw'   ,     ''   ,     A__   ,     0   ,     re.M  )
      return int(A__  )







def   a   (    )					->   Optional[int]:





      """simple docstring"""



      _lowercase			 =29500
      _lowercase			 =pytest_xdist_worker_id()
      return port + uniq_delta





import argparse

import torch
from datasets import load_dataset
from donut import DonutModel

from transformers import (
    DonutImageProcessor,
    DonutProcessor,
    DonutSwinConfig,
    DonutSwinModel,
    MBartConfig,
    MBartForCausalLM,
    VisionEncoderDecoderModel,
    XLMRobertaTokenizerFast,
)
def   a   (    A__			:     Tuple  )					->   Any:





      """simple docstring"""



      _lowercase			 =model.config

      _lowercase			 =DonutSwinConfig(
          image_size=original_config.input_size   ,     patch_size=4   ,     depths=original_config.encoder_layer   ,     num_heads=[4, 8, 16, 32]   ,     window_size=original_config.window_size   ,     embed_dim=128   ,     )
      _lowercase			 =MBartConfig(
          is_decoder=A__   ,     is_encoder_decoder=A__   ,     add_cross_attention=A__   ,     decoder_layers=original_config.decoder_layer   ,     max_position_embeddings=original_config.max_position_embeddings   ,     vocab_size=len(
              model.decoder.tokenizer  )   ,     scale_embedding=A__   ,     add_final_layer_norm=A__   ,     )

      return encoder_config, decoder_config
def   a   (    A__			:     Union[str, Any]  )					->   str:





      """simple docstring"""



      if "encoder.model" in name:
            _lowercase			 =name.replace('encoder.model'   ,     'encoder'  )
      if "decoder.model" in name:
            _lowercase			 =name.replace('decoder.model'   ,     'decoder'  )
      if "patch_embed.proj" in name:
            _lowercase			 =name.replace('patch_embed.proj'   ,     'embeddings.patch_embeddings.projection'  )
      if "patch_embed.norm" in name:
            _lowercase			 =name.replace('patch_embed.norm'   ,     'embeddings.norm'  )
      if name.startswith('encoder'  ):
            if "layers" in name:
                  _lowercase			 ='encoder.' + name
            if "attn.proj" in name:
                  _lowercase			 =name.replace('attn.proj'   ,     'attention.output.dense'  )
            if "attn" in name and "mask" not in name:
                  _lowercase			 =name.replace('attn'   ,     'attention.self'  )
            if "norm1" in name:
                  _lowercase			 =name.replace('norm1'   ,     'layernorm_before'  )
            if "norm2" in name:
                  _lowercase			 =name.replace('norm2'   ,     'layernorm_after'  )
            if "mlp.fc1" in name:
                  _lowercase			 =name.replace('mlp.fc1'   ,     'intermediate.dense'  )
            if "mlp.fc2" in name:
                  _lowercase			 =name.replace('mlp.fc2'   ,     'output.dense'  )

            if name == "encoder.norm.weight":
                  _lowercase			 ='encoder.layernorm.weight'
            if name == "encoder.norm.bias":
                  _lowercase			 ='encoder.layernorm.bias'

      return name
def   a   (    A__			:     Optional[Any]   ,     A__			:     List[Any]  )					->   List[str]:





      """simple docstring"""



      for key in orig_state_dict.copy().keys():
            _lowercase			 =orig_state_dict.pop(A__  )

            if "qkv" in key:
                  _lowercase			 =key.split('.'  )
                  _lowercase			 =int(key_split[3]  )
                  _lowercase			 =int(key_split[5]  )
                  _lowercase			 =model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size

                  if "weight" in key:
                        _lowercase			 =val[:dim, :]
                        _lowercase			 =val[dim : dim * 2, :]
                        _lowercase			 =val[-dim:, :]
                  else:
                        _lowercase			 =val[:dim]
                        _lowercase			 =val[dim : dim * 2]
                        _lowercase			 =val[-dim:]
            elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
                  # HuggingFace implementation doesn't use attn_mask buffer
                  # and model doesn't use final LayerNorms for the encoder
                  pass
            else:
                  _lowercase			 =val

      return orig_state_dict
def   a   (    A__			:     str   ,     A__			:     List[str]=None   ,     A__			:     List[Any]=False  )					->   List[str]:





      """simple docstring"""



      _lowercase			 =DonutModel.from_pretrained(A__  ).eval()

      # load HuggingFace model
      _lowercase , _lowercase			 =get_configs(A__  )
      _lowercase			 =DonutSwinModel(A__  )
      _lowercase			 =MBartForCausalLM(A__  )
      _lowercase			 =VisionEncoderDecoderModel(encoder=A__   ,     decoder=A__  )
      model.eval()

      _lowercase			 =original_model.state_dict()
      _lowercase			 =convert_state_dict(A__   ,     A__  )
      model.load_state_dict(A__  )

      # verify results on scanned document
      _lowercase			 =load_dataset('hf-internal-testing/example-documents'  )
      _lowercase			 =dataset['test'][0]['image'].convert('RGB'  )

      _lowercase			 =XLMRobertaTokenizerFast.from_pretrained(A__   ,     from_slow=A__  )
      _lowercase			 =DonutImageProcessor(
          do_align_long_axis=original_model.config.align_long_axis   ,     size=original_model.config.input_size[::-1]  )
      _lowercase			 =DonutProcessor(A__   ,     A__  )
      _lowercase			 =processor(A__   ,     return_tensors='pt'  ).pixel_values

      if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
            _lowercase			 ='<s_docvqa><s_question>{user_input}</s_question><s_answer>'
            _lowercase			 ='When is the coffee break?'
            _lowercase			 =task_prompt.replace('{user_input}'   ,     A__  )
      elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
            _lowercase			 ='<s_rvlcdip>'
      elif model_name in [
          "naver-clova-ix/donut-base-finetuned-cord-v1",
          "naver-clova-ix/donut-base-finetuned-cord-v1-2560",
      ]:
            _lowercase			 ='<s_cord>'
      elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
            _lowercase			 ='s_cord-v2>'
      elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
            _lowercase			 ='<s_zhtrainticket>'
      elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
            # use a random prompt
            _lowercase			 ='hello world'
      else:
            raise ValueError('Model name not supported'  )
      _lowercase			 =original_model.decoder.tokenizer(A__   ,     add_special_tokens=A__   ,     return_tensors='pt'  )[
          'input_ids'
      ]

      _lowercase			 =original_model.encoder.model.patch_embed(A__  )
      _lowercase , _lowercase			 =model.encoder.embeddings(A__  )
      assert torch.allclose(A__   ,     A__   ,     atol=1e-3  )

      # verify encoder hidden states
      _lowercase			 =original_model.encoder(A__  )
      _lowercase			 =model.encoder(A__  ).last_hidden_state
      assert torch.allclose(A__   ,     A__   ,     atol=1e-2  )

      # verify decoder hidden states
      _lowercase			 =original_model(A__   ,     A__   ,     A__  ).logits
      _lowercase			 =model(A__   ,     decoder_input_ids=A__  ).logits
      assert torch.allclose(A__   ,     A__   ,     atol=1e-3  )
      print('Looks ok!'  )

      if pytorch_dump_folder_path is not None:
            print(F'''Saving model and processor to {pytorch_dump_folder_path}'''  )
            model.save_pretrained(A__  )
            processor.save_pretrained(A__  )

      if push_to_hub:
            model.push_to_hub('nielsr/' + model_name.split('/'  )[-1]   ,     commit_message='Update model'  )
            processor.push_to_hub('nielsr/' + model_name.split('/'  )[-1]   ,     commit_message='Update model'  )


if __name__ == "__main__":
  lowercase_             =     argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--model_name',
      default='naver-clova-ix/donut-base-finetuned-docvqa',
      required=False,
      type=str,
      help='Name of the original model you\'d like to convert.',
  )
  parser.add_argument(
      '--pytorch_dump_folder_path',
      default=None,
      required=False,
      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 and processor to the 🤗 hub.',
  )

  lowercase_             =     parser.parse_args()
  convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


