avnigashi commited on
Commit
4828ead
·
verified ·
1 Parent(s): ce49923

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +333 -189
app.py CHANGED
@@ -2,14 +2,18 @@ import os
2
  import tempfile
3
  import gradio as gr
4
  import eyed3
5
- from PIL import Image
6
  import io
7
  import shutil
8
  from pydub import AudioSegment
9
  import numpy as np
 
10
 
11
  # Function to load MP3 file and extract metadata
12
  def load_mp3(file_obj):
 
 
 
13
  # Create a temporary directory
14
  temp_dir = tempfile.mkdtemp()
15
  temp_path = os.path.join(temp_dir, "temp.mp3")
@@ -28,44 +32,128 @@ def load_mp3(file_obj):
28
  if audiofile is None or audiofile.tag is None:
29
  # Create a new tag if one doesn't exist
30
  if audiofile is None:
31
- return None, "Invalid MP3 file", None, None, None, None, None, None, None, None, None, None
32
  audiofile.initTag()
33
 
34
- title = audiofile.tag.title or ""
35
- artist = audiofile.tag.artist or ""
36
- album = audiofile.tag.album or ""
37
- year = str(audiofile.tag.getBestDate() or "")
38
- track_num = str(audiofile.tag.track_num[0]) if audiofile.tag.track_num and audiofile.tag.track_num[0] else ""
39
- genre = str(audiofile.tag.genre or "")
40
- comments = audiofile.tag.comments[0].text if audiofile.tag.comments and len(audiofile.tag.comments) > 0 else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # Extract album art if available
43
  cover_art = None
44
- for img in audiofile.tag.images:
45
- if img.picture_type == 3: # Front cover
46
- image_data = img.image_data
47
- cover_art = Image.open(io.BytesIO(image_data))
48
- break
 
 
 
49
 
50
- # Return the file path and metadata
51
- return (
52
- temp_path, # File path (for internal use)
53
- os.path.basename(file_path), # File name (for display)
54
- title,
55
- artist,
56
- album,
57
- year,
58
- track_num,
59
- genre,
60
- comments,
61
- cover_art,
62
- temp_path, # Audio path for the audio component
63
- "File loaded successfully!"
64
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  except Exception as e:
67
  print(f"Error loading MP3: {str(e)}")
68
- return None, f"Error: {str(e)}", None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # Function to save changes and provide download
71
  def save_changes(
@@ -79,8 +167,10 @@ def save_changes(
79
  comments,
80
  cover_art,
81
  remove_cover_art_option,
82
- audio_data,
83
  enable_cutting,
 
 
84
  save_selection_only
85
  ):
86
  if not file_path:
@@ -88,7 +178,7 @@ def save_changes(
88
 
89
  try:
90
  # Create output path
91
- output_dir = tempfile.mkdtemp()
92
  filename = os.path.basename(file_path)
93
  if not filename.endswith('.mp3'):
94
  filename += '.mp3'
@@ -96,44 +186,26 @@ def save_changes(
96
  output_path = os.path.join(output_dir, f"edited_{filename}")
97
 
98
  # Handle audio cutting if enabled
99
- if enable_cutting and audio_data and isinstance(audio_data, tuple):
100
  try:
101
- # Check if we got a trimmed selection from the Audio component
102
- sample_rate, audio_array = audio_data
103
 
104
- # Convert to AudioSegment for saving
105
- # Ensure audio data is in the correct format
106
- if audio_array.dtype != np.int16:
107
- audio_array = (audio_array * 32767).astype(np.int16)
108
 
109
- # Create AudioSegment from numpy array
110
- # If audio is stereo, shape will be (samples, channels)
111
- # If audio is mono, shape will be (samples,)
112
- channels = 1
113
- if len(audio_array.shape) > 1:
114
- channels = audio_array.shape[1]
115
 
116
- # Create AudioSegment
117
- if channels == 1:
118
- segment = AudioSegment(
119
- audio_array.tobytes(),
120
- frame_rate=sample_rate,
121
- sample_width=2, # 16-bit audio = 2 bytes
122
- channels=1
123
- )
124
- else:
125
- segment = AudioSegment(
126
- audio_array.tobytes(),
127
- frame_rate=sample_rate,
128
- sample_width=2,
129
- channels=channels
130
- )
131
 
132
  # If saving only the selection, use this as our new audio
133
  if save_selection_only:
134
  # Save to a temporary file
135
  temp_cut_path = os.path.join(output_dir, "temp_cut.mp3")
136
- segment.export(temp_cut_path, format="mp3")
137
 
138
  # Use this as our source for metadata
139
  file_path = temp_cut_path
@@ -141,104 +213,125 @@ def save_changes(
141
  # Otherwise just copy the original file for metadata editing
142
  shutil.copy2(file_path, output_path)
143
  except Exception as e:
144
- return None, f"Error processing audio: {str(e)}"
145
  else:
146
  # Just copy the file if not cutting
147
  shutil.copy2(file_path, output_path)
148
 
149
  # Load the MP3 file for metadata editing
150
- audiofile = eyed3.load(file_path)
151
- if audiofile is None:
152
- return None, "Failed to load MP3 file"
153
-
154
- # Ensure there's a tag
155
- if audiofile.tag is None:
156
- audiofile.initTag()
157
-
158
- # Update the metadata
159
- audiofile.tag.title = title
160
- audiofile.tag.artist = artist
161
- audiofile.tag.album = album
162
-
163
- # Handle year
164
- if year:
165
- try:
166
- audiofile.tag.year = int(year)
167
- except ValueError:
168
- pass
169
-
170
- # Handle track number
171
- if track_num:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  try:
173
- audiofile.tag.track_num = int(track_num)
174
- except ValueError:
175
- pass
176
-
177
- # Handle genre
178
- if genre:
179
- audiofile.tag.genre = genre
180
-
181
- # Handle comments
182
- # First remove any existing comments
183
- for comment in list(audiofile.tag.comments):
184
- audiofile.tag.comments.remove(comment.description)
185
-
186
- if comments:
187
- audiofile.tag.comments.set(comments, description="", lang="eng")
188
-
189
- # Remove cover art if requested
190
- if remove_cover_art_option:
191
- for img in list(audiofile.tag.images):
192
- audiofile.tag.images.remove(img.description)
193
- else:
194
- # Handle cover art if new art is uploaded
195
- if cover_art is not None and isinstance(cover_art, dict) and "name" in cover_art:
196
- # Remove existing cover art
197
- for img in list(audiofile.tag.images):
198
- audiofile.tag.images.remove(img.description)
199
 
200
- # Add new cover art
201
- with open(cover_art["name"], "rb") as img_file:
202
- img_data = img_file.read()
203
- mime_type = "image/jpeg" if cover_art["name"].lower().endswith((".jpg", ".jpeg")) else "image/png"
204
- audiofile.tag.images.set(3, img_data, mime_type, "Front cover")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  # Save the metadata
207
- audiofile.tag.save(output_path if save_selection_only else None)
 
 
 
208
 
209
  # If we're saving a selection, we need to copy the edited metadata to our cut file
210
  if enable_cutting and save_selection_only:
211
- # Export the cut audio with metadata
212
- temp_cut_path = os.path.join(output_dir, "temp_cut.mp3")
213
- output_audio = AudioSegment.from_mp3(temp_cut_path)
214
- output_audio.export(output_path, format="mp3", tags={
215
- 'title': title,
216
- 'artist': artist,
217
- 'album': album,
218
- 'year': year,
219
- 'track': track_num,
220
- 'genre': genre,
221
- 'comments': comments
222
- })
223
-
224
- # Handle cover art separately since pydub doesn't support it well
225
- if not remove_cover_art_option:
226
- # Re-apply cover art with eyed3
227
- output_file = eyed3.load(output_path)
228
- if output_file.tag is None:
229
- output_file.initTag()
230
 
231
- # Copy images from the source file
232
  if not remove_cover_art_option:
233
- for img in audiofile.tag.images:
234
- output_file.tag.images.set(
235
- img.picture_type,
236
- img.image_data,
237
- img.mime_type,
238
- img.description
239
- )
240
-
241
- output_file.tag.save()
 
 
 
 
 
 
 
 
 
242
 
243
  return output_path, "Changes saved successfully!"
244
  except Exception as e:
@@ -251,17 +344,52 @@ def update_cover_art(cover_art_file):
251
  return None
252
  return cover_art_file
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  # Function to toggle cutting controls visibility
255
  def toggle_cutting_controls(enable):
256
  return gr.update(visible=enable)
257
 
258
- # Create the Gradio interface with waveform visualization
259
  with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
260
  gr.Markdown("# MP3 Tag Editor with Cutting")
261
  gr.Markdown("Upload an MP3 file to edit its metadata, album art, and trim the audio.")
262
 
263
  # Store state variables (hidden from UI)
264
  file_path = gr.State(None)
 
 
265
 
266
  with gr.Row():
267
  with gr.Column(scale=1):
@@ -289,47 +417,39 @@ with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
289
  comments_input = gr.Textbox(label="Comments", lines=3)
290
 
291
  with gr.TabItem("Cut/Crop Audio"):
292
- # Using the built-in Audio component with waveform visualization
293
- audio_component = gr.Audio(
294
- label="Audio Editor",
295
- type="numpy",
296
- format="mp3",
297
- editable=True, # Enable trimming in the UI
298
- waveform_options=gr.WaveformOptions(
299
- waveform_color="#1f77b4",
300
- waveform_progress_color="#2ca02c",
301
- trim_region_color="#ff7f0e",
302
- show_recording_waveform=False,
303
- show_controls=True
304
- )
305
- )
306
 
307
- with gr.Row():
308
- enable_cutting = gr.Checkbox(label="Enable audio trimming", value=False)
309
- save_selection_only = gr.Checkbox(label="Save selection only (crop)", value=False, visible=False)
 
 
 
 
 
 
 
 
 
 
310
 
311
  save_button = gr.Button("Save Changes")
312
  download_btn = gr.File(label="Download Modified MP3")
313
 
314
  # Event handlers
315
- def update_ui_with_loaded_file(file_path, file_name, title, artist, album, year, track_num,
316
- genre, comments, album_art, audio_path, status):
317
- # Make the save_selection_only checkbox visible when a file is loaded
318
- if file_path is not None:
319
- return (
320
- file_path, file_name, title, artist, album, year, track_num,
321
- genre, comments, album_art, audio_path, status,
322
- gr.update(visible=True) # Update the save_selection_only visibility
323
- )
324
- else:
325
- return (
326
- None, "", "", "", "", "", "", "", "", None, None, status,
327
- gr.update(visible=False)
328
- )
329
 
330
- # Load file event
331
- load_result = load_button.click(
332
- load_mp3,
333
  inputs=[file_input],
334
  outputs=[
335
  file_path,
@@ -342,25 +462,42 @@ with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
342
  genre_input,
343
  comments_input,
344
  album_art_display,
345
- audio_component,
346
  status_msg,
347
- save_selection_only # Output to update visibility
 
348
  ]
349
  )
350
 
 
 
 
 
 
 
 
351
  # Toggle cutting controls visibility
352
  enable_cutting.change(
353
- lambda x: gr.update(visible=x),
354
  inputs=[enable_cutting],
355
- outputs=[save_selection_only]
356
  )
357
 
 
358
  cover_art_input.change(
359
  update_cover_art,
360
  inputs=[cover_art_input],
361
  outputs=[cover_art_input]
362
  )
363
 
 
 
 
 
 
 
 
 
364
  save_button.click(
365
  save_changes,
366
  inputs=[
@@ -374,24 +511,31 @@ with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
374
  comments_input,
375
  cover_art_input,
376
  remove_cover_art,
377
- audio_component,
378
  enable_cutting,
 
 
379
  save_selection_only
380
  ],
381
  outputs=[download_btn, status_msg]
382
  )
383
 
 
 
 
 
384
  # Provide instructions
385
  gr.Markdown("""
386
  ## How to Use
387
  1. Upload an MP3 file
388
- 2. Click "Load MP3" to extract current metadata and load the audio
389
  3. Edit the metadata fields in the Metadata tab
390
  4. Optionally upload new album art or check 'Remove cover image completely?'
391
  5. To trim the audio:
392
  - Go to the "Cut/Crop Audio" tab
393
- - Use the built-in audio editor to drag the trim handles to select a region
394
- - Check "Enable audio trimming"
 
395
  - Check "Save selection only" to crop the audio to just that section
396
  6. Click "Save Changes" to apply your edits
397
  7. Download the modified MP3 file
@@ -399,7 +543,7 @@ with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
399
  ## Notes
400
  - All processing happens in your browser
401
  - Your files are not stored permanently on the server
402
- - Original audio quality is preserved when not cropping
403
  """)
404
 
405
  # Launch the app
 
2
  import tempfile
3
  import gradio as gr
4
  import eyed3
5
+ from PIL import Image, ImageDraw
6
  import io
7
  import shutil
8
  from pydub import AudioSegment
9
  import numpy as np
10
+ import matplotlib.pyplot as plt
11
 
12
  # Function to load MP3 file and extract metadata
13
  def load_mp3(file_obj):
14
+ if file_obj is None:
15
+ return None, "No file uploaded", None, None, None, None, None, None, None, None, None, None, 0, None
16
+
17
  # Create a temporary directory
18
  temp_dir = tempfile.mkdtemp()
19
  temp_path = os.path.join(temp_dir, "temp.mp3")
 
32
  if audiofile is None or audiofile.tag is None:
33
  # Create a new tag if one doesn't exist
34
  if audiofile is None:
35
+ return None, "Invalid MP3 file", None, None, None, None, None, None, None, None, None, None, 0, None
36
  audiofile.initTag()
37
 
38
+ # Extract basic metadata with safe handling
39
+ try:
40
+ title = audiofile.tag.title or ""
41
+ except:
42
+ title = ""
43
+
44
+ try:
45
+ artist = audiofile.tag.artist or ""
46
+ except:
47
+ artist = ""
48
+
49
+ try:
50
+ album = audiofile.tag.album or ""
51
+ except:
52
+ album = ""
53
+
54
+ try:
55
+ year = str(audiofile.tag.getBestDate() or "")
56
+ except:
57
+ year = ""
58
+
59
+ try:
60
+ track_num = str(audiofile.tag.track_num[0]) if audiofile.tag.track_num and audiofile.tag.track_num[0] else ""
61
+ except:
62
+ track_num = ""
63
+
64
+ try:
65
+ genre = str(audiofile.tag.genre or "")
66
+ except:
67
+ genre = ""
68
+
69
+ try:
70
+ comments = audiofile.tag.comments[0].text if audiofile.tag.comments and len(audiofile.tag.comments) > 0 else ""
71
+ except:
72
+ comments = ""
73
 
74
  # Extract album art if available
75
  cover_art = None
76
+ try:
77
+ for img in audiofile.tag.images:
78
+ if img.picture_type == 3: # Front cover
79
+ image_data = img.image_data
80
+ cover_art = Image.open(io.BytesIO(image_data))
81
+ break
82
+ except:
83
+ cover_art = None
84
 
85
+ # Load audio for waveform and duration
86
+ try:
87
+ audio = AudioSegment.from_mp3(temp_path)
88
+ duration_seconds = len(audio) / 1000.0
89
+
90
+ # Generate waveform image
91
+ waveform_path = os.path.join(temp_dir, "waveform.png")
92
+ generate_waveform(audio, waveform_path)
93
+
94
+ # Return the file path and metadata
95
+ return (
96
+ temp_path,
97
+ os.path.basename(file_path),
98
+ title,
99
+ artist,
100
+ album,
101
+ year,
102
+ track_num,
103
+ genre,
104
+ comments,
105
+ cover_art,
106
+ waveform_path,
107
+ "File loaded successfully!",
108
+ duration_seconds,
109
+ temp_dir # Keep track of temp directory
110
+ )
111
+ except Exception as e:
112
+ print(f"Error processing audio: {str(e)}")
113
+ return (
114
+ temp_path,
115
+ os.path.basename(file_path),
116
+ title,
117
+ artist,
118
+ album,
119
+ year,
120
+ track_num,
121
+ genre,
122
+ comments,
123
+ cover_art,
124
+ None,
125
+ f"Error processing audio: {str(e)}",
126
+ 0,
127
+ temp_dir
128
+ )
129
 
130
  except Exception as e:
131
  print(f"Error loading MP3: {str(e)}")
132
+ return None, f"Error: {str(e)}", None, None, None, None, None, None, None, None, None, None, 0, None
133
+
134
+ # Function to generate waveform image
135
+ def generate_waveform(audio, output_path):
136
+ # Convert audio to numpy array
137
+ samples = np.array(audio.get_array_of_samples())
138
+
139
+ # If stereo, take the average of both channels
140
+ if audio.channels == 2:
141
+ samples = samples.reshape((-1, 2))
142
+ samples = samples.mean(axis=1)
143
+
144
+ # Reduce the number of points to plot (for efficiency)
145
+ if len(samples) > 10000:
146
+ samples = samples[::len(samples) // 10000]
147
+
148
+ # Plot the waveform
149
+ plt.figure(figsize=(10, 2))
150
+ plt.plot(samples, color='#3498db')
151
+ plt.axis('off')
152
+ plt.tight_layout(pad=0)
153
+ plt.savefig(output_path, bbox_inches='tight', pad_inches=0, dpi=100)
154
+ plt.close()
155
+
156
+ return output_path
157
 
158
  # Function to save changes and provide download
159
  def save_changes(
 
167
  comments,
168
  cover_art,
169
  remove_cover_art_option,
170
+ temp_dir,
171
  enable_cutting,
172
+ start_time,
173
+ end_time,
174
  save_selection_only
175
  ):
176
  if not file_path:
 
178
 
179
  try:
180
  # Create output path
181
+ output_dir = tempfile.mkdtemp() if temp_dir is None else temp_dir
182
  filename = os.path.basename(file_path)
183
  if not filename.endswith('.mp3'):
184
  filename += '.mp3'
 
186
  output_path = os.path.join(output_dir, f"edited_{filename}")
187
 
188
  # Handle audio cutting if enabled
189
+ if enable_cutting and start_time is not None and end_time is not None:
190
  try:
191
+ # Load audio with pydub
192
+ audio = AudioSegment.from_mp3(file_path)
193
 
194
+ # Convert start and end times from seconds to milliseconds
195
+ start_ms = max(0, int(start_time * 1000))
196
+ end_ms = min(int(end_time * 1000), len(audio))
 
197
 
198
+ if start_ms >= end_ms:
199
+ return None, "Invalid time range: start time must be less than end time"
 
 
 
 
200
 
201
+ # Extract the segment
202
+ audio_segment = audio[start_ms:end_ms]
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
  # If saving only the selection, use this as our new audio
205
  if save_selection_only:
206
  # Save to a temporary file
207
  temp_cut_path = os.path.join(output_dir, "temp_cut.mp3")
208
+ audio_segment.export(temp_cut_path, format="mp3")
209
 
210
  # Use this as our source for metadata
211
  file_path = temp_cut_path
 
213
  # Otherwise just copy the original file for metadata editing
214
  shutil.copy2(file_path, output_path)
215
  except Exception as e:
216
+ return None, f"Error cutting audio: {str(e)}"
217
  else:
218
  # Just copy the file if not cutting
219
  shutil.copy2(file_path, output_path)
220
 
221
  # Load the MP3 file for metadata editing
222
+ try:
223
+ audiofile = eyed3.load(file_path)
224
+ if audiofile is None:
225
+ return None, "Failed to load MP3 file"
226
+
227
+ # Ensure there's a tag
228
+ if audiofile.tag is None:
229
+ audiofile.initTag()
230
+
231
+ # Update the metadata
232
+ audiofile.tag.title = title
233
+ audiofile.tag.artist = artist
234
+ audiofile.tag.album = album
235
+
236
+ # Handle year
237
+ if year:
238
+ try:
239
+ audiofile.tag.year = int(year)
240
+ except ValueError:
241
+ pass
242
+
243
+ # Handle track number
244
+ if track_num:
245
+ try:
246
+ audiofile.tag.track_num = int(track_num)
247
+ except ValueError:
248
+ pass
249
+
250
+ # Handle genre
251
+ if genre:
252
+ try:
253
+ audiofile.tag.genre = genre
254
+ except:
255
+ pass
256
+
257
+ # Handle comments
258
  try:
259
+ # First remove any existing comments
260
+ for comment in list(audiofile.tag.comments):
261
+ audiofile.tag.comments.remove(comment.description)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
+ if comments:
264
+ audiofile.tag.comments.set(comments, description="", lang="eng")
265
+ except:
266
+ pass
267
+
268
+ # Remove cover art if requested
269
+ if remove_cover_art_option:
270
+ try:
271
+ for img in list(audiofile.tag.images):
272
+ audiofile.tag.images.remove(img.description)
273
+ except:
274
+ pass
275
+ else:
276
+ # Handle cover art if new art is uploaded
277
+ if cover_art is not None and isinstance(cover_art, dict) and "name" in cover_art:
278
+ try:
279
+ # Remove existing cover art
280
+ for img in list(audiofile.tag.images):
281
+ audiofile.tag.images.remove(img.description)
282
+
283
+ # Add new cover art
284
+ with open(cover_art["name"], "rb") as img_file:
285
+ img_data = img_file.read()
286
+ mime_type = "image/jpeg" if cover_art["name"].lower().endswith((".jpg", ".jpeg")) else "image/png"
287
+ audiofile.tag.images.set(3, img_data, mime_type, "Front cover")
288
+ except Exception as e:
289
+ print(f"Error adding cover art: {str(e)}")
290
+ except Exception as e:
291
+ return None, f"Error updating metadata: {str(e)}"
292
 
293
  # Save the metadata
294
+ try:
295
+ audiofile.tag.save(output_path if save_selection_only else None)
296
+ except Exception as e:
297
+ return None, f"Error saving metadata: {str(e)}"
298
 
299
  # If we're saving a selection, we need to copy the edited metadata to our cut file
300
  if enable_cutting and save_selection_only:
301
+ try:
302
+ # Export the cut audio with metadata
303
+ temp_cut_path = os.path.join(output_dir, "temp_cut.mp3")
304
+ output_audio = AudioSegment.from_mp3(temp_cut_path)
305
+ output_audio.export(output_path, format="mp3", tags={
306
+ 'title': title,
307
+ 'artist': artist,
308
+ 'album': album,
309
+ 'year': year,
310
+ 'track': track_num,
311
+ 'genre': genre,
312
+ 'comments': comments
313
+ })
 
 
 
 
 
 
314
 
315
+ # Handle cover art separately since pydub doesn't support it well
316
  if not remove_cover_art_option:
317
+ # Re-apply cover art with eyed3
318
+ output_file = eyed3.load(output_path)
319
+ if output_file.tag is None:
320
+ output_file.initTag()
321
+
322
+ # Copy images from the source file
323
+ if not remove_cover_art_option:
324
+ for img in audiofile.tag.images:
325
+ output_file.tag.images.set(
326
+ img.picture_type,
327
+ img.image_data,
328
+ img.mime_type,
329
+ img.description
330
+ )
331
+
332
+ output_file.tag.save()
333
+ except Exception as e:
334
+ return None, f"Error finalizing audio cut: {str(e)}"
335
 
336
  return output_path, "Changes saved successfully!"
337
  except Exception as e:
 
344
  return None
345
  return cover_art_file
346
 
347
+ # Function to update the waveform display with time markers
348
+ def update_waveform_display(waveform, start_time, end_time, duration):
349
+ if waveform is None or duration == 0:
350
+ return None
351
+
352
+ try:
353
+ # Load the original waveform
354
+ img = Image.open(waveform)
355
+
356
+ # Create a drawable version
357
+ draw_img = img.copy()
358
+ draw = ImageDraw.Draw(draw_img)
359
+
360
+ # Calculate positions for markers
361
+ width, height = draw_img.size
362
+ start_x = int((start_time / duration) * width)
363
+ end_x = int((end_time / duration) * width)
364
+
365
+ # Draw markers
366
+ # Start marker (green)
367
+ draw.line([(start_x, 0), (start_x, height)], fill=(0, 255, 0), width=2)
368
+ # End marker (red)
369
+ draw.line([(end_x, 0), (end_x, height)], fill=(255, 0, 0), width=2)
370
+
371
+ # Save the modified image
372
+ modified_path = waveform.replace('.png', '_marked.png')
373
+ draw_img.save(modified_path)
374
+
375
+ return modified_path
376
+ except Exception as e:
377
+ print(f"Error updating waveform: {str(e)}")
378
+ return waveform
379
+
380
  # Function to toggle cutting controls visibility
381
  def toggle_cutting_controls(enable):
382
  return gr.update(visible=enable)
383
 
384
+ # Create the Gradio interface
385
  with gr.Blocks(title="MP3 Tag Editor with Cutting") as app:
386
  gr.Markdown("# MP3 Tag Editor with Cutting")
387
  gr.Markdown("Upload an MP3 file to edit its metadata, album art, and trim the audio.")
388
 
389
  # Store state variables (hidden from UI)
390
  file_path = gr.State(None)
391
+ temp_dir = gr.State(None)
392
+ duration = gr.State(0)
393
 
394
  with gr.Row():
395
  with gr.Column(scale=1):
 
417
  comments_input = gr.Textbox(label="Comments", lines=3)
418
 
419
  with gr.TabItem("Cut/Crop Audio"):
420
+ waveform_display = gr.Image(label="Audio Waveform")
 
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
+ enable_cutting = gr.Checkbox(label="Enable audio cutting", value=False)
423
+
424
+ with gr.Column(visible=False) as cutting_controls:
425
+ duration_display = gr.Textbox(label="Duration (seconds)", interactive=False)
426
+
427
+ with gr.Row():
428
+ start_time = gr.Slider(label="Start Time (seconds)", minimum=0, maximum=100, step=0.1, value=0)
429
+ end_time = gr.Slider(label="End Time (seconds)", minimum=0, maximum=100, step=0.1, value=100)
430
+
431
+ save_selection_only = gr.Checkbox(label="Save selection only (crop)", value=False)
432
+
433
+ # Preview button to show waveform with markers
434
+ preview_button = gr.Button("Preview Selection")
435
 
436
  save_button = gr.Button("Save Changes")
437
  download_btn = gr.File(label="Download Modified MP3")
438
 
439
  # Event handlers
440
+ def process_load_result(path, name, title, artist, album, year, track, genre, comments,
441
+ cover, waveform, status, dur, tmp_dir):
442
+ # Update state variables
443
+ file_path.value = path
444
+ temp_dir.value = tmp_dir
445
+ duration.value = dur
446
+
447
+ # Return values to update UI
448
+ return name, title, artist, album, year, track, genre, comments, cover, waveform, status
 
 
 
 
 
449
 
450
+ # Load file event - using a staged approach to avoid "too many arguments" error
451
+ load_button.click(
452
+ fn=load_mp3,
453
  inputs=[file_input],
454
  outputs=[
455
  file_path,
 
462
  genre_input,
463
  comments_input,
464
  album_art_display,
465
+ waveform_display,
466
  status_msg,
467
+ duration,
468
+ temp_dir
469
  ]
470
  )
471
 
472
+ # Update duration sliders when file is loaded
473
+ duration.change(
474
+ update_duration_sliders,
475
+ inputs=[duration],
476
+ outputs=[end_time, start_time, duration_display]
477
+ )
478
+
479
  # Toggle cutting controls visibility
480
  enable_cutting.change(
481
+ toggle_cutting_controls,
482
  inputs=[enable_cutting],
483
+ outputs=[cutting_controls]
484
  )
485
 
486
+ # Update cover art
487
  cover_art_input.change(
488
  update_cover_art,
489
  inputs=[cover_art_input],
490
  outputs=[cover_art_input]
491
  )
492
 
493
+ # Preview selection on waveform
494
+ preview_button.click(
495
+ update_waveform_display,
496
+ inputs=[waveform_display, start_time, end_time, duration],
497
+ outputs=[waveform_display]
498
+ )
499
+
500
+ # Save changes
501
  save_button.click(
502
  save_changes,
503
  inputs=[
 
511
  comments_input,
512
  cover_art_input,
513
  remove_cover_art,
514
+ temp_dir,
515
  enable_cutting,
516
+ start_time,
517
+ end_time,
518
  save_selection_only
519
  ],
520
  outputs=[download_btn, status_msg]
521
  )
522
 
523
+ # Define the update_duration_sliders function
524
+ def update_duration_sliders(duration_seconds):
525
+ return gr.update(maximum=duration_seconds, value=duration_seconds), gr.update(maximum=duration_seconds, value=0), gr.update(value=f"{duration_seconds:.2f}")
526
+
527
  # Provide instructions
528
  gr.Markdown("""
529
  ## How to Use
530
  1. Upload an MP3 file
531
+ 2. Click "Load MP3" to extract current metadata and generate waveform
532
  3. Edit the metadata fields in the Metadata tab
533
  4. Optionally upload new album art or check 'Remove cover image completely?'
534
  5. To trim the audio:
535
  - Go to the "Cut/Crop Audio" tab
536
+ - Check "Enable audio cutting"
537
+ - Use the sliders to select start and end points
538
+ - Click "Preview Selection" to see the selected region on the waveform
539
  - Check "Save selection only" to crop the audio to just that section
540
  6. Click "Save Changes" to apply your edits
541
  7. Download the modified MP3 file
 
543
  ## Notes
544
  - All processing happens in your browser
545
  - Your files are not stored permanently on the server
546
+ - Original audio quality is preserved
547
  """)
548
 
549
  # Launch the app