jpjp9292 commited on
Commit
74a7283
β€’
1 Parent(s): b16e75d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -208
app.py CHANGED
@@ -300,116 +300,6 @@
300
  # """)
301
 
302
 
303
- # import streamlit as st
304
- # import yt_dlp
305
- # import os
306
- # from pathlib import Path
307
-
308
- # # Set page config
309
- # st.set_page_config(page_title="YouTube Video Downloader", page_icon="πŸ“Ί")
310
-
311
- # # Set the title of the app
312
- # st.title("YouTube Video Downloader πŸ“Ί")
313
-
314
- # # Create output directory if it doesn't exist
315
- # output_dir = Path("downloads")
316
- # output_dir.mkdir(exist_ok=True)
317
-
318
- # # Check if cookies file exists
319
- # COOKIES_FILE = 'youtube.com_cookies.txt'
320
- # has_cookies = os.path.exists(COOKIES_FILE)
321
-
322
- # if has_cookies:
323
- # st.success("βœ… Cookie file detected")
324
- # else:
325
- # st.warning("⚠️ No cookie file found - Some videos might be restricted")
326
-
327
- # # Input field for YouTube video URL
328
- # video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
329
-
330
- # def download_video(url):
331
- # try:
332
- # ydl_opts = {
333
- # 'format': 'bestvideo+bestaudio/best',
334
- # 'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
335
- # 'merge_output_format': 'webm',
336
- # 'quiet': True,
337
- # 'no_warnings': True,
338
- # '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',
339
- # 'referer': 'https://www.youtube.com/',
340
- # 'http_chunk_size': 10485760
341
- # }
342
-
343
- # # Add cookies file if available
344
- # if has_cookies:
345
- # ydl_opts['cookiefile'] = COOKIES_FILE
346
-
347
- # # Progress placeholder
348
- # progress_bar = st.progress(0)
349
- # status_text = st.empty()
350
-
351
- # def progress_hook(d):
352
- # if d['status'] == 'downloading':
353
- # try:
354
- # progress = d['downloaded_bytes'] / d['total_bytes']
355
- # progress_bar.progress(progress)
356
- # status_text.text(f"Downloading: {progress:.1%}")
357
- # except:
358
- # status_text.text("Downloading... (size unknown)")
359
- # elif d['status'] == 'finished':
360
- # progress_bar.progress(1.0)
361
- # status_text.text("Processing...")
362
-
363
- # ydl_opts['progress_hooks'] = [progress_hook]
364
-
365
- # with yt_dlp.YoutubeDL(ydl_opts) as ydl:
366
- # info = ydl.extract_info(url, download=True)
367
- # filename = ydl.prepare_filename(info)
368
- # return filename
369
-
370
- # except Exception as e:
371
- # st.error(f"An error occurred: {str(e)}")
372
- # return None
373
-
374
- # # Download button
375
- # if st.button("Download"):
376
- # if video_url:
377
- # try:
378
- # with st.spinner("Preparing download..."):
379
- # downloaded_file_path = download_video(video_url)
380
-
381
- # if downloaded_file_path and os.path.exists(downloaded_file_path):
382
- # with open(downloaded_file_path, 'rb') as file:
383
- # st.download_button(
384
- # label="Click here to download",
385
- # data=file,
386
- # file_name=os.path.basename(downloaded_file_path),
387
- # mime="application/octet-stream"
388
- # )
389
- # st.success("βœ… Download ready!")
390
- # else:
391
- # st.error("❌ Download failed. Please try again.")
392
- # except Exception as e:
393
- # st.error(f"❌ An error occurred: {str(e)}")
394
- # else:
395
- # st.warning("⚠️ Please enter a valid YouTube URL.")
396
-
397
- # # Help section
398
- # with st.expander("ℹ️ Help & Information"):
399
- # st.markdown("""
400
- # **About Cookie Authentication:**
401
- # - This app uses cookie authentication to bypass YouTube's bot detection
402
- # - Cookies help the app behave like a logged-in browser
403
- # - No personal data is stored or transmitted
404
-
405
- # **If downloads fail:**
406
- # 1. Check if the video is public
407
- # 2. Verify the URL is correct
408
- # 3. Try a different video
409
- # 4. Try again later if YouTube is blocking requests
410
- # """)
411
-
412
-
413
  import streamlit as st
414
  import yt_dlp
415
  import os
@@ -425,69 +315,36 @@ st.title("YouTube Video Downloader πŸ“Ί")
425
  output_dir = Path("downloads")
426
  output_dir.mkdir(exist_ok=True)
427
 
 
 
 
 
 
 
 
 
 
428
  # Input field for YouTube video URL
429
  video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
430
 
431
- # Format selection
432
- format_option = st.selectbox(
433
- "Select Quality",
434
- ["Best Quality", "720p", "480p", "360p", "Audio Only"]
435
- )
436
-
437
- def get_format_options(format_choice):
438
- if format_choice == "Best Quality":
439
- return {
440
- 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
441
- 'merge_output_format': 'mp4'
442
- }
443
- elif format_choice == "720p":
444
- return {
445
- 'format': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
446
- 'merge_output_format': 'mp4'
447
- }
448
- elif format_choice == "480p":
449
- return {
450
- 'format': 'bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]/best',
451
- 'merge_output_format': 'mp4'
452
- }
453
- elif format_choice == "360p":
454
- return {
455
- 'format': 'bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360][ext=mp4]/best',
456
- 'merge_output_format': 'mp4'
457
- }
458
- else: # Audio Only
459
- return {
460
- 'format': 'bestaudio[ext=m4a]/best',
461
- 'merge_output_format': 'm4a'
462
- }
463
-
464
- def download_video(url, format_choice):
465
  try:
466
- # Base options
467
  ydl_opts = {
 
468
  'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
 
469
  'quiet': True,
470
  'no_warnings': True,
471
- 'extract_flat': False,
472
- 'no_color': True,
473
- # Advanced options to help avoid detection
474
- 'socket_timeout': 30,
475
- 'retries': 3,
476
- 'ignoreerrors': True,
477
- 'nocheckcertificate': True,
478
- # Modern browser headers
479
- 'headers': {
480
- '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',
481
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
482
- 'Accept-Language': 'en-us,en;q=0.5',
483
- 'Sec-Fetch-Mode': 'navigate',
484
- }
485
  }
486
-
487
- # Add format-specific options
488
- ydl_opts.update(get_format_options(format_choice))
489
-
490
- # Progress tracking
 
491
  progress_bar = st.progress(0)
492
  status_text = st.empty()
493
 
@@ -498,34 +355,20 @@ def download_video(url, format_choice):
498
  progress_bar.progress(progress)
499
  status_text.text(f"Downloading: {progress:.1%}")
500
  except:
501
- progress = -1
502
- if 'downloaded_bytes' in d:
503
- status_text.text(f"Downloading... ({d['downloaded_bytes'] / 1024 / 1024:.1f} MB)")
504
- else:
505
- status_text.text("Downloading... (size unknown)")
506
  elif d['status'] == 'finished':
507
  progress_bar.progress(1.0)
508
  status_text.text("Processing...")
509
-
510
  ydl_opts['progress_hooks'] = [progress_hook]
511
 
512
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
513
- # First extract info to verify video is accessible
514
- info = ydl.extract_info(url, download=False)
515
- if info:
516
- # Then proceed with download
517
- info = ydl.extract_info(url, download=True)
518
- filename = ydl.prepare_filename(info)
519
- return filename
520
-
521
- except yt_dlp.utils.DownloadError as e:
522
- if "Sign in to confirm you're not a bot" in str(e):
523
- st.error("❌ YouTube is requesting verification. Please try again later or try a different video.")
524
- else:
525
- st.error(f"❌ Download error: {str(e)}")
526
- return None
527
  except Exception as e:
528
- st.error(f"❌ An error occurred: {str(e)}")
529
  return None
530
 
531
  # Download button
@@ -533,28 +376,19 @@ if st.button("Download"):
533
  if video_url:
534
  try:
535
  with st.spinner("Preparing download..."):
536
- downloaded_file_path = download_video(video_url, format_option)
537
 
538
  if downloaded_file_path and os.path.exists(downloaded_file_path):
539
- # Get file size
540
- file_size = os.path.getsize(downloaded_file_path) / (1024 * 1024) # Convert to MB
541
-
542
  with open(downloaded_file_path, 'rb') as file:
543
  st.download_button(
544
- label=f"Download ({file_size:.1f} MB)",
545
  data=file,
546
  file_name=os.path.basename(downloaded_file_path),
547
  mime="application/octet-stream"
548
  )
549
  st.success("βœ… Download ready!")
550
-
551
- # Clean up downloaded file after successful download
552
- try:
553
- os.remove(downloaded_file_path)
554
- except:
555
- pass
556
  else:
557
- st.error("❌ Download failed. Please try a different video or quality setting.")
558
  except Exception as e:
559
  st.error(f"❌ An error occurred: {str(e)}")
560
  else:
@@ -563,17 +397,183 @@ if st.button("Download"):
563
  # Help section
564
  with st.expander("ℹ️ Help & Information"):
565
  st.markdown("""
566
- **Features:**
567
- - Multiple quality options available
568
- - Supports both video and audio-only downloads
569
- - Automatic format selection based on availability
570
 
571
  **If downloads fail:**
572
- 1. Try a lower quality setting
573
- 2. Verify the video is publicly available
574
- 3. Check your internet connection
575
- 4. Wait a few minutes and try again
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
 
577
- **Note:**
578
- This app respects YouTube's terms of service and is intended for downloading videos that are freely available and permitted to be downloaded.
579
- """)
 
300
  # """)
301
 
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  import streamlit as st
304
  import yt_dlp
305
  import os
 
315
  output_dir = Path("downloads")
316
  output_dir.mkdir(exist_ok=True)
317
 
318
+ # Check if cookies file exists
319
+ COOKIES_FILE = 'youtube.com_cookies.txt'
320
+ has_cookies = os.path.exists(COOKIES_FILE)
321
+
322
+ if has_cookies:
323
+ st.success("βœ… Cookie file detected")
324
+ else:
325
+ st.warning("⚠️ No cookie file found - Some videos might be restricted")
326
+
327
  # Input field for YouTube video URL
328
  video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
329
 
330
+ def download_video(url):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  try:
 
332
  ydl_opts = {
333
+ 'format': 'bestvideo+bestaudio/best',
334
  'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
335
+ 'merge_output_format': 'webm',
336
  'quiet': True,
337
  'no_warnings': True,
338
+ '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',
339
+ 'referer': 'https://www.youtube.com/',
340
+ 'http_chunk_size': 10485760
 
 
 
 
 
 
 
 
 
 
 
341
  }
342
+
343
+ # Add cookies file if available
344
+ if has_cookies:
345
+ ydl_opts['cookiefile'] = COOKIES_FILE
346
+
347
+ # Progress placeholder
348
  progress_bar = st.progress(0)
349
  status_text = st.empty()
350
 
 
355
  progress_bar.progress(progress)
356
  status_text.text(f"Downloading: {progress:.1%}")
357
  except:
358
+ status_text.text("Downloading... (size unknown)")
 
 
 
 
359
  elif d['status'] == 'finished':
360
  progress_bar.progress(1.0)
361
  status_text.text("Processing...")
362
+
363
  ydl_opts['progress_hooks'] = [progress_hook]
364
 
365
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
366
+ info = ydl.extract_info(url, download=True)
367
+ filename = ydl.prepare_filename(info)
368
+ return filename
369
+
 
 
 
 
 
 
 
 
 
 
370
  except Exception as e:
371
+ st.error(f"An error occurred: {str(e)}")
372
  return None
373
 
374
  # Download button
 
376
  if video_url:
377
  try:
378
  with st.spinner("Preparing download..."):
379
+ downloaded_file_path = download_video(video_url)
380
 
381
  if downloaded_file_path and os.path.exists(downloaded_file_path):
 
 
 
382
  with open(downloaded_file_path, 'rb') as file:
383
  st.download_button(
384
+ label="Click here to download",
385
  data=file,
386
  file_name=os.path.basename(downloaded_file_path),
387
  mime="application/octet-stream"
388
  )
389
  st.success("βœ… Download ready!")
 
 
 
 
 
 
390
  else:
391
+ st.error("❌ Download failed. Please try again.")
392
  except Exception as e:
393
  st.error(f"❌ An error occurred: {str(e)}")
394
  else:
 
397
  # Help section
398
  with st.expander("ℹ️ Help & Information"):
399
  st.markdown("""
400
+ **About Cookie Authentication:**
401
+ - This app uses cookie authentication to bypass YouTube's bot detection
402
+ - Cookies help the app behave like a logged-in browser
403
+ - No personal data is stored or transmitted
404
 
405
  **If downloads fail:**
406
+ 1. Check if the video is public
407
+ 2. Verify the URL is correct
408
+ 3. Try a different video
409
+ 4. Try again later if YouTube is blocking requests
410
+ """)
411
+
412
+
413
+ # import streamlit as st
414
+ # import yt_dlp
415
+ # import os
416
+ # from pathlib import Path
417
+
418
+ # # Set page config
419
+ # st.set_page_config(page_title="YouTube Video Downloader", page_icon="πŸ“Ί")
420
+
421
+ # # Set the title of the app
422
+ # st.title("YouTube Video Downloader πŸ“Ί")
423
+
424
+ # # Create output directory if it doesn't exist
425
+ # output_dir = Path("downloads")
426
+ # output_dir.mkdir(exist_ok=True)
427
+
428
+ # # Input field for YouTube video URL
429
+ # video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
430
+
431
+ # # Format selection
432
+ # format_option = st.selectbox(
433
+ # "Select Quality",
434
+ # ["Best Quality", "720p", "480p", "360p", "Audio Only"]
435
+ # )
436
+
437
+ # def get_format_options(format_choice):
438
+ # if format_choice == "Best Quality":
439
+ # return {
440
+ # 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
441
+ # 'merge_output_format': 'mp4'
442
+ # }
443
+ # elif format_choice == "720p":
444
+ # return {
445
+ # 'format': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
446
+ # 'merge_output_format': 'mp4'
447
+ # }
448
+ # elif format_choice == "480p":
449
+ # return {
450
+ # 'format': 'bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]/best',
451
+ # 'merge_output_format': 'mp4'
452
+ # }
453
+ # elif format_choice == "360p":
454
+ # return {
455
+ # 'format': 'bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360][ext=mp4]/best',
456
+ # 'merge_output_format': 'mp4'
457
+ # }
458
+ # else: # Audio Only
459
+ # return {
460
+ # 'format': 'bestaudio[ext=m4a]/best',
461
+ # 'merge_output_format': 'm4a'
462
+ # }
463
+
464
+ # def download_video(url, format_choice):
465
+ # try:
466
+ # # Base options
467
+ # ydl_opts = {
468
+ # 'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
469
+ # 'quiet': True,
470
+ # 'no_warnings': True,
471
+ # 'extract_flat': False,
472
+ # 'no_color': True,
473
+ # # Advanced options to help avoid detection
474
+ # 'socket_timeout': 30,
475
+ # 'retries': 3,
476
+ # 'ignoreerrors': True,
477
+ # 'nocheckcertificate': True,
478
+ # # Modern browser headers
479
+ # 'headers': {
480
+ # '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',
481
+ # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
482
+ # 'Accept-Language': 'en-us,en;q=0.5',
483
+ # 'Sec-Fetch-Mode': 'navigate',
484
+ # }
485
+ # }
486
+
487
+ # # Add format-specific options
488
+ # ydl_opts.update(get_format_options(format_choice))
489
+
490
+ # # Progress tracking
491
+ # progress_bar = st.progress(0)
492
+ # status_text = st.empty()
493
+
494
+ # def progress_hook(d):
495
+ # if d['status'] == 'downloading':
496
+ # try:
497
+ # progress = d['downloaded_bytes'] / d['total_bytes']
498
+ # progress_bar.progress(progress)
499
+ # status_text.text(f"Downloading: {progress:.1%}")
500
+ # except:
501
+ # progress = -1
502
+ # if 'downloaded_bytes' in d:
503
+ # status_text.text(f"Downloading... ({d['downloaded_bytes'] / 1024 / 1024:.1f} MB)")
504
+ # else:
505
+ # status_text.text("Downloading... (size unknown)")
506
+ # elif d['status'] == 'finished':
507
+ # progress_bar.progress(1.0)
508
+ # status_text.text("Processing...")
509
+
510
+ # ydl_opts['progress_hooks'] = [progress_hook]
511
+
512
+ # with yt_dlp.YoutubeDL(ydl_opts) as ydl:
513
+ # # First extract info to verify video is accessible
514
+ # info = ydl.extract_info(url, download=False)
515
+ # if info:
516
+ # # Then proceed with download
517
+ # info = ydl.extract_info(url, download=True)
518
+ # filename = ydl.prepare_filename(info)
519
+ # return filename
520
+
521
+ # except yt_dlp.utils.DownloadError as e:
522
+ # if "Sign in to confirm you're not a bot" in str(e):
523
+ # st.error("❌ YouTube is requesting verification. Please try again later or try a different video.")
524
+ # else:
525
+ # st.error(f"❌ Download error: {str(e)}")
526
+ # return None
527
+ # except Exception as e:
528
+ # st.error(f"❌ An error occurred: {str(e)}")
529
+ # return None
530
+
531
+ # # Download button
532
+ # if st.button("Download"):
533
+ # if video_url:
534
+ # try:
535
+ # with st.spinner("Preparing download..."):
536
+ # downloaded_file_path = download_video(video_url, format_option)
537
+
538
+ # if downloaded_file_path and os.path.exists(downloaded_file_path):
539
+ # # Get file size
540
+ # file_size = os.path.getsize(downloaded_file_path) / (1024 * 1024) # Convert to MB
541
+
542
+ # with open(downloaded_file_path, 'rb') as file:
543
+ # st.download_button(
544
+ # label=f"Download ({file_size:.1f} MB)",
545
+ # data=file,
546
+ # file_name=os.path.basename(downloaded_file_path),
547
+ # mime="application/octet-stream"
548
+ # )
549
+ # st.success("βœ… Download ready!")
550
+
551
+ # # Clean up downloaded file after successful download
552
+ # try:
553
+ # os.remove(downloaded_file_path)
554
+ # except:
555
+ # pass
556
+ # else:
557
+ # st.error("❌ Download failed. Please try a different video or quality setting.")
558
+ # except Exception as e:
559
+ # st.error(f"❌ An error occurred: {str(e)}")
560
+ # else:
561
+ # st.warning("⚠️ Please enter a valid YouTube URL.")
562
+
563
+ # # Help section
564
+ # with st.expander("ℹ️ Help & Information"):
565
+ # st.markdown("""
566
+ # **Features:**
567
+ # - Multiple quality options available
568
+ # - Supports both video and audio-only downloads
569
+ # - Automatic format selection based on availability
570
+
571
+ # **If downloads fail:**
572
+ # 1. Try a lower quality setting
573
+ # 2. Verify the video is publicly available
574
+ # 3. Check your internet connection
575
+ # 4. Wait a few minutes and try again
576
 
577
+ # **Note:**
578
+ # This app respects YouTube's terms of service and is intended for downloading videos that are freely available and permitted to be downloaded.
579
+ # """)