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

XFEstudio/gpt4free

Add upload cookie files

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

代码差异

5 个文件 +47 -27
Modified g4f/Provider/needs_auth/OpenaiChat.py +3 -1
@@ -418,6 +418,7 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
418 418 [debug.log(text) for text in (
419 419 f"Arkose: {'False' if not need_arkose else RequestConfig.arkose_token[:12]+'...'}",
420 420 f"Proofofwork: {'False' if proofofwork is None else proofofwork[:12]+'...'}",
421 f"AccessToken: {'False' if cls._api_key is None else cls._api_key[:12]+'...'}",
421 422 )]
422 423 data = {
423 424 "action": action,
@@ -438,7 +439,8 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
438 439 messages = messages if conversation_id is None else [messages[-1]]
439 440 data["messages"] = cls.create_messages(messages, image_request)
440 441 headers = {
441 "accept": "text/event-stream",
442 "Accept": "text/event-stream",
443 "Content-Type": "application/json",
442 444 "Openai-Sentinel-Chat-Requirements-Token": chat_token,
443 445 **cls._headers
444 446 }
Modified g4f/Provider/openai/har_file.py +4 -4
@@ -81,10 +81,10 @@ def readHAR():
81 81 RequestConfig.access_token = match.group(1)
82 82 except KeyError:
83 83 continue
84 RequestConfig.cookies = {c['name']: c['value'] for c in v['request']['cookies'] if c['name'] != "oai-did"}
84 RequestConfig.cookies = {c['name']: c['value'] for c in v['request']['cookies']}
85 85 RequestConfig.headers = v_headers
86 if RequestConfig.access_token is None:
87 raise NoValidHarFileError("No accessToken found in .har files")
86 if RequestConfig.proof_token is None:
87 raise NoValidHarFileError("No proof_token found in .har files")
88 88
89 89 def get_headers(entry) -> dict:
90 90 return {h['name'].lower(): h['value'] for h in entry['request']['headers'] if h['name'].lower() not in ['content-length', 'cookie'] and not h['name'].startswith(':')}
@@ -149,7 +149,7 @@ def getN() -> str:
149 149 return base64.b64encode(timestamp.encode()).decode()
150 150
151 151 async def get_request_config(proxy: str) -> RequestConfig:
152 if RequestConfig.access_token is None:
152 if RequestConfig.proof_token is None:
153 153 readHAR()
154 154 if RequestConfig.arkose_request is not None:
155 155 RequestConfig.arkose_token = await sendRequest(genArkReq(RequestConfig.arkose_request), proxy)
Modified g4f/gui/client/index.html +1 -1
@@ -224,7 +224,7 @@
224 224 <i class="fa-solid fa-camera"></i>
225 225 </label>
226 226 <label class="file-label" for="file">
227 <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/>
227 <input type="file" id="file" name="file" accept="text/plain, text/html, text/xml, application/json, text/javascript, .har, .sh, .py, .php, .css, .yaml, .sql, .log, .csv, .twig, .md" required/>
228 228 <i class="fa-solid fa-paperclip"></i>
229 229 </label>
230 230 <label class="micro-label" for="micro">
Modified g4f/gui/client/static/js/chat.v1.js +23 -10
@@ -1338,17 +1338,25 @@ fileInput.addEventListener('click', async (event) => {
1338 1338 delete fileInput.dataset.text;
1339 1339 });
1340 1340
1341 async function upload_cookies() {
1342 const file = fileInput.files[0];
1343 const formData = new FormData();
1344 formData.append('file', file);
1345 response = await fetch("/backend-api/v2/upload_cookies", {
1346 method: 'POST',
1347 body: formData,
1348 });
1349 if (response.status == 200) {
1350 inputCount.innerText = `${file.name} was uploaded successfully`;
1351 }
1352 fileInput.value = "";
1353 }
1354
1341 1355 fileInput.addEventListener('change', async (event) => {
1342 1356 if (fileInput.files.length) {
1343 type = fileInput.files[0].type;
1344 if (type && type.indexOf('/')) {
1345 type = type.split('/').pop().replace('x-', '')
1346 type = type.replace('plain', 'plaintext')
1347 .replace('shellscript', 'sh')
1348 .replace('svg+xml', 'svg')
1349 .replace('vnd.trolltech.linguist', 'ts')
1350 } else {
1351 type = fileInput.files[0].name.split('.').pop()
1357 type = fileInput.files[0].name.split('.').pop()
1358 if (type == "har") {
1359 return await upload_cookies();
1352 1360 }
1353 1361 fileInput.dataset.type = type
1354 1362 const reader = new FileReader();
@@ -1357,14 +1365,19 @@ fileInput.addEventListener('change', async (event) => {
1357 1365 if (type == "json") {
1358 1366 const data = JSON.parse(fileInput.dataset.text);
1359 1367 if ("g4f" in data.options) {
1368 let count = 0;
1360 1369 Object.keys(data).forEach(key => {
1361 1370 if (key != "options" && !localStorage.getItem(key)) {
1362 1371 appStorage.setItem(key, JSON.stringify(data[key]));
1363 }
1372 count += 1;
1373 }
1364 1374 });
1365 1375 delete fileInput.dataset.text;
1366 1376 await load_conversations();
1367 1377 fileInput.value = "";
1378 inputCount.innerText = `${count} Conversations were imported successfully`;
1379 } else {
1380 await upload_cookies();
1368 1381 }
1369 1382 }
1370 1383 });
Modified g4f/gui/server/backend.py +16 -11
@@ -1,12 +1,15 @@
1 1 import json
2 2 import asyncio
3 3 import flask
4 import os
4 5 from flask import request, Flask
5 6 from typing import AsyncGenerator, Generator
7 from werkzeug.utils import secure_filename
6 8
7 9 from g4f.image import is_allowed_extension, to_image
8 10 from g4f.client.service import convert_to_provider
9 11 from g4f.errors import ProviderNotFoundError
12 from g4f.cookies import get_cookies_dir
10 13 from .api import Api
11 14
12 15 def safe_iter_generator(generator: Generator) -> Generator:
@@ -79,8 +82,8 @@ class Backend_Api(Api):
79 82 'function': self.handle_synthesize,
80 83 'methods': ['GET']
81 84 },
82 '/backend-api/v2/error': {
83 'function': self.handle_error,
85 '/backend-api/v2/upload_cookies': {
86 'function': self.upload_cookies,
84 87 'methods': ['POST']
85 88 },
86 89 '/images/<path:name>': {
@@ -89,15 +92,17 @@ class Backend_Api(Api):
89 92 }
90 93 }
91 94
92 def handle_error(self):
93 """
94 Initialize the backend API with the given Flask application.
95
96 Args:
97 app (Flask): Flask application instance to attach routes to.
98 """
99 print(request.json)
100 return 'ok', 200
95 def upload_cookies(self):
96 file = None
97 if "file" in request.files:
98 file = request.files['file']
99 if file.filename == '':
100 return 'No selected file', 400
101 if file and file.filename.endswith(".json") or file.filename.endswith(".har"):
102 filename = secure_filename(file.filename)
103 file.save(os.path.join(get_cookies_dir(), filename))
104 return "File saved", 200
105 return 'Not supported file', 400
101 106
102 107 def handle_conversation(self):
103 108 """