



"""simple docstring"""







import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


lowercase__		:    Tuple				   =     logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""")

def     UpperCamelCase_   (   lowerCAmelCase__				:    np.ndarray   ,       lowerCAmelCase__				:    float   ,       lowerCAmelCase__				:    int = 1_6000						)						->       Dict:

  """simple docstring"""




  lowerCAmelCase_       :    str								=			int(round(sample_rate * max_length						)						)
  if len(lowerCAmelCase__						) <= sample_length:
    return wav
  lowerCAmelCase_       :    List[str]								=			randint(0   ,       len(lowerCAmelCase__						) - sample_length - 1						)
  return wav[random_offset : random_offset + sample_length]







@dataclass
class 				UpperCamelCase__       :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					field(default=lowercase_, metadata={"""help""": """Name of a dataset from the datasets package"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """A file containing the training audio paths and labels."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """A file containing the validation audio paths and labels."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""train""", metadata={
              """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""validation""", metadata={
              """help""": (
                  """The name of the training data set split to use (via the datasets library). Defaults to 'validation'"""
              )
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""audio""", metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""}, )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""label""", metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of training examples to this """
                  """value if set."""
              )
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                  """value if set."""
              )
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=20, metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""}, )







@dataclass
class 				UpperCamelCase__       :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					field(
          default="""facebook/wav2vec2-base""", metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""main""", metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Name or path of preprocessor config."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={
              """help""": (
                  """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                  """with private models)."""
              )
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}, )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        if not self.freeze_feature_extractor and self.freeze_feature_encoder:
          warnings.warn(
              'The argument `--freeze_feature_extractor` is deprecated and '
              'will be removed in a future version. Use `--freeze_feature_encoder`'
              'instead. Setting `freeze_feature_encoder==True`.'   ,      SCREAMING_SNAKE_CASE_   ,      )
        if self.freeze_feature_extractor and not self.freeze_feature_encoder:
          raise ValueError(
              'The argument `--freeze_feature_extractor` is deprecated and '
              'should not be used in combination with `--freeze_feature_encoder`.'
              'Only make use of `--freeze_feature_encoder`.'	)




def     UpperCamelCase_   (   )						->       List[Any]:

  """simple docstring"""




  lowerCAmelCase_       :    str								=			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
  if len(sys.argv						) == 2 and sys.argv[1].endswith('.json'						):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Union[str, Any]								=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
  else:
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Tuple								=			parser.parse_args_into_dataclasses()

  # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
  # information sent is the one passed as arguments along with your Python/PyTorch versions.
  send_example_telemetry('run_audio_classification'   ,       lowerCAmelCase__   ,       lowerCAmelCase__						)

  # Setup logging
  logging.basicConfig(
      format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'   ,       datefmt='%m/%d/%Y %H:%M:%S'   ,       handlers=[logging.StreamHandler(sys.stdout						)]   ,       )

  if training_args.should_log:
    # The default of training_args.log_level is passive, so we set log level at info here to have that default.
    transformers.utils.logging.set_verbosity_info()

  lowerCAmelCase_       :    str								=			training_args.get_process_log_level()
  logger.setLevel(lowerCAmelCase__						)
  transformers.utils.logging.set_verbosity(lowerCAmelCase__						)
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()

  # Log on each process the small summary:
  logger.warning(
      f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
      + f"distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}"						)
  logger.info(f"Training/evaluation parameters {training_args}"						)

  # Set seed before initializing model.
  set_seed(training_args.seed						)

  # Detecting last checkpoint.
  lowerCAmelCase_       :    Dict								=			None
  if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
    lowerCAmelCase_       :    int								=			get_last_checkpoint(training_args.output_dir						)
    if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
      raise ValueError(
          f"Output directory ({training_args.output_dir}) already exists and is not empty. "
          'Use --overwrite_output_dir to train from scratch.'						)
    elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
      logger.info(
          f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
          'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'						)

    # Initialize our dataset and prepare it for the audio classification task.
  lowerCAmelCase_       :    int								=			DatasetDict()
  lowerCAmelCase_       :    Union[str, Any]								=			load_dataset(
      data_args.dataset_name   ,       data_args.dataset_config_name   ,       split=data_args.train_split_name   ,       use_auth_token=True if model_args.use_auth_token else None   ,       )
  lowerCAmelCase_       :    Any								=			load_dataset(
      data_args.dataset_name   ,       data_args.dataset_config_name   ,       split=data_args.eval_split_name   ,       use_auth_token=True if model_args.use_auth_token else None   ,       )

  if data_args.audio_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
        'Make sure to set `--audio_column_name` to the correct audio column - one of '
        f"{', '.join(raw_datasets['train'].column_names						)}."						)

  if data_args.label_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
        'Make sure to set `--label_column_name` to the correct text column - one of '
        f"{', '.join(raw_datasets['train'].column_names						)}."						)

  # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
  # transformer outputs in the classifier, but it doesn't always lead to better accuracy
  lowerCAmelCase_       :    int								=			AutoFeatureExtractor.from_pretrained(
      model_args.feature_extractor_name or model_args.model_name_or_path   ,       return_attention_mask=model_args.attention_mask   ,       cache_dir=model_args.cache_dir   ,       revision=model_args.model_revision   ,       use_auth_token=True if model_args.use_auth_token else None   ,       )

  # `datasets` takes care of automatically loading and resampling the audio,
  # so we just need to set the correct target sampling rate.
  lowerCAmelCase_       :    Optional[int]								=			raw_datasets.cast_column(
      data_args.audio_column_name   ,       datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate						)						)

  lowerCAmelCase_       :    Any								=			feature_extractor.model_input_names[0]

  def train_transforms(lowerCAmelCase__				:    Optional[Any]						):
    lowerCAmelCase_       :    Optional[Any]								=			[]
    for audio in batch[data_args.audio_column_name]:
      lowerCAmelCase_       :    Union[str, Any]								=			random_subsample(
          audio['array']   ,       max_length=data_args.max_length_seconds   ,       sample_rate=feature_extractor.sampling_rate						)
      subsampled_wavs.append(lowerCAmelCase__						)
    lowerCAmelCase_       :    Union[str, Any]								=			feature_extractor(lowerCAmelCase__   ,       sampling_rate=feature_extractor.sampling_rate						)
    lowerCAmelCase_       :    int								=			{model_input_name: inputs.get(lowerCAmelCase__						)}
    lowerCAmelCase_       :    Optional[Any]								=			list(batch[data_args.label_column_name]						)

    return output_batch

  def val_transforms(lowerCAmelCase__				:    int						):
    lowerCAmelCase_       :    Optional[int]								=			[audio['array'] for audio in batch[data_args.audio_column_name]]
    lowerCAmelCase_       :    Optional[int]								=			feature_extractor(lowerCAmelCase__   ,       sampling_rate=feature_extractor.sampling_rate						)
    lowerCAmelCase_       :    List[Any]								=			{model_input_name: inputs.get(lowerCAmelCase__						)}
    lowerCAmelCase_       :    Optional[int]								=			list(batch[data_args.label_column_name]						)

    return output_batch

  # Prepare label mappings.
  # We'll include these in the model's config to get human readable labels in the Inference API.
  lowerCAmelCase_       :    Tuple								=			raw_datasets['train'].features[data_args.label_column_name].names
  lowerCAmelCase_						,lowerCAmelCase_       :    Dict								=			{}, {}
  for i, label in enumerate(lowerCAmelCase__						):
    lowerCAmelCase_       :    List[Any]								=			str(lowerCAmelCase__						)
    lowerCAmelCase_       :    List[str]								=			label

  # Load the accuracy metric from the datasets package
  lowerCAmelCase_       :    Any								=			evaluate.load('accuracy'						)

  # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
  # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
  def compute_metrics(lowerCAmelCase__				:    str						):
    lowerCAmelCase_       :    Optional[int]								=			np.argmax(eval_pred.predictions   ,       axis=1						)
    return metric.compute(predictions=lowerCAmelCase__   ,       references=eval_pred.label_ids						)

  lowerCAmelCase_       :    Dict								=			AutoConfig.from_pretrained(
      model_args.config_name or model_args.model_name_or_path   ,       num_labels=len(lowerCAmelCase__						)   ,       labelaid=lowerCAmelCase__   ,       idalabel=lowerCAmelCase__   ,       finetuning_task='audio-classification'   ,       cache_dir=model_args.cache_dir   ,       revision=model_args.model_revision   ,       use_auth_token=True if model_args.use_auth_token else None   ,       )
  lowerCAmelCase_       :    Union[str, Any]								=			AutoModelForAudioClassification.from_pretrained(
      model_args.model_name_or_path   ,       from_tf=bool('.ckpt' in model_args.model_name_or_path						)   ,       config=lowerCAmelCase__   ,       cache_dir=model_args.cache_dir   ,       revision=model_args.model_revision   ,       use_auth_token=True if model_args.use_auth_token else None   ,       ignore_mismatched_sizes=model_args.ignore_mismatched_sizes   ,       )

  # freeze the convolutional waveform encoder
  if model_args.freeze_feature_encoder:
    model.freeze_feature_encoder()

  if training_args.do_train:
    if data_args.max_train_samples is not None:
      lowerCAmelCase_       :    List[Any]								=			(
          raw_datasets['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
      )
    # Set the training transforms
    raw_datasets["train"].set_transform(lowerCAmelCase__   ,       output_all_columns=lowerCAmelCase__						)

  if training_args.do_eval:
    if data_args.max_eval_samples is not None:
      lowerCAmelCase_       :    Dict								=			(
          raw_datasets['eval'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
      )
    # Set the validation transforms
    raw_datasets["eval"].set_transform(lowerCAmelCase__   ,       output_all_columns=lowerCAmelCase__						)

  # Initialize our trainer
  lowerCAmelCase_       :    str								=			Trainer(
      model=lowerCAmelCase__   ,       args=lowerCAmelCase__   ,       train_dataset=raw_datasets['train'] if training_args.do_train else None   ,       eval_dataset=raw_datasets['eval'] if training_args.do_eval else None   ,       compute_metrics=lowerCAmelCase__   ,       tokenizer=lowerCAmelCase__   ,       )

  # Training
  if training_args.do_train:
    lowerCAmelCase_       :    int								=			None
    if training_args.resume_from_checkpoint is not None:
      lowerCAmelCase_       :    Any								=			training_args.resume_from_checkpoint
    elif last_checkpoint is not None:
      lowerCAmelCase_       :    Dict								=			last_checkpoint
    lowerCAmelCase_       :    str								=			trainer.train(resume_from_checkpoint=lowerCAmelCase__						)
    trainer.save_model()
    trainer.log_metrics('train'   ,       train_result.metrics						)
    trainer.save_metrics('train'   ,       train_result.metrics						)
    trainer.save_state()

  # Evaluation
  if training_args.do_eval:
    lowerCAmelCase_       :    Optional[int]								=			trainer.evaluate()
    trainer.log_metrics('eval'   ,       lowerCAmelCase__						)
    trainer.save_metrics('eval'   ,       lowerCAmelCase__						)

  # Write model card and (optionally) push to hub
  lowerCAmelCase_       :    List[str]								=			{
      'finetuned_from': model_args.model_name_or_path,
      'tasks': 'audio-classification',
      'dataset': data_args.dataset_name,
      'tags': ['audio-classification'],
  }
  if training_args.push_to_hub:
    trainer.push_to_hub(**lowerCAmelCase__						)
  else:
    trainer.create_model_card(**lowerCAmelCase__						)


if __name__ == "__main__":
     main()










"""simple docstring"""







from abc import ABC, abstractmethod
from typing import List, Optional







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				int	):
        # test for the above condition
        self.test()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Any								=			0
        lowerCAmelCase_       :    Optional[Any]								=			False
        while not completed:
          if counter == 1:
            self.reset()
          lowerCAmelCase_       :    Any								=			self.advance()
          if not self.does_advance(SCREAMING_SNAKE_CASE_	):
            raise Exception(
                'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'	)

          lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    List[str]								=			self.update(SCREAMING_SNAKE_CASE_	)
          counter += 1

          if counter > 1_0_0_0_0:
            raise Exception('update() does not fulfill the constraint.'	)

        if self.remaining() != 0:
          raise Exception('Custom Constraint is not defined correctly.'	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)





      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=False	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				List[int]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or len(SCREAMING_SNAKE_CASE_	) == 0:
          raise ValueError(F"`token_ids` has to be a non-empty list, but is {token_ids}."	)
        if any((not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or token_id < 0) for token_id in token_ids	):
          raise ValueError(F"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}."	)

        lowerCAmelCase_       :    Union[str, Any]								=			token_ids

        lowerCAmelCase_       :    Union[str, Any]								=			len(self.token_ids	)
        lowerCAmelCase_       :    Union[str, Any]								=			-1  # the index of the currently fulfilled step
        lowerCAmelCase_       :    Dict								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        if self.completed:
          return None
        return self.token_ids[self.fulfilled_idx + 1]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        if self.completed:
          return False

        return token_id == self.token_ids[self.fulfilled_idx + 1]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    List[Any]								=			False
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    Union[str, Any]								=			False

        if self.does_advance(SCREAMING_SNAKE_CASE_	):
          self.fulfilled_idx += 1
          lowerCAmelCase_       :    Optional[int]								=			True
          if self.fulfilled_idx == (self.seqlen - 1):
            lowerCAmelCase_       :    List[str]								=			True
          lowerCAmelCase_       :    List[str]								=			completed
        else:
          # failed to make progress.
          lowerCAmelCase_       :    Optional[Any]								=			True
          self.reset()
        return stepped, completed, reset



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    int								=			0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        return self.seqlen - (self.fulfilled_idx + 1)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple=False	):
        lowerCAmelCase_       :    Any								=			PhrasalConstraint(self.token_ids	)

        if stateful:
          lowerCAmelCase_       :    int								=			self.seqlen
          lowerCAmelCase_       :    Dict								=			self.fulfilled_idx
          lowerCAmelCase_       :    Optional[Any]								=			self.completed

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=True	):
        lowerCAmelCase_       :    Tuple								=			max([len(SCREAMING_SNAKE_CASE_	) for one in nested_token_ids]	)

        lowerCAmelCase_       :    Optional[Any]								=			{}
        for token_ids in nested_token_ids:
          lowerCAmelCase_       :    Union[str, Any]								=			root
          for tidx, token_id in enumerate(SCREAMING_SNAKE_CASE_	):
            if token_id not in level:
              lowerCAmelCase_       :    Dict								=			{}

            lowerCAmelCase_       :    Tuple								=			level[token_id]

        if no_subsets and self.has_subsets(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(
              'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
              F" {nested_token_ids}."	)

        lowerCAmelCase_       :    Union[str, Any]								=			root



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    str								=			self.trie

        for current_token in current_seq:
          lowerCAmelCase_       :    Optional[int]								=			start[current_token]

        lowerCAmelCase_       :    Dict								=			list(start.keys()	)

        return next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    Any								=			self.next_tokens(SCREAMING_SNAKE_CASE_	)

        return len(SCREAMING_SNAKE_CASE_	) == 0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Tuple								=			list(root.values()	)
        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return 1
        else:
          return sum([self.count_leaves(SCREAMING_SNAKE_CASE_	) for nn in next_nodes]	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]	):
        lowerCAmelCase_       :    Any								=			self.count_leaves(SCREAMING_SNAKE_CASE_	)
        return len(SCREAMING_SNAKE_CASE_	) != leaf_count







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or len(SCREAMING_SNAKE_CASE_	) == 0:
          raise ValueError(F"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."	)
        if any(not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) for token_ids in nested_token_ids	):
          raise ValueError(F"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}."	)
        if any(
            any((not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or token_id < 0) for token_id in token_ids	)
            for token_ids in nested_token_ids	):
          raise ValueError(
              F"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."	)

        lowerCAmelCase_       :    Dict								=			DisjunctiveTrie(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[int]								=			nested_token_ids

        lowerCAmelCase_       :    Tuple								=			self.trie.max_height
        lowerCAmelCase_       :    Union[str, Any]								=			[]
        lowerCAmelCase_       :    Optional[Any]								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    int								=			self.trie.next_tokens(self.current_seq	)

        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return None
        else:
          return token_list



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    Optional[int]								=			self.trie.next_tokens(self.current_seq	)

        return token_id in next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    int								=			False
        lowerCAmelCase_       :    Dict								=			False
        lowerCAmelCase_       :    Optional[Any]								=			False

        if self.does_advance(SCREAMING_SNAKE_CASE_	):
          self.current_seq.append(SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    List[Any]								=			True
        else:
          lowerCAmelCase_       :    List[str]								=			True
          self.reset()

        lowerCAmelCase_       :    Dict								=			self.trie.reached_leaf(self.current_seq	)
        lowerCAmelCase_       :    List[str]								=			completed

        return stepped, completed, reset



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    int								=			False
        lowerCAmelCase_       :    Optional[Any]								=			[]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        if self.completed:
          # since this can be completed without reaching max height
          return 0
        else:
          return self.seqlen - len(self.current_seq	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict=False	):
        lowerCAmelCase_       :    Dict								=			DisjunctiveConstraint(self.token_ids	)

        if stateful:
          lowerCAmelCase_       :    Dict								=			self.seqlen
          lowerCAmelCase_       :    Optional[Any]								=			self.current_seq
          lowerCAmelCase_       :    List[Any]								=			self.completed

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[Constraint]	):
        lowerCAmelCase_       :    Optional[int]								=			constraints

        # max # of steps required to fulfill a given constraint
        lowerCAmelCase_       :    Optional[int]								=			max([c.seqlen for c in constraints]	)
        lowerCAmelCase_       :    List[str]								=			len(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    List[str]								=			False

        self.init_state()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Tuple								=			[]
        lowerCAmelCase_       :    int								=			None
        lowerCAmelCase_       :    Optional[int]								=			[constraint.copy(stateful=SCREAMING_SNAKE_CASE_	) for constraint in self.constraints]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        lowerCAmelCase_       :    Optional[Any]								=			0
        if self.inprogress_constraint:
          # extra points for having a constraint mid-fulfilled
          add += self.max_seqlen - self.inprogress_constraint.remaining()

        return (len(self.complete_constraints	) * self.max_seqlen) + add



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    List[str]								=			[]
        if self.inprogress_constraint is None:
          for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
            lowerCAmelCase_       :    List[Any]								=			constraint.advance()
            if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
              token_list.append(SCREAMING_SNAKE_CASE_	)
            elif isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
              token_list.extend(SCREAMING_SNAKE_CASE_	)
        else:
          lowerCAmelCase_       :    Dict								=			self.inprogress_constraint.advance()
          if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
            token_list.append(SCREAMING_SNAKE_CASE_	)
          elif isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
            token_list.extend(SCREAMING_SNAKE_CASE_	)

        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return None
        else:
          return token_list



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[List[int]]	):
        self.init_state()

        if token_ids is not None:
          for token in token_ids:
            # completes or steps **one** constraint
            lowerCAmelCase_						,lowerCAmelCase_       :    Union[str, Any]								=			self.add(SCREAMING_SNAKE_CASE_	)

            # the entire list of constraints are fulfilled
            if self.completed:
              break



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` should be an `int`, but is `{token_id}`."	)

        lowerCAmelCase_						,lowerCAmelCase_       :    Tuple								=			False, False

        if self.completed:
          lowerCAmelCase_       :    Any								=			True
          lowerCAmelCase_       :    Dict								=			False
          return complete, stepped

        if self.inprogress_constraint is not None:
          # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
          # job, simply update the state

          lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Any								=			self.inprogress_constraint.update(SCREAMING_SNAKE_CASE_	)
          if reset:
            # 1. If the next token breaks the progress, then we must restart.
            #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

            #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
            #     constraint, not the full list of constraints.

            self.pending_constraints.append(self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE_	)	)
            lowerCAmelCase_       :    Optional[int]								=			None

          if complete:
            # 2. If the next token completes the constraint, move it to completed list, set
            #     inprogress to None. If there are no pending constraints either, then this full list of constraints
            #     is complete.

            self.complete_constraints.append(self.inprogress_constraint	)
            lowerCAmelCase_       :    str								=			None

            if len(self.pending_constraints	) == 0:
              # we're done!
              lowerCAmelCase_       :    Union[str, Any]								=			True

        else:
          # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
          # of constraints?

          for cidx, pending_constraint in enumerate(self.pending_constraints	):
            if pending_constraint.does_advance(SCREAMING_SNAKE_CASE_	):
              lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    str								=			pending_constraint.update(SCREAMING_SNAKE_CASE_	)

              if not stepped:
                raise Exception(
                    '`constraint.update(token_id)` is not yielding incremental progress, '
                    'even though `constraint.does_advance(token_id)` is true.'	)

              if complete:
                self.complete_constraints.append(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    Any								=			None

              if not complete and stepped:
                lowerCAmelCase_       :    Optional[Any]								=			pending_constraint

              if complete or stepped:
                # If we made any progress at all, then it's at least not a "pending constraint".

                lowerCAmelCase_       :    Optional[int]								=			(
                    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                )

                if len(self.pending_constraints	) == 0 and self.inprogress_constraint is None:
                  # If there's no longer any pending after this and no inprogress either, then we must be
                  # complete.

                  lowerCAmelCase_       :    Optional[Any]								=			True

                break  # prevent accidentally stepping through multiple constraints with just one token.

        return complete, stepped





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str=True	):
        lowerCAmelCase_       :    List[Any]								=			ConstraintListState(self.constraints	)  # we actually never though self.constraints objects
        # throughout this process. So it's at initialization state.

        if stateful:
          lowerCAmelCase_       :    Any								=			[
              constraint.copy(stateful=SCREAMING_SNAKE_CASE_	) for constraint in self.complete_constraints
          ]
          if self.inprogress_constraint is not None:
            lowerCAmelCase_       :    List[str]								=			self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    List[Any]								=			[constraint.copy() for constraint in self.pending_constraints]

        return new_state





