Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pydub
|
| 3 |
-
import numpy as np
|
| 4 |
-
import os
|
| 5 |
import tempfile
|
| 6 |
from pathlib import Path
|
| 7 |
import time
|
| 8 |
-
import
|
| 9 |
-
warnings.filterwarnings("ignore")
|
| 10 |
|
| 11 |
def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
|
| 12 |
"""Convert MP3 file to 16-bit FLAC"""
|
| 13 |
try:
|
|
|
|
|
|
|
|
|
|
| 14 |
progress(0, desc="Starting conversion...")
|
| 15 |
|
| 16 |
# Read MP3 file
|
|
@@ -28,7 +32,7 @@ def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
|
|
| 28 |
with tempfile.NamedTemporaryFile(suffix='.flac', delete=False) as tmp:
|
| 29 |
flac_path = tmp.name
|
| 30 |
|
| 31 |
-
# Export as FLAC
|
| 32 |
audio.export(flac_path, format="flac", parameters=["-sample_fmt", "s16"])
|
| 33 |
|
| 34 |
progress(1.0, desc="Conversion complete!")
|
|
@@ -36,119 +40,138 @@ def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
|
|
| 36 |
return flac_path
|
| 37 |
|
| 38 |
except Exception as e:
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
def
|
| 42 |
-
"""Clean up temporary files
|
| 43 |
temp_dir = tempfile.gettempdir()
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
# Create Gradio interface
|
| 52 |
-
with gr.Blocks(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
gr.Markdown("# 🎵 MP3 to 16-bit FLAC Converter")
|
| 54 |
gr.Markdown("Upload an MP3 file and convert it to 16-bit FLAC format")
|
| 55 |
|
| 56 |
with gr.Row():
|
| 57 |
with gr.Column(scale=1):
|
| 58 |
mp3_input = gr.File(
|
| 59 |
-
label="Upload MP3 File",
|
| 60 |
file_types=[".mp3"],
|
| 61 |
-
type="filepath"
|
| 62 |
)
|
| 63 |
-
convert_btn = gr.Button("Convert to FLAC", variant="primary", scale=0)
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
**Default Settings:**
|
| 68 |
- Output format: FLAC
|
| 69 |
- Bit depth: 16-bit
|
| 70 |
- Channels: Preserved from source
|
| 71 |
- Sample rate: Preserved from source
|
|
|
|
| 72 |
""")
|
| 73 |
|
| 74 |
with gr.Column(scale=1):
|
| 75 |
flac_output = gr.File(
|
| 76 |
-
label="Download FLAC File",
|
| 77 |
file_types=[".flac"]
|
| 78 |
)
|
| 79 |
-
info_box = gr.Markdown("""
|
| 80 |
-
**Conversion Status:** Waiting for file upload...
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
- Download link will appear after conversion
|
| 86 |
-
""")
|
| 87 |
-
|
| 88 |
-
# Stats display
|
| 89 |
-
with gr.Row():
|
| 90 |
-
with gr.Column():
|
| 91 |
-
stats_text = gr.Markdown("**File Statistics:** No file processed yet")
|
| 92 |
|
| 93 |
-
#
|
| 94 |
-
with gr.Accordion("
|
| 95 |
gr.Markdown("""
|
| 96 |
-
##
|
| 97 |
-
|
| 98 |
-
**
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
-
|
| 107 |
-
-
|
| 108 |
-
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
""")
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
- Duration: {len(audio) / 1000:.2f} seconds
|
| 125 |
-
- Channels: {'Mono' if audio.channels == 1 else 'Stereo'}
|
| 126 |
-
- Sample Rate: {audio.frame_rate} Hz
|
| 127 |
-
- Bit Depth: 16-bit (output)
|
| 128 |
-
- File Size: {os.path.getsize(mp3_path) / 1024 / 1024:.2f} MB
|
| 129 |
-
"""
|
| 130 |
-
return stats
|
| 131 |
-
except:
|
| 132 |
-
return "**File Statistics:** Could not read file details"
|
| 133 |
-
return "**File Statistics:** No file processed yet"
|
| 134 |
|
| 135 |
-
# Connect the conversion function
|
| 136 |
convert_btn.click(
|
| 137 |
fn=convert_mp3_to_flac,
|
| 138 |
inputs=[mp3_input],
|
| 139 |
outputs=[flac_output]
|
| 140 |
-
)
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
mp3_input.change(
|
| 144 |
-
fn=update_stats,
|
| 145 |
-
inputs=[mp3_input],
|
| 146 |
-
outputs=[stats_text]
|
| 147 |
)
|
| 148 |
|
|
|
|
| 149 |
if __name__ == "__main__":
|
| 150 |
-
|
| 151 |
-
cleanup_temp_files()
|
| 152 |
demo.launch(
|
| 153 |
server_name="0.0.0.0",
|
| 154 |
server_port=7860,
|
|
|
|
| 1 |
+
|
| 2 |
+
## **Updated app.py for Hugging Face Spaces:**
|
| 3 |
+
|
| 4 |
+
```python
|
| 5 |
import gradio as gr
|
| 6 |
import pydub
|
|
|
|
|
|
|
| 7 |
import tempfile
|
| 8 |
from pathlib import Path
|
| 9 |
import time
|
| 10 |
+
import os
|
|
|
|
| 11 |
|
| 12 |
def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
|
| 13 |
"""Convert MP3 file to 16-bit FLAC"""
|
| 14 |
try:
|
| 15 |
+
if not mp3_file_path:
|
| 16 |
+
raise ValueError("No file uploaded")
|
| 17 |
+
|
| 18 |
progress(0, desc="Starting conversion...")
|
| 19 |
|
| 20 |
# Read MP3 file
|
|
|
|
| 32 |
with tempfile.NamedTemporaryFile(suffix='.flac', delete=False) as tmp:
|
| 33 |
flac_path = tmp.name
|
| 34 |
|
| 35 |
+
# Export as FLAC with 16-bit PCM
|
| 36 |
audio.export(flac_path, format="flac", parameters=["-sample_fmt", "s16"])
|
| 37 |
|
| 38 |
progress(1.0, desc="Conversion complete!")
|
|
|
|
| 40 |
return flac_path
|
| 41 |
|
| 42 |
except Exception as e:
|
| 43 |
+
error_msg = f"Conversion failed: {str(e)}"
|
| 44 |
+
raise gr.Error(error_msg)
|
| 45 |
+
|
| 46 |
+
def get_file_stats(file_path):
|
| 47 |
+
"""Get statistics about the uploaded file"""
|
| 48 |
+
if not file_path or not os.path.exists(file_path):
|
| 49 |
+
return "**File Statistics:** No file uploaded"
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
audio = pydub.AudioSegment.from_mp3(file_path)
|
| 53 |
+
file_size = os.path.getsize(file_path)
|
| 54 |
+
|
| 55 |
+
stats = f"""
|
| 56 |
+
**File Statistics:**
|
| 57 |
+
- Duration: {len(audio) / 1000:.2f} seconds
|
| 58 |
+
- Channels: {'Mono' if audio.channels == 1 else 'Stereo'}
|
| 59 |
+
- Sample Rate: {audio.frame_rate:,} Hz
|
| 60 |
+
- Bit Depth: 16-bit (output)
|
| 61 |
+
- File Size: {file_size / 1024 / 1024:.2f} MB
|
| 62 |
+
- Format: MP3 → FLAC
|
| 63 |
+
"""
|
| 64 |
+
return stats
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return f"**File Statistics:** Could not read file details - {str(e)}"
|
| 67 |
|
| 68 |
+
def cleanup_old_files():
|
| 69 |
+
"""Clean up temporary files older than 1 hour"""
|
| 70 |
temp_dir = tempfile.gettempdir()
|
| 71 |
+
current_time = time.time()
|
| 72 |
+
|
| 73 |
+
for ext in ['.flac', '.mp3']:
|
| 74 |
+
for file in Path(temp_dir).glob(f"*{ext}"):
|
| 75 |
+
try:
|
| 76 |
+
if file.stat().st_mtime < (current_time - 3600):
|
| 77 |
+
file.unlink()
|
| 78 |
+
except:
|
| 79 |
+
pass
|
| 80 |
|
| 81 |
# Create Gradio interface
|
| 82 |
+
with gr.Blocks(
|
| 83 |
+
title="MP3 to 16-bit FLAC Converter",
|
| 84 |
+
theme=gr.themes.Soft()
|
| 85 |
+
) as demo:
|
| 86 |
+
|
| 87 |
gr.Markdown("# 🎵 MP3 to 16-bit FLAC Converter")
|
| 88 |
gr.Markdown("Upload an MP3 file and convert it to 16-bit FLAC format")
|
| 89 |
|
| 90 |
with gr.Row():
|
| 91 |
with gr.Column(scale=1):
|
| 92 |
mp3_input = gr.File(
|
| 93 |
+
label="📁 Upload MP3 File",
|
| 94 |
file_types=[".mp3"],
|
| 95 |
+
type="filepath"
|
| 96 |
)
|
|
|
|
| 97 |
|
| 98 |
+
convert_btn = gr.Button(
|
| 99 |
+
"🔄 Convert to FLAC",
|
| 100 |
+
variant="primary",
|
| 101 |
+
size="lg"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
with gr.Accordion("⚙️ Conversion Settings", open=False):
|
| 105 |
+
gr.Markdown("""
|
| 106 |
**Default Settings:**
|
| 107 |
- Output format: FLAC
|
| 108 |
- Bit depth: 16-bit
|
| 109 |
- Channels: Preserved from source
|
| 110 |
- Sample rate: Preserved from source
|
| 111 |
+
- Compression: Lossless
|
| 112 |
""")
|
| 113 |
|
| 114 |
with gr.Column(scale=1):
|
| 115 |
flac_output = gr.File(
|
| 116 |
+
label="💾 Download FLAC File",
|
| 117 |
file_types=[".flac"]
|
| 118 |
)
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
stats_display = gr.Markdown(
|
| 121 |
+
"**File Statistics:** Upload a file to see details"
|
| 122 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
# Info section
|
| 125 |
+
with gr.Accordion("📚 How to Use & Info", open=False):
|
| 126 |
gr.Markdown("""
|
| 127 |
+
## Usage Instructions
|
| 128 |
+
|
| 129 |
+
1. **Upload** an MP3 file using the upload button or drag & drop
|
| 130 |
+
2. **Check** the file statistics to verify your upload
|
| 131 |
+
3. **Click** the "Convert to FLAC" button
|
| 132 |
+
4. **Wait** for the conversion to complete (progress bar will show)
|
| 133 |
+
5. **Download** your converted FLAC file
|
| 134 |
+
|
| 135 |
+
## Technical Information
|
| 136 |
+
|
| 137 |
+
- **Input**: MP3 files of any bitrate (8-320 kbps)
|
| 138 |
+
- **Output**: 16-bit FLAC (lossless compression)
|
| 139 |
+
- **Maximum file size**: 200MB
|
| 140 |
+
- **Processing time**: ~1-2 seconds per minute of audio
|
| 141 |
+
|
| 142 |
+
## Important Notes
|
| 143 |
+
|
| 144 |
+
⚠️ **Converting MP3 to FLAC does NOT improve audio quality**
|
| 145 |
+
- MP3 is a lossy format - some audio data is permanently removed
|
| 146 |
+
- FLAC is lossless but cannot restore what was lost in MP3 compression
|
| 147 |
+
- The FLAC file will have the same perceived quality as the original MP3
|
| 148 |
+
|
| 149 |
+
## Use Cases
|
| 150 |
+
|
| 151 |
+
- Preparing audio for editing software that prefers FLAC
|
| 152 |
+
- Archiving music in a lossless format
|
| 153 |
+
- Compatibility with devices that require FLAC
|
| 154 |
""")
|
| 155 |
|
| 156 |
+
# Connect components
|
| 157 |
+
mp3_input.change(
|
| 158 |
+
fn=get_file_stats,
|
| 159 |
+
inputs=[mp3_input],
|
| 160 |
+
outputs=[stats_display]
|
| 161 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
|
|
|
| 163 |
convert_btn.click(
|
| 164 |
fn=convert_mp3_to_flac,
|
| 165 |
inputs=[mp3_input],
|
| 166 |
outputs=[flac_output]
|
| 167 |
+
).then(
|
| 168 |
+
fn=lambda: "**Status:** Ready for new conversion",
|
| 169 |
+
outputs=[stats_display]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
)
|
| 171 |
|
| 172 |
+
# Clean up old files and launch
|
| 173 |
if __name__ == "__main__":
|
| 174 |
+
cleanup_old_files()
|
|
|
|
| 175 |
demo.launch(
|
| 176 |
server_name="0.0.0.0",
|
| 177 |
server_port=7860,
|