Skip to content

Commit

Permalink
lint: pep8 format
Browse files Browse the repository at this point in the history
  • Loading branch information
lss233 committed Sep 8, 2023
1 parent 5aec583 commit 0c7c811
Show file tree
Hide file tree
Showing 50 changed files with 669 additions and 285 deletions.
17 changes: 17 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# https://editorconfig.org

root = true

[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
end_of_line = lf

[*.py]
max_line_length = 120

[LICENSE]
insert_final_newline = false
57 changes: 57 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
[MASTER]
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=0


[MESSAGES CONTROL]

# Disable the message, report, category or checker with the given id(s).
disable=all

# Enable the message, report, category or checker with the given id(s).
enable=c-extension-no-member,
bad-indentation,
bare-except,
broad-except,
dangerous-default-value,
function-redefined,
len-as-condition,
line-too-long,
misplaced-future,
missing-final-newline,
mixed-line-endings,
multiple-imports,
multiple-statements,
singleton-comparison,
trailing-comma-tuple,
trailing-newlines,
trailing-whitespace,
unexpected-line-ending-format,
unused-import,
unused-variable,
wildcard-import,
wrong-import-order


[FORMAT]

# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=LF

# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$

# Maximum number of characters on a single line.
max-line-length=120

# Maximum number of lines in a module.
max-module-lines=2000


[EXCEPTIONS]

# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception
15 changes: 11 additions & 4 deletions adapter/gpt4free/g4f_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,18 @@ def g4f_check_account(account: G4fModels):

try:
response = g4f.ChatCompletion.create(
model=eval(account.model) if account.model.startswith("g4f.models.") else account.model,
provider=eval(account.provider),
messages=[vars(ChatMessage(ROLE_USER, "hello"))],
model=eval(
account.model) if account.model.startswith("g4f.models.") else account.model,
provider=eval(
account.provider),
messages=[
vars(
ChatMessage(
ROLE_USER,
"hello"))],
)
logger.debug(f"g4f model ({vars(account)}) is active. hello -> {response}")
logger.debug(
f"g4f model ({vars(account)}) is active. hello -> {response}")
except KeyError as e:
logger.debug(f"g4f model ({vars(account)}) is inactive. hello -> {e}")
return False
Expand Down
9 changes: 6 additions & 3 deletions adapter/gpt4free/gpt4free.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ async def on_reset(self):
async def ask(self, prompt: str) -> Generator[str, None, None]:
self.conversation_history.append(vars(ChatMessage(ROLE_USER, prompt)))
response = g4f.ChatCompletion.create(
model=eval(self.model.model) if self.model.model.startswith("g4f.models.") else self.model.model,
provider=eval(self.model.provider),
model=eval(
self.model.model) if self.model.model.startswith("g4f.models.") else self.model.model,
provider=eval(
self.model.provider),
messages=self.conversation_history,
)
self.conversation_history.append(vars(ChatMessage(ROLE_ASSISTANT, response)))
self.conversation_history.append(
vars(ChatMessage(ROLE_ASSISTANT, response)))
yield response
29 changes: 15 additions & 14 deletions adapter/xunfei/xinghuo.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,18 @@ async def ask(self, prompt) -> Generator[str, None, None]:

full_response = ''
async with self.client.stream(
"POST",
url="https://xinghuo.xfyun.cn/iflygpt-chat/u/chat_message/chat",
data={
'fd': self.account.fd,
'chatId': self.conversation_id,
'text': prompt,
'GtToken': self.account.GtToken,
'sid': self.account.sid,
'clientType': '1',
'isBot':'0'
},
) as req:
"POST",
url="https://xinghuo.xfyun.cn/iflygpt-chat/u/chat_message/chat",
data={
'fd': self.account.fd,
'chatId': self.conversation_id,
'text': prompt,
'GtToken': self.account.GtToken,
'sid': self.account.sid,
'clientType': '1',
'isBot': '0'
},
) as req:
async for line in req.aiter_lines():
if not line:
continue
Expand Down Expand Up @@ -113,10 +113,11 @@ async def preset_ask(self, role: str, text: str):
else:
logger.debug(f"[预设] 发送:{text}")
item = None
async for item in self.ask(text): ...
async for item in self.ask(text):
...
if item:
logger.debug(f"[预设] Chatbot 回应:{item}")

def __check_response(self, resp):
if int(resp['code']) != 0:
raise Exception(resp['msg'])
raise Exception(resp['msg'])
34 changes: 20 additions & 14 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import os
import sys

from quart import Quart

sys.path.append(os.getcwd())
from framework.accounts import account_manager

from framework.tts import AzureTTSEngine, TTSEngine, EdgeTTSEngine

import creart
from asyncio import AbstractEventLoop
import asyncio
from framework.utils.exithooks import hook
import creart
import threading
from quart import Quart
from loguru import logger

import constants
import threading
from framework.utils.exithooks import hook
from framework.tts import AzureTTSEngine, TTSEngine, EdgeTTSEngine
from framework.accounts import account_manager

loop = creart.create(AbstractEventLoop)

loop = creart.create(asyncio.AbstractEventLoop)

def setup_cloudflared(app: Quart):
logger.info("尝试开启 Cloudflare Tunnel……")
Expand All @@ -36,7 +33,12 @@ def setup_cloudflared(app: Quart):

tasks = []
if constants.config.azure:
tasks.append(loop.create_task(TTSEngine.register("azure", AzureTTSEngine(constants.config.azure))))
tasks.append(
loop.create_task(
TTSEngine.register(
"azure",
AzureTTSEngine(
constants.config.azure))))

tasks.extend(
(
Expand Down Expand Up @@ -74,6 +76,7 @@ def setup_cloudflared(app: Quart):

bots.append(start_task())


async def setup_web_service():
from framework.platforms.onebot_bot import bot, start_http_app
from framework.platforms.http_service import route as routes_http
Expand All @@ -87,11 +90,14 @@ async def setup_web_service():
routes_wecom(bot.server_app)

if constants.config.http.cloudflared:
threading.Thread(target=setup_cloudflared, args=(bot.server_app,)).start()
threading.Thread(
target=setup_cloudflared, args=(
bot.server_app,)).start()

logger.info("启动 HTTP API 中……")
for service_name, proto, uri in bot.server_app.service_routes:
logger.info(f"{service_name} 地址:{proto}://{constants.config.http.host}:{constants.config.http.port}{uri}")
logger.info(
f"{service_name} 地址:{proto}://{constants.config.http.host}:{constants.config.http.port}{uri}")
await start_http_app()


Expand Down
31 changes: 18 additions & 13 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ class HttpService(BaseModel):
)



class WecomBot(BaseModel):
corp_id: str = Field(
title="企业 ID",
Expand All @@ -123,6 +122,7 @@ class WecomBot(BaseModel):
description="企业微信应用 API 令牌 的 EncodingAESKey",
)


class QQChannel(BaseModel):
appid: str = Field(
title="Appid",
Expand All @@ -135,6 +135,7 @@ class QQChannel(BaseModel):
default=None
)


class OpenAIGPT3Params(BaseModel):
temperature: float = Field(
title="Temperature",
Expand Down Expand Up @@ -176,7 +177,10 @@ class OpenAIAuths(BaseModel):

gpt_params: OpenAIParams = OpenAIParams()

accounts: List[Union[OpenAIEmailAuth, OpenAISessionTokenAuth, OpenAIAccessTokenAuth, OpenAIAPIKey]] = []
accounts: List[Union[OpenAIEmailAuth,
OpenAISessionTokenAuth,
OpenAIAccessTokenAuth,
OpenAIAPIKey]] = []


class OpenAIAuthBase(BaseModel):
Expand Down Expand Up @@ -433,8 +437,7 @@ class TextToSpeech(BaseModel):
default: str = Field(
title="默认音色",
description="你可以在[这里](https://learn.microsoft.com/zh-CN/azure/cognitive-services/speech-service/language-support?tabs=tts#neural-voices)查看支持的音色列表",
default="zh-CN-XiaoxiaoNeural"
)
default="zh-CN-XiaoxiaoNeural")
default_voice_prefix: List[str] = Field(
title="Default Voice Prefix",
description="默认的提示音色前缀",
Expand Down Expand Up @@ -618,8 +621,7 @@ class Response(BaseModel):
error_request_too_many: str = Field(
title="请求过多时的消息",
description="糟糕!当前收到的请求太多了,我需要一段时间冷静冷静。你可以选择“重置会话”,或者过一会儿再来找我!\n预计恢复时间:{exc}\n",
default="糟糕!当前收到的请求太多了,我需要一段时间冷静冷静。你可以选择“重置会话”,或者过一会儿再来找我!\n预计恢复时间:{exc}\n"
)
default="糟糕!当前收到的请求太多了,我需要一段时间冷静冷静。你可以选择“重置会话”,或者过一会儿再来找我!\n预计恢复时间:{exc}\n")

error_request_concurrent_error: str = Field(
title="并发错误时的消息",
Expand Down Expand Up @@ -816,8 +818,7 @@ class Ratelimit(BaseModel):
warning_msg: str = Field(
title="额度警告消息",
description="\n\n警告:额度即将耗尽!\n目前已发送:{usage}条消息,最大限制为{limit}条消息/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}",
default="\n\n警告:额度即将耗尽!\n目前已发送:{usage}条消息,最大限制为{limit}条消息/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}"
)
default="\n\n警告:额度即将耗尽!\n目前已发送:{usage}条消息,最大限制为{limit}条消息/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}")
exceed: str = Field(
title="额度超限消息",
description="已达到额度限制,请等待下一小时继续和我对话。",
Expand All @@ -826,8 +827,7 @@ class Ratelimit(BaseModel):
draw_warning_msg: str = Field(
title="画图额度警告消息",
description="\n\n警告:额度即将耗尽!\n目前已画:{usage}个图,最大限制为{limit}个图/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}",
default="\n\n警告:额度即将耗尽!\n目前已画:{usage}个图,最大限制为{limit}个图/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}"
)
default="\n\n警告:额度即将耗尽!\n目前已画:{usage}个图,最大限制为{limit}个图/小时,请调整您的节奏。\n额度限制整点重置,当前服务器时间:{current_time}")
draw_exceed: str = Field(
title="画图额度超限消息",
description="已达到额度限制,请等待下一小时再使用画图功能。",
Expand Down Expand Up @@ -980,7 +980,9 @@ def load_preset(self, keyword):
try:
with open(self.prompts.keywords[keyword], "rb") as f:
if guessed_str := from_bytes(f.read()).best():
return str(guessed_str).replace('<|im_end|>', '').replace('\r', '').split('\n\n')
return str(guessed_str).replace(
'<|im_end|>', '').replace(
'\r', '').split('\n\n')
else:
raise ValueError("无法识别预设的 JSON 格式,请检查编码!")

Expand Down Expand Up @@ -1019,7 +1021,8 @@ def load_config() -> Config:
) and os.path.exists('config.json'):
logger.info("正在转换旧版配置文件……")
Config.save_config(Config.__load_json_config())
logger.warning("提示:配置文件已经修改为 config.cfg,原来的 config.json 将被重命名为 config.json.old。")
logger.warning(
"提示:配置文件已经修改为 config.cfg,原来的 config.json 将被重命名为 config.json.old。")
try:
os.rename('config.json', 'config.json.old')
except Exception as e:
Expand All @@ -1039,7 +1042,9 @@ def load_config() -> Config:
def save_config(config: Config):
try:
with open("config.cfg", "wb") as f:
parsed_str = toml.dumps(config.dict()).encode(sys.getdefaultencoding())
parsed_str = toml.dumps(
config.dict()).encode(
sys.getdefaultencoding())
f.write(parsed_str)
except Exception as e:
logger.exception(e)
Expand Down
3 changes: 2 additions & 1 deletion constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@

if config.sdwebui:
DrawingAIFactory.register("sd", SDWebUI, (config.sdwebui,))
DrawingAIFactory.register("bing", BingAdapter, ("drawing", ConversationStyle.creative))
DrawingAIFactory.register(
"bing", BingAdapter, ("drawing", ConversationStyle.creative))
DrawingAIFactory.register("openai", ChatGPTAPIAdapter, ("drawing",))


Expand Down
12 changes: 8 additions & 4 deletions framework/accounts/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def pick(self, type_: str) -> CT:
raise NoAvailableBotException(type_)

if type_ not in self._roundrobin:
self._roundrobin[type_] = itertools.cycle(self.loggedin_accounts[type_])
self._roundrobin[type_] = itertools.cycle(
self.loggedin_accounts[type_])
return next(self._roundrobin[type_])

async def login_account(self, type_: str, account: CT):
Expand All @@ -69,7 +70,8 @@ async def load_accounts(self, accounts_model: AccountsModel):
for field in accounts_model.__fields__.keys():
if field not in self.loaded_accounts:
self.loaded_accounts[field] = []
self.loaded_accounts[field].extend(accounts_model.__getattribute__(field))
self.loaded_accounts[field].extend(
accounts_model.__getattribute__(field))

tasks = []
for field in accounts_model.__fields__.keys():
Expand All @@ -79,8 +81,10 @@ async def load_accounts(self, accounts_model: AccountsModel):
)
before_logins = len(tasks)
await asyncio.gather(*tasks, return_exceptions=True)
after_logins = sum(len(models) for _, models in self.loggedin_accounts.items())
logger.debug(f"[AccountManager] 登录完毕,共有 {after_logins}/{before_logins} 个账号成功登录。")
after_logins = sum(len(models)
for _, models in self.loggedin_accounts.items())
logger.debug(
f"[AccountManager] 登录完毕,共有 {after_logins}/{before_logins} 个账号成功登录。")

@property
def loggedin_accounts(self) -> Dict[str, List[CT]]:
Expand Down
3 changes: 2 additions & 1 deletion framework/chatbot/chatgpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ async def rename_conversation(self, conversation_id: str, title: str):
def refresh_accessed_at(self):
# 删除栈顶过期的信息
current_time = datetime.datetime.now()
while len(self.accessed_at) > 0 and current_time - self.accessed_at[0] > datetime.timedelta(hours=1):
while len(self.accessed_at) > 0 and current_time - \
self.accessed_at[0] > datetime.timedelta(hours=1):
self.accessed_at.pop(0)
if len(self.accessed_at) == 0:
self.accessed_at.append(current_time)
Expand Down
Loading

0 comments on commit 0c7c811

Please sign in to comment.