
    Wpfb:                        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  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"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 classifier task.    N)CallableMappingOptionalList)packet_creator)packet_getter)image)packet)classifications_pb2)classifier_options_pb2)"image_classifier_graph_options_pb2)classification_result)rect)base_options)	task_info)doc_controls)base_vision_task_api)image_processing_options)vision_task_running_modeclassifications_outCLASSIFICATIONSimage_in	image_outIMAGEnorm_rect_in	NORM_RECTz<mediapipe.tasks.vision.image_classifier.ImageClassifierGraphi  c                   0   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d<   dZe
ee                  ed<   dZe
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 )ImageClassifierOptionsa
  Options for the image classifier task.

  Attributes:
    base_options: Base options for the image classifier task.
    running_mode: The running mode of the task. Default to the image mode. Image
      classifier task has three running modes: 1) The image mode for classifying
      objects on single image inputs. 2) The video mode for classifying objects
      on the decoded frames of a video. 3) The live stream mode for classifying
      objects on a live stream of input data, such as from camera.
    display_names_locale: The locale to use for display names specified through
      the TFLite Model Metadata.
    max_results: The maximum number of top-scored classification results to
      return.
    score_threshold: Overrides the ones provided in the model metadata. Results
      below this value are rejected.
    category_allowlist: Allowlist of category names. If non-empty,
      classification results whose category name is not in this set will be
      filtered out. Duplicate or unknown category names are ignored. Mutually
      exclusive with `category_denylist`.
    category_denylist: Denylist of category names. If non-empty, classification
      results whose category name is in this set will be filtered out. Duplicate
      or unknown category names are ignored. Mutually exclusive with
      `category_allowlist`.
    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display_names_localemax_resultsscore_thresholdcategory_allowlistcategory_denylistresult_callbackreturnc                     | j                                         }| j        t          j        k    rdnd|_        t          | j        | j        | j	        | j
        | j                  }t          ||          S )z4Generates an ImageClassifierOptions protobuf object.FT)r"   r#   r$   r    r!   )r   classifier_options)r   to_pb2r   _RunningModer   use_stream_mode_ClassifierOptionsProtor"   r#   r$   r    r!   !_ImageClassifierGraphOptionsProto)selfbase_options_protoclassifier_options_protos      n/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/mediapipe/tasks/python/vision/image_classifier.pyr)   zImageClassifierOptions.to_pb2d   s     *1133"l&888d &  7,20!6$      -'3       )__name__
__module____qualname____doc___BaseOptions__annotations__r*   r   r   r    r   strr!   intr"   floatr#   r   r$   r%   r   ImageClassifierResultimage_moduleImager   do_not_generate_docsr-   r)    r2   r1   r   r   ;   s         8 +1,111(,,,,#+x}###%)/8E?))),0htCy)000+/Xd3i(///  8%|'93?EF    $7    %$  r2   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dS )ImageClassifiera  Class that performs image classification 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 `classes and either 2 or 4 dimensions, i.e. `[1 x N]` or
      `[1 x 1 x 1 x N]`
    - optional (but recommended) label map(s) as AssociatedFiles with type
      TENSOR_AXIS_LABELS, containing one label per line. The first such
      AssociatedFile (if any) is used to fill the `class_name` field of the
      results. The `display_name` field is filled from the AssociatedFile (if
      any) whose locale matches the `display_names_locale` field of the
      `ImageClassifierOptions` used at creation time ("en" by default, i.e.
      English). If none of these are available, only the `index` field of the
      results will be filled.
    - optional score calibration can be attached using ScoreCalibrationOptions
      and an AssociatedFile with type TENSOR_AXIS_SCORE_CALIBRATION. See
      metadata_schema.fbs [1] for more details.

  An example of such model can be found at:
  https://tfhub.dev/bohemian-visual-recognition-alliance/lite-model/models/mushroom-identification_v1/1

  [1]:
  https://github.com/google/mediapipe/blob/6cdc6443b6a7ed662744e2a2ce2d58d9c83e6d6f/mediapipe/tasks/metadata/metadata_schema.fbs#L456
  
model_pathr&   c                     t          |          }t          |t          j                  }|                     |          S )aW  Creates an `ImageClassifier` object from a TensorFlow Lite model and the default `ImageClassifierOptions`.

    Note that the created `ImageClassifier` instance is in image mode, for
    classifying objects on single image inputs.

    Args:
      model_path: Path to the model.

    Returns:
      `ImageClassifier` object that's created from the model file and the
      default `ImageClassifierOptions`.

    Raises:
      ValueError: If failed to create `ImageClassifier` object from the provided
        file such as invalid file path.
      RuntimeError: If other types of error occurred.
    )model_asset_path)r   r   )r7   r   r*   r   create_from_options)clsrC   r   optionss       r1   create_from_model_pathz&ImageClassifier.create_from_model_path   sF    &  <<<L$!0B  G ""7+++r2   rH   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 `ImageClassifier` object from image classifier options.

    Args:
      options: Options for the image classifier task.

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

    Raises:
      ValueError: If failed to create `ImageClassifier` object from
        `ImageClassifierOptions` 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   ClassificationResultCopyFromr   	get_proto_CLASSIFICATIONS_STREAM_NAME	get_image	timestampr%   r<   create_from_pb2value_MICRO_SECONDS_PER_MILLISECOND)rK   classification_result_protor	   rU   rH   s       r1   packets_callbackz=ImageClassifier.create_from_options.<locals>.packets_callback   s    	.	/	8	8	:	: $7$L$N$N!!**

!.1M"N
O
O   %n5K&LMMe !78Bi

/
/0K
L
L

/;
;    r2   :)
task_graphinput_streamsoutput_streamstask_options)enable_flow_limitingN)r   r9   r
   Packet	_TaskInfo_TASK_GRAPH_NAMEjoin
_IMAGE_TAG_IMAGE_IN_STREAM_NAME_NORM_RECT_TAG_NORM_RECT_STREAM_NAME_CLASSIFICATIONS_TAGrS   rN   generate_graph_configr   r*   LIVE_STREAMr%   )rG   rH   rZ   r   s    `  r1   rF   z#ImageClassifier.create_from_options   s   $fm1C)D        #HHj"7899HHn&<=>>

 HH*,HIJJHHj"89::
   I 3''!(!5'"( 	( 	
 	
 	#3=  r2   Nr	   r   c           	         |                      ||          }|                     t          t          j        |          t
          t          j        |                                          i          }t          j	                    }|
                    t          j        |t                                        t                              |          S )a  Performs image classification on the provided MediaPipe Image.

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

    Returns:
      A classification result object that contains a list of classifications.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If image classification failed to run.
    )convert_to_normalized_rect_process_image_datarf   r   create_imagerh   create_protor)   r   rP   rQ   r   rR   rS   r<   rV   )r.   r	   r   normalized_rectrK   rY   s         r1   classifyzImageClassifier.classify   s    $ 55 % O --~:5AA ;""$$!
 !
/  N #6"J"L"L((/K LMM   !001LMMMr2   timestamp_msc           	      
   |                      ||          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i          }t          j                    }|                    t          j        |t                                        t                               |          S )a  Performs image classification on the provided video frames.

    Only use this method when the ImageClassifier 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:
      A classification result object that contains a list of classifications.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If image classification failed to run.
    )rm   _process_video_datarf   r   ro   atrX   rh   rp   r)   r   rP   rQ   r   rR   rS   r<   rV   )r.   r	   rs   r   rq   rK   rY   s          r1   classify_for_videoz"ImageClassifier.classify_for_video  s    2 55 % O --~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;/  N #6"J"L"L((/K LMM   !001LMMMr2   c           	      P   |                      ||          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i           dS )a  Sends live image data (an Image with a unique timestamp) to perform image classification.

    Only use this method when the ImageClassifier 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 `ImageClassifierOptions`. The
    `classify_async` method is designed to process live stream data such as
    camera input. To lower the overall latency, image classifier may drop the
    input images if needed. In other words, it's not guaranteed to have output
    per input image.

    The `result_callback` provides:
      - A classification result object that contains a list of classifications.
      - The input image that the image classifier 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
        classifier has already processed.
    N)
rm   _send_live_stream_datarf   r   ro   rv   rX   rh   rp   r)   )r.   r	   rs   r   rq   s        r1   classify_asynczImageClassifier.classify_async<  s    @ 55 % O 	~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;!     r2   rM   )r3   r4   r5   r6   classmethodr9   rI   r   rF   r=   r>   r   _ImageProcessingOptionsr<   rr   r:   rw   rz   r@   r2   r1   rB   rB   y   su       ! !F ,c ,6G , , , ;,0 4*44 4 4 ;4r EI!N !N!N !))@ A!N 	!N !N !N !NN EI	*N *N*N *N !))@ A	*N
 *N *N *N *N` EI	* ** * !))@ A	*
 * * * * * *r2   rB   )Ar6   dataclassestypingr   r   r   r   mediapipe.pythonr   r   $mediapipe.python._framework_bindingsr	   r=   r
   .mediapipe.tasks.cc.components.containers.protor   .mediapipe.tasks.cc.components.processors.protor   0mediapipe.tasks.cc.vision.image_classifier.protor   ,mediapipe.tasks.python.components.containersr   classification_result_moduler   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   rP   r<   NormalizedRect_NormalizedRectBaseOptionsr7   ImageClassifierGraphOptionsr-   ClassifierOptionsr,   VisionTaskRunningModer*   ImageProcessingOptionsr|   TaskInforb   rS   ri   rf   rN   re   rh   rg   rc   rX   	dataclassr   BaseVisionTaskApirB   r@   r2   r1   <module>r      sF   ' &     4 4 4 4 4 4 4 4 4 4 4 4 + + + + + + * * * * * * F F F F F F 7 7 7 7 7 7 N N N N N N Q Q Q Q Q Q _ _ _ _ _ _ n n n n n n = = = = = = 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 G G G G G G4I %".&B " 1B '=9P %	4 ( " $ 
' B  "&  : : : : : : : :zm m m m m*< m m m m mr2   