Spaces:
Running
Running
import os | |
import yt_dlp | |
from .. import helpers | |
from yt_dlp.utils import download_range_func | |
def getPreview(request): | |
error_code = None | |
url = helpers.getFromRequest(request, "url") | |
if not url: return {"status": "error", "details": { "error_code": 101, "error_details": "No link provided" }}, 400 | |
bitrate = helpers.getFromRequest(request, "bitrate") | |
if not bitrate: bitrate = "64k" | |
quality = helpers.getFromRequest(request, "quality") | |
if not quality or quality.lower() not in ['best', 'worst']: | |
quality = 'worst' | |
else: quality = quality.lower() | |
audioformat = helpers.getFromRequest(request, "extension") | |
if not audioformat or audioformat.lower() not in ['m4a', 'aac', 'mp3', 'ogg', 'opus', 'webm']: | |
audioformat = 'ogg' | |
else: audioformat = audioformat.lower() | |
urlcode = url.partition('?v=')[2] | |
if not urlcode: urlcode = "NPRNRQh2fAo" | |
duration = helpers.getFromRequest(request, "duration") | |
try: duration = int(duration) | |
except Exception as e: | |
print(e) | |
duration = 45 | |
config = helpers.configFile() | |
__filename = f"{urlcode}_dur{duration}.{audioformat}" | |
if os.path.exists(f"{config['previews-path']}/{__filename}"): | |
return { | |
"status": "pass", | |
"details": { | |
"code": error_code, | |
"name":f"{urlcode}.{audioformat}", | |
"result": f"{config['url']}/static/previews/{__filename}" | |
} | |
} | |
ydl_opts = { | |
'format': f'{audioformat}/{quality}audio/{quality}', | |
'outtmpl': f"{config['previews-path']}/{__filename}", | |
'progress_hooks': [helpers.thisIsHook], | |
'download_ranges': download_range_func(None, [(0, duration)]), | |
'force_keyframes_at_cuts': True, | |
"extractor_args": {"youtube": {"player_client": "ios"}}, | |
} | |
try: | |
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
error_code = ydl.download(url) | |
except Exception as e: return {"status": "error", "details": {"error_code": 102, "error_details": str(e)}}, 400 | |
return { | |
"status": "pass", | |
"details": { | |
"code": error_code, | |
"name":f"{urlcode}.{audioformat}", | |
"result": f"{config['url']}/static/previews/{__filename}" | |
} | |
} |