RO-Rtechs commited on
Commit
a53b85e
1 Parent(s): f6c2ce7

Update media_utils.py

Browse files
Files changed (1) hide show
  1. media_utils.py +384 -383
media_utils.py CHANGED
@@ -1,383 +1,384 @@
1
- import gradio as gr
2
- import subprocess
3
- import os
4
- from tqdm import tqdm
5
- import time
6
- from PIL import Image
7
- from concurrent.futures import ThreadPoolExecutor
8
- import torch
9
-
10
- def get_device():
11
- if torch.cuda.is_available():
12
- return torch.device('cuda')
13
- else:
14
- return torch.device('cpu')
15
-
16
- device = get_device()
17
- print(f"Using device: {device}")
18
-
19
- def get_unique_filename(base_name, extension):
20
- counter = 1
21
- unique_name = f"{base_name}{extension}"
22
- while os.path.exists(unique_name):
23
- unique_name = f"{base_name}_{counter}{extension}"
24
- counter += 1
25
- return unique_name
26
-
27
- def combine_videos(video_files):
28
- if not video_files:
29
- return "No video files selected.", None
30
- output_file = get_unique_filename("combined_video", ".mp4")
31
- filelist_path = os.path.abspath("filelist.txt")
32
- with open(filelist_path, "w") as filelist:
33
- for video in video_files:
34
- filelist.write(f"file '{os.path.abspath(video).replace('\\', '/')}'\n")
35
-
36
- command = [
37
- "ffmpeg", "-f", "concat", "-safe", "0", "-i", filelist_path,
38
- "-c", "copy", output_file
39
- ]
40
-
41
- with ThreadPoolExecutor() as executor:
42
- future = executor.submit(subprocess.run, command, text=True, capture_output=True)
43
- result = future.result() # Waits for the command to complete and returns the result
44
-
45
- if result.returncode == 0:
46
- return f"Videos combined successfully into {output_file}", output_file
47
- else:
48
- return f"Error combining videos: {result.stderr}", None
49
-
50
- def combine_audios(audio_files):
51
- if not audio_files:
52
- return "No audio files selected.", None
53
- output_file = get_unique_filename("combined_audio", ".mp3")
54
- filelist_path = os.path.abspath("filelist.txt")
55
- with open(filelist_path, "w") as filelist:
56
- for audio in audio_files:
57
- filelist.write(f"file '{os.path.abspath(audio).replace('\\', '/')}'\n")
58
-
59
- command = [
60
- "ffmpeg", "-f", "concat", "-safe", "0", "-i", filelist_path,
61
- "-c", "copy", output_file
62
- ]
63
-
64
- with ThreadPoolExecutor() as executor:
65
- future = executor.submit(subprocess.run, command, text=True, capture_output=True)
66
- result = future.result() # Waits for the command to complete and returns the result
67
-
68
- if result.returncode == 0:
69
- return f"Audios combined successfully into {output_file}", output_file
70
- else:
71
- return f"Error combining audios: {result.stderr}", None
72
-
73
- def combine_images(image_files):
74
- if not image_files:
75
- return "No image files selected.", None
76
- output_file = get_unique_filename("combined_image", ".mp4")
77
- command = ["convert"] + image_files + [output_file]
78
-
79
- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
80
- total_time = 0
81
- with tqdm(total=100, desc="Combining Images") as pbar:
82
- while True:
83
- output = process.stderr.readline()
84
- if output == '' and process.poll() is not None:
85
- break
86
- if output:
87
- total_time += 1
88
- pbar.update(1)
89
- time.sleep(0.1)
90
-
91
- return f"Images combined successfully into {output_file}", output_file
92
-
93
- def adjust_speed(media_file, speed):
94
- if not media_file:
95
- return "No media file selected.", None
96
- output_file = get_unique_filename(f"adjusted_speed_{os.path.basename(media_file)}", ".mp4")
97
- command = [
98
- "ffmpeg", "-i", media_file, "-filter:v", f"setpts={1/speed}*PTS",
99
- "-filter:a", f"atempo={speed}", output_file
100
- ]
101
-
102
- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
103
- total_time = 0
104
- with tqdm(total=100, desc="Adjusting Speed") as pbar:
105
- while True:
106
- output = process.stderr.readline()
107
- if output == '' and process.poll() is not None:
108
- break
109
- if output:
110
- total_time += 1
111
- pbar.update(1)
112
- time.sleep(0.1)
113
-
114
- return f"Speed adjusted successfully to {speed}x in {output_file}", output_file
115
-
116
- def adjust_speed_by_length(media_file, desired_length_hhmmss):
117
- if not media_file:
118
- return "No media file selected.", None
119
- original_length = get_media_length(media_file)
120
- desired_length = hhmmss_to_seconds(desired_length_hhmmss)
121
- speed = original_length / desired_length
122
- return adjust_speed(media_file, speed)
123
-
124
- def adjust_speed_combined(media_file, speed, hours, minutes, seconds, compress):
125
- if hours or minutes or seconds:
126
- desired_length = f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
127
- output_message, output_file = adjust_speed_by_length(media_file, desired_length)
128
- else:
129
- output_message, output_file = adjust_speed(media_file, speed)
130
-
131
- if compress and output_file:
132
- compressed_output_file = get_unique_filename(f"compressed_{os.path.basename(output_file)}", ".mp4")
133
- compress_video(output_file, compressed_output_file)
134
- output_message = f"{output_message} and compressed to {compressed_output_file}"
135
- output_file = compressed_output_file
136
-
137
- return output_message, output_file
138
-
139
- def hhmmss_to_seconds(hhmmss):
140
- h, m, s = map(int, hhmmss.split(':'))
141
- return h * 3600 + m * 60 + s
142
-
143
- def get_media_length(media_file):
144
- result = subprocess.run(
145
- ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", media_file],
146
- stdout=subprocess.PIPE,
147
- stderr=subprocess.STDOUT
148
- )
149
- return float(result.stdout)
150
-
151
- def auto_color_correct(video_file):
152
- if not video_file:
153
- return "No video file selected.", None
154
- output_file = get_unique_filename(f"color_corrected_{os.path.basename(video_file)}", "")
155
- command = [
156
- "ffmpeg", "-i", video_file, "-vf", "eq=brightness=0.06:saturation=1.5", output_file
157
- ]
158
- subprocess.run(command, check=True)
159
- return f"Auto color correction applied successfully to {output_file}", output_file
160
-
161
- def extract_audio(video_file):
162
- if not video_file:
163
- return "No video file selected.", None
164
- output_file = get_unique_filename(f"extracted_audio_{os.path.basename(video_file)}", ".mka")
165
- command = [
166
- "ffmpeg", "-i", video_file, "-vn", "-acodec", "copy", output_file
167
- ]
168
- try:
169
- subprocess.run(command, check=True)
170
- except subprocess.CalledProcessError as e:
171
- return f"Error extracting audio: {e}. Command: {' '.join(command)}", None
172
- return f"Audio extracted successfully into {output_file}", output_file
173
-
174
- def compress_video(input_file, output_file):
175
- command = [
176
- "ffmpeg", "-i", input_file, "-vcodec", "libx265", "-crf", "28", output_file
177
- ]
178
- subprocess.run(command, check=True)
179
- return output_file
180
-
181
- def add_watermark(video_file, watermark_type, watermark_text, watermark_image, opacity, position_x, position_y, font_size, font_color, resize_width, resize_height):
182
- if not video_file:
183
- return "No video file selected.", None
184
-
185
- output_file = get_unique_filename(f"watermarked_{os.path.basename(video_file)}", ".mp4")
186
- drawtext = f"drawtext=text='{watermark_text}':x={position_x}:y={position_y}:fontsize={font_size}:fontcolor={font_color}@{opacity}" if watermark_type == "text" else ""
187
- def add_watermark(video_file, watermark_type, watermark_text, watermark_image, opacity, position, font_size, font_color, resize):
188
- if not video_file:
189
- return "No video file selected.", None
190
-
191
- output_file = get_unique_filename(f"watermarked_{os.path.basename(video_file)}", ".mp4")
192
- drawtext = f"drawtext=text='{watermark_text}':x={position[0]}:y={position[1]}:fontsize={font_size}:fontcolor={font_color}@{opacity}" if watermark_type == "text" else ""
193
- overlay = f"overlay={position[0]}:{position[1]}" if watermark_type == "image" else ""
194
- resize_cmd = f"scale={resize[0]}:{resize[1]}" if resize else "scale=iw:ih"
195
-
196
- command = [
197
- "ffmpeg", "-i", video_file,
198
- "-vf", f"{resize_cmd},{drawtext if watermark_type == 'text' else ''}{overlay if watermark_type == 'image' else ''}",
199
- output_file
200
- ]
201
-
202
- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
203
- total_time = 0
204
- with tqdm(total=100, desc="Adding Watermark") as pbar:
205
- while True:
206
- output = process.stderr.readline()
207
- if output == '' and process.poll() is not None:
208
- break
209
- if output:
210
- total_time += 1
211
- pbar.update(1)
212
- time.sleep(0.1)
213
-
214
- return f"Watermark added successfully to {output_file}", output_file
215
-
216
- def compress_image(input_image):
217
- if not input_image:
218
- return "No image file selected.", None
219
- output_file = get_unique_filename(f"compressed_{os.path.basename(input_image)}", ".jpg")
220
-
221
- with Image.open(input_image) as img:
222
- img.save(output_file, "JPEG", quality=95) # Adjust quality as needed
223
-
224
- return f"Image compressed successfully into {output_file}", output_file
225
-
226
- def compress_image_lossless(input_image):
227
- if not input_image:
228
- return "No image file selected.", None
229
- output_file = get_unique_filename(f"compressed_lossless_{os.path.basename(input_image)}", ".png")
230
-
231
- with Image.open(input_image) as img:
232
- img.save(output_file, "PNG", optimize=True) # PNG is lossless
233
-
234
- return f"Image compressed losslessly into {output_file}", output_file
235
-
236
- def mp3_to_video(mp3_file, image_file):
237
- if not mp3_file or not image_file:
238
- return "MP3 file or image file not selected.", None
239
- output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(mp3_file))[0]}", ".mp4")
240
- command = [
241
- "ffmpeg", "-loop", "1", "-i", image_file, "-i", mp3_file, "-c:v", "libx264", "-c:a", "aac", "-b:a", "192k", "-shortest", output_file
242
- ]
243
- subprocess.run(command, check=True)
244
- return f"MP3 converted to video successfully into {output_file}", output_file
245
-
246
- def video_to_mp3(video_file):
247
- if not video_file:
248
- return "No video file selected.", None
249
- output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(video_file))[0]}", ".mp3")
250
- command = [
251
- "ffmpeg", "-i", video_file, "-q:a", "0", "-map", "a", output_file
252
- ]
253
- subprocess.run(command, check=True)
254
- return f"Video converted to MP3 successfully into {output_file}", output_file
255
-
256
- def convert_image_format(input_image, output_format):
257
- if not input_image:
258
- return "No image file selected.", None
259
- output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(input_image))[0]}", f".{output_format}")
260
-
261
- with Image.open(input_image) as img:
262
- img.save(output_file, output_format.upper())
263
-
264
- return f"Image converted to {output_format} format successfully into {output_file}", output_file
265
-
266
- def interface():
267
- with gr.Blocks(theme="small_and_pretty") as demo: # Applying the "small_and_pretty" theme
268
- gr.Markdown("### Media Combiner Tool")
269
-
270
- with gr.Tab("Combine Videos"):
271
- video_files = gr.File(label="Select Video Files", type="filepath", file_count="multiple")
272
- video_submit = gr.Button("Combine Videos")
273
- video_output = gr.Textbox(label="Output")
274
- video_download = gr.File(label="Download Combined Video")
275
- video_submit.click(combine_videos, inputs=[video_files], outputs=[video_output, video_download])
276
-
277
- with gr.Tab("Combine Audios"):
278
- audio_files = gr.File(label="Select Audio Files", type="filepath", file_count="multiple")
279
- audio_submit = gr.Button("Combine Audios")
280
- audio_output = gr.Textbox(label="Output")
281
- audio_download = gr.File(label="Download Combined Audio")
282
- audio_submit.click(combine_audios, inputs=[audio_files], outputs=[audio_output, audio_download])
283
-
284
- with gr.Tab("Combine Images"):
285
- image_files = gr.File(label="Select Image Files", type="filepath", file_count="multiple")
286
- image_submit = gr.Button("Combine Images")
287
- image_output = gr.Textbox(label="Output")
288
- image_download = gr.File(label="Download Combined Image")
289
- image_submit.click(combine_images, inputs=[image_files], outputs=[image_output, image_download])
290
-
291
- with gr.Tab("Adjust Speed"):
292
- media_file = gr.File(label="Select Media File", type="filepath")
293
- speed = gr.Slider(label="Speed", minimum=0.5, maximum=2.0, step=0.1, value=1.0)
294
- with gr.Row():
295
- hours = gr.Number(label="Hours", value=0, precision=0)
296
- minutes = gr.Number(label="Minutes", value=0, precision=0)
297
- seconds = gr.Number(label="Seconds", value=0, precision=0)
298
- compress = gr.Checkbox(label="Compress Video", value=False)
299
- speed_submit = gr.Button("Adjust Speed")
300
- speed_output = gr.Textbox(label="Output")
301
- speed_download = gr.File(label="Download Adjusted Media")
302
-
303
- speed_submit.click(adjust_speed_combined, inputs=[media_file, speed, hours, minutes, seconds, compress], outputs=[speed_output, speed_download])
304
-
305
- with gr.Tab("Auto Color Correction"):
306
- video_file = gr.File(label="Select Video File", type="filepath")
307
- color_submit = gr.Button("Apply Color Correction")
308
- color_output = gr.Textbox(label="Output")
309
- color_download = gr.File(label="Download Color Corrected Video")
310
- color_submit.click(auto_color_correct, inputs=[video_file], outputs=[color_output, color_download])
311
-
312
- with gr.Tab("Extract Audio"):
313
- video_file = gr.File(label="Select Video File", type="filepath")
314
- extract_submit = gr.Button("Extract Audio")
315
- extract_output = gr.Textbox(label="Output")
316
- extract_download = gr.File(label="Download Extracted Audio")
317
- extract_submit.click(extract_audio, inputs=[video_file], outputs=[extract_output, extract_download])
318
-
319
- with gr.Tab("Add Watermark"):
320
- video_file = gr.File(label="Select Video File", type="filepath")
321
- watermark_type = gr.Radio(label="Watermark Type", choices=["text", "image"], value="text")
322
- watermark_text = gr.Textbox(label="Watermark Text", visible=True)
323
- watermark_image = gr.File(label="Watermark Image", type="filepath", visible=False)
324
- opacity = gr.Slider(label="Opacity", minimum=0.0, maximum=1.0, step=0.1, value=1.0)
325
- position_x = gr.Slider(label="Position X", minimum=0, maximum=1920, step=1, value=0)
326
- position_y = gr.Slider(label="Position Y", minimum=0, maximum=1080, step=1, value=0)
327
- font_size = gr.Slider(label="Font Size", minimum=10, maximum=100, step=1, value=24, visible=True)
328
- font_color = gr.ColorPicker(label="Font Color", value="#FFFFFF", visible=True)
329
- resize_width = gr.Number(label="Resize Width", visible=False)
330
- resize_height = gr.Number(label="Resize Height", visible=False)
331
- watermark_submit = gr.Button("Add Watermark")
332
- watermark_output = gr.Textbox(label="Output")
333
- watermark_download = gr.File(label="Download Watermarked Video")
334
-
335
- def update_visibility(watermark_type):
336
- return {
337
- watermark_text: gr.update(visible=watermark_type == "text"),
338
- watermark_image: gr.update(visible=watermark_type == "image"),
339
- font_size: gr.update(visible=watermark_type == "text"),
340
- font_color: gr.update(visible=watermark_type == "text"),
341
- resize_width: gr.update(visible=watermark_type == "image"),
342
- resize_height: gr.update(visible=watermark_type == "image")
343
- }
344
-
345
- watermark_type.change(update_visibility, inputs=[watermark_type], outputs=[watermark_text, watermark_image, font_size, font_color, resize_width, resize_height])
346
- watermark_submit.click(add_watermark, inputs=[video_file, watermark_type, watermark_text, watermark_image, opacity, position_x, position_y, font_size, font_color, resize_width, resize_height], outputs=[watermark_output, watermark_download])
347
-
348
-
349
- with gr.Tab("Compress Image Losslessly"):
350
- image_file = gr.File(label="Select Image File", type="filepath")
351
- compress_submit = gr.Button("Compress Image Losslessly")
352
- compress_output = gr.Textbox(label="Output")
353
- compress_download = gr.File(label="Download Compressed Image")
354
- compress_submit.click(compress_image_lossless, inputs=[image_file], outputs=[compress_output, compress_download])
355
-
356
- with gr.Tab("Convert MP3 to Video"):
357
- mp3_file = gr.File(label="Select MP3 File", type="filepath")
358
- image_file = gr.File(label="Select Image File", type="filepath")
359
- convert_submit = gr.Button("Convert MP3 to Video")
360
- convert_output = gr.Textbox(label="Output")
361
- convert_download = gr.File(label="Download Converted Video")
362
- convert_submit.click(mp3_to_video, inputs=[mp3_file, image_file], outputs=[convert_output, convert_download])
363
-
364
- with gr.Tab("Convert Video to MP3"):
365
- video_file = gr.File(label="Select Video File", type="filepath")
366
- convert_submit = gr.Button("Convert Video to MP3")
367
- convert_output = gr.Textbox(label="Output")
368
- convert_download = gr.File(label="Download Converted MP3")
369
- convert_submit.click(video_to_mp3, inputs=[video_file], outputs=[convert_output, convert_download])
370
-
371
- with gr.Tab("Convert Image Format"):
372
- input_image = gr.File(label="Select Image File", type="filepath")
373
- output_format = gr.Dropdown(label="Output Format", choices=["png", "jpg", "bmp", "gif"], value="png")
374
- convert_submit = gr.Button("Convert Image Format")
375
- convert_output = gr.Textbox(label="Output")
376
- convert_download = gr.File(label="Download Converted Image")
377
- convert_submit.click(convert_image_format, inputs=[input_image, output_format], outputs=[convert_output, convert_download])
378
-
379
- return demo
380
-
381
- if __name__ == "__main__":
382
- demo = interface()
383
- demo.launch(share=True)
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ from tqdm import tqdm
5
+ import time
6
+ from PIL import Image
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ import torch
9
+
10
+ def get_device():
11
+ if torch.cuda.is_available():
12
+ return torch.device('cuda')
13
+ else:
14
+ return torch.device('cpu')
15
+
16
+ device = get_device()
17
+ print(f"Using device: {device}")
18
+
19
+ def get_unique_filename(base_name, extension):
20
+ counter = 1
21
+ unique_name = f"{base_name}{extension}"
22
+ while os.path.exists(unique_name):
23
+ unique_name = f"{base_name}_{counter}{extension}"
24
+ counter += 1
25
+ return unique_name
26
+
27
+ def combine_videos(video_files):
28
+ if not video_files:
29
+ return "No video files selected.", None
30
+ output_file = get_unique_filename("combined_video", ".mp4")
31
+ filelist_path = os.path.abspath("filelist.txt")
32
+ with open(filelist_path, "w") as filelist:
33
+ for video in video_files:
34
+ video_path = os.path.abspath(video).replace('\\', '/')
35
+ filelist.write(f"file '{video_path}'\n")
36
+
37
+ command = [
38
+ "ffmpeg", "-f", "concat", "-safe", "0", "-i", filelist_path,
39
+ "-c", "copy", output_file
40
+ ]
41
+
42
+ with ThreadPoolExecutor() as executor:
43
+ future = executor.submit(subprocess.run, command, text=True, capture_output=True)
44
+ result = future.result() # Waits for the command to complete and returns the result
45
+
46
+ if result.returncode == 0:
47
+ return f"Videos combined successfully into {output_file}", output_file
48
+ else:
49
+ return f"Error combining videos: {result.stderr}", None
50
+
51
+ def combine_audios(audio_files):
52
+ if not audio_files:
53
+ return "No audio files selected.", None
54
+ output_file = get_unique_filename("combined_audio", ".mp3")
55
+ filelist_path = os.path.abspath("filelist.txt")
56
+ with open(filelist_path, "w") as filelist:
57
+ for audio in audio_files:
58
+ filelist.write(f"file '{os.path.abspath(audio).replace('\\', '/')}'\n")
59
+
60
+ command = [
61
+ "ffmpeg", "-f", "concat", "-safe", "0", "-i", filelist_path,
62
+ "-c", "copy", output_file
63
+ ]
64
+
65
+ with ThreadPoolExecutor() as executor:
66
+ future = executor.submit(subprocess.run, command, text=True, capture_output=True)
67
+ result = future.result() # Waits for the command to complete and returns the result
68
+
69
+ if result.returncode == 0:
70
+ return f"Audios combined successfully into {output_file}", output_file
71
+ else:
72
+ return f"Error combining audios: {result.stderr}", None
73
+
74
+ def combine_images(image_files):
75
+ if not image_files:
76
+ return "No image files selected.", None
77
+ output_file = get_unique_filename("combined_image", ".mp4")
78
+ command = ["convert"] + image_files + [output_file]
79
+
80
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
81
+ total_time = 0
82
+ with tqdm(total=100, desc="Combining Images") as pbar:
83
+ while True:
84
+ output = process.stderr.readline()
85
+ if output == '' and process.poll() is not None:
86
+ break
87
+ if output:
88
+ total_time += 1
89
+ pbar.update(1)
90
+ time.sleep(0.1)
91
+
92
+ return f"Images combined successfully into {output_file}", output_file
93
+
94
+ def adjust_speed(media_file, speed):
95
+ if not media_file:
96
+ return "No media file selected.", None
97
+ output_file = get_unique_filename(f"adjusted_speed_{os.path.basename(media_file)}", ".mp4")
98
+ command = [
99
+ "ffmpeg", "-i", media_file, "-filter:v", f"setpts={1/speed}*PTS",
100
+ "-filter:a", f"atempo={speed}", output_file
101
+ ]
102
+
103
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
104
+ total_time = 0
105
+ with tqdm(total=100, desc="Adjusting Speed") as pbar:
106
+ while True:
107
+ output = process.stderr.readline()
108
+ if output == '' and process.poll() is not None:
109
+ break
110
+ if output:
111
+ total_time += 1
112
+ pbar.update(1)
113
+ time.sleep(0.1)
114
+
115
+ return f"Speed adjusted successfully to {speed}x in {output_file}", output_file
116
+
117
+ def adjust_speed_by_length(media_file, desired_length_hhmmss):
118
+ if not media_file:
119
+ return "No media file selected.", None
120
+ original_length = get_media_length(media_file)
121
+ desired_length = hhmmss_to_seconds(desired_length_hhmmss)
122
+ speed = original_length / desired_length
123
+ return adjust_speed(media_file, speed)
124
+
125
+ def adjust_speed_combined(media_file, speed, hours, minutes, seconds, compress):
126
+ if hours or minutes or seconds:
127
+ desired_length = f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
128
+ output_message, output_file = adjust_speed_by_length(media_file, desired_length)
129
+ else:
130
+ output_message, output_file = adjust_speed(media_file, speed)
131
+
132
+ if compress and output_file:
133
+ compressed_output_file = get_unique_filename(f"compressed_{os.path.basename(output_file)}", ".mp4")
134
+ compress_video(output_file, compressed_output_file)
135
+ output_message = f"{output_message} and compressed to {compressed_output_file}"
136
+ output_file = compressed_output_file
137
+
138
+ return output_message, output_file
139
+
140
+ def hhmmss_to_seconds(hhmmss):
141
+ h, m, s = map(int, hhmmss.split(':'))
142
+ return h * 3600 + m * 60 + s
143
+
144
+ def get_media_length(media_file):
145
+ result = subprocess.run(
146
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", media_file],
147
+ stdout=subprocess.PIPE,
148
+ stderr=subprocess.STDOUT
149
+ )
150
+ return float(result.stdout)
151
+
152
+ def auto_color_correct(video_file):
153
+ if not video_file:
154
+ return "No video file selected.", None
155
+ output_file = get_unique_filename(f"color_corrected_{os.path.basename(video_file)}", "")
156
+ command = [
157
+ "ffmpeg", "-i", video_file, "-vf", "eq=brightness=0.06:saturation=1.5", output_file
158
+ ]
159
+ subprocess.run(command, check=True)
160
+ return f"Auto color correction applied successfully to {output_file}", output_file
161
+
162
+ def extract_audio(video_file):
163
+ if not video_file:
164
+ return "No video file selected.", None
165
+ output_file = get_unique_filename(f"extracted_audio_{os.path.basename(video_file)}", ".mka")
166
+ command = [
167
+ "ffmpeg", "-i", video_file, "-vn", "-acodec", "copy", output_file
168
+ ]
169
+ try:
170
+ subprocess.run(command, check=True)
171
+ except subprocess.CalledProcessError as e:
172
+ return f"Error extracting audio: {e}. Command: {' '.join(command)}", None
173
+ return f"Audio extracted successfully into {output_file}", output_file
174
+
175
+ def compress_video(input_file, output_file):
176
+ command = [
177
+ "ffmpeg", "-i", input_file, "-vcodec", "libx265", "-crf", "28", output_file
178
+ ]
179
+ subprocess.run(command, check=True)
180
+ return output_file
181
+
182
+ def add_watermark(video_file, watermark_type, watermark_text, watermark_image, opacity, position_x, position_y, font_size, font_color, resize_width, resize_height):
183
+ if not video_file:
184
+ return "No video file selected.", None
185
+
186
+ output_file = get_unique_filename(f"watermarked_{os.path.basename(video_file)}", ".mp4")
187
+ drawtext = f"drawtext=text='{watermark_text}':x={position_x}:y={position_y}:fontsize={font_size}:fontcolor={font_color}@{opacity}" if watermark_type == "text" else ""
188
+ def add_watermark(video_file, watermark_type, watermark_text, watermark_image, opacity, position, font_size, font_color, resize):
189
+ if not video_file:
190
+ return "No video file selected.", None
191
+
192
+ output_file = get_unique_filename(f"watermarked_{os.path.basename(video_file)}", ".mp4")
193
+ drawtext = f"drawtext=text='{watermark_text}':x={position[0]}:y={position[1]}:fontsize={font_size}:fontcolor={font_color}@{opacity}" if watermark_type == "text" else ""
194
+ overlay = f"overlay={position[0]}:{position[1]}" if watermark_type == "image" else ""
195
+ resize_cmd = f"scale={resize[0]}:{resize[1]}" if resize else "scale=iw:ih"
196
+
197
+ command = [
198
+ "ffmpeg", "-i", video_file,
199
+ "-vf", f"{resize_cmd},{drawtext if watermark_type == 'text' else ''}{overlay if watermark_type == 'image' else ''}",
200
+ output_file
201
+ ]
202
+
203
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
204
+ total_time = 0
205
+ with tqdm(total=100, desc="Adding Watermark") as pbar:
206
+ while True:
207
+ output = process.stderr.readline()
208
+ if output == '' and process.poll() is not None:
209
+ break
210
+ if output:
211
+ total_time += 1
212
+ pbar.update(1)
213
+ time.sleep(0.1)
214
+
215
+ return f"Watermark added successfully to {output_file}", output_file
216
+
217
+ def compress_image(input_image):
218
+ if not input_image:
219
+ return "No image file selected.", None
220
+ output_file = get_unique_filename(f"compressed_{os.path.basename(input_image)}", ".jpg")
221
+
222
+ with Image.open(input_image) as img:
223
+ img.save(output_file, "JPEG", quality=95) # Adjust quality as needed
224
+
225
+ return f"Image compressed successfully into {output_file}", output_file
226
+
227
+ def compress_image_lossless(input_image):
228
+ if not input_image:
229
+ return "No image file selected.", None
230
+ output_file = get_unique_filename(f"compressed_lossless_{os.path.basename(input_image)}", ".png")
231
+
232
+ with Image.open(input_image) as img:
233
+ img.save(output_file, "PNG", optimize=True) # PNG is lossless
234
+
235
+ return f"Image compressed losslessly into {output_file}", output_file
236
+
237
+ def mp3_to_video(mp3_file, image_file):
238
+ if not mp3_file or not image_file:
239
+ return "MP3 file or image file not selected.", None
240
+ output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(mp3_file))[0]}", ".mp4")
241
+ command = [
242
+ "ffmpeg", "-loop", "1", "-i", image_file, "-i", mp3_file, "-c:v", "libx264", "-c:a", "aac", "-b:a", "192k", "-shortest", output_file
243
+ ]
244
+ subprocess.run(command, check=True)
245
+ return f"MP3 converted to video successfully into {output_file}", output_file
246
+
247
+ def video_to_mp3(video_file):
248
+ if not video_file:
249
+ return "No video file selected.", None
250
+ output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(video_file))[0]}", ".mp3")
251
+ command = [
252
+ "ffmpeg", "-i", video_file, "-q:a", "0", "-map", "a", output_file
253
+ ]
254
+ subprocess.run(command, check=True)
255
+ return f"Video converted to MP3 successfully into {output_file}", output_file
256
+
257
+ def convert_image_format(input_image, output_format):
258
+ if not input_image:
259
+ return "No image file selected.", None
260
+ output_file = get_unique_filename(f"{os.path.splitext(os.path.basename(input_image))[0]}", f".{output_format}")
261
+
262
+ with Image.open(input_image) as img:
263
+ img.save(output_file, output_format.upper())
264
+
265
+ return f"Image converted to {output_format} format successfully into {output_file}", output_file
266
+
267
+ def interface():
268
+ with gr.Blocks(theme="small_and_pretty") as demo: # Applying the "small_and_pretty" theme
269
+ gr.Markdown("### Media Combiner Tool")
270
+
271
+ with gr.Tab("Combine Videos"):
272
+ video_files = gr.File(label="Select Video Files", type="filepath", file_count="multiple")
273
+ video_submit = gr.Button("Combine Videos")
274
+ video_output = gr.Textbox(label="Output")
275
+ video_download = gr.File(label="Download Combined Video")
276
+ video_submit.click(combine_videos, inputs=[video_files], outputs=[video_output, video_download])
277
+
278
+ with gr.Tab("Combine Audios"):
279
+ audio_files = gr.File(label="Select Audio Files", type="filepath", file_count="multiple")
280
+ audio_submit = gr.Button("Combine Audios")
281
+ audio_output = gr.Textbox(label="Output")
282
+ audio_download = gr.File(label="Download Combined Audio")
283
+ audio_submit.click(combine_audios, inputs=[audio_files], outputs=[audio_output, audio_download])
284
+
285
+ with gr.Tab("Combine Images"):
286
+ image_files = gr.File(label="Select Image Files", type="filepath", file_count="multiple")
287
+ image_submit = gr.Button("Combine Images")
288
+ image_output = gr.Textbox(label="Output")
289
+ image_download = gr.File(label="Download Combined Image")
290
+ image_submit.click(combine_images, inputs=[image_files], outputs=[image_output, image_download])
291
+
292
+ with gr.Tab("Adjust Speed"):
293
+ media_file = gr.File(label="Select Media File", type="filepath")
294
+ speed = gr.Slider(label="Speed", minimum=0.5, maximum=2.0, step=0.1, value=1.0)
295
+ with gr.Row():
296
+ hours = gr.Number(label="Hours", value=0, precision=0)
297
+ minutes = gr.Number(label="Minutes", value=0, precision=0)
298
+ seconds = gr.Number(label="Seconds", value=0, precision=0)
299
+ compress = gr.Checkbox(label="Compress Video", value=False)
300
+ speed_submit = gr.Button("Adjust Speed")
301
+ speed_output = gr.Textbox(label="Output")
302
+ speed_download = gr.File(label="Download Adjusted Media")
303
+
304
+ speed_submit.click(adjust_speed_combined, inputs=[media_file, speed, hours, minutes, seconds, compress], outputs=[speed_output, speed_download])
305
+
306
+ with gr.Tab("Auto Color Correction"):
307
+ video_file = gr.File(label="Select Video File", type="filepath")
308
+ color_submit = gr.Button("Apply Color Correction")
309
+ color_output = gr.Textbox(label="Output")
310
+ color_download = gr.File(label="Download Color Corrected Video")
311
+ color_submit.click(auto_color_correct, inputs=[video_file], outputs=[color_output, color_download])
312
+
313
+ with gr.Tab("Extract Audio"):
314
+ video_file = gr.File(label="Select Video File", type="filepath")
315
+ extract_submit = gr.Button("Extract Audio")
316
+ extract_output = gr.Textbox(label="Output")
317
+ extract_download = gr.File(label="Download Extracted Audio")
318
+ extract_submit.click(extract_audio, inputs=[video_file], outputs=[extract_output, extract_download])
319
+
320
+ with gr.Tab("Add Watermark"):
321
+ video_file = gr.File(label="Select Video File", type="filepath")
322
+ watermark_type = gr.Radio(label="Watermark Type", choices=["text", "image"], value="text")
323
+ watermark_text = gr.Textbox(label="Watermark Text", visible=True)
324
+ watermark_image = gr.File(label="Watermark Image", type="filepath", visible=False)
325
+ opacity = gr.Slider(label="Opacity", minimum=0.0, maximum=1.0, step=0.1, value=1.0)
326
+ position_x = gr.Slider(label="Position X", minimum=0, maximum=1920, step=1, value=0)
327
+ position_y = gr.Slider(label="Position Y", minimum=0, maximum=1080, step=1, value=0)
328
+ font_size = gr.Slider(label="Font Size", minimum=10, maximum=100, step=1, value=24, visible=True)
329
+ font_color = gr.ColorPicker(label="Font Color", value="#FFFFFF", visible=True)
330
+ resize_width = gr.Number(label="Resize Width", visible=False)
331
+ resize_height = gr.Number(label="Resize Height", visible=False)
332
+ watermark_submit = gr.Button("Add Watermark")
333
+ watermark_output = gr.Textbox(label="Output")
334
+ watermark_download = gr.File(label="Download Watermarked Video")
335
+
336
+ def update_visibility(watermark_type):
337
+ return {
338
+ watermark_text: gr.update(visible=watermark_type == "text"),
339
+ watermark_image: gr.update(visible=watermark_type == "image"),
340
+ font_size: gr.update(visible=watermark_type == "text"),
341
+ font_color: gr.update(visible=watermark_type == "text"),
342
+ resize_width: gr.update(visible=watermark_type == "image"),
343
+ resize_height: gr.update(visible=watermark_type == "image")
344
+ }
345
+
346
+ watermark_type.change(update_visibility, inputs=[watermark_type], outputs=[watermark_text, watermark_image, font_size, font_color, resize_width, resize_height])
347
+ watermark_submit.click(add_watermark, inputs=[video_file, watermark_type, watermark_text, watermark_image, opacity, position_x, position_y, font_size, font_color, resize_width, resize_height], outputs=[watermark_output, watermark_download])
348
+
349
+
350
+ with gr.Tab("Compress Image Losslessly"):
351
+ image_file = gr.File(label="Select Image File", type="filepath")
352
+ compress_submit = gr.Button("Compress Image Losslessly")
353
+ compress_output = gr.Textbox(label="Output")
354
+ compress_download = gr.File(label="Download Compressed Image")
355
+ compress_submit.click(compress_image_lossless, inputs=[image_file], outputs=[compress_output, compress_download])
356
+
357
+ with gr.Tab("Convert MP3 to Video"):
358
+ mp3_file = gr.File(label="Select MP3 File", type="filepath")
359
+ image_file = gr.File(label="Select Image File", type="filepath")
360
+ convert_submit = gr.Button("Convert MP3 to Video")
361
+ convert_output = gr.Textbox(label="Output")
362
+ convert_download = gr.File(label="Download Converted Video")
363
+ convert_submit.click(mp3_to_video, inputs=[mp3_file, image_file], outputs=[convert_output, convert_download])
364
+
365
+ with gr.Tab("Convert Video to MP3"):
366
+ video_file = gr.File(label="Select Video File", type="filepath")
367
+ convert_submit = gr.Button("Convert Video to MP3")
368
+ convert_output = gr.Textbox(label="Output")
369
+ convert_download = gr.File(label="Download Converted MP3")
370
+ convert_submit.click(video_to_mp3, inputs=[video_file], outputs=[convert_output, convert_download])
371
+
372
+ with gr.Tab("Convert Image Format"):
373
+ input_image = gr.File(label="Select Image File", type="filepath")
374
+ output_format = gr.Dropdown(label="Output Format", choices=["png", "jpg", "bmp", "gif"], value="png")
375
+ convert_submit = gr.Button("Convert Image Format")
376
+ convert_output = gr.Textbox(label="Output")
377
+ convert_download = gr.File(label="Download Converted Image")
378
+ convert_submit.click(convert_image_format, inputs=[input_image, output_format], outputs=[convert_output, convert_download])
379
+
380
+ return demo
381
+
382
+ if __name__ == "__main__":
383
+ demo = interface()
384
+ demo.launch(share=True)