





import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
  import sqlitea

  import sqlalchemy





class  lowerCAmelCase							(       lowercase_ ):







  def __init__(      self  :List[str]   ,							_lowercase  :Union[str, "sqlalchemy.sql.Selectable"]   ,							_lowercase  :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]   ,							_lowercase  :Optional[Features] = None   ,							_lowercase  :str = None   ,							_lowercase  :bool = False   ,							**_lowercase  :Union[str, Any]   ,							):






     '''simple docstring'''





     super().__init__(features=_lowercase   ,							cache_dir=_lowercase   ,							keep_in_memory=_lowercase   ,							**_lowercase )
     lowercase__			       =  Sql(
         cache_dir=_lowercase   ,							features=_lowercase   ,							sql=_lowercase   ,							con=_lowercase   ,							**_lowercase   ,							)







  def   UpperCAmelCase					(      self  :Any ):






     '''simple docstring'''





     lowercase__			       =  None
     lowercase__			       =  None
     lowercase__			       =  None
     lowercase__			       =  None

     self.builder.download_and_prepare(
         download_config=_lowercase   ,							download_mode=_lowercase   ,							verification_mode=_lowercase   ,							base_path=_lowercase   ,							)

     # Build dataset for splits
     lowercase__			       =  self.builder.as_dataset(
         split="train"   ,							verification_mode=_lowercase   ,							in_memory=self.keep_in_memory )
     return dataset





class  lowerCAmelCase							:







  def __init__(      self  :str   ,							_lowercase  :Dataset   ,							_lowercase  :str   ,							_lowercase  :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]   ,							_lowercase  :Optional[int] = None   ,							_lowercase  :Optional[int] = None   ,							**_lowercase  :List[str]   ,							):






     '''simple docstring'''





     if num_proc is not None and num_proc <= 0:
        raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' )

     lowercase__			       =  dataset
     lowercase__			       =  name
     lowercase__			       =  con
     lowercase__			       =  batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
     lowercase__			       =  num_proc
     lowercase__			       =  to_sql_kwargs







  def   UpperCAmelCase					(      self  :Any ):






     '''simple docstring'''





     lowercase__			       =  self.to_sql_kwargs.pop("sql"   ,							_lowercase )
     lowercase__			       =  self.to_sql_kwargs.pop("con"   ,							_lowercase )
     lowercase__			       =  self.to_sql_kwargs.pop("index"   ,							_lowercase )

     lowercase__			       =  self._write(index=_lowercase   ,							**self.to_sql_kwargs )
     return written







  def   UpperCAmelCase					(      self  :List[str]   ,							_lowercase  :Dict ):






     '''simple docstring'''





     lowercase__       ,							lowercase__       ,							lowercase__			       =  args
     lowercase__			       =  {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs
     lowercase__			       =  query_table(
         table=self.dataset.data   ,							key=slice(_lowercase   ,							offset + self.batch_size )   ,							indices=self.dataset._indices   ,							)
     lowercase__			       =  batch.to_pandas()
     lowercase__			       =  df.to_sql(self.name   ,							self.con   ,							index=_lowercase   ,							**_lowercase )
     return num_rows or len(_lowercase )







  def   UpperCAmelCase					(      self  :Dict   ,							_lowercase  :List[Any]   ,							**_lowercase  :str ):






     '''simple docstring'''





     lowercase__			       =  0

     if self.num_proc is None or self.num_proc == 1:
        for offset in logging.tqdm(
            range(0   ,							len(self.dataset )   ,							self.batch_size )   ,							unit="ba"   ,							disable=not logging.is_progress_bar_enabled()   ,							desc="Creating SQL from Arrow format"   ,							):
           written += self._batch_sql((offset, index, to_sql_kwargs) )
     else:
        lowercase__       ,							lowercase__			       =  len(self.dataset ), self.batch_size
        with multiprocessing.Pool(self.num_proc ) as pool:
           for num_rows in logging.tqdm(
               pool.imap(
                   self._batch_sql   ,							[(offset, index, to_sql_kwargs) for offset in range(0   ,							_lowercase   ,							_lowercase )]   ,							)   ,							total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size   ,							unit="ba"   ,							disable=not logging.is_progress_bar_enabled()   ,							desc="Creating SQL from Arrow format"   ,							):
              written += num_rows

     return written













import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch


def _A       (   __magic_name__	):  # picklable for multiprocessing
   return x.sum()


def _A       (   __magic_name__	):  # picklable for multiprocessing
   return i + 1





@dataclass
class  lowerCAmelCase							:
  __lowerCamelCase		=      42
  __lowerCamelCase		=      42





class  lowerCAmelCase							(       lowercase_ ):







  def   UpperCAmelCase					(      self  :Optional[Any] ):






     '''simple docstring'''





     lowercase__			       =  {}
     lowercase__			       =  []
     lowercase__			       =  1
     lowercase__			       =  [1, 2]
     lowercase__			       =  {"a": 1, "b": 2}
     lowercase__			       =  {"a": [1, 2], "b": [3, 4]}
     lowercase__			       =  {"a": {"1": 1}, "b": 2}
     lowercase__			       =  {"a": 1, "b": 2, "c": 3, "d": 4}
     lowercase__			       =  {}
     lowercase__			       =  []
     lowercase__			       =  2
     lowercase__			       =  [2, 3]
     lowercase__			       =  {"a": 2, "b": 3}
     lowercase__			       =  {"a": [2, 3], "b": [4, 5]}
     lowercase__			       =  {"a": {"1": 2}, "b": 3}
     lowercase__			       =  {"a": 2, "b": 3, "c": 4, "d": 5}
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase )   ,							_lowercase )

     lowercase__			       =  2
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )

     lowercase__			       =  {"a": np.eye(2 ), "b": np.zeros(3 ), "c": np.ones(2 )}
     lowercase__			       =  {"a": 2, "b": 0, "c": 2}
     lowercase__			       =  {
         "a": np.eye(2 ).astype(_lowercase ),
         "b": np.zeros(3 ).astype(_lowercase ),
         "c": np.ones(2 ).astype(_lowercase ),
     }
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							map_numpy=_lowercase )   ,							_lowercase )
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(_lowercase   ,							_lowercase   ,							map_numpy=_lowercase ).items()}   ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}   ,							)
     self.assertEqual(map_nested(_lowercase   ,							_lowercase   ,							map_numpy=_lowercase   ,							num_proc=_lowercase )   ,							_lowercase )
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(_lowercase   ,							_lowercase   ,							map_numpy=_lowercase   ,							num_proc=_lowercase ).items()}   ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}   ,							)
     with self.assertRaises(_lowercase ):  # can't pickle a local lambda
        map_nested(lambda _lowercase : x + 1   ,							_lowercase   ,							num_proc=_lowercase )







  def   UpperCAmelCase					(      self  :List[Any] ):






     '''simple docstring'''





     lowercase__			       =  {"a": 1, "b": 2}
     lowercase__			       =  {"a": 3, "b": 4}
     lowercase__			       =  {"a": 5, "b": 6}
     lowercase__			       =  sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))] )
     self.assertEqual(sorted(zip_dict(_lowercase   ,							_lowercase   ,							_lowercase ) )   ,							_lowercase )







  def   UpperCAmelCase					(      self  :Union[str, Any] ):






     '''simple docstring'''





     class  lowerCAmelCase							:
       __lowerCamelCase		=      'bar'
     lowercase__			       =  Foo()
     self.assertEqual(foo.my_attr   ,							"bar" )
     with temporary_assignment(_lowercase   ,							"my_attr"   ,							"BAR" ):
        self.assertEqual(foo.my_attr   ,							"BAR" )
     self.assertEqual(foo.my_attr   ,							"bar" )


@pytest.mark.parametrize(
    "iterable_length, num_proc, expected_num_proc"  , [
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ]  , )
def _A       (   __magic_name__  , __magic_name__  , __magic_name__	):
   with patch("datasets.utils.py_utils._single_map_nested"	) as mock_single_map_nested, patch(
       "datasets.parallel.parallel.Pool"	) as mock_multiprocessing_pool:
      lowercase__			       =  {f'''{i}''': i for i in range(__magic_name__	)}
      lowercase__			       =  map_nested(lambda __magic_name__	: x + 10  , __magic_name__  , num_proc=__magic_name__  , parallel_min_length=16	)
      if expected_num_proc == 1:
         assert mock_single_map_nested.called
         assert not mock_multiprocessing_pool.called
      else:
         assert not mock_single_map_nested.called
         assert mock_multiprocessing_pool.called
         assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc





class  lowerCAmelCase							(       lowercase_ ):







  @require_tf
  def   UpperCAmelCase					(      self  :List[Any] ):






     '''simple docstring'''





     import tensorflow as tf
     from tensorflow.keras import layers

     lowercase__			       =  layers.Dense(2 )

     def gen_random_output():
        lowercase__			       =  tf.random.uniform((1, 3) )
        return model(_lowercase ).numpy()

     with temp_seed(42   ,							set_tensorflow=_lowercase ):
        lowercase__			       =  gen_random_output()
     with temp_seed(42   ,							set_tensorflow=_lowercase ):
        lowercase__			       =  gen_random_output()
     lowercase__			       =  gen_random_output()

     np.testing.assert_equal(_lowercase   ,							_lowercase )
     self.assertGreater(np.abs(outa - outa ).sum()   ,							0 )







  @require_torch
  def   UpperCAmelCase					(      self  :Optional[int] ):






     '''simple docstring'''





     import torch

     def gen_random_output():
        lowercase__			       =  torch.nn.Linear(3   ,							2 )
        lowercase__			       =  torch.rand(1   ,							3 )
        return model(_lowercase ).detach().numpy()

     with temp_seed(42   ,							set_pytorch=_lowercase ):
        lowercase__			       =  gen_random_output()
     with temp_seed(42   ,							set_pytorch=_lowercase ):
        lowercase__			       =  gen_random_output()
     lowercase__			       =  gen_random_output()

     np.testing.assert_equal(_lowercase   ,							_lowercase )
     self.assertGreater(np.abs(outa - outa ).sum()   ,							0 )







  def   UpperCAmelCase					(      self  :str ):






     '''simple docstring'''





     def gen_random_output():
        return np.random.rand(1   ,							3 )

     with temp_seed(42 ):
        lowercase__			       =  gen_random_output()
     with temp_seed(42 ):
        lowercase__			       =  gen_random_output()
     lowercase__			       =  gen_random_output()

     np.testing.assert_equal(_lowercase   ,							_lowercase )
     self.assertGreater(np.abs(outa - outa ).sum()   ,							0 )


@pytest.mark.parametrize("input_data"  , [{}]	)
def _A       (   __magic_name__	):
   lowercase__			       =  NestedDataStructure(__magic_name__	).data
   assert output_data == input_data


@pytest.mark.parametrize(
    "data, expected_output"  , [
        ({}, []),
        ([], []),
        ("foo", ["foo"]),
        (["foo", "bar"], ["foo", "bar"]),
        ([["foo", "bar"]], ["foo", "bar"]),
        ([[["foo"], ["bar"]]], ["foo", "bar"]),
        ([[["foo"], "bar"]], ["foo", "bar"]),
        ({"a": 1, "b": 2}, [1, 2]),
        ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]),
        ({"a": {"1": 1}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": [2]}, [1, 2]),
    ]  , )
def _A       (   __magic_name__  , __magic_name__	):
   lowercase__			       =  NestedDataStructure(__magic_name__	).flatten()
   assert output == expected_output


def _A       (   ):
   lowercase__			       =  A(x=1  , y="foobar"	)
   lowercase__			       =  {"x": 1, "y": "foobar"}
   assert asdict(__magic_name__	) == expected_output

   lowercase__			       =  {"a": {"b": A(x=10  , y="foo"	)}, "c": [A(x=20  , y="bar"	)]}
   lowercase__			       =  {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]}
   assert asdict(__magic_name__	) == expected_output

   with pytest.raises(__magic_name__	):
      asdict([1, A(x=10  , y="foo"	)]	)


def _A       (   __magic_name__	):
   return text.split()


def _A       (   __magic_name__	):
   yield (time.time(), content)
   time.sleep(2	)
   yield (time.time(), content)







def _A       (   ):
   with Pool(2	) as pool:
      lowercase__			       =  list(iflatmap_unordered(__magic_name__  , _split_text  , kwargs_iterable=[{"text": "hello there"}] * 10	)	)
      assert out.count("hello"	) == 10
      assert out.count("there"	) == 10
      assert len(__magic_name__	) == 20

   # check multiprocess from pathos (uses dill for pickling)
   with multiprocess.Pool(2	) as pool:
      lowercase__			       =  list(iflatmap_unordered(__magic_name__  , _split_text  , kwargs_iterable=[{"text": "hello there"}] * 10	)	)
      assert out.count("hello"	) == 10
      assert out.count("there"	) == 10
      assert len(__magic_name__	) == 20

   # check that we get items as fast as possible
   with Pool(2	) as pool:
      lowercase__			       =  []
      for yield_time, content in iflatmap_unordered(
          __magic_name__  , _aseconds_generator_of_aitems_with_timing  , kwargs_iterable=[{"content": "a"}, {"content": "b"}]	):
         assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
         out.append(__magic_name__	)
      assert out.count("a"	) == 2
      assert out.count("b"	) == 2
      assert len(__magic_name__	) == 4






