o
    c:+                     @   s  d dl Z d dlZd dlZd dlZd dl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 d dlmZ d dlZd dlZd dlZd dlZd dlmZmZ eeZ			
ddedededee dee ddfddZdd Z d defddZ!de"fddZ#de"defddZ$dS )!    N)Thread)AudioSegment)detect_nonsilent)ThreadPoolExecutor)StatusProcessedMedia)get_audio_parts)AnyOptionallibx264aac
video_path
audio_pathoutput_video_pathvideo_codecaudio_codecreturnc                 C   s0  t j| rt j| std|  t j| d }|dv r't|| dS |dvr2td| t j|r>t j|sEtd| t j|d dvr\tdt j|d  d	d
d| d|ddddd|d|dd|g}ztj	|dtj
tj
d W dS  tjy } zt|j t|j  d}~ww )a2  
        Creates a new video by replacing the old audio with the generated audio input using FFmpeg.

        This function uses the `ffmpeg` command line utility to combine the video file at `video_path` and
        the audio file at `audio_path` into a new video file at `output_video_path`.

        Parameters: ==> Args:
            video_path        : The path to the input video file.
            audio_path        : The path to the input audio file that will be used to replace the audio in the input video.
            output_video_path : The path where the output video with the new audio will be saved.
            video_codec       : The codec to use for the video stream. Default is 'libx264'.
            audio_codec       : The codec to use for the audio stream. Default is 'aac'.

        Returns:

    z/Video file not found or is not a regular file:    )z.mp3.wavz.flacN).mp4z.aviz.mkvz"Unsupported video file extention: z/Audio file not found or is not a regular file: z"Unsupported audio file extention: ffmpegz-hide_bannerz-iz-mapz0:v:0z1:a:0z-c:vz-c:az-strictexperimentalT)checkstdoutstderr)ospathexistsisfile
ValueErrorsplitextshutilcopyfile
subprocessrunPIPECalledProcessErrorloggingerrorr   r   )r   r   r   r   r   	video_extcommande r,   9/var/www/html/docker_usevoice/src/apps/process/handler.pysave_new_media   sL   r.   c                 C   sP   |  | j} |  }dd |D }t|jtj}|t|d j	j
 }|S )Nc                 S      g | ]}|  qS r,   )get_array_of_samples).0sr,   r,   r-   
<listcomp>g       z.audiosegment_to_librosawav.<locals>.<listcomp>r   )set_frame_rate
frame_ratesplit_to_mononparrayTastypefloat32iinfotypecodemax)soundchannel_soundssamplesfp_arrr,   r,   r-   audiosegment_to_librosawavd   s   rD   mp3
video_filec              
   C   s   t j| \}}d|vrt jdd| n| }d|vr't jdd| d| n| d| }t j|r6|S t jt j|dd d| d| }ztj|ddtj	tj	d	 W |S  tj
yq } ztd
|j   d}~ww )z^Converts video to audio directly using `ffmpeg` command with the help of the subprocess moduleoriginal_audiosmediaoriginal_videos.T)exist_okzffmpeg -hide_banner -i  )shellr   r   r   z"Failed to convert video to audio: N)r   r   r    joinr   makedirsdirnamer#   r$   r%   r&   	Exceptionr   decodestrip)rF   
output_extfilenameext
input_pathoutput_pathffmpeg_commandr+   r,   r,   r-   convert_video_to_audio_ffmpeg{   s   0rZ   partc           	      C   s~   |dur;|g kr=| |d |d  }t |}|j}||\}}td tjds0td |r3	 |||d}|S dS dS )z?This function is used to remove the sounds from the audio part.Nr   r   g?zmedia/music_output)r[   voice
background)	rD   r:   splittimesleepr   r   r   mkdir)	audior[   MLmodelsaveextracted_audioaudio_librosavoice_audiobackground_audiomodel_resultr,   r,   r-   remove_sound   s    

rj   
parts_listc                    sd  t d t | t | t|dd}|dur,tj|r.tj|r0t||dur;|g kr;tdt	gg}t
  fdd|D }dd |D }W d   n1 s[w   Y  tt	|}t }|D ]H}	|	|v rt	|dkrtt	|D ](}
||
 d	 |	kr||
 d
 }t|d }t| j|jjdd}||7 }qqm||	d |	d  7 }qmtjj|d}|dd  dt j d}|jjdkr|jjj nd| }|jjdkrd|jj dt j dnd|dd  dt j d}tjdstd |j |dd t!||| t"j#|_$||_%||_&|'  dS dS dS dS )z:This function is used to remove the sounds from the video.zReciving Filewav)rT   Nr   c              	      s   g | ]} t| d qS )T)submitrj   )r1   r[   rc   rb   executorr,   r-   r3      s    z)start_removing_sounds.<locals>.<listcomp>c                 S   r/   r,   )result)r1   futurer,   r,   r-   r3      r4   r[   r\   i      )r6   sample_widthchannelsr   )idrJ   _r   zmedia/original_videos/zmedia/new_video/r   zmedia/new_video)format)(printrZ   r   r   r   r   r   	from_fileintlenr   r   emptyranger8   int16tobytesr6   dtypeitemsizer   objectsgetr^   uuiduuid4hexrH   
youtube_idoriginal_fileexistingPathra   exportr.   r   	Completedstatusr   r   rd   )rc   rk   r   modia_idr   futuresresults	all_parts
audiofinalr[   indexaudio_segmentprocessedMedianew_audio_pathsave_video_pathnew_video_pathr,   rn   r-   start_removing_sounds   sL   &
 "J
r   )r   r   )rE   )%r   r_   r   numpyr8   	soundfilesf	threadingr   pydubr   pydub.silencer   concurrent.futuresr   apps.process.modelsr   r   apps.process.utilsr   r!   r'   	mimetypesr#   typingr	   r
   	getLogger__file__loggerstrr.   rD   rZ   listrj   r   r,   r,   r,   r-   <module>   sH    

L