MySafeCode commited on
Commit
d2b9965
·
verified ·
1 Parent(s): 077f2b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -81
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 warnings
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
- raise gr.Error(f"Conversion failed: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- def cleanup_temp_files():
42
- """Clean up temporary files if needed"""
43
  temp_dir = tempfile.gettempdir()
44
- for file in Path(temp_dir).glob("*.flac"):
45
- try:
46
- if file.stat().st_mtime < (time.time() - 3600): # Older than 1 hour
47
- file.unlink()
48
- except:
49
- pass
 
 
 
50
 
51
  # Create Gradio interface
52
- with gr.Blocks(title="MP3 to 16-bit FLAC Converter", theme=gr.themes.Soft()) as demo:
 
 
 
 
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" # Fixed: Changed from 'file' to 'filepath'
62
  )
63
- convert_btn = gr.Button("Convert to FLAC", variant="primary", scale=0)
64
 
65
- with gr.Accordion("Settings", open=False):
66
- info_text = gr.Markdown("""
 
 
 
 
 
 
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
- **Note:**
83
- - Maximum file size: 200MB
84
- - Processing time depends on file size
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
- # Additional info
94
- with gr.Accordion("ℹ️ About this converter", open=False):
95
  gr.Markdown("""
96
- ## Features
97
-
98
- **Audio Conversion:**
99
- - Converts MP3 to FLAC format
100
- - Ensures 16-bit depth (CD quality)
101
- - Maintains original sample rate and channels
102
- - Lossless compression for FLAC output
103
-
104
- **Technical Specifications:**
105
- - Uses pydub (FFmpeg wrapper) for audio processing
106
- - FLAC files use 16-bit PCM encoding (signed 16-bit integer)
107
- - Original channels (mono/stereo) are preserved
108
- - No quality loss in format conversion
109
-
110
- **Limitations:**
111
- - This converts formats, but cannot enhance audio quality
112
- - MP3 files are already lossy compressed
113
- - Output FLAC will have same perceived quality as input MP3
114
-
115
- **Supported Formats:** .mp3 .flac
 
 
 
 
 
 
 
116
  """)
117
 
118
- def update_stats(mp3_path):
119
- if mp3_path:
120
- try:
121
- audio = pydub.AudioSegment.from_mp3(mp3_path)
122
- stats = f"""
123
- **File Statistics:**
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
- # Update stats when file is uploaded
143
- mp3_input.change(
144
- fn=update_stats,
145
- inputs=[mp3_input],
146
- outputs=[stats_text]
147
  )
148
 
 
149
  if __name__ == "__main__":
150
- # Clean up old temp files on startup
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,