codelion commited on
Commit
d3f132f
·
verified ·
1 Parent(s): 16f0b30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -12
app.py CHANGED
@@ -4,11 +4,11 @@ import tempfile
4
  import requests
5
  import gradio as gr
6
  import cv2
7
- from pytube import YouTube
8
  from google import genai
9
  from google.genai import types
10
  from google.genai.types import Part
11
  from tenacity import retry, stop_after_attempt, wait_random_exponential
 
12
 
13
  # Retrieve API key from environment variables.
14
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
@@ -51,21 +51,23 @@ def hhmmss_to_seconds(time_str: str) -> float:
51
 
52
  def download_video(video_url: str) -> str:
53
  """
54
- Download the video from a URL (either YouTube or direct link) and return the local file path.
 
 
55
  """
56
  local_file = None
57
  if "youtube.com" in video_url or "youtu.be" in video_url:
58
- yt = YouTube(video_url)
59
- stream = yt.streams.filter(file_extension="mp4", progressive=True).first()
60
- if stream is None:
61
- raise ValueError("No suitable mp4 stream found on YouTube.")
62
- temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
63
- stream.stream_to_buffer(temp_file)
64
- temp_file.flush()
65
- local_file = temp_file.name
66
- temp_file.close()
67
  else:
68
- # Assume it's a direct link to a video file, download using requests.
69
  response = requests.get(video_url, stream=True)
70
  if response.status_code == 200:
71
  temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
 
4
  import requests
5
  import gradio as gr
6
  import cv2
 
7
  from google import genai
8
  from google.genai import types
9
  from google.genai.types import Part
10
  from tenacity import retry, stop_after_attempt, wait_random_exponential
11
+ import yt_dlp # Use yt-dlp for robust YouTube downloading
12
 
13
  # Retrieve API key from environment variables.
14
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
 
51
 
52
  def download_video(video_url: str) -> str:
53
  """
54
+ Download the video from a URL. If it's a YouTube URL, use yt-dlp;
55
+ otherwise, use requests for direct links.
56
+ Returns the local file path.
57
  """
58
  local_file = None
59
  if "youtube.com" in video_url or "youtu.be" in video_url:
60
+ ydl_opts = {
61
+ 'format': 'mp4',
62
+ 'outtmpl': '%(id)s.%(ext)s',
63
+ 'noplaylist': True,
64
+ 'quiet': True,
65
+ }
66
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
67
+ info = ydl.extract_info(video_url, download=True)
68
+ local_file = ydl.prepare_filename(info)
69
  else:
70
+ # Assume it's a direct link to a video file.
71
  response = requests.get(video_url, stream=True)
72
  if response.status_code == 200:
73
  temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)