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

XFEstudio/gpt4free

fix(provider): bypass Turnstile Captcha for DeepInfra using DrissionPage (#3453)

8973f4b3
kqlio67 <kqlio67@users.noreply.github.com>
提交于

代码差异

1 个文件 +71 -0
Modified g4f/Provider/DeepInfra.py +71 -0
@@ -1,10 +1,75 @@
1 1 from __future__ import annotations
2 2
3 import time
3 4 import requests
4 5
5 6 from ..typing import Messages, AsyncResult
6 7 from .template import OpenaiTemplate
7 8
9 def get_turnstile_token() -> str:
10 """
11 Opens the DeepInfra page using DrissionPage to obtain a Turnstile token.
12 Raises MissingRequirementsError if DrissionPage is not installed.
13 """
14 try:
15 from DrissionPage import ChromiumPage, ChromiumOptions
16 except ImportError:
17 from ..errors import MissingRequirementsError
18 raise MissingRequirementsError('Install "DrissionPage" package to use DeepInfra without an API key | pip install DrissionPage')
19
20 co = ChromiumOptions()
21 # Hide the window off-screen
22 co.set_argument('--window-position=-2000,-2000')
23 co.set_argument('--window-size=800,600')
24 co.set_argument('--log-level=3')
25
26 page = ChromiumPage(co)
27
28 try:
29 # Generate a token on any model's page; it is valid for the entire domain
30 page.get('https://deepinfra.com/zai-org/GLM-5.2')
31
32 # Inject JS to block the original request
33 js_block_fetch = """
34 const origFetch = window.fetch;
35 window.fetch = async function(...args) {
36 let url = args[0];
37 if (typeof url === 'string' && url.includes('/chat/completions')) {
38 return new Response('{}', {status: 200});
39 }
40 return origFetch.apply(this, args);
41 };
42 """
43 page.run_js(js_block_fetch)
44
45 # Initiate Turnstile
46 textarea = page.ele('tag:textarea', timeout=15)
47 if not textarea:
48 return ""
49
50 textarea.input('Test')
51 textarea.input('\n')
52
53 # Wait for the challenge to be solved
54 token_input = page.ele('@name=cf-turnstile-response', timeout=20)
55
56 if not token_input:
57 return ""
58
59 token = ""
60 for _ in range(40):
61 token = token_input.attr('value')
62 if token:
63 break
64 time.sleep(0.5)
65
66 return token
67 finally:
68 try:
69 page.quit()
70 except:
71 pass
72
8 73 class DeepInfra(OpenaiTemplate):
9 74 url = "https://deepinfra.com"
10 75 login_url = "https://deepinfra.com/dash/api_keys"
@@ -36,4 +101,10 @@ class DeepInfra(OpenaiTemplate):
36 101 headers["X-Deepinfra-Source"] = "model-embed"
37 102 headers["Origin"] = "https://deepinfra.com"
38 103 headers["Referer"] = "https://deepinfra.com/"
104
105 # Generate a Turnstile token for each request (required without an API key)
106 token = get_turnstile_token()
107 if token:
108 headers["X-DeepInfra-Turnstile"] = token
109
39 110 return headers