


'''simple docstring'''






import os
from typing import Optional

import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 =""
       UpperCAmelCase		 =(
           None  # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
       )
       UpperCAmelCase		 =None  # compression type in fsspec. ex: "gzip"
       UpperCAmelCase		 =None  # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz






       def __init__(     self    ,				snake_case = ""    ,				snake_case = None    ,				snake_case = None    ,				**snake_case)		->    int:




          '''simple docstring'''
          super().__init__(self    ,				**snake_case)
          # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
          _UpperCAmelCase  :  Union[str, Any]				       =fsspec.open(
              snake_case    ,				mode='rb'    ,				protocol=snake_case    ,				compression=self.compression    ,				client_kwargs={
                  'requote_redirect_url': False,  # see https://github.com/huggingface/datasets/pull/5459
                  'trust_env': True,  # Enable reading proxy env variables.
                  **(target_options or {}).pop('client_kwargs'    ,				{}),  # To avoid issues if it was already passed.
              }    ,				**(target_options or {})    ,				)
          _UpperCAmelCase  :  List[str]				       =os.path.basename(self.file.path.split('::')[0])
          _UpperCAmelCase  :  Tuple				       =(
              self.compressed_name[: self.compressed_name.rindex('.')]
              if '.' in self.compressed_name
              else self.compressed_name
          )
          _UpperCAmelCase  :  List[str]				       =None






       @classmethod
       def      lowerCAmelCase						(     cls    ,				snake_case)		->    Optional[int]:




          '''simple docstring'''
          # compressed file paths are always relative to the archive root
          return super()._strip_protocol(snake_case).lstrip('/')






       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          if self.dir_cache is None:
             _UpperCAmelCase  :  Union[str, Any]				       ={**self.file.fs.info(self.file.path), 'name': self.uncompressed_name}
             _UpperCAmelCase  :  int				       ={f['name']: f}






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




          '''simple docstring'''
          return self.file.open().read()






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case = "rb"    ,				snake_case=None    ,				snake_case=True    ,				snake_case=None    ,				**snake_case    ,				)		->    Any:




          '''simple docstring'''
          _UpperCAmelCase  :  Tuple				       =self._strip_protocol(snake_case)
          if mode != "rb":
             raise ValueError(f"Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'")
          return self.file.open()






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 ="bz2"
       UpperCAmelCase		 ="bz2"
       UpperCAmelCase		 =".bz2"






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 ="gzip"
       UpperCAmelCase		 ="gzip"
       UpperCAmelCase		 =".gz"






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 ="lz4"
       UpperCAmelCase		 ="lz4"
       UpperCAmelCase		 =".lz4"






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 ="xz"
       UpperCAmelCase		 ="xz"
       UpperCAmelCase		 =".xz"






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 ="zstd"
       UpperCAmelCase		 ="zstd"
       UpperCAmelCase		 =".zst"






       def __init__(     self    ,				snake_case    ,				snake_case = "rb"    ,				snake_case = None    ,				snake_case = None    ,				snake_case = DEFAULT_BLOCK_SIZE    ,				**snake_case    ,				)		->    Tuple:




          '''simple docstring'''
          super().__init__(
              fo=snake_case    ,				mode=snake_case    ,				target_protocol=snake_case    ,				target_options=snake_case    ,				block_size=snake_case    ,				**snake_case    ,				)
          # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
          #
          # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
          #     out.close = close
          # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
          #
          # see https://github.com/intake/filesystem_spec/issues/725
          _UpperCAmelCase  :  Any				       =self.file.__enter__






          class    __magic_name__				:






                 def __init__(     self    ,				snake_case)		->    Any:




                    '''simple docstring'''
                    _UpperCAmelCase  :  Any				       =file_






                 def __enter__(     self)		->    Optional[int]:




                    '''simple docstring'''
                    self._file.__enter__()
                    return self






                 def __exit__(     self    ,				*snake_case    ,				**snake_case)		->    Any:




                    '''simple docstring'''
                    self._file.__exit__(*snake_case    ,				**snake_case)






                 def __iter__(     self)		->    Dict:




                    '''simple docstring'''
                    return iter(self._file)






                 def      lowerCAmelCase						(     self)		->    Tuple:




                    '''simple docstring'''
                    return next(self._file)






                 def __getattr__(     self    ,				snake_case)		->    List[Any]:




                    '''simple docstring'''
                    return getattr(self._file    ,				snake_case)

          def fixed_enter(*snake_case    ,				**snake_case):
             return WrappedFile(_enter(*snake_case    ,				**snake_case))

          _UpperCAmelCase  :  Any				       =fixed_enter





'''simple docstring'''






from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

lowercase				=logging.get_logger(__name__)






@add_end_docstrings(lowerCAmelCase							)
class    __magic_name__				(						lowerCAmelCase							):






       def __init__(     self    ,				*snake_case    ,				**snake_case)		->    Dict:




          '''simple docstring'''
          super().__init__(*snake_case    ,				**snake_case)
          requires_backends(self    ,				'vision')
          self.check_model_type(
              TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
              if self.framework == 'tf'
              else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING)






       def      lowerCAmelCase						(     self    ,				snake_case=None)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       ={}
          if top_k is not None:
             _UpperCAmelCase  :  Optional[int]				       =top_k
          return {}, {}, postprocess_params






       def __call__(     self    ,				snake_case    ,				**snake_case)		->    List[str]:




          '''simple docstring'''
          return super().__call__(snake_case    ,				**snake_case)






       def      lowerCAmelCase						(     self    ,				snake_case)		->    List[str]:




          '''simple docstring'''
          _UpperCAmelCase  :  int				       =load_image(snake_case)
          _UpperCAmelCase  :  Tuple				       =self.image_processor(images=snake_case    ,				return_tensors=self.framework)
          return model_inputs






       def      lowerCAmelCase						(     self    ,				snake_case)		->    Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =self.model(**snake_case)
          return model_outputs






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=5)		->    Any:




          '''simple docstring'''
          if top_k > self.model.config.num_labels:
             _UpperCAmelCase  :  Optional[Any]				       =self.model.config.num_labels

          if self.framework == "pt":
             _UpperCAmelCase  :  List[Any]				       =model_outputs.logits.softmax(-1)[0]
             _UpperCAmelCase       ,			_UpperCAmelCase  :  Optional[Any]				       =probs.topk(snake_case)
          elif self.framework == "tf":
             _UpperCAmelCase  :  int				       =stable_softmax(model_outputs.logits    ,				axis=-1)[0]
             _UpperCAmelCase  :  List[Any]				       =tf.math.top_k(snake_case    ,				k=snake_case)
             _UpperCAmelCase       ,			_UpperCAmelCase  :  List[str]				       =topk.values.numpy(), topk.indices.numpy()
          else:
             raise ValueError(f"Unsupported framework: {self.framework}")

          _UpperCAmelCase  :  int				       =scores.tolist()
          _UpperCAmelCase  :  Tuple				       =ids.tolist()
          return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case    ,				snake_case)]

