Skip to content
This repository has been archived by the owner on Aug 10, 2023. It is now read-only.

Refactor #1473

Merged
merged 22 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
0a2729b
Use named expression
danparizher Apr 6, 2023
481adbb
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 7, 2023
f0c7e58
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 8, 2023
d88d7c0
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 8, 2023
e7d084d
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 9, 2023
bfba3c0
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 9, 2023
cc9e194
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 10, 2023
956d9ae
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 12, 2023
79a36c7
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 14, 2023
6348c13
Refactor
danparizher Apr 14, 2023
6cbdd90
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 14, 2023
57dd5e9
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 15, 2023
11bb0cc
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 16, 2023
ac10023
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 17, 2023
b728210
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 18, 2023
1222358
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 19, 2023
0e23714
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 20, 2023
c9f3403
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 21, 2023
fa745e2
Merge https://github.com/acheong08/ChatGPT
danparizher Apr 23, 2023
361b6fa
Merge https://github.com/acheong08/ChatGPT
danparizher May 3, 2023
9ec5e5a
Merge branch 'main' of https://github.com/Arborym/ChatGPT
danparizher Jul 21, 2023
7ce9b7b
Refactor
danparizher Jul 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 73 additions & 60 deletions src/revChatGPT/V1.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def random_int(min: int, max: int) -> int:
log = logging.getLogger(__name__)


def logger(is_timed: bool):
def logger(is_timed: bool) -> function:
"""Logger decorator

Args:
Expand All @@ -88,7 +88,7 @@ def logger(is_timed: bool):
_type_: decorated function
"""

def decorator(func):
def decorator(func: function) -> function:
wraps(func)

def wrapper(*args, **kwargs):
Expand Down Expand Up @@ -146,9 +146,7 @@ def captcha_solver(images: list[str], challenge_details: dict) -> int:
"Developer instructions: The captcha images have an index starting from 0 from left to right",
)
print("Enter the index of the images that matches the captcha instructions:")
index = int(input())

return index
return int(input())


CAPTCHA_URL = getenv("CAPTCHA_URL", "https://bypass.churchless.tech/captcha/")
Expand Down Expand Up @@ -198,41 +196,39 @@ def get_arkose_token(
if resp.status_code != 200:
raise Exception("Failed to verify captcha")
return resp_json.get("token")
else:
working_endpoints: list[str] = []
# Check uptime for different endpoints via gatus
resp2: list[dict] = requests.get(
"https://stats.churchless.tech/api/v1/endpoints/statuses?page=1"
).json()
for endpoint in resp2:
# print(endpoint.get("name"))
if endpoint.get("group") != "Arkose Labs":
continue
# Check the last 5 results
results: list[dict] = endpoint.get("results", [])[-5:-1]
# print(results)
if not results:
print(f"Endpoint {endpoint.get('name')} has no results")
continue
# Check if all the results are up
if all(result.get("success") == True for result in results):
working_endpoints.append(endpoint.get("name"))
if not working_endpoints:
print("No working endpoints found. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
# Choose a random endpoint
endpoint = random.choice(working_endpoints)
resp: requests.Response = requests.get(endpoint)
if resp.status_code != 200:
if resp.status_code != 511:
raise Exception("Failed to get captcha token")
else:
print("Captcha required. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
try:
return resp.json().get("token")
except Exception:
return resp.text
working_endpoints: list[str] = []
# Check uptime for different endpoints via gatus
resp2: list[dict] = requests.get(
"https://stats.churchless.tech/api/v1/endpoints/statuses?page=1",
).json()
for endpoint in resp2:
# print(endpoint.get("name"))
if endpoint.get("group") != "Arkose Labs":
continue
# Check the last 5 results
results: list[dict] = endpoint.get("results", [])[-5:-1]
# print(results)
if not results:
print(f"Endpoint {endpoint.get('name')} has no results")
continue
# Check if all the results are up
if all(result.get("success") is True for result in results):
working_endpoints.append(endpoint.get("name"))
if not working_endpoints:
print("No working endpoints found. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
# Choose a random endpoint
endpoint = random.choice(working_endpoints)
resp: requests.Response = requests.get(endpoint)
if resp.status_code != 200:
if resp.status_code != 511:
raise Exception("Failed to get captcha token")
print("Captcha required. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
try:
return resp.json().get("token")
except Exception:
return resp.text


class Chatbot:
Expand Down Expand Up @@ -315,8 +311,8 @@ def __init__(
else:
self.session.proxies.update(proxies)

self.conversation_id = conversation_id or config.get("conversation_id", None)
self.parent_id = parent_id or config.get("parent_id", None)
self.conversation_id = conversation_id or config.get("conversation_id")
self.parent_id = parent_id or config.get("parent_id")
self.conversation_mapping = {}
self.conversation_id_prev_queue = []
self.parent_id_prev_queue = []
Expand Down Expand Up @@ -482,7 +478,7 @@ def __write_cache(self, info: dict) -> None:
json.dump(info, open(self.cache_path, "w", encoding="utf-8"), indent=4)

@logger(is_timed=False)
def __read_cache(self):
def __read_cache(self) -> dict[str, dict[str, str]]:
try:
cached = json.load(open(self.cache_path, encoding="utf-8"))
except (FileNotFoundError, json.decoder.JSONDecodeError):
Expand Down Expand Up @@ -529,7 +525,7 @@ def __send_request(
# print(f"Arkose token obtained: {data['arkose_token']}")
except Exception as e:
print(e)
raise e
raise

cid, pid = data["conversation_id"], data["parent_message_id"]
message = ""
Expand Down Expand Up @@ -584,10 +580,12 @@ def __send_request(
author = {}
if line.get("message"):
author = metadata.get("author", {}) or line["message"].get("author", {})
if line["message"].get("content"):
if line["message"]["content"].get("parts"):
if len(line["message"]["content"]["parts"]) > 0:
message_exists = True
if (
line["message"].get("content")
and line["message"]["content"].get("parts")
and len(line["message"]["content"]["parts"]) > 0
):
message_exists = True
message: str = (
line["message"]["content"]["parts"][0] if message_exists else ""
)
Expand Down Expand Up @@ -629,7 +627,7 @@ def post_messages(
messages: list[dict],
conversation_id: str | None = None,
parent_id: str | None = None,
plugin_ids: list = [],
plugin_ids: list = None,
model: str | None = None,
auto_continue: bool = False,
timeout: float = 360,
Expand All @@ -656,6 +654,8 @@ def post_messages(
"citations": list[dict],
}
"""
if plugin_ids is None:
plugin_ids = []
if parent_id and not conversation_id:
raise t.Error(
source="User",
Expand Down Expand Up @@ -720,7 +720,7 @@ def ask(
conversation_id: str | None = None,
parent_id: str = "",
model: str = "",
plugin_ids: list = [],
plugin_ids: list = None,
auto_continue: bool = False,
timeout: float = 360,
**kwargs,
Expand All @@ -745,6 +745,8 @@ def ask(
"recipient": str,
}
"""
if plugin_ids is None:
plugin_ids = []
messages = [
{
"id": str(uuid.uuid4()),
Expand Down Expand Up @@ -1034,7 +1036,12 @@ def rollback_conversation(self, num: int = 1) -> None:
self.parent_id = self.parent_id_prev_queue.pop()

@logger(is_timed=True)
def get_plugins(self, offset: int = 0, limit: int = 250, status: str = "approved"):
def get_plugins(
self,
offset: int = 0,
limit: int = 250,
status: str = "approved",
) -> dict[str, str]:
"""
Get plugins
:param offset: Integer. Offset (Only supports 0)
Expand All @@ -1048,7 +1055,7 @@ def get_plugins(self, offset: int = 0, limit: int = 250, status: str = "approved
return json.loads(response.text)

@logger(is_timed=True)
def install_plugin(self, plugin_id: str):
def install_plugin(self, plugin_id: str) -> None:
"""
Install plugin by ID
:param plugin_id: String. ID of plugin
Expand Down Expand Up @@ -1156,10 +1163,12 @@ async def __send_request(
"author",
{},
)
if line["message"].get("content"):
if line["message"]["content"].get("parts"):
if len(line["message"]["content"]["parts"]) > 0:
message_exists = True
if (
line["message"].get("content")
and line["message"]["content"].get("parts")
and len(line["message"]["content"]["parts"]) > 0
):
message_exists = True
message: str = (
line["message"]["content"]["parts"][0] if message_exists else ""
)
Expand Down Expand Up @@ -1200,7 +1209,7 @@ async def post_messages(
messages: list[dict],
conversation_id: str | None = None,
parent_id: str | None = None,
plugin_ids: list = [],
plugin_ids: list = None,
model: str | None = None,
auto_continue: bool = False,
timeout: float = 360,
Expand Down Expand Up @@ -1229,6 +1238,8 @@ async def post_messages(
"citations": list[dict],
}
"""
if plugin_ids is None:
plugin_ids = []
if parent_id and not conversation_id:
raise t.Error(
source="User",
Expand Down Expand Up @@ -1292,7 +1303,7 @@ async def ask(
conversation_id: str | None = None,
parent_id: str = "",
model: str = "",
plugin_ids: list = [],
plugin_ids: list = None,
auto_continue: bool = False,
timeout: int = 360,
**kwargs,
Expand Down Expand Up @@ -1320,6 +1331,8 @@ async def ask(
}
"""

if plugin_ids is None:
plugin_ids = []
messages = [
{
"id": str(uuid.uuid4()),
Expand Down Expand Up @@ -1649,7 +1662,7 @@ def handle_commands(command: str) -> bool:
elif command == "!exit":
if isinstance(chatbot.session, httpx.AsyncClient):
chatbot.session.aclose()
exit()
sys.exit()
else:
return False
return True
Expand Down Expand Up @@ -1703,7 +1716,7 @@ def handle_commands(command: str) -> bool:
print()

except (KeyboardInterrupt, EOFError):
exit()
sys.exit()
except Exception as exc:
error = t.CLIError("command line program unknown error")
raise error from exc
Expand Down
21 changes: 10 additions & 11 deletions src/revChatGPT/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@ def verify() -> None:
if int(__import__("platform").python_version_tuple()[0]) < 3:
error = t.NotAllowRunning("Not available Python version")
raise error
elif int(__import__("platform").python_version_tuple()[1]) < 9:
if int(__import__("platform").python_version_tuple()[1]) < 9:
error = t.NotAllowRunning(
f"Not available Python version: {__import__('platform').python_version()}",
)
raise error
else:
if (
int(__import__("platform").python_version_tuple()[1]) < 10
and int(__import__("platform").python_version_tuple()[0]) == 3
):
__import__("warnings").warn(
UserWarning(
"The current Python is not a recommended version, 3.10+ is recommended",
),
)
if (
int(__import__("platform").python_version_tuple()[1]) < 10
and int(__import__("platform").python_version_tuple()[0]) == 3
):
__import__("warnings").warn(
UserWarning(
"The current Python is not a recommended version, 3.10+ is recommended",
),
)


verify()
2 changes: 1 addition & 1 deletion src/revChatGPT/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
__all__ = ()


def main():
def main() -> None:
"""
main function for CLI
"""
Expand Down
3 changes: 2 additions & 1 deletion src/revChatGPT/typings.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""
A module that contains all the types used in this project
"""

import os
import platform
from enum import Enum
from typing import Union


python_version = [each for each in platform.python_version_tuple()]
python_version = list(platform.python_version_tuple())
SUPPORT_ADD_NOTES = int(python_version[0]) >= 3 and int(python_version[1]) >= 11


Expand Down
2 changes: 1 addition & 1 deletion tests/test_recipient.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
config = json.load(open("/home/acheong/.config/revChatGPT/config.json"))


async def main():
async def main() -> None:
chatbot = AsyncChatbot(config)
async for message in chatbot.ask("Hello, how are you?"):
print(message.get("message"))
Expand Down