rm-dev-null commited on
Commit
bad268f
·
verified ·
1 Parent(s): 1c9e038

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -103
app.py CHANGED
@@ -4,47 +4,31 @@ from pydub import AudioSegment
4
  import shazamio
5
  import os
6
  import time
7
- import tempfile
8
- from pathlib import Path
9
- import sys
10
 
11
- # Replace with your actual client ID and client secret
 
12
  client_id = os.environ.get('SOUNDCLOUD_CLIENT_ID')
13
  client_secret = os.environ.get('SOUNDCLOUD_CLIENT_SECRET')
14
- token = os.environ.get('TOKEN')
15
-
16
- def get_soundcloud_access_token(client_id, client_secret):
17
- try:
18
- auth_string = f'{client_id}:{client_secret}'
19
- auth_headers = {
20
- 'Authorization': 'Basic ' + base64.b64encode(auth_string.encode()).decode()
21
- }
22
- data = {
23
- 'grant_type': 'client_credentials'
24
- }
25
- response = requests.post('https://api.soundcloud.com/oauth2/token', headers=auth_headers, data=data)
26
- if response.status_code == 200:
27
- token_data = response.json()
28
- return token_data['access_token']
29
- else:
30
- raise Exception(f"Failed to obtain access token: {response.text}")
31
- except Exception as e:
32
- return f"Error obtaining access token: {str(e)}"
33
 
 
34
  def download_audio(streaming_url, output_path, headers):
35
  try:
36
  response = requests.get(streaming_url, headers=headers, stream=True)
 
37
  with open(output_path, 'wb') as f:
38
  for chunk in response.iter_content(chunk_size=8192):
39
  f.write(chunk)
 
40
  except Exception as e:
41
- raise Exception(f"Error downloading audio: {str(e)}")
42
 
43
- async def identify_track(shazam, audio_chunk, temp_dir):
 
44
  try:
45
- temp_file = os.path.join(temp_dir, 'temp_chunk.wav')
46
  audio_chunk.export(temp_file, format='wav')
47
  result = await shazam.recognize_file(temp_file)
 
48
  if result and 'track' in result:
49
  track_data = result['track']
50
  return {
@@ -54,84 +38,65 @@ async def identify_track(shazam, audio_chunk, temp_dir):
54
  else:
55
  return None
56
  except Exception as e:
57
- return f"Error identifying track: {str(e)}"
58
 
 
59
  async def process_dj_set(track_url, progress=gr.Progress()):
60
- temp_dir = tempfile.mkdtemp()
61
- output_path = os.path.join(temp_dir, 'track.wav')
62
- tracklist_path = os.path.join(temp_dir, 'tracklist.txt')
63
- status_messages = []
64
-
65
- # Get access token
66
- access_token = get_soundcloud_access_token(client_id, client_secret)
67
- if isinstance(access_token, str) and access_token.startswith("Error"):
68
- return "", "", access_token
69
-
70
- headers = {
71
- 'Authorization': f'Bearer {access_token}'
72
- }
73
-
74
- # Resolve track URL
75
  try:
 
 
76
  resolve_response = requests.get(f'https://api.soundcloud.com/resolve.json?url={track_url}', headers=headers)
 
77
  if resolve_response.status_code != 200:
78
- return "", "", f"Failed to resolve track URL: {resolve_response.text}"
 
79
  track_data = resolve_response.json()
80
- streaming_url = track_data['stream_url']
81
- status_messages.append("Track URL resolved successfully.")
82
- except Exception as e:
83
- return "", "", f"Error resolving track URL: {str(e)}"
84
-
85
- # Download audio
86
- try:
87
- download_audio(streaming_url, output_path, headers)
88
- status_messages.append("Audio downloaded successfully.")
89
- except Exception as e:
90
- return "", "", f"Error downloading audio: {str(e)}"
91
-
92
- # Load audio
93
- try:
94
- audio = AudioSegment.from_wav(output_path)
95
- status_messages.append("Audio loaded successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  except Exception as e:
97
- return "", "", f"Error loading audio: {str(e)}"
98
-
99
- # Split audio into chunks
100
- chunk_duration = 30000 # 30 seconds
101
- overlap = 10000 # 10 seconds
102
- chunks = []
103
- start = 0
104
- while start + chunk_duration < len(audio):
105
- end = start + chunk_duration
106
- chunk = audio[start:end]
107
- chunks.append((start, chunk))
108
- start += chunk_duration - overlap
109
-
110
- # Initialize Shazam
111
- shazam = shazamio.Shazam()
112
-
113
- # Identify tracks
114
- tracklist = []
115
- for start_time, chunk in chunks:
116
- progress(0.1)
117
- track_info = await identify_track(shazam, chunk, temp_dir)
118
- if isinstance(track_info, dict):
119
- timestamp = time.strftime("%M:%S", time.gmtime(start_time / 1000))
120
- tracklist.append(f"{timestamp} - {track_info['title']} by {track_info['subtitle']}")
121
- elif isinstance(track_info, str):
122
- status_messages.append(track_info)
123
-
124
- # Prepare tracklist output
125
- tracklist_output = "\n".join(tracklist)
126
- with open(tracklist_path, 'w') as f:
127
- f.write(tracklist_output)
128
-
129
- # Prepare status message
130
- status_message = "\n".join(status_messages)
131
- if not tracklist:
132
- status_message += "\nNo tracks identified."
133
-
134
- return tracklist_output, tracklist_path, status_message
135
 
136
  css = """
137
  #col-container {
@@ -143,22 +108,26 @@ css = """
143
  with gr.Blocks(css=css) as demo:
144
  with gr.Column(elem_id="col-container"):
145
  gr.Markdown("# SoundCloud DJ Set Track Identifier")
146
- status_text = gr.Markdown(elem_id="status_text")
147
  with gr.Row():
148
- track_url = gr.Text(
149
  label="SoundCloud DJ Set URL",
150
  show_label=False,
151
  max_lines=1,
152
  placeholder="Enter SoundCloud DJ set URL",
153
  container=False,
154
  )
 
155
  run_button = gr.Button("Process", scale=0, variant="primary")
156
- result = gr.Textbox(label="Tracklist", show_label=False)
 
 
157
  with gr.Accordion("Download Tracklist", open=False):
158
  download_button = gr.File(label="Download")
159
- gr.Examples(examples=["https://soundcloud.com/your-track-url"], inputs=[track_url])
160
 
161
- run_button.click(process_dj_set, inputs=track_url, outputs=[result, download_button, status_text])
 
 
162
 
163
  if __name__ == "__main__":
164
- demo.launch()
 
4
  import shazamio
5
  import os
6
  import time
 
 
 
7
 
8
+ # Environment variables
9
+ token = os.environ.get('TOKEN')
10
  client_id = os.environ.get('SOUNDCLOUD_CLIENT_ID')
11
  client_secret = os.environ.get('SOUNDCLOUD_CLIENT_SECRET')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Function to download audio
14
  def download_audio(streaming_url, output_path, headers):
15
  try:
16
  response = requests.get(streaming_url, headers=headers, stream=True)
17
+ response.raise_for_status()
18
  with open(output_path, 'wb') as f:
19
  for chunk in response.iter_content(chunk_size=8192):
20
  f.write(chunk)
21
+ return "Audio downloaded successfully."
22
  except Exception as e:
23
+ return f"Error downloading audio: {e}"
24
 
25
+ # Function to identify track using Shazam
26
+ async def identify_track(shazam, audio_chunk):
27
  try:
28
+ temp_file = 'temp_chunk.wav'
29
  audio_chunk.export(temp_file, format='wav')
30
  result = await shazam.recognize_file(temp_file)
31
+ os.remove(temp_file) # Clean up temporary file
32
  if result and 'track' in result:
33
  track_data = result['track']
34
  return {
 
38
  else:
39
  return None
40
  except Exception as e:
41
+ return f"Error identifying track: {e}"
42
 
43
+ # Main processing function
44
  async def process_dj_set(track_url, progress=gr.Progress()):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  try:
46
+ status = "Resolving SoundCloud URL..."
47
+ headers = {'Authorization': f'Bearer {token}'}
48
  resolve_response = requests.get(f'https://api.soundcloud.com/resolve.json?url={track_url}', headers=headers)
49
+
50
  if resolve_response.status_code != 200:
51
+ return "Failed to resolve track URL.", ""
52
+
53
  track_data = resolve_response.json()
54
+ streaming_url = track_data.get('stream_url')
55
+
56
+ if not streaming_url:
57
+ return "Streaming URL not found.", ""
58
+
59
+ status = "Downloading audio..."
60
+ download_status = download_audio(streaming_url, 'track.wav', headers)
61
+
62
+ if "Error" in download_status:
63
+ return download_status, ""
64
+
65
+ status = "Processing audio..."
66
+ audio = AudioSegment.from_wav('track.wav')
67
+
68
+ chunk_duration = 30000 # 30 seconds
69
+ overlap = 10000 # 10 seconds
70
+
71
+ chunks = []
72
+ start = 0
73
+
74
+ while start + chunk_duration < len(audio):
75
+ end = start + chunk_duration
76
+ chunk = audio[start:end]
77
+ chunks.append((start, chunk))
78
+ start += chunk_duration - overlap
79
+
80
+ shazam = shazamio.Shazam()
81
+ tracklist = []
82
+
83
+ for start_time, chunk in chunks:
84
+ progress(0.1)
85
+ track_info = await identify_track(shazam, chunk)
86
+
87
+ if isinstance(track_info, str) and "Error" in track_info: # Check for errors in identification
88
+ return track_info, ""
89
+
90
+ if track_info:
91
+ timestamp = time.strftime("%M:%S", time.gmtime(start_time / 1000))
92
+ tracklist.append(f"{timestamp} - {track_info['title']} by {track_info['subtitle']}")
93
+
94
+ status = "Generating output..."
95
+ tracklist_output = "\n".join(tracklist)
96
+
97
+ return tracklist_output, tracklist_output
98
  except Exception as e:
99
+ return f"An error occurred during processing: {e}", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  css = """
102
  #col-container {
 
108
  with gr.Blocks(css=css) as demo:
109
  with gr.Column(elem_id="col-container"):
110
  gr.Markdown("# SoundCloud DJ Set Track Identifier")
111
+
112
  with gr.Row():
113
+ track_url_input = gr.Text(
114
  label="SoundCloud DJ Set URL",
115
  show_label=False,
116
  max_lines=1,
117
  placeholder="Enter SoundCloud DJ set URL",
118
  container=False,
119
  )
120
+
121
  run_button = gr.Button("Process", scale=0, variant="primary")
122
+
123
+ result_output = gr.Textbox(label="Tracklist", show_label=False)
124
+
125
  with gr.Accordion("Download Tracklist", open=False):
126
  download_button = gr.File(label="Download")
 
127
 
128
+ gr.Examples(examples=["https://soundcloud.com/your-track-url"], inputs=[track_url_input])
129
+
130
+ run_button.click(process_dj_set, inputs=track_url_input, outputs=[result_output, download_button])
131
 
132
  if __name__ == "__main__":
133
+ demo.launch(share=True)