Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import uuid
|
3 |
+
import zipfile
|
4 |
+
import gradio as gr
|
5 |
+
from datetime import datetime
|
6 |
+
from pydub import AudioSegment
|
7 |
+
|
8 |
+
|
9 |
+
def convert_audio(input_files, output_format, session_id):
|
10 |
+
output_files = []
|
11 |
+
for input_file in input_files:
|
12 |
+
# Load the audio file
|
13 |
+
audio = AudioSegment.from_file(input_file)
|
14 |
+
|
15 |
+
# Create the output filename
|
16 |
+
base_name = os.path.splitext(os.path.basename(input_file))[0]
|
17 |
+
output_filename = f"{base_name}.{output_format}"
|
18 |
+
output_path = os.path.join(session_id, output_filename)
|
19 |
+
|
20 |
+
# Ensure the output directory exists
|
21 |
+
os.makedirs(session_id, exist_ok=True)
|
22 |
+
|
23 |
+
# Export the audio file to the desired format
|
24 |
+
audio.export(output_path, format=output_format)
|
25 |
+
output_files.append(output_path)
|
26 |
+
|
27 |
+
return output_files
|
28 |
+
|
29 |
+
|
30 |
+
def create_zip(output_files, session_id):
|
31 |
+
zip_filename = f"{session_id}.zip"
|
32 |
+
with zipfile.ZipFile(zip_filename, 'w') as zipf:
|
33 |
+
for file in output_files:
|
34 |
+
zipf.write(file, os.path.basename(file))
|
35 |
+
return zip_filename
|
36 |
+
|
37 |
+
|
38 |
+
def process_files(files, output_format):
|
39 |
+
# Generate a unique session ID using timestamp and UUID
|
40 |
+
session_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + str(uuid.uuid4()[:8])
|
41 |
+
output_files = convert_audio(files, output_format, session_id)
|
42 |
+
zip_filename = create_zip(output_files, session_id)
|
43 |
+
return zip_filename
|
44 |
+
|
45 |
+
|
46 |
+
# List of supported audio formats
|
47 |
+
audio_formats = [
|
48 |
+
"wav", "flac", "mp3", "ogg", "aac", "m4a", "aiff", "wma", "opus", "ac3",
|
49 |
+
"amr", "dts", "mka", "au", "ra", "voc", "iff", "sd2", "wv", "caf",
|
50 |
+
"mpc", "tta", "spx", "gsm"
|
51 |
+
]
|
52 |
+
|
53 |
+
|
54 |
+
with gr.Blocks() as demo:
|
55 |
+
gr.Markdown("## Audio File Converter")
|
56 |
+
with gr.Row():
|
57 |
+
file_input = gr.Files(file_types=["audio"], height=160)
|
58 |
+
format_choice = gr.Dropdown(choices=audio_formats, label="Output Format", value="mp3")
|
59 |
+
submit_button = gr.Button("Convert")
|
60 |
+
output_file = gr.File(label="Download Converted File")
|
61 |
+
submit_button.click(process_files, inputs=[file_input, format_choice], outputs=output_file)
|
62 |
+
|
63 |
+
if __name__ == "__main__":
|
64 |
+
demo.launch()
|