-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
274 lines (224 loc) · 10.8 KB
/
main.py
File metadata and controls
274 lines (224 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import os
import sys
import uuid
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading
import tempfile
# Fix for PyInstaller compatibility
if getattr(sys, 'frozen', False):
# Set ffmpeg path for moviepy
ffmpeg_path = os.path.join(sys._MEIPASS, 'ffmpeg.exe')
if os.path.exists(ffmpeg_path):
os.environ['IMAGEIO_FFMPEG_EXE'] = ffmpeg_path
else:
# Try alternative locations
alt_paths = [
os.path.join(os.path.dirname(sys.executable), 'ffmpeg.exe'),
os.path.join(os.path.dirname(sys.executable), 'bin', 'ffmpeg.exe'),
'ffmpeg.exe' # System PATH
]
for path in alt_paths:
if os.path.exists(path) or path == 'ffmpeg.exe':
os.environ['IMAGEIO_FFMPEG_EXE'] = path
break
def get_temp_dir():
"""Get a writable temporary directory that works with PyInstaller"""
if getattr(sys, 'frozen', False):
# When frozen by PyInstaller, use system temp directory
return tempfile.gettempdir()
else:
# When running normally, use current directory
return os.getcwd()
from moviepy import VideoFileClip, concatenate_videoclips
from pydub import AudioSegment, silence
def trim_silent_parts(video_path: str,
output_path: str,
silence_thresh: int = -30,
min_silence_len: int = 1000,
padding: int = 300,
progress_callback=None) -> str:
"""
Removes silent sections from a video and returns the path to the processed video.
Parameters:
video_path (str): Path to the input video.
output_path (str): Path to save the output video.
silence_thresh (int): Silence threshold in dBFS. Default: -30
min_silence_len (int): Minimum silence length in ms. Default: 1000
padding (int): Padding around non-silent parts in ms. Default: 300
progress_callback (callable): Optional callback for progress updates.
Returns:
str: Path to the output video with silent parts removed.
"""
# Load video
if progress_callback:
progress_callback("Loading video...", 10)
print(f"Loading video: {video_path}")
video = VideoFileClip(video_path)
# Check if video has audio
if video.audio is None:
raise ValueError("The selected video file has no audio track. Cannot trim silence from a video without audio.")
# Export audio to temporary WAV file
if progress_callback:
progress_callback("Extracting audio...", 25)
temp_dir = get_temp_dir()
temp_audio_path = os.path.join(temp_dir, f"temp_{uuid.uuid4().hex}.wav")
video.audio.write_audiofile(temp_audio_path, logger=None)
# Load audio using pydub
audio = AudioSegment.from_wav(temp_audio_path)
# Detect non-silent chunks
if progress_callback:
progress_callback("Detecting non-silent parts...", 50)
print("Detecting non-silent parts...")
non_silent_ranges = silence.detect_nonsilent(audio,
min_silence_len=min_silence_len,
silence_thresh=silence_thresh)
if not non_silent_ranges:
print("No non-silent parts detected.")
os.remove(temp_audio_path)
return None
# Convert ms to seconds and apply padding
clips = []
for start_ms, end_ms in non_silent_ranges:
start = max((start_ms - padding) / 1000, 0)
end = min((end_ms + padding) / 1000, video.duration)
clip = video.subclipped(start, end)
clips.append(clip)
# Concatenate non-silent clips
if progress_callback:
progress_callback("Concatenating video clips...", 70)
print("Concatenating non-silent video clips...")
final_clip = concatenate_videoclips(clips)
# Save output
if progress_callback:
progress_callback("Saving output video...", 90)
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac")
# Cleanup
os.remove(temp_audio_path)
if progress_callback:
progress_callback("Complete!", 100)
print(f"Processed video saved to: {output_path}")
return output_path
class VideoTrimmerApp:
def __init__(self, root):
self.root = root
self.root.title("Video Silence Trimmer")
self.root.geometry("600x500")
self.input_path = ""
self.output_path = ""
self.create_widgets()
def create_widgets(self):
# Input file selection
tk.Label(self.root, text="Input Video:", font=("Arial", 12)).pack(pady=10)
input_frame = tk.Frame(self.root)
input_frame.pack(pady=5)
self.input_label = tk.Label(input_frame, text="No file selected", width=50, anchor="w",
relief="sunken", bg="white")
self.input_label.pack(side="left", padx=5)
tk.Button(input_frame, text="Browse", command=self.browse_input).pack(side="right", padx=5)
# Output file selection
tk.Label(self.root, text="Output Location:", font=("Arial", 12)).pack(pady=(20, 10))
output_frame = tk.Frame(self.root)
output_frame.pack(pady=5)
self.output_label = tk.Label(output_frame, text="No location selected", width=50, anchor="w",
relief="sunken", bg="white")
self.output_label.pack(side="left", padx=5)
tk.Button(output_frame, text="Browse", command=self.browse_output).pack(side="right", padx=5)
# Parameters frame
params_frame = tk.LabelFrame(self.root, text="Parameters", font=("Arial", 12))
params_frame.pack(pady=20, padx=20, fill="x")
# Silence threshold
tk.Label(params_frame, text="Silence Threshold (dBFS):").grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.silence_thresh_var = tk.StringVar(value="-30")
tk.Entry(params_frame, textvariable=self.silence_thresh_var, width=10).grid(row=0, column=1, padx=5, pady=5)
# Min silence length
tk.Label(params_frame, text="Min Silence Length (ms):").grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.min_silence_var = tk.StringVar(value="1000")
tk.Entry(params_frame, textvariable=self.min_silence_var, width=10).grid(row=1, column=1, padx=5, pady=5)
# Padding
tk.Label(params_frame, text="Padding (ms):").grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.padding_var = tk.StringVar(value="300")
tk.Entry(params_frame, textvariable=self.padding_var, width=10).grid(row=2, column=1, padx=5, pady=5)
# Progress bar
self.progress_var = tk.StringVar(value="Ready")
tk.Label(self.root, textvariable=self.progress_var, font=("Arial", 10)).pack(pady=10)
self.progress_bar = ttk.Progressbar(self.root, mode='determinate', maximum=100)
self.progress_bar.pack(pady=5, padx=20, fill="x")
# Process button
self.process_button = tk.Button(self.root, text="Trim Video", command=self.process_video,
bg="#4CAF50", fg="white", font=("Arial", 12), height=2)
self.process_button.pack(pady=20)
def browse_input(self):
filename = filedialog.askopenfilename(
title="Select Input Video",
filetypes=[("Video files", "*.mp4 *.avi *.mov *.mkv *.wmv"), ("All files", "*.*")]
)
if filename:
self.input_path = filename
self.input_label.config(text=os.path.basename(filename))
def browse_output(self):
filename = filedialog.asksaveasfilename(
title="Save Output Video As",
defaultextension=".mp4",
filetypes=[("MP4 files", "*.mp4"), ("All files", "*.*")]
)
if filename:
self.output_path = filename
self.output_label.config(text=os.path.basename(filename))
def update_progress(self, message, progress=None):
self.progress_var.set(message)
if progress is not None:
self.progress_bar['value'] = progress
self.root.update_idletasks()
def process_video(self):
if not self.input_path:
messagebox.showerror("Error", "Please select an input video file")
return
if not self.output_path:
messagebox.showerror("Error", "Please select an output location")
return
try:
silence_thresh = int(self.silence_thresh_var.get())
min_silence_len = int(self.min_silence_var.get())
padding = int(self.padding_var.get())
except ValueError:
messagebox.showerror("Error", "Please enter valid numeric values for parameters")
return
self.process_button.config(state="disabled")
self.progress_bar['value'] = 0
def process_thread():
try:
# Validate input file exists
if not os.path.exists(self.input_path):
raise FileNotFoundError(f"Input file not found: {self.input_path}")
# Check if ffmpeg is available
ffmpeg_exe = os.environ.get('IMAGEIO_FFMPEG_EXE', 'ffmpeg')
print(f"Using ffmpeg at: {ffmpeg_exe}")
result = trim_silent_parts(
self.input_path,
self.output_path,
silence_thresh=silence_thresh,
min_silence_len=min_silence_len,
padding=padding,
progress_callback=self.update_progress
)
if result:
messagebox.showinfo("Success", f"Video processed successfully!\nSaved to: {result}")
else:
messagebox.showwarning("Warning", "Video had no non-silent parts.")
except FileNotFoundError as e:
messagebox.showerror("File Error", f"File not found: {str(e)}")
except Exception as e:
import traceback
error_details = f"Error: {str(e)}\n\nDetails:\n{traceback.format_exc()}"
print(error_details) # Print to console for debugging
messagebox.showerror("Error", f"An error occurred: {str(e)}")
finally:
self.progress_bar['value'] = 0
self.process_button.config(state="normal")
self.update_progress("Ready")
threading.Thread(target=process_thread, daemon=True).start()
if __name__ == "__main__":
root = tk.Tk()
app = VideoTrimmerApp(root)
root.mainloop()