Chatbot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

251 lines
12 KiB

import asyncio
import os, sys
import time
import importlib
import re
import logging
from functools import partial
from .memory.chatlog import ChatLog
from .utilities.messages import Message
from .ai.langchain import AI
logger = logging.getLogger(__name__)
class ChatBot(object):
"""Main chatbot"""
def __init__(self, name, connection):
self.name = name
self.connection = connection
#self.say_cb = None
self.chatlog = ChatLog(self.name)
self.rooms = {}
self.queue = asyncio.Queue(maxsize=0)
self.background_tasks = set()
task = asyncio.create_task(self.worker(f'worker-{self.name}', self.queue))
self.background_tasks.add(task)
task.add_done_callback(self.background_tasks.discard)
#print(f"Hello, I'm {name}")
def init_character(self, persona, scenario, greeting, example_dialogue=[], nsfw=False, temperature=0.72):
self.persona = persona
self.scenario = scenario
self.greeting = greeting
self.example_dialogue = example_dialogue
# .replace("\\n", "\n") ??????
self.nsfw = nsfw
self.temperature = temperature
def persist(self, data_dir):
self.chatlog_path = f"{data_dir}/chatlogs"
self.images_path = f"{data_dir}/images"
self.memory_path = f"{data_dir}/memory"
os.makedirs(self.chatlog_path, exist_ok=True)
os.makedirs(self.images_path, exist_ok=True)
os.makedirs(self.memory_path, exist_ok=True)
self.chatlog.enable_logging(self.chatlog_path)
async def connect(self):
await self.connection.login()
self.connection.callbacks.add_message_callback(self.message_cb, self.redaction_cb)
await self.schedule(self.queue, print, f"Hello, I'm {self.name}")
async def disconnect(self):
# Wait until the queue is fully processed.
await self.queue.join()
# Cancel our worker tasks.
for task in self.background_tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*self.background_tasks, return_exceptions=True)
await self.connection.logout()
async def load_ai(self, available_text_endpoints, available_image_endpoints):
# module_text_ai = importlib.import_module("bot.ai.langchain", package=None)
# self.text_ai = module_text_ai.AI(self)
from .wrappers.langchain_koboldcpp import KoboldCpp
from .wrappers.runpod_text import RunpodTextWrapper
text_generators = {}
for text_endpoint in sorted(available_text_endpoints, key=lambda d: d['id']):
if text_endpoint['service'] == "koboldcpp":
text_generator = KoboldCpp(temperature=self.temperature, endpoint_url=text_endpoint['endpoint'], stop=['<|endoftext|>'])
elif text_endpoint['service'] == "stablehorde":
pass
elif text_endpoint['service'] == "runpod":
text_generator = RunpodTextWrapper(text_endpoint['api_key'], endpoint=text_endpoint['endpoint'])
pass
else:
raise ValueError(f"no text service with the name \"{service_text}\"")
i = text_endpoint['id']
text_generators[i] = text_generator
from .wrappers.runpod_image import RunpodImageWrapper
from .wrappers.runpod_image_automatic1111 import RunpodImageAutomaticWrapper
image_generators = {}
for image_endpoint in sorted(available_image_endpoints, key=lambda d: d['id']):
if image_endpoint['service'] == "runpod":
image_generator = RunpodImageWrapper(image_endpoint['api_key'])
elif image_endpoint['service'] == "runpod-automatic1111":
image_generator = RunpodImageAutomaticWrapper(image_endpoint['api_key'])
elif image_endpoint['service'] == "stablehorde":
#image_generator = StableHordeImageWrapper(image_endpoint['api_key'])
pass
else:
raise ValueError(f"no image service with the name \"{service_image}\"")
i = image_endpoint['id']
def make_fn_generate_image_for_endpoint(wrapper, endpoint):
async def generate_image(input_prompt, negative_prompt, typing_fn, timeout=180):
return await wrapper.generate(input_prompt, negative_prompt, endpoint, typing_fn, timeout)
return generate_image
#self.image_generators.append(generate_image)
image_generators[i] = make_fn_generate_image_for_endpoint(image_generator, image_endpoint['endpoint'])
self.ai = AI(self, text_generators, image_generators)
async def message_cb(self, room, event) -> None:
message = Message.from_matrix(room, event)
reply_fn = partial(self.connection.send_message, room.room_id)
typing_fn = lambda : self.connection.room_typing(room.room_id, True, 15000)
if not room.room_id in self.rooms:
self.rooms[room.room_id] = {}
# ToDo: set ticks 0 / start
if not self.connection.synced:
self.chatlog.save(message, False)
return
if message.is_from(self.connection.user_id):
"""Skip messages from ouselves"""
self.chatlog.save(message)
return
if event.decrypted:
encrypted_symbol = "🛡 "
else:
encrypted_symbol = "⚠️ "
print(
f"{room.display_name} |{encrypted_symbol}| {room.user_name(event.sender)}: {event.body}"
)
print(repr(room))
print(repr(event))
if room.is_named:
print(f"room.display_name: {room.display_name}")
if room.is_group:
print(f"room.group_name(): {room.group_name()}")
print(f"room.joined_count: {room.joined_count}")
print(f"room.member_count: {room.member_count}")
print(f"room.encrypted: {room.encrypted}")
print(f"room.users: {room.users}")
print(f"room.room_id: {room.room_id}")
if self.name.casefold() == message.user_name.casefold():
"""Bot and user have the same name"""
message.user_name += "2" # or simply "You"
message.user_name = message.user_name.title()
if hasattr(self, "owner"):
if not message.is_from(self.owner):
self.chatlog.save(message)
return
if "disabled" in self.rooms[message.room_id] and self.rooms[message.room_id]["disabled"] == True and not message.message.startswith('!start'):
return
await self.connection.room_read_markers(room.room_id, event.event_id, event.event_id)
if message.is_command():
await self.schedule(self.queue, self.process_command, message, reply_fn, typing_fn)
# elif re.search("^(?=.*\bsend\b)(?=.*\bpicture\b).*$", event.body, flags=re.IGNORECASE):
# # send, mail, drop, snap picture, photo, image, portrait
else:
await self.schedule(self.queue, self.process_message, message, reply_fn, typing_fn)
self.chatlog.save(message)
async def redaction_cb(self, room, event) -> None:
self.chatlog.remove_message_by_id(event.event_id)
async def process_command(self, message, reply_fn, typing_fn):
if message.message.startswith("!replybot"):
await reply_fn("Hello World")
elif re.search("(?s)^!image(?P<num>[0-9])?(\s(?P<cmd>.*))?$", message.message, flags=re.DOTALL):
m = re.search("(?s)^!image(?P<num>[0-9])?(\s(?P<cmd>.*))?$", message.message, flags=re.DOTALL)
if m['num']:
num = int(m['num'])
else:
num = 1
if m['cmd']:
prompt = m['cmd'].strip()
else:
prompt = "a beautiful woman"
negative_prompt = "out of frame, (ugly:1.3), (fused fingers), (too many fingers), (bad anatomy:1.5), (watermark:1.5), (words), letters, untracked eyes, asymmetric eyes, floating head, (logo:1.5), (bad hands:1.3), (mangled hands:1.2), (missing hands), (missing arms), backward hands, floating jewelry, unattached jewelry, floating head, doubled head, unattached head, doubled head, head in body, (misshapen body:1.1), (badly fitted headwear:1.2), floating arms, (too many arms:1.5), limbs fused with body, (facial blemish:1.5), badly fitted clothes, imperfect eyes, untracked eyes, crossed eyes, hair growing from clothes, partial faces, hair not attached to head"
#"anime, cartoon, penis, fake, drawing, illustration, boring, 3d render, long neck, out of frame, extra fingers, mutated hands, monochrome, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), ((ugly)), blurry, ((bad anatomy)), (((bad proportions))), ((extra limbs)), cloned face, glitchy, bokeh, (((long neck))), 3D, 3DCG, cgstation, red eyes, multiple subjects, extra heads, close up, watermarks, logo"
#"ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, disfigured, deformed, body out of frame, bad anatomy, watermark, signature, cut off, low contrast, underexposed, overexposed, bad art, beginner, amateur, distorted face"
#"ugly, deformed, out of frame"
try:
output = await self.ai.image_generators[num](prompt, negative_prompt, typing_fn)
await self.connection.room_typing(message.room_id, False)
for imagefile in output:
await self.connection.send_image(message.room_id, imagefile)
except (KeyError, IndexError, ValueError) as err:
#await self.connection.room_typing(message.room_id, False)
errormessage = f"<ERROR> {err=}, {type(err)=}"
logger.error(errormessage)
await reply_fn(errormessage)
elif message.message.startswith("!image_negative_prompt"):
self.negative_prompt = message.message.removeprefix('!image_negative_prompt').strip()
elif message.message.startswith('!temperature'):
self.temperature = float( message.message.removeprefix('!temperature').strip() )
elif message.message.startswith('!begin'):
self.chatlog.clear(message.room_id)
# ToDo reset time / ticks
await reply_fn(self.greeting)
elif message.message.startswith('!start'):
self.rooms[message.room_id]["disabled"] = False
elif message.message.startswith('!stop'):
self.rooms[message.room_id]["disabled"] = True
elif message.message.startswith('!!'):
if self.chatlog.chat_history_len(message.room_id) > 2:
for _ in range(2):
old_message = self.chatlog.remove_message_in_room(message.room_id, 1)
await self.connection.room_redact(message.room_id, old_message.event_id, reason="user-request")
message = self.chatlog.get_last_message(message.room_id)
async def process_message(self, message, reply_fn, typing_fn):
output = await self.ai.generate_roleplay(message, reply_fn, typing_fn)
# typing false
await reply_fn(output)
async def worker(self, name: str, q: asyncio.Queue) -> None:
while True:
cb, args, kwargs = await q.get()
start = time.perf_counter()
logger.info("queued task started")
if asyncio.iscoroutinefunction(cb):
await cb(*args, **kwargs)
else:
cb(*args, **kwargs)
q.task_done()
elapsed = time.perf_counter() - start
logger.info(f"Queued task done in {elapsed:0.5f} seconds.")
logger.debug("queue item processed")
async def schedule(self, q: asyncio.Queue, cb, *args, **kwargs) -> None:
logger.info(f"queuing task")
await q.put((cb, args, kwargs))
#q.put_nowait((cb, args, kwargs))
async def schedule_task(self, done_callback, cb, *args, **kwargs):
logger.info(f"creating background task")
task = asyncio.create_task(cb(*args, **kwargs))
task.add_done_callback(done_callback)
self.background_tasks.add(task)
task.add_done_callback(self.background_tasks.discard)