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

XFEstudio/gpt4free

Add GPT 4 support in You, Add camera input, Enable logging on debug in GUI, Don't load expired cookies

6c422b29
Heiner Lohaus <hlohaus@users.noreply.github.com>
提交于

代码差异

7 个文件 +136 -30
Modified g4f/Provider/You.py +63 -3
@@ -1,6 +1,8 @@
1 1 from __future__ import annotations
2 2
3 3 import json
4 import base64
5 import uuid
4 6
5 7 from ..requests import StreamSession
6 8 from ..typing import AsyncGenerator, Messages
@@ -11,7 +13,9 @@ class You(AsyncGeneratorProvider):
11 13 url = "https://you.com"
12 14 working = True
13 15 supports_gpt_35_turbo = True
14
16 supports_gpt_4 = True
17 _session_used = 0
18 _session_token = None
15 19
16 20 @classmethod
17 21 async def create_async_generator(
@@ -27,14 +31,70 @@ class You(AsyncGeneratorProvider):
27 31 "Accept": "text/event-stream",
28 32 "Referer": f"{cls.url}/search?fromSearchBar=true&tbm=youchat",
29 33 }
30 data = {"q": format_prompt(messages), "domain": "youchat", "chat": ""}
34 data = {
35 "q": format_prompt(messages),
36 "domain": "youchat",
37 "chat": "", "selectedChatMode": "gpt-4" if model == "gpt-4" else "default"
38 }
31 39 async with session.get(
32 40 f"{cls.url}/api/streamingSearch",
33 41 params=data,
34 headers=headers
42 headers=headers,
43 cookies=cls.get_cookies(await cls.get_session_token(proxy, timeout)) if model == "gpt-4" else None
35 44 ) as response:
36 45 response.raise_for_status()
37 46 start = b'data: {"youChatToken": '
38 47 async for line in response.iter_lines():
39 48 if line.startswith(start):
40 49 yield json.loads(line[len(start):-1])
50
51 @classmethod
52 async def get_session_token(cls, proxy: str, timeout: int):
53 if not cls._session_token or cls._session_used >= 5:
54 cls._session_token = await cls.create_session_token(proxy, timeout)
55 cls._session_used += 1
56 return cls._session_token
57
58 def get_cookies(access_token: str, session_jwt: str = "0"):
59 return {
60 'stytch_session_jwt': session_jwt,
61 'ydc_stytch_session': access_token,
62 'ydc_stytch_session_jwt': session_jwt
63 }
64
65 @classmethod
66 def get_jwt(cls):
67 return base64.standard_b64encode(json.dumps({
68 "event_id":f"event-id-{str(uuid.uuid4())}",
69 "app_session_id":f"app-session-id-{str(uuid.uuid4())}",
70 "persistent_id":f"persistent-id-{uuid.uuid4()}",
71 "client_sent_at":"","timezone":"",
72 "stytch_user_id":f"user-live-{uuid.uuid4()}",
73 "stytch_session_id":f"session-live-{uuid.uuid4()}",
74 "app":{"identifier":"you.com"},
75 "sdk":{"identifier":"Stytch.js Javascript SDK","version":"3.3.0"
76 }}).encode()).decode()
77
78 @classmethod
79 async def create_session_token(cls, proxy: str, timeout: int):
80 async with StreamSession(proxies={"https": proxy}, impersonate="chrome110", timeout=timeout) as session:
81 user_uuid = str(uuid.uuid4())
82 auth_uuid = "507a52ad-7e69-496b-aee0-1c9863c7c8"
83 auth_token = f"public-token-live-{auth_uuid}bb:public-token-live-{auth_uuid}19"
84 auth = base64.standard_b64encode(auth_token.encode()).decode()
85 async with session.post(
86 "https://web.stytch.com/sdk/v1/passwords",
87 headers={
88 "Authorization": f"Basic {auth}",
89 "X-SDK-Client": cls.get_jwt(),
90 "X-SDK-Parent-Host": "https://you.com"
91 },
92 json={
93 "email": f"{user_uuid}@gmail.com",
94 "password": f"{user_uuid}#{user_uuid}",
95 "session_duration_minutes": 129600
96 }
97 ) as response:
98 if not response.ok:
99 raise RuntimeError(f"Response: {await response.text()}")
100 return (await response.json())["data"]["session_token"]
Modified g4f/cookies.py +3 -1
@@ -1,6 +1,7 @@
1 1 from __future__ import annotations
2 2
3 3 import os
4 import time
4 5
5 6 try:
6 7 from platformdirs import user_config_dir
@@ -72,7 +73,8 @@ def load_cookies_from_browsers(domain_name: str, raise_requirements_error: bool
72 73 print(f"Read cookies from {cookie_fn.__name__} for {domain_name}")
73 74 for cookie in cookie_jar:
74 75 if cookie.name not in cookies:
75 cookies[cookie.name] = cookie.value
76 if not cookie.expires or cookie.expires > time.time():
77 cookies[cookie.name] = cookie.value
76 78 if single_browser and len(cookie_jar):
77 79 break
78 80 except BrowserCookieError:
Modified g4f/gui/__init__.py +3 -0
@@ -7,6 +7,9 @@ except ImportError:
7 7 raise MissingRequirementsError('Install "flask" package for the gui')
8 8
9 9 def run_gui(host: str = '0.0.0.0', port: int = 8080, debug: bool = False) -> None:
10 if debug:
11 import g4f
12 g4f.debug.logging = True
10 13 config = {
11 14 'host' : host,
12 15 'port' : port,
Modified g4f/gui/client/css/style.css +21 -4
@@ -404,7 +404,7 @@ body {
404 404 display: none;
405 405 }
406 406
407 #image, #file {
407 #image, #file, #camera {
408 408 display: none;
409 409 }
410 410
@@ -412,20 +412,37 @@ label[for="image"]:has(> input:valid){
412 412 color: var(--accent);
413 413 }
414 414
415 label[for="camera"]:has(> input:valid){
416 color: var(--accent);
417 }
418
415 419 label[for="file"]:has(> input:valid){
416 420 color: var(--accent);
417 421 }
418 422
419 label[for="image"], label[for="file"] {
423 label[for="image"], label[for="file"], label[for="camera"] {
420 424 cursor: pointer;
421 425 position: absolute;
422 426 top: 10px;
423 427 left: 10px;
424 428 }
425 429
426 label[for="file"] {
430 label[for="image"] {
427 431 top: 32px;
428 left: 10px;
432 }
433
434 label[for="camera"] {
435 top: 54px;
436 }
437
438 label[for="camera"] {
439 display: none;
440 }
441
442 @media (pointer:none), (pointer:coarse) {
443 label[for="camera"] {
444 display: block;
445 }
429 446 }
430 447
431 448 .buttons input[type="checkbox"] {
Modified g4f/gui/client/html/index.html +6 -2
@@ -114,10 +114,14 @@
114 114 <div class="box input-box">
115 115 <textarea id="message-input" placeholder="Ask a question" cols="30" rows="10"
116 116 style="white-space: pre-wrap;resize: none;"></textarea>
117 <label for="image" title="Works only with Bing and OpenaiChat">
118 <input type="file" id="image" name="image" accept="image/png, image/gif, image/jpeg, image/svg+xml" required/>
117 <label for="image" title="Works only with Bing, Gemini and OpenaiChat">
118 <input type="file" id="image" name="image" accept="image/*" required/>
119 119 <i class="fa-regular fa-image"></i>
120 120 </label>
121 <label for="camera">
122 <input type="file" id="camera" name="camera" accept="image/*" capture="camera" required/>
123 <i class="fa-solid fa-camera"></i>
124 </label>
121 125 <label for="file">
122 126 <input type="file" id="file" name="file" accept="text/plain, text/html, text/xml, application/json, text/javascript, .sh, .py, .php, .css, .yaml, .sql, .log, .csv, .twig, .md" required/>
123 127 <i class="fa-solid fa-paperclip"></i>
Modified g4f/gui/client/js/chat.v1.js +33 -18
@@ -8,6 +8,7 @@ const stop_generating = document.querySelector(`.stop_generating`);
8 8 const regenerate = document.querySelector(`.regenerate`);
9 9 const send_button = document.querySelector(`#send-button`);
10 10 const imageInput = document.querySelector('#image');
11 const cameraInput = document.querySelector('#camera');
11 12 const fileInput = document.querySelector('#file');
12 13
13 14 let prompt_lock = false;
@@ -63,6 +64,10 @@ const handle_ask = async () => {
63 64 ? '<img src="' + imageInput.dataset.src + '" alt="Image upload">'
64 65 : ''
65 66 }
67 ${cameraInput.dataset.src
68 ? '<img src="' + cameraInput.dataset.src + '" alt="Image capture">'
69 : ''
70 }
66 71 </div>
67 72 </div>
68 73 `;
@@ -141,9 +146,10 @@ const ask_gpt = async () => {
141 146 const headers = {
142 147 accept: 'text/event-stream'
143 148 }
144 if (imageInput && imageInput.files.length > 0) {
149 const input = imageInput && imageInput.files.length > 0 ? imageInput : cameraInput
150 if (input && input.files.length > 0) {
145 151 const formData = new FormData();
146 formData.append('image', imageInput.files[0]);
152 formData.append('image', input.files[0]);
147 153 formData.append('json', body);
148 154 body = formData;
149 155 } else {
@@ -211,8 +217,11 @@ const ask_gpt = async () => {
211 217 message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
212 218 }
213 219 }
214 if (!error && imageInput) imageInput.value = "";
215 if (!error && fileInput) fileInput.value = "";
220 if (!error) {
221 if (imageInput) imageInput.value = "";
222 if (cameraInput) cameraInput.value = "";
223 if (fileInput) fileInput.value = "";
224 }
216 225 } catch (e) {
217 226 console.error(e);
218 227
@@ -668,21 +677,27 @@ observer.observe(message_input, { attributes: true });
668 677 }
669 678 document.getElementById("version_text").innerHTML = text
670 679 })()
671 imageInput.addEventListener('click', async (event) => {
672 imageInput.value = '';
673 delete imageInput.dataset.src;
674 });
675 imageInput.addEventListener('change', async (event) => {
676 if (imageInput.files.length) {
677 const reader = new FileReader();
678 reader.addEventListener('load', (event) => {
679 imageInput.dataset.src = event.target.result;
680 });
681 reader.readAsDataURL(imageInput.files[0]);
682 } else {
683 delete imageInput.dataset.src;
680 for (el of [imageInput, cameraInput]) {
681 console.log(el.files);
682 el.addEventListener('click', async () => {
683 el.value = '';
684 delete el.dataset.src;
685 });
686 do_load = async () => {
687 if (el.files.length) {
688 delete imageInput.dataset.src;
689 delete cameraInput.dataset.src;
690 const reader = new FileReader();
691 reader.addEventListener('load', (event) => {
692 el.dataset.src = event.target.result;
693 console.log(el.dataset.src);
694 });
695 reader.readAsDataURL(el.files[0]);
696 }
684 697 }
685 });
698 do_load()
699 el.addEventListener('change', do_load);
700 }
686 701 fileInput.addEventListener('click', async (event) => {
687 702 fileInput.value = '';
688 703 delete fileInput.dataset.text;
Modified g4f/gui/server/backend.py +7 -2
@@ -134,25 +134,30 @@ class Backend_Api:
134 134 dict: Arguments prepared for chat completion.
135 135 """
136 136 kwargs = {}
137 if 'image' in request.files:
137 if "image" in request.files:
138 138 file = request.files['image']
139 139 if file.filename != '' and is_allowed_extension(file.filename):
140 140 kwargs['image'] = to_image(file.stream, file.filename.endswith('.svg'))
141 if 'json' in request.form:
141 if "json" in request.form:
142 142 json_data = json.loads(request.form['json'])
143 143 else:
144 144 json_data = request.json
145 145
146 146 provider = json_data.get('provider', '').replace('g4f.Provider.', '')
147 147 provider = provider if provider and provider != "Auto" else None
148
149 if "image" in kwargs and not provider:
150 provider = "Bing"
148 151 if provider == 'OpenaiChat':
149 152 kwargs['auto_continue'] = True
153
150 154 messages = json_data['messages']
151 155 if json_data.get('web_search'):
152 156 if provider == "Bing":
153 157 kwargs['web_search'] = True
154 158 else:
155 159 messages[-1]["content"] = get_search_message(messages[-1]["content"])
160
156 161 model = json_data.get('model')
157 162 model = model if model else models.default
158 163 patch = patch_provider if json_data.get('patch_provider') else None