just_minigpt/minigpt.py

226 lines
6.6 KiB
Python
Raw Permalink Normal View History

2024-01-01 21:06:13 +00:00
import telebot
2024-03-07 13:03:26 +00:00
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
2024-01-01 21:06:13 +00:00
### LOAD TOKEN ###
import json, os
if not os.path.exists('db.json'):
db = {"token": "None"}
js = json.dumps(db, indent=2)
with open("db.json", "w") as outfile:
outfile.write(js)
print('Input token in "None" (db.json)')
exit()
with open('db.json', 'r') as openfile:
db = json.load(openfile)
API_TOKEN = db["token"]
bot = telebot.TeleBot(API_TOKEN)
##################
2024-01-01 22:27:06 +00:00
2024-01-01 21:06:13 +00:00
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message, f"""Это подобие ChatGPT на минималках.
2024-01-01 22:27:06 +00:00
2024-01-07 21:47:54 +00:00
__ Есть 3 версии:
2024-03-07 13:03:26 +00:00
0.1 - Простейшая, быстрейшая, краткая, не помнит что вы говорили.
0.2 - Умнее, относительно быстрая, помнит что вы говорили.
/m - Выбор модели
__ Список команд:
help - Справка
i - Информация о конфигурации
m - Сменить модель
cc - Очистить контекст
p - Задать инструкцию (системную)
cp - Сбросить инструкцию
Ещё проекты: @just_openbots (тут много интересного)
{telebot.formatting.hlink("Исходный код","https://gitea.gulyaipole.fun/justuser/just_minigpt")}
""", parse_mode = "HTML")
bot.send_message(message.chat.id, f"""Также настоятельно рекомендую подписаться на канал бота: @justuser31
Обратная связь ( @just_anonchat_bot ) : {telebot.formatting.hcode(":justuser")}""", parse_mode = "HTML")
2024-01-01 21:06:13 +00:00
### MAIN ###
from api import *
from img_api import *
2024-01-01 21:06:13 +00:00
import traceback
import logging
# Заданные модели
2024-01-01 22:27:06 +00:00
setted_models = {}
# Системные инструкции
2024-01-03 01:01:08 +00:00
system_prompts = {}
# Размер изображения
img_size = {}
######### INFO AND HELP #################
2024-01-03 01:01:08 +00:00
@bot.message_handler(commands=['info','i'])
2024-01-03 01:01:08 +00:00
def info(message):
global setted_models, system_prompts
id = str(message.chat.id)
if id not in setted_models:
setted_models[id] = "0.1"
if id not in system_prompts:
prompt = "None"
else:
prompt = system_prompts[str(message.chat.id)]
bot.send_message(message.chat.id, f"""____ Информация ____
Версия: {setted_models[id]}
System-prompt: {telebot.formatting.hcode(prompt)}
""", parse_mode="HTML")
2024-01-01 22:27:06 +00:00
2024-03-07 13:03:26 +00:00
############ MODEL SELECTION ############
@bot.message_handler(commands=['m'])
2024-01-01 22:27:06 +00:00
def set_model(message):
mm = bot.send_message(message.chat.id, "Выберите новую модель:")
m_id = mm.id
bot.edit_message_text("Выберите новую модель:", chat_id = message.chat.id, message_id = m_id
, reply_markup=gen_markup(str(message.chat.id), m_id, message.chat.id))
2024-03-07 13:03:26 +00:00
def gen_markup(id, m_id, c_id):
2024-03-07 13:03:26 +00:00
markup = InlineKeyboardMarkup()
markup.row_width = 3
markup.add(InlineKeyboardButton("0.1", callback_data=id+"_0.1_"+str(m_id)+"_"+str(c_id)),
InlineKeyboardButton("0.2", callback_data=id+"_0.2_"+str(m_id)+"_"+str(c_id)),
InlineKeyboardButton("RWKV", callback_data=id+"_RWKV_"+str(m_id)+"_"+str(c_id)),
)
# InlineKeyboardButton("VER", callback_data=id+"_VER_"+str(m_id)+"_"+str(c_id)),
2024-03-07 13:03:26 +00:00
return markup
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
2024-01-01 22:27:06 +00:00
global setted_models, iddb
id, m, m_id, c_id = call.data.split("_")
m_id = int(m_id)
c_id = int(c_id)
2024-03-07 13:03:26 +00:00
2024-01-01 22:27:06 +00:00
try:
2024-03-07 13:03:26 +00:00
iddb.pop(id)
2024-01-01 22:27:06 +00:00
except:
pass
setted_models[id] = m
bot.edit_message_text(f"Успешно установлена модель {m} 🤖", chat_id = c_id, message_id = m_id)
2024-01-01 22:27:06 +00:00
############### PROMPT ###################
2024-01-01 22:27:06 +00:00
2024-03-07 13:03:26 +00:00
@bot.message_handler(commands=['p'])
2024-01-03 01:01:08 +00:00
def set_prompt(message):
global system_prompts
2024-03-07 13:03:26 +00:00
system_prompts[str(message.chat.id)] = message.text[3:]
bot.reply_to(message, "Установлен новый system-prompt 🤖")
@bot.message_handler(commands=['cprompt','cp'])
2024-01-03 01:01:08 +00:00
def clear_prompt(message):
global system_prompts
try:
system_prompts.pop(str(message.chat.id))
except:
pass
bot.reply_to(message, "System-prompt очищен 🤖")
2024-03-07 13:03:26 +00:00
@bot.message_handler(commands=['cc'])
def clear_context(message):
2024-01-07 21:47:54 +00:00
global iddb, history
try:
iddb.pop(str(message.chat.id))
except:
pass
2024-01-07 21:47:54 +00:00
try:
history[id] = []
except:
pass
bot.reply_to(message, "Контекст очищен 🤖")
2024-01-01 21:06:13 +00:00
############### IMG ####################
@bot.message_handler(commands=['img'])
def draw_image(message):
mm = bot.send_message(message.chat.id, "Генерируем изображение...")
try:
m_id = mm.id
prompt = " ".join( message.text.split()[1:] )
img_way = draw(prompt, message.chat.id)
with open(img_way, 'rb') as f:
img = f.read()
f.close()
bot.send_photo(message.chat.id, img, f'{telebot.formatting.hcode(prompt)}', parse_mode="HTML")
bot.delete_message(message.chat.id, m_id)
except:
bot.send_message(message.chat.id, "Извините, возникла непредвиденная ошибка")
##########################################
2024-01-01 21:06:13 +00:00
@bot.message_handler(func=lambda message: True)
def echo_message(message):
# Отвечаем в ЛС, либо по команде
2024-03-07 13:03:26 +00:00
if bot.get_chat(message.chat.id).type == "private" or message.text[:2] == "/a":
global setted_models, system_prompts
# Текст генерации при команде
2024-03-07 13:03:26 +00:00
if message.text[:2] == "/a":
text = message.text[3:]
else:
text = message.text
id = str(message.chat.id)
if id not in setted_models:
setted_models[id] = "0.1"
mm = bot.send_message(message.chat.id, "Печатает...")
m_id = mm.id
# Если задана инструкция
2024-03-07 13:03:26 +00:00
if id in system_prompts:
if setted_models[id] == "0.1" or setted_models[id] == "0.2":
2024-03-07 13:03:26 +00:00
prompt = '[INST]' + system_prompts[id] + '[/INST]\n\n' + text
elif setted_models[id] == "RWKV":
prompt = f'''
Instruction: {system_prompts[id]}
\nInput:{text}
\nResponse:\n'''
# Если инструкция не задана
2024-03-07 13:03:26 +00:00
else:
if setted_models[id] == "0.1" or setted_models[id] == "0.2":
prompt = text
elif setted_models[id] == "RWKV":
prompt = f'''
Input: {text}
\nResponse:\n'''
2024-03-07 13:03:26 +00:00
try:
#if 1:
2024-03-07 13:03:26 +00:00
predicted = gen(prompt, message.chat.id, setted_models[id])
except:
bot.send_message(message.chat.id, "Извините, возникла непредвиденная ошибка")
try:
bot.edit_message_text(predicted, chat_id=message.chat.id, message_id=m_id, parse_mode="Markdown")
2024-03-07 13:03:26 +00:00
except Exception as e:
bot.edit_message_text(predicted, chat_id=message.chat.id, message_id=m_id, parse_mode="HTML")
2024-03-07 13:03:26 +00:00
logging.error(traceback.format_exc())
2024-01-03 01:01:08 +00:00
#bot.delete_message(message.chat.id, st.id)
2024-01-01 21:06:13 +00:00
############
bot.infinity_polling()