UrlToVideo / app.py
rapacious's picture
Update app.py
b41072e verified
raw
history blame
3.18 kB
import gradio as gr
import yt_dlp
import os
def download_video(url, quality, format_choice, download_playlist, cookies_file):
try:
# Tùy chọn cấu hình cho yt-dlp
ydl_opts = {
'outtmpl': 'downloads/%(title)s.%(ext)s', # Đường dẫn lưu file
'noplaylist': not download_playlist, # Tải playlist nếu được chọn
}
# Sử dụng file cookie nếu được cung cấp
if cookies_file and os.path.exists(cookies_file):
ydl_opts['cookiefile'] = cookies_file
# Điều chỉnh chất lượng video
if quality == "Best":
ydl_opts['format'] = 'bestvideo+bestaudio/best'
elif quality == "Medium":
ydl_opts['format'] = 'bestvideo[height<=720]+bestaudio/best[height<=720]'
else: # Low
ydl_opts['format'] = 'bestvideo[height<=480]+bestaudio/best[height<=480]'
# Điều chỉnh định dạng đầu ra
if format_choice == "MP4":
ydl_opts['merge_output_format'] = 'mp4'
elif format_choice == "MKV":
ydl_opts['merge_output_format'] = 'mkv'
else: # Audio Only (MP3)
ydl_opts['format'] = 'bestaudio'
ydl_opts['postprocessors'] = [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}]
# Tạo thư mục downloads nếu chưa tồn tại
if not os.path.exists('downloads'):
os.makedirs('downloads')
# Tải video
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info)
return f"Video đã tải thành công: {filename}"
except Exception as e:
return f"Lỗi: {str(e)}"
# Tạo giao diện Gradio
interface = gr.Interface(
fn=download_video,
inputs=[
gr.Textbox(label="Dán URL video vào đây", placeholder="https://..."),
gr.Dropdown(
choices=["Best", "Medium", "Low"],
label="Chất lượng video",
value="Best",
info="Best: Cao nhất, Medium: 720p, Low: 480p"
),
gr.Dropdown(
choices=["MP4", "MKV", "Audio Only (MP3)"],
label="Định dạng đầu ra",
value="MP4",
info="Chọn định dạng file xuất ra"
),
gr.Checkbox(
label="Tải toàn bộ playlist (nếu có)",
value=False,
info="Check để tải toàn bộ playlist"
),
gr.Textbox(
label="Đường dẫn file cookie (nếu cần)",
placeholder="Ví dụ: cookies.txt",
info="Dùng file cookie để tải video yêu cầu đăng nhập (YouTube, v.v.)"
)
],
outputs=gr.Textbox(label="Kết quả"),
title="Trình tải video nâng cao",
description="Dán URL video và tùy chỉnh. Nếu video yêu cầu đăng nhập, cung cấp file cookie."
)
# Khởi chạy ứng dụng
interface.launch()