
import os
import sys
import unittest


lowercase  :					Any						    =							os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
lowercase  :					List[Any]						    =							os.path.join(git_repo_path, """src""", """transformers""")

lowercase  :					List[Any]						    =							"""
{0} = None
"""

lowercase  :					Tuple						    =							"""
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
"""


lowercase  :					Optional[Any]						    =							"""
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""

class __snake_case		(      unittest.TestCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""      )
           self.assertIsNone(snake_case      )

           lowercase							:     List[str]       	=      find_backend("""    if not is_tokenizers_available():"""      )
           self.assertEqual(snake_case		,"""tokenizers"""      )

           lowercase							:     List[Any]       	=      find_backend("""    if not is_tensorflow_text_available():"""      )
           self.assertEqual(snake_case		,"""tensorflow_text"""      )

           lowercase							:     Any       	=      find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""      )
           self.assertEqual(snake_case		,"""sentencepiece_and_tokenizers"""      )

           lowercase							:     Tuple       	=      find_backend(
               """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""      )
           self.assertEqual(snake_case		,"""sentencepiece_and_tensorflow_text"""      )

           lowercase							:     Union[str, Any]       	=      find_backend(
               """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""      )
           self.assertEqual(snake_case		,"""sentencepiece_and_tokenizers_and_vision"""      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("""torch"""		,snake_case      )
           self.assertIn("""tensorflow_text"""		,snake_case      )
           self.assertIn("""sentencepiece_and_tokenizers"""		,snake_case      )

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("""BertModel"""		,objects["""torch"""]      )
           self.assertIn("""TFBertModel"""		,objects["""tf"""]      )
           self.assertIn("""FlaxBertModel"""		,objects["""flax"""]      )
           self.assertIn("""BertModel"""		,objects["""torch"""]      )
           self.assertIn("""TFBertTokenizer"""		,objects["""tensorflow_text"""]      )
           self.assertIn("""convert_slow_tokenizer"""		,objects["""sentencepiece_and_tokenizers"""]      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Any       	=      create_dummy_object("""CONSTANT"""		,"""'torch'"""      )
           self.assertEqual(snake_case		,"""\nCONSTANT = None\n"""      )

           lowercase							:     Any       	=      create_dummy_object("""function"""		,"""'torch'"""      )
           self.assertEqual(
               snake_case		,"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""      )

           lowercase							:     Any       	=      """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
           lowercase							:     int       	=      create_dummy_object("""FakeClass"""		,"""'torch'"""      )
           self.assertEqual(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
           lowercase							:     Union[str, Any]       	=      create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}      )
           self.assertEqual(dummy_files["""torch"""]		,snake_case      )


import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Any:
       assert isinstance(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       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







@require_sqlalchemy
@pytest.mark.parametrize("""keep_in_memory"""					,	[False, True]				)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Union[str, Any]:
       lowercase							:     Union[str, Any]       	=      tmp_path / """cache"""
       lowercase							:     Optional[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():
              lowercase							:     Any       	=      SqlDatasetReader(
                  """dataset"""					,	"""sqlite:///""" + sqlite_path					,	cache_dir=SCREAMING_SNAKE_CASE__					,	keep_in_memory=SCREAMING_SNAKE_CASE__				).read()
       _check_sql_dataset(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)







@require_sqlalchemy
@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 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Tuple:
       lowercase							:     Union[str, Any]       	=      tmp_path / """cache"""
       lowercase							:     int       	=      {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
       lowercase							:     str       	=      features.copy() if features else default_expected_features
       lowercase							:     Optional[Any]       	=      (
           Features({feature: Value(SCREAMING_SNAKE_CASE__				) for feature, dtype in features.items()}				) if features is not None else None
       )
       lowercase							:     Optional[int]       	=      SqlDatasetReader("""dataset"""					,	"""sqlite:///""" + sqlite_path					,	features=SCREAMING_SNAKE_CASE__					,	cache_dir=SCREAMING_SNAKE_CASE__				).read()
       _check_sql_dataset(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)







def 						_snake_case(  SCREAMING_SNAKE_CASE__				) ->    List[Any]:
       with contextlib.closing(sqlitea.connect(SCREAMING_SNAKE_CASE__				)				) as con:
              lowercase							:     Optional[int]       	=      con.cursor()
              cur.execute("""SELECT * FROM dataset"""				)
              for row in cur:
                     yield row







@require_sqlalchemy
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    int:
       lowercase							:     Any       	=      tmp_path / """cache"""
       lowercase							:     int       	=      os.path.join(SCREAMING_SNAKE_CASE__					,	"""tmp.sql"""				)
       lowercase							:     List[str]       	=      SqlDatasetReader("""dataset"""					,	"""sqlite:///""" + sqlite_path					,	cache_dir=SCREAMING_SNAKE_CASE__				).read()
       SqlDatasetWriter(SCREAMING_SNAKE_CASE__					,	"""dataset"""					,	"""sqlite:///""" + output_sqlite_path					,	num_proc=1				).write()

       lowercase							:     List[str]       	=      iter_sql_file(SCREAMING_SNAKE_CASE__				)
       lowercase							:     Tuple       	=      iter_sql_file(SCREAMING_SNAKE_CASE__				)

       for rowa, rowa in zip(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				):
              assert rowa == rowa







@require_sqlalchemy
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Dict:
       lowercase							:     Dict       	=      tmp_path / """cache"""
       lowercase							:     List[str]       	=      os.path.join(SCREAMING_SNAKE_CASE__					,	"""tmp.sql"""				)
       lowercase							:     List[str]       	=      SqlDatasetReader("""dataset"""					,	"""sqlite:///""" + sqlite_path					,	cache_dir=SCREAMING_SNAKE_CASE__				).read()
       SqlDatasetWriter(SCREAMING_SNAKE_CASE__					,	"""dataset"""					,	"""sqlite:///""" + output_sqlite_path					,	num_proc=2				).write()

       lowercase							:     Optional[int]       	=      iter_sql_file(SCREAMING_SNAKE_CASE__				)
       lowercase							:     List[Any]       	=      iter_sql_file(SCREAMING_SNAKE_CASE__				)

       for rowa, rowa in zip(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				):
              assert rowa == rowa







@require_sqlalchemy
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    List[str]:
       lowercase							:     str       	=      tmp_path / """cache"""
       lowercase							:     Optional[int]       	=      os.path.join(SCREAMING_SNAKE_CASE__					,	"""tmp.sql"""				)
       lowercase							:     Optional[Any]       	=      SqlDatasetReader("""dataset"""					,	"""sqlite:///""" + sqlite_path					,	cache_dir=SCREAMING_SNAKE_CASE__				).read()
       with pytest.raises(SCREAMING_SNAKE_CASE__				):
              SqlDatasetWriter(SCREAMING_SNAKE_CASE__					,	"""dataset"""					,	"""sqlite:///""" + output_sqlite_path					,	num_proc=0				).write()
