U
    h7                     @   s   d Z ddlmZmZmZ ddlmZ ddlmZ ddl	m
Z
 ddlm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mZmZmZ ddlmZmZmZmZmZ ddl m!Z! G dd dej"Z#G dd dej"Z$G dd dej"Z%G dd dej&Z'dS )z
REST API Views for Jingles Application

This module contains Django REST Framework views for managing
jingle detection, ad break analysis, and related operations
through a RESTful API interface.
    )viewsetsstatuspermissions)action)Response)PageNumberPagination)DjangoFilterBackend)timezone)CountAvgQ)	timedelta)JingleTemplateJingleDetectionAdBreakDetectionStatistics)JingleTemplateSerializerJingleDetectionSerializerAdBreakSerializerDetectionStatisticsSerializerDetectionSummarySerializer)extract_iframes_from_segmentc                   @   s   e Zd ZdZej dZe	Z
ejgZegZdddgZdddgZddd	gZdgZd
d ZeddgddddZeddgddddZeddgddd ZdS )JingleTemplateViewSetz
    ViewSet for managing jingle templates via REST API.
    
    Provides CRUD operations for jingle templates along with
    custom actions for template management and statistics.
    
created_by	is_activecategorynameslugdescription
created_atsimilarity_thresholdc                 C   s   |j | jjd dS )z-Set the current user as the template creator.)r   N)saverequestuser)self
serializer r&   ;/var/www/html/StreamProcessor/src/apps/jingles/api/views.pyperform_create+   s    z$JingleTemplateViewSet.perform_createTgetdetailmethodsNc                 C   sj   |   }|jddd}|jd}|jd}|rD|j|d}|rT|j|d}t|dd	}t|j	S )
a	  
        Get all detections for a specific template.
        
        Args:
            request: HTTP request with optional filters
            pk: Template primary key
            
        Returns:
            Response: List of detections for the template
        session__channelsegment-detection_time	date_fromdate_toZdetection_time__gte)Zdetection_time__lteTmany)

get_object
detectionsselect_relatedorder_byquery_paramsr)   filterr   r   data)r$   r"   pktemplater6   r0   r1   r%   r&   r&   r'   r6   /   s     z JingleTemplateViewSet.detectionsc                 C   s   |   }|j }| }|jdd }|dkrr|| d }|jtddd }|jt t	dd	 d
 }	nd}d}d}	||t
|d|rt
|dnd|	d}
t|
S )z
        Get detailed statistics for a specific template.
        
        Args:
            request: HTTP request
            pk: Template primary key
            
        Returns:
            Response: Template statistics data
        Tis_confirmedr   d   confidence_score)avgrB      daysr2         )total_detectionsconfirmed_detectionsaccuracy_rateavg_confidencerecent_detections)r5   r6   allcountr:   	aggregater   r	   nowr   roundr   )r$   r"   r<   r=   r6   rH   rI   rJ   rK   rL   statsr&   r&   r'   
statisticsL   s(    
z JingleTemplateViewSet.statisticsFc                 C   s&   | j jdd}| j|dd}t|jS )z Get all active jingle templates.Tr   r3   querysetr:   get_serializerr   r;   )r$   r"   active_templatesr%   r&   r&   r'   activev   s    zJingleTemplateViewSet.active)N)N)__name__
__module____qualname____doc__r   objectsrM   r7   rV   r   serializer_classr   IsAuthenticatedpermission_classesr   filter_backendsfilterset_fieldssearch_fieldsordering_fieldsorderingr(   r   r6   rS   rY   r&   r&   r&   r'   r      s    


)r   c                   @   s   e Zd ZdZej dddZe	Z
ejgZegZdddgZddgZd	gZed
dgddddZed
dgddddZeddgddd Zeddgddd ZdS )JingleDetectionViewSetz
    ViewSet for managing jingle detections via REST API.
    
    Provides access to detection data with filtering and
    confirmation capabilities.
    r=   r-   r.   sessionr?   detection_timerA   r/   Tpostr*   Nc                 C   s*   |   }d|_|  | |}t|jS )z
        Confirm a jingle detection as accurate.
        
        Args:
            request: HTTP request
            pk: Detection primary key
            
        Returns:
            Response: Updated detection data
        T)r5   r?   r!   rW   r   r;   )r$   r"   r<   	detectionr%   r&   r&   r'   confirm   s
    
zJingleDetectionViewSet.confirmc                 C   sp   |   }d|_|  z.tjj|j|jd}| jd7  _|  W n tj	k
rZ   Y nX | 
|}t|jS )z
        Mark a detection as false positive.
        
        Args:
            request: HTTP request
            pk: Detection primary key
            
        Returns:
            Response: Updated detection data
        F)rh   r=      )r5   r?   r!   r   r^   r)   rh   r=   false_positivesDoesNotExistrW   r   r;   )r$   r"   r<   rk   rR   r%   r&   r&   r'   reject   s    
zJingleDetectionViewSet.rejectFr)   c                 C   s,   | j ddd }| j|dd}t|jS )z+Get recent detections across all templates.r/   N2   Tr3   )rV   r8   rW   r   r;   )r$   r"   rL   r%   r&   r&   r'   recent   s    zJingleDetectionViewSet.recentc                 C   s   t  }| }|tdd }| j }| jj|d }| jjdd }d}|dkrd|| d }ttj	j|dj
td	d
ddd dd}	t| jj|dddddd dddd}
|||t|d|	|
d}t|}t|jS )z
        Get detection summary statistics.
        
        Args:
            request: HTTP request
            
        Returns:
            Response: Summary statistics data
        rC   rD   )detection_time__dateTr>   r   r@   )Zdetections__detection_time__gter6   )detection_countz-detection_countN   r   rt   r2   r=   r-   r/   
   template__namesession__channel__nameri   rA   rF   )rH   detections_todayrI   rJ   top_templatesrecent_activity)r	   rP   dater   rV   rN   r:   listr   r^   annotater
   r8   valuesr7   rQ   r   r   r;   )r$   r"   rP   todayZlast_7_daysrH   ry   rI   rJ   rz   r{   Zsummary_datar%   r&   r&   r'   summary   sb    
    	zJingleDetectionViewSet.summary)N)N)rZ   r[   r\   r]   r   r^   rM   r7   rV   r   r_   r   r`   ra   r   rb   rc   re   rf   r   rl   rp   rr   r   r&   r&   r&   r'   rg   ~   s(   
  

rg   c                   @   s   e Zd ZdZej dddZe	Z
ejgZegZdddgZdd	gZd
gZeddgddddZeddgddd Zeddgddd ZdS )AdBreakViewSetz
    ViewSet for managing ad breaks via REST API.
    
    Provides access to ad break data with external API
    integration capabilities.
    r-   start_detection__templateend_detection__templater   regionis_sent_to_api
start_timeduration_secondsz-start_timeTrj   r*   Nc              
   C   s   |   }| s"tdditjdS |jr:tdditjdS z6ddlm} |t	|j
}tdd|j
d	tjdW S  tk
r } ztdt	|itjd W Y S d
}~X Y nX d
S )z
        Send ad break data to external API.
        
        Args:
            request: HTTP request
            pk: Ad break primary key
            
        Returns:
            Response: API submission result
        errorzAd break is not completer   zAd break already sent to APIrF   )send_ad_break_notificationTz"Ad break queued for API submission)successmessagetask_idN)r5   is_completer   r   HTTP_400_BAD_REQUESTr   tasksr   delaystridHTTP_202_ACCEPTED	ExceptionHTTP_500_INTERNAL_SERVER_ERROR)r$   r"   r<   ad_breakr   tasker&   r&   r'   send_to_api  s4    
zAdBreakViewSet.send_to_apiFr)   c                 C   s&   | j jdd}| j|dd}t|jS )zGet all active ad breaks.rY   r   Tr3   rU   )r$   r"   Zactive_breaksr%   r&   r&   r'   rY   E  s    zAdBreakViewSet.activec                 C   s2   t   }| jj|d}| j|dd}t|jS )zGet ad breaks from today.)start_time__dateTr3   )r	   rP   r|   rV   r:   rW   r   r;   )r$   r"   r   Ztoday_breaksr%   r&   r&   r'   r   L  s    zAdBreakViewSet.today)N)rZ   r[   r\   r]   r   r^   rM   r7   rV   r   r_   r   r`   ra   r   rb   rc   re   rf   r   r   rY   r   r&   r&   r&   r'   r     s$   
  
,
r   c                   @   sb   e Zd ZdZej ddZe	Z
ejgZegZddgZdddgZdgZed	d
gddd ZdS )DetectionStatisticsViewSetz
    ViewSet for detection statistics (read-only).
    
    Provides access to performance metrics and analysis
    data for jingle detection accuracy.
    r=   r-   rh   last_detectionrH   rJ   z-last_detectionFr)   r*   c           	      C   s   | j  }| s$tdddg dS tdd |D }tdd |D }|dkr\|| d nd}g }|jddd	d
d D ] }||jj	|
 |jd q~t|d|tjjdd |d}t|S )z
        Get overall performance statistics.
        
        Args:
            request: HTTP request
            
        Returns:
            Response: Performance summary data
        r   )overall_accuracyrH   rX   best_performersc                 s   s   | ]}|j V  qd S N)rH   .0sr&   r&   r'   	<genexpr>}  s     z9DetectionStatisticsViewSet.performance.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S r   )rI   r   r&   r&   r'   r   ~  s     r@   rv   )Ztotal_detections__gtez-accuracy_rateNru   )template_namerJ   rH   rF   TrT   )rV   rM   existsr   sumr:   r8   appendr=   r   rJ   rH   rQ   r   r^   rN   )	r$   r"   rR   rH   Ztotal_confirmedr   r   statZperformance_datar&   r&   r'   performanceg  s0    

z&DetectionStatisticsViewSet.performanceN)rZ   r[   r\   r]   r   r^   rM   r7   rV   r   r_   r   r`   ra   r   rb   rc   re   rf   r   r   r&   r&   r&   r'   r   U  s   
 
r   N)(r]   rest_frameworkr   r   r   rest_framework.decoratorsr   rest_framework.responser   Zrest_framework.paginationr   Zdjango_filters.rest_frameworkr   django.utilsr	   django.db.modelsr
   r   r   datetimer   apps.jingles.modelsr   r   r   r   Zapps.jingles.api.serializersr   r   r   r   r   apps.streams.tasksr   ModelViewSetr   rg   r   ReadOnlyModelViewSetr   r&   r&   r&   r'   <module>   s    d 	O