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

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
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_  							=			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>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					str		,							__SCREAMING_SNAKE_CASE       :					Union[str, Any]		,							__SCREAMING_SNAKE_CASE       :					str=0   ):







    '''simple docstring'''
    __snake_case       :				int 			=    (size, size) if isinstance(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE   ) else size
    __snake_case       :				List[str] 			=    img.size
    __snake_case       :				List[Any] 			=    size[1] - original_height if original_height < size[1] else 0
    __snake_case       :				Optional[int] 			=    size[0] - original_width if original_width < size[0] else 0
    __snake_case       :				Dict 			=    functional.pad(_SCREAMING_SNAKE_CASE		,							(0, 0, pad_width, pad_height)		,							fill=_SCREAMING_SNAKE_CASE   )
    return img







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Dict			,			_lowerCAmelCase					:     int			):
           __snake_case       :				Any 			=    transforms





       def __call__(							self					:     Optional[Any]			,			_lowerCAmelCase					:     Dict			,			_lowerCAmelCase					:     Dict			):
           for t in self.transforms:
               __snake_case       :				Union[str, Any] 			=    t(UpperCamelCase_			,			UpperCamelCase_			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Tuple			):
           pass





       def __call__(							self					:     Optional[int]			,			_lowerCAmelCase					:     str			,			_lowerCAmelCase					:     Dict			):
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Optional[int]			,			_lowerCAmelCase					:     List[Any]			):
           __snake_case       :				Optional[Any] 			=    size





       def __call__(							self					:     List[Any]			,			_lowerCAmelCase					:     List[str]			,			_lowerCAmelCase					:     int			):
           __snake_case       :				str 			=    functional.resize(UpperCamelCase_			,			self.size			)
           __snake_case       :				Union[str, Any] 			=    functional.resize(UpperCamelCase_			,			self.size			,			interpolation=transforms.InterpolationMode.NEAREST			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Tuple			,			_lowerCAmelCase					:     Dict			,			_lowerCAmelCase					:     List[Any]=None			):
           __snake_case       :				Dict 			=    min_size
           if max_size is None:
               __snake_case       :				List[Any] 			=    min_size
           __snake_case       :				int 			=    max_size





       def __call__(							self					:     Optional[int]			,			_lowerCAmelCase					:     str			,			_lowerCAmelCase					:     str			):
           __snake_case       :				int 			=    random.randint(self.min_size			,			self.max_size			)
           __snake_case       :				str 			=    functional.resize(UpperCamelCase_			,			UpperCamelCase_			)
           __snake_case       :				List[Any] 			=    functional.resize(UpperCamelCase_			,			UpperCamelCase_			,			interpolation=transforms.InterpolationMode.NEAREST			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Any			,			_lowerCAmelCase					:     Optional[Any]			):
           __snake_case       :				List[Any] 			=    size if isinstance(UpperCamelCase_			,			UpperCamelCase_			) else (size, size)





       def __call__(							self					:     Optional[Any]			,			_lowerCAmelCase					:     Optional[Any]			,			_lowerCAmelCase					:     List[str]			):
           __snake_case       :				str 			=    pad_if_smaller(UpperCamelCase_			,			self.size			)
           __snake_case       :				Union[str, Any] 			=    pad_if_smaller(UpperCamelCase_			,			self.size			,			fill=2_55			)
           __snake_case       :				List[Any] 			=    transforms.RandomCrop.get_params(UpperCamelCase_			,			self.size			)
           __snake_case       :				Optional[int] 			=    functional.crop(UpperCamelCase_			,			*UpperCamelCase_			)
           __snake_case       :				str 			=    functional.crop(UpperCamelCase_			,			*UpperCamelCase_			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Dict			,			_lowerCAmelCase					:     Tuple			):
           __snake_case       :				List[str] 			=    flip_prob





       def __call__(							self					:     str			,			_lowerCAmelCase					:     Dict			,			_lowerCAmelCase					:     Any			):
           if random.random() < self.flip_prob:
               __snake_case       :				Optional[Any] 			=    functional.hflip(UpperCamelCase_			)
               __snake_case       :				Dict 			=    functional.hflip(UpperCamelCase_			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __call__(							self					:     Optional[int]			,			_lowerCAmelCase					:     Any			,			_lowerCAmelCase					:     List[str]			):
           __snake_case       :				List[Any] 			=    functional.pil_to_tensor(UpperCamelCase_			)
           __snake_case       :				Optional[Any] 			=    torch.as_tensor(np.array(UpperCamelCase_			)			,			dtype=torch.intaa			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Optional[Any]			,			_lowerCAmelCase					:     List[Any]			):
           __snake_case       :				Any 			=    dtype





       def __call__(							self					:     Dict			,			_lowerCAmelCase					:     str			,			_lowerCAmelCase					:     Tuple			):
           __snake_case       :				Dict 			=    functional.convert_image_dtype(UpperCamelCase_			,			self.dtype			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Tuple			,			_lowerCAmelCase					:     Optional[int]			,			_lowerCAmelCase					:     int			):
           __snake_case       :				List[str] 			=    mean
           __snake_case       :				Tuple 			=    std





       def __call__(							self					:     Union[str, Any]			,			_lowerCAmelCase					:     Dict			,			_lowerCAmelCase					:     str			):
           __snake_case       :				List[Any] 			=    functional.normalize(UpperCamelCase_			,			mean=self.mean			,			std=self.std			)
           return image, target







class      SCREAMING_SNAKE_CASE__					:

       def __call__(							self					:     List[str]			,			_lowerCAmelCase					:     Tuple			,			_lowerCAmelCase					:     List[Any]			):
           if not isinstance(UpperCamelCase_			,			np.ndarray			):
               __snake_case       :				Dict 			=    np.array(UpperCamelCase_			).astype(np.uinta			)
           # avoid using underflow conversion
           __snake_case       :				Any 			=    2_55
           __snake_case       :				List[Any] 			=    target - 1
           __snake_case       :				Tuple 			=    2_55

           __snake_case       :				Optional[Any] 			=    Image.fromarray(UpperCamelCase_			)
           return image, target







@dataclass
class      SCREAMING_SNAKE_CASE__					:
       A							:	Optional[str]          =	field(
           default="segments/sidewalk-semantic"   ,							metadata={
               "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
           }   ,							)
       A							:	Optional[str]          =	field(
           default=lowerCAmelCase_   ,							metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}    )
       A							:	Optional[float]          =	field(
           default=0.15   ,							metadata={"help": "Percent to split off of train for validation."}    )
       A							:	Optional[int]          =	field(
           default=lowerCAmelCase_   ,							metadata={
               "help": (
                   "For debugging purposes or quicker training, truncate the number of training examples to this "
                   "value if set."
               )
           }   ,							)
       A							:	Optional[int]          =	field(
           default=lowerCAmelCase_   ,							metadata={
               "help": (
                   "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                   "value if set."
               )
           }   ,							)
       A							:	Optional[bool]          =	field(
           default=lowerCAmelCase_   ,							metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}   ,							)

       def 			snake_case__    (							self					:     List[Any]			):
           if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
               raise ValueError(
                   """You must specify either a dataset name from the hub or a train and/or validation directory."""			)







@dataclass
class      SCREAMING_SNAKE_CASE__					:
       A							:	str          =	field(
           default="nvidia/mit-b0"   ,							metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}   ,							)
       A							:	Optional[str]          =	field(
           default=lowerCAmelCase_   ,							metadata={"help": "Pretrained config name or path if not the same as model_name"}    )
       A							:	Optional[str]          =	field(
           default=lowerCAmelCase_   ,							metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}    )
       A							:	str          =	field(
           default="main"   ,							metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}   ,							)
       A							:	str          =	field(default=lowerCAmelCase_   ,							metadata={"help": "Name or path of preprocessor config."}    )
       A							:	bool          =	field(
           default=lowerCAmelCase_   ,							metadata={
               "help": (
                   "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
                   "with private models)."
               )
           }   ,							)







def 					__lowerCAmelCase				(		):







    '''simple docstring'''
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    __snake_case       :				Optional[int] 			=    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.
        __snake_case       :				int 			=    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
    else:
        __snake_case       :				Optional[Any] 			=    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_semantic_segmentation"""		,							_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE   )

    # 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()

    __snake_case       :				Optional[int] 			=    training_args.get_process_log_level()
    logger.setLevel(_SCREAMING_SNAKE_CASE   )
    transformers.utils.logging.set_verbosity(_SCREAMING_SNAKE_CASE   )
    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}'''   )

    # Detecting last checkpoint.
    __snake_case       :				Optional[Any] 			=    None
    if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
        __snake_case       :				Tuple 			=    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 overcome."""   )
        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."""   )

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
    __snake_case       :				Any 			=    load_dataset(data_args.dataset_name		,							cache_dir=model_args.cache_dir   )

    # Rename column names to standardized names (only "image" and "label" need to be present)
    if "pixel_values" in dataset["train"].column_names:
        __snake_case       :				Union[str, Any] 			=    dataset.rename_columns({"""pixel_values""": """image"""}   )
    if "annotation" in dataset["train"].column_names:
        __snake_case       :				str 			=    dataset.rename_columns({"""annotation""": """label"""}   )

    # If we don't have a validation split, split off a percentage of train as validation.
    __snake_case       :				int 			=    None if '''validation''' in dataset.keys() else data_args.train_val_split
    if isinstance(data_args.train_val_split		,							_SCREAMING_SNAKE_CASE   ) and data_args.train_val_split > 0.0:
        __snake_case       :				Any 			=    dataset['''train'''].train_test_split(data_args.train_val_split   )
        __snake_case       :				Tuple 			=    split['''train''']
        __snake_case       :				Optional[Any] 			=    split['''test''']

    # Prepare label mappings.
    # We'll include these in the model's config to get human readable labels in the Inference API.
    if data_args.dataset_name == "scene_parse_150":
        __snake_case       :				Optional[Any] 			=    '''huggingface/label-files'''
        __snake_case       :				List[Any] 			=    '''ade20k-id2label.json'''
    else:
        __snake_case       :				Dict 			=    data_args.dataset_name
        __snake_case       :				Tuple 			=    '''id2label.json'''
    __snake_case       :				str 			=    json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE		,							repo_type="""dataset"""   )		,							"""r"""   )   )
    __snake_case       :				Any 			=    {int(_SCREAMING_SNAKE_CASE   ): v for k, v in idalabel.items()}
    __snake_case       :				Dict 			=    {v: str(_SCREAMING_SNAKE_CASE   ) for k, v in idalabel.items()}

    # Load the mean IoU metric from the datasets package
    __snake_case       :				Dict 			=    evaluate.load("""mean_iou"""   )

    # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
    @torch.no_grad()
    def compute_metrics(__SCREAMING_SNAKE_CASE       :					Optional[int]   ):
        __snake_case       :				List[str] 			=    eval_pred
        __snake_case       :				Optional[int] 			=    torch.from_numpy(_SCREAMING_SNAKE_CASE   )
        # scale the logits to the size of the label
        __snake_case       :				Union[str, Any] 			=    nn.functional.interpolate(
            _SCREAMING_SNAKE_CASE		,							size=labels.shape[-2:]		,							mode="""bilinear"""		,							align_corners=_SCREAMING_SNAKE_CASE		,							).argmax(dim=1   )

        __snake_case       :				Optional[int] 			=    logits_tensor.detach().cpu().numpy()
        __snake_case       :				int 			=    metric.compute(
            predictions=_SCREAMING_SNAKE_CASE		,							references=_SCREAMING_SNAKE_CASE		,							num_labels=len(_SCREAMING_SNAKE_CASE   )		,							ignore_index=0		,							reduce_labels=image_processor.do_reduce_labels		,							)
        # add per category metrics as individual key-value pairs
        __snake_case       :				Any 			=    metrics.pop("""per_category_accuracy"""   ).tolist()
        __snake_case       :				int 			=    metrics.pop("""per_category_iou"""   ).tolist()

        metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(_SCREAMING_SNAKE_CASE   )}   )
        metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(_SCREAMING_SNAKE_CASE   )}   )

        return metrics

    __snake_case       :				Any 			=    AutoConfig.from_pretrained(
        model_args.config_name or model_args.model_name_or_path		,							labelaid=_SCREAMING_SNAKE_CASE		,							idalabel=_SCREAMING_SNAKE_CASE		,							cache_dir=model_args.cache_dir		,							revision=model_args.model_revision		,							use_auth_token=True if model_args.use_auth_token else None		,							)
    __snake_case       :				Tuple 			=    AutoModelForSemanticSegmentation.from_pretrained(
        model_args.model_name_or_path		,							from_tf=bool(""".ckpt""" in model_args.model_name_or_path   )		,							config=_SCREAMING_SNAKE_CASE		,							cache_dir=model_args.cache_dir		,							revision=model_args.model_revision		,							use_auth_token=True if model_args.use_auth_token else None		,							)
    __snake_case       :				int 			=    AutoImageProcessor.from_pretrained(
        model_args.image_processor_name or model_args.model_name_or_path		,							cache_dir=model_args.cache_dir		,							revision=model_args.model_revision		,							use_auth_token=True if model_args.use_auth_token else None		,							)

    # Define torchvision transforms to be applied to each image + target.
    # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
    # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
    if "shortest_edge" in image_processor.size:
        # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
        __snake_case       :				Optional[Any] 			=    (image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
    else:
        __snake_case       :				int 			=    (image_processor.size['''height'''], image_processor.size['''width'''])
    __snake_case       :				Optional[int] 			=    Compose(
        [
            ReduceLabels() if data_args.reduce_labels else Identity(),
            RandomCrop(size=_SCREAMING_SNAKE_CASE   ),
            RandomHorizontalFlip(flip_prob=0.5   ),
            PILToTensor(),
            ConvertImageDtype(torch.float   ),
            Normalize(mean=image_processor.image_mean		,							std=image_processor.image_std   ),
        ]   )
    # Define torchvision transform to be applied to each image.
    # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
    __snake_case       :				int 			=    Compose(
        [
            ReduceLabels() if data_args.reduce_labels else Identity(),
            Resize(size=_SCREAMING_SNAKE_CASE   ),
            PILToTensor(),
            ConvertImageDtype(torch.float   ),
            Normalize(mean=image_processor.image_mean		,							std=image_processor.image_std   ),
        ]   )

    def preprocess_train(__SCREAMING_SNAKE_CASE       :					str   ):
        __snake_case       :				int 			=    []
        __snake_case       :				Optional[int] 			=    []
        for image, target in zip(example_batch["""image"""]		,							example_batch["""label"""]   ):
            __snake_case       :				Any 			=    train_transforms(image.convert("""RGB"""   )		,							_SCREAMING_SNAKE_CASE   )
            pixel_values.append(_SCREAMING_SNAKE_CASE   )
            labels.append(_SCREAMING_SNAKE_CASE   )

        __snake_case       :				Dict 			=    {}
        __snake_case       :				List[str] 			=    torch.stack(_SCREAMING_SNAKE_CASE   )
        __snake_case       :				Tuple 			=    torch.stack(_SCREAMING_SNAKE_CASE   )

        return encoding

    def preprocess_val(__SCREAMING_SNAKE_CASE       :					int   ):
        __snake_case       :				List[Any] 			=    []
        __snake_case       :				Any 			=    []
        for image, target in zip(example_batch["""image"""]		,							example_batch["""label"""]   ):
            __snake_case       :				Optional[int] 			=    val_transforms(image.convert("""RGB"""   )		,							_SCREAMING_SNAKE_CASE   )
            pixel_values.append(_SCREAMING_SNAKE_CASE   )
            labels.append(_SCREAMING_SNAKE_CASE   )

        __snake_case       :				List[Any] 			=    {}
        __snake_case       :				Optional[int] 			=    torch.stack(_SCREAMING_SNAKE_CASE   )
        __snake_case       :				List[Any] 			=    torch.stack(_SCREAMING_SNAKE_CASE   )

        return encoding

    if training_args.do_train:
        if "train" not in dataset:
            raise ValueError("""--do_train requires a train dataset"""   )
        if data_args.max_train_samples is not None:
            __snake_case       :				Any 			=    (
                dataset['''train'''].shuffle(seed=training_args.seed   ).select(range(data_args.max_train_samples   )   )
            )
        # Set the training transforms
        dataset["train"].set_transform(_SCREAMING_SNAKE_CASE   )

    if training_args.do_eval:
        if "validation" not in dataset:
            raise ValueError("""--do_eval requires a validation dataset"""   )
        if data_args.max_eval_samples is not None:
            __snake_case       :				Any 			=    (
                dataset['''validation'''].shuffle(seed=training_args.seed   ).select(range(data_args.max_eval_samples   )   )
            )
        # Set the validation transforms
        dataset["validation"].set_transform(_SCREAMING_SNAKE_CASE   )

    # Initalize our trainer
    __snake_case       :				Union[str, Any] 			=    Trainer(
        model=_SCREAMING_SNAKE_CASE		,							args=_SCREAMING_SNAKE_CASE		,							train_dataset=dataset["""train"""] if training_args.do_train else None		,							eval_dataset=dataset["""validation"""] if training_args.do_eval else None		,							compute_metrics=_SCREAMING_SNAKE_CASE		,							tokenizer=_SCREAMING_SNAKE_CASE		,							data_collator=_SCREAMING_SNAKE_CASE		,							)

    # Training
    if training_args.do_train:
        __snake_case       :				Optional[Any] 			=    None
        if training_args.resume_from_checkpoint is not None:
            __snake_case       :				List[Any] 			=    training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            __snake_case       :				Optional[Any] 			=    last_checkpoint
        __snake_case       :				List[Any] 			=    trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE   )
        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:
        __snake_case       :				str 			=    trainer.evaluate()
        trainer.log_metrics("""eval"""		,							_SCREAMING_SNAKE_CASE   )
        trainer.save_metrics("""eval"""		,							_SCREAMING_SNAKE_CASE   )

    # Write model card and (optionally) push to hub
    __snake_case       :				int 			=    {
        '''finetuned_from''': model_args.model_name_or_path,
        '''dataset''': data_args.dataset_name,
        '''tags''': ['''image-segmentation''', '''vision'''],
    }
    if training_args.push_to_hub:
        trainer.push_to_hub(**_SCREAMING_SNAKE_CASE   )
    else:
        trainer.create_model_card(**_SCREAMING_SNAKE_CASE   )


if __name__ == "__main__":
     main()





'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


__lowercase	=    {
    '''configuration_xlm_prophetnet''': ['''XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMProphetNetConfig'''],
}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowercase	=    ['''XLMProphetNetTokenizer''']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowercase	=    [
							    '''XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
							    '''XLMProphetNetDecoder''',
							    '''XLMProphetNetEncoder''',
							    '''XLMProphetNetForCausalLM''',
							    '''XLMProphetNetForConditionalGeneration''',
							    '''XLMProphetNetModel''',
							    '''XLMProphetNetPreTrainedModel''',
							]


if TYPE_CHECKING:
							from .configuration_xlm_prophetnet import XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMProphetNetConfig

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_xlm_prophetnet import XLMProphetNetTokenizer

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_xlm_prophetnet import (
														    XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST,
														    XLMProphetNetDecoder,
														    XLMProphetNetEncoder,
														    XLMProphetNetForCausalLM,
														    XLMProphetNetForConditionalGeneration,
														    XLMProphetNetModel,
														    XLMProphetNetPreTrainedModel,
														)

else:
							import sys

							__lowercase	=    _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






