
    Wpf:3                        d Z ddlZddlmZmZmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ej"        Z#ej$        Z%ej&        Z'ej(        Z)ej*        Z+ej,        Z-ej.        Z/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9ej:         G d d                      Z; G d dej<                  Z=dS )zMediaPipe audio embedder task.    N)CallableMappingListOptional)packet_creator)packet_getter)packet) audio_embedder_graph_options_pb2)embeddings_pb2)embedder_options_pb2)audio_task_running_mode)base_audio_task_api)
audio_data)embedding_result)base_options)	task_info)doc_controlsaudio_inAUDIOembeddings_out
EMBEDDINGSsample_rate_inSAMPLE_RATEz7mediapipe.tasks.audio.audio_embedder.AudioEmbedderGraphtimestamped_embeddings_outTIMESTAMPED_EMBEDDINGSi  c                       e Zd ZU dZeed<   ej        Zeed<   dZ	e
e         ed<   dZe
e         ed<   dZe
eeegdf                  ed<   ej        defd	            ZdS )
AudioEmbedderOptionsaI  Options for the audio embedder task.

  Attributes:
    base_options: Base options for the audio embedder task.
    running_mode: The running mode of the task. Default to the audio clips mode.
      Audio embedder task has two running modes: 1) The audio clips mode for
      running embedding extraction on independent audio clips. 2) The audio
      stream mode for running embedding extraction on the audio stream, such as
      from microphone. In this mode,  the "result_callback" below must be
      specified to receive the embedding results asynchronously.
    l2_normalize: Whether to normalize the returned feature vector with L2 norm.
      Use this option only if the model does not already contain a native
      L2_NORMALIZATION TF Lite Op. In most cases, this is already the case and
      L2 norm is thus achieved through TF Lite inference.
    quantize: Whether the returned embedding should be quantized to bytes via
      scalar quantization. Embeddings are implicitly assumed to be unit-norm and
      therefore any dimension is guaranteed to have a value in [-1.0, 1.0]. Use
      the l2_normalize option if this is not the case.
    result_callback: The user-defined result callback for processing audio
      stream data. The result callback should only be specified when the running
      mode is set to the audio stream mode.
  r   running_modeNl2_normalizequantizeresult_callbackreturnc                     | j                                         }| j        t          j        k    rdnd|_        t          | j        | j                  }t          ||          S )z2Generates an AudioEmbedderOptions protobuf object.FT)r   r    )r   embedder_options)
r   to_pb2r   _RunningModeAUDIO_CLIPSuse_stream_mode_EmbedderOptionsProtor   r    _AudioEmbedderGraphOptionsProto)selfbase_options_protoembedder_options_protos      k/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/mediapipe/tasks/python/audio/audio_embedder.pyr%   zAudioEmbedderOptions.to_pb2S   sx     *1133262C|G_2_2_ei&2&@ @ @ +'/1 1 1 1    )__name__
__module____qualname____doc___BaseOptions__annotations__r&   r'   r   r   r   boolr    r!   r   AudioEmbedderResultintr   do_not_generate_docsr*   r%    r/   r.   r   r   5   s          , +7,777!%,%%%!(HTN!!!JN/8H&93%?%EFGNNN$	15 	1 	1 	1 %$	1 	1 	1r/   r   c                       e Zd ZdZededd fd            Zededd fd            Zde	de
e         fdZd	e	d
eddfdZdS )AudioEmbedderaA  Class that performs embedding extraction on audio clips or audio stream.

  This API expects a TFLite model with mandatory TFLite Model Metadata that
  contains the mandatory AudioProperties of the solo input audio tensor and the
  optional (but recommended) label items as AssociatedFiles with type
  TENSOR_AXIS_LABELS per output embedding tensor.

  Input tensor:
    (kTfLiteFloat32)
    - input audio buffer of size `[batch * samples]`.
    - batch inference is not supported (`batch` is required to be 1).
    - for multi-channel models, the channels must be interleaved.
  At least one output tensor with:
    (kTfLiteUInt8/kTfLiteFloat32)
    - `N` components corresponding to the `N` dimensions of the returned
    feature vector for this output layer.
    - Either 2 or 4 dimensions, i.e. `[1 x N]` or `[1 x 1 x 1 x N]`.
  
model_pathr"   c                     t          |          }t          |t          j                  }|                     |          S )aZ  Creates an `AudioEmbedder` object from a TensorFlow Lite model and the default `AudioEmbedderOptions`.

    Note that the created `AudioEmbedder` instance is in audio clips mode, for
    embedding extraction on the independent audio clips.

    Args:
      model_path: Path to the model.

    Returns:
      `AudioEmbedder` object that's created from the model file and the
      default `AudioEmbedderOptions`.

    Raises:
      ValueError: If failed to create `AudioEmbedder` object from the provided
        file such as invalid file path.
      RuntimeError: If other types of error occurred.
    )model_asset_path)r   r   )r4   r   r&   r'   create_from_options)clsr=   r   optionss       r.   create_from_model_pathz$AudioEmbedder.create_from_model_patht   sG    &  <<<L"!0HJ J JG""7+++r/   rB   c           	         dt           t          t          j        f         ffd}t	          t
          d                    t          t          g          d                    t          t          g          gd                    t          t          g          d                    t          t          g          g          } | |                    d          j        j        r|nd          S )a  Creates the `AudioEmbedder` object from audio embedder options.

    Args:
      options: Options for the audio embedder task.

    Returns:
      `AudioEmbedder` object that's created from `options`.

    Raises:
      ValueError: If failed to create `AudioEmbedder` object from
        `AudioEmbedderOptions` such as missing the model.
      RuntimeError: If other types of error occurred.
    output_packetsc                    | t                    j        j        t          z  }| t                                                    r&                    t          g           |           d S t          j                    }|	                    t          j        | t                                                             t                              |          |           d S )N)
embeddings)_EMBEDDINGS_STREAM_NAME	timestampvalue_MICRO_SECONDS_PER_MILLISECONDis_emptyr!   r7   r   EmbeddingResultCopyFromr   	get_protocreate_from_pb2)rE   timestamp_msembedding_result_protorB   s      r.   packets_callbackz;AudioEmbedder.create_from_options.<locals>.packets_callback   s    #
!##,U6TUl	/	0	9	9	;	; 2...	> 	> 	>-=??%%

!.1H"I
J
JL L L

-
-.D
E
E
    r/   :)
task_graphinput_streamsoutput_streamstask_optionsF)enable_flow_limitingN)r   strr	   Packet	_TaskInfo_TASK_GRAPH_NAMEjoin
_AUDIO_TAG_AUDIO_IN_STREAM_NAME_SAMPLE_RATE_TAG_SAMPLE_RATE_IN_STREAM_NAME_EMBEDDINGS_TAGrH   _TIMESTAMPTED_EMBEDDINGS_TAG$_TIMESTAMPTED_EMBEDDINGS_STREAM_NAMEgenerate_graph_configr   r!   )rA   rB   rS   r   s    `  r.   r@   z!AudioEmbedder.create_from_options   s    "fm1C)D       #HHj"7899HH&(CDEE

 HHo'>?@@#((,4L C C
   I 3 	''U'CC#3=? ? ?r/   
audio_clipc                    |j         j        st          d          |                     t          t          j        |j        d          t          t          j	        |j         j                  i          }g }t          j        |t                             }|D ]W}t          j                    }|                    |           |                    t"                              |                     X|S )a  Performs embedding extraction on the provided audio clips.

    The audio clip is represented as a MediaPipe AudioData. The method accepts
    audio clips with various length and audio sample rate. It's required to
    provide the corresponding audio sample rate within the `AudioData` object.

    The input audio clip may be longer than what the model is able to process
    in a single inference. When this occurs, the input audio clip is split into
    multiple chunks starting at different timestamps. For this reason, this
    function returns a vector of EmbeddingResult objects, each associated
    ith a timestamp corresponding to the start (in milliseconds) of the chunk
    data on which embedding extraction was carried out.

    Args:
      audio_clip: MediaPipe AudioData.

    Returns:
      An `AudioEmbedderResult` object that contains a list of embedding result
      objects, each associated with a timestamp corresponding to the start
      (in milliseconds) of the chunk data on which embedding extraction was
      carried out.

    Raises:
      ValueError: If any of the input arguments is invalid, such as the sample
        rate is not provided in the `AudioData` object.
      RuntimeError: If audio embedding extraction failed to run.
    1Must provide the audio sample rate in audio data.T	transpose)audio_formatsample_rate
ValueError_process_audio_clipr`   r   create_matrixbufferrb   create_doubler   get_proto_listre   r   rM   rN   appendr7   rP   )r+   rg   rE   output_listembeddings_proto_listprotorR   s          r.   embedzAudioEmbedder.embed   s    8 ". LJKKK--():dKKK#()@)LMM	/  N K)8;<> >& G G-=??%%e,,,

-
-.D
E
EG G G Gr/   audio_blockrQ   Nc                    |j         j        st          d          | j        s2|j         j        | _        |                     t
          | j                   n:|j         j        | j        k    r%t          d|j         j         d| j         d          |                     t          t          j	        |j
        d                              |t          z            i           dS )a  Sends audio data (a block in a continuous audio stream) to perform audio embedding extraction.

    Only use this method when the AudioEmbedder is created with the audio
    stream running mode. The input timestamps should be monotonically increasing
    for adjacent calls of this method. This method will return immediately after
    the input audio data is accepted. The results will be available via the
    `result_callback` provided in the `AudioEmbedderOptions`. The
    `embed_async` method is designed to process auido stream data such as
    microphone input.

    The input audio data may be longer than what the model is able to process
    in a single inference. When this occurs, the input audio block is split
    into multiple chunks. For this reason, the callback may be called multiple
    times (once per chunk) for each call to this function.

    The `result_callback` provides:
      - An `AudioEmbedderResult` object that contains a list of
        embeddings.
      - The input timestamp in milliseconds.

    Args:
      audio_block: MediaPipe AudioData.
      timestamp_ms: The timestamp of the input audio data in milliseconds.

    Raises:
      ValueError: If any of the followings:
        1) The sample rate is not provided in the `AudioData` object or the
        provided sample rate is inconsistent with the previously received.
        2) The current input timestamp is smaller than what the audio
        embedder has already processed.
    ri   z.The audio sample rate provided in audio data: z/ is inconsistent with the previously received: .Trj   N)rl   rm   rn   _default_sample_rate_set_sample_raterb   _send_audio_stream_datar`   r   rp   rq   atrK   )r+   ry   rQ   s      r.   embed_asynczAudioEmbedder.embed_async   s   @ #/ LJKKK$ D"-":"Fd
7 57 7 7 7		!	-1J	J	JC%1C C&*&?C C CD D D
 	  ();tLLLOO==? ?"     r/   )r0   r1   r2   r3   classmethodrZ   rC   r   r@   
_AudioDatar   r7   rx   r8   r   r:   r/   r.   r<   r<   `   s         & ,c ,o , , , ;,. 0?#70?<K0? 0? 0? ;0?d,j ,T2E-F , , , ,\0Z 0s 0t 0 0 0 0 0 0r/   r<   )>r3   dataclassestypingr   r   r   r   mediapipe.pythonr   r   $mediapipe.python._framework_bindingsr	   -mediapipe.tasks.cc.audio.audio_embedder.protor
   .mediapipe.tasks.cc.components.containers.protor   .mediapipe.tasks.cc.components.processors.protor   !mediapipe.tasks.python.audio.corer   running_mode_moduler   ,mediapipe.tasks.python.components.containersr   audio_data_moduler   embedding_result_modulemediapipe.tasks.python.corer   base_options_moduler   task_info_module1mediapipe.tasks.python.core.optional_dependenciesr   rM   r7   AudioEmbedderGraphOptionsr*   	AudioDatar   BaseOptionsr4   EmbedderOptionsr)   AudioTaskRunningModer&   TaskInfor\   r`   r_   rH   rc   rb   ra   r]   re   rd   rK   	dataclassr   BaseAudioTaskApir<   r:   r/   r.   <module>r      s   % $     4 4 4 4 4 4 4 4 4 4 4 4 + + + + + + * * * * * * 7 7 7 7 7 7 Z Z Z Z Z Z I I I I I I O O O O O O \ \ \ \ \ \ A A A A A A X X X X X X d d d d d d K K K K K K E E E E E E J J J J J J-= "B"\ (
".,< "7%	" 
* .   L 'C $7 !%  '1 '1 '1 '1 '1 '1 '1 '1T} } } } }'8 } } } } }r/   