WeVi commited on
Commit
8cd79ca
·
verified ·
1 Parent(s): 0bb7aa2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -47
app.py CHANGED
@@ -1,74 +1,93 @@
1
  import yt_dlp
2
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
3
 
4
  def get_video_info(url):
5
  try:
6
- ydl_opts = {"quiet": True, "skip_download": True}
 
7
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
8
  info = ydl.extract_info(url, download=False)
9
-
10
  formats = []
11
- for f in info['formats']:
12
- if f.get("vcodec") != "none" and f.get("acodec") != "none":
13
  resolution = f.get("format_note") or f"{f.get('height')}p"
14
- if resolution and f.get("url"):
15
  formats.append({
16
  "resolution": resolution,
17
  "ext": f.get("ext"),
18
- "url": f.get("url")
19
  })
20
-
21
- # remove duplicates and sort
22
  unique = {f["resolution"]: f for f in formats}
23
- sorted_formats = sorted(unique.values(), key=lambda x: int(x["resolution"].replace("p","").replace("k","000")))
24
-
25
- return info["title"], sorted_formats
26
  except Exception as e:
27
- return str(e), []
28
-
29
 
30
  def download_video(url, quality):
31
- title, formats = get_video_info(url)
32
- if not formats:
33
- return None, "No formats available."
34
-
35
- for f in formats:
36
- if f["resolution"] == quality:
37
- return f["url"], f"Click the link below to download {title} in {quality}"
38
-
39
- return None, "Selected quality not available."
40
-
41
-
42
- def ui_app(url):
43
- title, formats = get_video_info(url)
44
- if not formats:
45
- return "Error fetching video info", None, []
46
-
47
- qualities = [f["resolution"] for f in formats]
48
- return title, url, qualities
49
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
51
  with gr.Blocks() as demo:
52
- gr.Markdown("## 🎥 YouTube Video Downloader")
53
-
54
- with gr.Row():
55
- url_in = gr.Textbox(label="YouTube Video URL")
56
- fetch_btn = gr.Button("Fetch Info")
57
-
58
  title_out = gr.Textbox(label="Video Title", interactive=False)
59
  quality_out = gr.Dropdown(label="Select Quality")
60
 
61
- with gr.Row():
62
- download_btn = gr.Button("Get Download Link")
63
-
64
- result_msg = gr.Textbox(label="Message", interactive=False)
65
- download_link = gr.Textbox(label="Direct Download Link", interactive=False)
66
-
67
  def fetch_info(url):
68
- title, _, qualities = ui_app(url)
 
69
  return title, gr.Dropdown.update(choices=qualities)
70
-
71
  fetch_btn.click(fetch_info, inputs=[url_in], outputs=[title_out, quality_out])
72
- download_btn.click(download_video, inputs=[url_in, quality_out], outputs=[download_link, result_msg])
73
 
74
  demo.launch()
 
1
  import yt_dlp
2
  import gradio as gr
3
+ import os
4
+
5
+ DOWNLOAD_DIR = "downloads"
6
+ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
7
+
8
+ def clean_url(url: str) -> str:
9
+ """Convert youtu.be short links to full format"""
10
+ if "youtu.be" in url:
11
+ return url.replace("youtu.be/", "www.youtube.com/watch?v=")
12
+ return url
13
 
14
  def get_video_info(url):
15
  try:
16
+ url = clean_url(url)
17
+ ydl_opts = {"quiet": True, "skip_download": True, "nocheckcertificate": True}
18
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
19
  info = ydl.extract_info(url, download=False)
 
20
  formats = []
21
+ for f in info.get("formats", []):
22
+ if f.get("vcodec") != "none":
23
  resolution = f.get("format_note") or f"{f.get('height')}p"
24
+ if resolution:
25
  formats.append({
26
  "resolution": resolution,
27
  "ext": f.get("ext"),
28
+ "format_id": f.get("format_id")
29
  })
30
+ # remove duplicates by resolution
 
31
  unique = {f["resolution"]: f for f in formats}
32
+ return info.get("title", "Unknown"), list(unique.values())
 
 
33
  except Exception as e:
34
+ return f"Error: {str(e)}", []
 
35
 
36
  def download_video(url, quality):
37
+ try:
38
+ url = clean_url(url)
39
+ title, formats = get_video_info(url)
40
+ if not formats:
41
+ return None, "No formats available."
42
+
43
+ # find selected format
44
+ format_id = None
45
+ ext = "mp4"
46
+ for f in formats:
47
+ if f["resolution"] == quality:
48
+ format_id = f["format_id"]
49
+ ext = f["ext"]
50
+ break
51
+
52
+ if not format_id:
53
+ return None, "Selected quality not available."
54
+
55
+ # unique file path
56
+ safe_title = "".join(c if c.isalnum() else "_" for c in title)[:50]
57
+ filepath = os.path.join(DOWNLOAD_DIR, f"{safe_title}_{quality}.{ext}")
58
+
59
+ ydl_opts = {
60
+ "format": format_id,
61
+ "outtmpl": filepath,
62
+ "quiet": True,
63
+ "nocheckcertificate": True
64
+ }
65
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
66
+ ydl.download([url])
67
+
68
+ return filepath, f"Downloaded {title} in {quality}"
69
+ except Exception as e:
70
+ return None, f"Error: {str(e)}"
71
 
72
+ # ---------- Gradio UI ----------
73
  with gr.Blocks() as demo:
74
+ gr.Markdown("## 🎥 YouTube Video Downloader (Demo)")
75
+
76
+ url_in = gr.Textbox(label="Enter YouTube URL")
77
+ fetch_btn = gr.Button("Fetch Info")
 
 
78
  title_out = gr.Textbox(label="Video Title", interactive=False)
79
  quality_out = gr.Dropdown(label="Select Quality")
80
 
81
+ download_btn = gr.Button("Download")
82
+ result_msg = gr.Textbox(label="Status", interactive=False)
83
+ download_file = gr.File(label="Download File")
84
+
 
 
85
  def fetch_info(url):
86
+ title, formats = get_video_info(url)
87
+ qualities = [f["resolution"] for f in formats]
88
  return title, gr.Dropdown.update(choices=qualities)
89
+
90
  fetch_btn.click(fetch_info, inputs=[url_in], outputs=[title_out, quality_out])
91
+ download_btn.click(download_video, inputs=[url_in, quality_out], outputs=[download_file, result_msg])
92
 
93
  demo.launch()