



"""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


lowercase__		:    List[Any]				   =     logging.get_logger(__name__)

lowercase__		:    Tuple				   =     {
    """artists_file""": """artists.json""",
    """lyrics_file""": """lyrics.json""",
    """genres_file""": """genres.json""",
}

lowercase__		:    Optional[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""",
    },
}

lowercase__		:    List[Any]				   =     {
    """jukebox""": 5_1_2,
}







class 				UpperCamelCase__       (     SCREAMING_SNAKE_CASE_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					VOCAB_FILES_NAMES
      _SCREAMING_SNAKE_CASE      =					PRETRAINED_VOCAB_FILES_MAP
      _SCREAMING_SNAKE_CASE      =					PRETRAINED_LYRIC_TOKENS_SIZES
      _SCREAMING_SNAKE_CASE      =					["""input_ids""", """attention_mask"""]



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

        with open(snake_case__   ,      encoding='utf-8'	) as vocab_handle:
          lowerCAmelCase_       :    List[str]								=			json.load(snake_case__	)

        with open(snake_case__   ,      encoding='utf-8'	) as vocab_handle:
          lowerCAmelCase_       :    List[Any]								=			json.load(snake_case__	)

        with open(snake_case__   ,      encoding='utf-8'	) as vocab_handle:
          lowerCAmelCase_       :    Optional[Any]								=			json.load(snake_case__	)

        lowerCAmelCase_       :    Any								=			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:
          lowerCAmelCase_       :    Union[str, Any]								=			oov.replace(r'\-\''   ,      r'\-+\''	)

        lowerCAmelCase_       :    Optional[int]								=			regex.compile(snake_case__	)
        lowerCAmelCase_       :    Tuple								=			{v: k for k, v in self.artists_encoder.items()}
        lowerCAmelCase_       :    Union[str, Any]								=			{v: k for k, v in self.genres_encoder.items()}
        lowerCAmelCase_       :    Optional[Any]								=			{v: k for k, v in self.lyrics_encoder.items()}



      @property
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        return len(self.artists_encoder	) + len(self.genres_encoder	) + len(self.lyrics_encoder	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        return dict(self.artists_encoder   ,      self.genres_encoder   ,      self.lyrics_encoder	)



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

        lowerCAmelCase_       :    List[str]								=			[[self.lyrics_encoder.get(snake_case__   ,      0	) for character in list_lyrics[0]], [], []]
        return artists_id, list_genres, lyric_ids



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]	):
        return list(snake_case__	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      **SCREAMING_SNAKE_CASE_    :				Optional[int]	):
        lowerCAmelCase_       :    Optional[int]								=			self.prepare_for_tokenization(snake_case__   ,      snake_case__   ,      snake_case__	)
        lowerCAmelCase_       :    str								=			self._tokenize(snake_case__	)
        return artist, genre, lyrics



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				List[Any] = False	):

        for idx in range(len(self.version	)	):
          if self.version[idx] == "v3":
            lowerCAmelCase_       :    int								=			artists[idx].lower()
            lowerCAmelCase_       :    Tuple								=			[genres[idx].lower()]
          else:
            lowerCAmelCase_       :    Optional[int]								=			self._normalize(artists[idx]	) + '.v2'
            lowerCAmelCase_       :    str								=			[
                self._normalize(snake_case__	) + '.v2' for genre in genres[idx].split('_'	)
            ]  # split is for the full dictionary with combined genres

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

        lowerCAmelCase_       :    List[str]								=			self._run_strip_accents(snake_case__	)
        lowerCAmelCase_       :    Optional[int]								=			lyrics.replace('\\'   ,      '\n'	)
        lowerCAmelCase_       :    Tuple								=			self.out_of_vocab.sub(''   ,      snake_case__	), [], []
        return artists, genres, lyrics



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]	):
        lowerCAmelCase_       :    List[str]								=			unicodedata.normalize('NFD'   ,      snake_case__	)
        lowerCAmelCase_       :    Optional[Any]								=			[]
        for char in text:
          lowerCAmelCase_       :    Dict								=			unicodedata.category(snake_case__	)
          if cat == "Mn":
            continue
          output.append(snake_case__	)
        return "".join(snake_case__	)



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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]	):
        return " ".join(snake_case__	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any] = None   ,      SCREAMING_SNAKE_CASE_    :				Optional[int] = False	):

        if not isinstance(snake_case__   ,      snake_case__	):
          lowerCAmelCase_       :    Dict								=			TensorType(snake_case__	)

        # 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

          lowerCAmelCase_       :    List[str]								=			tf.constant
          lowerCAmelCase_       :    str								=			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

          lowerCAmelCase_       :    Union[str, Any]								=			torch.tensor
          lowerCAmelCase_       :    int								=			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

          lowerCAmelCase_       :    int								=			jnp.array
          lowerCAmelCase_       :    Optional[Any]								=			_is_jax
        else:
          lowerCAmelCase_       :    List[Any]								=			np.asarray
          lowerCAmelCase_       :    List[Any]								=			_is_numpy

        # Do the tensor conversion in batch

        try:
          if prepend_batch_axis:
            lowerCAmelCase_       :    Dict								=			[inputs]

          if not is_tensor(snake_case__	):
            lowerCAmelCase_       :    Tuple								=			as_tensor(snake_case__	)
        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    :				Any   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=""   ,      SCREAMING_SNAKE_CASE_    :				Tuple="pt"	):
        lowerCAmelCase_       :    Dict								=			[0, 0, 0]
        lowerCAmelCase_       :    List[Any]								=			[artist] * len(self.version	)
        lowerCAmelCase_       :    Tuple								=			[genres] * len(self.version	)

        lowerCAmelCase_       :    Optional[Any]								=			self.tokenize(snake_case__   ,      snake_case__   ,      snake_case__	)
        lowerCAmelCase_       :    List[Any]								=			self._convert_token_to_id(snake_case__   ,      snake_case__   ,      snake_case__	)

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				str = None	):

        if not os.path.isdir(snake_case__	):
          logger.error(F"Vocabulary path ({save_directory}) should be a directory"	)
          return

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

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

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

        return (artists_file, genres_file, lyrics_file)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]	):
        lowerCAmelCase_       :    Dict								=			self.artists_decoder.get(snake_case__	)
        lowerCAmelCase_       :    Optional[int]								=			[self.genres_decoder.get(snake_case__	) for genre in genres_index]
        lowerCAmelCase_       :    Any								=			[self.lyrics_decoder.get(snake_case__	) for character in lyric_index]
        return artist, genres, lyrics










"""simple docstring"""







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


lowercase__		:    List[Any]				   =     logging.get_logger(__name__)

lowercase__		:    List[str]				   =     {
    """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""",
}







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					"""open-llama"""



      def __init__(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Tuple=1_0_0_0_0_0   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=4_0_9_6   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=1_1_0_0_8   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=3_2   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=3_2   ,      SCREAMING_SNAKE_CASE_    :				str="silu"   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=2_0_4_8   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=0.02   ,      SCREAMING_SNAKE_CASE_    :				int=1E-6   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				Dict=0   ,      SCREAMING_SNAKE_CASE_    :				Dict=1   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=2   ,      SCREAMING_SNAKE_CASE_    :				str=False   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=True   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				Any=True   ,      SCREAMING_SNAKE_CASE_    :				Tuple=None   ,      **SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      ):
        lowerCAmelCase_       :    Union[str, Any]								=			vocab_size
        lowerCAmelCase_       :    int								=			max_position_embeddings
        lowerCAmelCase_       :    Union[str, Any]								=			hidden_size
        lowerCAmelCase_       :    Optional[Any]								=			intermediate_size
        lowerCAmelCase_       :    List[Any]								=			num_hidden_layers
        lowerCAmelCase_       :    Optional[int]								=			num_attention_heads
        lowerCAmelCase_       :    List[Any]								=			hidden_act
        lowerCAmelCase_       :    List[Any]								=			initializer_range
        lowerCAmelCase_       :    List[str]								=			rms_norm_eps
        lowerCAmelCase_       :    List[Any]								=			use_cache
        lowerCAmelCase_       :    Optional[int]								=			kwargs.pop(
            'use_memorry_efficient_attention'   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    List[Any]								=			hidden_dropout_prob
        lowerCAmelCase_       :    List[str]								=			attention_dropout_prob
        lowerCAmelCase_       :    Tuple								=			use_stable_embedding
        lowerCAmelCase_       :    Optional[Any]								=			shared_input_output_embedding
        lowerCAmelCase_       :    Optional[Any]								=			rope_scaling
        self._rope_scaling_validation()

        super().__init__(
            pad_token_id=SCREAMING_SNAKE_CASE_   ,      bos_token_id=SCREAMING_SNAKE_CASE_   ,      eos_token_id=SCREAMING_SNAKE_CASE_   ,      tie_word_embeddings=SCREAMING_SNAKE_CASE_   ,      **SCREAMING_SNAKE_CASE_   ,      )





      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        if self.rope_scaling is None:
          return

        if not isinstance(self.rope_scaling   ,      SCREAMING_SNAKE_CASE_	) or len(self.rope_scaling	) != 2:
          raise ValueError(
              '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '
              F"got {self.rope_scaling}"	)
        lowerCAmelCase_       :    int								=			self.rope_scaling.get('type'   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Union[str, Any]								=			self.rope_scaling.get('factor'   ,      SCREAMING_SNAKE_CASE_	)
        if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
          raise ValueError(
              F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"	)
        if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or rope_scaling_factor <= 1.0:
          raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"	)





