


import os
import re
import shutil
from argparse import ArgumentParser, Namespace

from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger


_lowercase       :      List[Any]	=	"<<<<<<< This should probably be modified because it mentions: "

_lowercase       :      List[str]	=	"=======\n>>>>>>>\n"

_lowercase       :      Tuple	=	[
    "TextEncoderConfig",
    "ByteTextEncoder",
    "SubwordTextEncoder",
    "encoder_config",
    "maybe_build_from_corpus",
    "manual_dir",
]

_lowercase       :      Optional[Any]	=	[
    # (pattern, replacement)
    # Order is important here for some replacements
    (R"tfds\.core", R"datasets"),
    (R"tf\.io\.gfile\.GFile", R"open"),
    (R"tf\.([\w\d]+)", R"datasets.Value(\'\1\')"),
    (R"tfds\.features\.Text\(\)", R"datasets.Value(\'string\')"),
    (R"tfds\.features\.Text\(", R"datasets.Value(\'string\'),"),
    (R"features\s*=\s*tfds.features.FeaturesDict\(", R"features=datasets.Features("),
    (R"tfds\.features\.FeaturesDict\(", R"dict("),
    (R"The TensorFlow Datasets Authors", R"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"),
    (R"tfds\.", R"datasets."),
    (R"dl_manager\.manual_dir", R"self.config.data_dir"),
    (R"self\.builder_config", R"self.config"),
]





def   _lowerCAmelCase				(   UpperCamelCase__:     Dict						) ->   List[str]:





	"""simple docstring"""







	return ConvertCommand(args.tfds_path							,					args.datasets_directory						)






class       _UpperCamelCase    (					__snake_case				):

				"""simple docstring"""







				@staticmethod
				def      _UpperCAmelCase					(						a__   )	->				Optional[int]:
					A								=				parser.add_parser(
					    """convert"""				,   help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset."""				,   )
					train_parser.add_argument(
					    """--tfds_path"""				,   type=_SCREAMING_SNAKE_CASE				,   required=_SCREAMING_SNAKE_CASE				,   help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert."""				,   )
					train_parser.add_argument(
					    """--datasets_directory"""				,   type=_SCREAMING_SNAKE_CASE				,   required=_SCREAMING_SNAKE_CASE				,   help="""Path to the HuggingFace Datasets folder."""   )
					train_parser.set_defaults(func=_SCREAMING_SNAKE_CASE   )

				def __init__(						self				,   a__				,   a__				,   *a__   )	->				Union[str, Any]:
					A								=				get_logger("""datasets-cli/converting"""   )

					A								=				tfds_path
					A								=				datasets_directory

				def      _UpperCAmelCase					(						self   )	->				str:






					if os.path.isdir(self._tfds_path   ):
						A								=				os.path.abspath(self._tfds_path   )
					elif os.path.isfile(self._tfds_path   ):
						A								=				os.path.dirname(self._tfds_path   )
					else:
						raise ValueError("""--tfds_path is neither a directory nor a file. Please check path."""   )

					A								=				os.path.abspath(self._datasets_directory   )

					self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}'   )

					A								=				[]
					A								=				[]
					A								=				{}

					if os.path.isdir(self._tfds_path   ):
						A								=				os.listdir(_SCREAMING_SNAKE_CASE   )
					else:
						A								=				[os.path.basename(self._tfds_path   )]

					for f_name in file_names:
						self._logger.info(f'Looking at file {f_name}'   )
						A								=				os.path.join(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )
						A								=				os.path.join(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )

						if not os.path.isfile(_SCREAMING_SNAKE_CASE   ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
							self._logger.info("""Skipping file"""   )
							continue

						with open(_SCREAMING_SNAKE_CASE				,   encoding="""utf-8"""   ) as f:
							A								=				f.readlines()

						A								=				[]
						A								=				False
						A								=				False
						A								=				[]
						for line in lines:
							A								=				line

							# Convert imports
							if "import tensorflow.compat.v2 as tf" in out_line:
								continue
							elif "@tfds.core" in out_line:
								continue
							elif "builder=self" in out_line:
								continue
							elif "import tensorflow_datasets.public_api as tfds" in out_line:
								A								=				"""import datasets\n"""
							elif "import tensorflow" in out_line:
								# order is important here
								A								=				""""""
								continue
							elif "from absl import logging" in out_line:
								A								=				"""from datasets import logging\n"""
							elif "getLogger" in out_line:
								A								=				out_line.replace("""getLogger"""				,   """get_logger"""   )
							elif any(expression in out_line for expression in TO_HIGHLIGHT   ):
								A								=				True
								A								=				list(filter(lambda a__   : e in out_line				,   _SCREAMING_SNAKE_CASE   )   )
								out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_SCREAMING_SNAKE_CASE   ) + """\n"""   )
								out_lines.append(_SCREAMING_SNAKE_CASE   )
								out_lines.append(_SCREAMING_SNAKE_CASE   )
								continue
							else:
								for pattern, replacement in TO_CONVERT:
									A								=				re.sub(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )

                # Take care of saving utilities (to later move them together with main script)
							if "tensorflow_datasets" in out_line:
								A								=				re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)"""				,   _SCREAMING_SNAKE_CASE   )
								tfds_imports.extend(imp.strip() for imp in match.group(1   ).split(""","""   )   )
								A								=				"""from . import """ + match.group(1   )

							# Check we have not forget anything
							if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
								raise ValueError(f'Error converting {out_line.strip()}'   )

							if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
								A								=				True
							out_lines.append(_SCREAMING_SNAKE_CASE   )

						if is_builder or "wmt" in f_name:
							# We create a new directory for each dataset
							A								=				f_name.replace(""".py"""				,   """"""   )
							A								=				os.path.join(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )
							A								=				os.path.join(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )
							os.makedirs(_SCREAMING_SNAKE_CASE				,   exist_ok=_SCREAMING_SNAKE_CASE   )
							self._logger.info(f'Adding directory {output_dir}'   )
							imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}   )
						else:
							# Utilities will be moved at the end
							utils_files.append(_SCREAMING_SNAKE_CASE   )

						if needs_manual_update:
							with_manual_update.append(_SCREAMING_SNAKE_CASE   )

						with open(_SCREAMING_SNAKE_CASE				,   """w"""				,   encoding="""utf-8"""   ) as f:
							f.writelines(_SCREAMING_SNAKE_CASE   )
						self._logger.info(f'Converted in {output_file}'   )

					for utils_file in utils_files:
						try:
							A								=				os.path.basename(_SCREAMING_SNAKE_CASE   )
							A								=				imports_to_builder_map[f_name.replace(""".py"""				,   """"""   )]
							self._logger.info(f'Moving {dest_folder} to {utils_file}'   )
							shutil.copy(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE   )
						except KeyError:
							self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.'   )

					if with_manual_update:
						for file_path in with_manual_update:
							self._logger.warning(
							    f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.'   )







from sklearn.metrics import recall_score

import datasets


_lowercase       :      Any	=	"\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


_lowercase       :      int	=	"\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


_lowercase       :      Dict	=	"\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,		_KWARGS_DESCRIPTION				)
class       _UpperCamelCase    (					datasets.Metric				):

				"""simple docstring"""







				def      _UpperCAmelCase					(						self   )	->				Tuple:
					return datasets.MetricInfo(
					    description=_DESCRIPTION				,   citation=_CITATION				,   inputs_description=_KWARGS_DESCRIPTION				,   features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					            """references""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					        }
					        if self.config_name == """multilabel"""
					        else {
					            """predictions""": datasets.Value("""int32"""   ),
					            """references""": datasets.Value("""int32"""   ),
					        }   )				,   reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]				,   )

				def      _UpperCAmelCase					(						self				,   a__				,   a__				,   a__=None				,   a__=1				,   a__="binary"				,   a__=None				,   a__="warn"				,   )	->				Any:
					A								=				recall_score(
					    a__				,   a__				,   labels=a__				,   pos_label=a__				,   average=a__				,   sample_weight=a__				,   zero_division=a__				,   )
					return {"recall": float(a__   ) if score.size == 1 else score}



