

"""simple docstring"""





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
							import jax
							import jaxlib

__UpperCamelCase  :      str							      =		get_logger()

__UpperCamelCase  :      Optional[dict]							      =		None







class 				SCREAMING_SNAKE_CASE					(		TensorFormatter[Mapping, "jax.Array", Mapping]       ):






					"""simple docstring"""



					def __init__(       self			:				Any   ,lowercase_			:				str=None   ,lowercase_			:				Union[str, Any]=None   ,**lowercase_			:				List[Any]		):
						super().__init__(features=lowercase_		)
						import jax
						from jaxlib.xla_client import Device

						if isinstance(lowercase_   ,lowercase_		):
							raise ValueError(
							    F'Expected {device} to be a `str` not {type(lowercase_		)}, as `jaxlib.xla_extension.Device` '
							    '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
							    '''the device with `str()` to get its string identifier that will be internally mapped '''
							    '''to the actual `jaxlib.xla_extension.Device`.'''		)
						lowerCAmelCase__	:						Optional[Any]  				=	device if isinstance(lowercase_   ,lowercase_		) else str(jax.devices()[0]		)
						# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
						# with `pickle` nor with `dill`, so we need to use a global variable instead
						global DEVICE_MAPPING
						if DEVICE_MAPPING is None:
							lowerCAmelCase__	:						Dict  				=	self._map_devices_to_str()
						if self.device not in list(DEVICE_MAPPING.keys()		):
							logger.warning(
							    F'Device with string identifier {self.device} not listed among the available '
							    F'devices: {list(DEVICE_MAPPING.keys()		)}, so falling back to the default '
							    F'device: {str(jax.devices()[0]		)}.'		)
							lowerCAmelCase__	:						List[str]  				=	str(jax.devices()[0]		)
						lowerCAmelCase__	:						Optional[int]  				=	jnp_array_kwargs







					@staticmethod
					def        __lowerCAmelCase (       ):
						import jax

						return {str(lowercase_		): device for device in jax.devices()}







					def        __lowerCAmelCase (       self			:				Optional[Any]   ,lowercase_			:				Optional[Any]		):
						import jax
						import jax.numpy as jnp

						if isinstance(lowercase_   ,lowercase_		) and column:
							if all(
							    isinstance(lowercase_   ,jax.Array		) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column		):
								return jnp.stack(lowercase_   ,axis=0		)
						return column







					def        __lowerCAmelCase (       self			:				int   ,lowercase_			:				str		):
						import jax
						import jax.numpy as jnp

						if isinstance(lowercase_   ,(str, bytes, type(lowercase_		))		):
							return value
						elif isinstance(lowercase_   ,(np.character, np.ndarray)		) and np.issubdtype(value.dtype   ,np.character		):
							return value.tolist()

						lowerCAmelCase__	:						List[Any]  				=	{}

						if isinstance(lowercase_   ,(np.number, np.ndarray)		) and np.issubdtype(value.dtype   ,np.integer		):
							# the default int precision depends on the jax config
							# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
							if jax.config.jax_enable_xaa:
								lowerCAmelCase__	:						int  				=	{'''dtype''': jnp.intaa}
							else:
								lowerCAmelCase__	:						Optional[Any]  				=	{'''dtype''': jnp.intaa}
						elif isinstance(lowercase_   ,(np.number, np.ndarray)		) and np.issubdtype(value.dtype   ,np.floating		):
							lowerCAmelCase__	:						List[Any]  				=	{'''dtype''': jnp.floataa}
						elif config.PIL_AVAILABLE and "PIL" in sys.modules:
							import PIL.Image

							if isinstance(lowercase_   ,PIL.Image.Image		):
								lowerCAmelCase__	:						Union[str, Any]  				=	np.asarray(lowercase_		)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
						global DEVICE_MAPPING
						if DEVICE_MAPPING is None:
							lowerCAmelCase__	:						int  				=	self._map_devices_to_str()

						with jax.default_device(DEVICE_MAPPING[self.device]		):
							# calling jnp.array on a np.ndarray does copy the data
							# see https://github.com/google/jax/issues/4486
							return jnp.array(lowercase_   ,**{**default_dtype, **self.jnp_array_kwargs}		)







					def        __lowerCAmelCase (       self			:				int   ,lowercase_			:				Tuple		):
						import jax

						# support for torch, tf, jax etc.
						if config.TORCH_AVAILABLE and "torch" in sys.modules:
							import torch

							if isinstance(lowercase_   ,torch.Tensor		):
								return self._tensorize(data_struct.detach().cpu().numpy()[()]		)
						if hasattr(lowercase_   ,'''__array__'''		) and not isinstance(lowercase_   ,jax.Array		):
							lowerCAmelCase__	:						Optional[int]  				=	data_struct.__array__()
						# support for nested types like struct of list of struct
						if isinstance(lowercase_   ,np.ndarray		):
							if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
								return self._consolidate([self.recursive_tensorize(lowercase_		) for substruct in data_struct]		)
						elif isinstance(lowercase_   ,(list, tuple)		):
							return self._consolidate([self.recursive_tensorize(lowercase_		) for substruct in data_struct]		)
						return self._tensorize(lowercase_		)







					def        __lowerCAmelCase (       self			:				Tuple   ,lowercase_			:				dict		):
						return map_nested(self._recursive_tensorize   ,lowercase_   ,map_list=lowercase_		)







					def        __lowerCAmelCase (       self			:				Union[str, Any]   ,lowercase_			:				pa.Table		):
						lowerCAmelCase__	:						Tuple  				=	self.numpy_arrow_extractor().extract_row(lowercase_		)
						lowerCAmelCase__	:						int  				=	self.python_features_decoder.decode_row(lowercase_		)
						return self.recursive_tensorize(lowercase_		)







					def        __lowerCAmelCase (       self			:				Union[str, Any]   ,lowercase_			:				pa.Table		):
						lowerCAmelCase__	:						Any  				=	self.numpy_arrow_extractor().extract_column(lowercase_		)
						lowerCAmelCase__	:						List[Any]  				=	self.python_features_decoder.decode_column(lowercase_   ,pa_table.column_names[0]		)
						lowerCAmelCase__	:						Optional[Any]  				=	self.recursive_tensorize(lowercase_		)
						lowerCAmelCase__	:						int  				=	self._consolidate(lowercase_		)
						return column







					def        __lowerCAmelCase (       self			:				Union[str, Any]   ,lowercase_			:				pa.Table		):
						lowerCAmelCase__	:						List[Any]  				=	self.numpy_arrow_extractor().extract_batch(lowercase_		)
						lowerCAmelCase__	:						Dict  				=	self.python_features_decoder.decode_batch(lowercase_		)
						lowerCAmelCase__	:						int  				=	self.recursive_tensorize(lowercase_		)
						for column_name in batch:
							lowerCAmelCase__	:						Tuple  				=	self._consolidate(batch[column_name]		)
						return batch







"""simple docstring"""





import webbrowser
from sys import argv
from urllib.parse import parse_qs, quote

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

if __name__ == "__main__":
							__UpperCamelCase  :      Tuple							      =		'''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''Search: ''')))

							print('''Googling.....''')

							__UpperCamelCase  :      Optional[int]							      =		F'''https://www.google.com/search?q={query}&num=100'''

							__UpperCamelCase  :      Optional[Any]							      =		requests.get(
							    url,
							    headers={'''User-Agent''': str(UserAgent().random)},
							)

							try:
														__UpperCamelCase  :      Union[str, Any]							      =		(
														    BeautifulSoup(res.text, '''html.parser''')
														    .find('''div''', attrs={'''class''': '''yuRUbf'''})
														    .find('''a''')
														    .get('''href''')
														)

							except AttributeError:
														__UpperCamelCase  :      str							      =		parse_qs(
														    BeautifulSoup(res.text, '''html.parser''')
														    .find('''div''', attrs={'''class''': '''kCrYT'''})
														    .find('''a''')
														    .get('''href''')
														)['''url'''][0]

							webbrowser.open(link)




