o
    Whj                     @   s@   d dl mZmZmZ d dlmZ d dlmZ G dd deZdS )    )BaseSolutionSolutionAnnotatorSolutionResults)LOGGER)colorsc                       s:   e Zd ZdZ fddZdd ZdddZd	d
 Z  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)
    c                    s:   t  jdi | d| _| jd | _d| _d| _d| _dS )z
        Initialize 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)selfkwargs	__class__r
   X/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/security_alarm.pyr   #   s   
zSecurityAlarm.__init__c                 C   s<   ddl }|d| _| j  | j|| || _|| _dS )a#  
        Authenticate the email server for sending alert notifications.

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

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

        Examples:
            >>> alarm = SecurityAlarm()
            >>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com")
        r   Nzsmtp.gmail.com: 587)smtplibSMTPr   starttlsloginr   r   )r   r   passwordr   r   r
   r
   r   authenticate1   s   

zSecurityAlarm.authenticate   c              
   C   s   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d}
||
 z| j| td W dS  tyr } ztd|  W Y d}~dS d}~ww )ax  
        Send an email notification with an image attachment indicating the number of objects detected.

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

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

        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 objects have been detected!!zultralytics.jpg)nameu   ✅ 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    r)   	img_bytesmessagemessage_bodyimage_attachmenter
   r
   r   
send_emailH   s(   


zSecurityAlarm.send_emailc                 C   s   |  | t|| jd}t| j| jD ]\}}|j|| j| t|dd qt	| j}|| j
kr<| js<| || d| _| }| | t|t	| j| jdS )aQ  
        Monitor the frame, process object detections, and trigger alerts if thresholds are exceeded.

        Args:
            im0 (numpy.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).

        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 surpasses the specified threshold and an alert has not
        already been sent.

        Examples:
            >>> alarm = SecurityAlarm()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> results = alarm.process(frame)
        )
line_widthT)labelcolor)plot_imtotal_tracksr   )extract_tracksr   r8   zipboxesclss	box_labelnamesr   lenr   r   r7   resultdisplay_outputr   	track_ids)r   r1   	annotatorboxcls	total_detr;   r
   r
   r   processu   s   


zSecurityAlarm.process)r   )	__name__
__module____qualname____doc__r   r   r7   rK   __classcell__r
   r
   r   r   r      s    
-r   N)	ultralytics.solutions.solutionsr   r   r   ultralytics.utilsr   ultralytics.utils.plottingr   r   r
   r
   r
   r   <module>   s   