
    hPI                         S r SSKJr  SSKJr  SSKJr  SSKJrJ	r	  SSK
JrJrJr  SSKJrJr  SSKJrJrJrJrJr  SS	KrSS	Kr " S
 S\\5      r " S S\\5      r " S S\\\5      r " S S\\5      rg	)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                      \ rS rSrSr\R                  " SS\/SS9r\R                  " SS\
/SS9r\R                  " SSS	9r\R                  " S
\/SS9r\R                   " S\/SS9r\R&                  " SSSS9r\R                  " S/ SQSSS9r\R,                  " S\R.                  SSS9r\R,                  " \\R.                  SSS9r " S S5      rS rS rS  rS! rS"r g#)$JingleTemplate   a  
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   ))ad_startzAdvertisement Start)ad_endzAdvertisement End)program_startzProgram Start)program_endzProgram End)
transition
Transition)brandingzChannel Branding)otherOtherr(   z'Category classification for this jingler   choicesr   r   zstreams.Channeljingle_templatesz'Channel this jingle template belongs to	on_deleterelated_namer   z&User who uploaded this jingle templatec                       \ rS rSrSrSrSS/r\R                  " S/S9\R                  " S/S9\R                  " S/S9/r	S	r
g
)JingleTemplate.Metas   zJingle TemplatezJingle Templatescategorynameslugfields	is_active N__name__
__module____qualname____firstlineno__verbose_nameverbose_name_pluralorderingr   Indexindexes__static_attributes__r9       ?C:\Users\brahi\OneDrive\Desktop\Code\src\apps\jingles\models.pyMetar1   s   sH    (0'LL)LL.LL-
rE   rG   c                 :    U R                    SU R                   S3$ )z-String representation of the jingle template. ())r4   r3   selfs    rF   __str__JingleTemplate.__str__}   s    ))Bt}}oQ//rE   c                 T    [         R                  R                  U R                  5      $ )z1Check if the reference image file exists on disk.)ospathexists
image_pathrK   s    rF   image_existsJingleTemplate.image_exists       ww~~doo..rE   c                 v     [         R                  R                  U R                  5      $ ! [         a     gf = f)z)Get the size of the reference image file.N)rP   rQ   getsizerS   OSErrorrK   s    rF   get_image_sizeJingleTemplate.get_image_size   s0    	77??4??33 		s   (+ 
88c                      [         R                  R                  U R                  5      (       a!  [         R                  " U R                  5        g g! [
         a     gf = f)z*Delete the reference image file from disk.TF)rP   rQ   rR   rS   removerY   rK   s    rF   delete_imageJingleTemplate.delete_image   R    	ww~~doo..		$//* /
   		   AA 
A A r9   N)!r;   r<   r=   r>   __doc__r   	CharFieldr   r4   	SlugFieldr   r5   	TextFielddescriptionr   rS   
FloatFieldr   similarity_thresholdBooleanFieldr8   r3   
ForeignKeyCASCADEchannelr   
created_byrG   rM   rT   rZ   r^   rD   r9   rE   rF   r   r      s=   & ()6	D ():	D ""AK !!&'DJ ",,-.I ##HI 
 ;H  ..';	G ""..':	J
 
0/rE   r   c                      \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " \
\R                  SSS9r\R                  " \\R                  SSS9r\R                  " \" S	5      \" S
5      /SS9r\R$                  " SSS9r\R(                  " SSS9r\R                  " \" S	5      /SS9r\R.                  " SSSS9r\R2                  " \SSS9r " S S5      rS rS rS rS r Sr!g )!JingleDetection   a  
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
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                       \ rS rSrSrSrS/r\R                  " SS/S9\R                  " SS/S9\R                  " S	/S9\R                  " S
/S9/r	Sr
g)JingleDetection.Meta   zJingle DetectionzJingle Detections-detection_timesessiondetection_timer6   templateis_confirmedconfidence_scorer9   Nr:   r9   rE   rF   rG   ry      s_    )1%&LL,< =>LL-= >?LL 01LL!3 45	
rE   rG   c                 j    U R                   R                   SU R                  S SU R                   S3$ )z.String representation of the jingle detection. - z.3frI   rJ   )r~   r4   r   r}   rK   s    rF   rM   JingleDetection.__str__   s7    --$$%S)>)>s(C2dFYFYEZZ[\\rE   c                 T    [         R                  R                  U R                  5      $ )z1Check if the extracted frame file exists on disk.)rP   rQ   rR   
frame_pathrK   s    rF   frame_existsJingleDetection.frame_exists   rV   rE   c                 Z    S[         R                  R                  U R                  5       3$ )z*Get URL for accessing the extracted frame.z/media/frames/)rP   rQ   basenamer   rK   s    rF   get_frame_urlJingleDetection.get_frame_url   s%       0 0 ABCCrE   c                      [         R                  R                  U R                  5      (       a!  [         R                  " U R                  5        g g! [
         a     gf = f)z*Delete the extracted frame file from disk.TF)rP   rQ   rR   r   r]   rY   rK   s    rF   delete_frameJingleDetection.delete_frame   r`   ra   r9   N)"r;   r<   r=   r>   rb   r   rj   r   rk   r|   r   segmentr   r~   rg   r   r   r   rc   r   DateTimeFieldr}   frame_timestampri   r   	JSONFielddictmetadatarG   rM   r   r   r   rD   r9   rE   rF   ro   ro      s<   ( ..(@	G ..(9	G   ..!4	H ((%c*,=c,BC? !!5J ))4N
 ''%c*+IO &&FL FH	
 	
]/D
rE   ro   c            	       D  ^  \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " SSS9r\R                  " S	/ S
QSSS9r\R                  " \\R                  SSSSS9r\R                  " \\R                  SSSSS9r\R                   " SS9r\R                   " SSSS9r\R&                  " SS\" S5      \" S5      /SS9r\R.                  " SSSS9r\R2                  " \SSS 9r\R8                  " SS!S"9r " S# S$5      rS% rS& r S' r!U 4S( jr"S)r#U =r$$ )*AdBreaki	  az  
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
	ad_breaksz'Stream session containing this ad breakr-   r   z/Channel identifier for external API integrationru   r    ))Netherlandsr   )Francer   )Globalr   r   z#Geographic region for this ad breakr*   ad_breaks_startedTz7Jingle detection that marked the start of this ad break)r.   r/   nullr   r   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 callsrw   z4Additional notes or observations about this ad breakr   c                       \ rS rSrSrSrS/r\R                  " SS/S9\R                  " SS	/S9\R                  " S
/S9\R                  " S/S9/r	Sr
g)AdBreak.Metaio  zAdvertisement BreakzAdvertisement Breaksz-start_timer|   
start_timer6   channel_nameregionis_sent_to_apistatusr9   Nr:   r9   rE   rF   rG   r   o  s[    ,4!?LLL 9:LL :;LL!1 23LL
+	
rE   rG   c                     U R                   (       a  SU R                    S3OSnU R                   SU R                  R                  S5       U 3$ )z&String representation of the ad break.rI   zs) r   z%H:%M:%S)duration_secondsr   r   strftime)rL   duration_strs     rF   rM   AdBreak.__str__z  sN    9=9N9ND112"5TV##$C(@(@(L'Ml^\\rE   c                     U R                   (       aC  U R                  (       a2  U R                  U R                   -
  n[        UR                  5       5      $ g)z'Calculate the duration of the ad break.N)r   end_timeinttotal_seconds)rL   deltas     rF   calculate_durationAdBreak.calculate_duration  s8    ??t}}MMDOO3Eu**,--rE   c                 H    U R                   SL=(       a    U R                  SL$ )z3Check if the ad break has both start and end times.N)r   r   rK   s    rF   is_completeAdBreak.is_complete  s    d*Ht}}D/HHrE   c                    > U R                  5       (       a&  U R                  (       d  U R                  5       U l        [        TU ]  " U0 UD6  g)z2Override save to automatically calculate duration.N)r   r   r   supersave)rL   argskwargs	__class__s      rF   r   AdBreak.save  s<    d&;&;$($;$;$=D!d%f%rE   )r   )%r;   r<   r=   r>   rb   r   rj   r   rk   r|   rc   r   r   ro   start_detectionend_detectionr   r   r   PositiveIntegerFieldr   r   r   ri   r   r   r   api_responsere   notesrG   rM   r   r   r   rD   __classcell__)r   s   @rF   r   r   	  s   * .. ;	G ##CL
 

 7	F ''..(KO %%..&IM %%8J ##6H 22%a(*;D*AB7	 ((GN ##9L HE
	
 	
]
I& &rE   r   c                   <   \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " \
\R                  SSS9r\R                  " SS	S
9r\R                  " SSS
9r\R                  " SSS
9r\R                   " SS\" S5      \" S5      /SS9r\R                   " SS\" S5      \" S5      /SS9r\R                   " SS\" S5      \" S5      /SS9r\R                   " SS\" S5      /SS9r\R.                  " SSSS9r " S S5      rS rS rS rS rSrg)DetectionStatisticsi  aX  
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
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 detectionsTrs   rt   z+Average confidence score for all detectionsr   z!Minimum confidence score recordedz!Maximum confidence score recordedzNumber of detections per hourz&Timestamp of the most recent detectionr   c                   p    \ rS rSrSrSrSS/rS/r\R                  " SS/S9\R                  " S/S9/r
Srg	)
DetectionStatistics.Metai  zDetection Statisticsr|   r~   z-last_detectionr6   last_detectionr9   N)r;   r<   r=   r>   r?   r@   unique_togetherrA   r   rB   rC   rD   r9   rE   rF   rG   r     sG    -4$j1%&LLJ 78LL!1 23
rE   rG   c                 N    U R                   R                   SU R                   S3$ )z2String representation of the detection statistics.r   z detections)r~   r4   total_detectionsrK   s    rF   rM   DetectionStatistics.__str__  s'    --$$%S)>)>(?{KKrE   c                 \    U R                   S:  a  U R                  U R                   -  S-  $ g)zBCalculate the accuracy rate as percentage of confirmed detections.r   r   )r   confirmed_detectionsrK   s    rF   accuracy_rate!DetectionStatistics.accuracy_rate  s/      1$--0E0EELLrE   c                 \    U R                   S:  a  U R                  U R                   -  S-  $ g)z0Calculate the false positive rate as percentage.r   r   )r   false_positivesrK   s    rF   false_positive_rate'DetectionStatistics.false_positive_rate  s/      1$((4+@+@@CGGrE   c                    [         R                  R                  U R                  U R                  S9nUR                  5       U l        UR                  SS9R                  5       U l        U R                  S:  a  UR                  SSS9n[        U5      [        U5      -  U l        [        U5      U l        [        U5      U l        UR!                  S5      R#                  5       nU(       a  UR$                  U l        U R)                  5         g)	z7Recalculate statistics based on current detection data.)r|   r~   T)r   r   r   )flatr{   N)ro   objectsfilterr|   r~   countr   r   values_listsumlenavg_confidenceminmin_confidencemaxmax_confidenceorder_byfirstr}   r   r   )rL   rr   confidence_scoreslatest_detections       rF   update_statistics%DetectionStatistics.update_statistics  s    $,,33LL]] 4 


 !+ 0 0 2$.$5$54$5$H$N$N$P!  1$ * 6 67IPT 6 U"%&7"83?P;Q"QD"%&7"8D"%&7"8D)223DEKKM&6&E&E#		rE   )r   r   r   r   r   r   N)r;   r<   r=   r>   rb   r   rj   r   rk   r|   r   r~   r   r   r   r   rg   r   r   r   r   r   detection_rater   r   rG   rM   r   r   r   rD   r9   rE   rF   r   r     s   ( ..+7	G   ..!8	H 22@
 "66;
 11BO &&%c*,=c,BC?	N &&%c*,=c,BC5	N &&%c*,=c,BC5	N &&%c*+1	N )):N
 
LrE   r   )rb   	django.dbr   django.contrib.auth.modelsr   django.utilsr   django.core.validatorsr   r   apps.core.modelsr   r	   r
   apps.streams.modelsr   r   apps.core.validatorsr   r   r   r   r   rP   jsonr   ro   r   r   r9   rE   rF   <module>r      s|     + ! G E E 9  
 |%y |~o&	 odE&	; E&PE*I ErE   