

import importlib
import shutil
import threading
import warnings
from typing import List

import fsspec
import fsspec.asyn

from . import compression
from .hffilesystem import HfFileSystem


__lowercase				      =						importlib.util.find_spec("""s3fs""") is not None

if _has_safs:
      from .safilesystem import SaFileSystem  # noqa: F401

__lowercase				      =						[
    compression.BzaFileSystem,
    compression.GzipFileSystem,
    compression.LzaFileSystem,
    compression.XzFileSystem,
    compression.ZstdFileSystem,
]

# Register custom filesystems
for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]:
      if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class:
            warnings.warn(f'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.')
      fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True)







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      if "://" in dataset_path:
            A_							       =		dataset_path.split('''://'''   )[1]
      return dataset_path







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      if fs is not None and fs.protocol != "file":
            return True
      else:
            return False







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      A_							       =		not is_remote_filesystem(SCREAMING_SNAKE_CASE   )
      if is_local:
            # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory
            shutil.move(fs._strip_protocol(SCREAMING_SNAKE_CASE   )		,				fs._strip_protocol(SCREAMING_SNAKE_CASE   )   )
      else:
            fs.mv(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				recursive=SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      if hasattr(fsspec.asyn		,				'''reset_lock'''   ):
            # for future fsspec>2022.05.0
            fsspec.asyn.reset_lock()
      else:
            A_							       =		None
            A_							       =		None
            A_							       =		threading.Lock()








import unittest

from transformers import LiltConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          LiltForQuestionAnswering,
          LiltForSequenceClassification,
          LiltForTokenClassification,
          LiltModel,
      )
      from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST

class    _lowercase				:

   def __init__(				self	:    Tuple			,						lowerCamelCase__	:    Optional[int]			,						lowerCamelCase__	:    Dict=1_3			,						lowerCamelCase__	:    Any=7			,						lowerCamelCase__	:    Optional[Any]=True			,						lowerCamelCase__	:    Optional[Any]=True			,						lowerCamelCase__	:    List[Any]=True			,						lowerCamelCase__	:    Union[str, Any]=True			,						lowerCamelCase__	:    Optional[int]=9_9			,						lowerCamelCase__	:    Optional[int]=2_4			,						lowerCamelCase__	:    Optional[int]=2			,						lowerCamelCase__	:    Dict=6			,						lowerCamelCase__	:    List[str]=3_7			,						lowerCamelCase__	:    Optional[Any]="gelu"			,						lowerCamelCase__	:    Dict=0.1			,						lowerCamelCase__	:    Optional[int]=0.1			,						lowerCamelCase__	:    Any=5_1_2			,						lowerCamelCase__	:    int=1_6			,						lowerCamelCase__	:    Union[str, Any]=2			,						lowerCamelCase__	:    Optional[int]=0.02			,						lowerCamelCase__	:    Optional[Any]=3			,						lowerCamelCase__	:    Optional[int]=None			,						lowerCamelCase__	:    Any=1_0_0_0			,						) ->			Any:
         """simple docstring"""





         A_							       =		parent
         A_							       =		batch_size
         A_							       =		seq_length
         A_							       =		is_training
         A_							       =		use_input_mask
         A_							       =		use_token_type_ids
         A_							       =		use_labels
         A_							       =		vocab_size
         A_							       =		hidden_size
         A_							       =		num_hidden_layers
         A_							       =		num_attention_heads
         A_							       =		intermediate_size
         A_							       =		hidden_act
         A_							       =		hidden_dropout_prob
         A_							       =		attention_probs_dropout_prob
         A_							       =		max_position_embeddings
         A_							       =		type_vocab_size
         A_							       =		type_sequence_label_size
         A_							       =		initializer_range
         A_							       =		num_labels
         A_							       =		scope
         A_							       =		range_bbox

   def     UpperCamelCase					(				self	:    int       ) ->			int:
         """simple docstring"""





         A_							       =		ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size       )

         A_							       =		ids_tensor([self.batch_size, self.seq_length, 4]			,						self.range_bbox       )
         # Ensure that bbox is legal
         for i in range(bbox.shape[0]       ):
               for j in range(bbox.shape[1]       ):
                     if bbox[i, j, 3] < bbox[i, j, 1]:
                           A_							       =		bbox[i, j, 3]
                           A_							       =		bbox[i, j, 1]
                           A_							       =		t
                     if bbox[i, j, 2] < bbox[i, j, 0]:
                           A_							       =		bbox[i, j, 2]
                           A_							       =		bbox[i, j, 0]
                           A_							       =		t

         A_							       =		None
         if self.use_input_mask:
               A_							       =		ids_tensor([self.batch_size, self.seq_length]			,						vocab_size=2       )

         A_							       =		None
         if self.use_token_type_ids:
               A_							       =		ids_tensor([self.batch_size, self.seq_length]			,						self.type_vocab_size       )

         A_							       =		None
         A_							       =		None
         if self.use_labels:
               A_							       =		ids_tensor([self.batch_size]			,						self.type_sequence_label_size       )
               A_							       =		ids_tensor([self.batch_size, self.seq_length]			,						self.num_labels       )

         A_							       =		self.get_config()

         return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[str]:
         """simple docstring"""





         return LiltConfig(
             vocab_size=self.vocab_size			,						hidden_size=self.hidden_size			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						hidden_act=self.hidden_act			,						hidden_dropout_prob=self.hidden_dropout_prob			,						attention_probs_dropout_prob=self.attention_probs_dropout_prob			,						max_position_embeddings=self.max_position_embeddings			,						type_vocab_size=self.type_vocab_size			,						initializer_range=self.initializer_range			,						)

   def     UpperCamelCase					(				self	:    Dict			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    Any			,						) ->			List[Any]:
         """simple docstring"""





         A_							       =		LiltModel(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__       )
         A_							       =		model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						token_type_ids=lowerCamelCase__       )
         A_							       =		model(lowerCamelCase__			,						bbox=lowerCamelCase__       )

         self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)       )
         self.parent.assertEqual(result.pooler_output.shape			,						(self.batch_size, self.hidden_size)       )

   def     UpperCamelCase					(				self	:    Optional[int]			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    Optional[Any]			,						) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		self.num_labels
         A_							       =		LiltForTokenClassification(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(
             lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						labels=lowerCamelCase__       )
         self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.num_labels)       )

   def     UpperCamelCase					(				self	:    Dict			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    List[str]			,						) ->			Any:
         """simple docstring"""





         A_							       =		LiltForQuestionAnswering(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(
             lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						start_positions=lowerCamelCase__			,						end_positions=lowerCamelCase__			,						)
         self.parent.assertEqual(result.start_logits.shape			,						(self.batch_size, self.seq_length)       )
         self.parent.assertEqual(result.end_logits.shape			,						(self.batch_size, self.seq_length)       )





   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[Any]:
         """simple docstring"""





         A_							       =		self.prepare_config_and_inputs()
         (
             (
             A_
         )       ,(
             A_
         )       ,(
             A_
         )       ,(
             A_
         )       ,(
             A_
         )       ,(
             A_
         )       ,(
             A_
         )       ,
         )							       =		config_and_inputs
         A_							       =		{
             '''input_ids''': input_ids,
             '''bbox''': bbox,
             '''token_type_ids''': token_type_ids,
             '''attention_mask''': input_mask,
         }
         return config, inputs_dict



@require_torch
class    _lowercase				(					__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       Dict  					=    (
       (
           LiltModel,
           LiltForSequenceClassification,
           LiltForTokenClassification,
           LiltForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   _lowercase     :       List[Any]  					=    (
       {
           'feature-extraction': LiltModel,
           'question-answering': LiltForQuestionAnswering,
           'text-classification': LiltForSequenceClassification,
           'token-classification': LiltForTokenClassification,
           'zero-shot': LiltForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _lowercase     :       Dict  					=    False
   _lowercase     :       Optional[int]  					=    False

   def     UpperCamelCase					(				self	:    Optional[Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    int			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    List[str]       ) ->			Any:
         """simple docstring"""





         return True

   def     UpperCamelCase					(				self	:    int       ) ->			Any:
         """simple docstring"""





         A_							       =		LiltModelTester(self       )
         A_							       =		ConfigTester(self			,						config_class=lowerCamelCase__			,						hidden_size=3_7       )

   def     UpperCamelCase					(				self	:    int       ) ->			Optional[Any]:
         """simple docstring"""





         self.config_tester.run_common_tests()

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Dict:
         """simple docstring"""





         A_							       =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			int:
         """simple docstring"""





         A_							       =		self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
               A_							       =		type
               self.model_tester.create_and_check_model(*lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[Any]       ) ->			int:
         """simple docstring"""





         A_							       =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[str]       ) ->			Any:
         """simple docstring"""





         A_							       =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__       )





   @slow
   def     UpperCamelCase					(				self	:    Any       ) ->			Dict:
         """simple docstring"""





         for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A_							       =		LiltModel.from_pretrained(lowerCamelCase__       )
               self.assertIsNotNone(lowerCamelCase__       )



@require_torch
@slow
class    _lowercase				(					unittest.TestCase			):

   def     UpperCamelCase					(				self	:    List[str]       ) ->			Optional[Any]:
         """simple docstring"""





         A_							       =		LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base'''       ).to(lowerCamelCase__       )

         A_							       =		torch.tensor([[1, 2]]			,						device=lowerCamelCase__       )
         A_							       =		torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]			,						device=lowerCamelCase__       )

         # forward pass
         with torch.no_grad():
               A_							       =		model(input_ids=lowerCamelCase__			,						bbox=lowerCamelCase__       )

         A_							       =		torch.Size([1, 2, 7_6_8]       )
         A_							       =		torch.tensor(
             [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]]			,						device=lowerCamelCase__			,						)

         self.assertTrue(outputs.last_hidden_state.shape			,						lowerCamelCase__       )
         self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3]			,						lowerCamelCase__			,						atol=1e-3       )       )





