mirror of
https://github.com/Balshgit/gpt_chat_bot.git
synced 2025-12-16 21:20:39 +03:00
add style check by ruff (#34)
* reformat settings * add init tests for timed lru cache * add check style by ruff
This commit is contained in:
@@ -45,7 +45,7 @@ class BotApplication:
|
||||
|
||||
async def polling(self) -> None:
|
||||
if self.settings.STAGE == "runtests":
|
||||
return None
|
||||
return
|
||||
await self.application.initialize()
|
||||
await self.application.start()
|
||||
await self.application.updater.start_polling() # type: ignore
|
||||
|
||||
@@ -23,7 +23,7 @@ async def main_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> st
|
||||
|
||||
async def about_me(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.effective_message:
|
||||
return None
|
||||
return
|
||||
await update.effective_message.reply_text(
|
||||
"Автор бота: *Дмитрий Афанасьев*\n\nTg nickname: *Balshtg*", parse_mode="MarkdownV2"
|
||||
)
|
||||
@@ -31,7 +31,7 @@ async def about_me(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
|
||||
async def about_bot(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.effective_message:
|
||||
return None
|
||||
return
|
||||
chatgpt_service = ChatGptService.build()
|
||||
model = await chatgpt_service.get_current_chatgpt_model()
|
||||
await update.effective_message.reply_text(
|
||||
@@ -44,7 +44,7 @@ async def about_bot(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
|
||||
async def website(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.effective_message:
|
||||
return None
|
||||
return
|
||||
website = urljoin(settings.DOMAIN, f"{settings.chat_prefix}/")
|
||||
await update.effective_message.reply_text(f"Веб версия: {website}")
|
||||
|
||||
@@ -53,7 +53,7 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
"""Send a message when the command /help is issued."""
|
||||
|
||||
if not update.effective_message:
|
||||
return None
|
||||
return
|
||||
reply_markup = InlineKeyboardMarkup(main_keyboard)
|
||||
await update.effective_message.reply_text(
|
||||
"Help!",
|
||||
@@ -65,7 +65,7 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
|
||||
async def ask_question(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message:
|
||||
return None
|
||||
return
|
||||
|
||||
await update.message.reply_text("Пожалуйста подождите, ответ в среднем занимает 10-15 секунд")
|
||||
|
||||
@@ -77,10 +77,10 @@ async def ask_question(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
|
||||
async def voice_recognize(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message:
|
||||
return None
|
||||
return
|
||||
await update.message.reply_text("Пожалуйста, ожидайте :)\nТрехминутная запись обрабатывается примерно 30 секунд")
|
||||
if not update.message.voice:
|
||||
return None
|
||||
return
|
||||
|
||||
sound_file = await update.message.voice.get_file()
|
||||
sound_bytes = await sound_file.download_as_bytearray()
|
||||
|
||||
@@ -70,15 +70,16 @@ class ChatGPTRepository:
|
||||
status = response.status_code
|
||||
for message in INVALID_GPT_REQUEST_MESSAGES:
|
||||
if message in response.text:
|
||||
message = f"{message}: {chatgpt_model}"
|
||||
logger.info(message, question=question, chatgpt_model=chatgpt_model)
|
||||
return message
|
||||
invalid_model_message = f"{message}: {chatgpt_model}"
|
||||
logger.info(invalid_model_message, question=question, chatgpt_model=chatgpt_model)
|
||||
return invalid_model_message
|
||||
if status != httpx.codes.OK:
|
||||
logger.info(f"got response status: {status} from chat api", response.text)
|
||||
return "Что-то пошло не так, попробуйте еще раз или обратитесь к администратору"
|
||||
return response.text
|
||||
except Exception as error:
|
||||
logger.error("error get data from chat api", error=error)
|
||||
else:
|
||||
return response.text
|
||||
return "Вообще всё сломалось :("
|
||||
|
||||
async def request_to_chatgpt_microservice(self, question: str, chatgpt_model: str) -> Response:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import subprocess # noqa
|
||||
import subprocess # noqa: S404
|
||||
import tempfile
|
||||
from concurrent.futures.thread import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
@@ -68,7 +68,7 @@ class SpeechToTextService:
|
||||
new_filename = self.filename + ".wav"
|
||||
cmd = ["ffmpeg", "-loglevel", "quiet", "-i", self.filename, "-vn", new_filename]
|
||||
try:
|
||||
subprocess.run(args=cmd) # noqa: S603
|
||||
subprocess.run(args=cmd, check=True) # noqa: S603
|
||||
logger.info("file has been converted to wav", filename=new_filename)
|
||||
except Exception as error:
|
||||
logger.error("cant convert voice", error=error, filename=self.filename)
|
||||
@@ -80,11 +80,10 @@ class SpeechToTextService:
|
||||
with AudioFile(tmpfile) as source:
|
||||
audio_text = self.recognizer.listen(source)
|
||||
try:
|
||||
text = self.recognizer.recognize_google(audio_text, language="ru-RU")
|
||||
return text
|
||||
return self.recognizer.recognize_google(audio_text, language="ru-RU")
|
||||
except SpeechRecognizerError as error:
|
||||
logger.error("error recognizing text with google", error=error)
|
||||
raise error
|
||||
raise
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -3,6 +3,8 @@ from functools import cache, wraps
|
||||
from inspect import cleandoc
|
||||
from typing import Any, Callable
|
||||
|
||||
from constants import MOSCOW_TZ
|
||||
|
||||
|
||||
def timed_lru_cache(
|
||||
microseconds: int = 0,
|
||||
@@ -15,14 +17,14 @@ def timed_lru_cache(
|
||||
update_delta = timedelta(
|
||||
microseconds=microseconds, milliseconds=milliseconds, seconds=seconds, minutes=minutes, hours=hours
|
||||
)
|
||||
next_update = datetime.utcnow() + update_delta
|
||||
next_update = datetime.now(tz=MOSCOW_TZ) + update_delta
|
||||
|
||||
cached_func = cache(func)
|
||||
|
||||
@wraps(func)
|
||||
def _wrapped(*args: Any, **kwargs: Any) -> Callable[[Any], Any]:
|
||||
nonlocal next_update
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(tz=MOSCOW_TZ)
|
||||
if now >= next_update:
|
||||
cached_func.cache_clear()
|
||||
next_update = now + update_delta
|
||||
|
||||
Reference in New Issue
Block a user