U
    9d:+                     @   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eeeee ee ddddZdd Z dedddZ!e"dddZ#e"ed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   s>  t j| rt j| s&td|  t j| d }|dkrNt|| dS |dkrdtd| t j|r|t j|std| t j|d dkrt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 n@ tjk
r8 } zt|j t|j  W 5 d}~X Y nX dS )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   Z	video_extcommande r+   8/var/www/html/UseVoiceDocker/src/apps/process/handler.pysave_new_media   sH    r-   c                 C   sP   |  | j} |  }dd |D }t|jtj}|t|d j	j
 }|S )Nc                 S   s   g | ]}|  qS r+   )Zget_array_of_samples).0sr+   r+   r,   
<listcomp>g   s     z.audiosegment_to_librosawav.<locals>.<listcomp>r   )Zset_frame_rate
frame_rateZsplit_to_mononparrayTastypefloat32iinfotypecodemax)soundZchannel_soundssamplesZfp_arrr+   r+   r,   audiosegment_to_librosawavd   s    r<   mp3)
video_filec              
   C   s   t j| \}}d|kr(t jdd| n| }d|krNt jdd| d| n| d| }t j|rl|S t jt j|dd d| d| }ztj|ddtj	tj	d	 W n< tj
k
r } ztd
|j   W 5 d}~X Y nX |S )z^Converts video to audio directly using `ffmpeg` command with the help of the subprocess moduleZoriginal_audiosmediaZ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)r>   
output_extfilenameextZ
input_pathoutput_pathZffmpeg_commandr*   r+   r+   r,   convert_video_to_audio_ffmpeg{   s    0*rN   )partc           	      C   sx   |dk	rt|g krt| |d |d  }t |}|j}||\}}td tjds`td |rd|||d}|S dS )z?This function is used to remove the sounds from the audio part.Nr   r   g?zmedia/music_output)rO   voice
background)	r<   r4   splittimesleepr   r   r   mkdir)	audiorO   MLmodelsaveZextracted_audioZaudio_librosaZvoice_audioZbackground_audioZmodel_resultr+   r+   r,   remove_sound   s    

rY   )
parts_listr   c              	      sL  t d t | t | t|dd}|dk	rHtj|rHtj|rHt||dk	rv|g krvtdt	gg}t
 * fdd|D }dd |D }W 5 Q R X tt	|}t }|D ]}	|	|krBt	|dkrBtt	|D ]P}
||
 d	 |	kr||
 d
 }t|d }t| j|jjdd}||7 }qq||	d |	d  7 }qt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 )z:This function is used to remove the sounds from the video.zReciving Filewav)rJ   Nr   c              	      s   g | ]} t| d qS )T)submitrY   )r.   rO   rW   rV   executorr+   r,   r0      s     z)start_removing_sounds.<locals>.<listcomp>c                 S   s   g | ]}|  qS r+   )result)r.   futurer+   r+   r,   r0      s     rO   rP   i      )r1   Zsample_widthchannelsr   )idr@   _r   zmedia/original_videos/zmedia/new_video/r   zmedia/new_video)format)(printrN   r   r   r   r   r   	from_fileintlenr   r   emptyranger2   int16tobytesr1   dtypeitemsizer   objectsgetrR   uuiduuid4hexr?   
youtube_idoriginal_fileexistingPathrU   exportr-   r   	Completedstatusr   r   rX   )rW   rZ   r   Zmodia_idr   futuresresultsZ	all_partsZ
audiofinalrO   indexZaudio_segmentZprocessedMediaZnew_audio_pathZsave_video_pathZnew_video_pathr+   r]   r,   start_removing_sounds   sD    &
 $L
r~   )r   r   )r=   )%r   rS   rr   numpyr2   	soundfilesf	threadingr   Zpydubr   Zpydub.silencer   concurrent.futuresr   apps.process.modelsr   r   apps.process.utilsr   r!   r'   	mimetypesr#   typingr	   r
   	getLogger__file__loggerstrr-   r<   rN   listrY   r~   r+   r+   r+   r,   <module>   s<   
   L