mp3to16bitflac / app.py
MySafeCode's picture
Update app.py
77ecfd5 verified
raw
history blame
5.2 kB
import gradio as gr
import pydub
import numpy as np
import os
import tempfile
from pathlib import Path
import time
import warnings
warnings.filterwarnings("ignore")
def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
"""Convert MP3 file to 16-bit FLAC"""
try:
progress(0, desc="Starting conversion...")
# Read MP3 file
progress(0.2, desc="Loading MP3 file...")
audio = pydub.AudioSegment.from_mp3(mp3_file_path)
# Ensure it's 16-bit (PCM_16)
progress(0.5, desc="Converting to 16-bit PCM...")
audio = audio.set_sample_width(2) # 2 bytes = 16 bits
# Save as FLAC
progress(0.8, desc="Saving as FLAC...")
# Create temporary file for output
with tempfile.NamedTemporaryFile(suffix='.flac', delete=False) as tmp:
flac_path = tmp.name
# Export as FLAC
audio.export(flac_path, format="flac", parameters=["-sample_fmt", "s16"])
progress(1.0, desc="Conversion complete!")
return flac_path
except Exception as e:
raise gr.Error(f"Conversion failed: {str(e)}")
def cleanup_temp_files():
"""Clean up temporary files if needed"""
temp_dir = tempfile.gettempdir()
for file in Path(temp_dir).glob("*.flac"):
try:
if file.stat().st_mtime < (time.time() - 3600): # Older than 1 hour
file.unlink()
except:
pass
# Create Gradio interface
with gr.Blocks(title="MP3 to 16-bit FLAC Converter", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🎵 MP3 to 16-bit FLAC Converter")
gr.Markdown("Upload an MP3 file and convert it to 16-bit FLAC format")
with gr.Row():
with gr.Column(scale=1):
mp3_input = gr.File(
label="Upload MP3 File",
file_types=[".mp3"],
type="filepath" # Fixed: Changed from 'file' to 'filepath'
)
convert_btn = gr.Button("Convert to FLAC", variant="primary", scale=0)
with gr.Accordion("Settings", open=False):
info_text = gr.Markdown("""
**Default Settings:**
- Output format: FLAC
- Bit depth: 16-bit
- Channels: Preserved from source
- Sample rate: Preserved from source
""")
with gr.Column(scale=1):
flac_output = gr.File(
label="Download FLAC File",
file_types=[".flac"]
)
info_box = gr.Markdown("""
**Conversion Status:** Waiting for file upload...
**Note:**
- Maximum file size: 200MB
- Processing time depends on file size
- Download link will appear after conversion
""")
# Stats display
with gr.Row():
with gr.Column():
stats_text = gr.Markdown("**File Statistics:** No file processed yet")
# Additional info
with gr.Accordion("ℹ️ About this converter", open=False):
gr.Markdown("""
## Features
**Audio Conversion:**
- Converts MP3 to FLAC format
- Ensures 16-bit depth (CD quality)
- Maintains original sample rate and channels
- Lossless compression for FLAC output
**Technical Specifications:**
- Uses pydub (FFmpeg wrapper) for audio processing
- FLAC files use 16-bit PCM encoding (signed 16-bit integer)
- Original channels (mono/stereo) are preserved
- No quality loss in format conversion
**Limitations:**
- This converts formats, but cannot enhance audio quality
- MP3 files are already lossy compressed
- Output FLAC will have same perceived quality as input MP3
**Supported Formats:** .mp3 → .flac
""")
def update_stats(mp3_path):
if mp3_path:
try:
audio = pydub.AudioSegment.from_mp3(mp3_path)
stats = f"""
**File Statistics:**
- Duration: {len(audio) / 1000:.2f} seconds
- Channels: {'Mono' if audio.channels == 1 else 'Stereo'}
- Sample Rate: {audio.frame_rate} Hz
- Bit Depth: 16-bit (output)
- File Size: {os.path.getsize(mp3_path) / 1024 / 1024:.2f} MB
"""
return stats
except:
return "**File Statistics:** Could not read file details"
return "**File Statistics:** No file processed yet"
# Connect the conversion function
convert_btn.click(
fn=convert_mp3_to_flac,
inputs=[mp3_input],
outputs=[flac_output]
)
# Update stats when file is uploaded
mp3_input.change(
fn=update_stats,
inputs=[mp3_input],
outputs=[stats_text]
)
if __name__ == "__main__":
# Clean up old temp files on startup
cleanup_temp_files()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)