MySafeCode commited on
Commit
ffd04f3
·
verified ·
1 Parent(s): 4f02f65

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -71
app.py CHANGED
@@ -9,11 +9,13 @@ os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
9
 
10
  def sanitize_filename(filename):
11
  """Remove invalid characters from filename"""
12
- # Remove characters that are invalid in filenames
13
  return re.sub(r'[<>:"/\\|?*]', '', filename)
14
 
15
- def download_audio(url, file_format, platform):
16
  try:
 
 
 
17
  # Set download options
18
  ydl_opts = {
19
  'format': 'bestaudio/best',
@@ -22,14 +24,6 @@ def download_audio(url, file_format, platform):
22
  'no_warnings': True
23
  }
24
 
25
- # Platform-specific handling if needed
26
- if platform == "youtube":
27
- # You could add YouTube-specific options here
28
- pass
29
- elif platform == "soundcloud":
30
- # You could add SoundCloud-specific options here
31
- pass
32
-
33
  with YoutubeDL(ydl_opts) as ydl:
34
  info = ydl.extract_info(url, download=True)
35
  original_filename = ydl.prepare_filename(info)
@@ -40,7 +34,7 @@ def download_audio(url, file_format, platform):
40
  else:
41
  # Sometimes the extension might be different
42
  base_name = os.path.splitext(original_filename)[0]
43
- for ext in ['.m4a', '.webm', '.mp3', '.opus']:
44
  possible_file = base_name + ext
45
  if os.path.exists(possible_file):
46
  downloaded_file = possible_file
@@ -63,73 +57,38 @@ def download_audio(url, file_format, platform):
63
  # Convert audio format
64
  audio = AudioSegment.from_file(downloaded_file)
65
  audio.export(output_file, format=file_format.lower())
 
 
66
  downloaded_file = output_file
67
  except Exception as e:
68
  print(f"Conversion failed: {e}")
69
  # Return original file if conversion fails
70
  pass
71
 
72
- return downloaded_file
73
 
74
  except Exception as e:
75
- return f"Error: {str(e)}"
76
 
77
- # Gradio interface
78
- with gr.Blocks(title="Audio Downloader", theme=gr.themes.Soft()) as iface:
79
- gr.Markdown("# 🎵 Audio Downloader")
80
- gr.Markdown("Download audio from YouTube or SoundCloud")
81
-
82
- with gr.Row():
83
- platform_choice = gr.Dropdown(
84
- choices=["youtube", "soundcloud"],
85
- value="youtube",
86
- label="Select Platform"
87
- )
88
-
89
- with gr.Row():
90
- url_input = gr.Textbox(
91
- label="URL",
92
- placeholder="Enter YouTube or SoundCloud URL here...",
93
- scale=4
94
- )
95
-
96
- with gr.Row():
97
- format_choice = gr.Dropdown(
98
- choices=["original", "mp3", "m4a", "wav", "opus"],
99
- value="mp3",
100
- label="Select Output Format"
101
- )
102
-
103
- with gr.Row():
104
- download_button = gr.Button("Download Audio", variant="primary", size="lg")
105
-
106
- with gr.Row():
107
- download_file = gr.File(label="Download Your Audio")
108
-
109
- with gr.Row():
110
- status_output = gr.Textbox(label="Status", visible=False)
111
-
112
- def download_wrapper(url, file_format, platform):
113
- result = download_audio(url, file_format, platform)
114
- if isinstance(result, str) and result.startswith("Error:"):
115
- return gr.update(value=None, visible=True), gr.update(value=result, visible=True)
116
- else:
117
- return gr.update(value=result, visible=True), gr.update(value="Download complete!", visible=True)
118
-
119
- download_button.click(
120
- fn=download_wrapper,
121
- inputs=[url_input, format_choice, platform_choice],
122
- outputs=[download_file, status_output]
123
- )
124
-
125
- # Examples
126
- gr.Examples(
127
- examples=[
128
- ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", "mp3", "youtube"],
129
- ["https://soundcloud.com/artist/track", "mp3", "soundcloud"],
130
- ],
131
- inputs=[url_input, format_choice, platform_choice],
132
- label="Try these examples:"
133
- )
134
 
135
- iface.launch(share=False, show_error=True)
 
 
 
9
 
10
  def sanitize_filename(filename):
11
  """Remove invalid characters from filename"""
 
12
  return re.sub(r'[<>:"/\\|?*]', '', filename)
13
 
14
+ def download_audio(url, file_format):
15
  try:
16
+ if not url or not url.strip():
17
+ return None, "Error: Please enter a URL"
18
+
19
  # Set download options
20
  ydl_opts = {
21
  'format': 'bestaudio/best',
 
24
  'no_warnings': True
25
  }
26
 
 
 
 
 
 
 
 
 
27
  with YoutubeDL(ydl_opts) as ydl:
28
  info = ydl.extract_info(url, download=True)
29
  original_filename = ydl.prepare_filename(info)
 
34
  else:
35
  # Sometimes the extension might be different
36
  base_name = os.path.splitext(original_filename)[0]
37
+ for ext in ['.m4a', '.webm', '.mp3', '.opus', '.flac', '.wav']:
38
  possible_file = base_name + ext
39
  if os.path.exists(possible_file):
40
  downloaded_file = possible_file
 
57
  # Convert audio format
58
  audio = AudioSegment.from_file(downloaded_file)
59
  audio.export(output_file, format=file_format.lower())
60
+ # Optionally remove original file after conversion
61
+ # os.remove(downloaded_file)
62
  downloaded_file = output_file
63
  except Exception as e:
64
  print(f"Conversion failed: {e}")
65
  # Return original file if conversion fails
66
  pass
67
 
68
+ return downloaded_file, "Download completed successfully!"
69
 
70
  except Exception as e:
71
+ return None, f"Error: {str(e)}"
72
 
73
+ # Create Gradio interface
74
+ iface = gr.Interface(
75
+ fn=download_audio,
76
+ inputs=[
77
+ gr.Textbox(label="YouTube or SoundCloud URL", placeholder="Enter URL here..."),
78
+ gr.Dropdown(["original", "mp3", "m4a", "wav"], value="mp3", label="Output Format")
79
+ ],
80
+ outputs=[
81
+ gr.File(label="Download Audio"),
82
+ gr.Textbox(label="Status")
83
+ ],
84
+ title="🎵 Audio Downloader",
85
+ description="Download audio from YouTube or SoundCloud. Supports MP3, M4A, WAV formats.",
86
+ examples=[
87
+ ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", "mp3"],
88
+ ["https://soundcloud.com/aviciiofficial/levels", "mp3"],
89
+ ]
90
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ # Launch the interface
93
+ if __name__ == "__main__":
94
+ iface.launch(share=False, show_error=True)