MySafeCode commited on
Commit
8c27928
·
verified ·
1 Parent(s): fcebe5c

Delete app2.py

Browse files
Files changed (1) hide show
  1. app2.py +0 -307
app2.py DELETED
@@ -1,307 +0,0 @@
1
- import gradio as gr
2
- from yt_dlp import YoutubeDL
3
- import os
4
- from pydub import AudioSegment
5
-
6
- DOWNLOADS_FOLDER = "downloads"
7
- os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
8
-
9
- def download_youtube_audio(url, file_format, duration_sec):
10
- """Download and process audio from YouTube"""
11
- try:
12
- # Download best audio available
13
- ydl_opts = {
14
- 'format': 'bestaudio/best',
15
- 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
16
- 'quiet': False,
17
- 'no_warnings': False,
18
- 'extract_flat': False,
19
- 'noplaylist': True,
20
- }
21
-
22
- with YoutubeDL(ydl_opts) as ydl:
23
- info = ydl.extract_info(url, download=True)
24
-
25
- original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
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
-
38
- # Load audio
39
- audio = AudioSegment.from_file(original_file)
40
-
41
- # Handle duration
42
- if duration_sec > 0:
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]
50
-
51
- if file_format.lower() == "mp3":
52
- output_file = base_name + ".mp3"
53
- trimmed_audio.export(output_file, format="mp3", bitrate="192k")
54
-
55
- elif file_format.lower() == "opus":
56
- output_file = base_name + ".opus"
57
- trimmed_audio.export(output_file, format="opus", bitrate="128k")
58
-
59
- elif file_format.lower() == "wav":
60
- output_file = base_name + ".wav"
61
- trimmed_audio.export(output_file, format="wav")
62
-
63
- elif file_format.lower() == "m4a":
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
71
- if output_file != original_file and os.path.exists(original_file):
72
- os.remove(original_file)
73
-
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'),
85
- 'quiet': False,
86
- 'no_warnings': False,
87
- 'extract_flat': False,
88
- }
89
-
90
- with YoutubeDL(ydl_opts) as ydl:
91
- info = ydl.extract_info(url, download=True)
92
-
93
- original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
94
-
95
- # Clean filename
96
- safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
97
- safe_title = safe_title[:100]
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
-
106
- # Load and process audio
107
- audio = AudioSegment.from_file(original_file)
108
-
109
- if duration_sec > 0:
110
- duration_ms = min(len(audio), int(duration_sec * 1000))
111
- trimmed_audio = audio[:duration_ms]
112
- else:
113
- trimmed_audio = audio
114
-
115
- # Convert to desired format
116
- base_name = os.path.splitext(original_file)[0]
117
-
118
- if file_format.lower() == "mp3":
119
- output_file = base_name + ".mp3"
120
- trimmed_audio.export(output_file, format="mp3", bitrate="192k")
121
-
122
- elif file_format.lower() == "opus":
123
- output_file = base_name + ".opus"
124
- trimmed_audio.export(output_file, format="opus", bitrate="128k")
125
-
126
- elif file_format.lower() == "wav":
127
- output_file = base_name + ".wav"
128
- trimmed_audio.export(output_file, format="wav")
129
-
130
- elif file_format.lower() == "m4a":
131
- output_file = base_name + ".m4a"
132
- trimmed_audio.export(output_file, format="ipod", codec="aac")
133
-
134
- else:
135
- output_file = original_file
136
-
137
- # Clean up
138
- if output_file != original_file and os.path.exists(original_file):
139
- os.remove(original_file)
140
-
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 - REMOVE theme parameter from here
147
- with gr.Blocks(title="Audio Downloader") 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(
158
- label="YouTube URL",
159
- placeholder="https://www.youtube.com/watch?v=...",
160
- lines=1
161
- )
162
-
163
- with gr.Row():
164
- youtube_format = gr.Dropdown(
165
- choices=["mp3", "m4a", "opus", "wav"],
166
- value="mp3",
167
- label="Output Format"
168
- )
169
-
170
- youtube_duration = gr.Slider(
171
- minimum=0,
172
- maximum=1800,
173
- value=60,
174
- step=5,
175
- label="Duration (seconds)",
176
- info="0 = full video"
177
- )
178
-
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(
191
- label="Downloaded File",
192
- interactive=False
193
- )
194
-
195
- # YouTube examples
196
- with gr.Accordion("YouTube Examples", open=False):
197
- gr.Examples(
198
- examples=[
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(
213
- label="SoundCloud URL",
214
- placeholder="https://soundcloud.com/...",
215
- lines=1
216
- )
217
-
218
- with gr.Row():
219
- soundcloud_format = gr.Dropdown(
220
- choices=["mp3", "m4a", "opus", "wav"],
221
- value="mp3",
222
- label="Output Format"
223
- )
224
-
225
- soundcloud_duration = gr.Slider(
226
- minimum=0,
227
- maximum=600,
228
- value=60,
229
- step=5,
230
- label="Duration (seconds)",
231
- info="0 = full track"
232
- )
233
-
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(
246
- label="Downloaded File",
247
- interactive=False
248
- )
249
-
250
- # SoundCloud examples
251
- with gr.Accordion("SoundCloud Examples", open=False):
252
- gr.Examples(
253
- examples=[
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:"
261
- )
262
-
263
- # Instructions
264
- with gr.Accordion("📖 Instructions & Info", open=False):
265
- gr.Markdown("""
266
- ### How to Use:
267
- 1. **Select the platform tab** (YouTube or SoundCloud)
268
- 2. **Paste a URL** from the selected platform
269
- 3. **Choose output format** (MP3, M4A, Opus, or WAV)
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
286
- youtube_btn.click(
287
- fn=download_youtube_audio,
288
- inputs=[youtube_url, youtube_format, youtube_duration],
289
- outputs=[youtube_output, youtube_status]
290
- )
291
-
292
- soundcloud_btn.click(
293
- fn=download_soundcloud_audio,
294
- inputs=[soundcloud_url, soundcloud_format, soundcloud_duration],
295
- outputs=[soundcloud_output, soundcloud_status]
296
- )
297
-
298
- # Launch the app - MOVE theme parameter to here
299
- if __name__ == "__main__":
300
- iface.launch(
301
- server_name="127.0.0.1",
302
- server_port=7860,
303
- show_error=True,
304
- share=False,
305
- theme=gr.themes.Soft(),
306
- ssr_mode=False # Disable SSR to avoid warning
307
- )