sheikhed commited on
Commit
6aab7cd
·
verified ·
1 Parent(s): 5089897

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -95
app.py CHANGED
@@ -1,109 +1,74 @@
1
  import gradio as gr
2
  import yt_dlp
3
  import os
4
- import re
5
- from pathlib import Path
6
 
7
- def get_browser_cookies():
8
- """Get cookies from browser - tries Chrome first, then Firefox, then Edge"""
9
- browsers = ['chrome', 'firefox', 'edge']
10
- for browser in browsers:
11
- try:
12
- return browser
13
- except Exception:
14
- continue
15
- return None
16
 
17
- def sanitize_filename(title):
18
- """Remove invalid characters from filename"""
19
- return re.sub(r'[<>:"/\\|?*]', '', title)
 
 
 
 
20
 
21
- def download_audio(url, output_dir="downloads"):
22
- try:
23
- # Create output directory if it doesn't exist
24
- if not os.path.exists(output_dir):
25
- os.makedirs(output_dir)
26
-
27
- # Get browser cookies
28
- browser = get_browser_cookies()
29
- if not browser:
30
- return {
31
- "status": "error",
32
- "message": "No supported browser found. Please ensure Chrome, Firefox, or Edge is installed."
33
- }
34
 
35
- # Configure yt-dlp options
36
- ydl_opts = {
37
- 'format': 'bestaudio/best',
38
- 'postprocessors': [{
39
- 'key': 'FFmpegExtractAudio',
40
- 'preferredcodec': 'mp3',
41
- 'preferredquality': '192',
42
- }],
43
- 'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
44
- 'cookiesfrombrowser': (browser,), # Add browser cookies
45
- 'verbose': True
46
- }
47
-
48
- # Download with yt-dlp
49
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
50
- # Get video info first
51
- info = ydl.extract_info(url, download=False)
52
- title = info.get('title', 'video')
53
- duration = info.get('duration', 0)
54
- author = info.get('uploader', 'Unknown')
55
-
56
- # Download the video
57
- ydl.download([url])
58
-
59
- # Construct the output filepath
60
- safe_title = sanitize_filename(title)
61
- output_file = os.path.join(output_dir, f"{safe_title}.mp3")
62
-
63
- return {
64
- "status": "success",
65
- "message": f"Successfully downloaded: {safe_title}",
66
- "title": title,
67
- "author": author,
68
- "duration": f"{duration // 60}:{duration % 60:02d}",
69
- "file_path": output_file
70
- }
71
-
72
  except Exception as e:
73
- return {
74
- "status": "error",
75
- "message": f"Error: {str(e)}",
76
- "title": "",
77
- "author": "",
78
- "duration": "",
79
- "file_path": ""
80
- }
 
 
 
 
 
 
 
 
 
81
 
82
- def process_url(url):
83
- if not url.strip():
84
- return "Please enter a YouTube URL"
85
-
86
- result = download_audio(url)
87
-
88
- if result["status"] == "error":
89
- return result["message"]
90
-
91
- return f"""Download successful!
92
- Title: {result['title']}
93
- Author: {result['author']}
94
- Duration: {result['duration']}
95
- Saved to: {result['file_path']}"""
96
 
97
- # Create Gradio interface
98
- iface = gr.Interface(
99
- fn=process_url,
100
- inputs=gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here..."),
101
- outputs=gr.Textbox(label="Status"),
102
- title="YouTube to MP3 Downloader",
103
- description="Enter a YouTube URL to download the audio as MP3. Make sure you're logged into YouTube in Chrome, Firefox, or Edge.",
104
- examples=[["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]],
105
- theme=gr.themes.Base()
106
- )
107
 
108
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  iface.launch()
 
1
  import gradio as gr
2
  import yt_dlp
3
  import os
 
 
4
 
5
+ def download_video_as_mp3(video_url, output_dir="downloads"):
6
+ """
7
+ Downloads a YouTube video as an MP3 file using yt-dlp.
 
 
 
 
 
 
8
 
9
+ :param video_url: The URL of the YouTube video.
10
+ :param output_dir: Directory where the MP3 file will be saved.
11
+ :return: A tuple containing the filepath of the downloaded MP3 and a status message.
12
+ Returns (None, error_message) if an error occurred.
13
+ """
14
+ if not os.path.exists(output_dir):
15
+ os.makedirs(output_dir)
16
 
17
+ ydl_opts = {
18
+ 'format': 'bestaudio/best',
19
+ 'postprocessors': [{
20
+ 'key': 'FFmpegExtractAudio',
21
+ 'preferredcodec': 'mp3',
22
+ 'preferredquality': '192',
23
+ }],
24
+ 'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
25
+ 'quiet': True, # Set to True for cleaner Gradio output, remove if you want yt-dlp's progress in terminal
26
+ 'noplaylist': True,
27
+ }
 
 
28
 
29
+ try:
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
31
+ info_dict = ydl.extract_info(video_url, download=True)
32
+ video_title = info_dict.get('title', 'video')
33
+ output_filepath = os.path.join(output_dir, f"{video_title}.mp3")
34
+ status_message = "Download complete!"
35
+ return output_filepath, status_message
36
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  except Exception as e:
38
+ error_message = f"An error occurred: {e}"
39
+ return None, error_message
40
+
41
+
42
+ def gradio_interface(video_url):
43
+ """
44
+ Gradio interface function to download YouTube video as MP3.
45
+
46
+ :param video_url: YouTube video URL from Gradio Textbox.
47
+ :return: A tuple containing the filepath of the downloaded MP3 (for Gradio File output) and status message (for Gradio Textbox).
48
+ """
49
+ if not video_url:
50
+ return None, "Please enter a YouTube video URL."
51
+
52
+ output_directory = "downloads" # Default output directory
53
+
54
+ filepath, status_message = download_video_as_mp3(video_url, output_directory)
55
 
56
+ return filepath, status_message
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  if __name__ == "__main__":
60
+ iface = gr.Interface(
61
+ fn=gradio_interface,
62
+ inputs=gr.Textbox(label="YouTube Video URL", placeholder="Enter YouTube URL here"),
63
+ outputs=[
64
+ gr.File(label="Downloaded MP3 File"),
65
+ gr.Textbox(label="Status"),
66
+ ],
67
+ title="YouTube to MP3 Downloader",
68
+ description="Enter a YouTube video URL and click 'Submit' to download it as MP3. The file will be saved in the 'downloads' directory.",
69
+ examples=[
70
+ ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
71
+ ["https://www.youtube.com/watch?v=your_video_id"],
72
+ ]
73
+ )
74
  iface.launch()