Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,14 +5,17 @@ import gradio as gr
|
|
| 5 |
from tqdm import tqdm
|
| 6 |
from datetime import datetime
|
| 7 |
from pydub import AudioSegment
|
|
|
|
|
|
|
| 8 |
|
| 9 |
def convert_audio(input_files, output_format, session_id, merge_files, gap_duration):
|
|
|
|
| 10 |
output_files = []
|
| 11 |
merged_audio = AudioSegment.silent(duration=0)
|
| 12 |
|
| 13 |
-
for input_file in tqdm(input_files, desc="Converting files"):
|
| 14 |
-
audio = AudioSegment.from_file(input_file)
|
| 15 |
-
base_name = os.path.splitext(os.path.basename(input_file))[0]
|
| 16 |
output_filename = f"{base_name}.{output_format}"
|
| 17 |
output_path = os.path.join(session_id, output_filename)
|
| 18 |
os.makedirs(session_id, exist_ok=True)
|
|
@@ -20,53 +23,153 @@ def convert_audio(input_files, output_format, session_id, merge_files, gap_durat
|
|
| 20 |
|
| 21 |
if merge_files:
|
| 22 |
merged_audio += audio + AudioSegment.silent(duration=gap_duration)
|
|
|
|
|
|
|
| 23 |
|
| 24 |
if merge_files:
|
| 25 |
merged_output_path = os.path.join(session_id, f"merged_output.{output_format}")
|
| 26 |
merged_audio.export(merged_output_path, format=output_format)
|
| 27 |
return merged_output_path
|
| 28 |
|
| 29 |
-
return
|
| 30 |
|
| 31 |
-
def create_zip(
|
|
|
|
| 32 |
zip_filename = f"{session_id}.zip"
|
| 33 |
with zipfile.ZipFile(zip_filename, 'w') as zipf:
|
| 34 |
-
for file in tqdm(
|
| 35 |
zipf.write(file, os.path.basename(file))
|
| 36 |
return zip_filename
|
| 37 |
|
| 38 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_" + str(uuid.uuid4())[:8]
|
| 40 |
-
print(f"\nStarting
|
| 41 |
-
print(f"
|
| 42 |
|
| 43 |
output_files = convert_audio(files, output_format, session_id, merge_files, gap_duration)
|
| 44 |
|
| 45 |
-
print("Processing completed!")
|
| 46 |
if merge_files:
|
|
|
|
| 47 |
return output_files
|
| 48 |
|
|
|
|
| 49 |
zip_filename = create_zip(output_files, session_id)
|
|
|
|
| 50 |
return zip_filename
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
"
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
with gr.Row():
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
if __name__ == "__main__":
|
| 72 |
-
demo.launch()
|
|
|
|
| 5 |
from tqdm import tqdm
|
| 6 |
from datetime import datetime
|
| 7 |
from pydub import AudioSegment
|
| 8 |
+
from moviepy.editor 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 |
+
audio = AudioSegment.from_file(input_file.name)
|
| 18 |
+
base_name = os.path.splitext(os.path.basename(input_file.name))[0]
|
| 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)
|
|
|
|
| 23 |
|
| 24 |
if merge_files:
|
| 25 |
merged_audio += audio + AudioSegment.silent(duration=gap_duration)
|
| 26 |
+
else:
|
| 27 |
+
output_files.append(output_path)
|
| 28 |
|
| 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"
|
| 39 |
with zipfile.ZipFile(zip_filename, 'w') as zipf:
|
| 40 |
+
for file in tqdm(files_to_zip, desc="Creating ZIP archive"):
|
| 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:
|
| 47 |
+
raise gr.Error("Please upload at least one audio file!")
|
| 48 |
+
|
| 49 |
session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_" + str(uuid.uuid4())[:8]
|
| 50 |
+
print(f"\nStarting audio session: {session_id}")
|
| 51 |
+
print(f"Files to convert: {len(files)} to format {output_format}")
|
| 52 |
|
| 53 |
output_files = convert_audio(files, output_format, session_id, merge_files, gap_duration)
|
| 54 |
|
|
|
|
| 55 |
if merge_files:
|
| 56 |
+
print("Merging complete!")
|
| 57 |
return output_files
|
| 58 |
|
| 59 |
+
print("Conversion complete! Creating ZIP archive...")
|
| 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:
|
| 68 |
+
raise gr.Error("Please upload a video file first!")
|
| 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 |
+
base_name = os.path.splitext(os.path.basename(input_video))[0]
|
| 74 |
+
output_filename = f"{base_name}_converted.{output_format}"
|
| 75 |
+
output_path = os.path.join(session_id, output_filename)
|
| 76 |
+
|
| 77 |
+
print(f"\nStarting video session: {session_id}")
|
| 78 |
+
print(f"Conversion type: {conversion_type}, Output format: {output_format}")
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
clip = VideoFileClip(input_video)
|
| 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='bar')
|
| 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='bar')
|
| 93 |
+
audio_clip.close()
|
| 94 |
+
|
| 95 |
+
clip.close()
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"An error occurred: {e}")
|
| 99 |
+
raise gr.Error(f"An error occurred during processing: {e}")
|
| 100 |
+
|
| 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":
|
| 107 |
+
return gr.Dropdown(choices=video_formats, value="mp4", label="Output Video Format")
|
| 108 |
+
else:
|
| 109 |
+
return gr.Dropdown(choices=audio_formats, value="mp3", label="Output Audio Format")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
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 by checking the box.")
|
| 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)", info="Only used when merging")
|
| 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.Video(label="Upload Video File")
|
| 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],
|
| 171 |
+
outputs=video_output_file
|
| 172 |
+
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
+
demo.launch(debug=True)
|