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

XFEstudio/gpt4free

Add share auth for EasyChat

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

代码差异

2 个文件 +53 -28
Modified g4f/Provider/EasyChat.py +40 -13
@@ -1,6 +1,8 @@
1 1 from __future__ import annotations
2 2
3 import os
3 4 import asyncio
5 import requests
4 6 import json
5 7 try:
6 8 import nodriver
@@ -12,6 +14,7 @@ from ..config import DEFAULT_MODEL
12 14 from ..requests import get_args_from_nodriver
13 15 from ..providers.base_provider import AuthFileMixin
14 16 from .template import OpenaiTemplate
17 from .helper import get_last_user_message
15 18 from .. import debug
16 19
17 20 class EasyChat(OpenaiTemplate, AuthFileMixin):
@@ -24,10 +27,12 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
24 27
25 28 default_model = DEFAULT_MODEL.split("/")[-1]
26 29 model_aliases = {
27 DEFAULT_MODEL: default_model,
30 DEFAULT_MODEL: f"{default_model}-free",
28 31 }
29 32
30 captchaToken: dict = None
33 captchaToken: str = None
34 share_url: str = None
35 looked: bool = False
31 36
32 37 @classmethod
33 38 def get_models(cls, **kwargs) -> list[str]:
@@ -47,15 +52,10 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
47 52 extra_body: dict = None,
48 53 **kwargs
49 54 ) -> AsyncResult:
55 cls.share_url = os.getenv("G4F_SHARE_URL")
50 56 model = cls.get_model(model)
51 57 args = None
52 auth_file = cls.get_cache_file()
53 if auth_file.exists():
54 with auth_file.open("r") as f:
55 args = json.load(f)
56 cls.captchaToken = args.pop("captchaToken")
57 if cls.captchaToken:
58 debug.log("EasyChat: Using cached captchaToken.")
58 cache_file = cls.get_cache_file()
59 59 async def callback(page):
60 60 cls.captchaToken = None
61 61 def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):
@@ -92,6 +92,28 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
92 92 if cls.captchaToken:
93 93 break
94 94 await asyncio.sleep(3)
95 if cache_file.exists():
96 with cache_file.open("r") as f:
97 args = json.load(f)
98 cls.captchaToken = args.pop("captchaToken")
99 if cls.captchaToken:
100 debug.log("EasyChat: Using cached captchaToken.")
101 elif not cls.looked and cls.share_url:
102 cls.looked = True
103 debug.log("No cache file found, trying to fetch from fallback URL.")
104 response = requests.get(cls.share_url, params={
105 "prompt": get_last_user_message(messages),
106 "model": model,
107 "provider": cls.__name__
108 })
109 text, *sub = response.text.split("\n" * 10 + "<!--", 1)
110 if sub:
111 debug.log("Save args to cache file:", str(cache_file))
112 with cache_file.open("w") as f:
113 f.write(sub[0].strip())
114 yield text
115 cls.looked = False
116 return
95 117 for _ in range(2):
96 118 if not args:
97 119 args = await get_args_from_nodriver(cls.url, proxy=proxy, callback=callback)
@@ -104,7 +126,8 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
104 126 model=model,
105 127 messages=messages,
106 128 extra_body=extra_body,
107 **args
129 **args,
130 **kwargs
108 131 ):
109 132 # Remove provided by
110 133 if last_chunk == "\n" and chunk == "\n":
@@ -113,12 +136,16 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
113 136 yield chunk
114 137 except Exception as e:
115 138 if "CLEAR-CAPTCHA-TOKEN" in str(e):
116 debug.log("EasyChat: Captcha token expired, clearing auth file.")
117 auth_file.unlink(missing_ok=True)
139 debug.log("EasyChat: Captcha token expired, clearing cache file.")
140 cache_file.unlink(missing_ok=True)
118 141 args = None
119 142 continue
120 143 raise e
121 144 break
122 with auth_file.open("w") as f:
145 if os.getenv("G4F_SHARE_AUTH"):
146 yield "\n" * 10
147 yield "<!--"
148 yield json.dumps({**args, "captchaToken": cls.captchaToken})
149 with cache_file.open("w") as f:
123 150 json.dump({**args, "captchaToken": cls.captchaToken}, f)
124 151
Modified g4f/Provider/needs_auth/LMArenaBeta.py +13 -15
@@ -6,7 +6,6 @@ import json
6 6 import asyncio
7 7 import os
8 8 import requests
9 from pathlib import Path
10 9
11 10 from ...typing import AsyncResult, Messages, MediaListType
12 11 from ...requests import StreamSession, get_args_from_nodriver, raise_for_status, merge_cookies, has_nodriver
@@ -122,7 +121,7 @@ vision_models = [model["publicName"] for model in models if "image" in model["ca
122 121 class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
123 122 label = "LMArena (New)"
124 123 url = "https://lmarena.ai"
125 fallback_url = None
124 share_url = None
126 125 api_endpoint = "https://lmarena.ai/api/stream/create-evaluation"
127 126 working = True
128 127 active_by_default = True
@@ -147,13 +146,13 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
147 146 timeout: int = None,
148 147 **kwargs
149 148 ) -> AsyncResult:
150 cls.fallback_url = os.getenv("LMARENA_FALLBACK_URL")
149 cls.share_url = os.getenv("G4F_SHARE_URL")
151 150 prompt = get_last_user_message(messages)
152 151 cache_file = cls.get_cache_file()
153 152 if cache_file.exists() and cache_file.stat().st_mtime > time.time() - 60 * 30:
154 153 with cache_file.open("r") as f:
155 154 args = json.load(f)
156 elif has_nodriver or cls.fallback_url is None:
155 elif has_nodriver or cls.share_url is None:
157 156 async def callback(page):
158 157 button = await page.find("Accept Cookies")
159 158 if button:
@@ -163,19 +162,19 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
163 162 if not await page.evaluate('document.cookie.indexOf("arena-auth-prod-v1") >= 0'):
164 163 debug.log("No authentication cookie found, trying to authenticate.")
165 164 await page.select('#cf-turnstile', 300)
166 debug.log("Found:'#cf-turnstile'")
165 debug.log("Found Element: 'cf-turnstile'")
167 166 await asyncio.sleep(3)
168 167 for _ in range(3):
169 168 size = None
170 169 for idx in range(15):
171 170 size = await page.js_dumps('document.getElementById("cf-turnstile")?.getBoundingClientRect()||{}')
172 171 debug.log("Found size:", {size.get("x"), size.get("y")})
173 if "x" not in size or "y" not in size:
172 if "x" not in size:
174 173 break
175 174 await page.flash_point(size.get("x") + idx * 2, size.get("y") + idx * 2)
176 175 await page.mouse_click(size.get("x") + idx * 2, size.get("y") + idx * 2)
177 176 await asyncio.sleep(1)
178 if "x" not in size or "y" not in size:
177 if "x" not in size:
179 178 break
180 179 debug.log("Clicked on the turnstile.")
181 180 while not await page.evaluate('document.cookie.indexOf("arena-auth-prod-v1") >= 0'):
@@ -183,21 +182,21 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
183 182 while not await page.evaluate('document.querySelector(\'textarea\')'):
184 183 await asyncio.sleep(1)
185 184 args = await get_args_from_nodriver(cls.url, proxy=proxy, callback=callback)
186 else:
185 elif not cls.looked:
187 186 cls.looked = True
188 187 debug.log("No cache file found, trying to fetch from fallback URL.")
189 response = requests.get(cls.fallback_url, params={
188 response = requests.get(cls.share_url, params={
190 189 "prompt": prompt,
191 "stream": True,
192 190 "model": model,
193 191 "provider": cls.__name__
194 192 })
195 _, args = response.text.split("\n" * 10 + "<!--", 1)
193 text, *args = response.text.split("\n" * 10 + "<!--", 1)
196 194 if args:
197 195 debug.log("Save args to cache file:", str(cache_file))
198 196 with cache_file.open("w") as f:
199 f.write(args.strip())
200 yield response.text
197 f.write(args[0].strip())
198 yield text
199 cls.looked = False
201 200 return
202 201
203 202 # Build the JSON payload
@@ -286,11 +285,10 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
286 285 yield FinishReason(finish["finishReason"])
287 286 if "usage" in finish:
288 287 yield Usage(**finish["usage"])
289 if os.getenv("LMAREANA_SHARE_AUTH"):
288 if os.getenv("G4F_SHARE_AUTH"):
290 289 yield "\n" * 10
291 290 yield "<!--"
292 291 yield json.dumps(args)
293 cls.looked = False
294 292 # Save the args to cache file
295 293 with cache_file.open("w") as f:
296 294 json.dump(args, f)