MySafeCode commited on
Commit
26b7f05
·
verified ·
1 Parent(s): 67ae8ed

Create appold.py

Browse files
Files changed (1) hide show
  1. appold.py +136 -0
appold.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from yt_dlp import YoutubeDL
3
+ import tempfile
4
+ import os
5
+ import subprocess
6
+
7
+ def download_snippet(url, duration_sec):
8
+ """Download and trim audio snippet"""
9
+ # Create temp directory
10
+ temp_dir = tempfile.mkdtemp()
11
+
12
+ try:
13
+ # First, download the full track (or best we can get)
14
+ ydl_opts = {
15
+ 'format': 'bestaudio/best',
16
+ 'outtmpl': os.path.join(temp_dir, 'full_audio.%(ext)s'),
17
+ 'quiet': True,
18
+ 'no_warnings': True,
19
+ 'noplaylist': True,
20
+ }
21
+
22
+ with YoutubeDL(ydl_opts) as ydl:
23
+ # Get info for filename
24
+ info = ydl.extract_info(url, download=False)
25
+ title = info.get('title', 'soundcloud_track')
26
+ safe_title = "".join(c for c in title if c.isalnum() or c in (' ', '-', '_')).rstrip()
27
+
28
+ # Download
29
+ ydl.download([url])
30
+
31
+ # Find the downloaded file
32
+ downloaded_files = [f for f in os.listdir(temp_dir) if f.startswith('full_audio')]
33
+ if not downloaded_files:
34
+ raise Exception("No file was downloaded")
35
+
36
+ input_file = os.path.join(temp_dir, downloaded_files[0])
37
+
38
+ # Check if file exists and has content
39
+ if not os.path.exists(input_file) or os.path.getsize(input_file) == 0:
40
+ raise Exception("Downloaded file is empty")
41
+
42
+ # Create output filename
43
+ output_file = os.path.join(temp_dir, f"{safe_title}_{duration_sec}s.mp3")
44
+
45
+ # Use ffmpeg to trim (this is the key fix!)
46
+ cmd = [
47
+ 'ffmpeg',
48
+ '-i', input_file, # Input file
49
+ '-t', str(duration_sec), # Duration to keep
50
+ '-acodec', 'libmp3lame', # MP3 codec
51
+ '-q:a', '2', # Good quality
52
+ '-y', # Overwrite output
53
+ output_file
54
+ ]
55
+
56
+ # Run ffmpeg
57
+ result = subprocess.run(cmd, capture_output=True, text=True)
58
+
59
+ if result.returncode != 0:
60
+ raise Exception(f"FFmpeg error: {result.stderr}")
61
+
62
+ # Check if output was created
63
+ if not os.path.exists(output_file) or os.path.getsize(output_file) == 0:
64
+ raise Exception("Trimmed file is empty")
65
+
66
+ return output_file, f"{safe_title}_{duration_sec}s.mp3"
67
+
68
+ except Exception as e:
69
+ # Clean up on error
70
+ if os.path.exists(temp_dir):
71
+ import shutil
72
+ shutil.rmtree(temp_dir, ignore_errors=True)
73
+ raise e
74
+
75
+ # Simple Gradio interface
76
+ with gr.Blocks(title="SoundCloud Snippet", theme=gr.themes.Soft()) as demo:
77
+ gr.Markdown("""
78
+ # 🎵 SoundCloud Snippet Downloader
79
+ Download the first N seconds of any public SoundCloud track
80
+ """)
81
+
82
+ with gr.Row():
83
+ url = gr.Textbox(
84
+ label="SoundCloud URL",
85
+ placeholder="https://soundcloud.com/artist/track-name",
86
+ value="https://soundcloud.com/emma-eline-pihlstr-m/have-yourself-a-merry-little-christmas",
87
+ lines=2
88
+ )
89
+
90
+ with gr.Row():
91
+ duration = gr.Slider(
92
+ minimum=5,
93
+ maximum=400,
94
+ value=30,
95
+ step=5,
96
+ label="Duration (seconds)"
97
+ )
98
+
99
+ with gr.Row():
100
+ download_btn = gr.Button("Download Snippet", variant="primary")
101
+
102
+ with gr.Row():
103
+ audio_player = gr.Audio(label="Preview", type="filepath")
104
+ download_file = gr.DownloadButton("Save MP3", visible=False)
105
+
106
+ # Store file path
107
+ file_path = gr.State()
108
+
109
+ def process_download(url, duration):
110
+ if not url or 'soundcloud.com' not in url.lower():
111
+ raise gr.Error("Please enter a valid SoundCloud URL")
112
+
113
+ try:
114
+ filepath, filename = download_snippet(url, duration)
115
+ return {
116
+ audio_player: filepath,
117
+ download_file: gr.DownloadButton(visible=True),
118
+ file_path: filepath
119
+ }
120
+ except Exception as e:
121
+ raise gr.Error(f"Download failed: {str(e)}")
122
+
123
+ download_btn.click(
124
+ process_download,
125
+ inputs=[url, duration],
126
+ outputs=[audio_player, download_file, file_path]
127
+ )
128
+
129
+ download_file.click(
130
+ lambda x: x if x and os.path.exists(x) else None,
131
+ inputs=[file_path],
132
+ outputs=None
133
+ )
134
+
135
+ if __name__ == "__main__":
136
+ demo.launch()