XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/gpt4free

Update Video API

0d8234bc
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

2 个文件 +40 -11
Modified g4f/Provider/needs_auth/Video.py +23 -10
@@ -13,7 +13,7 @@ except:
13 13 pass
14 14
15 15 from ...typing import Messages, AsyncResult
16 from ...providers.response import VideoResponse
16 from ...providers.response import VideoResponse, Reasoning
17 17 from ...requests import get_nodriver
18 18 from ...errors import MissingRequirementsError
19 19 from ..base_provider import AsyncGeneratorProvider
@@ -57,14 +57,18 @@ class Video(AsyncGeneratorProvider):
57 57 except Exception as e:
58 58 debug.error(f"Error getting nodriver:", e)
59 59 async with ClientSession() as session:
60 yield Reasoning(label="Lookup")
60 61 async with session.get(cls.search_url + quote_plus(prompt) + f"&min={prompt.count(' ') + 1}", timeout=ClientTimeout(total=10)) as response:
61 62 if response.status == 200:
63 yield Reasoning(label="Found", status="")
62 64 yield VideoResponse(str(response.url), prompt)
63 65 return
66 yield Reasoning(label="Generating")
64 67 async with session.post(cls.api_url + quote(prompt)) as response:
65 68 if not response.ok:
66 debug.error(f"Failed to connect to Video API: {response.status}")
69 debug.error(f"Failed to lookup Video: {response.status}")
67 70 else:
71 yield Reasoning(label="Finished", status="")
68 72 if response.headers.get("content-type", "text/plain").startswith("text/plain"):
69 73 data = (await response.text()).split("\n")
70 74 yield VideoResponse([f"{cls.pub_url}{url}" if url.startswith("/") else url for url in data], prompt)
@@ -77,6 +81,13 @@ class Video(AsyncGeneratorProvider):
77 81 cls.page = await browser.get(random.choice(cls.urls))
78 82 except Exception as e:
79 83 debug.error(f"Error opening page:", e)
84 if RequestConfig.urls:
85 RequestConfig.urls = list(set(RequestConfig.urls))
86 debug.log(f"Video URL: {len(RequestConfig.urls)}")
87 yield VideoResponse(RequestConfig.urls, prompt, {
88 "headers": {"authorization": RequestConfig.headers.get("authorization")} if RequestConfig.headers.get("authorization") else {}
89 })
90 return
80 91 try:
81 92 page = cls.page
82 93 await asyncio.sleep(3)
@@ -128,13 +139,16 @@ class Video(AsyncGeneratorProvider):
128 139 await button.click()
129 140 except Exception as e:
130 141 debug.error(f"Error clicking 'Activity' button:", e)
131 try:
132 await asyncio.sleep(15)
133 button = await page.find("Queued", timeout=30)
134 if button:
135 await button.click()
136 except Exception as e:
137 debug.error(f"Error clicking 'Queued' button:", e)
142 for idx in range(60):
143 await asyncio.sleep(1)
144 try:
145 button = await page.find("Queued")
146 if button:
147 await button.click()
148 debug.log(f"Clicked 'Queued' button")
149 break
150 except:
151 debug.error(f"Error clicking 'Queued' button:", e)
138 152 debug.log(f"Waiting for Video URL...")
139 153 for idx in range(600):
140 154 await asyncio.sleep(1)
@@ -145,7 +159,6 @@ class Video(AsyncGeneratorProvider):
145 159 yield VideoResponse(RequestConfig.urls, prompt, {
146 160 "headers": {"authorization": RequestConfig.headers.get("authorization")} if RequestConfig.headers.get("authorization") else {}
147 161 })
148 RequestConfig.urls = []
149 162 break
150 163 if idx == 599:
151 164 raise RuntimeError("Failed to get Video URL")
Modified g4f/api/__init__.py +17 -1
@@ -10,6 +10,7 @@ from email.utils import formatdate
10 10 import os.path
11 11 import hashlib
12 12 import asyncio
13 from contextlib import asynccontextmanager
13 14 from urllib.parse import quote_plus
14 15 from fastapi import FastAPI, Response, Request, UploadFile, Form, Depends
15 16 from fastapi.responses import StreamingResponse, RedirectResponse, HTMLResponse, JSONResponse, FileResponse
@@ -48,6 +49,11 @@ try:
48 49 except ImportError:
49 50 class Annotated:
50 51 pass
52 try:
53 from nodriver import util
54 has_nodriver = True
55 except ImportError:
56 has_nodriver = False
51 57
52 58 import g4f
53 59 import g4f.debug
@@ -77,8 +83,18 @@ logger = logging.getLogger(__name__)
77 83
78 84 DEFAULT_PORT = 1337
79 85
86 @asynccontextmanager
87 async def lifespan(app: FastAPI):
88 # Read cookie files if not ignored
89 if not AppConfig.ignore_cookie_files:
90 read_cookie_files()
91 yield
92 for browser in util.get_registered_instances():
93 if browser.connection:
94 browser.stop()
95
80 96 def create_app():
81 app = FastAPI()
97 app = FastAPI(lifespan=lifespan)
82 98
83 99 # Add CORS middleware
84 100 app.add_middleware(