Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,17 +8,21 @@ from pydub import AudioSegment
|
|
| 8 |
from moviepy import VideoFileClip
|
| 9 |
|
| 10 |
|
|
|
|
| 11 |
def convert_audio(input_files, output_format, session_id, merge_files, gap_duration):
|
| 12 |
"""Converts or merges a list of audio files."""
|
| 13 |
output_files = []
|
| 14 |
merged_audio = AudioSegment.silent(duration=0)
|
| 15 |
|
|
|
|
|
|
|
| 16 |
for input_file in tqdm(input_files, desc="Converting audio files"):
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
output_filename = f"{base_name}.{output_format}"
|
| 20 |
output_path = os.path.join(session_id, output_filename)
|
| 21 |
-
os.makedirs(session_id, exist_ok=True)
|
| 22 |
audio.export(output_path, format=output_format)
|
| 23 |
|
| 24 |
if merge_files:
|
|
@@ -29,10 +33,12 @@ def convert_audio(input_files, output_format, session_id, merge_files, gap_durat
|
|
| 29 |
if merge_files:
|
| 30 |
merged_output_path = os.path.join(session_id, f"merged_output.{output_format}")
|
| 31 |
merged_audio.export(merged_output_path, format=output_format)
|
| 32 |
-
return merged_output_path
|
| 33 |
|
| 34 |
return output_files
|
| 35 |
|
|
|
|
|
|
|
| 36 |
def create_zip(files_to_zip, session_id):
|
| 37 |
"""Creates a ZIP archive from a list of files."""
|
| 38 |
zip_filename = f"{session_id}.zip"
|
|
@@ -41,6 +47,8 @@ def create_zip(files_to_zip, session_id):
|
|
| 41 |
zipf.write(file, os.path.basename(file))
|
| 42 |
return zip_filename
|
| 43 |
|
|
|
|
|
|
|
| 44 |
def process_audio_files(files, output_format, merge_files, gap_duration, progress=gr.Progress(track_tqdm=True)):
|
| 45 |
"""Main handler function for audio processing."""
|
| 46 |
if not files:
|
|
@@ -52,16 +60,15 @@ def process_audio_files(files, output_format, merge_files, gap_duration, progres
|
|
| 52 |
|
| 53 |
output_files = convert_audio(files, output_format, session_id, merge_files, gap_duration)
|
| 54 |
|
| 55 |
-
if
|
| 56 |
-
print("
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
zip_filename = create_zip(output_files, session_id)
|
| 61 |
-
print("Zipping complete!")
|
| 62 |
-
return zip_filename
|
| 63 |
|
| 64 |
|
|
|
|
| 65 |
def process_video(input_video, conversion_type, output_format, progress=gr.Progress(track_tqdm=True)):
|
| 66 |
"""Converts a video to another format or extracts its audio."""
|
| 67 |
if not input_video:
|
|
@@ -69,8 +76,9 @@ def process_video(input_video, conversion_type, output_format, progress=gr.Progr
|
|
| 69 |
|
| 70 |
session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_" + str(uuid.uuid4())[:8]
|
| 71 |
os.makedirs(session_id, exist_ok=True)
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
output_filename = f"{base_name}_converted.{output_format}"
|
| 75 |
output_path = os.path.join(session_id, output_filename)
|
| 76 |
|
|
@@ -78,20 +86,20 @@ def process_video(input_video, conversion_type, output_format, progress=gr.Progr
|
|
| 78 |
print(f"Conversion type: {conversion_type}, Output format: {output_format}")
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
clip = VideoFileClip(
|
| 82 |
|
| 83 |
if conversion_type == "Video to Video":
|
| 84 |
print("Converting video to video...")
|
| 85 |
-
clip.write_videofile(output_path, codec='libx264', audio_codec='aac', logger=
|
| 86 |
-
|
| 87 |
elif conversion_type == "Video to Audio":
|
| 88 |
print("Extracting audio from video...")
|
| 89 |
if clip.audio is None:
|
| 90 |
raise gr.Error("The uploaded video file does not contain an audio track.")
|
| 91 |
audio_clip = clip.audio
|
| 92 |
-
audio_clip.write_audiofile(output_path, logger=
|
| 93 |
audio_clip.close()
|
| 94 |
-
|
| 95 |
clip.close()
|
| 96 |
|
| 97 |
except Exception as e:
|
|
@@ -101,6 +109,8 @@ def process_video(input_video, conversion_type, output_format, progress=gr.Progr
|
|
| 101 |
print("Video processing complete!")
|
| 102 |
return output_path
|
| 103 |
|
|
|
|
|
|
|
| 104 |
def update_format_choices(conversion_type):
|
| 105 |
"""Dynamically updates the format dropdown based on the conversion type."""
|
| 106 |
if conversion_type == "Video to Video":
|
|
@@ -113,58 +123,63 @@ audio_formats = ["mp3", "wav", "flac", "ogg", "aac", "m4a", "aiff", "wma", "opus
|
|
| 113 |
video_formats = ["mp4", "webm", "mkv", "avi", "mov", "flv"]
|
| 114 |
|
| 115 |
|
|
|
|
| 116 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 117 |
gr.Markdown("# Universal Media Converter π§π¬")
|
| 118 |
gr.Markdown("Use the tabs below to switch between the Audio and Video converters.")
|
| 119 |
|
| 120 |
with gr.Tabs():
|
|
|
|
| 121 |
with gr.TabItem("πΆ Audio Converter"):
|
| 122 |
gr.Markdown("## Convert and Merge Audio Files")
|
| 123 |
-
gr.Markdown("Upload one or more audio files and select the output format. You can also merge all files into a single track
|
|
|
|
| 124 |
with gr.Row():
|
| 125 |
with gr.Column(scale=2):
|
| 126 |
audio_file_input = gr.Files(label="Upload Audio Files", file_types=["audio"])
|
| 127 |
with gr.Column(scale=1):
|
| 128 |
audio_format_choice = gr.Dropdown(choices=audio_formats, label="Output Format", value="mp3")
|
| 129 |
merge_files_checkbox = gr.Checkbox(label="Merge all files into one")
|
| 130 |
-
gap_slider = gr.Slider(minimum=0, maximum=5000, step=100, value=500, label="Gap between files (ms)"
|
| 131 |
-
|
| 132 |
audio_submit_button = gr.Button("π Convert", variant="primary")
|
| 133 |
audio_output_file = gr.File(label="Download Result")
|
| 134 |
-
|
| 135 |
audio_submit_button.click(
|
| 136 |
-
fn=process_audio_files,
|
| 137 |
-
inputs=[audio_file_input, audio_format_choice, merge_files_checkbox, gap_slider],
|
| 138 |
outputs=audio_output_file
|
| 139 |
)
|
| 140 |
|
|
|
|
| 141 |
with gr.TabItem("π¬ Video Converter"):
|
| 142 |
gr.Markdown("## Convert Video and Extract Audio")
|
| 143 |
gr.Markdown("Upload a video file, then choose whether to convert it to another video format or to extract its audio track.")
|
|
|
|
| 144 |
with gr.Row():
|
| 145 |
with gr.Column(scale=2):
|
| 146 |
-
video_input = gr.
|
| 147 |
with gr.Column(scale=1):
|
| 148 |
conversion_type_radio = gr.Radio(
|
| 149 |
-
choices=["Video to Video", "Video to Audio"],
|
| 150 |
-
label="Conversion Type",
|
| 151 |
value="Video to Video"
|
| 152 |
)
|
| 153 |
video_format_dropdown = gr.Dropdown(
|
| 154 |
-
choices=video_formats,
|
| 155 |
-
label="Output Video Format",
|
| 156 |
value="mp4"
|
| 157 |
)
|
| 158 |
-
|
| 159 |
video_submit_button = gr.Button("π Convert", variant="primary")
|
| 160 |
video_output_file = gr.File(label="Download Result")
|
| 161 |
|
| 162 |
conversion_type_radio.change(
|
| 163 |
-
fn=update_format_choices,
|
| 164 |
-
inputs=conversion_type_radio,
|
| 165 |
outputs=video_format_dropdown
|
| 166 |
)
|
| 167 |
-
|
| 168 |
video_submit_button.click(
|
| 169 |
fn=process_video,
|
| 170 |
inputs=[video_input, conversion_type_radio, video_format_dropdown],
|
|
@@ -172,4 +187,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
demo.launch(debug=True)
|
|
|
|
| 8 |
from moviepy import VideoFileClip
|
| 9 |
|
| 10 |
|
| 11 |
+
# ---------- AUDIO PROCESSING ----------
|
| 12 |
def convert_audio(input_files, output_format, session_id, merge_files, gap_duration):
|
| 13 |
"""Converts or merges a list of audio files."""
|
| 14 |
output_files = []
|
| 15 |
merged_audio = AudioSegment.silent(duration=0)
|
| 16 |
|
| 17 |
+
os.makedirs(session_id, exist_ok=True)
|
| 18 |
+
|
| 19 |
for input_file in tqdm(input_files, desc="Converting audio files"):
|
| 20 |
+
file_path = input_file if isinstance(input_file, str) else input_file.name
|
| 21 |
+
audio = AudioSegment.from_file(file_path)
|
| 22 |
+
|
| 23 |
+
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
| 24 |
output_filename = f"{base_name}.{output_format}"
|
| 25 |
output_path = os.path.join(session_id, output_filename)
|
|
|
|
| 26 |
audio.export(output_path, format=output_format)
|
| 27 |
|
| 28 |
if merge_files:
|
|
|
|
| 33 |
if merge_files:
|
| 34 |
merged_output_path = os.path.join(session_id, f"merged_output.{output_format}")
|
| 35 |
merged_audio.export(merged_output_path, format=output_format)
|
| 36 |
+
return [merged_output_path]
|
| 37 |
|
| 38 |
return output_files
|
| 39 |
|
| 40 |
+
|
| 41 |
+
# ---------- ZIP CREATION ----------
|
| 42 |
def create_zip(files_to_zip, session_id):
|
| 43 |
"""Creates a ZIP archive from a list of files."""
|
| 44 |
zip_filename = f"{session_id}.zip"
|
|
|
|
| 47 |
zipf.write(file, os.path.basename(file))
|
| 48 |
return zip_filename
|
| 49 |
|
| 50 |
+
|
| 51 |
+
# ---------- AUDIO HANDLER ----------
|
| 52 |
def process_audio_files(files, output_format, merge_files, gap_duration, progress=gr.Progress(track_tqdm=True)):
|
| 53 |
"""Main handler function for audio processing."""
|
| 54 |
if not files:
|
|
|
|
| 60 |
|
| 61 |
output_files = convert_audio(files, output_format, session_id, merge_files, gap_duration)
|
| 62 |
|
| 63 |
+
if len(output_files) > 1:
|
| 64 |
+
print("Creating ZIP archive...")
|
| 65 |
+
zip_filename = create_zip(output_files, session_id)
|
| 66 |
+
return zip_filename
|
| 67 |
|
| 68 |
+
return output_files[0]
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
+
# ---------- VIDEO HANDLER ----------
|
| 72 |
def process_video(input_video, conversion_type, output_format, progress=gr.Progress(track_tqdm=True)):
|
| 73 |
"""Converts a video to another format or extracts its audio."""
|
| 74 |
if not input_video:
|
|
|
|
| 76 |
|
| 77 |
session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_" + str(uuid.uuid4())[:8]
|
| 78 |
os.makedirs(session_id, exist_ok=True)
|
| 79 |
+
|
| 80 |
+
input_path = input_video if isinstance(input_video, str) else input_video.name
|
| 81 |
+
base_name = os.path.splitext(os.path.basename(input_path))[0]
|
| 82 |
output_filename = f"{base_name}_converted.{output_format}"
|
| 83 |
output_path = os.path.join(session_id, output_filename)
|
| 84 |
|
|
|
|
| 86 |
print(f"Conversion type: {conversion_type}, Output format: {output_format}")
|
| 87 |
|
| 88 |
try:
|
| 89 |
+
clip = VideoFileClip(input_path)
|
| 90 |
|
| 91 |
if conversion_type == "Video to Video":
|
| 92 |
print("Converting video to video...")
|
| 93 |
+
clip.write_videofile(output_path, codec='libx264', audio_codec='aac', logger=None)
|
| 94 |
+
|
| 95 |
elif conversion_type == "Video to Audio":
|
| 96 |
print("Extracting audio from video...")
|
| 97 |
if clip.audio is None:
|
| 98 |
raise gr.Error("The uploaded video file does not contain an audio track.")
|
| 99 |
audio_clip = clip.audio
|
| 100 |
+
audio_clip.write_audiofile(output_path, logger=None)
|
| 101 |
audio_clip.close()
|
| 102 |
+
|
| 103 |
clip.close()
|
| 104 |
|
| 105 |
except Exception as e:
|
|
|
|
| 109 |
print("Video processing complete!")
|
| 110 |
return output_path
|
| 111 |
|
| 112 |
+
|
| 113 |
+
# ---------- FORMAT CHOICES ----------
|
| 114 |
def update_format_choices(conversion_type):
|
| 115 |
"""Dynamically updates the format dropdown based on the conversion type."""
|
| 116 |
if conversion_type == "Video to Video":
|
|
|
|
| 123 |
video_formats = ["mp4", "webm", "mkv", "avi", "mov", "flv"]
|
| 124 |
|
| 125 |
|
| 126 |
+
# ---------- UI ----------
|
| 127 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 128 |
gr.Markdown("# Universal Media Converter π§π¬")
|
| 129 |
gr.Markdown("Use the tabs below to switch between the Audio and Video converters.")
|
| 130 |
|
| 131 |
with gr.Tabs():
|
| 132 |
+
# AUDIO TAB
|
| 133 |
with gr.TabItem("πΆ Audio Converter"):
|
| 134 |
gr.Markdown("## Convert and Merge Audio Files")
|
| 135 |
+
gr.Markdown("Upload one or more audio files and select the output format. You can also merge all files into a single track.")
|
| 136 |
+
|
| 137 |
with gr.Row():
|
| 138 |
with gr.Column(scale=2):
|
| 139 |
audio_file_input = gr.Files(label="Upload Audio Files", file_types=["audio"])
|
| 140 |
with gr.Column(scale=1):
|
| 141 |
audio_format_choice = gr.Dropdown(choices=audio_formats, label="Output Format", value="mp3")
|
| 142 |
merge_files_checkbox = gr.Checkbox(label="Merge all files into one")
|
| 143 |
+
gap_slider = gr.Slider(minimum=0, maximum=5000, step=100, value=500, label="Gap between files (ms)")
|
| 144 |
+
|
| 145 |
audio_submit_button = gr.Button("π Convert", variant="primary")
|
| 146 |
audio_output_file = gr.File(label="Download Result")
|
| 147 |
+
|
| 148 |
audio_submit_button.click(
|
| 149 |
+
fn=process_audio_files,
|
| 150 |
+
inputs=[audio_file_input, audio_format_choice, merge_files_checkbox, gap_slider],
|
| 151 |
outputs=audio_output_file
|
| 152 |
)
|
| 153 |
|
| 154 |
+
# VIDEO TAB
|
| 155 |
with gr.TabItem("π¬ Video Converter"):
|
| 156 |
gr.Markdown("## Convert Video and Extract Audio")
|
| 157 |
gr.Markdown("Upload a video file, then choose whether to convert it to another video format or to extract its audio track.")
|
| 158 |
+
|
| 159 |
with gr.Row():
|
| 160 |
with gr.Column(scale=2):
|
| 161 |
+
video_input = gr.File(label="Upload Video File", file_types=["video"])
|
| 162 |
with gr.Column(scale=1):
|
| 163 |
conversion_type_radio = gr.Radio(
|
| 164 |
+
choices=["Video to Video", "Video to Audio"],
|
| 165 |
+
label="Conversion Type",
|
| 166 |
value="Video to Video"
|
| 167 |
)
|
| 168 |
video_format_dropdown = gr.Dropdown(
|
| 169 |
+
choices=video_formats,
|
| 170 |
+
label="Output Video Format",
|
| 171 |
value="mp4"
|
| 172 |
)
|
| 173 |
+
|
| 174 |
video_submit_button = gr.Button("π Convert", variant="primary")
|
| 175 |
video_output_file = gr.File(label="Download Result")
|
| 176 |
|
| 177 |
conversion_type_radio.change(
|
| 178 |
+
fn=update_format_choices,
|
| 179 |
+
inputs=conversion_type_radio,
|
| 180 |
outputs=video_format_dropdown
|
| 181 |
)
|
| 182 |
+
|
| 183 |
video_submit_button.click(
|
| 184 |
fn=process_video,
|
| 185 |
inputs=[video_input, conversion_type_radio, video_format_dropdown],
|
|
|
|
| 187 |
)
|
| 188 |
|
| 189 |
if __name__ == "__main__":
|
| 190 |
+
demo.launch(debug=True)
|