

import subprocess
from typing import Union

import numpy as np
import requests

from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


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

UpperCamelCase__		   =    logging.get_logger(__name__)







def 	lowerCamelCase__			(   __A						:bytes  ,__A						:int		):


       """simple docstring"""




       __snake_case					  =       F'{sampling_rate}'
       __snake_case					  =       """1"""
       __snake_case					  =       """f32le"""
       __snake_case					  =       [
           """ffmpeg""",
           """-i""",
           """pipe:0""",
           """-ac""",
           ac,
           """-ar""",
           ar,
           """-f""",
           format_for_conversion,
           """-hide_banner""",
           """-loglevel""",
           """quiet""",
           """pipe:1""",
       ]

       try:
              __snake_case					  =       subprocess.Popen(__A  ,stdin=subprocess.PIPE  ,stdout=subprocess.PIPE		)
       except FileNotFoundError:
              raise ValueError("""ffmpeg was not found but is required to load audio files from filename"""		)
       __snake_case					  =       ffmpeg_process.communicate(__A		)
       __snake_case					  =       output_stream[0]

       __snake_case					  =       np.frombuffer(__A  ,np.floataa		)
       if audio.shape[0] == 0:
              raise ValueError("""Malformed soundfile"""		)
       return audio




@add_end_docstrings(snake_case__     )
class 						__snake_case						(							snake_case__     ):
       """simple docstring"""







       def __init__(		self			,   *_UpperCamelCase			,   **_UpperCamelCase      )			->       Optional[Any]:






              """simple docstring"""


              __snake_case					  =       5
              super().__init__(*_UpperCamelCase			,   **_UpperCamelCase      )

              if self.framework != "pt":
                     raise ValueError(F'The {self.__class__} is only available in PyTorch.'      )

              self.check_model_type(_UpperCamelCase      )


       def __call__(		self			,   _UpperCamelCase			,   **_UpperCamelCase			,   )			->       Tuple:






              """simple docstring"""


              return super().__call__(_UpperCamelCase			,   **_UpperCamelCase      )


       def  a		(		self			,   _UpperCamelCase=None			,   **_UpperCamelCase      )			->       Dict:






              """simple docstring"""


              __snake_case					  =       {}
              if top_k is not None:
                     if top_k > self.model.config.num_labels:
                            __snake_case					  =       self.model.config.num_labels
                     __snake_case					  =       top_k
              return {}, {}, postprocess_params


       def  a		(		self			,   _UpperCamelCase      )			->       Any:






              """simple docstring"""


              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     if inputs.startswith("""http://"""      ) or inputs.startswith("""https://"""      ):
                            # We need to actually check for a real protocol, otherwise it's impossible to use a local file
                            # like http_huggingface_co.png
                            __snake_case					  =       requests.get(_UpperCamelCase      ).content
                     else:
                            with open(_UpperCamelCase			,   """rb"""      ) as f:
                                   __snake_case					  =       f.read()

              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     __snake_case					  =       ffmpeg_read(_UpperCamelCase			,   self.feature_extractor.sampling_rate      )

              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     # Accepting `"array"` which is the key defined in `datasets` for
                     # better integration
                     if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
                            raise ValueError(
                                """When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a """
                                """\"raw\" key containing the numpy array representing the audio and a \"sampling_rate\" key, """
                                """containing the sampling_rate associated with that array"""      )

                     __snake_case					  =       inputs.pop("""raw"""			,   _UpperCamelCase      )
                     if _inputs is None:
                            # Remove path which will not be used from `datasets`.
                            inputs.pop("""path"""			,   _UpperCamelCase      )
                            __snake_case					  =       inputs.pop("""array"""			,   _UpperCamelCase      )
                     __snake_case					  =       inputs.pop("""sampling_rate"""      )
                     __snake_case					  =       _inputs
                     if in_sampling_rate != self.feature_extractor.sampling_rate:
                            import torch

                            if is_torchaudio_available():
                                   from torchaudio import functional as F
                            else:
                                   raise ImportError(
                                       """torchaudio is required to resample audio samples in AudioClassificationPipeline. """
                                       """The torchaudio package can be installed through: `pip install torchaudio`."""      )

                            __snake_case					  =       F.resample(
                                torch.from_numpy(_UpperCamelCase      )			,   _UpperCamelCase			,   self.feature_extractor.sampling_rate      ).numpy()

              if not isinstance(_UpperCamelCase			,   np.ndarray      ):
                     raise ValueError("""We expect a numpy ndarray as input"""      )
              if len(inputs.shape      ) != 1:
                     raise ValueError("""We expect a single channel audio input for AudioClassificationPipeline"""      )

              __snake_case					  =       self.feature_extractor(
                  _UpperCamelCase			,   sampling_rate=self.feature_extractor.sampling_rate			,   return_tensors="""pt"""      )
              return processed


       def  a		(		self			,   _UpperCamelCase      )			->       Any:






              """simple docstring"""


              __snake_case					  =       self.model(**_UpperCamelCase      )
              return model_outputs






       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase=5      )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       model_outputs.logits[0].softmax(-1      )
              __snake_case  ,						__snake_case					  =       probs.topk(_UpperCamelCase      )

              __snake_case					  =       scores.tolist()
              __snake_case					  =       ids.tolist()

              __snake_case					  =       [{"""score""": score, """label""": self.model.config.idalabel[_id]} for score, _id in zip(_UpperCamelCase			,   _UpperCamelCase      )]

              return labels




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


UpperCamelCase__		   =    1000

class 						__snake_case						:
       """simple docstring"""







       def __init__(		self			,   _UpperCamelCase			,   _UpperCamelCase=1.2			,   _UpperCamelCase="g"			,   _UpperCamelCase=0.5			,   _UpperCamelCase="-"			,   _UpperCamelCase="test_out.jpg"			,   _UpperCamelCase=True			,   _UpperCamelCase=False			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=0.7			,   )			->       Union[str, Any]:






              """simple docstring"""


              if isinstance(_UpperCamelCase			,   torch.Tensor      ):
                     __snake_case					  =       img.numpy().astype("""np.uint8"""      )
              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     __snake_case					  =       img_tensorize(_UpperCamelCase      )
              assert isinstance(_UpperCamelCase			,   np.ndarray      )

              __snake_case  ,						__snake_case					  =       img.shape[1], img.shape[0]
              __snake_case					  =       mplfigure.Figure(frameon=_UpperCamelCase      )
              __snake_case					  =       fig.get_dpi()
              __snake_case					  =       (width * scale + 1E-2) / dpi
              __snake_case					  =       (height * scale + 1E-2) / dpi
              fig.set_size_inches(_UpperCamelCase			,   _UpperCamelCase      )
              __snake_case					  =       fig.add_axes([0.0, 0.0, 1.0, 1.0]      )
              ax.axis("""off"""      )
              ax.set_xlim(0.0			,   _UpperCamelCase      )
              ax.set_ylim(_UpperCamelCase      )

              __snake_case					  =       saveas
              __snake_case					  =       rgb
              __snake_case					  =       pynb
              __snake_case					  =       img
              __snake_case					  =       edgecolor
              __snake_case					  =       0.5
              __snake_case					  =       linestyle
              __snake_case					  =       int(np.sqrt(min(_UpperCamelCase			,   _UpperCamelCase      )      ) * scale // 3      )
              __snake_case					  =       width
              __snake_case					  =       height
              __snake_case					  =       scale
              __snake_case					  =       fig
              __snake_case					  =       ax
              __snake_case					  =       pad
              __snake_case					  =       idaobj
              __snake_case					  =       idaattr
              __snake_case					  =       FigureCanvasAgg(_UpperCamelCase      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase=None      )			->       int:






              """simple docstring"""


              if color is None:
                     __snake_case					  =       self.edgecolor
              ((__snake_case)  ,						(__snake_case)  ,						(__snake_case)  ,						(__snake_case))					  =       box
              __snake_case					  =       xa - xa
              __snake_case					  =       ya - ya
              self.ax.add_patch(
                  mpl.patches.Rectangle(
                      (xa, ya)			,   _UpperCamelCase			,   _UpperCamelCase			,   fill=_UpperCamelCase			,   edgecolor=_UpperCamelCase			,   linewidth=self.font_size // 3			,   alpha=self.alpha			,   linestyle=self.linestyle			,   )      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=None      )			->       List[str]:






              """simple docstring"""


              if len(boxes.shape      ) > 2:
                     __snake_case					  =       boxes[0]
              if len(obj_ids.shape      ) > 1:
                     __snake_case					  =       obj_ids[0]
              if len(obj_scores.shape      ) > 1:
                     __snake_case					  =       obj_scores[0]
              if len(attr_ids.shape      ) > 1:
                     __snake_case					  =       attr_ids[0]
              if len(attr_scores.shape      ) > 1:
                     __snake_case					  =       attr_scores[0]
              if isinstance(_UpperCamelCase			,   torch.Tensor      ):
                     __snake_case					  =       boxes.numpy()
              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     __snake_case					  =       np.array(_UpperCamelCase      )
              assert isinstance(_UpperCamelCase			,   np.ndarray      )
              __snake_case					  =       np.prod(boxes[:, 2:] - boxes[:, :2]			,   axis=1      )
              __snake_case					  =       np.argsort(-areas      ).tolist()
              __snake_case					  =       boxes[sorted_idxs] if boxes is not None else None
              __snake_case					  =       obj_ids[sorted_idxs] if obj_ids is not None else None
              __snake_case					  =       obj_scores[sorted_idxs] if obj_scores is not None else None
              __snake_case					  =       attr_ids[sorted_idxs] if attr_ids is not None else None
              __snake_case					  =       attr_scores[sorted_idxs] if attr_scores is not None else None

              __snake_case					  =       [self._random_color(maximum=1      ) for _ in range(len(_UpperCamelCase      )      )]
              __snake_case					  =       [assigned_colors[idx] for idx in sorted_idxs]
              if obj_ids is not None:
                     __snake_case					  =       self._create_text_labels_attr(_UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )
                     for i in range(len(_UpperCamelCase      )      ):
                            __snake_case					  =       assigned_colors[i]
                            self.add_box(boxes[i]			,   _UpperCamelCase      )
                            self.draw_labels(labels[i]			,   boxes[i]			,   _UpperCamelCase      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )			->       Optional[Any]:






              """simple docstring"""


              __snake_case  ,						__snake_case  ,						__snake_case  ,						__snake_case					  =       box
              __snake_case					  =       (xa, ya)
              __snake_case					  =       (ya - ya) * (xa - xa)
              __snake_case					  =       _SMALL_OBJ * self.scale
              if instance_area < small or ya - ya < 40 * self.scale:
                     if ya >= self.height - 5:
                            __snake_case					  =       (xa, ya)
                     else:
                            __snake_case					  =       (xa, ya)

              __snake_case					  =       (ya - ya) / np.sqrt(self.height * self.width      )
              __snake_case					  =       self._change_color_brightness(_UpperCamelCase			,   brightness_factor=0.7      )
              __snake_case					  =       np.clip((height_ratio - 0.02) / 0.08 + 1			,   1.2			,   2      )
              font_size *= 0.75 * self.font_size

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


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase="g"			,   _UpperCamelCase="left"			,   )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       0
              __snake_case					  =       self.font_size
              __snake_case					  =       np.maximum(list(mplc.to_rgb(_UpperCamelCase      )      )			,   0.2      )
              __snake_case					  =       max(0.8			,   np.max(_UpperCamelCase      )      )
              __snake_case					  =       {
                  """facecolor""": """black""",
                  """alpha""": self.alpha,
                  """pad""": self.pad,
                  """edgecolor""": """none""",
              }
              __snake_case  ,						__snake_case					  =       position
              self.ax.text(
                  _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   size=font_size * self.scale			,   family="""sans-serif"""			,   bbox=_UpperCamelCase			,   verticalalignment="""top"""			,   horizontalalignment=_UpperCamelCase			,   color=_UpperCamelCase			,   zorder=10			,   rotation=_UpperCamelCase			,   )


       def  a		(		self			,   _UpperCamelCase=None      )			->       str:






              """simple docstring"""


              if saveas is None:
                     __snake_case					  =       self.saveas
              if saveas.lower().endswith(""".jpg"""      ) or saveas.lower().endswith(""".png"""      ):
                     cva.imwrite(
                         _UpperCamelCase			,   self._get_buffer()[:, :, ::-1]			,   )
              else:
                     self.fig.savefig(_UpperCamelCase      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       [self.idaobj[i] for i in classes]
              __snake_case					  =       [self.idaattr[i] for i in attr_classes]
              __snake_case					  =       [
                  F'{label} {score:.2f} {attr} {attr_score:.2f}'
                  for label, score, attr, attr_score in zip(_UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )
              ]
              return labels


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






              """simple docstring"""


              __snake_case					  =       [self.idaobj[i] for i in classes]
              if scores is not None:
                     if labels is None:
                            __snake_case					  =       ["""{:.0f}%""".format(s * 1_00      ) for s in scores]
                     else:
                            __snake_case					  =       ["""{} {:.0f}%""".format(_UpperCamelCase			,   s * 1_00      ) for li, s in zip(_UpperCamelCase			,   _UpperCamelCase      )]
              return labels


       def  a		(		self			,   _UpperCamelCase=2_55      )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       np.random.randint(0			,   len(_COLORS      )      )
              __snake_case					  =       _COLORS[idx] * maximum
              if not self.rgb:
                     __snake_case					  =       ret[::-1]
              return ret


       def  a		(		self      )			->       Optional[Any]:






              """simple docstring"""


              if not self.pynb:
                     __snake_case  ,						__snake_case					  =       self.canvas.print_to_buffer()
                     if (width, height) != (self.width, self.height):
                            __snake_case					  =       cva.resize(self.img			,   (width, height)      )
                     else:
                            __snake_case					  =       self.img
              else:
                     __snake_case					  =       io.BytesIO()  # works for cairo backend
                     self.canvas.print_rgba(_UpperCamelCase      )
                     __snake_case  ,						__snake_case					  =       self.width, self.height
                     __snake_case					  =       buf.getvalue()
                     __snake_case					  =       self.img

              __snake_case					  =       np.frombuffer(_UpperCamelCase			,   dtype="""uint8"""      )
              __snake_case					  =       buffer.reshape(_UpperCamelCase			,   _UpperCamelCase			,   4      )
              __snake_case  ,						__snake_case					  =       np.split(_UpperCamelCase			,   [3]			,   axis=2      )

              try:
                     import numexpr as ne  # fuse them with numexpr

                     __snake_case					  =       ne.evaluate("""img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"""      )
              except ImportError:
                     __snake_case					  =       alpha.astype("""float32"""      ) / 255.0
                     __snake_case					  =       img * (1 - alpha) + rgb * alpha

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






       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase      )			->       Dict:






              """simple docstring"""


              assert brightness_factor >= -1.0 and brightness_factor <= 1.0
              __snake_case					  =       mplc.to_rgb(_UpperCamelCase      )
              __snake_case					  =       colorsys.rgb_to_hls(*mplc.to_rgb(_UpperCamelCase      )      )
              __snake_case					  =       polygon_color[1] + (brightness_factor * polygon_color[1])
              __snake_case					  =       0.0 if modified_lightness < 0.0 else modified_lightness
              __snake_case					  =       1.0 if modified_lightness > 1.0 else modified_lightness
              __snake_case					  =       colorsys.hls_to_rgb(polygon_color[0]			,   _UpperCamelCase			,   polygon_color[2]      )
              return modified_color






UpperCamelCase__		   =    (
    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)
)

