youngtsai commited on
Commit
aad76cf
·
1 Parent(s): ff03c35

get_youtube_title_from_gemini

Browse files
Files changed (1) hide show
  1. app.py +57 -10
app.py CHANGED
@@ -37,6 +37,39 @@ def mock_summary():
37
  # 假資料模擬摘要
38
  return "這份文件主要討論人工智慧在工作效率提升方面的應用,並提供了實際案例來說明其價值。"
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def get_youtube_title(url):
41
  """獲取 YouTube 影片標題"""
42
  try:
@@ -47,18 +80,32 @@ def get_youtube_title(url):
47
  else:
48
  url = f'https://www.youtube.com/watch?v={url}'
49
 
50
- ydl_opts = {
51
- 'quiet': True,
52
- 'no_warnings': True,
53
- 'extract_flat': True
54
- }
55
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
56
- info = ydl.extract_info(url, download=False)
57
- title = info.get('title', url)
58
- print(f"YouTube title: {title}")
 
 
 
 
 
 
 
 
 
 
 
 
59
  return title
 
 
60
  except Exception as e:
61
- print(f"Error fetching YouTube title: {str(e)}")
62
  return url
63
 
64
  def add_to_file_list(file, file_list):
 
37
  # 假資料模擬摘要
38
  return "這份文件主要討論人工智慧在工作效率提升方面的應用,並提供了實際案例來說明其價值。"
39
 
40
+ def get_youtube_title_from_gemini(url):
41
+ """使用 Gemini 獲取 YouTube 標題"""
42
+ print(f"\n開始獲取 YouTube 標題: {url}")
43
+ try:
44
+ print("初始化 Gemini 模型設定...")
45
+ video = types.Part.from_uri(
46
+ file_uri=url,
47
+ mime_type="video/*",
48
+ )
49
+
50
+ print("開始生成標題...")
51
+ response = GENAI_CLIENT.models.generate_content(
52
+ model="gemini-2.0-flash-exp",
53
+ contents=[
54
+ types.Content(
55
+ role="user",
56
+ parts=[
57
+ video,
58
+ types.Part.from_text("請只回傳這個影片的標題,不要加入其他任何文字。")
59
+ ]
60
+ )
61
+ ]
62
+ )
63
+
64
+ if response and response.text:
65
+ title = response.text.strip()
66
+ print(f"成功獲取標題: {title}")
67
+ return title
68
+ return url
69
+ except Exception as e:
70
+ print(f"Gemini 獲取標題失敗: {str(e)}")
71
+ return url
72
+
73
  def get_youtube_title(url):
74
  """獲取 YouTube 影片標題"""
75
  try:
 
80
  else:
81
  url = f'https://www.youtube.com/watch?v={url}'
82
 
83
+ # 首先嘗試使用 yt-dlp
84
+ try:
85
+ ydl_opts = {
86
+ 'quiet': True,
87
+ 'no_warnings': True,
88
+ 'extract_flat': True
89
+ }
90
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
91
+ info = ydl.extract_info(url, download=False)
92
+ title = info.get('title', '')
93
+ if title:
94
+ print(f"YouTube title from yt-dlp: {title}")
95
+ return title
96
+ except Exception as e:
97
+ print(f"yt-dlp 獲取標題失敗: {str(e)}")
98
+
99
+ # 如果 yt-dlp 失敗,嘗試使用 Gemini
100
+ print("嘗試使用 Gemini 獲取標題...")
101
+ title = get_youtube_title_from_gemini(url)
102
+ if title and title != url:
103
+ print(f"YouTube title from Gemini: {title}")
104
  return title
105
+
106
+ return url
107
  except Exception as e:
108
+ print(f"獲取標題失敗: {str(e)}")
109
  return url
110
 
111
  def add_to_file_list(file, file_list):