
    Wpf/8                        d Z ddlZddl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! 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j0        Z1e#j2        Z3dZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;dZ<ej=         G d d                      Z> G d de!j?                  Z@dS ) zMediaPipe image embedder task.    N)CallableMappingOptional)packet_creator)packet_getter)image)packet)embeddings_pb2)embedder_options_pb2) image_embedder_graph_options_pb2)embedding_resultcosine_similarity)base_options)	task_info)doc_controls)base_vision_task_api)image_processing_options)vision_task_running_modeembeddings_out
EMBEDDINGSimage_in	image_outIMAGEnorm_rect_in	NORM_RECTz8mediapipe.tasks.vision.image_embedder.ImageEmbedderGraphi  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j        egdf                  ed<   ej        defd	            ZdS )
ImageEmbedderOptionsa  Options for the image embedder task.

  Attributes:
    base_options: Base options for the image embedder task.
    running_mode: The running mode of the task. Default to the image mode. Image
      embedder task has three running modes: 1) The image mode for embedding
      image on single image inputs. 2) The video mode for embedding image on the
      decoded frames of a video. 3) The live stream mode for embedding image on
      a live stream of input data, such as from camera.
    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 live stream
      data. The result callback should only be specified when the running mode
      is set to the live 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 ImageEmbedderOptions protobuf object.FT)r    r!   )r   embedder_options)
r   to_pb2r   _RunningModer   use_stream_mode_EmbedderOptionsProtor    r!   _ImageEmbedderGraphOptionsProto)selfbase_options_protoembedder_options_protos      l/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/mediapipe/tasks/python/vision/image_embedder.pyr&   zImageEmbedderOptions.to_pb2X   sx     *1133"l&888d & 3&   +':P       )__name__
__module____qualname____doc___BaseOptions__annotations__r'   r   r   r    r   boolr!   r"   r   ImageEmbedderResultimage_moduleImageintr   do_not_generate_docsr*   r&    r/   r.   r   r   8   s          , +1,111!%,%%%!(HTN!!!  8#\%7=tCD    $5    %$  r/   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de	j
        d	ee         defd
Z	 dde	j
        ded	ee         defdZ	 dde	j
        ded	ee         ddfdZedej        dej        defd            ZdS )ImageEmbeddera  Class that performs embedding extraction on images.

  The API expects a TFLite model with optional, but strongly recommended,
  TFLite Model Metadata.

  Input tensor:
    (kTfLiteUInt8/kTfLiteFloat32)
    - image input of size `[batch x height x width x channels]`.
    - batch inference is not supported (`batch` is required to be 1).
    - only RGB inputs are supported (`channels` is required to be 3).
    - if type is kTfLiteFloat32, NormalizationOptions are required to be
      attached to the metadata for input normalization.
  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 )aG  Creates an `ImageEmbedder` object from a TensorFlow Lite model and the default `ImageEmbedderOptions`.

    Note that the created `ImageEmbedder` instance is in image mode, for
    embedding image on single image inputs.

    Args:
      model_path: Path to the model.

    Returns:
      `ImageEmbedder` object that's created from the model file and the default
      `ImageEmbedderOptions`.

    Raises:
      ValueError: If failed to create `ImageEmbedder` 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$ImageEmbedder.create_from_model_path|   sF    &  <<<L"!0B  G ""7+++r/   rD   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          } | |                    j        t           j        k              j        j        r|nd          S )a  Creates the `ImageEmbedder` object from image embedder options.

    Args:
      options: Options for the image embedder task.

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

    Raises:
      ValueError: If failed to create `ImageEmbedder` object from
        `ImageEmbedderOptions` such as missing the model.
      RuntimeError: If other types of error occurred.
    output_packetsc                    | t                                                    rd S t          j                    }|                    t          j        | t                                        t          j        | t                              }| t                    j	        }
                    t                              |          ||j        t          z             d S N)_IMAGE_OUT_STREAM_NAMEis_emptyr
   EmbeddingResultCopyFromr   	get_proto_EMBEDDINGS_OUT_STREAM_NAME	get_image	timestampr"   r7   create_from_pb2value_MICRO_SECONDS_PER_MILLISECOND)rG   embedding_result_protor   rQ   rD   s       r.   packets_callbackz;ImageEmbedder.create_from_options.<locals>.packets_callback   s    	.	/	8	8	:	: -=??%%

!.1L"M
N
N   %n5K&LMMe !78Bi

-
-.D
E
E

/;
;    r/   :)
task_graphinput_streamsoutput_streamstask_options)enable_flow_limitingN)r   strpacket_modulePacket	_TaskInfo_TASK_GRAPH_NAMEjoin
_IMAGE_TAG_IMAGE_IN_STREAM_NAME_NORM_RECT_TAG_NORM_RECT_STREAM_NAME_EMBEDDINGS_TAGrO   rJ   generate_graph_configr   r'   LIVE_STREAMr"   )rC   rD   rV   r   s    `  r.   rB   z!ImageEmbedder.create_from_options   s   $m6J1J)K      " #HHj"7899HHn&<=>>

 HHo'BCDDHHj"89::
   I 3''!(!5'"( 	( 	
 	
 	#3=  r/   Nr   r   c           	         |                      ||          }|                     t          t          j        |          t
          t          j        |                                          i          }t          j	                    }|
                    t          j        |t                                        t                              |          S )a  Performs image embedding extraction on the provided MediaPipe Image.

     Extraction is performed on the region of interest specified by the `roi`
     argument if provided, or on the entire image otherwise.

    Args:
      image: MediaPipe Image.
      image_processing_options: Options for image processing.

    Returns:
      An embedding result object that contains a list of embeddings.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If image embedder failed to run.
    )convert_to_normalized_rect_process_image_datard   r   create_imagerf   create_protor&   r
   rL   rM   r   rN   rO   r7   rR   )r+   r   r   normalized_rectrG   rU   s         r.   embedzImageEmbedder.embed   s    * 55 % O --~:5AA ;""$$!
 !
/  N ,;==##/J KLL   ../EFFFr/   timestamp_msc           	      
   |                      ||          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i          }t          j                    }|                    t          j        |t                                        t                               |          S )ay  Performs image embedding extraction on the provided video frames.

    Extraction is performed on the region of interested specified by the `roi`
    argument if provided, or on the entire image otherwise.

    Only use this method when the ImageEmbedder is created with the video
    running mode. It's required to provide the video frame's timestamp (in
    milliseconds) along with the video frame. The input timestamps should be
    monotonically increasing for adjacent calls of this method.

    Args:
      image: MediaPipe Image.
      timestamp_ms: The timestamp of the input video frame in milliseconds.
      image_processing_options: Options for image processing.

    Returns:
      An embedding result object that contains a list of embeddings.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If image embedder failed to run.
    )rk   _process_video_datard   r   rm   atrT   rf   rn   r&   r
   rL   rM   r   rN   rO   r7   rR   )r+   r   rq   r   ro   rG   rU   s          r.   embed_for_videozImageEmbedder.embed_for_video   s    8 55 % O --~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;/  N ,;==##/J KLL   ../EFFFr/   c           	      P   |                      ||          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i           dS )a  Sends live image data to embedder.

    The results will be available via the "result_callback" provided in the
    ImageEmbedderOptions. Embedding extraction is performed on the region of
    interested specified by the `roi` argument if provided, or on the entire
    image otherwise.

    Only use this method when the ImageEmbedder is created with the live
    stream running mode. The input timestamps should be monotonically increasing
    for adjacent calls of this method. This method will return immediately after
    the input image is accepted. The results will be available via the
    `result_callback` provided in the `ImageEmbedderOptions`. The
    `embed_async` method is designed to process live stream data such as
    camera input. To lower the overall latency, image embedder may drop the
    input images if needed. In other words, it's not guaranteed to have output
    per input image.

    The `result_callback` provides:
      - An embedding result object that contains a list of embeddings.
      - The input image that the image embedder runs on.
      - The input timestamp in milliseconds.

    Args:
      image: MediaPipe Image.
      timestamp_ms: The timestamp of the input image in milliseconds.
      image_processing_options: Options for image processing.

    Raises:
      ValueError: If the current input timestamp is smaller than what the image
        embedder has already processed.
    N)
rk   _send_live_stream_datard   r   rm   rt   rT   rf   rn   r&   )r+   r   rq   r   ro   s        r.   embed_asynczImageEmbedder.embed_async!  s    J 55 % O 	~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;!     r/   uvc                 ,    t          j         ||          S )a=  Utility function to compute cosine similarity between two embedding entries.

    May return an InvalidArgumentError if e.g. the feature vectors are of
    different types (quantized vs. float), have different sizes, or have an
    L2-norm of 0.

    Args:
      u: An embedding entry.
      v: An embedding entry.

    Returns:
      The cosine similarity for the two embeddings.

    Raises:
      ValueError: May return an error if e.g. the feature vectors are of
        different types (quantized vs. float), have different sizes, or have
        an L2-norm of 0.
    r   )rC   ry   rz   s      r.   r   zImageEmbedder.cosine_similarityR  s    0 .q!444r/   rI   )r0   r1   r2   r3   classmethodr]   rE   r   rB   r8   r9   r   _ImageProcessingOptionsr7   rp   r:   ru   rx   embedding_result_module	Embeddingfloatr   r<   r/   r.   r>   r>   h   s        & ,c ,o , , , ;,0 5(55 5 5 ;5t EI$G $G$G !))@ A$G 	$G $G $G $GT EI	,G ,G,G ,G !))@ A	,G
 ,G ,G ,G ,Gd EI	/ // / !))@ A	/
 / / / /b 5	 	*5 
!	*5 	5 5 5 ;5 5 5r/   r>   )Ar3   dataclassestypingr   r   r   mediapipe.pythonr   r   $mediapipe.python._framework_bindingsr   r8   r	   r^   .mediapipe.tasks.cc.components.containers.protor
   .mediapipe.tasks.cc.components.processors.protor   .mediapipe.tasks.cc.vision.image_embedder.protor   ,mediapipe.tasks.python.components.containersr   r~   'mediapipe.tasks.python.components.utilsr   mediapipe.tasks.python.corer   base_options_moduler   task_info_module1mediapipe.tasks.python.core.optional_dependenciesr   "mediapipe.tasks.python.vision.corer   r   image_processing_options_moduler   running_mode_modulerL   r7   BaseOptionsr4   ImageEmbedderGraphOptionsr*   EmbedderOptionsr)   VisionTaskRunningModer'   TaskInfor`   ImageProcessingOptionsr}   rO   rg   rd   rJ   rc   rf   re   ra   rT   	dataclassr   BaseVisionTaskApir>   r<   r/   r.   <module>r      s3   % $     . . . . . . . . . . + + + + + + * * * * * * F F F F F F H H H H H H I I I I I I O O O O O O [ [ [ [ [ [ d d d d d d E E E E E E K K K K K K E E E E E E J J J J J J C C C C C C j j j j j j ^ ^ ^ ^ ^ ^-= ".$>   -< "8%	9P . " $ 
' M !%  , , , , , , , ,^B5 B5 B5 B5 B5(: B5 B5 B5 B5 B5r/   