From 59fcf9d2d3be66c5988731f8e8ffa707d01c6539 Mon Sep 17 00:00:00 2001 From: Heiner Lohaus Date: Wed, 15 May 2024 02:27:51 +0200 Subject: Update chatgpt url, uvloop support --- g4f/Provider/needs_auth/Gemini.py | 25 ++++++++++++++++++------- g4f/Provider/needs_auth/OpenaiChat.py | 15 ++++++++------- g4f/Provider/openai/har_file.py | 2 +- g4f/Provider/openai/proofofwork.py | 7 ++----- 4 files changed, 29 insertions(+), 20 deletions(-) (limited to 'g4f/Provider') diff --git a/g4f/Provider/needs_auth/Gemini.py b/g4f/Provider/needs_auth/Gemini.py index 75cdd199..25ad1c6e 100644 --- a/g4f/Provider/needs_auth/Gemini.py +++ b/g4f/Provider/needs_auth/Gemini.py @@ -17,12 +17,12 @@ except ImportError: pass from ... import debug -from ...typing import Messages, Cookies, ImageType, AsyncResult +from ...typing import Messages, Cookies, ImageType, AsyncResult, AsyncIterator from ..base_provider import AsyncGeneratorProvider from ..helper import format_prompt, get_cookies from ...requests.raise_for_status import raise_for_status from ...errors import MissingAuthError, MissingRequirementsError -from ...image import to_bytes, ImageResponse +from ...image import to_bytes, to_data_uri, ImageResponse from ...webdriver import get_browser, get_driver_cookies REQUEST_HEADERS = { @@ -59,7 +59,7 @@ class Gemini(AsyncGeneratorProvider): _cookies: Cookies = None @classmethod - async def nodriver_login(cls) -> Cookies: + async def nodriver_login(cls) -> AsyncIterator[str]: try: import nodriver as uc except ImportError: @@ -72,6 +72,9 @@ class Gemini(AsyncGeneratorProvider): if debug.logging: print(f"Open nodriver with user_dir: {user_data_dir}") browser = await uc.start(user_data_dir=user_data_dir) + login_url = os.environ.get("G4F_LOGIN_URL") + if login_url: + yield f"Please login: [Google Gemini]({login_url})\n\n" page = await browser.get(f"{cls.url}/app") await page.select("div.ql-editor.textarea", 240) cookies = {} @@ -79,10 +82,10 @@ class Gemini(AsyncGeneratorProvider): if c.domain.endswith(".google.com"): cookies[c.name] = c.value await page.close() - return cookies + cls._cookies = cookies @classmethod - async def webdriver_login(cls, proxy: str): + async def webdriver_login(cls, proxy: str) -> AsyncIterator[str]: driver = None try: driver = get_browser(proxy=proxy) @@ -131,13 +134,14 @@ class Gemini(AsyncGeneratorProvider): ) as session: snlm0e = await cls.fetch_snlm0e(session, cls._cookies) if cls._cookies else None if not snlm0e: - cls._cookies = await cls.nodriver_login(); + async for chunk in cls.nodriver_login(): + yield chunk if cls._cookies is None: async for chunk in cls.webdriver_login(proxy): yield chunk if not snlm0e: - if "__Secure-1PSID" not in cls._cookies: + if cls._cookies is None or "__Secure-1PSID" not in cls._cookies: raise MissingAuthError('Missing "__Secure-1PSID" cookie') snlm0e = await cls.fetch_snlm0e(session, cls._cookies) if not snlm0e: @@ -193,6 +197,13 @@ class Gemini(AsyncGeneratorProvider): image = fetch.headers["location"] resolved_images.append(image) preview.append(image.replace('=s512', '=s200')) + # preview_url = image.replace('=s512', '=s200') + # async with client.get(preview_url) as fetch: + # preview_data = to_data_uri(await fetch.content.read()) + # async with client.get(image) as fetch: + # data = to_data_uri(await fetch.content.read()) + # preview.append(preview_data) + # resolved_images.append(data) yield ImageResponse(resolved_images, image_prompt, {"orginal_links": images, "preview": preview}) def build_request( diff --git a/g4f/Provider/needs_auth/OpenaiChat.py b/g4f/Provider/needs_auth/OpenaiChat.py index 056a3702..03ea4539 100644 --- a/g4f/Provider/needs_auth/OpenaiChat.py +++ b/g4f/Provider/needs_auth/OpenaiChat.py @@ -38,7 +38,7 @@ DEFAULT_HEADERS = { "accept": "*/*", "accept-encoding": "gzip, deflate, br, zstd", "accept-language": "en-US,en;q=0.5", - "referer": "https://chat.openai.com/", + "referer": "https://chatgpt.com/", "sec-ch-ua": "\"Brave\";v=\"123\", \"Not:A-Brand\";v=\"8\", \"Chromium\";v=\"123\"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "\"Windows\"", @@ -53,15 +53,15 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin): """A class for creating and managing conversations with OpenAI chat service""" label = "OpenAI ChatGPT" - url = "https://chat.openai.com" + url = "https://chatgpt.com" working = True supports_gpt_35_turbo = True supports_gpt_4 = True supports_message_history = True supports_system_message = True default_model = None - default_vision_model = "gpt-4-vision" - models = ["gpt-3.5-turbo", "gpt-4", "gpt-4-gizmo"] + default_vision_model = "gpt-4o" + models = ["gpt-3.5-turbo", "gpt-4", "gpt-4-gizmo", "gpt-4o"] model_aliases = { "text-davinci-002-render-sha": "gpt-3.5-turbo", "": "gpt-3.5-turbo", @@ -442,6 +442,7 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin): try: image_request = await cls.upload_image(session, cls._headers, image, image_name) if image else None except Exception as e: + image_request = None if debug.logging: print("OpenaiChat: Upload image failed") print(f"{e.__class__.__name__}: {e}") @@ -601,7 +602,7 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin): this._fetch = this.fetch; this.fetch = async (url, options) => { const response = await this._fetch(url, options); - if (url == "https://chat.openai.com/backend-api/conversation") { + if (url == "https://chatgpt.com/backend-api/conversation") { this._headers = options.headers; return response; } @@ -637,7 +638,7 @@ this.fetch = async (url, options) => { if debug.logging: print(f"Open nodriver with user_dir: {user_data_dir}") browser = await uc.start(user_data_dir=user_data_dir) - page = await browser.get("https://chat.openai.com/") + page = await browser.get("https://chatgpt.com/") await page.select("[id^=headlessui-menu-button-]", 240) api_key = await page.evaluate( "(async () => {" @@ -652,7 +653,7 @@ this.fetch = async (url, options) => { ) cookies = {} for c in await page.browser.cookies.get_all(): - if c.domain.endswith("chat.openai.com"): + if c.domain.endswith("chatgpt.com"): cookies[c.name] = c.value user_agent = await page.evaluate("window.navigator.userAgent") await page.close() diff --git a/g4f/Provider/openai/har_file.py b/g4f/Provider/openai/har_file.py index 6a34c97a..220c20bf 100644 --- a/g4f/Provider/openai/har_file.py +++ b/g4f/Provider/openai/har_file.py @@ -26,7 +26,7 @@ class arkReq: self.userAgent = userAgent arkPreURL = "https://tcr9i.chat.openai.com/fc/gt2/public_key/35536E1E-65B4-4D96-9D97-6ADB7EFF8147" -sessionUrl = "https://chat.openai.com/api/auth/session" +sessionUrl = "https://chatgpt.com/api/auth/session" chatArk: arkReq = None accessToken: str = None cookies: dict = None diff --git a/g4f/Provider/openai/proofofwork.py b/g4f/Provider/openai/proofofwork.py index e44ef6f7..51d96bc4 100644 --- a/g4f/Provider/openai/proofofwork.py +++ b/g4f/Provider/openai/proofofwork.py @@ -16,12 +16,9 @@ def generate_proof_token(required: bool, seed: str, difficulty: str, user_agent: # Get current UTC time now_utc = datetime.now(timezone.utc) - # Convert UTC time to Eastern Time - now_et = now_utc.astimezone(timezone(timedelta(hours=-5))) + parse_time = now_utc.strftime('%a, %d %b %Y %H:%M:%S GMT') - parse_time = now_et.strftime('%a, %d %b %Y %H:%M:%S GMT') - - config = [core + screen, parse_time, 4294705152, 0, user_agent] + config = [core + screen, parse_time, None, 0, user_agent, "https://tcr9i.chat.openai.com/v2/35536E1E-65B4-4D96-9D97-6ADB7EFF8147/api.js","dpl=53d243de46ff04dadd88d293f088c2dd728f126f","en","en-US",442,"pluginsāˆ’[object PluginArray]","","alert"] diff_len = len(difficulty) // 2 -- cgit v1.2.3