Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,8 +8,9 @@ import tempfile
|
|
| 8 |
from pathlib import Path
|
| 9 |
import sys
|
| 10 |
import asyncio
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
client_id = os.environ.get('SOUNDCLOUD_CLIENT_ID')
|
| 14 |
client_secret = os.environ.get('SOUNDCLOUD_CLIENT_SECRET')
|
| 15 |
token = os.environ.get('TOKEN')
|
|
@@ -24,22 +25,21 @@ def get_soundcloud_access_token(client_id, client_secret):
|
|
| 24 |
'grant_type': 'client_credentials'
|
| 25 |
}
|
| 26 |
response = requests.post('https://api.soundcloud.com/oauth2/token', headers=auth_headers, data=data)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
except Exception as e:
|
| 33 |
-
return f"Error obtaining access token: {str(e)}"
|
| 34 |
|
| 35 |
def download_audio(streaming_url, output_path, headers):
|
| 36 |
try:
|
| 37 |
response = requests.get(streaming_url, headers=headers, stream=True)
|
|
|
|
| 38 |
with open(output_path, 'wb') as f:
|
| 39 |
for chunk in response.iter_content(chunk_size=8192):
|
| 40 |
f.write(chunk)
|
| 41 |
-
except
|
| 42 |
-
raise Exception(f"
|
| 43 |
|
| 44 |
async def identify_track(shazam, audio_chunk, temp_dir):
|
| 45 |
try:
|
|
@@ -52,58 +52,56 @@ async def identify_track(shazam, audio_chunk, temp_dir):
|
|
| 52 |
'title': track_data['title'],
|
| 53 |
'subtitle': track_data['subtitle']
|
| 54 |
}
|
| 55 |
-
|
| 56 |
-
return None
|
| 57 |
except Exception as e:
|
| 58 |
-
return f"
|
| 59 |
|
| 60 |
async def process_dj_set(track_url, progress=gr.Progress()):
|
| 61 |
-
temp_dir =
|
| 62 |
output_path = os.path.join(temp_dir, 'track.wav')
|
| 63 |
tracklist_path = os.path.join(temp_dir, 'tracklist.txt')
|
| 64 |
status_messages = []
|
| 65 |
|
| 66 |
-
#
|
| 67 |
if not client_id or not client_secret or not token:
|
| 68 |
-
return "", "", "
|
| 69 |
|
| 70 |
-
#
|
| 71 |
access_token = get_soundcloud_access_token(client_id, client_secret)
|
| 72 |
-
if isinstance(access_token, str) and access_token.startswith("
|
| 73 |
return "", "", access_token
|
| 74 |
|
| 75 |
headers = {
|
| 76 |
'Authorization': f'Bearer {access_token}'
|
| 77 |
}
|
| 78 |
|
| 79 |
-
#
|
| 80 |
try:
|
| 81 |
resolve_response = requests.get(f'https://api.soundcloud.com/resolve.json?url={track_url}', headers=headers)
|
| 82 |
-
|
| 83 |
-
return "", "", f"Failed to resolve track URL: {resolve_response.text}"
|
| 84 |
track_data = resolve_response.json()
|
| 85 |
streaming_url = track_data['stream_url']
|
| 86 |
-
status_messages.append("Track
|
| 87 |
-
except
|
| 88 |
-
return "", "", f"
|
| 89 |
|
| 90 |
-
#
|
| 91 |
try:
|
| 92 |
download_audio(streaming_url, output_path, headers)
|
| 93 |
-
status_messages.append("Audio
|
| 94 |
except Exception as e:
|
| 95 |
-
return "", "", f"
|
| 96 |
|
| 97 |
-
#
|
| 98 |
try:
|
| 99 |
audio = AudioSegment.from_wav(output_path)
|
| 100 |
-
status_messages.append("Audio
|
| 101 |
except Exception as e:
|
| 102 |
-
return "", "", f"
|
| 103 |
|
| 104 |
-
#
|
| 105 |
-
chunk_duration = 30000 # 30
|
| 106 |
-
overlap = 10000 # 10
|
| 107 |
chunks = []
|
| 108 |
start = 0
|
| 109 |
while start + chunk_duration < len(audio):
|
|
@@ -112,33 +110,33 @@ async def process_dj_set(track_url, progress=gr.Progress()):
|
|
| 112 |
chunks.append((start, chunk))
|
| 113 |
start += chunk_duration - overlap
|
| 114 |
|
| 115 |
-
#
|
| 116 |
shazam = shazamio.Shazam()
|
| 117 |
|
| 118 |
-
#
|
| 119 |
tracklist = []
|
| 120 |
for start_time, chunk in chunks:
|
| 121 |
progress(0.1)
|
| 122 |
track_info = await identify_track(shazam, chunk, temp_dir)
|
| 123 |
if isinstance(track_info, dict):
|
| 124 |
timestamp = time.strftime("%M:%S", time.gmtime(start_time / 1000))
|
| 125 |
-
tracklist.append(f"{timestamp} - {track_info['title']}
|
| 126 |
elif isinstance(track_info, str):
|
| 127 |
status_messages.append(track_info)
|
| 128 |
|
| 129 |
-
#
|
| 130 |
tracklist_output = "\n".join(tracklist)
|
| 131 |
with open(tracklist_path, 'w') as f:
|
| 132 |
f.write(tracklist_output)
|
| 133 |
|
| 134 |
-
#
|
| 135 |
import shutil
|
| 136 |
shutil.rmtree(temp_dir)
|
| 137 |
|
| 138 |
-
#
|
| 139 |
status_message = "\n".join(status_messages)
|
| 140 |
if not tracklist:
|
| 141 |
-
status_message += "\
|
| 142 |
|
| 143 |
return tracklist_output, tracklist_path, status_message
|
| 144 |
|
|
@@ -158,13 +156,13 @@ with gr.Blocks(css=css) as demo:
|
|
| 158 |
label="SoundCloud DJ Set URL",
|
| 159 |
show_label=False,
|
| 160 |
max_lines=1,
|
| 161 |
-
placeholder="
|
| 162 |
container=False,
|
| 163 |
)
|
| 164 |
-
run_button = gr.Button("
|
| 165 |
-
result = gr.Textbox(label="
|
| 166 |
-
with gr.Accordion("
|
| 167 |
-
download_button = gr.File(label="
|
| 168 |
gr.Examples(examples=["https://soundcloud.com/your-track-url"], inputs=[track_url])
|
| 169 |
|
| 170 |
run_button.click(process_dj_set, inputs=track_url, outputs=[result, download_button, status_text])
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
import sys
|
| 10 |
import asyncio
|
| 11 |
+
import base64 # Hinzugefügt, um base64 zu importieren
|
| 12 |
|
| 13 |
+
# Ersetzen Sie dies durch Ihre tatsächliche Client-ID und Client-Secret
|
| 14 |
client_id = os.environ.get('SOUNDCLOUD_CLIENT_ID')
|
| 15 |
client_secret = os.environ.get('SOUNDCLOUD_CLIENT_SECRET')
|
| 16 |
token = os.environ.get('TOKEN')
|
|
|
|
| 25 |
'grant_type': 'client_credentials'
|
| 26 |
}
|
| 27 |
response = requests.post('https://api.soundcloud.com/oauth2/token', headers=auth_headers, data=data)
|
| 28 |
+
response.raise_for_status() # Verwenden Sie raise_for_status, um Fehler zu behandeln
|
| 29 |
+
token_data = response.json()
|
| 30 |
+
return token_data['access_token']
|
| 31 |
+
except requests.RequestException as e:
|
| 32 |
+
return f"Fehler beim Abrufen des Zugriffstokens: {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 |
+
response.raise_for_status() # Verwenden Sie raise_for_status, um Fehler zu behandeln
|
| 38 |
with open(output_path, 'wb') as f:
|
| 39 |
for chunk in response.iter_content(chunk_size=8192):
|
| 40 |
f.write(chunk)
|
| 41 |
+
except requests.RequestException as e:
|
| 42 |
+
raise Exception(f"Fehler beim Herunterladen des Audios: {str(e)}")
|
| 43 |
|
| 44 |
async def identify_track(shazam, audio_chunk, temp_dir):
|
| 45 |
try:
|
|
|
|
| 52 |
'title': track_data['title'],
|
| 53 |
'subtitle': track_data['subtitle']
|
| 54 |
}
|
| 55 |
+
return None
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
+
return f"Fehler bei der Identifizierung des Tracks: {str(e)}"
|
| 58 |
|
| 59 |
async def process_dj_set(track_url, progress=gr.Progress()):
|
| 60 |
+
temp_dir = tempfile.gettempdir() # Verwenden Sie tempfile für temporäre Verzeichnisse
|
| 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 |
+
# Überprüfen Sie die Umgebungsvariablen
|
| 66 |
if not client_id or not client_secret or not token:
|
| 67 |
+
return "", "", "Umgebungsvariablen sind nicht gesetzt."
|
| 68 |
|
| 69 |
+
# Zugriffstoken abrufen
|
| 70 |
access_token = get_soundcloud_access_token(client_id, client_secret)
|
| 71 |
+
if isinstance(access_token, str) and access_token.startswith("Fehler"):
|
| 72 |
return "", "", access_token
|
| 73 |
|
| 74 |
headers = {
|
| 75 |
'Authorization': f'Bearer {access_token}'
|
| 76 |
}
|
| 77 |
|
| 78 |
+
# Track-URL auflösen
|
| 79 |
try:
|
| 80 |
resolve_response = requests.get(f'https://api.soundcloud.com/resolve.json?url={track_url}', headers=headers)
|
| 81 |
+
resolve_response.raise_for_status() # Verwenden Sie raise_for_status, um Fehler zu behandeln
|
|
|
|
| 82 |
track_data = resolve_response.json()
|
| 83 |
streaming_url = track_data['stream_url']
|
| 84 |
+
status_messages.append("Track-URL erfolgreich aufgelöst.")
|
| 85 |
+
except requests.RequestException as e:
|
| 86 |
+
return "", "", f"Fehler beim Auflösen der Track-URL: {str(e)}"
|
| 87 |
|
| 88 |
+
# Audio herunterladen
|
| 89 |
try:
|
| 90 |
download_audio(streaming_url, output_path, headers)
|
| 91 |
+
status_messages.append("Audio erfolgreich heruntergeladen.")
|
| 92 |
except Exception as e:
|
| 93 |
+
return "", "", f"Fehler beim Herunterladen des Audios: {str(e)}"
|
| 94 |
|
| 95 |
+
# Audio laden
|
| 96 |
try:
|
| 97 |
audio = AudioSegment.from_wav(output_path)
|
| 98 |
+
status_messages.append("Audio erfolgreich geladen.")
|
| 99 |
except Exception as e:
|
| 100 |
+
return "", "", f"Fehler beim Laden des Audios: {str(e)}"
|
| 101 |
|
| 102 |
+
# Audio in Chunks aufteilen
|
| 103 |
+
chunk_duration = 30000 # 30 Sekunden
|
| 104 |
+
overlap = 10000 # 10 Sekunden
|
| 105 |
chunks = []
|
| 106 |
start = 0
|
| 107 |
while start + chunk_duration < len(audio):
|
|
|
|
| 110 |
chunks.append((start, chunk))
|
| 111 |
start += chunk_duration - overlap
|
| 112 |
|
| 113 |
+
# Shazam initialisieren
|
| 114 |
shazam = shazamio.Shazam()
|
| 115 |
|
| 116 |
+
# Tracks identifizieren
|
| 117 |
tracklist = []
|
| 118 |
for start_time, chunk in chunks:
|
| 119 |
progress(0.1)
|
| 120 |
track_info = await identify_track(shazam, chunk, temp_dir)
|
| 121 |
if isinstance(track_info, dict):
|
| 122 |
timestamp = time.strftime("%M:%S", time.gmtime(start_time / 1000))
|
| 123 |
+
tracklist.append(f"{timestamp} - {track_info['title']} von {track_info['subtitle']}")
|
| 124 |
elif isinstance(track_info, str):
|
| 125 |
status_messages.append(track_info)
|
| 126 |
|
| 127 |
+
# Tracklist-Ausgabe vorbereiten
|
| 128 |
tracklist_output = "\n".join(tracklist)
|
| 129 |
with open(tracklist_path, 'w') as f:
|
| 130 |
f.write(tracklist_output)
|
| 131 |
|
| 132 |
+
# Temporäres Verzeichnis bereinigen
|
| 133 |
import shutil
|
| 134 |
shutil.rmtree(temp_dir)
|
| 135 |
|
| 136 |
+
# Statusnachricht vorbereiten
|
| 137 |
status_message = "\n".join(status_messages)
|
| 138 |
if not tracklist:
|
| 139 |
+
status_message += "\nKeine Tracks identifiziert."
|
| 140 |
|
| 141 |
return tracklist_output, tracklist_path, status_message
|
| 142 |
|
|
|
|
| 156 |
label="SoundCloud DJ Set URL",
|
| 157 |
show_label=False,
|
| 158 |
max_lines=1,
|
| 159 |
+
placeholder="Geben Sie die SoundCloud DJ-Set-URL ein",
|
| 160 |
container=False,
|
| 161 |
)
|
| 162 |
+
run_button = gr.Button("Verarbeiten", scale=0, variant="primary")
|
| 163 |
+
result = gr.Textbox(label="Trackliste", show_label=False)
|
| 164 |
+
with gr.Accordion("Trackliste herunterladen", open=False):
|
| 165 |
+
download_button = gr.File(label="Herunterladen")
|
| 166 |
gr.Examples(examples=["https://soundcloud.com/your-track-url"], inputs=[track_url])
|
| 167 |
|
| 168 |
run_button.click(process_dj_set, inputs=track_url, outputs=[result, download_button, status_text])
|