
import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class 							A__	(			__SCREAMING_SNAKE_CASE						,     unittest.TestCase):
      _UpperCAmelCase       :					List[Any]					 =    PreTrainedTokenizerFast
      _UpperCAmelCase       :					Any					 =    False
      _UpperCAmelCase       :					List[Any]					 =    True
      _UpperCAmelCase       :					Optional[int]					 =    """tokenizer_file"""
      def 		UpperCamelCase__							(   self   ):
       lowerCamelCase	:			List[str]           =   False  # because we don't have pretrained_vocab_files_map
       super().setUp()
       lowerCamelCase	:			List[Any]           =   True

       lowerCamelCase	:			Tuple           =   ["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
       lowerCamelCase	:			Optional[Any]           =   """SaulLu/dummy-tokenizer-bytelevel-bpe"""

       # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
       lowerCamelCase	:			Union[str, Any]           =   [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

       lowerCamelCase	:			Dict           =   PreTrainedTokenizerFast.from_pretrained(model_paths[0]   )
       tokenizer.save_pretrained(self.tmpdirname   )
      def 		UpperCamelCase__							(   self   ):
       # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
       # model
       pass
      def 		UpperCamelCase__							(   self   ):
       # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
       # model
       pass
      def 		UpperCamelCase__							(   self   ):
       # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
       # model
       pass
      def 		UpperCamelCase__							(   self   ):
       # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
       pass
      def 		UpperCamelCase__							(   self   ):
       lowerCamelCase	:			Dict           =   self.tmpdirname
       # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
        with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''   ):
         try:
          lowerCamelCase	:			Union[str, Any]           =   tempfile.mkdtemp()
          lowerCamelCase	:			Union[str, Any]           =   self.rust_tokenizer_class.from_pretrained(__magic_name__					,						**__magic_name__   )

          tokenizer.save_pretrained(self.tmpdirname   )
          super().test_training_new_tokenizer()
         finally:
          # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
          # is restored
          shutil.rmtree(self.tmpdirname   )
          lowerCamelCase	:			Any           =   tmpdirname_orig
      def 		UpperCamelCase__							(   self   ):
       lowerCamelCase	:			List[str]           =   self.tmpdirname
       # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
        with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''   ):
         try:
          lowerCamelCase	:			Optional[int]           =   tempfile.mkdtemp()
          lowerCamelCase	:			List[str]           =   self.rust_tokenizer_class.from_pretrained(__magic_name__					,						**__magic_name__   )

          tokenizer.save_pretrained(self.tmpdirname   )
          super().test_training_new_tokenizer_with_special_tokens_change()
         finally:
          # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
          # is restored
          shutil.rmtree(self.tmpdirname   )
          lowerCamelCase	:			Optional[int]           =   tmpdirname_orig






      def 		UpperCamelCase__							(   self   ):
       lowerCamelCase	:			Any           =   self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name   )

       lowerCamelCase	:			str           =   ("""a""" for _ in range(1_0_0_0   ))
       lowerCamelCase	:			str           =   tokenizer.train_new_from_iterator(text_iterator=__magic_name__					,						length=1_0_0_0					,						vocab_size=5_0   )

       lowerCamelCase	:			Tuple           =   new_tokenizer.encode("""a🤗"""   )
       self.assertEqual(__magic_name__					,						[6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]   )





@require_tokenizers
class 							A__	(			unittest.TestCase):
      def 		UpperCamelCase__							(   self   ):
       lowerCamelCase	:			Dict           =   AutoTokenizer.from_pretrained("""bert-base-cased"""   )
       lowerCamelCase	:			Optional[Any]           =   json.loads(tokenizer._tokenizer.to_str()   )
       lowerCamelCase	:			str           =   len(__magic_name__   )

       with tempfile.TemporaryDirectory() as tmp_dir:
        # Hack to save this in the tokenizer_config.json
        lowerCamelCase	:			int           =   ["""tokenizer.4.0.0.json"""]
        tokenizer.save_pretrained(__magic_name__   )
        json.dump(__magic_name__					,						open(os.path.join(__magic_name__					,						"""tokenizer.4.0.0.json"""   )					,						"""w"""   )   )

        # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
        lowerCamelCase	:			Optional[Any]           =   AutoTokenizer.from_pretrained(__magic_name__   )
        self.assertEqual(len(__magic_name__   )					,						len(__magic_name__   ) + 1   )
        lowerCamelCase	:			int           =   json.loads(new_tokenizer._tokenizer.to_str()   )
        self.assertIn("""huggingface"""					,						json_tokenizer["""model"""]["""vocab"""]   )

        # Will need to be adjusted if we reach v42 and this test is still here.
        # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
        shutil.move(os.path.join(__magic_name__					,						"""tokenizer.4.0.0.json"""   )					,						os.path.join(__magic_name__					,						"""tokenizer.42.0.0.json"""   )   )
        lowerCamelCase	:			Any           =   ["""tokenizer.42.0.0.json"""]
        tokenizer.save_pretrained(__magic_name__   )
        lowerCamelCase	:			Tuple           =   AutoTokenizer.from_pretrained(__magic_name__   )
        self.assertEqual(len(__magic_name__   )					,						len(__magic_name__   )   )
        lowerCamelCase	:			str           =   json.loads(new_tokenizer._tokenizer.to_str()   )
        self.assertNotIn("""huggingface"""					,						json_tokenizer["""model"""]["""vocab"""]   )






      def 		UpperCamelCase__							(   self   ):
       # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
       lowerCamelCase	:			int           =   """hf-internal-testing/test-two-tokenizers"""

       # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
       lowerCamelCase	:			Any           =   AutoTokenizer.from_pretrained(__magic_name__   )
       self.assertEqual(len(__magic_name__   )					,						2_8_9_9_7   )
       lowerCamelCase	:			Dict           =   json.loads(tokenizer._tokenizer.to_str()   )
       self.assertIn("""huggingface"""					,						json_tokenizer["""model"""]["""vocab"""]   )

       # Testing an older version by monkey-patching the version in the module it's used.
       import transformers as old_transformers

       lowerCamelCase	:			Any           =   """3.0.0"""
       lowerCamelCase	:			Optional[Any]           =   old_transformers.models.auto.AutoTokenizer.from_pretrained(__magic_name__   )
       self.assertEqual(len(__magic_name__   )					,						2_8_9_9_6   )
       lowerCamelCase	:			Any           =   json.loads(old_tokenizer._tokenizer.to_str()   )
       self.assertNotIn("""huggingface"""					,						json_tokenizer["""model"""]["""vocab"""]   )





@require_tokenizers
class 							A__	(			unittest.TestCase):
      def 		UpperCamelCase__							(   self   ):
       # See https://github.com/huggingface/transformers/pull/12550
       # and https://github.com/huggingface/tokenizers/issues/537
       lowerCamelCase	:			Optional[Any]           =   PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""   )
       lowerCamelCase	:			List[str]           =   """The Matrix is a 1999 science fiction action film."""

       with concurrent.futures.ThreadPoolExecutor() as executor:
        lowerCamelCase	:			Tuple           =   [executor.submit(self.fetch					,						__magic_name__					,						__magic_name__   ) for i in range(1_0   )]
        lowerCamelCase	:			Optional[int]           =   [future.result() for future in futures]
        self.assertEqual(__magic_name__					,						[[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0   )]   )






      def 		UpperCamelCase__							(   self					,						__magic_name__					,						__magic_name__   ):
       return tokenizer.encode(__magic_name__					,						truncation="""longest_first"""					,						padding="""longest"""   )






import json
import os
import subprocess
import sys
import warnings
from argparse import ArgumentParser
from contextlib import AbstractContextManager
from typing import Dict, List, Optional

import requests

from ..utils import logging
from . import BaseTransformersCLICommand


_lowerCamelCase           =logging.get_logger(__name__)  # pylint: disable=invalid-name


_lowerCamelCase           ="""lfs-multipart-upload"""





class 							A__	(			__SCREAMING_SNAKE_CASE):
      @staticmethod
      def 		UpperCamelCase__							(   __magic_name__   ):
       lowerCamelCase	:			List[Any]           =   parser.add_parser(
           """lfs-enable-largefiles"""					,						help=(
               """Deprecated: use `huggingface-cli` instead. Configure your repository to enable upload of files > 5GB."""
           )					,						)
       enable_parser.add_argument("""path"""					,						type=__magic_name__					,						help="""Local path to repository you want to configure."""   )
       enable_parser.set_defaults(func=lambda __magic_name__   : LfsEnableCommand(__magic_name__   )   )

       lowerCamelCase	:			Union[str, Any]           =   parser.add_parser(
           __magic_name__					,						help=(
               """Deprecated: use `huggingface-cli` instead. """
               """Command will get called by git-lfs, do not call it directly."""
           )					,						)
       upload_parser.set_defaults(func=lambda __magic_name__   : LfsUploadCommand(__magic_name__   )   )





class 							A__	:
      def __init__(   self					,						__magic_name__   ):
       lowerCamelCase	:			int           =   args






      def 		UpperCamelCase__							(   self   ):
       warnings.warn(
           """Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead."""   )
       lowerCamelCase	:			Dict           =   os.path.abspath(self.args.path   )
       if not os.path.isdir(__magic_name__   ):
        print("""This does not look like a valid git repo."""   )
        exit(1   )
       subprocess.run(
           """git config lfs.customtransfer.multipart.path transformers-cli""".split()					,						check=__magic_name__					,						cwd=__magic_name__   )
       subprocess.run(
           F'''git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}'''.split()					,						check=__magic_name__					,						cwd=__magic_name__					,						)
       print("""Local repo set up for largefiles"""   )





def 					_a      (		lowerCamelCase							):
 lowerCamelCase	:			Dict           =   json.dumps(lowerCamelCase							) + """\n"""
 sys.stdout.write(lowerCamelCase							)
 sys.stdout.flush()





def 					_a      (		):
 lowerCamelCase	:			Tuple           =   json.loads(sys.stdin.readline().strip()							)

 if "terminate" in (msg.get("""type"""							), msg.get("""event"""							)):
  # terminate message received
  return None

 if msg.get("""event"""							) not in ("download", "upload"):
  logger.critical("""Received unexpected message"""							)
  sys.exit(1							)

 return msg





class 							A__	(			__SCREAMING_SNAKE_CASE):
      def __init__(   self					,						__magic_name__					,						__magic_name__					,						__magic_name__   ):
       lowerCamelCase	:			List[str]           =   filepath
       lowerCamelCase	:			Dict           =   seek_from
       lowerCamelCase	:			str           =   read_limit
       lowerCamelCase	:			Tuple           =   0
      def __enter__(   self   ):
       lowerCamelCase	:			str           =   open(self.filepath					,						"""rb"""   )
       self.f.seek(self.seek_from   )
       return self
      def __len__(   self   ):
       lowerCamelCase	:			Any           =   os.fstat(self.f.fileno()   ).st_size
       return min(self.read_limit					,						total_length - self.seek_from   )
      def 		UpperCamelCase__							(   self					,						__magic_name__=-1   ):
       if self.n_seen >= self.read_limit:
        return b""
       lowerCamelCase	:			Tuple           =   self.read_limit - self.n_seen
       lowerCamelCase	:			Dict           =   self.f.read(remaining_amount if n < 0 else min(__magic_name__					,						__magic_name__   )   )
       self.n_seen += len(__magic_name__   )
       return data
      def __iter__(   self   ):
       yield self.read(n=4 * 1_0_2_4 * 1_0_2_4   )






      def __exit__(   self					,						*__magic_name__   ):
       self.f.close()





class 							A__	:
      def __init__(   self					,						__magic_name__   ):
       lowerCamelCase	:			Dict           =   args






      def 		UpperCamelCase__							(   self   ):
       # Immediately after invoking a custom transfer process, git-lfs
       # sends initiation data to the process over stdin.
       # This tells the process useful information about the configuration.
       lowerCamelCase	:			Dict           =   json.loads(sys.stdin.readline().strip()   )
       if not (init_msg.get("""event"""   ) == "init" and init_msg.get("""operation"""   ) == "upload"):
        write_msg({"""error""": {"""code""": 3_2, """message""": """Wrong lfs init operation"""}}   )
        sys.exit(1   )

       # The transfer process should use the information it needs from the
       # initiation structure, and also perform any one-off setup tasks it
       # needs to do. It should then respond on stdout with a simple empty
       # confirmation structure, as follows:
       write_msg({}   )

       # After the initiation exchange, git-lfs will send any number of
       # transfer requests to the stdin of the transfer process, in a serial sequence.
       while True:
        lowerCamelCase	:			Dict           =   read_msg()
        if msg is None:
         # When all transfers have been processed, git-lfs will send
         # a terminate event to the stdin of the transfer process.
         # On receiving this message the transfer process should
         # clean up and terminate. No response is expected.
         sys.exit(0   )

        lowerCamelCase	:			Optional[int]           =   msg["""oid"""]
        lowerCamelCase	:			Union[str, Any]           =   msg["""path"""]
        lowerCamelCase	:			Any           =   msg["""action"""]["""href"""]
        lowerCamelCase	:			Optional[int]           =   msg["""action"""]["""header"""]
        lowerCamelCase	:			Dict           =   int(header.pop("""chunk_size"""   )   )
        lowerCamelCase	:			List[str]           =   list(header.values()   )

        lowerCamelCase	:			str           =   []
        for i, presigned_url in enumerate(__magic_name__   ):
         with FileSlice(__magic_name__					,						seek_from=i * chunk_size					,						read_limit=__magic_name__   ) as data:
          lowerCamelCase	:			Dict           =   requests.put(__magic_name__					,						data=__magic_name__   )
          r.raise_for_status()
          parts.append(
              {
                  """etag""": r.headers.get("""etag"""   ),
                  """partNumber""": i + 1,
              }   )
          # In order to support progress reporting while data is uploading / downloading,
          # the transfer process should post messages to stdout
          write_msg(
              {
                  """event""": """progress""",
                  """oid""": oid,
                  """bytesSoFar""": (i + 1) * chunk_size,
                  """bytesSinceLast""": chunk_size,
              }   )
          # Not precise but that's ok.

        lowerCamelCase	:			Optional[Any]           =   requests.post(
            __magic_name__					,						json={
                """oid""": oid,
                """parts""": parts,
            }					,						)
        r.raise_for_status()

        write_msg({"""event""": """complete""", """oid""": oid}   )




