jonathang commited on
Commit
32ed7fa
1 Parent(s): 74aeb4c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import moviepy.editor as mp
2
+ import librosa
3
+ import numpy as np
4
+ import gradio as gr
5
+ from pytube import YouTube
6
+ import subprocess
7
+
8
+
9
+ def buffer_n_merge(intervals, buffer=0.1):
10
+ if not intervals: return []
11
+
12
+ new_intervals = [intervals[0]]
13
+ new_intervals[0][0] -= buffer
14
+ new_intervals[0][1] += buffer
15
+
16
+ for start, end in intervals[1:]:
17
+ start -= buffer
18
+ end += buffer
19
+ if new_intervals[-1][-1] >= start:
20
+ new_intervals[-1][-1] = end
21
+ else:
22
+ new_intervals.append([start, end])
23
+ return new_intervals
24
+
25
+
26
+ def download_and_process_video(youtube_url, threshold_db, buffer_sec):
27
+ # Download the YouTube video
28
+ youtube = YouTube(youtube_url)
29
+ vidpath = 'downloaded_video'
30
+ youtube.streams.first().download(filename=vidpath)
31
+
32
+ # load the video
33
+ video = mp.VideoFileClip(vidpath)
34
+ # extract audio and convert to mono
35
+ audio = video.audio.to_soundarray(fps=22000)
36
+
37
+ # use librosa to get non-silent intervals
38
+ non_silent_intervals = librosa.effects.split(audio[:, 0], top_db=threshold_db)
39
+ # convert non_silent_intervals from samples to seconds, as librosa works with samples not seconds
40
+ non_silent_intervals_sec = np.array(non_silent_intervals) / 22000
41
+
42
+ # Add buffer and merge intervals
43
+ non_silent_intervals_sec = buffer_n_merge(non_silent_intervals_sec.tolist(), buffer=buffer_sec)
44
+
45
+ # Process video
46
+ # cut the video using the non-silent intervals and store the clips in a list
47
+ clips = [video.subclip(max(0, start_time), min(end_time, video.duration)) for start_time, end_time in non_silent_intervals_sec]
48
+
49
+ output_file = 'my_concatenation.mp4'
50
+ final_clip = mp.concatenate_videoclips(clips)
51
+ final_clip.write_videofile(output_file, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True)
52
+
53
+ return output_file
54
+
55
+
56
+ iface = gr.Interface(
57
+ fn=download_and_process_video,
58
+ inputs=[
59
+ gr.inputs.Text(label="YouTube URL"),
60
+ gr.inputs.Slider(minimum=1, maximum=70, step=1, default=30, label="Threshold (db)"),
61
+ gr.inputs.Slider(minimum=0, maximum=2, step=0.01, default=0.1, label="Buffer (sec)"),
62
+ ],
63
+ outputs=gr.outputs.Video(label="Processed Video"),
64
+ title="YouTube Video Silence Remover"
65
+ )
66
+
67
+ iface.launch()