Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to fix linting warnings #132

Merged
merged 3 commits into from
Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ dist/*
usercookies/
fortest/
.mypy_cache
.vscode/
build/
40 changes: 20 additions & 20 deletions src/hugchat/cli.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Entry for the hugchat command line interface.

simply type
simply type
```bash
python -m hugchat.cli
```
Expand Down Expand Up @@ -59,7 +59,7 @@ def cli():
try:
if email:
cookies = Login(email).loadCookiesFromDir()
except Exception as e:
except Exception:
pass
if not cookies or inputpass:
if not email:
Expand All @@ -75,7 +75,7 @@ def cli():
passwd = getpass.getpass("Password: ")
else:
passwd = PASSWD

print(f"Sign in as :{email}")
sign = Login(email, passwd)
try:
Expand All @@ -85,24 +85,24 @@ def cli():
print("Logging in...")
cookies = sign.login()
sign.saveCookiesToDir()

chatbot = ChatBot(cookies=cookies)
running = True
is_web_search = False
web_search_hint = False

print("Login successfully🎉 You can input `/help` to open the command menu.")

while running:
question = input("> ")

if question == "/new":
cid = chatbot.new_conversation()
print("The new conversation ID is: " + cid)
chatbot.change_conversation(cid)
print("Conversation changed successfully.")
continue

elif question.startswith("/switch"):
try:
conversations = chatbot.get_conversation_list()
Expand All @@ -111,7 +111,7 @@ def cli():
conversation_id = int(conversation_id)
except Exception:
pass
if type(conversation_id) == int:
if isinstance(conversation_id, int):
if conversation_id <= len(conversations) and conversation_id > 0:
new_conversation_id = conversations[conversation_id-1]
if chatbot.current_conversation != new_conversation_id:
Expand All @@ -132,7 +132,7 @@ def cli():
print(f"# Conversation switched successfully to {conversation_id}")
except ValueError:
print("# Please enter a valid ID number")

elif question.startswith("/del"):
try:
conversations = chatbot.get_conversation_list()
Expand All @@ -141,12 +141,12 @@ def cli():
conversation_id = int(conversation_id)
except Exception:
pass
if type(conversation_id) == int:
if isinstance(conversation_id, int):
if conversation_id <= len(conversations) and conversation_id > 0:
new_conversation_id = conversations[conversation_id-1]
if chatbot.current_conversation != new_conversation_id:
chatbot.delete_conversation(new_conversation_id)
print(f"# Conversations successfully deleted")
print("# Conversations successfully deleted")
else:
print("# Cannot delete active session")
else:
Expand All @@ -159,18 +159,18 @@ def cli():
print("# Cannot delete active session")
else:
chatbot.delete_conversation(conversation_id)
print(f"# Conversation successfully deleted")
print("# Conversation successfully deleted")
except ValueError:
print("# Please enter a valid ID number")

elif question == "/ids":
id_list = list(chatbot.get_conversation_list())
[print(f"# {id_list.index(i) + 1} : {i}{' <active>' if chatbot.current_conversation == i else ''}") for i in
id_list]

elif question in ["/exit", "/quit", "/close"]:
running = False

elif question.startswith("/llm"):
command = question.split(" ")[1] if len(question.split(" ")) > 1 else ""
llms = chatbot.get_available_llm_models()
Expand All @@ -196,7 +196,7 @@ def cli():
elif question.startswith("/sharewithauthor"):
command = question.split(" ")[1] if len(question.split(" ")) > 1 else ""
if command:
if command in ["on","off"]:
if command in ["on", "off"]:
chatbot.set_share_conversations(True if command == "on" else False)
else:
print('# Invalid argument. Expected "on" or "off"')
Expand Down Expand Up @@ -229,7 +229,7 @@ def cli():
elif question.startswith("/web-hint"):
command = question.split(" ")[1] if len(question.split(" ")) > 1 else ""
if command:
if command in ["on","off"]:
if command in ["on", "off"]:
web_search_hint = True if command == "on" else False
print(f"# Web search hint {'enabled' if web_search_hint else 'disabled'}")
else:
Expand All @@ -240,7 +240,7 @@ def cli():
elif question.startswith("/web"):
command = question.split(" ")[1] if len(question.split(" ")) > 1 else ""
if command:
if command in ["on","off"]:
if command in ["on", "off"]:
is_web_search = True if command == "on" else False
print(f"# Web search {'enabled' if is_web_search else 'disabled'}")
else:
Expand All @@ -251,7 +251,7 @@ def cli():
elif question.startswith("/stream"):
command = question.split(" ")[1] if len(question.split(" ")) > 1 else ""
if command:
if command in ["on","off"]:
if command in ["on", "off"]:
streamoutput = True if command == "on" else False
print(f"# Streaming mode {'enabled' if streamoutput else 'disabled'}")
else:
Expand All @@ -261,7 +261,7 @@ def cli():

elif question.startswith("/"):
print("# Invalid command")

else:
try:
res = chatbot.chat(question, stream=True, _stream_yield_all=True, web_search=is_web_search)
Expand All @@ -278,7 +278,7 @@ def cli():
print(chunk['token'], end="", flush=True)

if web_search_hint and len(sources) > 0:
print(f"\nSources:")
print("\nSources:")
for i in range(len(sources)):
print(f" {i+1}. {sources[i]['title']} - {sources[i]['link']}")
print()
Expand Down
14 changes: 7 additions & 7 deletions src/hugchat/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
class ModelOverloadedError(Exception):
"""
HF Model Overloaded Error
Raised when hf return response `{"error":"Model is overloaded","error_type":"overloaded"}`

Raised when hf return response `{"error":"Model is overloaded", "error_type":"overloaded"}`
"""
pass


class ChatBotInitError(Exception):
"""
ChatBot Init Error

Raised when chatbot init failed
"""
pass
Expand All @@ -19,7 +19,7 @@ class ChatBotInitError(Exception):
class CreateConversationError(Exception):
"""
Create Conversation Error

Raised when create conversation failed
"""
pass
Expand All @@ -28,7 +28,7 @@ class CreateConversationError(Exception):
class InvalidConversationIDError(Exception):
"""
Invalid Conversation ID Error

Raised when using a invalid conversation id
"""
pass
Expand All @@ -37,7 +37,7 @@ class InvalidConversationIDError(Exception):
class DeleteConversationError(Exception):
"""
Delete Conversation Error

Raised when delete conversation failed
"""
pass
Expand All @@ -46,7 +46,7 @@ class DeleteConversationError(Exception):
class ChatError(Exception):
"""
Chat Error

Raised when chat failed
"""
pass
36 changes: 18 additions & 18 deletions src/hugchat/hugchat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from requests.sessions import RequestsCookieJar

from .message import Message
from .exceptions import *
from . import exceptions


class conversation:
Expand Down Expand Up @@ -92,16 +92,16 @@ def __init__(
Returns a ChatBot object
"""
if cookies is None and cookie_path == "":
raise ChatBotInitError(
raise exceptions.ChatBotInitError(
"Authentication is required now, but no cookies provided. See tutorial at https://github.com/Soulter/hugging-chat-api"
)
elif cookies is not None and cookie_path != "":
raise ChatBotInitError("Both cookies and cookie_path provided")
raise exceptions.ChatBotInitError("Both cookies and cookie_path provided")

if cookies is None and cookie_path != "":
# read cookies from path
if not os.path.exists(cookie_path):
raise ChatBotInitError(
raise exceptions.ChatBotInitError(
f"Cookie file {cookie_path} not found. Note: The file must be in JSON format and must contain a list of cookies. See more at https://github.com/Soulter/hugging-chat-api"
)
with open(cookie_path, "r", encoding="utf-8") as f:
Expand All @@ -124,7 +124,7 @@ def __init__(

self.llms = self.get_remote_llms()

if type(default_llm) == str:
if isinstance(type(default_llm), str):
self.active_model = self.get_llm_from_name(default_llm)
if self.active_model is None:
raise Exception(
Expand Down Expand Up @@ -213,7 +213,7 @@ def new_conversation(
"""
err_count = 0

if modelIndex == None:
if modelIndex is None:
model = self.active_model
else:
if modelIndex < 0 or modelIndex >= len(self.llms):
Expand Down Expand Up @@ -265,11 +265,11 @@ def new_conversation(
except BaseException as e:
err_count += 1
logging.debug(
f" Failed to create new conversation. Retrying... ({err_count})"
f" Failed to create new conversation ({e}). Retrying... ({err_count})"
)
if err_count > 5:
raise CreateConversationError(
f"Failed to create new conversation with status code: {resp.status_code}. ({err_count})"
raise exceptions.CreateConversationError(
f"Failed to create new conversation with status code: {resp.status_code}. Error: {e}. Retries: {err_count}."
)
continue

Expand All @@ -283,7 +283,7 @@ def change_conversation(self, conversation_object: conversation) -> bool:
self.current_conversation = conversation_object
return True

raise InvalidConversationIDError(
raise exceptions.InvalidConversationIDError(
"Invalid conversation id, not in conversation list."
)

Expand Down Expand Up @@ -329,7 +329,7 @@ def delete_all_conversations(self) -> None:
)

if r.status_code != 200:
raise DeleteConversationError(
raise exceptions.DeleteConversationError(
f"Failed to delete ALL conversations with status code: {r.status_code}"
)

Expand All @@ -353,7 +353,7 @@ def delete_conversation(self, conversation_object: conversation = None) -> None:
)

if r.status_code != 200:
raise DeleteConversationError(
raise exceptions.DeleteConversationError(
f"Failed to delete conversation with status code: {r.status_code}"
)
else:
Expand Down Expand Up @@ -449,7 +449,7 @@ def get_remote_llms(self) -> list:
"""

r = self.session.post(
self.hf_base_url + f"/chat/__data.json",
self.hf_base_url + "/chat/__data.json",
headers=self.get_headers(ref=False),
cookies=self.get_cookies(),
)
Expand Down Expand Up @@ -501,7 +501,7 @@ def get_remote_llms(self) -> list:
out_parameters_dict[key] = None
continue

if type(data[value]) == list:
if isinstance(type(data[value]), list):
out_parameters_dict[key] = [data[index] for index in data[value]]
continue

Expand All @@ -519,7 +519,7 @@ def get_remote_conversations(self, replace_conversation_list=True):
"""

r = self.session.post(
self.hf_base_url + f"/chat/__data.json",
self.hf_base_url + "/chat/__data.json",
headers=self.get_headers(ref=False),
cookies=self.get_cookies(),
)
Expand Down Expand Up @@ -676,7 +676,7 @@ def _stream_query(
if resp.status_code != 200:
retry_count -= 1
if retry_count <= 0:
raise ChatError(f"Failed to chat. ({resp.status_code})")
raise exceptions.ChatError(f"Failed to chat. ({resp.status_code})")

try:
for line in resp.iter_lines(decode_unicode=True):
Expand Down Expand Up @@ -715,11 +715,11 @@ def _stream_query(
except BaseException as e:
traceback.print_exc()
if "Model is overloaded" in str(e):
raise ModelOverloadedError(
raise exceptions.ModelOverloadedError(
"Model is overloaded, please try again later or switch to another model."
)
logging.debug(resp.headers)
raise ChatError(f"Failed to parse response: {res}")
raise exceptions.ChatError(f"Failed to parse response: {res}")
if break_label:
break

Expand Down
Loading
Loading