返回提交历史
Modified
g4f/Provider/needs_auth/ChatGPTLightweight.py
+80
-4
Modified
projects/android/app/src/main/java/dev/g4f/android/MainActivity.java
+1
-1
Modified
projects/android/gradlew
+220
-41
Added
projects/android/gradlew.bat
+92
-0
XFEstudio/gpt4free
Add missing gradle
4723968c
代码差异
4 个文件
+393
-46
@@ -1,7 +1,6 @@
1
1
from __future__ import annotations
2
2
3
3
import asyncio
4
import base64
5
4
import html
6
5
import json
7
6
import os
@@ -12,6 +11,7 @@ import uuid
12
11
13
12
from ...typing import AsyncResult, Messages
14
13
from ...requests import StreamSession
14
from ...requests.cdp import CDPSession
15
15
from ...requests.raise_for_status import raise_for_status
16
16
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
17
17
from ..helper import format_prompt
@@ -65,9 +65,11 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
65
65
required" (rate limiting / IP reputation). Requests are therefore retried
66
66
with a fresh session a few times before giving up.
67
67
68
A "cf_clearance" cookie from a real browser session (HAR capture or the
69
local browser profile) marks the visitor as trusted and greatly improves
70
the pass rate; see `_load_auth_state`.
68
A "cf_clearance" cookie from a real browser session marks the visitor
69
as trusted and greatly improves the pass rate. Fresh cookies and matching
70
client-hint headers are harvested through a CDP browser session on first
71
use (see `_harvest_via_cdp`), falling back to cached HAR captures
72
(`_load_auth_state`) when no browser is available.
71
73
"""
72
74
73
75
label = "ChatGPT (Lightweight)"
@@ -160,6 +162,8 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
160
162
# flagged, so reusing it would poison every retry.
161
163
if attempt > 0:
162
164
conversation.oai_did = str(uuid.uuid4())
165
if attempt >= 3:
166
cls._auth_state = None
163
167
reply = await cls._fetch_reply(prompt=prompt, conversation=conversation, proxy=proxy, timeout=timeout)
164
168
if reply is not None:
165
169
yield reply
@@ -244,6 +248,69 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
244
248
cls._auth_state_loaded_at = now
245
249
return cls._auth_state
246
250
251
@classmethod
252
async def _harvest_via_cdp(cls, proxy: str = None) -> tuple:
253
"""Harvest fresh chatgpt.com cookies and headers via a CDP browser.
254
255
Opens a real browser, waits for the Cloudflare gate to clear and
256
captures the cookies (notably "cf_clearance") together with the
257
client-hint headers the browser actually sends, so later requests
258
match the fingerprint the cookies were issued for.
259
"""
260
async with CDPSession(proxy=proxy) as session:
261
try:
262
await session.navigate(cls.url)
263
except Exception as e:
264
# A load-event race must not discard an otherwise good session.
265
debug.log(f"ChatGPTLightweight: CDP navigate: {e}")
266
# Wait for a pending Cloudflare challenge to resolve.
267
for _ in range(30):
268
title = await session.evaluate_js("document.title") or ""
269
if title and "Just a moment" not in title and "Attention Required" not in title:
270
break
271
await asyncio.sleep(1)
272
debug.log("ChatGPTLightweight: waiting for network idle")
273
await session.wait_for_network_idle()
274
debug.log("ChatGPTLightweight: network idle reached")
275
cookies = await session.get_cookies([f"{cls.url}/"])
276
if not cookies.get("cf_clearance"):
277
# The clearance cookie is minted once the challenge resolves;
278
# give it a moment to show up.
279
for _ in range(10):
280
await asyncio.sleep(1)
281
cookies = await session.get_cookies([f"{cls.url}/"])
282
if cookies.get("cf_clearance"):
283
break
284
if not cookies:
285
# Fall back to whatever the current page holds.
286
cookies = await session.get_cookies()
287
# Copy headers from requests the browser itself sent to chatgpt.com.
288
headers = {}
289
for params in session.network_requests:
290
request = params.get("request", {})
291
if "chatgpt.com" not in request.get("url", ""):
292
continue
293
sent = {
294
name.lower(): value
295
for name, value in request.get("headers", {}).items()
296
}
297
for name in cls._AUTH_HEADERS_WHITELIST:
298
if name in sent:
299
headers.setdefault(name, sent[name])
300
if "user-agent" in sent:
301
headers["user-agent"] = sent["user-agent"]
302
# Keep proof-of-work / turnstile on the same UA the
303
# cookies were issued for.
304
cls.user_agent = sent["user-agent"]
305
if "accept-language" in sent:
306
headers.setdefault("accept-language", sent["accept-language"])
307
debug.log(
308
f"ChatGPTLightweight: CDP harvest: {len(cookies)} cookies"
309
f" (cf_clearance={'yes' if cookies.get('cf_clearance') else 'no'}),"
310
f" {len(headers)} headers"
311
)
312
return cookies, headers
313
247
314
@classmethod
248
315
async def _fetch_reply(
249
316
cls,
@@ -252,6 +319,15 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
252
319
proxy: str = None,
253
320
timeout: int = 120,
254
321
) -> str:
322
if cls._auth_state is None:
323
# Harvest fresh cookies and headers from a real browser before
324
# falling back to cached HAR captures: a cf_clearance minted for
325
# the current IP passes the gate far more reliably.
326
try:
327
cls._auth_state = await cls._harvest_via_cdp(proxy=proxy)
328
cls._auth_state_loaded_at = time.time()
329
except Exception as e:
330
debug.log(f"ChatGPTLightweight: CDP harvest failed: {e}")
255
331
auth_cookies, auth_headers = cls._load_auth_state()
256
332
# Reuse the captured visitor id when available so the session stays
257
333
# consistent with the cf_clearance cookie it was issued with.
@@ -41,7 +41,7 @@ public class MainActivity extends Activity {
41
41
private ExecutorService executor;
42
42
public static final int PORT = 1337;
43
43
private static final String APP_DIR = "app";
44
private static final String EXTRACTION_VERSION = "5"; // bump to force re-extraction
44
private static final String EXTRACTION_VERSION = "6"; // bump to force re-extraction
45
45
46
46
// File chooser (image / file upload from the chat UI)
47
47
private static final int FILE_CHOOSER_REQUEST = 1001;
@@ -1,47 +1,127 @@
1
#!/usr/bin/env sh
1
#!/bin/sh
2
3
#
4
# Copyright © 2015-2021 the original authors.
5
#
6
# Licensed under the Apache License, Version 2.0 (the "License");
7
# you may not use this file except in compliance with the License.
8
# You may obtain a copy of the License at
9
#
10
# https://www.apache.org/licenses/LICENSE-2.0
11
#
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS,
14
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
# See the License for the specific language governing permissions and
16
# limitations under the License.
17
#
2
18
3
19
##############################################################################
4
##
5
## Gradle start up script for UN*X
6
##
20
#
21
# Gradle start up script for POSIX generated by Gradle.
22
#
23
# Important for running:
24
#
25
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26
# noncompliant, but you have some other compliant shell such as ksh or
27
# bash, then to run this script, type that shell name before the whole
28
# command line, like:
29
#
30
# ksh Gradle
31
#
32
# Busybox and similar reduced shells will NOT work, because this script
33
# requires all of these POSIX shell features:
34
# * functions;
35
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37
# * compound commands having a testable exit status, especially «case»;
38
# * various built-in commands including «command», «set», and «ulimit».
39
#
40
# Important for patching:
41
#
42
# (2) This script targets any POSIX shell, so it avoids extensions provided
43
# by Bash, Ksh, etc; in particular arrays are avoided.
44
#
45
# The "traditional" practice of packing multiple parameters into a
46
# space-separated string is a well documented source of bugs and security
47
# problems, so this is (mostly) avoided, by progressively accumulating
48
# options in "$@", and eventually passing that to Java.
49
#
50
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52
# see the in-line comments for details.
53
#
54
# There are tweaks for specific operating systems such as AIX, CygWin,
55
# Darwin, MinGW, and NonStop.
56
#
57
# (3) This script is generated from the Groovy template
58
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59
# within the Gradle project.
60
#
61
# You can find Gradle at https://github.com/gradle/gradle/.
62
#
7
63
##############################################################################
8
64
9
65
# Attempt to set APP_HOME
66
10
67
# Resolve links: $0 may be a link
11
PRG="$0"
12
# Need this for relative symlinks.
13
while [ -h "$PRG" ]; do
14
ls=`ls -ld "$PRG"`
15
link=`expr "$ls" : '.*-> \(.*\)$'`
16
if expr "$link" : '/.*' > /dev/null; then
17
PRG="$link"
18
else
19
PRG=`dirname "$PRG"`"/$link"
20
fi
68
app_path=$0
69
70
# Need this for daisy-chained symlinks.
71
while
72
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73
[ -h "$app_path" ]
74
do
75
ls=$( ls -ld "$app_path" )
76
link=${ls#*' -> '}
77
case $link in #(
78
/*) app_path=$link ;; #(
79
*) app_path=$APP_HOME$link ;;
80
esac
21
81
done
22
SAVED="`pwd`"
23
CDPATH=""
24
cd "`dirname \"$PRG\"`/" >/dev/null
25
APP_HOME="`pwd -P`"
26
cd "$SAVED" >/dev/null
27
82
28
APP_NAME="Gradle"
29
APP_BASE_NAME=`basename "$0"`
83
# This is normally unused
84
# shellcheck disable=SC2034
85
APP_BASE_NAME=${0##*/}
86
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
30
88
31
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
32
DEFAULT_JVM_OPTS='-Xmx64m -Xms64m'
89
# Use the maximum available, or set MAX_FD != -1 to use that value.
90
MAX_FD=maximum
33
91
34
# Use the maximum available byte code version of the current JVM.
35
# This option can be overridden by GRADLE_OPTS.
36
# Note: Since Gradle 8.3, Java 20 and Java 21 are supported.
37
# JAVA_OPTS="-XX:+IgnoreUnrecognizedVMOptions"
92
warn () {
93
echo "$*"
94
} >&2
38
95
39
# Find java
96
die () {
97
echo
98
echo "$*"
99
echo
100
exit 1
101
} >&2
102
103
# OS specific support (must be 'true' or 'false').
104
cygwin=false
105
msys=false
106
darwin=false
107
nonstop=false
108
case "$( uname )" in #(
109
CYGWIN* ) cygwin=true ;; #(
110
Darwin* ) darwin=true ;; #(
111
MSYS* | MINGW* ) msys=true ;; #(
112
NONSTOP* ) nonstop=true ;;
113
esac
114
115
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116
117
118
# Determine the Java command to use to start the JVM.
40
119
if [ -n "$JAVA_HOME" ] ; then
41
if [ -x "$JAVA_HOME/libexec/java_home" ] ; then
42
JAVACMD="$JAVA_HOME/libexec/java_home"
120
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121
# IBM's JDK on AIX uses strange locations for the executables
122
JAVACMD=$JAVA_HOME/jre/sh/java
43
123
else
44
JAVACMD="$JAVA_HOME/bin/java"
124
JAVACMD=$JAVA_HOME/bin/java
45
125
fi
46
126
if [ ! -x "$JAVACMD" ] ; then
47
127
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -50,21 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the
50
130
location of your Java installation."
51
131
fi
52
132
else
53
JAVACMD="java"
54
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
133
JAVACMD=java
134
if ! command -v java >/dev/null 2>&1
135
then
136
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
55
137
56
138
Please set the JAVA_HOME variable in your environment to match the
57
139
location of your Java installation."
140
fi
141
fi
142
143
# Increase the maximum file descriptors if we can.
144
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145
case $MAX_FD in #(
146
max*)
147
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148
# shellcheck disable=SC2039,SC3045
149
MAX_FD=$( ulimit -H -n ) ||
150
warn "Could not query maximum file descriptor limit"
151
esac
152
case $MAX_FD in #(
153
'' | soft) :;; #(
154
*)
155
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156
# shellcheck disable=SC2039,SC3045
157
ulimit -n "$MAX_FD" ||
158
warn "Could not set maximum file descriptor limit to $MAX_FD"
159
esac
160
fi
161
162
# Collect all arguments for the java command, stacking in reverse order:
163
# * args from the command line
164
# * the main class name
165
# * -classpath
166
# * -D...appname settings
167
# * --module-path (only if needed)
168
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169
170
# For Cygwin or MSYS, switch paths to Windows format before running java
171
if "$cygwin" || "$msys" ; then
172
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174
175
JAVACMD=$( cygpath --unix "$JAVACMD" )
176
177
# Now convert the arguments - kludge to limit ourselves to /bin/sh
178
for arg do
179
if
180
case $arg in #(
181
-*) false ;; # don't mess with options #(
182
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183
[ -e "$t" ] ;; #(
184
*) false ;;
185
esac
186
then
187
arg=$( cygpath --path --ignore --mixed "$arg" )
188
fi
189
# Roll the args list around exactly as many times as the number of
190
# args, so each arg winds up back in the position where it started, but
191
# possibly modified.
192
#
193
# NB: a `for` loop captures its iteration list before it begins, so
194
# changing the positional parameters here affects neither the number of
195
# iterations, nor the values presented in `arg`.
196
shift # remove old arg
197
set -- "$@" "$arg" # push replacement arg
198
done
58
199
fi
59
200
60
# Increase default memory limits if needed.
61
# GRADLE_OPTS="-Xmx1024m -XX:MaxMetaspaceSize=256m $GRADLE_OPTS"
62
201
63
# Find the wrapper jar directly or via class loading.
64
WRAPPER_JAR="$APP_HOME/gradle/wrapper/gradle-wrapper.jar"
202
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204
205
# Collect all arguments for the java command:
206
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207
# and any embedded shellness will be escaped.
208
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209
# treated as '${Hostname}' itself on the command line.
210
211
set -- \
212
"-Dorg.gradle.appname=$APP_BASE_NAME" \
213
-classpath "$CLASSPATH" \
214
org.gradle.wrapper.GradleWrapperMain \
215
"$@"
216
217
# Stop when "xargs" is not available.
218
if ! command -v xargs >/dev/null 2>&1
219
then
220
die "xargs is not available"
221
fi
222
223
# Use "xargs" to parse quoted args.
224
#
225
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226
#
227
# In Bash we could simply go:
228
#
229
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230
# set -- "${ARGS[@]}" "$@"
231
#
232
# but POSIX shell has neither arrays nor command substitution, so instead we
233
# post-process each arg (as a line of input to sed) to backslash-escape any
234
# character that might be a shell metacharacter, then use eval to reverse
235
# that process (while maintaining the separation between arguments), and wrap
236
# the whole thing up as a single "set" statement.
237
#
238
# This will of course break if any of these variables contains a newline or
239
# an unmatched quote.
240
#
65
241
66
# Determine classpath
67
CLASSPATH=$WRAPPER_JAR
242
eval "set -- $(
243
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244
xargs -n1 |
245
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246
tr '\n' ' '
247
)" '"$@"'
68
248
69
# Execute Gradle
70
exec "$JAVACMD" $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "-Dorg.gradle.appname=$APP_BASE_NAME" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
249
exec "$JAVACMD" "$@"
@@ -0,0 +1,92 @@
1
@rem
2
@rem Copyright 2015 the original author or authors.
3
@rem
4
@rem Licensed under the Apache License, Version 2.0 (the "License");
5
@rem you may not use this file except in compliance with the License.
6
@rem You may obtain a copy of the License at
7
@rem
8
@rem https://www.apache.org/licenses/LICENSE-2.0
9
@rem
10
@rem Unless required by applicable law or agreed to in writing, software
11
@rem distributed under the License is distributed on an "AS IS" BASIS,
12
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
@rem See the License for the specific language governing permissions and
14
@rem limitations under the License.
15
@rem
16
17
@if "%DEBUG%"=="" @echo off
18
@rem ##########################################################################
19
@rem
20
@rem Gradle startup script for Windows
21
@rem
22
@rem ##########################################################################
23
24
@rem Set local scope for the variables with windows NT shell
25
if "%OS%"=="Windows_NT" setlocal
26
27
set DIRNAME=%~dp0
28
if "%DIRNAME%"=="" set DIRNAME=.
29
@rem This is normally unused
30
set APP_BASE_NAME=%~n0
31
set APP_HOME=%DIRNAME%
32
33
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
34
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35
36
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38
39
@rem Find java.exe
40
if defined JAVA_HOME goto findJavaFromJavaHome
41
42
set JAVA_EXE=java.exe
43
%JAVA_EXE% -version >NUL 2>&1
44
if %ERRORLEVEL% equ 0 goto execute
45
46
echo. 1>&2
47
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
48
echo. 1>&2
49
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
50
echo location of your Java installation. 1>&2
51
52
goto fail
53
54
:findJavaFromJavaHome
55
set JAVA_HOME=%JAVA_HOME:"=%
56
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57
58
if exist "%JAVA_EXE%" goto execute
59
60
echo. 1>&2
61
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
62
echo. 1>&2
63
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
64
echo location of your Java installation. 1>&2
65
66
goto fail
67
68
:execute
69
@rem Setup the command line
70
71
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72
73
74
@rem Execute Gradle
75
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76
77
:end
78
@rem End local scope for the variables with windows NT shell
79
if %ERRORLEVEL% equ 0 goto mainEnd
80
81
:fail
82
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83
rem the _cmd.exe /c_ return code!
84
set EXIT_CODE=%ERRORLEVEL%
85
if %EXIT_CODE% equ 0 set EXIT_CODE=1
86
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87
exit /b %EXIT_CODE%
88
89
:mainEnd
90
if "%OS%"=="Windows_NT" endlocal
91
92
:omega