


import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
UpperCAmelCase_   :				Optional[int]						      = 'src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
UpperCAmelCase_   :				List[str]						      = direct_transformers_import(PATH_TO_TRANSFORMERS)

UpperCAmelCase_   :				Optional[int]						      = transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
UpperCAmelCase_   :				List[Any]						      = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)')


UpperCAmelCase_   :				List[str]						      = {
    'DecisionTransformerConfig',
    'EncoderDecoderConfig',
    'MusicgenConfig',
    'RagConfig',
    'SpeechEncoderDecoderConfig',
    'TimmBackboneConfig',
    'VisionEncoderDecoderConfig',
    'VisionTextDualEncoderConfig',
    'LlamaConfig',
}







def  SCREAMING_SNAKE_CASE_		(    __A				:    str       )			->	Any:

       """simple docstring"""

       a_      :	Optional[Any]							=						None

       # source code of `config_class`
       a_      :	str							=						inspect.getsource(__A       )
       a_      :	Any							=						_re_checkpoint.findall(__A       )

       # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
       # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
       for ckpt_name, ckpt_link in checkpoints:
              # allow the link to end with `/`
              if ckpt_link.endswith('/'       ):
                     a_      :	Union[str, Any]							=						ckpt_link[:-1]

              # verify the checkpoint name corresponds to the checkpoint link
              a_      :	List[Any]							=						F"""https://huggingface.co/{ckpt_name}"""
              if ckpt_link == ckpt_link_from_name:
                     a_      :	List[Any]							=						ckpt_name
                     break

       return checkpoint







def  SCREAMING_SNAKE_CASE_		(    )			->	str:

       """simple docstring"""

       a_      :	Optional[Any]							=						[]

       for config_class in list(CONFIG_MAPPING.values()       ):
              # Skip deprecated models
              if "models.deprecated" in config_class.__module__:
                     continue
              a_      :	Any							=						get_checkpoint_from_config_class(__A       )

              a_      :	Optional[int]							=						config_class.__name__
              if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
                     configs_without_checkpoint.append(__A       )

       if len(__A       ) > 0:
              a_      :	Union[str, Any]							=						'\n'.join(sorted(__A       )       )
              raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}"""       )


if __name__ == "__main__":
   check_config_docstrings_have_checkpoints()






import pyarrow.parquet as pq
import pytest

from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases







def  SCREAMING_SNAKE_CASE_		(    __A				:    Union[str, Any]						,					__A				:    Tuple       )			->	Any:

       """simple docstring"""

       assert isinstance(__A						,					__A       )
       assert dataset.num_rows == 4
       assert dataset.num_columns == 3
       assert dataset.column_names == ["col_1", "col_2", "col_3"]
       for feature, expected_dtype in expected_features.items():
              assert dataset.features[feature].dtype == expected_dtype







@pytest.mark.parametrize('keep_in_memory'						,					[False, True]       )
def  SCREAMING_SNAKE_CASE_		(    __A				:    List[Any]						,					__A				:    Any						,					__A				:    Tuple       )			->	Tuple:

       """simple docstring"""

       a_      :	Dict							=						tmp_path / 'cache'
       a_      :	int							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
              a_      :	Union[str, Any]							=						ParquetDatasetReader(__A						,					cache_dir=__A						,					keep_in_memory=__A       ).read()
       _check_parquet_dataset(__A						,					__A       )







@pytest.mark.parametrize(
    'features'						,					[
        None,
        {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
        {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
        {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
        {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
    ]						,					)
def  SCREAMING_SNAKE_CASE_		(    __A				:    str						,					__A				:    Dict						,					__A				:    Union[str, Any]       )			->	Dict:

       """simple docstring"""

       a_      :	Tuple							=						tmp_path / 'cache'
       a_      :	str							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_      :	List[str]							=						features.copy() if features else default_expected_features
       a_      :	int							=						(
           Features({feature: Value(__A       ) for feature, dtype in features.items()}       ) if features is not None else None
       )
       a_      :	List[str]							=						ParquetDatasetReader(__A						,					features=__A						,					cache_dir=__A       ).read()
       _check_parquet_dataset(__A						,					__A       )







@pytest.mark.parametrize('split'						,					[None, NamedSplit('train'       ), 'train', 'test']       )
def  SCREAMING_SNAKE_CASE_		(    __A				:    List[str]						,					__A				:    List[str]						,					__A				:    int       )			->	List[str]:

       """simple docstring"""

       a_      :	int							=						tmp_path / 'cache'
       a_      :	str							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_      :	List[str]							=						ParquetDatasetReader(__A						,					cache_dir=__A						,					split=__A       ).read()
       _check_parquet_dataset(__A						,					__A       )
       assert dataset.split == split if split else "train"







@pytest.mark.parametrize('path_type'						,					[str, list]       )
def  SCREAMING_SNAKE_CASE_		(    __A				:    Tuple						,					__A				:    str						,					__A				:    Optional[int]       )			->	Any:

       """simple docstring"""

       if issubclass(__A						,					__A       ):
              a_      :	Tuple							=						parquet_path
       elif issubclass(__A						,					__A       ):
              a_      :	str							=						[parquet_path]
       a_      :	int							=						tmp_path / 'cache'
       a_      :	int							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_      :	str							=						ParquetDatasetReader(__A						,					cache_dir=__A       ).read()
       _check_parquet_dataset(__A						,					__A       )







def  SCREAMING_SNAKE_CASE_		(    __A				:    Any						,					__A				:    Dict						,					__A				:    Optional[Any]=("train",)       )			->	Optional[int]:

       """simple docstring"""

       assert isinstance(__A						,					__A       )
       for split in splits:
              a_      :	str							=						dataset_dict[split]
              assert dataset.num_rows == 4
              assert dataset.num_columns == 3
              assert dataset.column_names == ["col_1", "col_2", "col_3"]
              for feature, expected_dtype in expected_features.items():
                     assert dataset.features[feature].dtype == expected_dtype







@pytest.mark.parametrize('keep_in_memory'						,					[False, True]       )
def  SCREAMING_SNAKE_CASE_		(    __A				:    Optional[Any]						,					__A				:    str						,					__A				:    str       )			->	Union[str, Any]:

       """simple docstring"""

       a_      :	Union[str, Any]							=						tmp_path / 'cache'
       a_      :	Any							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
              a_      :	Tuple							=						ParquetDatasetReader(
                  {'train': parquet_path}						,					cache_dir=__A						,					keep_in_memory=__A       ).read()
       _check_parquet_datasetdict(__A						,					__A       )







@pytest.mark.parametrize(
    'features'						,					[
        None,
        {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
        {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
        {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
        {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
    ]						,					)
def  SCREAMING_SNAKE_CASE_		(    __A				:    Any						,					__A				:    Optional[int]						,					__A				:    Tuple       )			->	List[Any]:

       """simple docstring"""

       a_      :	Optional[Any]							=						tmp_path / 'cache'
       a_      :	List[str]							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_      :	Optional[int]							=						features.copy() if features else default_expected_features
       a_      :	Tuple							=						(
           Features({feature: Value(__A       ) for feature, dtype in features.items()}       ) if features is not None else None
       )
       a_      :	Optional[Any]							=						ParquetDatasetReader({'train': parquet_path}						,					features=__A						,					cache_dir=__A       ).read()
       _check_parquet_datasetdict(__A						,					__A       )







@pytest.mark.parametrize('split'						,					[None, NamedSplit('train'       ), 'train', 'test']       )
def  SCREAMING_SNAKE_CASE_		(    __A				:    int						,					__A				:    List[Any]						,					__A				:    Optional[Any]       )			->	Any:

       """simple docstring"""

       if split:
              a_      :	Any							=						{split: parquet_path}
       else:
              a_      :	Dict							=						'train'
              a_      :	int							=						{'train': parquet_path, 'test': parquet_path}
       a_      :	int							=						tmp_path / 'cache'
       a_      :	List[Any]							=						{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_      :	Tuple							=						ParquetDatasetReader(__A						,					cache_dir=__A       ).read()
       _check_parquet_datasetdict(__A						,					__A						,					splits=list(path.keys()       )       )
       assert all(dataset[split].split == split for split in path.keys()       )







def  SCREAMING_SNAKE_CASE_		(    __A				:    Any						,					__A				:    Optional[int]       )			->	List[Any]:

       """simple docstring"""

       a_      :	List[str]							=						ParquetDatasetWriter(__A						,					tmp_path / 'foo.parquet'       )
       assert writer.write() > 0
       a_      :	List[str]							=						pq.ParquetFile(tmp_path / 'foo.parquet'       )
       a_      :	Dict							=						pf.read()
       assert dataset.data.table == output_table







def  SCREAMING_SNAKE_CASE_		(    __A				:    Optional[int]						,					__A				:    Any       )			->	Optional[int]:

       """simple docstring"""

       a_      :	str							=						str(shared_datadir / 'test_image_rgb.jpg'       )
       a_      :	List[Any]							=						{'image': [image_path]}
       a_      :	int							=						Features({'image': Image()}       )
       a_      :	List[Any]							=						Dataset.from_dict(__A						,					features=__A       )
       a_      :	str							=						ParquetDatasetWriter(__A						,					tmp_path / 'foo.parquet'       )
       assert writer.write() > 0

       a_      :	str							=						Dataset.from_parquet(str(tmp_path / 'foo.parquet'       )       )
       assert dataset.features == reloaded_dataset.features

       a_      :	str							=						ParquetDatasetReader(str(tmp_path / 'foo.parquet'       )						,					streaming=__A       ).read()
       assert dataset.features == reloaded_iterable_dataset.features







@pytest.mark.parametrize(
    'feature, expected'						,					[
        (Features({'foo': Value('int32'       )}       ), None),
        (Features({'image': Image(), 'foo': Value('int32'       )}       ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
        (Features({'nested': Sequence(Audio()       )}       ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
    ]						,					)
def  SCREAMING_SNAKE_CASE_		(    __A				:    int						,					__A				:    List[str]       )			->	List[str]:

       """simple docstring"""

       assert get_writer_batch_size(__A       ) == expected


