gpt4free/g4f/Provider/helper.py

77 lines
2.4 KiB
Python
Raw Normal View History

from __future__ import annotations
2023-10-07 20:00:45 +03:00
import asyncio
import sys
from asyncio import AbstractEventLoop
2023-10-04 04:15:17 +03:00
from os import path
2023-10-07 20:00:45 +03:00
from typing import Dict, List
import browser_cookie3
# Change event loop policy on windows
if sys.platform == 'win32':
if isinstance(
asyncio.get_event_loop_policy(), asyncio.WindowsProactorEventLoopPolicy
):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Local Cookie Storage
2023-10-07 20:00:45 +03:00
_cookies: Dict[str, Dict[str, str]] = {}
# If event loop is already running, handle nested event loops
# If "nest_asyncio" is installed, patch the event loop.
def get_event_loop() -> AbstractEventLoop:
try:
asyncio.get_running_loop()
except RuntimeError:
try:
return asyncio.get_event_loop()
except RuntimeError:
asyncio.set_event_loop(asyncio.new_event_loop())
return asyncio.get_event_loop()
try:
event_loop = asyncio.get_event_loop()
if not hasattr(event_loop.__class__, "_nest_patched"):
import nest_asyncio
nest_asyncio.apply(event_loop)
return event_loop
except ImportError:
raise RuntimeError(
2023-10-07 20:00:45 +03:00
'Use "create_async" instead of "create" function in a running event loop. Or install the "nest_asyncio" package.'
)
2023-10-07 20:00:45 +03:00
# Load cookies for a domain from all supported browsers.
# Cache the results in the "_cookies" variable.
def get_cookies(cookie_domain: str) -> Dict[str, str]:
if cookie_domain not in _cookies:
_cookies[cookie_domain] = {}
try:
for cookie in browser_cookie3.load(cookie_domain):
_cookies[cookie_domain][cookie.name] = cookie.value
except:
pass
return _cookies[cookie_domain]
2023-10-07 20:00:45 +03:00
def format_prompt(messages: List[Dict[str, str]], add_special_tokens=False) -> str:
if add_special_tokens or len(messages) > 1:
formatted = "\n".join(
2023-10-07 20:00:45 +03:00
[
"%s: %s" % ((message["role"]).capitalize(), message["content"])
for message in messages
]
)
return f"{formatted}\nAssistant:"
else:
return messages[0]["content"]
2023-10-07 20:00:45 +03:00
def get_browser(user_data_dir: str = None):
2023-10-04 04:15:17 +03:00
from undetected_chromedriver import Chrome
from platformdirs import user_config_dir
if not user_data_dir:
2023-10-04 04:15:17 +03:00
user_data_dir = user_config_dir("g4f")
user_data_dir = path.join(user_data_dir, "Default")
return Chrome(user_data_dir=user_data_dir)