




import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
 import sqlitea

 import sqlalchemy


SCREAMING_SNAKE_CASE_						:					Dict			   =       datasets.utils.logging.get_logger(__name__)







@dataclass
class 		__UpperCAmelCase(		datasets.BuilderConfig ):





     """simple docstring"""



     __UpperCAmelCase	: Union[str, "sqlalchemy.sql.Selectable"]						=    None
     __UpperCAmelCase	: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]						=    None
     __UpperCAmelCase	: Optional[Union[str, List[str]]]						=    None
     __UpperCAmelCase	: bool						=    True
     __UpperCAmelCase	: Optional[Union[List, Tuple, Dict]]						=    None
     __UpperCAmelCase	: Optional[Union[List, Dict]]						=    None
     __UpperCAmelCase	: Optional[List[str]]						=    None
     __UpperCAmelCase	: Optional[int]						=    10000
     __UpperCAmelCase	: Optional[datasets.Features]						=    None

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			Optional[int]:






         """simple docstring"""
         if self.sql is None:
             raise ValueError("""sql must be specified"""    )
         if self.con is None:
             raise ValueError("""con must be specified"""    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]						,				A :       dict						,				A :       Optional[datasets.Features] = None						,				)			->			str:






         """simple docstring"""
         a__      =       config_kwargs.copy()
         # We need to stringify the Selectable object to make its hash deterministic

         # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
         a__      =       config_kwargs["""sql"""]
         if not isinstance(A						,				A    ):
             if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                 import sqlalchemy

                 if isinstance(A						,				sqlalchemy.sql.Selectable    ):
                     a__      =       sqlalchemy.create_engine(config_kwargs["""con"""].split("""://"""    )[0] + """://"""    )
                     a__      =       str(sql.compile(dialect=engine.dialect    )    )
                     a__      =       sql_str
                 else:
                     raise TypeError(
                         f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(A    )}: {sql}"""    )
             else:
                 raise TypeError(
                     f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(A    )}: {sql}"""    )
         a__      =       config_kwargs["""con"""]
         if not isinstance(A						,				A    ):
             a__      =       id(A    )
             logger.info(
                 f"""SQL connection 'con' of type {type(A    )} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."""    )

         return super().create_config_id(A						,				custom_features=A    )






     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			str:






         """simple docstring"""
         a__      =       {
             """index_col""": self.index_col,
             """columns""": self.columns,
             """params""": self.params,
             """coerce_float""": self.coerce_float,
             """parse_dates""": self.parse_dates,
         }
         return pd_read_sql_kwargs







class 		__UpperCAmelCase(		datasets.ArrowBasedBuilder ):





     """simple docstring"""



     __UpperCAmelCase	: Union[str, Any]						=    SqlConfig

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Any:






         """simple docstring"""
         return datasets.DatasetInfo(features=self.config.features    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict						,				A :       str    )			->			Optional[int]:






         """simple docstring"""
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,				gen_kwargs={}    )]

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       pa.Table    )			->			pa.Table:






         """simple docstring"""
         if self.config.features is not None:
             a__      =       self.config.features.arrow_schema
             if all(not require_storage_cast(A    ) for feature in self.config.features.values()    ):
                 # cheaper cast
                 a__      =       pa.Table.from_arrays([pa_table[field.name] for field in schema]						,				schema=A    )
             else:
                 # more expensive cast; allows str <-> int/float or str to Audio for example
                 a__      =       table_cast(A						,				A    )
         return pa_table






     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]    )			->			str:






         """simple docstring"""
         a__      =       self.config.chunksize
         a__      =       pd.read_sql(
             self.config.sql						,				self.config.con						,				chunksize=A						,				**self.config.pd_read_sql_kwargs    )
         a__      =       [sql_reader] if chunksize is None else sql_reader
         for chunk_idx, df in enumerate(A    ):
             a__      =       pa.Table.from_pandas(A    )
             yield chunk_idx, self._cast_table(A    )












import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:







 class 		__UpperCAmelCase:





      """simple docstring"""



      @staticmethod
      def 				__SCREAMING_SNAKE_CASE		(      *A :       str						,				**A :       int    )			->			Union[str, Any]:






          """simple docstring"""
          pass







@is_pipeline_test
@require_torch_or_tf
@require_vision
class 		__UpperCAmelCase(		unittest.TestCase ):





     """simple docstring"""



     __UpperCAmelCase	: Tuple						=    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     __UpperCAmelCase	: Dict						=    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

     def 				__SCREAMING_SNAKE_CASE		(      self :       str						,				A :       Optional[int]						,				A :       Tuple						,				A :       int    )			->			str:






         """simple docstring"""
         a__      =       ImageClassificationPipeline(model=A						,				image_processor=A						,				top_k=2    )
         a__      =       [
             Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    ),
             """http://images.cocodataset.org/val2017/000000039769.jpg""",
         ]
         return image_classifier, examples

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any						,				A :       List[str]						,				A :       Dict    )			->			Union[str, Any]:






         """simple docstring"""
         a__      =       image_classifier("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )

         self.assertEqual(
             A						,				[
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
             ]						,				)

         import datasets

         a__      =       datasets.load_dataset("""hf-internal-testing/fixtures_image_utils"""						,				"""image"""						,				split="""test"""    )

         # Accepts URL + PIL.Image + lists
         a__      =       image_classifier(
             [
                 Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    ),
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 # RGBA
                 dataset[0]["""file"""],
                 # LA
                 dataset[1]["""file"""],
                 # L
                 dataset[2]["""file"""],
             ]    )
         self.assertEqual(
             A						,				[
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
             ]						,				)

     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]    )			->			Optional[Any]:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

     @require_tf
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			str:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A						,				framework="""tf"""    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			str:






         """simple docstring"""
         a__      =       PreTrainedTokenizer()

         # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
         a__      =       pipeline(
             """image-classification"""						,				model="""hf-internal-testing/tiny-random-vit"""						,				tokenizer=A    )

         self.assertIs(image_classifier.tokenizer						,				A    )






     @slow
     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			Dict:






         """simple docstring"""
         # Perceiver is not tested by `run_pipeline_test` properly.
         # That is because the type of feature_extractor and model preprocessor need to be kept
         # in sync, which is not the case in the current design
         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-conv"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.4_3_8_5, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.3_2_1, """label""": """tiger cat"""},
                 {"""score""": 0.0_5_0_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_1_3_7, """label""": """crib, cot"""},
                 {"""score""": 0.0_0_7, """label""": """radiator"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-fourier"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.5_6_5_8, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.1_3_0_9, """label""": """tiger cat"""},
                 {"""score""": 0.0_7_2_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_7_0_7, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_8_2, """label""": """computer keyboard, keypad"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-learned"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.3_0_2_2, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.2_3_6_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.1_8_5_6, """label""": """tiger cat"""},
                 {"""score""": 0.0_3_2_4, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_9_6, """label""": """quilt, comforter, comfort, puff"""},
             ]						,				)






