MySafeCode commited on
Commit
fc1edf2
·
verified ·
1 Parent(s): 15ced6a

Update app2.py

Browse files
Files changed (1) hide show
  1. app2.py +27 -37
app2.py CHANGED
@@ -16,7 +16,7 @@ def download_youtube_audio(url, file_format, duration_sec):
16
  'quiet': False,
17
  'no_warnings': False,
18
  'extract_flat': False,
19
- 'noplaylist': True, # Don't download playlists
20
  }
21
 
22
  with YoutubeDL(ydl_opts) as ydl:
@@ -26,11 +26,12 @@ def download_youtube_audio(url, file_format, duration_sec):
26
 
27
  # Clean filename
28
  safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
29
- safe_title = safe_title[:100] # Limit filename length
30
  original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
31
 
32
- # Rename if necessary
33
  if original_file != original_file_safe:
 
 
34
  os.rename(original_file, original_file_safe)
35
  original_file = original_file_safe
36
 
@@ -42,7 +43,7 @@ def download_youtube_audio(url, file_format, duration_sec):
42
  duration_ms = min(len(audio), int(duration_sec * 1000))
43
  trimmed_audio = audio[:duration_ms]
44
  else:
45
- trimmed_audio = audio # Full track
46
 
47
  # Determine output file
48
  base_name = os.path.splitext(original_file)[0]
@@ -63,7 +64,7 @@ def download_youtube_audio(url, file_format, duration_sec):
63
  output_file = base_name + ".m4a"
64
  trimmed_audio.export(output_file, format="ipod", codec="aac")
65
 
66
- else: # keep original
67
  output_file = original_file
68
 
69
  # Clean up original if converted
@@ -73,12 +74,11 @@ def download_youtube_audio(url, file_format, duration_sec):
73
  return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
74
 
75
  except Exception as e:
76
- raise gr.Error(f"Error downloading from YouTube: {str(e)}")
77
 
78
  def download_soundcloud_audio(url, file_format, duration_sec):
79
  """Download and process audio from SoundCloud"""
80
  try:
81
- # SoundCloud specific options
82
  ydl_opts = {
83
  'format': 'bestaudio/best',
84
  'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
@@ -98,6 +98,8 @@ def download_soundcloud_audio(url, file_format, duration_sec):
98
  original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
99
 
100
  if original_file != original_file_safe:
 
 
101
  os.rename(original_file, original_file_safe)
102
  original_file = original_file_safe
103
 
@@ -139,22 +141,17 @@ def download_soundcloud_audio(url, file_format, duration_sec):
139
  return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
140
 
141
  except Exception as e:
142
- raise gr.Error(f"Error downloading from SoundCloud: {str(e)}")
143
 
144
  # Create Gradio interface
145
- with gr.Blocks(title="Audio Downloader", css="""
146
- .tab-nav { background-color: #f0f0f0; }
147
- .download-btn { margin-top: 20px; }
148
- .status-box { margin-top: 10px; }
149
- """) as iface:
150
 
151
  gr.Markdown("# 🎵 Audio Downloader")
152
  gr.Markdown("Download audio from YouTube or SoundCloud")
153
 
154
- # Create tabs
155
  with gr.Tabs():
156
  # YouTube Tab
157
- with gr.TabItem("YouTube", id="youtube"):
158
  with gr.Row():
159
  with gr.Column():
160
  youtube_url = gr.Textbox(
@@ -172,7 +169,7 @@ with gr.Blocks(title="Audio Downloader", css="""
172
 
173
  youtube_duration = gr.Slider(
174
  minimum=0,
175
- maximum=1800, # 30 minutes max for YouTube
176
  value=60,
177
  step=5,
178
  label="Duration (seconds)",
@@ -182,14 +179,12 @@ with gr.Blocks(title="Audio Downloader", css="""
182
  youtube_btn = gr.Button(
183
  "Download from YouTube",
184
  variant="primary",
185
- size="lg",
186
- elem_classes="download-btn"
187
  )
188
 
189
  youtube_status = gr.Textbox(
190
  label="Status",
191
- interactive=False,
192
- elem_classes="status-box"
193
  )
194
 
195
  youtube_output = gr.File(
@@ -204,14 +199,14 @@ with gr.Blocks(title="Audio Downloader", css="""
204
  ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
205
  ["https://www.youtube.com/watch?v=JGwWNGJdvx8"],
206
  ["https://www.youtube.com/watch?v=9bZkp7q19f0"],
207
- ["https://www.youtube.com/watch?v=kJQP7kiw5Fk"]
208
  ],
209
  inputs=youtube_url,
210
  label="Try these URLs:"
211
  )
212
 
213
  # SoundCloud Tab
214
- with gr.TabItem("SoundCloud", id="soundcloud"):
215
  with gr.Row():
216
  with gr.Column():
217
  soundcloud_url = gr.Textbox(
@@ -229,7 +224,7 @@ with gr.Blocks(title="Audio Downloader", css="""
229
 
230
  soundcloud_duration = gr.Slider(
231
  minimum=0,
232
- maximum=600, # 10 minutes max for SoundCloud
233
  value=60,
234
  step=5,
235
  label="Duration (seconds)",
@@ -239,14 +234,12 @@ with gr.Blocks(title="Audio Downloader", css="""
239
  soundcloud_btn = gr.Button(
240
  "Download from SoundCloud",
241
  variant="primary",
242
- size="lg",
243
- elem_classes="download-btn"
244
  )
245
 
246
  soundcloud_status = gr.Textbox(
247
  label="Status",
248
- interactive=False,
249
- elem_classes="status-box"
250
  )
251
 
252
  soundcloud_output = gr.File(
@@ -261,7 +254,7 @@ with gr.Blocks(title="Audio Downloader", css="""
261
  ["https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover"],
262
  ["https://soundcloud.com/officialnikkig/kill-bill-sza-kill-bill-remix"],
263
  ["https://soundcloud.com/lofi-girl"],
264
- ["https://soundcloud.com/user-123456789/sample-track"]
265
  ],
266
  inputs=soundcloud_url,
267
  label="Try these URLs:"
@@ -277,18 +270,16 @@ with gr.Blocks(title="Audio Downloader", css="""
277
  4. **Set duration** (0 for full track, or specify seconds)
278
  5. **Click Download** button
279
 
280
- ### Features:
281
- - **YouTube**: Download audio from any YouTube video
282
- - **SoundCloud**: Download tracks from SoundCloud
283
- - **Format Conversion**: Convert to MP3, M4A, Opus, or WAV
284
- - **Duration Control**: Extract specific segments or full tracks
285
- - **Clean Interface**: Separate tabs for each platform
286
 
287
  ### Notes:
288
  - Files are saved in the 'downloads' folder
289
  - Some content may have download restrictions
290
  - Long videos may take time to process
291
- - Original files are deleted after conversion
292
  """)
293
 
294
  # Connect button events
@@ -310,6 +301,5 @@ if __name__ == "__main__":
310
  server_name="127.0.0.1",
311
  server_port=7860,
312
  show_error=True,
313
- share=False,
314
- theme=gr.themes.Soft()
315
  )
 
16
  'quiet': False,
17
  'no_warnings': False,
18
  'extract_flat': False,
19
+ 'noplaylist': True,
20
  }
21
 
22
  with YoutubeDL(ydl_opts) as ydl:
 
26
 
27
  # Clean filename
28
  safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
29
+ safe_title = safe_title[:100]
30
  original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
31
 
 
32
  if original_file != original_file_safe:
33
+ if os.path.exists(original_file_safe):
34
+ os.remove(original_file_safe)
35
  os.rename(original_file, original_file_safe)
36
  original_file = original_file_safe
37
 
 
43
  duration_ms = min(len(audio), int(duration_sec * 1000))
44
  trimmed_audio = audio[:duration_ms]
45
  else:
46
+ trimmed_audio = audio
47
 
48
  # Determine output file
49
  base_name = os.path.splitext(original_file)[0]
 
64
  output_file = base_name + ".m4a"
65
  trimmed_audio.export(output_file, format="ipod", codec="aac")
66
 
67
+ else:
68
  output_file = original_file
69
 
70
  # Clean up original if converted
 
74
  return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
75
 
76
  except Exception as e:
77
+ return None, f"Error: {str(e)}"
78
 
79
  def download_soundcloud_audio(url, file_format, duration_sec):
80
  """Download and process audio from SoundCloud"""
81
  try:
 
82
  ydl_opts = {
83
  'format': 'bestaudio/best',
84
  'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
 
98
  original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
99
 
100
  if original_file != original_file_safe:
101
+ if os.path.exists(original_file_safe):
102
+ os.remove(original_file_safe)
103
  os.rename(original_file, original_file_safe)
104
  original_file = original_file_safe
105
 
 
141
  return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
142
 
143
  except Exception as e:
144
+ return None, f"Error: {str(e)}"
145
 
146
  # Create Gradio interface
147
+ with gr.Blocks(title="Audio Downloader", theme=gr.themes.Soft()) as iface:
 
 
 
 
148
 
149
  gr.Markdown("# 🎵 Audio Downloader")
150
  gr.Markdown("Download audio from YouTube or SoundCloud")
151
 
 
152
  with gr.Tabs():
153
  # YouTube Tab
154
+ with gr.Tab("YouTube"):
155
  with gr.Row():
156
  with gr.Column():
157
  youtube_url = gr.Textbox(
 
169
 
170
  youtube_duration = gr.Slider(
171
  minimum=0,
172
+ maximum=1800,
173
  value=60,
174
  step=5,
175
  label="Duration (seconds)",
 
179
  youtube_btn = gr.Button(
180
  "Download from YouTube",
181
  variant="primary",
182
+ size="lg"
 
183
  )
184
 
185
  youtube_status = gr.Textbox(
186
  label="Status",
187
+ interactive=False
 
188
  )
189
 
190
  youtube_output = gr.File(
 
199
  ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
200
  ["https://www.youtube.com/watch?v=JGwWNGJdvx8"],
201
  ["https://www.youtube.com/watch?v=9bZkp7q19f0"],
202
+ ["https://youtu.be/kJQP7kiw5Fk"]
203
  ],
204
  inputs=youtube_url,
205
  label="Try these URLs:"
206
  )
207
 
208
  # SoundCloud Tab
209
+ with gr.Tab("SoundCloud"):
210
  with gr.Row():
211
  with gr.Column():
212
  soundcloud_url = gr.Textbox(
 
224
 
225
  soundcloud_duration = gr.Slider(
226
  minimum=0,
227
+ maximum=600,
228
  value=60,
229
  step=5,
230
  label="Duration (seconds)",
 
234
  soundcloud_btn = gr.Button(
235
  "Download from SoundCloud",
236
  variant="primary",
237
+ size="lg"
 
238
  )
239
 
240
  soundcloud_status = gr.Textbox(
241
  label="Status",
242
+ interactive=False
 
243
  )
244
 
245
  soundcloud_output = gr.File(
 
254
  ["https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover"],
255
  ["https://soundcloud.com/officialnikkig/kill-bill-sza-kill-bill-remix"],
256
  ["https://soundcloud.com/lofi-girl"],
257
+ ["https://soundcloud.com/monstercat/pegboard-nerds-disconnected"]
258
  ],
259
  inputs=soundcloud_url,
260
  label="Try these URLs:"
 
270
  4. **Set duration** (0 for full track, or specify seconds)
271
  5. **Click Download** button
272
 
273
+ ### Supported Formats:
274
+ - **MP3**: Most compatible, good quality
275
+ - **M4A**: Apple format, smaller file size
276
+ - **Opus**: Best quality at low bitrates
277
+ - **WAV**: Lossless, large file size
 
278
 
279
  ### Notes:
280
  - Files are saved in the 'downloads' folder
281
  - Some content may have download restrictions
282
  - Long videos may take time to process
 
283
  """)
284
 
285
  # Connect button events
 
301
  server_name="127.0.0.1",
302
  server_port=7860,
303
  show_error=True,
304
+ share=False
 
305
  )