
    j=                     N    d dl mZ d dlmZ d dlmZmZmZ  G d de          ZdS )    )defaultdict)Any)BaseSolutionSolutionAnnotatorSolutionResultsc                   8     e Zd ZdZdeddf fdZdefdZ xZS )AIGyma@  A class to manage gym steps of people in a real-time video stream based on their poses.

    This class extends BaseSolution to monitor workouts using YOLO pose estimation models. It tracks and counts
    repetitions of exercises based on predefined angle thresholds for up and down positions.

    Attributes:
        states (dict[int, dict[str, float | int | str]]): Per-track angle, rep count, and stage for workout monitoring.
        up_angle (float): Angle threshold for considering the 'up' position of an exercise.
        down_angle (float): Angle threshold for considering the 'down' position of an exercise.
        kpts (list[int]): Indices of keypoints used for angle calculation.

    Methods:
        process: Process a frame to detect poses, calculate angles, and count repetitions.

    Examples:
        >>> gym = AIGym(model="yolo26n-pose.pt")
        >>> image = cv2.imread("gym_scene.jpg")
        >>> results = gym.process(image)
        >>> processed_image = results.plot_im
        >>> cv2.imshow("Processed Image", processed_image)
        >>> cv2.waitKey(0)
    kwargsreturnNc                 6   |                     dd          |d<    t                      j        di | t          d           | _        t          | j        d                   | _        t          | j        d                   | _        | j        d         | _	        dS )	a  Initialize AIGym for workout monitoring using pose estimation and predefined angles.

        Args:
            **kwargs (Any): Keyword arguments passed to the parent class constructor including:
                - model (str): Model name or path, defaults to "yolo26n-pose.pt".
        modelzyolo26n-pose.ptc                      ddddS )Nr   -)anglecountstage r       a/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/solutions/ai_gym.py<lambda>z AIGym.__init__.<locals>.<lambda>*   s    AC*P*P r   up_angle
down_anglekptsNr   )
getsuper__init__r   statesfloatCFGr   r   r   )selfr
   	__class__s     r   r   zAIGym.__init__!   s     !**W.?@@w""6"""!"P"PQQ dhz233 677HV$			r   c                    t          || j                  }|                     |           t          | j                  r| j        j        j        }t          |          D ]\  }| j	        | j
        |                  } |j        fd| j        D              |d<   |                    | j        | j        dz             |d         | j        k     r"|d         dk    r|dxx         d	z  cc<   d
|d<   n|d         | j        k    rd|d<   | j        rI|                    |d         |d         |d         t%          | j        d	                                       |                                }|                     |           t+          |d | j	                                        D             d | j	                                        D             d | j	                                        D             t          | j
                            S )a[  Monitor workouts using Ultralytics YOLO Pose Model.

        This function processes an input image to track and analyze human poses for workout monitoring. It uses the YOLO
        Pose model to detect keypoints, estimate angles, and count repetitions based on predefined angle thresholds.

        Args:
            im0 (np.ndarray): Input image for processing.

        Returns:
            (SolutionResults): Contains processed image `plot_im`, 'workout_count' (list of completed reps),
                'workout_stage' (list of current stages), 'workout_angle' (list of angles), and 'total_tracks' (total
                number of tracked individuals).

        Examples:
            >>> gym = AIGym()
            >>> image = cv2.imread("workout.jpg")
            >>> results = gym.process(image)
            >>> processed_image = results.plot_im
        )
line_widthc                 :    g | ]}t          |                   S r   )int).0idxks     r   
<listcomp>z!AIGym.process.<locals>.<listcomp>O   s$    @b@b@bQT3s88@b@b@br   r      )radiusr   upr      down)
angle_text
count_text
stage_text
center_kptc                     g | ]
}|d          S )r   r   r&   vs     r   r)   z!AIGym.process.<locals>.<listcomp>h       DDD!1W:DDDr   c                     g | ]
}|d          S )r   r   r4   s     r   r)   z!AIGym.process.<locals>.<listcomp>i   r6   r   c                     g | ]
}|d          S )r   r   r4   s     r   r)   z!AIGym.process.<locals>.<listcomp>j   r6   r   )plot_imworkout_countworkout_stageworkout_angletotal_tracks)r   r#   extract_trackslenboxestracks	keypointsdata	enumerater   	track_idsestimate_pose_angler   draw_specific_kptsr   r   show_labelsplot_angle_and_count_and_stager%   resultdisplay_outputr   values)r    im0	annotatorkpt_dataistater9   r(   s          @r   processzAIGym.process1   s)   ( &cdoFFF	C   tz?? 	{,1H!(++  1DN1$56!>!>@b@b@b@bX\Xa@b@b@b!cg,,Q	$/TUBU,VVV >DO33W~--g!+%+E'NN7^dm33%)E'N # <<#(>#(>#(>#$S1%6%6#7	 =    ""$$G$$$ DDt{/A/A/C/CDDDDDt{/A/A/C/CDDDDDt{/A/A/C/CDDDT^,,
 
 
 	
r   )	__name__
__module____qualname____doc__r   r   r   rR   __classcell__)r!   s   @r   r	   r	   	   sp         .% % % % % % % % ;
o ;
 ;
 ;
 ;
 ;
 ;
 ;
 ;
r   r	   N)	collectionsr   typingr   ultralytics.solutions.solutionsr   r   r   r	   r   r   r   <module>r[      s    $ # # # # #       \ \ \ \ \ \ \ \ \ \c
 c
 c
 c
 c
L c
 c
 c
 c
 c
r   