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

Upload 2 files

Browse files
Files changed (2) hide show
  1. media_utils.py +383 -0
  2. requirements.txt +4 -0
media_utils.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ tqdm
3
+ Pillow
4
+ torch