U
    ZhI                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	 ddl
mZmZmZ ddlmZmZ ddlmZmZmZmZmZ dd	lZdd	lZG d
d deeZG dd deeZG dd deeeZG dd deeZd	S )a#  
Jingle Detection Models for Stream Processor Application

This module contains Django models for managing jingle detection,
ad break analysis, and related functionality. These models handle
the storage and management of jingle templates, detection results,
and ad break timing information.
    )models)User)timezone)MinValueValidatorMaxValueValidator)TimestampedModel	UUIDModelStatusModel)StreamSession
HLSSegment)validate_file_pathvalidate_slug_formatvalidate_name_formatvalidate_confidence_scorevalidate_template_contentNc                	   @   s   e Zd ZdZejddegddZejdde	gddZ
ejdddZejd	egd
dZejdegddZejddddZejddddddddgdddZejdejdddddZejeejd d!d"ZG d#d$ d$Zd%d& Zd'd( Zd)d* Zd+d, Zd-S ).JingleTemplatea6  
    Model representing a jingle template for detection.
    
    Jingle templates are reference images or video frames that are used
    to identify specific jingles in stream content. Each template represents
    a unique jingle that can be detected during stream processing.
    
    Attributes:
        name (CharField): Human-readable name for the jingle
        slug (SlugField): URL-friendly identifier
        description (TextField): Description of the jingle content
        image_path (CharField): Path to the reference image file
        similarity_threshold (FloatField): Threshold for detection matching
        is_active (BooleanField): Whether this template is active
        category (CharField): Category classification for the jingle
        created_by (ForeignKey): User who uploaded this template
    d   Tz"Human-readable name for the jingle)
max_lengthunique
validators	help_textz&URL-friendly identifier for the jinglez-Description of the jingle content and contextblankr     z0Path to the reference image file for this jingle)r   r   r   g?z5Similarity threshold for positive detection (0.0-1.0))defaultr   r   z4Whether this jingle template is active for detectionr   db_indexr   2   )Zad_startzAdvertisement Start)Zad_endzAdvertisement End)Zprogram_startzProgram Start)Zprogram_endzProgram End)Z
transitionZ
Transition)ZbrandingzChannel Branding)otherOtherr   z'Category classification for this jingler   choicesr   r   zstreams.ChannelZjingle_templatesz'Channel this jingle template belongs to	on_deleterelated_namenullr   r   Zcreated_jingle_templatesz&User who uploaded this jingle templater#   r$   r   c                   @   sD   e Zd ZdZdZddgZejdgdejdgdejdgdgZdS )	zJingleTemplate.MetazJingle TemplatezJingle Templatescategorynameslugfields	is_activeN	__name__
__module____qualname__verbose_nameverbose_name_pluralorderingr   Indexindexes r6   r6   7/var/www/html/JingleDetector/src/apps/jingles/models.pyMetau   s   r8   c                 C   s   | j  d| j dS )z-String representation of the jingle template. ())r(   r'   selfr6   r6   r7   __str__   s    zJingleTemplate.__str__c                 C   s   t j| jS )z1Check if the reference image file exists on disk.)ospathexists
image_pathr;   r6   r6   r7   image_exists   s    zJingleTemplate.image_existsc                 C   s,   zt j| jW S  tk
r&   Y dS X dS )z)Get the size of the reference image file.N)r>   r?   getsizerA   OSErrorr;   r6   r6   r7   get_image_size   s    zJingleTemplate.get_image_sizec                 C   s>   z$t j| jr"t | j W dS W n tk
r8   Y nX dS )z*Delete the reference image file from disk.TF)r>   r?   r@   rA   removerD   r;   r6   r6   r7   delete_image   s    
zJingleTemplate.delete_imageN)r.   r/   r0   __doc__r   	CharFieldr   r(   	SlugFieldr   r)   	TextFielddescriptionr   rA   
FloatFieldr   Zsimilarity_thresholdBooleanFieldr,   r'   
ForeignKeyCASCADEchannelr   
created_byr8   r=   rB   rE   rG   r6   r6   r6   r7   r      s   	

r   c                   @   s   e Zd ZdZejeejdddZeje	ejdddZ
ejeejdddZejeded	gd
dZejdddZejdddZejedgddZejddddZejedddZG dd dZdd Zdd Zdd Zd d! Zd"S )#JingleDetectionaO  
    Model representing a detected jingle instance.
    
    This model records when a jingle has been detected in a stream,
    including the confidence score, frame information, and associated
    segment data.
    
    Attributes:
        session (ForeignKey): Stream session where detection occurred
        segment (ForeignKey): HLS segment containing the detection
        template (ForeignKey): Jingle template that was matched
        confidence_score (FloatField): Confidence level of the detection
        frame_path (CharField): Path to the extracted frame image
        detection_time (DateTimeField): When the detection occurred
        frame_timestamp (FloatField): Timestamp within the segment
        is_confirmed (BooleanField): Whether detection has been confirmed
        metadata (JSONField): Additional detection metadata
    Zjingle_detectionsz,Stream session where this detection occurredr&   z%HLS segment containing this detection
detectionsz Jingle template that was matched              ?z+Confidence level of the detection (0.0-1.0))r   r   r   z!Path to the extracted frame imager   r   Tz When the detection was processed)auto_now_addr   z5Timestamp within the segment where detection occurredFz2Whether this detection has been manually confirmedr   z2Additional detection metadata and analysis resultsr   r   r   c                   @   sR   e Zd ZdZdZdgZejddgdejddgdejdgdejd	gdgZd
S )zJingleDetection.MetazJingle DetectionzJingle Detections-detection_timesessiondetection_timer*   templateis_confirmedconfidence_scoreNr-   r6   r6   r6   r7   r8      s   r8   c                 C   s    | j j d| jdd| j dS )z.String representation of the jingle detection. - z.3fr9   r:   )r]   r(   r_   r\   r;   r6   r6   r7   r=      s    zJingleDetection.__str__c                 C   s   t j| jS )z1Check if the extracted frame file exists on disk.)r>   r?   r@   
frame_pathr;   r6   r6   r7   frame_exists   s    zJingleDetection.frame_existsc                 C   s   dt j| j S )z*Get URL for accessing the extracted frame.z/media/frames/)r>   r?   basenamera   r;   r6   r6   r7   get_frame_url   s    zJingleDetection.get_frame_urlc                 C   s>   z$t j| jr"t | j W dS W n tk
r8   Y nX dS )z*Delete the extracted frame file from disk.TF)r>   r?   r@   ra   rF   rD   r;   r6   r6   r7   delete_frame   s    
zJingleDetection.delete_frameN) r.   r/   r0   rH   r   rO   r
   rP   r[   r   segmentr   r]   rM   r   r   r_   rI   ra   DateTimeFieldr\   Zframe_timestamprN   r^   	JSONFielddictmetadatar8   r=   rb   rd   re   r6   r6   r6   r7   rS      sd   rS   c                       s  e Zd ZdZejeejdddZej	dddZ
ej	dd	d
dgdddZejeejdddddZejeejdddddZejddZejddddZejddededgddZejddddZejedd d!Zejdd"d#ZG d$d% d%Zd&d' Zd(d) Zd*d+ Z  fd,d-Z!  Z"S ).AdBreaka  
    Model representing a detected advertisement break.
    
    Ad breaks are identified by pairs of jingle detections (start and end)
    and represent commercial interruptions in the stream content.
    
    Attributes:
        session (ForeignKey): Stream session containing the ad break
        channel_name (CharField): Channel identifier for external APIs
        region (CharField): Geographic region for the ad break
        start_detection (ForeignKey): Jingle detection marking the start
        end_detection (ForeignKey): Jingle detection marking the end
        start_time (DateTimeField): When the ad break started
        end_time (DateTimeField): When the ad break ended
        duration_seconds (PositiveIntegerField): Duration in seconds
        is_sent_to_api (BooleanField): Whether data was sent to external API
        api_response (JSONField): Response from external API
        notes (TextField): Additional notes about the ad break
    Z	ad_breaksz'Stream session containing this ad breakr&   r   z/Channel identifier for external API integrationrW   r   )Netherlandsrl   )Francerm   )Globalrn   rn   z#Geographic region for this ad breakr    Zad_breaks_startedTz7Jingle detection that marked the start of this ad breakr"   Zad_breaks_endedz5Jingle detection that marked the end of this ad breakz$When the advertisement break started)r   z"When the advertisement break endedr%   r   r      i  z#Duration of the ad break in secondsr%   r   r   r   Fz3Whether this ad break data was sent to external APIr   z%Response data from external API callsrY   z4Additional notes or observations about this ad breakr   c                   @   sR   e Zd ZdZdZdgZejddgdejddgdejd	gdejd
gdgZdS )zAdBreak.MetazAdvertisement BreakzAdvertisement Breaksz-start_timer[   
start_timer*   channel_nameregionis_sent_to_apistatusNr-   r6   r6   r6   r7   r8   q  s   r8   c                 C   s4   | j rd| j  dnd}| j d| jd | S )z&String representation of the ad break.r9   zs) r`   z%H:%M:%S)duration_secondsrs   rr   strftime)r<   Zduration_strr6   r6   r7   r=   |  s    zAdBreak.__str__c                 C   s(   | j r$| jr$| j| j  }t| S dS )z'Calculate the duration of the ad break.N)rr   end_timeinttotal_seconds)r<   deltar6   r6   r7   calculate_duration  s    zAdBreak.calculate_durationc                 C   s   | j dk	o| jdk	S )z3Check if the ad break has both start and end times.N)rr   rz   r;   r6   r6   r7   is_complete  s    zAdBreak.is_completec                    s*   |   r| js|  | _t j|| dS )z2Override save to automatically calculate duration.N)r   rx   r~   supersave)r<   argskwargs	__class__r6   r7   r     s    
zAdBreak.save)#r.   r/   r0   rH   r   rO   r
   rP   r[   rI   rs   rt   rS   Zstart_detectionZend_detectionrg   rr   rz   PositiveIntegerFieldr   r   rx   rN   ru   rh   ri   Zapi_responserK   Znotesr8   r=   r~   r   r   __classcell__r6   r6   r   r7   rk     s   	
rk   c                   @   s  e Zd ZdZejeejdddZeje	ejdddZ
ejddd	Zejdd
d	Zejddd	ZejddededgddZejddededgddZejddededgddZejddedgddZejddddZG dd dZdd Zdd Zdd Zdd Zd S )!DetectionStatisticsa  
    Model for tracking jingle detection statistics and metrics.
    
    This model aggregates detection data for reporting and analysis,
    providing insights into detection accuracy, frequency, and performance.
    
    Attributes:
        session (ForeignKey): Stream session for these statistics
        template (ForeignKey): Jingle template for these statistics
        total_detections (PositiveIntegerField): Total number of detections
        confirmed_detections (PositiveIntegerField): Number of confirmed detections
        false_positives (PositiveIntegerField): Number of false positive detections
        avg_confidence (FloatField): Average confidence score
        min_confidence (FloatField): Minimum confidence score
        max_confidence (FloatField): Maximum confidence score
        detection_rate (FloatField): Detections per hour
        last_detection (DateTimeField): Time of last detection
    Zdetection_statisticsz#Stream session for these statisticsr&   
statisticsz$Jingle template for these statisticsr   z,Total number of detections for this template)r   r   z'Number of manually confirmed detectionsz.Number of identified false positive detectionsTrU   rV   z+Average confidence score for all detectionsrq   z!Minimum confidence score recordedz!Maximum confidence score recordedzNumber of detections per hourz&Timestamp of the most recent detectionro   c                   @   s@   e Zd ZdZdZddgZdgZejddgdejdgdgZ	dS )zDetectionStatistics.MetazDetection Statisticsr[   r]   z-last_detectionr*   last_detectionN)
r.   r/   r0   r1   r2   unique_togetherr3   r   r4   r5   r6   r6   r6   r7   r8     s   r8   c                 C   s   | j j d| j dS )z2String representation of the detection statistics.r`   z detections)r]   r(   total_detectionsr;   r6   r6   r7   r=     s    zDetectionStatistics.__str__c                 C   s   | j dkr| j| j  d S dS )zBCalculate the accuracy rate as percentage of confirmed detections.r   r   )r   confirmed_detectionsr;   r6   r6   r7   accuracy_rate  s    
z!DetectionStatistics.accuracy_ratec                 C   s   | j dkr| j| j  d S dS )z0Calculate the false positive rate as percentage.r   r   )r   false_positivesr;   r6   r6   r7   false_positive_rate  s    
z'DetectionStatistics.false_positive_ratec                 C   s   t jj| j| jd}| | _|jdd | _| jdkr|jddd}t	|t
| | _t|| _t|| _|d }|r|j| _|   dS )	z7Recalculate statistics based on current detection data.)r[   r]   T)r^   r   r_   )flatrZ   N)rS   objectsfilterr[   r]   countr   r   values_listsumlenavg_confidenceminmin_confidencemaxmax_confidenceorder_byfirstr\   r   r   )r<   rT   Zconfidence_scoresZlatest_detectionr6   r6   r7   update_statistics  s    



z%DetectionStatistics.update_statisticsN)r.   r/   r0   rH   r   rO   r
   rP   r[   r   r]   r   r   r   r   rM   r   r   r   r   r   Zdetection_raterg   r   r8   r=   r   r   r   r6   r6   r6   r7   r     sv   
r   )rH   	django.dbr   django.contrib.auth.modelsr   django.utilsr   django.core.validatorsr   r   Zapps.core.modelsr   r   r	   Zapps.streams.modelsr
   r   apps.core.validatorsr   r   r   r   r   r>   jsonr   rS   rk   r   r6   r6   r6   r7   <module>   s   	 r 	