


import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


__lowerCamelCase   	=  1000


class 	a__						:

       def __init__( self   :  int   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  Optional[Any]=1.2   ,				lowerCamelCase_   :  Any="g"   ,				lowerCamelCase_   :  int=0.5   ,				lowerCamelCase_   :  Optional[Any]="-"   ,				lowerCamelCase_   :  Union[str, Any]="test_out.jpg"   ,				lowerCamelCase_   :  List[str]=True   ,				lowerCamelCase_   :  int=False   ,				lowerCamelCase_   :  Dict=None   ,				lowerCamelCase_   :  Any=None   ,				lowerCamelCase_   :  Union[str, Any]=0.7   ,				):
            if isinstance(lowerCamelCase_   ,				torch.Tensor     ):
                 a_     :  int				      =     img.numpy().astype("""np.uint8"""     )
            if isinstance(lowerCamelCase_   ,				lowerCamelCase_     ):
                 a_     :  str				      =     img_tensorize(lowerCamelCase_     )
            assert isinstance(lowerCamelCase_   ,				np.ndarray     )

            a_      ,      a_     :  Optional[Any]				      =     img.shape[1], img.shape[0]
            a_     :  str				      =     mplfigure.Figure(frameon=lowerCamelCase_     )
            a_     :  Dict				      =     fig.get_dpi()
            a_     :  Dict				      =     (width * scale + 1E-2) / dpi
            a_     :  List[str]				      =     (height * scale + 1E-2) / dpi
            fig.set_size_inches(lowerCamelCase_   ,				lowerCamelCase_     )
            a_     :  Any				      =     fig.add_axes([0.0, 0.0, 1.0, 1.0]     )
            ax.axis("""off"""     )
            ax.set_xlim(0.0   ,				lowerCamelCase_     )
            ax.set_ylim(lowerCamelCase_     )

            a_     :  Optional[Any]				      =     saveas
            a_     :  List[Any]				      =     rgb
            a_     :  List[str]				      =     pynb
            a_     :  Union[str, Any]				      =     img
            a_     :  Union[str, Any]				      =     edgecolor
            a_     :  Optional[Any]				      =     0.5
            a_     :  Tuple				      =     linestyle
            a_     :  List[str]				      =     int(np.sqrt(min(lowerCamelCase_   ,				lowerCamelCase_     )     ) * scale // 3     )
            a_     :  Any				      =     width
            a_     :  List[Any]				      =     height
            a_     :  int				      =     scale
            a_     :  List[Any]				      =     fig
            a_     :  List[Any]				      =     ax
            a_     :  int				      =     pad
            a_     :  str				      =     idaobj
            a_     :  Optional[int]				      =     idaattr
            a_     :  Dict				      =     FigureCanvasAgg(lowerCamelCase_     )

       def     UpperCAmelCase( self   :  List[str]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[Any]=None     ):
            if color is None:
                 a_     :  Union[str, Any]				      =     self.edgecolor
            ((a_)      ,      (a_)      ,      (a_)      ,      (a_))     :  Any				      =     box
            a_     :  Optional[int]				      =     xa - xa
            a_     :  Optional[int]				      =     ya - ya
            self.ax.add_patch(
                mpl.patches.Rectangle(
                    (xa, ya)   ,				lowerCamelCase_   ,				lowerCamelCase_   ,				fill=lowerCamelCase_   ,				edgecolor=lowerCamelCase_   ,				linewidth=self.font_size // 3   ,				alpha=self.alpha   ,				linestyle=self.linestyle   ,				)     )

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  Dict   ,				lowerCamelCase_   :  Any=None   ,				lowerCamelCase_   :  Tuple=None   ,				lowerCamelCase_   :  int=None   ,				lowerCamelCase_   :  Optional[int]=None     ):
            if len(boxes.shape     ) > 2:
                 a_     :  Optional[Any]				      =     boxes[0]
            if len(obj_ids.shape     ) > 1:
                 a_     :  int				      =     obj_ids[0]
            if len(obj_scores.shape     ) > 1:
                 a_     :  Dict				      =     obj_scores[0]
            if len(attr_ids.shape     ) > 1:
                 a_     :  Union[str, Any]				      =     attr_ids[0]
            if len(attr_scores.shape     ) > 1:
                 a_     :  Any				      =     attr_scores[0]
            if isinstance(lowerCamelCase_   ,				torch.Tensor     ):
                 a_     :  Union[str, Any]				      =     boxes.numpy()
            if isinstance(lowerCamelCase_   ,				lowerCamelCase_     ):
                 a_     :  Optional[int]				      =     np.array(lowerCamelCase_     )
            assert isinstance(lowerCamelCase_   ,				np.ndarray     )
            a_     :  Tuple				      =     np.prod(boxes[:, 2:] - boxes[:, :2]   ,				axis=1     )
            a_     :  Any				      =     np.argsort(-areas     ).tolist()
            a_     :  Tuple				      =     boxes[sorted_idxs] if boxes is not None else None
            a_     :  str				      =     obj_ids[sorted_idxs] if obj_ids is not None else None
            a_     :  Optional[Any]				      =     obj_scores[sorted_idxs] if obj_scores is not None else None
            a_     :  Optional[Any]				      =     attr_ids[sorted_idxs] if attr_ids is not None else None
            a_     :  int				      =     attr_scores[sorted_idxs] if attr_scores is not None else None

            a_     :  List[Any]				      =     [self._random_color(maximum=1     ) for _ in range(len(lowerCamelCase_     )     )]
            a_     :  int				      =     [assigned_colors[idx] for idx in sorted_idxs]
            if obj_ids is not None:
                 a_     :  Optional[Any]				      =     self._create_text_labels_attr(lowerCamelCase_   ,				lowerCamelCase_   ,				lowerCamelCase_   ,				lowerCamelCase_     )
                 for i in range(len(lowerCamelCase_     )     ):
                      a_     :  int				      =     assigned_colors[i]
                      self.add_box(boxes[i]   ,				lowerCamelCase_     )
                      self.draw_labels(labels[i]   ,				boxes[i]   ,				lowerCamelCase_     )

       def     UpperCAmelCase( self   :  Union[str, Any]   ,				lowerCamelCase_   :  Dict   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  List[str]     ):
            a_      ,      a_      ,      a_      ,      a_     :  Union[str, Any]				      =     box
            a_     :  List[Any]				      =     (xa, ya)
            a_     :  Optional[Any]				      =     (ya - ya) * (xa - xa)
            a_     :  Optional[int]				      =     _SMALL_OBJ * self.scale
            if instance_area < small or ya - ya < 4_0 * self.scale:
                 if ya >= self.height - 5:
                      a_     :  Optional[int]				      =     (xa, ya)
                 else:
                      a_     :  Tuple				      =     (xa, ya)

            a_     :  str				      =     (ya - ya) / np.sqrt(self.height * self.width     )
            a_     :  Any				      =     self._change_color_brightness(lowerCamelCase_   ,				brightness_factor=0.7     )
            a_     :  Dict				      =     np.clip((height_ratio - 0.0_2) / 0.0_8 + 1   ,				1.2   ,				2     )
            font_size *= 0.7_5 * self.font_size

            self.draw_text(
                text=lowerCamelCase_   ,				position=lowerCamelCase_   ,				color=lowerCamelCase_   ,				)

       def     UpperCAmelCase( self   :  str   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  Any   ,				lowerCamelCase_   :  Any="g"   ,				lowerCamelCase_   :  List[str]="left"   ,				):
            a_     :  str				      =     0
            a_     :  Any				      =     self.font_size
            a_     :  List[Any]				      =     np.maximum(list(mplc.to_rgb(lowerCamelCase_     )     )   ,				0.2     )
            a_     :  Optional[Any]				      =     max(0.8   ,				np.max(lowerCamelCase_     )     )
            a_     :  int				      =     {
                """facecolor""": """black""",
                """alpha""": self.alpha,
                """pad""": self.pad,
                """edgecolor""": """none""",
            }
            a_      ,      a_     :  int				      =     position
            self.ax.text(
                lowerCamelCase_   ,				lowerCamelCase_   ,				lowerCamelCase_   ,				size=font_size * self.scale   ,				family="""sans-serif"""   ,				bbox=lowerCamelCase_   ,				verticalalignment="""top"""   ,				horizontalalignment=lowerCamelCase_   ,				color=lowerCamelCase_   ,				zorder=1_0   ,				rotation=lowerCamelCase_   ,				)

       def     UpperCAmelCase( self   :  int   ,				lowerCamelCase_   :  Tuple=None     ):
            if saveas is None:
                 a_     :  Dict				      =     self.saveas
            if saveas.lower().endswith(""".jpg"""     ) or saveas.lower().endswith(""".png"""     ):
                 cva.imwrite(
                     lowerCamelCase_   ,				self._get_buffer()[:, :, ::-1]   ,				)
            else:
                 self.fig.savefig(lowerCamelCase_     )

       def     UpperCAmelCase( self   :  str   ,				lowerCamelCase_   :  Dict   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  int   ,				lowerCamelCase_   :  List[str]     ):
            a_     :  List[Any]				      =     [self.idaobj[i] for i in classes]
            a_     :  Union[str, Any]				      =     [self.idaattr[i] for i in attr_classes]
            a_     :  Optional[Any]				      =     [
                F'''{label} {score:.2f} {attr} {attr_score:.2f}'''
                for label, score, attr, attr_score in zip(lowerCamelCase_   ,				lowerCamelCase_   ,				lowerCamelCase_   ,				lowerCamelCase_     )
            ]
            return labels

       def     UpperCAmelCase( self   :  Optional[int]   ,				lowerCamelCase_   :  Union[str, Any]   ,				lowerCamelCase_   :  Union[str, Any]     ):
            a_     :  int				      =     [self.idaobj[i] for i in classes]
            if scores is not None:
                 if labels is None:
                      a_     :  Any				      =     ["""{:.0f}%""".format(s * 1_0_0     ) for s in scores]
                 else:
                      a_     :  Optional[Any]				      =     ["""{} {:.0f}%""".format(lowerCamelCase_   ,				s * 1_0_0     ) for li, s in zip(lowerCamelCase_   ,				lowerCamelCase_     )]
            return labels

       def     UpperCAmelCase( self   :  List[Any]   ,				lowerCamelCase_   :  Union[str, Any]=2_5_5     ):
            a_     :  str				      =     np.random.randint(0   ,				len(_COLORS     )     )
            a_     :  Union[str, Any]				      =     _COLORS[idx] * maximum
            if not self.rgb:
                 a_     :  Dict				      =     ret[::-1]
            return ret

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            if not self.pynb:
                 a_      ,      a_     :  int				      =     self.canvas.print_to_buffer()
                 if (width, height) != (self.width, self.height):
                      a_     :  str				      =     cva.resize(self.img   ,				(width, height)     )
                 else:
                      a_     :  Union[str, Any]				      =     self.img
            else:
                 a_     :  Union[str, Any]				      =     io.BytesIO()  # works for cairo backend
                 self.canvas.print_rgba(lowerCamelCase_     )
                 a_      ,      a_     :  str				      =     self.width, self.height
                 a_     :  Any				      =     buf.getvalue()
                 a_     :  Dict				      =     self.img

            a_     :  Tuple				      =     np.frombuffer(lowerCamelCase_   ,				dtype="""uint8"""     )
            a_     :  Union[str, Any]				      =     buffer.reshape(lowerCamelCase_   ,				lowerCamelCase_   ,				4     )
            a_      ,      a_     :  List[Any]				      =     np.split(lowerCamelCase_   ,				[3]   ,				axis=2     )

            try:
                 import numexpr as ne  # fuse them with numexpr

                 a_     :  Dict				      =     ne.evaluate("""img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"""     )
            except ImportError:
                 a_     :  List[str]				      =     alpha.astype("""float32"""     ) / 2_5_5.0
                 a_     :  Union[str, Any]				      =     img * (1 - alpha) + rgb * alpha

            return visualized_image.astype("""uint8"""     )

       def     UpperCAmelCase( self   :  List[Any]   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  int     ):
            assert brightness_factor >= -1.0 and brightness_factor <= 1.0
            a_     :  Optional[int]				      =     mplc.to_rgb(lowerCamelCase_     )
            a_     :  str				      =     colorsys.rgb_to_hls(*mplc.to_rgb(lowerCamelCase_     )     )
            a_     :  Union[str, Any]				      =     polygon_color[1] + (brightness_factor * polygon_color[1])
            a_     :  List[Any]				      =     0.0 if modified_lightness < 0.0 else modified_lightness
            a_     :  str				      =     1.0 if modified_lightness > 1.0 else modified_lightness
            a_     :  Dict				      =     colorsys.hls_to_rgb(polygon_color[0]   ,				lowerCamelCase_   ,				polygon_color[2]     )
            return modified_color

__lowerCamelCase   	=  (
    np.array(
        [
            0.000,
            0.447,
            0.741,
            0.850,
            0.325,
            0.098,
            0.929,
            0.694,
            0.125,
            0.494,
            0.184,
            0.556,
            0.466,
            0.674,
            0.188,
            0.301,
            0.745,
            0.933,
            0.635,
            0.078,
            0.184,
            0.300,
            0.300,
            0.300,
            0.600,
            0.600,
            0.600,
            1.000,
            0.000,
            0.000,
            1.000,
            0.500,
            0.000,
            0.749,
            0.749,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.333,
            0.333,
            0.000,
            0.333,
            0.667,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            0.333,
            0.000,
            0.667,
            0.667,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            1.000,
            0.000,
            0.000,
            0.333,
            0.500,
            0.000,
            0.667,
            0.500,
            0.000,
            1.000,
            0.500,
            0.333,
            0.000,
            0.500,
            0.333,
            0.333,
            0.500,
            0.333,
            0.667,
            0.500,
            0.333,
            1.000,
            0.500,
            0.667,
            0.000,
            0.500,
            0.667,
            0.333,
            0.500,
            0.667,
            0.667,
            0.500,
            0.667,
            1.000,
            0.500,
            1.000,
            0.000,
            0.500,
            1.000,
            0.333,
            0.500,
            1.000,
            0.667,
            0.500,
            1.000,
            1.000,
            0.500,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.333,
            0.333,
            1.000,
            0.333,
            0.667,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.667,
            0.333,
            1.000,
            0.667,
            0.667,
            1.000,
            0.667,
            1.000,
            1.000,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            1.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.143,
            0.143,
            0.143,
            0.857,
            0.857,
            0.857,
            1.000,
            1.000,
            1.000,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)




'''simple docstring'''


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


snake_case__	:     int      =    datasets.utils.logging.get_logger(__name__)






@dataclass
class 	__SCREAMING_SNAKE_CASE		(			datasets.BuilderConfig			):







  '''simple docstring'''






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


  def _UpperCamelCase	(					self		):




       '''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 _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_ = None ,						):




       '''simple docstring'''

       UpperCAmelCase_				:  List[Any]  = 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
       UpperCAmelCase_				:  str  = config_kwargs['sql']
       if not isinstance(snake_case_ ,						snake_case_		):
            if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                 import sqlalchemy

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

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






  @property
  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  List[Any]  = {
           '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 	__SCREAMING_SNAKE_CASE		(			datasets.ArrowBasedBuilder			):







  '''simple docstring'''






  lowerCamelCase_						:Any		       =						SqlConfig


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       return datasets.DatasetInfo(features=self.config.features		)


  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

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


  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

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






  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[Any]  = self.config.chunksize
       UpperCAmelCase_				:  Optional[Any]  = pd.read_sql(
           self.config.sql ,						self.config.con ,						chunksize=snake_case_ ,						**self.config.pd_read_sql_kwargs		)
       UpperCAmelCase_				:  int  = [sql_reader] if chunksize is None else sql_reader
       for chunk_idx, df in enumerate(snake_case_		):
            UpperCAmelCase_				:  Optional[Any]  = pa.Table.from_pandas(snake_case_		)
            yield chunk_idx, self._cast_table(snake_case_		)






