diff options
Diffstat (limited to 'main.py')
| -rw-r--r-- | main.py | 270 |
1 files changed, 87 insertions, 183 deletions
@@ -4,9 +4,9 @@ import base64 import io import sys import time -import string import gconfig +import input_msg # from aiogram.methods import SendMessageDraft from datetime import datetime @@ -36,6 +36,7 @@ from callbacks import * from statistics import * from colors import * from helpers import * +from vars import * from commands import * from dotenv import load_dotenv from random import uniform, shuffle, choices @@ -90,163 +91,9 @@ async def guest_middleware(handler, event, data): config = get_user_config(user_id) prompts = SYSTEM_PROMPTS | config["prompts"] p = prompts[config["prompt"]] - # внимание внизу самая умная система осторожнеее!!1!1 - if user_id in alo_command: - if message.chat.id == alo_command[user_id]["chat_id"]: - if alo_command[user_id]["action"] == "p_name": - alo_command[user_id]["action"] = "p_prompt" - alo_command[user_id]["name"] = message.text[:16] - return await bot.edit_message_text( - text=f"установи промпт для `{alo_command[user_id]['name']}`:", - chat_id=alo_command[user_id]["chat_id"], - message_id=alo_command[user_id]["message_id"], - reply_markup=InlineKeyboardMarkup( - inline_keyboard=[ - [ - InlineKeyboardButton( - text=f"❌ отменить", callback_data=f"p_cancel%{user_id}" - ), - ], - ] - ) - ) - elif alo_command[user_id]["action"] == "p_prompt": - alo_command[user_id]["action"] = None - alo_command[user_id]["prompt"] = message.text - - if len(config["prompts"]) >= MAX_PROMPTS: - return await bot.edit_message_text( - text=f"невозможно создать новый промпт так как ты превысил лимит промптов da.", - chat_id=alo_command[user_id]["chat_id"], - message_id=alo_command[user_id]["message_id"], - reply_markup=InlineKeyboardMarkup( - inline_keyboard=[ - [ - InlineKeyboardButton( - text=f"ок", callback_data=f"user_prompts%{user_id}" - ), - ], - ] - ) - ) - - while 1: - alo_command[user_id]["id"] = ''.join(choices(string.ascii_letters, k=10)) - if alo_command[user_id]["id"] not in config["prompts"]: - break - - config["prompts"] = config["prompts"] | { - alo_command[user_id]["id"]: { - "name": alo_command[user_id]["name"], - "text": alo_command[user_id]["prompt"], - "filer": False, - "public": False - } - } - - set_user_config( - user_id, - config.get("model"), - config.get("stream", True), - config.get("call"), - config.get("prompt"), - config.get("notify"), - config.get("markdown"), - config["prompts"] - ) - - return await bot.edit_message_text( - text=f"промпт `{alo_command[user_id]['name']}` создан!", - chat_id=alo_command[user_id]["chat_id"], - message_id=alo_command[user_id]["message_id"], - reply_markup=InlineKeyboardMarkup( - inline_keyboard=[ - [ - InlineKeyboardButton( - text=f"✅ посмотреть", callback_data=f"vp%{user_id}%{alo_command[user_id]['id']}" - ), - ], - ] - ) - ) - elif alo_command[user_id]["action"] == "p_e_name": - alo_command[user_id]["action"] = None - alo_command[user_id]["name"] = message.text[:16] - - - config["prompts"] = config["prompts"] | { - alo_command[user_id]["prompt_id"]: { - "name": alo_command[user_id]["name"], - "text": config["prompts"][alo_command[user_id]["prompt_id"]]["text"], - "filer": config["prompts"][alo_command[user_id]["prompt_id"]]["filer"], - "public": config["prompts"][alo_command[user_id]["prompt_id"]]["public"], - } - } - - set_user_config( - user_id, - config.get("model"), - config.get("stream", True), - config.get("call"), - config.get("prompt"), - config.get("notify"), - config.get("markdown"), - config["prompts"] - ) - - return await bot.edit_message_text( - text=f"имя промпта было изменено на `{alo_command[user_id]['name']}`.", - chat_id=alo_command[user_id]["chat_id"], - message_id=alo_command[user_id]["message_id"], - reply_markup=InlineKeyboardMarkup( - inline_keyboard=[ - [ - InlineKeyboardButton( - text=f"✅ посмотреть", callback_data=f"vp%{user_id}%{alo_command[user_id]['prompt_id']}" - ), - ], - ] - ) - ) - elif alo_command[user_id]["action"] == "p_e_prompt": - alo_command[user_id]["action"] = None - alo_command[user_id]["prompt"] = message.text - - - config["prompts"] = config["prompts"] | { - alo_command[user_id]["prompt_id"]: { - "name": config["prompts"][alo_command[user_id]["prompt_id"]]["name"], - "text": alo_command[user_id]["prompt"], - "filer": config["prompts"][alo_command[user_id]["prompt_id"]]["filer"], - "public": config["prompts"][alo_command[user_id]["prompt_id"]]["public"], - } - } - set_user_config( - user_id, - config.get("model"), - config.get("stream", True), - config.get("call"), - config.get("prompt"), - config.get("notify"), - config.get("markdown"), - config["prompts"] - ) - - return await bot.edit_message_text( - text=f"текст промпта был изменён.", - chat_id=alo_command[user_id]["chat_id"], - message_id=alo_command[user_id]["message_id"], - reply_markup=InlineKeyboardMarkup( - inline_keyboard=[ - [ - InlineKeyboardButton( - text=f"✅ посмотреть", callback_data=f"vp%{user_id}%{alo_command[user_id]['prompt_id']}" - ), - ], - ] - ) - ) + if await input_msg.da(bot, message, user_id) != None: + return if p["filer"]: if event.guest_message: @@ -294,7 +141,7 @@ async def guest_middleware(handler, event, data): last_command_time[user_id][1] = True last_command_time[user_id][2] += [message.message_id] - await asyncio.sleep(uniform(0,0.5)) + await asyncio.sleep(uniform(0,0.2)) if event.message: try: @@ -314,11 +161,26 @@ async def guest_middleware(handler, event, data): voice = None + model = config["model"].split("*", 1) + if VOSK_API != "": if message.voice: voice = message.voice elif replied and replied.voice: voice = replied.voice + + process = { + "text": "wait", + "photo_a": "wait" if replied and replied.photo and MODELS[model[0]].get("vision", False) == False else None, + "photo": "wait" if message.photo and MODELS[model[0]][model[1]].get("vision", False) == False else None, + "stt": "wait" if voice else None, + } + + if event.message: + if (config["stream"] == "edit") or (config["stream"] == "native" and user_id == message.chat.id): + msg = await message.reply(make_graph(message, process)) + else: + gmsg = await g_answer(message, make_graph(message, process)) location = None if message.location: @@ -339,7 +201,7 @@ async def guest_middleware(handler, event, data): try: brat = await bot.download(voice, destination=buf) except Exception as e: - print(f"{YELLOW} -- voice err - {e}{RESET}") + print(f"{YELLOW} -- voice download err - {e}{RESET}") buf.seek(0) try: @@ -349,6 +211,12 @@ async def guest_middleware(handler, event, data): buf.read() ) except Exception as e: + process["stt"] = "error" + if event.message and msg: + await msg.edit_text(make_graph(message, process)) + elif event.guest_message and gmsg: + await bot.edit_message_text(text=make_graph(message, process), inline_message_id=gmsg.inline_message_id) + prompt = f"<голосовое сообщение>ошибка подключения к api stt</голосовое сообщение>{prompt}" print(f"{RED} -- voice err - {e}{RESET}") else: @@ -356,17 +224,15 @@ async def guest_middleware(handler, event, data): if message.document: - if message.document.file_size > 4096: - await mans(message, "слишком много данных не хочу отвечать☝️☝️") - return - file_bytes = io.BytesIO() - try: await bot.download(message.document, destination=file_bytes) file_bytes.seek(0) - file_content = file_bytes.read().decode("utf-8", errors="ignore") + if message.document.file_size > 9000: + file_content = file_bytes.read().decode("utf-8", errors="ignore")[:9000] + else: + file_content = file_bytes.read().decode("utf-8", errors="ignore") file_bytes.close() prompt = f"<файл>{file_content}</файл>{prompt}" @@ -376,20 +242,20 @@ async def guest_middleware(handler, event, data): return except Exception: - await mans(message, "файл не вошёл ало ошибка❌❌") + if msg: + await msg.edit_text(message, "файл не вошёл ало ошибка❌❌") return if replied and replied.document: - if replied.document.file_size > 4096: - await mans(message, "слишком много данных не хочу отвечать☝️☝️") - return - file_bytes = io.BytesIO() - try: await bot.download(replied.document, destination=file_bytes) file_bytes.seek(0) - file_content = file_bytes.read().decode("utf-8", errors="ignore") + if replied.document.file_size > 9000: + file_content = file_bytes.read().decode("utf-8", errors="ignore")[:9000] + else: + file_content = file_bytes.read().decode("utf-8", errors="ignore") + file_bytes.close() prompt = f"<файл>{file_content}</файл>{prompt}" except UnicodeDecodeError: await mans(message, "файл не вошёл❌") @@ -433,23 +299,30 @@ async def guest_middleware(handler, event, data): file_bytes = await bot.download(photo) image_bytes = file_bytes.read() b64_image = base64.b64encode(image_bytes).decode("utf-8") - images += [b64_image] + images += [{"data": b64_image, "process": "photo_a"}] except Exception as e: + process["photo_a"] = "error" + if event.message and msg: + await msg.edit_text(make_graph(message, process)) + elif event.guest_message and gmsg: + await bot.edit_message_text(text=make_graph(message, process), inline_message_id=gmsg.inline_message_id) + print(f"{RED} -- photo - {e}{RESET}") if message.photo and IMAGE_MODEL != "": try: - if event.message: - if not msg: - msg = await message.reply("👀") photo = message.photo[-1] file_bytes = await bot.download(photo) image_bytes = file_bytes.read() b64_image = base64.b64encode(image_bytes).decode("utf-8") - images += [b64_image] + images += [{"data": b64_image, "process": "photo"}] except Exception as e: - print(f"{RED} -- photo - {e}{RESET}") - + process["photo"] = "error" + if event.message and msg: + await msg.edit_text(make_graph(message, process)) + elif event.guest_message and gmsg: + await bot.edit_message_text(text=make_graph(message, process), inline_message_id=gmsg.inline_message_id) + print(f"{RED} -- photo - {e}{RESET}") prompt = f"{prompt}\n{user_text}" if replied_text: prompt = f"<ответ на>{replied_text}</ответ> {prompt}" @@ -475,7 +348,10 @@ async def guest_middleware(handler, event, data): ] ) if event.guest_message: - await g_answer(message, alloh_one_text, reply_markup=reply_markup_url) + if gmsg: + await bot.edit_message_text(text=alloh_one_text, inline_message_id=gmsg.inline_message_id, reply_markup=reply_markup_url) + else: + await g_answer(message, alloh_one_text, reply_markup=reply_markup_url) elif event.message: await message.reply_rich(InputRichMessage(markdown="# новый крутой стилёк\n*da*\n```\nтестовое сообщение врат\n```")) await message.answer(alloh_text, reply_markup=reply_markup) @@ -489,10 +365,12 @@ async def guest_middleware(handler, event, data): if stream == "edit": if event.message: + im_model = IMAGE_MODEL.split("*", 1) + tx_model = config["model"].split("*", 1) if msg: message_id = msg.message_id else: - msg = await message.reply("💬") + msg = await message.reply("💭") message_id = msg.message_id elif event.guest_message: stream = "none" @@ -517,6 +395,9 @@ async def guest_middleware(handler, event, data): user_id=user_id, message_id=message_id, images=images, + msg=msg, + process=process, + message=message ) else: result = await generate( @@ -526,6 +407,7 @@ async def guest_middleware(handler, event, data): user_id=user_id, message_id=None, images=images, + inline_id=gmsg.inline_message_id ) result = parse_tools(result) @@ -633,8 +515,23 @@ async def guest_middleware(handler, event, data): try: if event.guest_message: - await g_answer(message, result, user_id=user_id) + if len(result) > 4000: + result = result[:4000] + "...\n\n__сообщение твой большой и он сокращен__" + if gmsg: + await bot.edit_message_text(text=result, inline_message_id=gmsg.inline_message_id) + else: + await g_answer(message, result, user_id=user_id) elif event.message: + if len(result) > 4000: + if msg: + await msg.delete() + file = BufferedInputFile( + file=result.encode("utf-8"), + filename=result.replace("\n", "").replace(" ", "_")[:5] + ".txt" + ) + return await message.reply_document( + document=file + ) if msg: if stream == "native": await msg.delete() @@ -653,7 +550,12 @@ async def guest_middleware(handler, event, data): kwargs["parse_mode"] = None try: if event.guest_message: - await g_answer(message, result) + if len(result) > 4000: + result = result[:4000] + "...\n\n__сообщение твой большой и он сокращен__" + if gmsg: + await bot.edit_message_text(text=result, inline_message_id=gmsg.inline_message_id, parse_mode="None") + else: + await g_answer(message, result, parse_mode="None") elif event.message: if msg: if stream == "native": @@ -777,6 +679,7 @@ async def chosen_inline_result_handler(chosen_result: ChosenInlineResult): await bot.edit_message_text( text=error["message"], inline_message_id=inline_message_id, + parse_mode=None ) print(f"{RED} -- {error['type']} -- {error['message']}") return @@ -823,3 +726,4 @@ async def main(): if __name__ == "__main__": asyncio.run(main()) + |