Spaces:
Runtime error
Runtime error
File size: 2,899 Bytes
7cc32a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | import asyncio
from unittest import result
import yt_dlp
import os
from shazamio import Shazam
import aiohttp
import base64
from functools import partial
CLIENT_ID = "550edc8d6d294381a0f4dac9c8c9fea5"
CLIENT_SECRET = "fade5c01cc8b40acb79ad1f598074b4c"
async def music_recognition(filepath):
shazam = Shazam()
out = await shazam.recognize(filepath)
songname = out['track']['title']
artist = out["track"]["subtitle"]
ydl_opts = {
"quiet": True,
"skip_download": True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f"ytsearch1:{songname} {artist}", download=False)
video = info["entries"][0]
title = video["title"]
yturl = video["webpage_url"]
thumbnail = video["thumbnail"]
duration = video["duration"]
spotifyshit = await spotify_search(f"{songname} {artist}")
spotifylink = spotifyshit["tracks"]["items"][0]["external_urls"]["spotify"]
return {
"songname": songname,
"artist": artist,
"title": title,
"yturl": yturl,
"thumbnail": thumbnail,
"duration": duration,
"spotifylink": spotifylink
}
async def spotify_auth():
auth_url = "https://accounts.spotify.com/api/token"
auth_string = f"{CLIENT_ID}:{CLIENT_SECRET}"
auth_header = base64.b64encode(auth_string.encode()).decode()
headers = {
"Authorization": f"Basic {auth_header}",
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials"
}
async with aiohttp.ClientSession() as session:
async with session.post(auth_url, headers=headers, data=data) as resp:
response = await resp.json()
return response["access_token"]
async def spotify_search(query: str, search_type="track"):
token = await spotify_auth()
url = "https://api.spotify.com/v1/search"
params = {
"q": query,
"type": search_type,
"limit": 1
}
headers = {
"Authorization": f"Bearer {token}"
}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as resp:
data = await resp.json()
return data
async def download_mp3(query: str):
def _download():
ydl_opts = {
"quiet": True,
"format": "bestaudio/best",
"outtmpl": "./assets/audio.%(ext)s",
"postprocessors": [{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.extract_info(f"ytsearch1:{query}", download=True)
return "./assets/audio.mp3"
return await asyncio.to_thread(_download)
|