Spaces:
Runtime error
Runtime error
File size: 15,474 Bytes
5657d70 5f28806 194ba2e 5f28806 561e61e 5f28806 194ba2e 5f28806 561e61e 5f28806 194ba2e 5f28806 74a7283 5f28806 194ba2e 5f28806 74a7283 5f28806 194ba2e 5f28806 74a7283 5f28806 561e61e 5f28806 194ba2e 5f28806 194ba2e 5f28806 864798c 5f28806 50c9fe4 5f28806 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 74a7283 864798c 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 e9a55dc 5f28806 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# import streamlit as st
# import yt_dlp
# import os
# from pathlib import Path
# # Set page config
# st.set_page_config(page_title="YouTube Video Downloader", page_icon="πΊ")
# # Set the title of the app
# st.title("YouTube Video Downloader πΊ")
# # Create output directory if it doesn't exist
# output_dir = Path("downloads")
# output_dir.mkdir(exist_ok=True)
# # Input field for YouTube video URL
# video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
# # Function to download video
# def download_video(url):
# try:
# ydl_opts = {
# 'format': 'bestvideo+bestaudio/best',
# 'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
# 'merge_output_format': 'webm',
# # Add these options to mimic browser behavior
# 'quiet': True,
# 'no_warnings': True,
# 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
# 'referer': 'https://www.youtube.com/',
# 'cookiefile': 'youtube.com_cookies.txt', # μΏ ν€ νμΌ μ¬μ©
# 'socket_timeout': 30,
# 'http_chunk_size': 10485760, # 10MB
# }
# # Progress placeholder
# progress_bar = st.progress(0)
# status_text = st.empty()
# def progress_hook(d):
# if d['status'] == 'downloading':
# try:
# progress = d['downloaded_bytes'] / d['total_bytes']
# progress_bar.progress(progress)
# status_text.text(f"Downloading: {progress:.1%}")
# except:
# status_text.text("Downloading... (size unknown)")
# elif d['status'] == 'finished':
# progress_bar.progress(1.0)
# status_text.text("Processing...")
# ydl_opts['progress_hooks'] = [progress_hook]
# with yt_dlp.YoutubeDL(ydl_opts) as ydl:
# info = ydl.extract_info(url, download=True)
# filename = ydl.prepare_filename(info)
# return filename
# except Exception as e:
# st.error(f"An error occurred: {str(e)}")
# return None
# # Download button
# if st.button("Download"):
# if video_url:
# try:
# with st.spinner("Preparing download..."):
# downloaded_file_path = download_video(video_url)
# if downloaded_file_path and os.path.exists(downloaded_file_path):
# with open(downloaded_file_path, 'rb') as file:
# st.download_button(
# label="Click here to download",
# data=file,
# file_name=os.path.basename(downloaded_file_path),
# mime="application/octet-stream"
# )
# st.success("β
Download ready!")
# else:
# st.error("β Download failed. Please try again.")
# except Exception as e:
# st.error(f"β An error occurred: {str(e)}")
# else:
# st.warning("β οΈ Please enter a valid YouTube URL.")
# # Help section
# with st.expander("βΉοΈ Help & Troubleshooting"):
# st.markdown("""
# **If you're experiencing download issues:**
# 1. Cookie Authentication Method:
# - Install a browser extension like "Get cookies.txt"
# - Visit YouTube and ensure you're logged in
# - Export cookies to 'youtube.com_cookies.txt'
# - Place the file in the same directory as this app
# 2. Alternative Solutions:
# - Try different videos
# - Check if the video is public/not age-restricted
# - Try again later if YouTube is blocking requests
# """)
# import streamlit as st
# import yt_dlp
# import os
# from pathlib import Path
# # Set page config
# st.set_page_config(page_title="YouTube Video Downloader", page_icon="πΊ")
# # Set the title of the app
# st.title("YouTube Video Downloader πΊ")
# # Create output directory if it doesn't exist
# output_dir = Path("downloads")
# output_dir.mkdir(exist_ok=True)
# # Check if cookies file exists
# COOKIES_FILE = 'youtube.com_cookies.txt'
# has_cookies = os.path.exists(COOKIES_FILE)
# if has_cookies:
# st.success("β
Cookie file detected")
# else:
# st.warning("β οΈ No cookie file found - Some videos might be restricted")
# # Input field for YouTube video URL
# video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
# def download_video(url):
# try:
# ydl_opts = {
# 'format': 'bestvideo+bestaudio/best',
# 'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
# 'merge_output_format': 'webm',
# 'quiet': True,
# 'no_warnings': True,
# 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
# 'referer': 'https://www.youtube.com/',
# 'http_chunk_size': 10485760
# }
# # Add cookies file if available
# if has_cookies:
# ydl_opts['cookiefile'] = COOKIES_FILE
# # Progress placeholder
# progress_bar = st.progress(0)
# status_text = st.empty()
# def progress_hook(d):
# if d['status'] == 'downloading':
# try:
# progress = d['downloaded_bytes'] / d['total_bytes']
# progress_bar.progress(progress)
# status_text.text(f"Downloading: {progress:.1%}")
# except:
# status_text.text("Downloading... (size unknown)")
# elif d['status'] == 'finished':
# progress_bar.progress(1.0)
# status_text.text("Processing...")
# ydl_opts['progress_hooks'] = [progress_hook]
# with yt_dlp.YoutubeDL(ydl_opts) as ydl:
# info = ydl.extract_info(url, download=True)
# filename = ydl.prepare_filename(info)
# return filename
# except Exception as e:
# st.error(f"An error occurred: {str(e)}")
# return None
# # Download button
# if st.button("Download"):
# if video_url:
# try:
# with st.spinner("Preparing download..."):
# downloaded_file_path = download_video(video_url)
# if downloaded_file_path and os.path.exists(downloaded_file_path):
# with open(downloaded_file_path, 'rb') as file:
# st.download_button(
# label="Click here to download",
# data=file,
# file_name=os.path.basename(downloaded_file_path),
# mime="application/octet-stream"
# )
# st.success("β
Download ready!")
# else:
# st.error("β Download failed. Please try again.")
# except Exception as e:
# st.error(f"β An error occurred: {str(e)}")
# else:
# st.warning("β οΈ Please enter a valid YouTube URL.")
# # Help section
# with st.expander("βΉοΈ Help & Information"):
# st.markdown("""
# **About Cookie Authentication:**
# - This app uses cookie authentication to bypass YouTube's bot detection
# - Cookies help the app behave like a logged-in browser
# - No personal data is stored or transmitted
# **If downloads fail:**
# 1. Check if the video is public
# 2. Verify the URL is correct
# 3. Try a different video
# 4. Try again later if YouTube is blocking requests
# """)
import streamlit as st
import yt_dlp
import os
from pathlib import Path
from http.cookiejar import MozillaCookieJar
import random
import time
# Constants
COOKIES_FILE = 'youtube.com_cookies.txt'
OUTPUT_DIR = Path("downloads")
# Set page config
st.set_page_config(page_title="YouTube Video Downloader", page_icon="πΊ")
st.title("YouTube Video Downloader πΊ")
# Create output directory if it doesn't exist
OUTPUT_DIR.mkdir(exist_ok=True)
def get_random_user_agent():
"""λλ€ User-Agent μμ±"""
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0'
]
return random.choice(user_agents)
def validate_cookies():
"""μΏ ν€ νμΌ μ ν¨μ± κ²μ¬ λ° κ°±μ """
if not os.path.exists(COOKIES_FILE):
return False, "Cookie file not found"
try:
cookie_jar = MozillaCookieJar(COOKIES_FILE)
cookie_jar.load()
return True, "Cookies loaded successfully"
except Exception as e:
return False, f"Cookie error: {str(e)}"
def download_with_retry(url, ydl_opts, max_retries=3, delay=5):
"""μ¬μλ λ‘μ§μ΄ ν¬ν¨λ λ€μ΄λ‘λ ν¨μ"""
for attempt in range(max_retries):
try:
# 맀 μλλ§λ€ μλ‘μ΄ User-Agent μ¬μ©
ydl_opts['headers']['User-Agent'] = get_random_user_agent()
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info)
return filename, info
except yt_dlp.utils.DownloadError as e:
if "Sign in to confirm you're not a bot" in str(e):
if attempt < max_retries - 1:
st.warning(f"Bot detection encountered. Retrying in {delay} seconds... (Attempt {attempt + 1}/{max_retries})")
time.sleep(delay)
delay *= 2 # μ§μ λ°±μ€ν
continue
raise e
except Exception as e:
if attempt < max_retries - 1:
st.warning(f"Error occurred. Retrying... (Attempt {attempt + 1}/{max_retries})")
time.sleep(delay)
continue
raise e
def download_video(url):
try:
ydl_opts = {
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
'outtmpl': str(OUTPUT_DIR / '%(title)s.%(ext)s'),
'merge_output_format': 'mp4',
# μΏ ν€ λ° μΈμ¦ μ€μ
'cookiefile': COOKIES_FILE,
'cookiesfrombrowser': ('chrome',),
# ν₯μλ μ΅μ
'quiet': True,
'no_warnings': True,
'extract_flat': False,
'socket_timeout': 30,
'retries': 10,
'fragment_retries': 10,
# ν₯μλ ν€λ
'headers': {
'User-Agent': get_random_user_agent(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Cache-Control': 'max-age=0',
},
# μΆκ° μ΅μ
'age_limit': None,
'geo_bypass': True,
'geo_bypass_country': 'US',
'sleep_interval': 2, # μμ² μ¬μ΄ λκΈ° μκ°
'max_sleep_interval': 5,
}
# μ§ν μν© νμ
progress_bar = st.progress(0)
status_text = st.empty()
def progress_hook(d):
if d['status'] == 'downloading':
try:
progress = d['downloaded_bytes'] / d['total_bytes']
progress_bar.progress(progress)
status_text.text(f"Downloading: {progress:.1%} | Speed: {d.get('speed_str', 'N/A')} | ETA: {d.get('eta_str', 'N/A')}")
except:
status_text.text(f"Downloading... Speed: {d.get('speed_str', 'N/A')}")
elif d['status'] == 'finished':
progress_bar.progress(1.0)
status_text.text("Processing...")
ydl_opts['progress_hooks'] = [progress_hook]
return download_with_retry(url, ydl_opts)
except Exception as e:
raise Exception(f"Download error: {str(e)}")
# μΏ ν€ μν νμΈ
cookie_valid, cookie_message = validate_cookies()
if not cookie_valid:
st.warning(f"β οΈ Cookie Issue: {cookie_message}")
else:
st.success("β
Cookies loaded successfully")
# λΉλμ€ URL μ
λ ₯
video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
# λ€μ΄λ‘λ λ²νΌ
if st.button("Download Video"):
if not video_url:
st.warning("β οΈ Please enter a valid YouTube URL.")
elif not cookie_valid:
st.error("β Cannot proceed without valid cookies.")
else:
try:
with st.spinner("Preparing download..."):
downloaded_file_path, video_info = download_video(video_url)
if downloaded_file_path and os.path.exists(downloaded_file_path):
file_size = os.path.getsize(downloaded_file_path)
st.info(f"""
**Download Complete!**
- File: {os.path.basename(downloaded_file_path)}
- Size: {file_size / (1024*1024):.1f} MB
""")
with open(downloaded_file_path, 'rb') as file:
st.download_button(
label="πΎ Download Video",
data=file,
file_name=os.path.basename(downloaded_file_path),
mime="video/mp4"
)
else:
st.error("β Download failed. Please try again.")
except Exception as e:
st.error(f"β {str(e)}")
# Help μΉμ
with st.expander("βΉοΈ Troubleshooting Guide"):
st.markdown("""
**If you encounter 'Sign in to confirm you're not a bot' error:**
1. Cookie Solution:
- Make sure you're logged into YouTube in your browser
- Install 'Get cookies.txt' or similar extension
- Export fresh cookies and replace the existing cookie file
2. General Tips:
- Wait a few minutes between download attempts
- Try using a different video URL
- Clear your browser cache before exporting cookies
3. Advanced Tips:
- The app automatically retries downloads with different settings
- Each retry uses a different User-Agent to avoid detection
- Built-in delays help avoid triggering YouTube's protection
""") |