
    j                     Z    d dl mZ d dlmZmZmZ d dlmZ d dlm	Z	  G d de          Z
dS )    )Any)BaseSolutionSolutionAnnotatorSolutionResults)LOGGER)colorsc                   b     e Zd ZdZdeddf fdZdedededdfd	ZddeddfdZ	de
fdZ xZS )SecurityAlarma  A class to manage security alarm functionalities for real-time monitoring.

    This class extends the BaseSolution class and provides features to monitor objects in a frame, send email
    notifications when specific thresholds are exceeded for total detections, and annotate the output frame for
    visualization.

    Attributes:
        email_sent (bool): Flag to track if an email has already been sent for the current event.
        records (int): Threshold for the number of detected objects to trigger an alert.
        server (smtplib.SMTP): SMTP server connection for sending email alerts.
        to_email (str): Recipient's email address for alerts.
        from_email (str): Sender's email address for alerts.

    Methods:
        authenticate: Set up email server authentication for sending alerts.
        send_email: Send an email notification with details and an image attachment.
        process: Monitor the frame, process detections, and trigger alerts if thresholds are crossed.

    Examples:
        >>> security = SecurityAlarm()
        >>> security.authenticate("abc@gmail.com", "1111222233334444", "xyz@gmail.com")
        >>> frame = cv2.imread("frame.jpg")
        >>> results = security.process(frame)
    kwargsreturnNc                      t                      j        di | d| _        | j        d         | _        d| _        d| _        d| _        dS )zInitialize the SecurityAlarm class with parameters for real-time object monitoring.

        Args:
            **kwargs (Any): Additional keyword arguments passed to the parent class.
        FrecordsN  )super__init__
email_sentCFGr   serverto_email
from_email)selfr   	__class__s     i/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/solutions/security_alarm.pyr   zSecurityAlarm.__init__$   sP     	""6"""x	*    r   passwordr   c                     ddl }|                    dd          | _        | j                                         | j                            ||           || _        || _        dS )a  Authenticate the email server for sending alert notifications.

        This method initializes a secure connection with the SMTP server and logs in using the provided credentials.

        Args:
            from_email (str): Sender's email address.
            password (str): Password for the sender's email account.
            to_email (str): Recipient's email address.

        Examples:
            >>> alarm = SecurityAlarm()
            >>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com")
        r   Nzsmtp.gmail.comiK  )smtplibSMTPr   starttlsloginr   r   )r   r   r   r   r   s        r   authenticatezSecurityAlarm.authenticate1   sa     	ll#3S99*h/// $r      r   c                    ddl m} ddlm} ddlm} ddl}|                    d|          d                                         } |            }| j	        |d<   | j
        |d	<   d
|d<   d| d}	|                     ||	                      ||d          }
|                    |
           	 | j                            |           t          j        d           dS # t           $ r"}t          j        d|            Y d}~dS d}~ww xY w)av  Send an email notification with an image attachment indicating the number of objects detected.

        This method encodes the input image, composes the email message with details about the detection, and sends it
        to the specified recipient.

        Args:
            im0 (np.ndarray): The input image or frame to be attached to the email.
            records (int, optional): The number of detected objects to be included in the email message.

        Examples:
            >>> alarm = SecurityAlarm()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> alarm.send_email(frame, records=10)
        r   )	MIMEImage)MIMEMultipart)MIMETextNz.jpg   FromTozSecurity AlertSubjectzUltralytics alert: z object(s) detected.zultralytics.jpg)namezEmail sent successfully!zFailed to send email: )email.mime.imager%   email.mime.multipartr&   email.mime.textr'   cv2imencodetobytesr   r   attachr   send_messager   info	Exceptionerror)r   im0r   r%   r&   r'   r0   	img_bytesmessagemessage_bodyimage_attachmentes               r   
send_emailzSecurityAlarm.send_emailG   sj    	/.....666666,,,,,,


LL--a088::	  -///-	 KWJJJxx--... %9Y5FGGG'(((	7K$$W---K233333 	7 	7 	7L5!55666666666	7s   /.C 
D)DDc           	      $   |                      |           t          || j                  }t          | j        | j                  D ]6\  }}|                    || j        |         t          |d                     7t          | j                  }|| j
        k    r$| j        s|                     ||           d| _        |                                }|                     |           t          |t          | j                  | j                  S )aG  Monitor the frame, process object detections, and trigger alerts if thresholds are met.

        This method processes the input frame, extracts detections, annotates the frame with bounding boxes, and sends
        an email notification if the number of detected objects meets or exceeds the specified threshold and an alert
        has not already been sent.

        Args:
            im0 (np.ndarray): The input image or frame to be processed and annotated.

        Returns:
            (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (total number of tracked objects) and
                'email_sent' (whether an email alert was triggered).

        Examples:
            >>> alarm = SecurityAlarm()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> results = alarm.process(frame)
        )
line_widthT)labelcolor)plot_imtotal_tracksr   )extract_tracksr   r@   zipboxesclss	box_labelnamesr   lenr   r   r>   resultdisplay_outputr   	track_ids)r   r8   	annotatorboxcls	total_detrC   s          r   processzSecurityAlarm.processs   s   & 	C   %cdoFFF	 DJ	22 	U 	UHC4:c?&dBSBSTTTT	NN	$$T_$OOC+++"DO""$$G$$$ wS=P=P]a]lmmmmr   )r#   )__name__
__module____qualname____doc__r   r   strr"   intr>   r   rS   __classcell__)r   s   @r   r
   r
   
   s         2       %s %c %S %T % % % %,*7 *7s *74 *7 *7 *7 *7X$no $n $n $n $n $n $n $n $nr   r
   N)typingr   ultralytics.solutions.solutionsr   r   r   ultralytics.utilsr   ultralytics.utils.plottingr   r
   r   r   r   <module>r_      s          \ \ \ \ \ \ \ \ \ \ $ $ $ $ $ $ - - - - - -Mn Mn Mn Mn MnL Mn Mn Mn Mn Mnr   