返回提交历史
Added
g4f/Provider/YouTube.py
+126
-0
Modified
g4f/Provider/__init__.py
+1
-0
Modified
g4f/Provider/needs_auth/Video.py
+8
-0
Modified
g4f/api/__init__.py
+1
-1
Modified
g4f/requests/__init__.py
+2
-0
XFEstudio/gpt4free
Add YouTube provider
c718011c
代码差异
5 个文件
+138
-1
@@ -0,0 +1,126 @@
1
from __future__ import annotations
2
3
import os
4
5
try:
6
import yt_dlp
7
has_yt_dlp = True
8
except ImportError:
9
has_yt_dlp = False
10
11
from ..typing import AsyncResult, Messages
12
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
13
from ..providers.response import AudioResponse, VideoResponse
14
from ..image.copy_images import get_media_dir
15
from .helper import format_media_prompt
16
17
class YouTube(AsyncGeneratorProvider, ProviderModelMixin):
18
url = "https://youtube.com"
19
working = has_yt_dlp
20
use_nodriver = True
21
22
@classmethod
23
async def create_async_generator(
24
cls,
25
model: str,
26
messages: Messages,
27
prompt: str = None,
28
**kwargs
29
) -> AsyncResult:
30
prompt = format_media_prompt(messages, prompt)
31
provider = YouTubeProvider()
32
results = await provider.search(prompt, max_results=1)
33
if results:
34
video_url = results[0]['url']
35
path = await provider.download(video_url, model="mp3", output_dir=get_media_dir())
36
if path.endswith('.mp3'):
37
yield AudioResponse(f"/media/{os.path.basename(path)}")
38
else:
39
yield VideoResponse(f"/media/{os.path.basename(path)}", prompt)
40
41
class YouTubeProvider:
42
"""
43
Search and download YouTube videos.
44
45
model: "mp3" for audio only, or "high-definition" for best video
46
"""
47
48
def __init__(self):
49
pass
50
51
async def search(self, query: str, max_results: int = 5) -> list[dict]:
52
"""
53
Search YouTube for videos matching the query.
54
55
Returns a list of dicts with keys: title, url, id, duration
56
"""
57
ydl_opts = {
58
'quiet': True,
59
'extract_flat': True,
60
'skip_download': True,
61
}
62
search_url = f"ytsearch{max_results}:{query}"
63
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
64
info = ydl.extract_info(search_url, download=False)
65
results = []
66
for entry in info.get('entries', []):
67
results.append({
68
'title': entry.get('title'),
69
'url': f"https://www.youtube.com/watch?v={entry.get('id')}",
70
'id': entry.get('id'),
71
'duration': entry.get('duration'),
72
})
73
return results
74
75
async def download(self, video_url: str, model: str = "high-definition", output_dir: str = ".") -> str:
76
"""
77
Download a YouTube video.
78
79
:param video_url: The video URL or video id
80
:param model: "mp3" for audio, "high-definition" for best video
81
:param output_dir: Download location
82
:return: The path to the downloaded file
83
"""
84
ydl_opts = {
85
'outtmpl': f"{output_dir}/%(title)s.%(ext)s",
86
'quiet': True,
87
}
88
if model == "mp3":
89
# Audio only, best quality
90
ydl_opts.update({
91
'format': 'bestaudio/best',
92
'postprocessors': [{
93
'key': 'FFmpegExtractAudio',
94
'preferredcodec': 'mp3',
95
'preferredquality': '192'
96
}]
97
})
98
elif model == "high-definition":
99
# Best video+audio
100
ydl_opts.update({
101
'format': 'bestvideo+bestaudio/best',
102
'merge_output_format': 'mp4',
103
})
104
else:
105
raise ValueError("model must be 'mp3' or 'high-definition'")
106
107
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
108
result = ydl.download([video_url])
109
return ydl.prepare_filename(ydl.extract_info(video_url, download=True)).replace('.webm', '.mp3')
110
# You can get actual file path via ydl.prepare_filename
111
# This is a simplified return - usually, you would parse the output or check the directory
112
return output_dir
113
114
# Example usage (async function to test)
115
116
async def demo():
117
provider = YouTubeProvider()
118
results = await provider.search("Python programming", max_results=2)
119
print("Search results:", results)
120
if results:
121
video_url = results[0]['url']
122
path = await provider.download(video_url, model="mp3")
123
print("Downloaded to:", path)
124
125
# To actually run demo()
126
# asyncio.run(demo())
@@ -53,6 +53,7 @@ from .Startnest import Startnest
53
53
from .TeachAnything import TeachAnything
54
54
from .Together import Together
55
55
from .WeWordle import WeWordle
56
from .YouTube import YouTube
56
57
from .Yqcloud import Yqcloud
57
58
58
59
import sys
@@ -131,7 +131,15 @@ class Video(AsyncGeneratorProvider, ProviderModelMixin):
131
131
for _, urls in RequestConfig.urls.items():
132
132
if event.request.url in urls:
133
133
return
134
debug.log(f"Adding URL: {event.request.url}")
134
135
RequestConfig.urls[prompt].append(event.request.url)
136
for idx in range(300):
137
button = await page.find("User menu")
138
if button:
139
break
140
if idx == 299:
141
stop_browser()
142
raise RuntimeError("Failed to wait for user menu.")
135
143
if model == "search" and page is not None:
136
144
await page.send(nodriver.cdp.network.enable())
137
145
page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
@@ -758,7 +758,7 @@ class Api:
758
758
if m:
759
759
return int(m.group(0))
760
760
else:
761
raise ValueError("No timestamp found in filename")
761
return 0
762
762
target = os.path.join(get_media_dir(), os.path.basename(filename))
763
763
if thumbnail and has_pillow:
764
764
thumbnail_dir = os.path.join(get_media_dir(), "thumbnails")
@@ -208,6 +208,8 @@ async def get_nodriver(
208
208
try:
209
209
if browser.connection:
210
210
browser.stop()
211
except:
212
pass
211
213
finally:
212
214
lock_file.unlink(missing_ok=True)
213
215
BrowserConfig.stop_browser = on_stop