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, "audioformat") | |
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() | |
if os.path.exists(f"{config['previews-path']}/{urlcode}.{audioformat}"): | |
return { | |
"status": "pass", | |
"details": { | |
"code": error_code, | |
"name":f"{urlcode}.{audioformat}", | |
"result": f"{config['url']}/static/previews/{urlcode}.{audioformat}" | |
} | |
} | |
ydl_opts = { | |
'format': f'{audioformat}/{quality}audio/{quality}', | |
'outtmpl': f"{config['previews-path']}/{urlcode}.{audioformat}", | |
'progress_hooks': [helpers.thisIsHook], | |
'download_ranges': download_range_func(None, [(0, duration)]), | |
'force_keyframes_at_cuts': True, | |
} | |
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/{urlcode}.{audioformat}" | |
} | |
} |