
    |hƑ                         d dl Z d dlmZ d dlmZ d dlmZmZmZm	Z	m
Z
 d dlZd dlZd dlmZ d dlmZ d dlmZmZmZ d dlmZmZ d d	lmZ  G d
 d      Z G d de      Z G d d      Zy)    N)defaultdict)	lru_cache)AnyDictListOptionalTuple)YOLO)SolutionConfig)
ASSETS_URLLOGGERops)check_imshowcheck_requirements)	Annotatorc            
           e Zd ZdZddededdfdZddeded	e	e   de	e
   fd
Zdej                  ddfdZd	eddfdZddZdej                  ddfdZdedefdZdedefdZy)BaseSolutiona  
    A base class for managing Ultralytics Solutions.

    This class provides core functionality for various Ultralytics Solutions, including model loading, object tracking,
    and region initialization. It serves as the foundation for implementing specific computer vision solutions such as
    object counting, pose estimation, and analytics.

    Attributes:
        LineString: Class for creating line string geometries from shapely.
        Polygon: Class for creating polygon geometries from shapely.
        Point: Class for creating point geometries from shapely.
        prep: Prepared geometry function from shapely for optimized spatial operations.
        CFG (Dict[str, Any]): Configuration dictionary loaded from YAML file and updated with kwargs.
        LOGGER: Logger instance for solution-specific logging.
        annotator: Annotator instance for drawing on images.
        tracks: YOLO tracking results from the latest inference.
        track_data: Extracted tracking data (boxes or OBB) from tracks.
        boxes (List): Bounding box coordinates from tracking results.
        clss (List[int]): Class indices from tracking results.
        track_ids (List[int]): Track IDs from tracking results.
        confs (List[float]): Confidence scores from tracking results.
        track_line: Current track line for storing tracking history.
        masks: Segmentation masks from tracking results.
        r_s: Region or line geometry object for spatial operations.
        frame_no (int): Current frame number for logging purposes.
        region (List[Tuple[int, int]]): List of coordinate tuples defining region of interest.
        line_width (int): Width of lines used in visualizations.
        model (YOLO): Loaded YOLO model instance.
        names (Dict[int, str]): Dictionary mapping class indices to class names.
        classes (List[int]): List of class indices to track.
        show_conf (bool): Flag to show confidence scores in annotations.
        show_labels (bool): Flag to show class labels in annotations.
        device (str): Device for model inference.
        track_add_args (Dict[str, Any]): Additional arguments for tracking configuration.
        env_check (bool): Flag indicating whether environment supports image display.
        track_history (defaultdict): Dictionary storing tracking history for each object.
        profilers (Tuple): Profiler instances for performance monitoring.

    Methods:
        adjust_box_label: Generate formatted label for bounding box.
        extract_tracks: Apply object tracking and extract tracks from input image.
        store_tracking_history: Store object tracking history for given track ID and bounding box.
        initialize_region: Initialize counting region and line segment based on configuration.
        display_output: Display processing results including frames or saved results.
        process: Process method to be implemented by each Solution subclass.

    Examples:
        >>> solution = BaseSolution(model="yolo11n.pt", region=[(0, 0), (100, 0), (100, 100), (0, 100)])
        >>> solution.initialize_region()
        >>> image = cv2.imread("image.jpg")
        >>> solution.extract_tracks(image)
        >>> solution.display_output(image)
    is_clikwargsreturnNc                 V   t         t               j                  di |      | _        t        | _        t        d       ddlm}m}m	} ddl
m} || _        || _	        || _        || _        d| _        d| _        d| _        g | _        g | _        g | _        d| _        d| _        d| _        d| _        | j                  j-                  d| j                          | j                  d   | _        | j                  d	   | _        | j                  d
   d| j                  d
<   t3        | j                  d
         | _        | j4                  j6                  | _        | j                  d   | _        | j                  d   | _        | j                  d   | _        | j                  d   | _        dD ci c]  }|| j                  |    c}| _         |ro| j                  d   `d| j                  d
   vrdnd}| j                  jC                  dtD         d|        ddl#m$}	  |	tD         d|        || j                  d<   tK        d      | _&        tO        tP              | _)        tU        jV                  | j>                        tU        jV                  | j>                        f| _,        yc c}w )a  
        Initialize the BaseSolution class with configuration settings and YOLO model.

        Args:
            is_cli (bool): Enable CLI mode if set to True.
            **kwargs (Any): Additional configuration parameters that override defaults.
        zshapely>=2.0.0r   )
LineStringPointPolygon)prepNu   Ultralytics Solutions: ✅ region
line_widthmodelz
yolo11n.ptclasses	show_confshow_labelsdevice>   iouconfhalfr#   max_dettrackersourcez-posezsolutions_ci_demo.mp4zsolution_ci_pose_demo.mp4z*source not provided. using default source /)safe_downloadT)warn)r#    )-varsr   updateCFGr   r   shapely.geometryr   r   r   shapely.preparedr   	annotatortracks
track_databoxesclss	track_ids
track_linemasksr_sframe_noinfor   r   r
   r   namesr    r!   r"   r#   track_add_argswarningr   ultralytics.utils.downloadsr+   r   	env_checkr   listtrack_historyr   Profile	profilers)
selfr   r   r   r   r   r   kd_sr+   s
             ^/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py__init__zBaseSolution.__init__I   sH    /(//9&9:+,??)$
	
	
6txxjABhhx(((<0 88G$ ,DHHW$((7+,
ZZ%%
xx	*+.88M2hhx( %\
 Atxx{N
 dhhx(0-4DHHW<M-M)SnCKK"LZLXYZ]Y^ _`AZL#/0!$DHHX &40(. KKt{{+KKt{{+
!
s   +J&clsr%   track_idc                 |    |dn| d| j                   |   z   }| j                  r| j                  r| d|dS |S dS )a  
        Generate a formatted label for a bounding box.

        This method constructs a label string for a bounding box using the class index and confidence score.
        Optionally includes the track ID if provided. The label format adapts based on the display settings
        defined in `self.show_conf` and `self.show_labels`.

        Args:
            cls (int): The class index of the detected object.
            conf (float): The confidence score of the detection.
            track_id (int, optional): The unique identifier for the tracked object.

        Returns:
            (str | None): The formatted label string if `self.show_labels` is True; otherwise, None.
        N  .2f)r>   r"   r!   )rG   rL   r%   rM   names        rJ   adjust_box_labelzBaseSolution.adjust_box_label   sO      &xjNdjjoMEIEUEU4&$s$_D_[__    im0c           	         | j                   d   5   | j                  j                  d|d| j                  dd| j                  d   | _        ddd       | j
                  j                  du}|r| j
                  j                  n| j
                  j                  | _        | j                  r| j                  j                  r|r| j                  j                  n| j                  j                  j                         | _        | j                  j                  j                         j                         | _        | j                  j                   j#                         j                         j                         | _        | j                  j&                  j                         j                         | _        y| j*                  j-                  d       g g g g f\  | _        | _        | _        | _        y# 1 sw Y   xY w)aC  
        Apply object tracking and extract tracks from an input image or frame.

        Args:
            im0 (np.ndarray): The input image or frame.

        Examples:
            >>> solution = BaseSolution()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> solution.extract_tracks(frame)
        r   TF)r)   persistr    verboseNzno tracks found!r-   )rF   r   trackr    r?   r4   obbr6   r5   is_trackxyxyxyxyxyxycpurL   tolistr7   idintr8   r%   confsr   r@   )rG   rU   is_obbs      rJ   extract_trackszBaseSolution.extract_tracks   st    ^^A 	*$**** D$,,QUQdQdDK	 ,-3$++//9J9J??t776<$//22$//BVBV[[]DJ++//188:DI!__//33599;BBDDN--113::<DJKK 23@BBB=DJ	4>4:	 	s   >G44G>c                 z   | j                   |   | _        | j                  j                  |j                         dkD  rt	        |j                  d            n+|ddd   j                         |ddd   j                         f       t        | j                        dkD  r| j                  j                  d       yy)aR  
        Store the tracking history of an object.

        This method updates the tracking history for a given object by appending the center point of its
        bounding box to the track line. It maintains a maximum of 30 points in the tracking history.

        Args:
            track_id (int): The unique identifier for the tracked object.
            box (List[float]): The bounding box coordinates of the object in the format [x1, y1, x2, y2].

        Examples:
            >>> solution = BaseSolution()
            >>> solution.store_tracking_history(1, [100, 200, 300, 400])
           r   )dimN         )rD   r9   appendnumeltuplemeanlenpop)rG   rM   boxs      rJ   store_tracking_historyz#BaseSolution.store_tracking_history   s      ,,X6quSXX!X_5sSWTUVWSWy~~O_adefghijejakapaparNstt"$OO" %rT   c                     | j                   	g d| _         t        | j                         dk\  r!| j                  | j                         | _        y| j                  | j                         | _        y)zPInitialize the counting region and line segment based on configuration settings.N))
      )  ru   )rv      )rt   rw      )r   ro   r   r   r;   )rG   s    rJ   initialize_regionzBaseSolution.initialize_region   sT    ;;HDK),T[[)9Q)>DLL% 	DHOOTXT_T_D` 	rT   plot_imc                     | j                   j                  d      r]| j                  rPt        j                  d|       t        j
                  d      dz  t        d      k(  rt        j                          yyyy)aU  
        Display the results of the processing, which could involve showing frames, printing counts, or saving results.

        This method is responsible for visualizing the output of the object detection and tracking process. It displays
        the processed frame with annotations, and allows for user interaction to close the display.

        Args:
            plot_im (np.ndarray): The image or frame that has been processed and annotated.

        Examples:
            >>> solution = BaseSolution()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> solution.display_output(frame)

        Notes:
            - This method will only display output if the 'show' configuration is set to True and the environment
              supports image display.
            - The display can be closed by pressing the 'q' key.
        showzUltralytics Solutionsri      qN)r0   getrB   cv2imshowwaitKeyorddestroyAllWindows)rG   rz   s     rJ   display_outputzBaseSolution.display_output   s^    ( 88<<DNNJJ.8{{1~$C0%%' 1 %3rT   argsc                      y)z?Process method should be implemented by each Solution subclass.Nr-   )rG   r   r   s      rJ   processzBaseSolution.process   s    rT   c                    | j                   d   5   | j                  |i |}ddd       t        |       j                  dk(  rdnd}| j                   d   j                  dz  }| j                   d   j                  | j                   d   j                  z
  dz  }||d|i_        | j                  d	   r| xj                  dz  c_        t        j                  | j                   d
|j                  j                  d    d|j                  j                  d    d|dd|dd| d|ddt        | j                  dd       d|j                  j                  d    d|j                  j                  d    d       |S # 1 sw Y   ZxY w)zEAllow instances to be called like a function with flexible arguments.ri   NObjectCropperpredictrY   r   g     @@solutionrX   : xrP   z.1fz
ms
Speed: zms , z#ms solution per image at shape (1, chrx   z)
)rF   r   type__name__dtspeedr0   r<   r   r=   rz   shapegetattrr   )rG   r   r   resulttrack_or_predicttrack_or_predict_speedsolution_speeds          rJ   __call__zBaseSolution.__call__   s   ^^A 	3!T\\4262F	3(,T
(;(;(N9T[!%!2!5!5!;..+..1B1E1EEL(*@*n]88IMMQMKK==/FNN$8$8$;#<Afnn>R>RST>U=VVWXfgjWk l05S9I8J"!#& 'tzz434Bv~~7K7KA7N6OrRXR`R`RfRfghRiQjjmo 	3 	3s   E;;F)F)N)r   N)r   
__module____qualname____doc__boolr   rK   ra   floatr   strrS   npndarrayrd   rr   ry   r   r   r   r-   rT   rJ   r   r      s    4l?
t ?
s ?
t ?
B`C `u ` `YabeYf `&O"** O O8#s #D #*
bjj T 4NS NC Nc S rT   r   c                   $    e Zd ZdZ	 	 	 	 	 d<dej
                  dee   dee   dede	def fdZ
	 	 	 d=d	eeeeef         d
eeeef   defdZ	 	 	 d>dedeeeeef         deeeef   deeeef   fdZdej
                  deeef   deeeef   deeeef   def
dZe ed      dee   dee   dee   defd              Z	 	 	 d?deee      deee      d ed!edej
                  f
d"Z	 	 d@d#ed$eeef   d
eeeef   deeeef   def
d%Z	 	 d@d&ed'ed(ed)ee   d
eeeef   deeeef   fd*Z	 	 dAd+ed,eeeef      d-eeeef   d.eeeef   fd/Zdej
                  dedeeeef   deeeef   d0ed1edefd2Z	 	 	 	 	 dBd3ed4edee   d
eeeef   deeeef   f
d5Z	 	 dCd6ee   d7eeef   d
eeeef   d8eeeef   fd9Z	 	 	 	 dDd6eeeeef   ded
eeeef   deeeef   def
d:Z	 	 	 	 dEd6eeeeef   ded
eeeef   deeeef   def
d;Z xZS )FSolutionAnnotatora  
    A specialized annotator class for visualizing and analyzing computer vision tasks.

    This class extends the base Annotator class, providing additional methods for drawing regions, centroids, tracking
    trails, and visual annotations for Ultralytics Solutions. It offers comprehensive visualization capabilities for
    various computer vision applications including object detection, tracking, pose estimation, and analytics.

    Attributes:
        im (np.ndarray): The image being annotated.
        line_width (int): Thickness of lines used in annotations.
        font_size (int): Size of the font used for text annotations.
        font (str): Path to the font file used for text rendering.
        pil (bool): Whether to use PIL for text rendering.
        example (str): An example attribute for demonstration purposes.

    Methods:
        draw_region: Draw a region using specified points, colors, and thickness.
        queue_counts_display: Display queue counts in the specified region.
        display_analytics: Display overall statistics for parking lot management.
        estimate_pose_angle: Calculate the angle between three points in an object pose.
        draw_specific_kpts: Draw specific keypoints on the image.
        plot_workout_information: Draw a labeled text box on the image.
        plot_angle_and_count_and_stage: Visualize angle, step count, and stage for workout monitoring.
        plot_distance_and_line: Display the distance between centroids and connect them with a line.
        display_objects_labels: Annotate bounding boxes with object class labels.
        sweep_annotator: Visualize a vertical sweep line and optional label.
        visioneye: Map and connect object centroids to a visual "eye" point.
        circle_label: Draw a circular label within a bounding box.
        text_label: Draw a rectangular label within a bounding box.

    Examples:
        >>> annotator = SolutionAnnotator(image)
        >>> annotator.draw_region([(0, 0), (100, 100)], color=(0, 255, 0), thickness=5)
        >>> annotator.display_analytics(
        ...     image, text={"Available Spots": 5}, txt_color=(0, 0, 0), bg_color=(255, 255, 255), margin=10
        ... )
    imr   	font_sizefontpilexamplec                 .    t         |   ||||||       y)a  
        Initialize the SolutionAnnotator class with an image for annotation.

        Args:
            im (np.ndarray): The image to be annotated.
            line_width (int, optional): Line thickness for drawing on the image.
            font_size (int, optional): Font size for text annotations.
            font (str): Path to the font file.
            pil (bool): Indicates whether to use PIL for rendering text.
            example (str): An example parameter for demonstration purposes.
        N)superrK   )rG   r   r   r   r   r   r   	__class__s          rJ   rK   zSolutionAnnotator.__init__-  s    ( 	ZD#wGrT   reg_ptscolor	thicknessc                     t        j                  | j                  t        j                  |t        j
                        gd||       |D ]0  }t        j                  | j                  |d   |d   f|dz  |d       2 y)	aB  
        Draw a region or line on the image.

        Args:
            reg_pts (List[Tuple[int, int]], optional): Region points (for line 2 points, for region 4+ points).
            color (Tuple[int, int, int]): RGB color value for the region.
            thickness (int): Line thickness for drawing the region.
        )dtypeT)isClosedr   r   r   ri   rh   r   N)r   	polylinesr   r   arrayint32circle)rG   r   r   r   points        rJ   draw_regionzSolutionAnnotator.draw_regionC  sl     	dgg ABTY^jst  	PEJJtwwq58 4i!mUBO	PrT   labelpointsregion_color	txt_colorc           
         |D cg c]  }|d   	 }}|D cg c]  }|d   	 }}t        |      t        |      z  }t        |      t        |      z  }	t        j                  |d| j                  | j
                        d   }
|
d   }|
d   }|dz   }|dz   }||dz  z
  |	|dz  z
  f}||dz  z   |	|dz  z   f}t        j                  | j                  |||d       ||dz  z
  }|	|dz  z   }t        j                  | j                  |||fd| j                  || j
                  t        j                         yc c}w c c}w )	a  
        Display queue counts on an image centered at the points with customizable font size and colors.

        Args:
            label (str): Queue counts label.
            points (List[Tuple[int, int]], optional): Region points for center point calculation to display text.
            region_color (Tuple[int, int, int]): RGB queue region color.
            txt_color (Tuple[int, int, int]): RGB text display color.
        r   ri   	fontScaler      rh   r   )r   r   r   lineTypeN)
sumro   r   getTextSizesftf	rectangler   putTextLINE_AA)rG   r   r   r   r   r   x_valuesy_valuescenter_xcenter_y	text_size
text_widthtext_height
rect_widthrect_heightrect_top_leftrect_bottom_righttext_xtext_ys                      rJ   queue_counts_displayz&SolutionAnnotator.queue_counts_displayW  sR     +11E!H11*01E!H11x=CK/x=CK/OOE1477STUV	q\
l"_
!B&!J!O3Xq@P5PQ%
a7KSTDT9TUdgg}.?rRJ!O+K1,, 	GGVgggg[[		
' 21s
   D6D;rU   textbg_colormarginc                    t        |j                  d   dz        }t        |j                  d   dz        }d}|j                         D ]	  \  }	}
|	 d|
 }t        j                  |d| j
                  | j                        d   }|d   dk  s|d   dk  rd}|j                  d   |d   z
  |dz  z
  |z
  }||d   z   |dz  z   |z   }||dz  z
  }||d   z
  |dz  z
  }||d   z   |dz  z   }||dz  z   }t        j                  |||f||f|d	       t        j                  ||||fd| j
                  || j                  t        j                  
       |} y)a  
        Display the overall statistics for parking lots, object counter etc.

        Args:
            im0 (np.ndarray): Inference image.
            text (Dict[str, Any]): Labels dictionary.
            txt_color (Tuple[int, int, int]): Display color for text foreground.
            bg_color (Tuple[int, int, int]): Display color for text background.
            margin (int): Gap between text and rectangle for better display.
        ri   g{Gz?r   g{Gz?r      )r   r   rh   r   r   N)
ra   r   itemsr   r   r   r   r   r   r   )rG   rU   r   r   r   r   horizontal_gapvertical_gaptext_y_offsetr   valuetxtr   r   r   rect_x1rect_y1rect_x2rect_y2s                      rJ   display_analyticsz#SolutionAnnotator.display_analytics  sy   $ SYYq\D01399Q<$./ JJL 	$LE5G2eW%CQA!DI|a9Q<!#3"	YYq\IaL06A:=NF"Yq\1FQJ>MFvz)Gy|+fqj8Gy|+fqj8Gvz)GMM#1GW3ExQSTKKS66"2Atww	477]`]h]hi#M	$rT      )maxsizeabcr   c                     t        j                  |d   |d   z
  |d   |d   z
        t        j                  | d   |d   z
  | d   |d   z
        z
  }t        |dz  t         j                  z        }|dk  r|S d|z
  S )a  
        Calculate the angle between three points for workout monitoring.

        Args:
            a (List[float]): The coordinates of the first point.
            b (List[float]): The coordinates of the second point (vertex).
            c (List[float]): The coordinates of the third point.

        Returns:
            (float): The angle in degrees between the three points.
        ri   r   g     f@ih  )mathatan2abspi)r   r   r   radiansangles        rJ   estimate_pose_anglez%SolutionAnnotator.estimate_pose_angle  s     **QqTAaD[!A$1+6AaD1Q4KQRSTQUXYZ[X\Q\9]]GeOdgg-.u9S5[9rT   	keypointsindicesradiusconf_threshc           	         |xs g d}t        |      D cg c]/  \  }}||v s|d   |k\  st        |d         t        |d         f1 }}}t        |dd |dd       D ]8  \  }}	t        j                  | j
                  ||	ddt        j                         : |D ]5  }
t        j                  | j
                  |
|d	dt        j                         7 | j
                  S c c}}w )
a1  
        Draw specific keypoints for gym steps counting.

        Args:
            keypoints (List[List[float]]): Keypoints data to be plotted, each in format [x, y, confidence].
            indices (List[int], optional): Keypoint indices to be plotted.
            radius (int): Keypoint radius.
            conf_thresh (float): Confidence threshold for keypoints.

        Returns:
            (np.ndarray): Image with drawn keypoints.

        Notes:
            Keypoint format: [x, y] or [x, y, confidence].
            Modifies self.im in-place.
        )rh   r      rh   r   ri   Nr   r   r}   r   r   )r   r   r}   )	enumeratera   zipr   liner   r   r   )rG   r   r   r   r   irH   r   startendpts              rJ   draw_specific_kptsz$SolutionAnnotator.draw_specific_kpts  s    . &Y5>y5IrTQQRY\^_`a^bfq^q3qt9c!A$i(rr fSbk6!":6 	PJE3HHTWWeS+q3;;O	P  	SBJJtwwFKckkR	S ww ss   C!C!C!display_textpositionc           	         t        j                  |d| j                  | j                        \  \  }}}t        j                  | j
                  |d   |d   |z
  dz
  f|d   |z   dz   |d   |z
  dz
  |z   dz   | j                  z   f|d       t        j                  | j
                  ||d| j                  || j                         |S )a  
        Draw workout text with a background on the image.

        Args:
            display_text (str): The text to be displayed.
            position (Tuple[int, int]): Coordinates (x, y) on the image where the text will be placed.
            color (Tuple[int, int, int]): Text background color.
            txt_color (Tuple[int, int, int]): Text foreground color.

        Returns:
            (int): The height of the text.
        r   r   ri   r   rt   r   )r   r   r   r   r   r   r   )rG   r  r  r   r   r   r   _s           rJ   plot_workout_informationz*SolutionAnnotator.plot_workout_information  s    & (+|QRVRYRYeielel'm$![1 	GGa[(1+3a78a[:%*HQK+,E,IK,WZ\,\_c_f_f,fg	
 	DGG\8QDGGTrT   
angle_text
count_text
stage_text
center_kptc                 V   d|dd| d| }}}| j                  |t        |d         t        |d         f||      }| j                  |t        |d         t        |d         |z   dz   f||      }| j                  |t        |d         t        |d         |z   |z   dz   f||       y)	a	  
        Plot the pose angle, count value, and step stage for workout monitoring.

        Args:
            angle_text (str): Angle value for workout monitoring.
            count_text (str): Counts value for workout monitoring.
            stage_text (str): Stage decision for workout monitoring.
            center_kpt (List[int]): Centroid pose index for workout monitoring.
            color (Tuple[int, int, int]): Text background color.
            txt_color (Tuple[int, int, int]): Text foreground color.
        rP   rQ   zSteps : r   ri   r   (   N)r	  ra   )	rG   r
  r  r  r  r   r   angle_heightcount_heights	            rJ   plot_angle_and_count_and_stagez0SolutionAnnotator.plot_angle_and_count_and_stage  s    * 01C0@-AXj\CZ^_`j_k\l
J
 44Z]+SA-?@%
 44Z]+SA-?,-NQS-STV[]f
 	%%Z]+SA-?,-NQ]-]`b-bcejlu	
rT   pixels_distance	centroids
line_colorcentroid_colorc           
      d   d|d}t        j                  |d| j                  | j                        \  \  }}}t        j                  | j
                  dd|z   dz   d|z   dz   f|d       dd|z   d	z   f}	t        j                  | j
                  ||	d| j                  d
| j                  t         j                         t        j                  | j
                  |d   |d   |d       t        j                  | j
                  |d   d|d       t        j                  | j
                  |d   d|d       y)a  
        Plot the distance and line between two centroids on the frame.

        Args:
            pixels_distance (float): Pixels distance between two bbox centroids.
            centroids (List[Tuple[int, int]]): Bounding box centroids data.
            line_color (Tuple[int, int, int]): Distance line color.
            centroid_color (Tuple[int, int, int]): Bounding box centroid color.
        zPixels Distance: rQ   r   )      r  r   r  r   rt   r}   r}   r}   ri   rx      N)
r   r   r   r   r   r   r   r   r   r   )
rG   r  r  r  r  r   text_width_mtext_height_mr  text_positions
             rJ   plot_distance_and_linez(SolutionAnnotator.plot_distance_and_line#  s   " #?3"78+.??4DGGTWW+U(%}q 	dggx"|*;b*@"}BTWYBY)Z\fhjk R-/"45GGGGGGKK		
 	)A,	!j!D

477IaL!^R@

477IaL!^R@rT   x_centery_centerc                 T   t        j                  |d| j                  | j                        d   }||d   dz  z
  }	||d   dz  z   }
|	|z
  }|
|d   z
  |z
  }|	|d   z   |z   }|
|z   }t        j                  |t        |      t        |      ft        |      t        |      ft        t        t
        |            d       t        j                  ||t        |	      t        |
      fd| j                  t        t        t
        |            | j                  t         j                         y)aA  
        Display the bounding boxes labels in parking management app.

        Args:
            im0 (np.ndarray): Inference image.
            text (str): Object/class name.
            txt_color (Tuple[int, int, int]): Display color for text foreground.
            bg_color (Tuple[int, int, int]): Display color for text background.
            x_center (float): The x position center point for bounding box.
            y_center (float): The y position center point for bounding box.
            margin (int): The gap between text and rectangle for better display.
        r   r   rh   ri   r   r   N)
r   r   r   r   r   ra   rm   mapr   r   )rG   rU   r   r   r   r   r!  r   r   r   r   r   r   r   r   s                  rJ   display_objects_labelsz(SolutionAnnotator.display_objects_labelsK  s   , OOD!tww$''RSTU	IaLA--IaLA--6/9Q<'&09Q<'&06/\3w<(\3w<(#c8$%	
 	[#f+&GG#c9%&GG[[		
rT   line_xline_yc           	      D   t        j                  | j                  |df||f|| j                  dz         |rt        j                  |t         j
                  | j                  | j                        \  \  }}}t        j                  | j                  ||dz  z
  dz
  |dz  |dz  z
  dz
  f||dz  z   dz   |dz  |dz  z   dz   f|d       t        j                  | j                  |||dz  z
  |dz  |dz  z   ft         j
                  | j                  || j                         yy)a  
        Draw a sweep annotation line and an optional label.

        Args:
            line_x (int): The x-coordinate of the sweep line.
            line_y (int): The y-coordinate limit of the sweep line.
            label (str, optional): Text label to be drawn in center of sweep line. If None, no label is drawn.
            color (Tuple[int, int, int]): RGB color for the line and label background.
            txt_color (Tuple[int, int, int]): RGB color for the label text.
        r   rh   rt   r   N)	r   r   r   r   r   FONT_HERSHEY_SIMPLEXr   r   r   )	rG   r%  r&  r   r   r   r   r   r  s	            rJ   sweep_annotatorz!SolutionAnnotator.sweep_annotator|  s'   & 	61+'7!L +.??5#BZBZ\`\c\ceielel+m(%ZqMM*/)B.!kQ>N0NQS0ST*/)B.!kQ>N0NQS0ST KK*/)6Q;9I+IJ(( rT   rq   center_point	pin_colorc                 z   t        |d   |d   z   dz        t        |d   |d   z   dz        f}t        j                  | j                  || j                  dz  |d       t        j                  | j                  || j                  dz  |d       t        j
                  | j                  |||| j                         y)a  
        Perform pinpoint human-vision eye mapping and plotting.

        Args:
            box (List[float]): Bounding box coordinates in format [x1, y1, x2, y2].
            center_point (Tuple[int, int]): Center point for vision eye view.
            color (Tuple[int, int, int]): Object centroid and line color.
            pin_color (Tuple[int, int, int]): Visioneye point color.
        r   rh   ri   rx   r   N)ra   r   r   r   r   r   )rG   rq   r*  r   r+  center_bboxs         rJ   	visioneyezSolutionAnnotator.visioneye  s      3q6CF?a/0#s1vA!6K2LL

477L$''A+y"E

477K1eR@,UDGGDrT   c                    t        |      dkD  r't        j                  dt        |       d       |dd }t        |d   |d   z   dz        t        |d   |d   z   dz        }}t	        j
                  t        |      t        j                  | j                  dz
  | j                        d   }t        |d   dz  |d   dz  z   d	z  dz        |z   }	t	        j                  | j                  ||f|	|d
       ||d   dz  z
  }
||d   dz  z   }t	        j                  | j                  t        |      |
|ft        j                  | j                  dz
  | j                  ||      | j                  t        j                         y)a  
        Draw a label with a background circle centered within a given bounding box.

        Args:
            box (Tuple[float, float, float, float]): The bounding box coordinates (x1, y1, x2, y2).
            label (str): The text label to be displayed.
            color (Tuple[int, int, int]): The background color of the circle (B, G, R).
            txt_color (Tuple[int, int, int]): The color of the text (R, G, B).
            margin (int): The margin between the text and the circle border.
        rx   zLength of label is z:, only first 3 letters will be used for circle annotation.Nr   rh   ri   g333333?g      ?r   r   )ro   r   r@   ra   r   r   r   r(  r   r   r   r   r   get_txt_colorr   )rG   rq   r   r   r   r   r   r!  r   required_radiusr   r   s               rJ   circle_labelzSolutionAnnotator.circle_label  sj   $ u:>NN0U<vwx"1IE !#a&3q6/Q!67c!fs1voQR=R9S(OOCJ0H0H$''TX.Z^ZaZabcde		! 1IaLA4E E#MQRRSV\\

477Xx0/5"MIaLA--IaLA--GGJV$$GGdNui0GG[[		
rT   c                 r   t        |d   |d   z   dz        t        |d   |d   z   dz        }}t        j                  |t        j                  | j                  dz
  | j
                        d   }||d   dz  z
  }	||d   dz  z   }
|	|z
  }|
|d   z
  |z
  }|	|d   z   |z   }|
|z   }t        j                  | j                  ||f||f|d       t        j                  | j                  ||	|
ft        j                  | j                  dz
  | j                  ||      | j
                  t        j                         y)	a  
        Draw a label with a background rectangle centered within a given bounding box.

        Args:
            box (Tuple[float, float, float, float]): The bounding box coordinates (x1, y1, x2, y2).
            label (str): The text label to be displayed.
            color (Tuple[int, int, int]): The background color of the rectangle (B, G, R).
            txt_color (Tuple[int, int, int]): The color of the text (R, G, B).
            margin (int): The margin between the text and the rectangle border.
        r   rh   ri   rx   g?r   r   N)ra   r   r   r(  r   r   r   r   r   r0  r   )rG   rq   r   r   r   r   r   r!  r   r   r   r   r   r   r   s                  rJ   
text_labelzSolutionAnnotator.text_label  s9   & !#a&3q6/Q!67c!fs1voQR=R9S(OOE3+C+CTWWs]TXT[T[\]^_	IaLA--IaLA--6/9Q<'&09Q<'&06/dgg1GW3EubQGGV$$GGcMui0GG[[		
rT   )NNz	Arial.ttfFabc)Nr   r   )Nr  )r   r   r   )Nrh   g      ?)h         r  )r6  r}   r   r}   )r   r   N)   r      r  ))         r:  )rO      rA  rA  r  rh   )rO   r@  r  r   ) r   r   r   r   r   r   r   ra   r   r   rK   r   r	   r   r   r   r   r   staticmethodr   r   r   r  r	  r  r  r$  r)  r.  r2  r4  __classcell__)r   s   @rJ   r   r     s   $R %)#'HJJH SMH C=	H
 H H H0 48&1	P$uS#X/0P S#s]#P 	P. 37-<*3,
,
 eCHo./,
 CcM*	,

 c3',
\"$ZZ"$ 38n"$ c3'	"$
 S#&"$ "$H s:tE{ :tE{ :tE{ :u :  :& (,!"U$" $s)$" 	"
 " 
"P '4*9   S/  S#s]#	 
 c3'  
 P '4*9 
 
  
 	 

 I 
 S#s]# 
 c3' 
L ,9/<&A&A c3h(&A #sC-(	&A
 c3m,&AP/
ZZ/
 /
 c3'	/

 S#&/
 /
 /
 /
f #&3*9'' ' }	'
 S#s]#' c3''Z '5*7E%[E CHoE S#s]#	E
 c3'E0 &5*9+
5%-.+
 +
 S#s]#	+

 c3'+
 +
` &5*9*
5%-.*
 *
 S#s]#	*

 c3'*
 *
rT   r   c                   "    e Zd ZdZd ZdefdZy)SolutionResultsaG  
    A class to encapsulate the results of Ultralytics Solutions.

    This class is designed to store and manage various outputs generated by the solution pipeline, including counts,
    angles, workout stages, and other analytics data. It provides a structured way to access and manipulate results
    from different computer vision solutions such as object counting, pose estimation, and tracking analytics.

    Attributes:
        plot_im (np.ndarray): Processed image with counts, blurred, or other effects from solutions.
        in_count (int): The total number of "in" counts in a video stream.
        out_count (int): The total number of "out" counts in a video stream.
        classwise_count (Dict[str, int]): A dictionary containing counts of objects categorized by class.
        queue_count (int): The count of objects in a queue or waiting area.
        workout_count (int): The count of workout repetitions.
        workout_angle (float): The angle calculated during a workout exercise.
        workout_stage (str): The current stage of the workout.
        pixels_distance (float): The calculated distance in pixels between two points or objects.
        available_slots (int): The number of available slots in a monitored area.
        filled_slots (int): The number of filled slots in a monitored area.
        email_sent (bool): A flag indicating whether an email notification was sent.
        total_tracks (int): The total number of tracked objects.
        region_counts (Dict[str, int]): The count of objects within a specific region.
        speed_dict (Dict[str, float]): A dictionary containing speed information for tracked objects.
        total_crop_objects (int): Total number of cropped objects using ObjectCropper class.
        speed (Dict[str, float]): Performance timing information for tracking and solution processing.
    c                 (   d| _         d| _        d| _        i | _        d| _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        d| _        i | _        i | _        d| _        i | _        | j"                  j%                  |       y)z
        Initialize a SolutionResults object with default or user-specified values.

        Args:
            **kwargs (Any): Optional arguments to override default attribute values.
        Nr           F)rz   in_count	out_countclasswise_countqueue_countworkout_countworkout_angleworkout_stager  available_slotsfilled_slots
email_senttotal_tracksregion_counts
speed_dicttotal_crop_objectsr   __dict__r/   )rG   r   s     rJ   rK   zSolutionResults.__init__0  s     ! !" "#
 	V$rT   r   c           
          | j                   j                         D ci c]  \  }}|dk7  r|di dddfvr|| }}}dj                  d |j                         D              S c c}}w )z
        Return a formatted string representation of the SolutionResults object.

        Returns:
            (str): A string representation listing non-null attributes.
        rz   Nr   rG  Fr   c              3   0   K   | ]  \  }}| d |   yw)=Nr-   ).0rH   vs      rJ   	<genexpr>z*SolutionResults.__str__.<locals>.<genexpr>X  s     >1A3as>s   )rV  r   join)rG   rH   r[  attrss       rJ   __str__zSolutionResults.__str__L  sq     ++-
1I~!D"ae+D"D qD
 

 yy>>>>
s   A"N)r   r   r   r   rK   r   r_  r-   rT   rJ   rE  rE    s    6%8? ?rT   rE  )r   collectionsr   	functoolsr   typingr   r   r   r   r	   r   numpyr   ultralyticsr
   ultralytics.solutions.configr   ultralytics.utilsr   r   r   ultralytics.utils.checksr   r   ultralytics.utils.plottingr   r   r   rE  r-   rT   rJ   <module>ri     sV     #  3 3 
   7 5 5 E 0q qhK
	 K
\D? D?rT   