diff --git a/api/__init__.py b/api/__init__.py deleted file mode 100644 index 48c45bd1..00000000 --- a/api/__init__.py +++ /dev/null @@ -1,2032 +0,0 @@ -###### -# Project : lollms-webui -# File : api/__init__.py -# Author : ParisNeo with the help of the community -# license : Apache 2.0 -# Description : -# A simple api to communicate with lollms-webui and its models. -###### -from flask import request -from datetime import datetime -from api.db import DiscussionsDB, Discussion -from pathlib import Path -from lollms.config import InstallOption -from lollms.types import MSG_TYPE, SENDER_TYPES -from lollms.extension import LOLLMSExtension, ExtensionBuilder -from lollms.personality import AIPersonality, PersonalityBuilder -from lollms.binding import LOLLMSConfig, BindingBuilder, LLMBinding, ModelBuilder, BindingType -from lollms.paths import LollmsPaths -from lollms.helpers import ASCIIColors, trace_exception -from lollms.com import NotificationType, NotificationDisplayType, LoLLMsCom -from lollms.app import LollmsApplication -from lollms.utilities import File64BitsManager, PromptReshaper, PackageManager, find_first_available_file_index, terminate_thread -try: - from lollms.media import WebcamImageSender, AudioRecorder - Media_on=True -except: - ASCIIColors.warning("Couldn't load media library.\nYou will not be able to perform any of the media linked operations. please verify the logs and install any required installations") - Media_on=False - -from safe_store import TextVectorizer, VectorizationMethod, VisualizationMethod -import threading -from tqdm import tqdm -import traceback -import sys -import gc -import ctypes -from functools import partial -import json -import shutil -import re -import string -import requests -from datetime import datetime -from typing import List, Tuple -import time -import numpy as np -from lollms.utilities import find_first_available_file_index, convert_language_name - -if not PackageManager.check_package_installed("requests"): - PackageManager.install_package("requests") -if not PackageManager.check_package_installed("bs4"): - PackageManager.install_package("beautifulsoup4") -import requests -from flask_socketio import SocketIO -from bs4 import BeautifulSoup - - - - - -__author__ = "parisneo" -__github__ = "https://github.com/ParisNeo/lollms-webui" -__copyright__ = "Copyright 2023, " -__license__ = "Apache 2.0" - - - -import subprocess -import pkg_resources - - -# =========================================================== -# Manage automatic install scripts - -def is_package_installed(package_name): - try: - dist = pkg_resources.get_distribution(package_name) - return True - except pkg_resources.DistributionNotFound: - return False - - -def install_package(package_name): - try: - # Check if the package is already installed - __import__(package_name) - print(f"{package_name} is already installed.") - except ImportError: - print(f"{package_name} is not installed. Installing...") - - # Install the package using pip - subprocess.check_call(["pip", "install", package_name]) - - print(f"{package_name} has been successfully installed.") - - -def parse_requirements_file(requirements_path): - with open(requirements_path, 'r') as f: - for line in f: - line = line.strip() - if not line or line.startswith('#'): - # Skip empty and commented lines - continue - package_name, _, version_specifier = line.partition('==') - package_name, _, version_specifier = line.partition('>=') - if is_package_installed(package_name): - # The package is already installed - print(f"{package_name} is already installed.") - else: - # The package is not installed, install it - if version_specifier: - install_package(f"{package_name}{version_specifier}") - else: - install_package(package_name) - - -# =========================================================== - - -class LoLLMsAPI(LollmsApplication): - def __init__(self, config:LOLLMSConfig, socketio:SocketIO, config_file_path:str, lollms_paths: LollmsPaths) -> None: - - self.sio = socketio - super().__init__("Lollms_webui",config, lollms_paths, callback=self.process_chunk, socketio=socketio) - - - self.busy = False - self.nb_received_tokens = 0 - - self.config_file_path = config_file_path - self.cancel_gen = False - - - - # Keeping track of current discussion and message - self._current_user_message_id = 0 - self._current_ai_message_id = 0 - self._message_id = 0 - - self.db_path = config["db_path"] - if Path(self.db_path).is_absolute(): - # Create database object - self.db = DiscussionsDB(self.db_path) - else: - # Create database object - self.db = DiscussionsDB(self.lollms_paths.personal_databases_path/self.db_path) - - # If the database is empty, populate it with tables - ASCIIColors.info("Checking discussions database... ",end="") - self.db.create_tables() - self.db.add_missing_columns() - ASCIIColors.success("ok") - - - - # prepare vectorization - if self.config.data_vectorization_activate and self.config.use_discussions_history: - try: - ASCIIColors.yellow("Loading long term memory") - folder = self.lollms_paths.personal_databases_path/"vectorized_dbs" - folder.mkdir(parents=True, exist_ok=True) - self.build_long_term_skills_memory() - ASCIIColors.yellow("Ready") - - except Exception as ex: - trace_exception(ex) - self.long_term_memory = None - else: - self.long_term_memory = None - - # This is used to keep track of messages - self.download_infos={} - - self.connections = { - 0:{ - "current_discussion":None, - "generated_text":"", - "cancel_generation": False, - "generation_thread": None, - "processing":False, - "schedule_for_deletion":False, - "continuing": False, - "first_chunk": True, - } - } - if Media_on: - try: - self.webcam = WebcamImageSender(socketio,lollmsCom=self) - except: - self.webcam = None - try: - self.rec_output_folder = lollms_paths.personal_outputs_path/"audio_rec" - self.rec_output_folder.mkdir(exist_ok=True, parents=True) - self.summoned = False - self.audio_cap = AudioRecorder(socketio,self.rec_output_folder/"rt.wav", callback=self.audio_callback,lollmsCom=self) - except: - self.audio_cap = None - self.rec_output_folder = None - else: - self.webcam = None - self.rec_output_folder = None - - # ========================================================================================= - # Socket IO stuff - # ========================================================================================= - @socketio.on('connect') - def connect(): - #Create a new connection information - self.connections[request.sid] = { - "current_discussion":self.db.load_last_discussion(), - "generated_text":"", - "continuing": False, - "first_chunk": True, - "cancel_generation": False, - "generation_thread": None, - "processing":False, - "schedule_for_deletion":False - } - self.sio.emit('connected', room=request.sid) - ASCIIColors.success(f'Client {request.sid} connected') - - @socketio.on('disconnect') - def disconnect(): - try: - self.sio.emit('disconnected', room=request.sid) - if self.connections[request.sid]["processing"]: - self.connections[request.sid]["schedule_for_deletion"]=True - else: - del self.connections[request.sid] - except Exception as ex: - pass - - ASCIIColors.error(f'Client {request.sid} disconnected') - - - # ---- chatbox ----- - - @socketio.on('add_webpage') - def add_webpage(data): - ASCIIColors.yellow("Scaping web page") - url = data['url'] - index = find_first_available_file_index(self.lollms_paths.personal_uploads_path,"web_",".txt") - file_path=self.lollms_paths.personal_uploads_path/f"web_{index}.txt" - self.scrape_and_save(url=url, file_path=file_path) - try: - if not self.personality.processor is None: - self.personality.processor.add_file(file_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('web_page_added', {'status':True,}) - else: - self.personality.add_file(file_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('web_page_added', {'status':True}) - except Exception as e: - # Error occurred while saving the file - socketio.emit('web_page_added', {'status':False}) - - @socketio.on('take_picture') - def take_picture(): - try: - self.info("Loading camera") - if not PackageManager.check_package_installed("cv2"): - PackageManager.install_package("opencv-python") - import cv2 - cap = cv2.VideoCapture(0) - n = time.time() - self.info("Stand by for taking a shot in 2s") - while(time.time()-n<2): - _, frame = cap.read() - _, frame = cap.read() - cap.release() - self.info("Shot taken") - cam_shot_path = self.lollms_paths.personal_uploads_path/"camera_shots" - cam_shot_path.mkdir(parents=True, exist_ok=True) - filename = find_first_available_file_index(cam_shot_path, "cam_shot_", extension=".png") - save_path = cam_shot_path/f"cam_shot_{filename}.png" # Specify the desired folder path - - try: - cv2.imwrite(str(save_path), frame) - if not self.personality.processor is None: - self.info("Sending file to scripted persona") - self.personality.processor.add_file(save_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('picture_taken', {'status':True, 'progress': 100}) - self.info("File sent to scripted persona") - else: - self.info("Sending file to persona") - self.personality.add_file(save_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('picture_taken', {'status':True, 'progress': 100}) - self.info("File sent to persona") - except Exception as e: - trace_exception(e) - # Error occurred while saving the file - socketio.emit('picture_taken', {'status':False, 'error': str(e)}) - - - except Exception as ex: - trace_exception(ex) - self.error("Couldn't use the webcam") - - @socketio.on('create_empty_message') - def create_empty_message(data): - client_id = request.sid - type = data.get("type",0) - message = data.get("message","") - if type==0: - ASCIIColors.info(f"Building empty User message requested by : {client_id}") - # send the message to the bot - print(f"Creating an empty message for AI answer orientation") - if self.connections[client_id]["current_discussion"]: - if not self.model: - self.error("No model selected. Please make sure you select a model before starting generation", client_id = client_id) - return - self.new_message(client_id, self.config.user_name, message, sender_type=SENDER_TYPES.SENDER_TYPES_USER, open=True) - self.sio.sleep(0.01) - else: - if self.personality is None: - self.warning("Select a personality") - return - ASCIIColors.info(f"Building empty AI message requested by : {client_id}") - # send the message to the bot - print(f"Creating an empty message for AI answer orientation") - if self.connections[client_id]["current_discussion"]: - if not self.model: - self.error("No model selected. Please make sure you select a model before starting generation", client_id=client_id) - return - self.new_message(client_id, self.personality.name, "[edit this to put your ai answer start]", open=True) - self.sio.sleep(0.01) - - # -- interactive view -- - - @socketio.on('start_webcam_video_stream') - def start_webcam_video_stream(): - self.info("Starting video capture") - self.webcam.start_capture() - - @socketio.on('stop_webcam_video_stream') - def stop_webcam_video_stream(): - self.info("Stopping video capture") - self.webcam.stop_capture() - - @socketio.on('start_audio_stream') - def start_audio_stream(): - self.info("Starting audio capture") - self.audio_cap.start_recording() - - @socketio.on('stop_audio_stream') - def stop_audio_stream(): - self.info("Stopping audio capture") - self.audio_cap.stop_recording() - - - # -- vectorization -- - - - @socketio.on('upgrade_vectorization') - def upgrade_vectorization(): - if self.config.data_vectorization_activate and self.config.use_discussions_history: - try: - self.sio.emit('show_progress') - self.sio.sleep(0) - ASCIIColors.yellow("0- Detected discussion vectorization request") - folder = self.lollms_paths.personal_databases_path/"vectorized_dbs" - folder.mkdir(parents=True, exist_ok=True) - self.build_long_term_skills_memory() - - ASCIIColors.yellow("1- Exporting discussions") - discussions = self.db.export_all_as_markdown_list_for_vectorization() - ASCIIColors.yellow("2- Adding discussions to vectorizer") - index = 0 - nb_discussions = len(discussions) - for (title,discussion) in tqdm(discussions): - self.sio.emit('update_progress',{'value':int(100*(index/nb_discussions))}) - self.sio.sleep(0) - index += 1 - if discussion!='': - skill = self.learn_from_discussion(title, discussion) - self.long_term_memory.add_document(title, skill, chunk_size=self.config.data_vectorization_chunk_size, overlap_size=self.config.data_vectorization_overlap_size, force_vectorize=False, add_as_a_bloc=False) - ASCIIColors.yellow("3- Indexing database") - self.long_term_memory.index() - ASCIIColors.yellow("4- Saving database") - self.long_term_memory.save_to_json() - - if self.config.data_vectorization_visualize_on_vectorization: - self.long_term_memory.show_document(show_interactive_form=True) - ASCIIColors.yellow("Ready") - except Exception as ex: - ASCIIColors.error(f"Couldn't vectorize database:{ex}") - self.sio.emit('hide_progress') - self.sio.sleep(0) - - - - # -- model -- - - @socketio.on('cancel_install') - def cancel_install(data): - try: - model_name = data["model_name"] - binding_folder = data["binding_folder"] - model_url = data["model_url"] - signature = f"{model_name}_{binding_folder}_{model_url}" - self.download_infos[signature]["cancel"]=True - self.sio.emit('canceled', { - 'status': True - }, - room=request.sid - ) - except Exception as ex: - trace_exception(ex) - self.sio.emit('canceled', { - 'status': False, - 'error':str(ex) - }, - room=request.sid - ) - - @socketio.on('install_model') - def install_model(data): - client_id = request.sid - tpe = threading.Thread(target=self.binding.install_model, args=(data["type"], data["path"], data["variant_name"], client_id)) - tpe.start() - - @socketio.on('uninstall_model') - def uninstall_model(data): - model_path = data['path'] - model_type:str=data.get("type","ggml") - installation_dir = self.binding.searchModelParentFolder(model_path) - - binding_folder = self.config["binding_name"] - if model_type=="gptq" or model_type=="awq": - filename = model_path.split("/")[4] - installation_path = installation_dir / filename - else: - filename = Path(model_path).name - installation_path = installation_dir / filename - model_name = filename - - if not installation_path.exists(): - socketio.emit('uninstall_progress',{ - 'status': False, - 'error': 'The model does not exist', - 'model_name' : model_name, - 'binding_folder' : binding_folder - }, room=request.sid) - try: - if not installation_path.exists(): - # Try to find a version - model_path = installation_path.name.lower().replace("-ggml","").replace("-gguf","") - candidates = [m for m in installation_dir.iterdir() if model_path in m.name] - if len(candidates)>0: - model_path = candidates[0] - installation_path = model_path - - if installation_path.is_dir(): - shutil.rmtree(installation_path) - else: - installation_path.unlink() - socketio.emit('uninstall_progress',{ - 'status': True, - 'error': '', - 'model_name' : model_name, - 'binding_folder' : binding_folder - }, room=request.sid) - except Exception as ex: - trace_exception(ex) - ASCIIColors.error(f"Couldn't delete {installation_path}, please delete it manually and restart the app") - socketio.emit('uninstall_progress',{ - 'status': False, - 'error': f"Couldn't delete {installation_path}, please delete it manually and restart the app", - 'model_name' : model_name, - 'binding_folder' : binding_folder - }, room=request.sid) - - - # -- discussion -- - - @socketio.on('new_discussion') - def new_discussion(data): - ASCIIColors.yellow("New descussion requested") - client_id = request.sid - title = data["title"] - if self.connections[client_id]["current_discussion"] is not None: - if self.long_term_memory is not None: - title, content = self.connections[client_id]["current_discussion"].export_for_vectorization() - skill = self.learn_from_discussion(title, content) - self.long_term_memory.add_document(title, skill, chunk_size=self.config.data_vectorization_chunk_size, overlap_size=self.config.data_vectorization_overlap_size, force_vectorize=False, add_as_a_bloc=False, add_to_index=True) - ASCIIColors.yellow("4- Saving database") - self.long_term_memory.save_to_json() - self.connections[client_id]["current_discussion"] = self.db.create_discussion(title) - # Get the current timestamp - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - - # Return a success response - if self.connections[client_id]["current_discussion"] is None: - self.connections[client_id]["current_discussion"] = self.db.load_last_discussion() - - if self.personality.welcome_message!="": - if self.config.force_output_language_to_be and self.config.force_output_language_to_be.lower().strip() !="english": - welcome_message = self.personality.fast_gen(f"!@>instruction: Translate the following text to {self.config.force_output_language_to_be.lower()}:\n{self.personality.welcome_message}\n!@>translation:") - else: - welcome_message = self.personality.welcome_message - - message = self.connections[client_id]["current_discussion"].add_message( - message_type = MSG_TYPE.MSG_TYPE_FULL.value if self.personality.include_welcome_message_in_disucssion else MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_AI.value, - sender_type = SENDER_TYPES.SENDER_TYPES_AI.value, - sender = self.personality.name, - content = welcome_message, - metadata = None, - rank = 0, - parent_message_id = -1, - binding = self.config.binding_name, - model = self.config.model_name, - personality = self.config.personalities[self.config.active_personality_id], - created_at=None, - finished_generating_at=None - ) - - self.sio.emit('discussion_created', - {'id':self.connections[client_id]["current_discussion"].discussion_id}, - room=client_id - ) - else: - self.sio.emit('discussion_created', - {'id':0}, - room=client_id - ) - - @socketio.on('load_discussion') - def load_discussion(data): - client_id = request.sid - ASCIIColors.yellow(f"Loading discussion for client {client_id} ... ", end="") - if "id" in data: - discussion_id = data["id"] - self.connections[client_id]["current_discussion"] = Discussion(discussion_id, self.db) - else: - if self.connections[client_id]["current_discussion"] is not None: - discussion_id = self.connections[client_id]["current_discussion"].discussion_id - self.connections[client_id]["current_discussion"] = Discussion(discussion_id, self.db) - else: - self.connections[client_id]["current_discussion"] = self.db.create_discussion() - messages = self.connections[client_id]["current_discussion"].get_messages() - jsons = [m.to_json() for m in messages] - self.sio.emit('discussion', - jsons, - room=client_id - ) - ASCIIColors.green(f"ok") - - # -- upload file -- - - @socketio.on('upload_file') - def upload_file(data): - ASCIIColors.yellow("Uploading file") - file = data['file'] - filename = file.filename - save_path = self.lollms_paths.personal_uploads_path/filename # Specify the desired folder path - - try: - if not self.personality.processor is None: - file.save(save_path) - self.personality.processor.add_file(save_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('progress', {'status':True, 'progress': 100}) - - else: - file.save(save_path) - self.personality.add_file(save_path, partial(self.process_chunk, client_id = request.sid)) - # File saved successfully - socketio.emit('progress', {'status':True, 'progress': 100}) - except Exception as e: - # Error occurred while saving the file - socketio.emit('progress', {'status':False, 'error': str(e)}) - - # -- personality -- - - @socketio.on('get_personality_files') - def get_personality_files(data): - client_id = request.sid - self.connections[client_id]["generated_text"] = "" - self.connections[client_id]["cancel_generation"] = False - - try: - self.personality.setCallback(partial(self.process_chunk,client_id = client_id)) - except Exception as ex: - trace_exception(ex) - - @socketio.on('send_file_chunk') - def send_file_chunk(data): - client_id = request.sid - filename = data['filename'] - chunk = data['chunk'] - offset = data['offset'] - is_last_chunk = data['isLastChunk'] - chunk_index = data['chunkIndex'] - path:Path = self.lollms_paths.personal_uploads_path / self.personality.personality_folder_name - path.mkdir(parents=True, exist_ok=True) - file_path = path / data["filename"] - # Save the chunk to the server or process it as needed - # For example: - if chunk_index==0: - with open(file_path, 'wb') as file: - file.write(chunk) - else: - with open(file_path, 'ab') as file: - file.write(chunk) - - if is_last_chunk: - print('File received and saved successfully') - if self.personality.processor: - result = self.personality.processor.add_file(file_path, partial(self.process_chunk, client_id=client_id)) - else: - result = self.personality.add_file(file_path, partial(self.process_chunk, client_id=client_id)) - - self.sio.emit('file_received', {'status': True, 'filename': filename}) - else: - # Request the next chunk from the client - self.sio.emit('request_next_chunk', {'offset': offset + len(chunk)}) - - @socketio.on('execute_command') - def execute_command(data): - client_id = request.sid - command = data["command"] - parameters = data["parameters"] - if self.personality.processor is not None: - self.start_time = datetime.now() - self.personality.processor.callback = partial(self.process_chunk, client_id=client_id) - self.personality.processor.execute_command(command, parameters) - else: - self.warning("Non scripted personalities do not support commands",client_id=client_id) - self.close_message(client_id) - - # -- misc -- - @self.sio.on('execute_python_code') - def execute_python_code(data): - """Executes Python code and returns the output.""" - client_id = request.sid - code = data["code"] - # Import the necessary modules. - import io - import sys - import time - - # Create a Python interpreter. - interpreter = io.StringIO() - sys.stdout = interpreter - - # Execute the code. - start_time = time.time() - exec(code) - end_time = time.time() - - # Get the output. - output = interpreter.getvalue() - self.sio.emit("execution_output", {"output":output,"execution_time":end_time - start_time}, room=client_id) - - - # -- generation -- - - @socketio.on('cancel_generation') - def cancel_generation(): - client_id = request.sid - self.cancel_gen = True - #kill thread - ASCIIColors.error(f'Client {request.sid} requested cancelling generation') - terminate_thread(self.connections[client_id]['generation_thread']) - ASCIIColors.error(f'Client {request.sid} canceled generation') - self.busy=False - - @self.sio.on('cancel_text_generation') - def cancel_text_generation(data): - client_id = request.sid - self.connections[client_id]["requested_stop"]=True - print(f"Client {client_id} requested canceling generation") - self.sio.emit("generation_canceled", {"message":"Generation is canceled."}, room=client_id) - self.sio.sleep(0) - self.busy = False - - # A copy of the original lollms-server generation code needed for playground - @self.sio.on('generate_text') - def handle_generate_text(data): - client_id = request.sid - self.cancel_gen = False - ASCIIColors.info(f"Text generation requested by client: {client_id}") - if self.busy: - self.sio.emit("busy", {"message":"I am busy. Come back later."}, room=client_id) - self.sio.sleep(0) - ASCIIColors.warning(f"OOps request {client_id} refused!! Server busy") - return - def generate_text(): - self.busy = True - try: - model = self.model - self.connections[client_id]["is_generating"]=True - self.connections[client_id]["requested_stop"]=False - prompt = data['prompt'] - tokenized = model.tokenize(prompt) - personality_id = data.get('personality', -1) - - n_crop = data.get('n_crop', len(tokenized)) - if n_crop!=-1: - prompt = model.detokenize(tokenized[-n_crop:]) - - n_predicts = data["n_predicts"] - parameters = data.get("parameters",{ - "temperature":self.config["temperature"], - "top_k":self.config["top_k"], - "top_p":self.config["top_p"], - "repeat_penalty":self.config["repeat_penalty"], - "repeat_last_n":self.config["repeat_last_n"], - "seed":self.config["seed"] - }) - - if personality_id==-1: - # Raw text generation - self.answer = {"full_text":""} - def callback(text, message_type: MSG_TYPE, metadata:dict={}): - if message_type == MSG_TYPE.MSG_TYPE_CHUNK: - ASCIIColors.success(f"generated:{len(self.answer['full_text'].split())} words", end='\r') - if text is not None: - self.answer["full_text"] = self.answer["full_text"] + text - self.sio.emit('text_chunk', {'chunk': text, 'type':MSG_TYPE.MSG_TYPE_CHUNK.value}, room=client_id) - self.sio.sleep(0) - if client_id in self.connections:# Client disconnected - if self.connections[client_id]["requested_stop"]: - return False - else: - return True - else: - return False - - tk = model.tokenize(prompt) - n_tokens = len(tk) - fd = model.detokenize(tk[-min(self.config.ctx_size-n_predicts,n_tokens):]) - - try: - ASCIIColors.print("warming up", ASCIIColors.color_bright_cyan) - - generated_text = model.generate(fd, - n_predict=n_predicts, - callback=callback, - temperature = parameters["temperature"], - top_k = parameters["top_k"], - top_p = parameters["top_p"], - repeat_penalty = parameters["repeat_penalty"], - repeat_last_n = parameters["repeat_last_n"], - seed = parameters["seed"], - ) - ASCIIColors.success(f"\ndone") - - if client_id in self.connections: - if not self.connections[client_id]["requested_stop"]: - # Emit the generated text to the client - self.sio.emit('text_generated', {'text': generated_text}, room=client_id) - self.sio.sleep(0) - except Exception as ex: - self.sio.emit('generation_error', {'error': str(ex)}, room=client_id) - ASCIIColors.error(f"\ndone") - self.busy = False - else: - try: - personality: AIPersonality = self.personalities[personality_id] - ump = self.config.discussion_prompt_separator +self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.personality.user_message_prefix - personality.model = model - cond_tk = personality.model.tokenize(personality.personality_conditioning) - n_cond_tk = len(cond_tk) - # Placeholder code for text generation - # Replace this with your actual text generation logic - print(f"Text generation requested by client: {client_id}") - - self.answer["full_text"] = '' - full_discussion_blocks = self.connections[client_id]["full_discussion_blocks"] - - if prompt != '': - if personality.processor is not None and personality.processor_cfg["process_model_input"]: - preprocessed_prompt = personality.processor.process_model_input(prompt) - else: - preprocessed_prompt = prompt - - if personality.processor is not None and personality.processor_cfg["custom_workflow"]: - full_discussion_blocks.append(ump) - full_discussion_blocks.append(preprocessed_prompt) - - else: - - full_discussion_blocks.append(ump) - full_discussion_blocks.append(preprocessed_prompt) - full_discussion_blocks.append(personality.link_text) - full_discussion_blocks.append(personality.ai_message_prefix) - - full_discussion = personality.personality_conditioning + ''.join(full_discussion_blocks) - - def callback(text, message_type: MSG_TYPE, metadata:dict={}): - if message_type == MSG_TYPE.MSG_TYPE_CHUNK: - self.answer["full_text"] = self.answer["full_text"] + text - self.sio.emit('text_chunk', {'chunk': text}, room=client_id) - self.sio.sleep(0) - try: - if self.connections[client_id]["requested_stop"]: - return False - else: - return True - except: # If the client is disconnected then we stop talking to it - return False - - tk = personality.model.tokenize(full_discussion) - n_tokens = len(tk) - fd = personality.model.detokenize(tk[-min(self.config.ctx_size-n_cond_tk-personality.model_n_predicts,n_tokens):]) - - if personality.processor is not None and personality.processor_cfg["custom_workflow"]: - ASCIIColors.info("processing...") - generated_text = personality.processor.run_workflow(prompt, previous_discussion_text=personality.personality_conditioning+fd, callback=callback) - else: - ASCIIColors.info("generating...") - generated_text = personality.model.generate( - personality.personality_conditioning+fd, - n_predict=personality.model_n_predicts, - callback=callback) - - if personality.processor is not None and personality.processor_cfg["process_model_output"]: - generated_text = personality.processor.process_model_output(generated_text) - - full_discussion_blocks.append(generated_text.strip()) - ASCIIColors.success("\ndone") - - # Emit the generated text to the client - self.sio.emit('text_generated', {'text': generated_text}, room=client_id) - self.sio.sleep(0) - except Exception as ex: - self.sio.emit('generation_error', {'error': str(ex)}, room=client_id) - ASCIIColors.error(f"\ndone") - self.busy = False - except Exception as ex: - trace_exception(ex) - self.sio.emit('generation_error', {'error': str(ex)}, room=client_id) - self.busy = False - - # Start the text generation task in a separate thread - task = self.sio.start_background_task(target=generate_text) - - @socketio.on('generate_msg') - def generate_msg(data): - client_id = request.sid - self.cancel_gen = False - self.connections[client_id]["generated_text"]="" - self.connections[client_id]["cancel_generation"]=False - self.connections[client_id]["continuing"]=False - self.connections[client_id]["first_chunk"]=True - - - - if not self.model: - ASCIIColors.error("Model not selected. Please select a model") - self.error("Model not selected. Please select a model", client_id=client_id) - return - - if not self.busy: - if self.connections[client_id]["current_discussion"] is None: - if self.db.does_last_discussion_have_messages(): - self.connections[client_id]["current_discussion"] = self.db.create_discussion() - else: - self.connections[client_id]["current_discussion"] = self.db.load_last_discussion() - - prompt = data["prompt"] - ump = self.config.discussion_prompt_separator +self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.personality.user_message_prefix - message = self.connections[client_id]["current_discussion"].add_message( - message_type = MSG_TYPE.MSG_TYPE_FULL.value, - sender_type = SENDER_TYPES.SENDER_TYPES_USER.value, - sender = ump.replace(self.config.discussion_prompt_separator,"").replace(":",""), - content=prompt, - metadata=None, - parent_message_id=self.message_id - ) - - ASCIIColors.green("Starting message generation by "+self.personality.name) - self.connections[client_id]['generation_thread'] = threading.Thread(target=self.start_message_generation, args=(message, message.id, client_id)) - self.connections[client_id]['generation_thread'].start() - - self.sio.sleep(0.01) - ASCIIColors.info("Started generation task") - self.busy=True - #tpe = threading.Thread(target=self.start_message_generation, args=(message, message_id, client_id)) - #tpe.start() - else: - self.error("I am busy. Come back later.", client_id=client_id) - - @socketio.on('generate_msg_from') - def generate_msg_from(data): - client_id = request.sid - self.cancel_gen = False - self.connections[client_id]["continuing"]=False - self.connections[client_id]["first_chunk"]=True - - if self.connections[client_id]["current_discussion"] is None: - ASCIIColors.warning("Please select a discussion") - self.error("Please select a discussion first", client_id=client_id) - return - id_ = data['id'] - generation_type = data.get('msg_type',None) - if id_==-1: - message = self.connections[client_id]["current_discussion"].current_message - else: - message = self.connections[client_id]["current_discussion"].load_message(id_) - if message is None: - return - self.connections[client_id]['generation_thread'] = threading.Thread(target=self.start_message_generation, args=(message, message.id, client_id, False, generation_type)) - self.connections[client_id]['generation_thread'].start() - - @socketio.on('continue_generate_msg_from') - def handle_connection(data): - client_id = request.sid - self.cancel_gen = False - self.connections[client_id]["continuing"]=True - self.connections[client_id]["first_chunk"]=True - - if self.connections[client_id]["current_discussion"] is None: - ASCIIColors.yellow("Please select a discussion") - self.error("Please select a discussion", client_id=client_id) - return - id_ = data['id'] - if id_==-1: - message = self.connections[client_id]["current_discussion"].current_message - else: - message = self.connections[client_id]["current_discussion"].load_message(id_) - - self.connections[client_id]["generated_text"]=message.content - self.connections[client_id]['generation_thread'] = threading.Thread(target=self.start_message_generation, args=(message, message.id, client_id, True)) - self.connections[client_id]['generation_thread'].start() - - # generation status - self.generating=False - ASCIIColors.blue(f"Your personal data is stored here :",end="") - ASCIIColors.green(f"{self.lollms_paths.personal_path}") - - def audio_callback(self, text): - if self.summoned: - client_id = 0 - self.cancel_gen = False - self.connections[client_id]["generated_text"]="" - self.connections[client_id]["cancel_generation"]=False - self.connections[client_id]["continuing"]=False - self.connections[client_id]["first_chunk"]=True - - if not self.model: - ASCIIColors.error("Model not selected. Please select a model") - self.error("Model not selected. Please select a model", client_id=client_id) - return - - if not self.busy: - if self.connections[client_id]["current_discussion"] is None: - if self.db.does_last_discussion_have_messages(): - self.connections[client_id]["current_discussion"] = self.db.create_discussion() - else: - self.connections[client_id]["current_discussion"] = self.db.load_last_discussion() - - prompt = text - ump = self.config.discussion_prompt_separator +self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.personality.user_message_prefix - message = self.connections[client_id]["current_discussion"].add_message( - message_type = MSG_TYPE.MSG_TYPE_FULL.value, - sender_type = SENDER_TYPES.SENDER_TYPES_USER.value, - sender = ump.replace(self.config.discussion_prompt_separator,"").replace(":",""), - content=prompt, - metadata=None, - parent_message_id=self.message_id - ) - - ASCIIColors.green("Starting message generation by " + self.personality.name) - self.connections[client_id]['generation_thread'] = threading.Thread(target=self.start_message_generation, args=(message, message.id, client_id)) - self.connections[client_id]['generation_thread'].start() - - self.sio.sleep(0.01) - ASCIIColors.info("Started generation task") - self.busy=True - #tpe = threading.Thread(target=self.start_message_generation, args=(message, message_id, client_id)) - #tpe.start() - else: - self.error("I am busy. Come back later.", client_id=client_id) - else: - if output["text"].lower()=="lollms": - self.summoned = True - - def scrape_and_save(self, url, file_path): - # Send a GET request to the URL - response = requests.get(url) - - # Parse the HTML content using BeautifulSoup - soup = BeautifulSoup(response.content, 'html.parser') - - # Find all the text content in the webpage - text_content = soup.get_text() - - # Remove extra returns and spaces - text_content = ' '.join(text_content.split()) - - # Save the text content as a text file - with open(file_path, 'w', encoding="utf-8") as file: - file.write(text_content) - - self.info(f"Webpage content saved to {file_path}") - - def rebuild_personalities(self, reload_all=False): - if reload_all: - self.mounted_personalities=[] - - loaded = self.mounted_personalities - loaded_names = [f"{p.category}/{p.personality_folder_name}:{p.selected_language}" if p.selected_language else f"{p.category}/{p.personality_folder_name}" for p in loaded] - mounted_personalities=[] - ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ") - ASCIIColors.success(f" ║ Building mounted Personalities ║ ") - ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ") - to_remove=[] - for i,personality in enumerate(self.config['personalities']): - if i==self.config["active_personality_id"]: - ASCIIColors.red("*", end="") - ASCIIColors.green(f" {personality}") - else: - ASCIIColors.yellow(f" {personality}") - if personality in loaded_names: - mounted_personalities.append(loaded[loaded_names.index(personality)]) - else: - personality_path = f"{personality}" if not ":" in personality else f"{personality.split(':')[0]}" - try: - personality = AIPersonality(personality_path, - self.lollms_paths, - self.config, - model=self.model, - app=self, - selected_language=personality.split(":")[1] if ":" in personality else None, - run_scripts=True) - mounted_personalities.append(personality) - if self.config.enable_voice_service and self.config.auto_read and len(personality.audio_samples)>0: - try: - from lollms.services.xtts.lollms_xtts import LollmsXTTS - if self.tts is None: - self.tts = LollmsXTTS(self, voice_samples_path=Path(__file__).parent.parent/"voices") - except: - self.warning(f"Personality {personality.name} request using custom voice but couldn't load XTTS") - except Exception as ex: - ASCIIColors.error(f"Personality file not found or is corrupted ({personality_path}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.") - ASCIIColors.info("Trying to force reinstall") - if self.config["debug"]: - print(ex) - try: - personality = AIPersonality( - personality_path, - self.lollms_paths, - self.config, - self.model, - app = self, - run_scripts=True, - selected_language=personality.split(":")[1] if ":" in personality else None, - installation_option=InstallOption.FORCE_INSTALL) - mounted_personalities.append(personality) - if personality.processor: - personality.processor.mounted() - except Exception as ex: - ASCIIColors.error(f"Couldn't load personality at {personality_path}") - trace_exception(ex) - ASCIIColors.info(f"Unmounting personality") - to_remove.append(i) - personality = AIPersonality(None, - self.lollms_paths, - self.config, - self.model, - app=self, - run_scripts=True, - installation_option=InstallOption.FORCE_INSTALL) - mounted_personalities.append(personality) - if personality.processor: - personality.processor.mounted() - - ASCIIColors.info("Reverted to default personality") - if self.config["active_personality_id"]>=0 and self.config["active_personality_id"]=len(self.config["personalities"]): - self.config["active_personality_id"]=0 - - return mounted_personalities - - - def rebuild_extensions(self, reload_all=False): - if reload_all: - self.mounted_extensions=[] - - loaded = self.mounted_extensions - loaded_names = [f"{p.category}/{p.extension_folder_name}" for p in loaded] - mounted_extensions=[] - ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ") - ASCIIColors.success(f" ║ Building mounted Extensions ║ ") - ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ") - to_remove=[] - for i,extension in enumerate(self.config['extensions']): - ASCIIColors.yellow(f" {extension}") - if extension in loaded_names: - mounted_extensions.append(loaded[loaded_names.index(extension)]) - else: - extension_path = self.lollms_paths.extensions_zoo_path/f"{extension}" - try: - extension = ExtensionBuilder().build_extension(extension_path,self.lollms_paths, self) - mounted_extensions.append(extension) - except Exception as ex: - ASCIIColors.error(f"Extension file not found or is corrupted ({extension_path}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.") - trace_exception(ex) - ASCIIColors.info("Trying to force reinstall") - if self.config["debug"]: - print(ex) - ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ") - ASCIIColors.success(f" ║ Done ║ ") - ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ") - # Sort the indices in descending order to ensure correct removal - to_remove.sort(reverse=True) - - # Remove elements from the list based on the indices - for index in to_remove: - if 0 <= index < len(mounted_extensions): - mounted_extensions.pop(index) - self.config["extensions"].pop(index) - ASCIIColors.info(f"removed personality {extension_path}") - - - return mounted_extensions - # ================================== LOLLMSApp - - #properties - @property - def message_id(self): - return self._message_id - @message_id.setter - def message_id(self, id): - self._message_id=id - - @property - def current_user_message_id(self): - return self._current_user_message_id - @current_user_message_id.setter - def current_user_message_id(self, id): - self._current_user_message_id=id - self._message_id = id - @property - def current_ai_message_id(self): - return self._current_ai_message_id - @current_ai_message_id.setter - def current_ai_message_id(self, id): - self._current_ai_message_id=id - self._message_id = id - - def download_file(self, url, installation_path, callback=None): - """ - Downloads a file from a URL, reports the download progress using a callback function, and displays a progress bar. - - Args: - url (str): The URL of the file to download. - installation_path (str): The path where the file should be saved. - callback (function, optional): A callback function to be called during the download - with the progress percentage as an argument. Defaults to None. - """ - try: - response = requests.get(url, stream=True) - - # Get the file size from the response headers - total_size = int(response.headers.get('content-length', 0)) - - with open(installation_path, 'wb') as file: - downloaded_size = 0 - with tqdm(total=total_size, unit='B', unit_scale=True, ncols=80) as progress_bar: - for chunk in response.iter_content(chunk_size=8192): - if chunk: - file.write(chunk) - downloaded_size += len(chunk) - if callback is not None: - callback(downloaded_size, total_size) - progress_bar.update(len(chunk)) - - if callback is not None: - callback(total_size, total_size) - - print("File downloaded successfully") - except Exception as e: - print("Couldn't download file:", str(e)) - - - - def clean_string(self, input_string): - # Remove extra spaces by replacing multiple spaces with a single space - #cleaned_string = re.sub(r'\s+', ' ', input_string) - - # Remove extra line breaks by replacing multiple consecutive line breaks with a single line break - cleaned_string = re.sub(r'\n\s*\n', '\n', input_string) - # Create a string containing all punctuation characters - punctuation_chars = string.punctuation - # Define a regular expression pattern to match and remove non-alphanumeric characters - #pattern = f'[^a-zA-Z0-9\s{re.escape(punctuation_chars)}]' # This pattern matches any character that is not a letter, digit, space, or punctuation - pattern = f'[^a-zA-Z0-9\u00C0-\u017F\s{re.escape(punctuation_chars)}]' - # Use re.sub to replace the matched characters with an empty string - cleaned_string = re.sub(pattern, '', cleaned_string) - return cleaned_string - - def make_discussion_title(self, discussion, client_id=None): - """ - Builds a title for a discussion - """ - # Get the list of messages - messages = discussion.get_messages() - discussion_messages = "!@>instruction: Create a short title to this discussion\n" - discussion_title = "\n!@>Discussion title:" - - available_space = self.config.ctx_size - 150 - len(self.model.tokenize(discussion_messages))- len(self.model.tokenize(discussion_title)) - # Initialize a list to store the full messages - full_message_list = [] - # Accumulate messages until the cumulative number of tokens exceeds available_space - tokens_accumulated = 0 - # Accumulate messages starting from message_index - for message in messages: - # Check if the message content is not empty and visible to the AI - if message.content != '' and ( - message.message_type <= MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_USER.value and message.message_type != MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_AI.value): - - # Tokenize the message content - message_tokenized = self.model.tokenize( - "\n" + self.config.discussion_prompt_separator + message.sender + ": " + message.content.strip()) - - # Check if adding the message will exceed the available space - if tokens_accumulated + len(message_tokenized) > available_space: - break - - # Add the tokenized message to the full_message_list - full_message_list.insert(0, message_tokenized) - - # Update the cumulative number of tokens - tokens_accumulated += len(message_tokenized) - - # Build the final discussion messages by detokenizing the full_message_list - - for message_tokens in full_message_list: - discussion_messages += self.model.detokenize(message_tokens) - discussion_messages += discussion_title - title = [""] - def receive( - chunk:str, - message_type:MSG_TYPE - ): - if chunk: - title[0] += chunk - antiprompt = self.personality.detect_antiprompt(title[0]) - if antiprompt: - ASCIIColors.warning(f"\nDetected hallucination with antiprompt: {antiprompt}") - title[0] = self.remove_text_from_string(title[0],antiprompt) - return False - else: - return True - - self._generate(discussion_messages, 150, client_id, receive) - ASCIIColors.info(title[0]) - return title[0] - - - def prepare_reception(self, client_id): - if not self.connections[client_id]["continuing"]: - self.connections[client_id]["generated_text"] = "" - - self.connections[client_id]["first_chunk"]=True - - self.nb_received_tokens = 0 - self.start_time = datetime.now() - - def recover_discussion(self,client_id, message_index=-1): - messages = self.connections[client_id]["current_discussion"].get_messages() - discussion="" - for msg in messages: - if message_index!=-1 and msg>message_index: - break - discussion += "\n" + self.config.discussion_prompt_separator + msg.sender + ": " + msg.content.strip() - return discussion - def prepare_query(self, client_id: str, message_id: int = -1, is_continue: bool = False, n_tokens: int = 0, generation_type = None) -> Tuple[str, str, List[str]]: - """ - Prepares the query for the model. - - Args: - client_id (str): The client ID. - message_id (int): The message ID. Default is -1. - is_continue (bool): Whether the query is a continuation. Default is False. - n_tokens (int): The number of tokens. Default is 0. - - Returns: - Tuple[str, str, List[str]]: The prepared query, original message content, and tokenized query. - """ - - # Get the list of messages - messages = self.connections[client_id]["current_discussion"].get_messages() - - # Find the index of the message with the specified message_id - message_index = -1 - for i, message in enumerate(messages): - if message.id == message_id: - message_index = i - break - - # Define current message - current_message = messages[message_index] - - # Build the conditionning text block - conditionning = self.personality.personality_conditioning - - # Check if there are document files to add to the prompt - documentation = "" - history = "" - - - # boosting information - if self.config.positive_boost: - positive_boost="\n!@>important information: "+self.config.positive_boost+"\n" - n_positive_boost = len(self.model.tokenize(positive_boost)) - else: - positive_boost="" - n_positive_boost = 0 - - if self.config.negative_boost: - negative_boost="\n!@>important information: "+self.config.negative_boost+"\n" - n_negative_boost = len(self.model.tokenize(negative_boost)) - else: - negative_boost="" - n_negative_boost = 0 - - if self.config.force_output_language_to_be: - force_language="\n!@>important information: Answer the user in this language :"+self.config.force_output_language_to_be+"\n" - n_force_language = len(self.model.tokenize(force_language)) - else: - force_language="" - n_force_language = 0 - - if generation_type != "simple_question": - if self.personality.persona_data_vectorizer: - if documentation=="": - documentation="!@>Documentation:\n" - - if self.config.data_vectorization_build_keys_words: - discussion = self.recover_discussion(client_id)[-512:] - query = self.personality.fast_gen(f"\n!@>instruction: Read the discussion and rewrite the last prompt for someone who didn't read the entire discussion.\nDo not answer the prompt. Do not add explanations.\n!@>discussion:\n{discussion}\n!@>enhanced query: ", max_generation_size=256, show_progress=True) - ASCIIColors.cyan(f"Query:{query}") - else: - query = current_message.content - try: - docs, sorted_similarities = self.personality.persona_data_vectorizer.recover_text(query, top_k=self.config.data_vectorization_nb_chunks) - for doc, infos in zip(docs, sorted_similarities): - documentation += f"document chunk:\n{doc}" - except: - self.warning("Couldn't add documentation to the context. Please verify the vector database") - - if len(self.personality.text_files) > 0 and self.personality.vectorizer: - if documentation=="": - documentation="!@>Documentation:\n" - - if self.config.data_vectorization_build_keys_words: - discussion = self.recover_discussion(client_id)[-512:] - query = self.personality.fast_gen(f"\n!@>instruction: Read the discussion and rewrite the last prompt for someone who didn't read the entire discussion.\nDo not answer the prompt. Do not add explanations.\n!@>discussion:\n{discussion}\n!@>enhanced query: ", max_generation_size=256, show_progress=True) - ASCIIColors.cyan(f"Query:{query}") - else: - query = current_message.content - - try: - docs, sorted_similarities = self.personality.vectorizer.recover_text(query, top_k=self.config.data_vectorization_nb_chunks) - for doc, infos in zip(docs, sorted_similarities): - documentation += f"document chunk:\nchunk path: {infos[0]}\nchunk content:{doc}" - documentation += "\n!@>important information: Use the documentation data to answer the user questions. If the data is not present in the documentation, please tell the user that the information he is asking for does not exist in the documentation section. It is strictly forbidden to give the user an answer without having actual proof from the documentation." - except: - self.warning("Couldn't add documentation to the context. Please verify the vector database") - # Check if there is discussion history to add to the prompt - if self.config.use_discussions_history and self.long_term_memory is not None: - if history=="": - history="!@>previous discussions:\n" - - try: - docs, sorted_similarities = self.long_term_memory.recover_text(current_message.content, top_k=self.config.data_vectorization_nb_chunks) - for i,(doc, infos) in enumerate(zip(docs, sorted_similarities)): - history += f"!@>previous discussion {i}:\n!@>discussion title:\n{infos[0]}\ndiscussion content:\n{doc}" - except: - self.warning("Couldn't add long term memory information to the context. Please verify the vector database") # Add information about the user - user_description="" - if self.config.use_user_name_in_discussions: - user_description="!@>User description:\n"+self.config.user_description+"\n" - - - # Tokenize the conditionning text and calculate its number of tokens - tokens_conditionning = self.model.tokenize(conditionning) - n_cond_tk = len(tokens_conditionning) - - # Tokenize the documentation text and calculate its number of tokens - if len(documentation)>0: - tokens_documentation = self.model.tokenize(documentation) - n_doc_tk = len(tokens_documentation) - else: - tokens_documentation = [] - n_doc_tk = 0 - - # Tokenize the history text and calculate its number of tokens - if len(history)>0: - tokens_history = self.model.tokenize(history) - n_history_tk = len(tokens_history) - else: - tokens_history = [] - n_history_tk = 0 - - - # Tokenize user description - if len(user_description)>0: - tokens_user_description = self.model.tokenize(user_description) - n_user_description_tk = len(tokens_user_description) - else: - tokens_user_description = [] - n_user_description_tk = 0 - - - # Calculate the total number of tokens between conditionning, documentation, and history - total_tokens = n_cond_tk + n_doc_tk + n_history_tk + n_user_description_tk + n_positive_boost + n_negative_boost + n_force_language - - # Calculate the available space for the messages - available_space = self.config.ctx_size - n_tokens - total_tokens - - if self.config.debug: - self.info(f"Tokens summary:\nConditionning:{n_cond_tk}\ndoc:{n_doc_tk}\nhistory:{n_history_tk}\nuser description:{n_user_description_tk}\nAvailable space:{available_space}",10) - - # Raise an error if the available space is 0 or less - if available_space<1: - self.error("Not enough space in context!!") - raise Exception("Not enough space in context!!") - - # Accumulate messages until the cumulative number of tokens exceeds available_space - tokens_accumulated = 0 - - - # Initialize a list to store the full messages - full_message_list = [] - # If this is not a continue request, we add the AI prompt - if not is_continue: - message_tokenized = self.model.tokenize( - "\n" +self.personality.ai_message_prefix.strip() - ) - full_message_list.append(message_tokenized) - # Update the cumulative number of tokens - tokens_accumulated += len(message_tokenized) - - - if generation_type != "simple_question": - # Accumulate messages starting from message_index - for i in range(message_index, -1, -1): - message = messages[i] - - # Check if the message content is not empty and visible to the AI - if message.content != '' and ( - message.message_type <= MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_USER.value and message.message_type != MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_AI.value): - - # Tokenize the message content - message_tokenized = self.model.tokenize( - "\n" + self.config.discussion_prompt_separator + message.sender + ": " + message.content.strip()) - - # Check if adding the message will exceed the available space - if tokens_accumulated + len(message_tokenized) > available_space: - break - - # Add the tokenized message to the full_message_list - full_message_list.insert(0, message_tokenized) - - # Update the cumulative number of tokens - tokens_accumulated += len(message_tokenized) - else: - message = messages[message_index] - - # Check if the message content is not empty and visible to the AI - if message.content != '' and ( - message.message_type <= MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_USER.value and message.message_type != MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_AI.value): - - # Tokenize the message content - message_tokenized = self.model.tokenize( - "\n" + self.config.discussion_prompt_separator + message.sender + ": " + message.content.strip()) - - # Add the tokenized message to the full_message_list - full_message_list.insert(0, message_tokenized) - - # Update the cumulative number of tokens - tokens_accumulated += len(message_tokenized) - - # Build the final discussion messages by detokenizing the full_message_list - discussion_messages = "" - for i in range(len(full_message_list)-1): - message_tokens = full_message_list[i] - discussion_messages += self.model.detokenize(message_tokens) - - # Build the final prompt by concatenating the conditionning and discussion messages - prompt_data = conditionning + documentation + history + user_description + discussion_messages + positive_boost + negative_boost + force_language + self.model.detokenize(full_message_list[-1]) - - # Tokenize the prompt data - tokens = self.model.tokenize(prompt_data) - - # if this is a debug then show prompt construction details - if self.config["debug"]: - ASCIIColors.bold("CONDITIONNING") - ASCIIColors.yellow(conditionning) - ASCIIColors.bold("DOC") - ASCIIColors.yellow(documentation) - ASCIIColors.bold("HISTORY") - ASCIIColors.yellow(history) - ASCIIColors.bold("DISCUSSION") - ASCIIColors.hilight(discussion_messages,"!@>",ASCIIColors.color_yellow,ASCIIColors.color_bright_red,False) - ASCIIColors.bold("Final prompt") - ASCIIColors.hilight(prompt_data,"!@>",ASCIIColors.color_yellow,ASCIIColors.color_bright_red,False) - ASCIIColors.info(f"prompt size:{len(tokens)} tokens") - ASCIIColors.info(f"available space after doc and history:{available_space} tokens") - - self.info(f"Tokens summary:\nPrompt size:{len(tokens)}\nTo generate:{available_space}",10) - - # Return the prepared query, original message content, and tokenized query - return prompt_data, current_message.content, tokens - - - def get_discussion_to(self, client_id, message_id=-1): - messages = self.connections[client_id]["current_discussion"].get_messages() - full_message_list = [] - ump = self.config.discussion_prompt_separator +self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.personality.user_message_prefix - - for message in messages: - if message["id"]<= message_id or message_id==-1: - if message["type"]!=MSG_TYPE.MSG_TYPE_FULL_INVISIBLE_TO_USER: - if message["sender"]==self.personality.name: - full_message_list.append(self.personality.ai_message_prefix+message["content"]) - else: - full_message_list.append(ump + message["content"]) - - link_text = "\n"# self.personality.link_text - - if len(full_message_list) > self.config["nb_messages_to_remember"]: - discussion_messages = self.personality.personality_conditioning+ link_text.join(full_message_list[-self.config["nb_messages_to_remember"]:]) - else: - discussion_messages = self.personality.personality_conditioning+ link_text.join(full_message_list) - - return discussion_messages # Removes the last return - - def notify( - self, - content, - notification_type:NotificationType=NotificationType.NOTIF_SUCCESS, - duration:int=4, - client_id=None, - display_type:NotificationDisplayType=NotificationDisplayType.TOAST, - verbose=True - ): - self.sio.emit('notification', { - 'content': content,# self.connections[client_id]["generated_text"], - 'notification_type': notification_type.value, - "duration": duration, - 'display_type':display_type.value - }, room=client_id - ) - self.sio.sleep(0.01) - if verbose: - if notification_type==NotificationType.NOTIF_SUCCESS: - ASCIIColors.success(content) - elif notification_type==NotificationType.NOTIF_INFO: - ASCIIColors.info(content) - elif notification_type==NotificationType.NOTIF_WARNING: - ASCIIColors.warning(content) - else: - ASCIIColors.red(content) - - - def new_message(self, - client_id, - sender=None, - content="", - parameters=None, - metadata=None, - ui=None, - message_type:MSG_TYPE=MSG_TYPE.MSG_TYPE_FULL, - sender_type:SENDER_TYPES=SENDER_TYPES.SENDER_TYPES_AI, - open=False - ): - - mtdt = metadata if metadata is None or type(metadata) == str else json.dumps(metadata, indent=4) - if sender==None: - sender= self.personality.name - msg = self.connections[client_id]["current_discussion"].add_message( - message_type = message_type.value, - sender_type = sender_type.value, - sender = sender, - content = content, - metadata = mtdt, - ui = ui, - rank = 0, - parent_message_id = self.connections[client_id]["current_discussion"].current_message.id, - binding = self.config["binding_name"], - model = self.config["model_name"], - personality = self.config["personalities"][self.config["active_personality_id"]], - ) # first the content is empty, but we'll fill it at the end - - self.sio.emit('new_message', - { - "sender": sender, - "message_type": message_type.value, - "sender_type": SENDER_TYPES.SENDER_TYPES_AI.value, - "content": content, - "parameters": parameters, - "metadata": metadata, - "ui": ui, - "id": msg.id, - "parent_message_id": msg.parent_message_id, - - 'binding': self.config["binding_name"], - 'model' : self.config["model_name"], - 'personality': self.config["personalities"][self.config["active_personality_id"]], - - 'created_at': self.connections[client_id]["current_discussion"].current_message.created_at, - 'finished_generating_at': self.connections[client_id]["current_discussion"].current_message.finished_generating_at, - - 'open': open - }, room=client_id - ) - - def update_message(self, client_id, chunk, - parameters=None, - metadata=[], - ui=None, - msg_type:MSG_TYPE=None - ): - self.connections[client_id]["current_discussion"].current_message.finished_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S') - mtdt = json.dumps(metadata, indent=4) if metadata is not None and type(metadata)== list else metadata - if self.nb_received_tokens==1: - self.sio.emit('update_message', { - "sender": self.personality.name, - 'id':self.connections[client_id]["current_discussion"].current_message.id, - 'content': "✍ warming up ...",# self.connections[client_id]["generated_text"], - 'ui': ui, - 'discussion_id':self.connections[client_id]["current_discussion"].discussion_id, - 'message_type': MSG_TYPE.MSG_TYPE_STEP_END.value, - 'finished_generating_at': self.connections[client_id]["current_discussion"].current_message.finished_generating_at, - 'parameters':parameters, - 'metadata':metadata - }, room=client_id - ) - - - self.sio.emit('update_message', { - "sender": self.personality.name, - 'id':self.connections[client_id]["current_discussion"].current_message.id, - 'content': chunk,# self.connections[client_id]["generated_text"], - 'ui': ui, - 'discussion_id':self.connections[client_id]["current_discussion"].discussion_id, - 'message_type': msg_type.value if msg_type is not None else MSG_TYPE.MSG_TYPE_CHUNK.value if self.nb_received_tokens>1 else MSG_TYPE.MSG_TYPE_FULL.value, - 'finished_generating_at': self.connections[client_id]["current_discussion"].current_message.finished_generating_at, - 'parameters':parameters, - 'metadata':metadata - }, room=client_id - ) - self.sio.sleep(0.01) - if msg_type != MSG_TYPE.MSG_TYPE_INFO: - self.connections[client_id]["current_discussion"].update_message(self.connections[client_id]["generated_text"], new_metadata=mtdt, new_ui=ui) - - - - def close_message(self, client_id): - if not self.connections[client_id]["current_discussion"]: - return - #fix halucination - self.connections[client_id]["generated_text"]=self.connections[client_id]["generated_text"].split("!@>")[0] - # Send final message - self.connections[client_id]["current_discussion"].current_message.finished_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S') - self.sio.emit('close_message', { - "sender": self.personality.name, - "id": self.connections[client_id]["current_discussion"].current_message.id, - "content":self.connections[client_id]["generated_text"], - - 'binding': self.config["binding_name"], - 'model' : self.config["model_name"], - 'personality':self.config["personalities"][self.config["active_personality_id"]], - - 'created_at': self.connections[client_id]["current_discussion"].current_message.created_at, - 'finished_generating_at': self.connections[client_id]["current_discussion"].current_message.finished_generating_at, - - }, room=client_id - ) - def process_chunk( - self, - chunk:str, - message_type:MSG_TYPE, - parameters:dict=None, - metadata:list=None, - client_id:int=0, - personality:AIPersonality=None - ): - """ - Processes a chunk of generated text - """ - if chunk is None: - return True - if not client_id in list(self.connections.keys()): - self.error("Connection lost", client_id=client_id) - return - if message_type == MSG_TYPE.MSG_TYPE_STEP: - ASCIIColors.info("--> Step:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_STEP_START: - ASCIIColors.info("--> Step started:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_STEP_END: - if parameters['status']: - ASCIIColors.success("--> Step ended:"+chunk) - else: - ASCIIColors.error("--> Step ended:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_EXCEPTION: - self.error(chunk, client_id=client_id) - ASCIIColors.error("--> Exception from personality:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_WARNING: - self.warning(chunk,client_id=client_id) - ASCIIColors.error("--> Exception from personality:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_INFO: - self.info(chunk, client_id=client_id) - ASCIIColors.info("--> Info:"+chunk) - if message_type == MSG_TYPE.MSG_TYPE_UI: - self.update_message(client_id, "", parameters, metadata, chunk, MSG_TYPE.MSG_TYPE_UI) - - if message_type == MSG_TYPE.MSG_TYPE_NEW_MESSAGE: - self.nb_received_tokens = 0 - self.start_time = datetime.now() - self.new_message( - client_id, - self.personality.name if personality is None else personality.name, - chunk if parameters["type"]!=MSG_TYPE.MSG_TYPE_UI.value else '', - metadata = [{ - "title":chunk, - "content":parameters["metadata"] - } - ] if parameters["type"]==MSG_TYPE.MSG_TYPE_JSON_INFOS.value else None, - ui= chunk if parameters["type"]==MSG_TYPE.MSG_TYPE_UI.value else None, - message_type= MSG_TYPE(parameters["type"])) - - elif message_type == MSG_TYPE.MSG_TYPE_FINISHED_MESSAGE: - self.close_message(client_id) - - elif message_type == MSG_TYPE.MSG_TYPE_CHUNK: - if self.nb_received_tokens==0: - self.start_time = datetime.now() - dt =(datetime.now() - self.start_time).seconds - if dt==0: - dt=1 - spd = self.nb_received_tokens/dt - ASCIIColors.green(f"Received {self.nb_received_tokens} tokens (speed: {spd:.2f}t/s) ",end="\r",flush=True) - sys.stdout = sys.__stdout__ - sys.stdout.flush() - if chunk: - self.connections[client_id]["generated_text"] += chunk - antiprompt = self.personality.detect_antiprompt(self.connections[client_id]["generated_text"]) - if antiprompt: - ASCIIColors.warning(f"\nDetected hallucination with antiprompt: {antiprompt}") - self.connections[client_id]["generated_text"] = self.remove_text_from_string(self.connections[client_id]["generated_text"],antiprompt) - self.update_message(client_id, self.connections[client_id]["generated_text"], parameters, metadata, None, MSG_TYPE.MSG_TYPE_FULL) - return False - else: - self.nb_received_tokens += 1 - if self.connections[client_id]["continuing"] and self.connections[client_id]["first_chunk"]: - self.update_message(client_id, self.connections[client_id]["generated_text"], parameters, metadata) - else: - self.update_message(client_id, chunk, parameters, metadata, msg_type=MSG_TYPE.MSG_TYPE_CHUNK) - self.connections[client_id]["first_chunk"]=False - # if stop generation is detected then stop - if not self.cancel_gen: - return True - else: - self.cancel_gen = False - ASCIIColors.warning("Generation canceled") - return False - - # Stream the generated text to the main process - elif message_type == MSG_TYPE.MSG_TYPE_FULL: - self.connections[client_id]["generated_text"] = chunk - self.nb_received_tokens += 1 - dt =(datetime.now() - self.start_time).seconds - if dt==0: - dt=1 - spd = self.nb_received_tokens/dt - ASCIIColors.green(f"Received {self.nb_received_tokens} tokens (speed: {spd:.2f}t/s) ",end="\r",flush=True) - antiprompt = self.personality.detect_antiprompt(self.connections[client_id]["generated_text"]) - if antiprompt: - ASCIIColors.warning(f"\nDetected hallucination with antiprompt: {antiprompt}") - self.connections[client_id]["generated_text"] = self.remove_text_from_string(self.connections[client_id]["generated_text"],antiprompt) - self.update_message(client_id, self.connections[client_id]["generated_text"], parameters, metadata, None, MSG_TYPE.MSG_TYPE_FULL) - return False - - self.update_message(client_id, chunk, parameters, metadata, ui=None, msg_type=message_type) - return True - # Stream the generated text to the frontend - else: - self.update_message(client_id, chunk, parameters, metadata, ui=None, msg_type=message_type) - return True - - - def generate(self, full_prompt, prompt, n_predict, client_id, callback=None): - if self.personality.processor is not None: - ASCIIColors.info("Running workflow") - try: - self.personality.callback = callback - self.personality.processor.run_workflow( prompt, full_prompt, callback) - except Exception as ex: - trace_exception(ex) - # Catch the exception and get the traceback as a list of strings - traceback_lines = traceback.format_exception(type(ex), ex, ex.__traceback__) - # Join the traceback lines into a single string - traceback_text = ''.join(traceback_lines) - ASCIIColors.error(f"Workflow run failed.\nError:{ex}") - ASCIIColors.error(traceback_text) - if callback: - callback(f"Workflow run failed\nError:{ex}", MSG_TYPE.MSG_TYPE_EXCEPTION) - print("Finished executing the workflow") - return - - - self._generate(full_prompt, n_predict, client_id, callback) - ASCIIColors.success("\nFinished executing the generation") - - def _generate(self, prompt, n_predict, client_id, callback=None): - self.nb_received_tokens = 0 - self.start_time = datetime.now() - if self.model is not None: - if self.model.binding_type==BindingType.TEXT_IMAGE and len(self.personality.image_files)>0: - ASCIIColors.info(f"warmup for generating up to {n_predict} tokens") - if self.config["override_personality_model_parameters"]: - output = self.model.generate_with_images( - prompt, - self.personality.image_files, - callback=callback, - n_predict=n_predict, - temperature=self.config['temperature'], - top_k=self.config['top_k'], - top_p=self.config['top_p'], - repeat_penalty=self.config['repeat_penalty'], - repeat_last_n = self.config['repeat_last_n'], - seed=self.config['seed'], - n_threads=self.config['n_threads'] - ) - else: - output = self.model.generate_with_images( - prompt, - self.personality.image_files, - callback=callback, - n_predict=min(n_predict,self.personality.model_n_predicts), - temperature=self.personality.model_temperature, - top_k=self.personality.model_top_k, - top_p=self.personality.model_top_p, - repeat_penalty=self.personality.model_repeat_penalty, - repeat_last_n = self.personality.model_repeat_last_n, - seed=self.config['seed'], - n_threads=self.config['n_threads'] - ) - else: - ASCIIColors.info(f"warmup for generating up to {n_predict} tokens") - if self.config["override_personality_model_parameters"]: - output = self.model.generate( - prompt, - callback=callback, - n_predict=n_predict, - temperature=self.config['temperature'], - top_k=self.config['top_k'], - top_p=self.config['top_p'], - repeat_penalty=self.config['repeat_penalty'], - repeat_last_n = self.config['repeat_last_n'], - seed=self.config['seed'], - n_threads=self.config['n_threads'] - ) - else: - output = self.model.generate( - prompt, - callback=callback, - n_predict=min(n_predict,self.personality.model_n_predicts), - temperature=self.personality.model_temperature, - top_k=self.personality.model_top_k, - top_p=self.personality.model_top_p, - repeat_penalty=self.personality.model_repeat_penalty, - repeat_last_n = self.personality.model_repeat_last_n, - seed=self.config['seed'], - n_threads=self.config['n_threads'] - ) - else: - print("No model is installed or selected. Please make sure to install a model and select it inside your configuration before attempting to communicate with the model.") - print("To do this: Install the model to your models/ folder.") - print("Then set your model information in your local configuration file that you can find in configs/local_config.yaml") - print("You can also use the ui to set your model in the settings page.") - output = "" - return output - - def start_message_generation(self, message, message_id, client_id, is_continue=False, generation_type=None): - if self.personality is None: - self.warning("Select a personality") - return - ASCIIColors.info(f"Text generation requested by client: {client_id}") - # send the message to the bot - print(f"Received message : {message.content}") - if self.connections[client_id]["current_discussion"]: - if not self.model: - self.error("No model selected. Please make sure you select a model before starting generation", client_id=client_id) - return - # First we need to send the new message ID to the client - if is_continue: - self.connections[client_id]["current_discussion"].load_message(message_id) - self.connections[client_id]["generated_text"] = message.content - else: - self.new_message(client_id, self.personality.name, "") - self.update_message(client_id, "✍ warming up ...", msg_type=MSG_TYPE.MSG_TYPE_STEP_START) - self.sio.sleep(0.01) - - # prepare query and reception - self.discussion_messages, self.current_message, tokens = self.prepare_query(client_id, message_id, is_continue, n_tokens=self.config.min_n_predict, generation_type=generation_type) - self.prepare_reception(client_id) - self.generating = True - self.connections[client_id]["processing"]=True - try: - self.generate( - self.discussion_messages, - self.current_message, - n_predict = self.config.ctx_size-len(tokens)-1, - client_id=client_id, - callback=partial(self.process_chunk,client_id = client_id) - ) - if self.config.enable_voice_service and self.config.auto_read and len(self.personality.audio_samples)>0: - try: - self.process_chunk("Generating voice output",MSG_TYPE.MSG_TYPE_STEP_START,client_id=client_id) - from lollms.services.xtts.lollms_xtts import LollmsXTTS - if self.tts is None: - self.tts = LollmsXTTS(self, voice_samples_path=Path(__file__).parent.parent/"voices") - language = convert_language_name(self.personality.language) - self.tts.set_speaker_folder(Path(self.personality.audio_samples[0]).parent) - fn = self.personality.name.lower().replace(' ',"_").replace('.','') - fn = f"{fn}_{message_id}.wav" - url = f"audio/{fn}" - self.tts.tts_to_file(self.connections[client_id]["generated_text"], Path(self.personality.audio_samples[0]).name, f"{fn}", language=language) - fl = f""" - -""" - self.process_chunk("Generating voice output", MSG_TYPE.MSG_TYPE_STEP_END, {'status':True},client_id=client_id) - self.process_chunk(fl,MSG_TYPE.MSG_TYPE_UI, client_id=client_id) - - """ - self.info("Creating audio output",10) - self.personality.step_start("Creating audio output") - if not PackageManager.check_package_installed("tortoise"): - PackageManager.install_package("tortoise-tts") - from tortoise import utils, api - import sounddevice as sd - if self.tts is None: - self.tts = api.TextToSpeech( kv_cache=True, half=True) - reference_clips = [utils.audio.load_audio(str(p), 22050) for p in self.personality.audio_samples] - tk = self.model.tokenize(self.connections[client_id]["generated_text"]) - if len(tk)>100: - chunk_size = 100 - - for i in range(0, len(tk), chunk_size): - chunk = self.model.detokenize(tk[i:i+chunk_size]) - if i==0: - pcm_audio = self.tts.tts_with_preset(chunk, voice_samples=reference_clips, preset='fast').numpy().flatten() - else: - pcm_audio = np.concatenate([pcm_audio, self.tts.tts_with_preset(chunk, voice_samples=reference_clips, preset='ultra_fast').numpy().flatten()]) - else: - pcm_audio = self.tts.tts_with_preset(self.connections[client_id]["generated_text"], voice_samples=reference_clips, preset='fast').numpy().flatten() - sd.play(pcm_audio, 22050) - self.personality.step_end("Creating audio output") - """ - - - - except Exception as ex: - ASCIIColors.error("Couldn't read") - trace_exception(ex) - print() - ASCIIColors.success("## Done Generation ##") - print() - except Exception as ex: - trace_exception(ex) - print() - ASCIIColors.error("## Generation Error ##") - print() - - self.cancel_gen = False - - # Send final message - self.close_message(client_id) - self.sio.sleep(0.01) - self.connections[client_id]["processing"]=False - if self.connections[client_id]["schedule_for_deletion"]: - del self.connections[client_id] - - ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ") - ASCIIColors.success(f" ║ Done ║ ") - ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ") - if self.config.auto_title: - d = self.connections[client_id]["current_discussion"] - ttl = d.title() - if ttl is None or ttl=="" or ttl=="untitled": - title = self.make_discussion_title(d, client_id=client_id) - d.rename(title) - self.sio.emit('disucssion_renamed',{ - 'status': True, - 'discussion_id':d.discussion_id, - 'title':title - }, room=client_id) - - self.busy=False - - else: - ump = self.config.discussion_prompt_separator +self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.personality.user_message_prefix - - self.cancel_gen = False - #No discussion available - ASCIIColors.warning("No discussion selected!!!") - - self.error("No discussion selected!!!", client_id=client_id) - - print() - self.busy=False - return "" diff --git a/api/config.py b/api/config.py index ff59005c..5e5fddd3 100644 --- a/api/config.py +++ b/api/config.py @@ -5,9 +5,7 @@ # Supported by Nomic-AI # license : Apache 2.0 # Description : -# A front end Flask application for llamacpp models. -# The official LOLLMS Web ui -# Made by the community for the community +# Configuration management tool ###### import yaml diff --git a/app_old.py b/app_old.py deleted file mode 100644 index 1107b8ec..00000000 --- a/app_old.py +++ /dev/null @@ -1,2646 +0,0 @@ -###### -# Project : lollms-webui -# Author : ParisNeo with the help of the community -# license : Apache 2.0 -# Description : -# A front end Flask application for llamacpp models. -# The official LOLLMS Web ui -# Made by the community for the community -###### - -__author__ = "parisneo" -__github__ = "https://github.com/ParisNeo/lollms-webui" -__copyright__ = "Copyright 2023, " -__license__ = "Apache 2.0" - -__version__ ="8.5" - -main_repo = "https://github.com/ParisNeo/lollms-webui.git" - - - -import os -import platform -import sys -from flask import request, jsonify, url_for -import io -import sys -import time -import traceback -import webbrowser -from pathlib import Path -from lollms.config import InstallOption -from lollms.main_config import LOLLMSConfig -from lollms.paths import LollmsPaths, gptqlora_repo -from lollms.com import NotificationType, NotificationDisplayType -from lollms.utilities import PackageManager, AdvancedGarbageCollector, reinstall_pytorch_with_cuda, convert_language_name, find_first_available_file_index, add_period -lollms_paths = LollmsPaths.find_paths(force_local=True, custom_default_cfg_path="configs/config.yaml") -# Configuration loading part -config = LOLLMSConfig.autoload(lollms_paths) - -def run_update_script(args=None): - update_script = Path(__file__).parent/"update_script.py" - - # Convert Namespace object to a dictionary - if args: - args_dict = vars(args) - else: - args_dict = {} - # Filter out any key-value pairs where the value is None - valid_args = {key: value for key, value in args_dict.items() if value is not None} - - # Save the arguments to a temporary file - temp_file = Path(__file__).parent/"temp_args.txt" - with open(temp_file, "w") as file: - # Convert the valid_args dictionary to a string in the format "key1 value1 key2 value2 ..." - arg_string = " ".join([f"--{key} {value}" for key, value in valid_args.items()]) - file.write(arg_string) - - os.system(f"python {update_script}") - sys.exit(0) - -from lollms.helpers import ASCIIColors, get_trace_exception, trace_exception - -try: - import git - import logging - import argparse - import json - import traceback - import subprocess - import signal - from lollms.binding import BindingBuilder - from lollms.personality import AIPersonality - from lollms.config import BaseConfig - from lollms.extension import LOLLMSExtension, ExtensionBuilder - - from flask_cors import CORS - from api.db import Discussion - from flask import ( - Flask, - jsonify, - render_template, - request, - send_from_directory - ) - - from flask_socketio import SocketIO - import yaml - from geventwebsocket.handler import WebSocketHandler - import logging - import psutil - from lollms.main_config import LOLLMSConfig - from typing import Optional - import gc - import pkg_resources - - from api.config import load_config - from api import LoLLMsAPI - import shutil - import socket - from api.db import DiscussionsDB, Discussion - from safe_store import TextVectorizer, VectorizationMethod, VisualizationMethod - from tqdm import tqdm - - try: - import mimetypes - mimetypes.add_type('application/javascript', '.js') - mimetypes.add_type('text/css', '.css') - except: - ASCIIColors.yellow("Couldn't set mimetype") - - def check_module_update_(repo_path, branch_name="main"): - try: - # Open the repository - ASCIIColors.yellow(f"Checking for updates from {repo_path}") - repo = git.Repo(repo_path) - - # Fetch updates from the remote for the specified branch - repo.remotes.origin.fetch(refspec=f"refs/heads/{branch_name}:refs/remotes/origin/{branch_name}") - - # Compare the local and remote commit IDs for the specified branch - local_commit = repo.head.commit - remote_commit = repo.remotes.origin.refs[branch_name].commit - - # Check if the local branch is behind the remote branch - is_behind = repo.is_ancestor(local_commit, remote_commit) and local_commit!= remote_commit - - ASCIIColors.yellow(f"update availability: {is_behind}") - - # Return True if the local branch is behind the remote branch - return is_behind - except Exception as e: - # Handle any errors that may occur during the fetch process - # trace_exception(e) - return False - - def check_update_(branch_name="main"): - try: - # Open the repository - repo_path = str(Path(__file__).parent) - if check_module_update_(repo_path, branch_name): - return True - repo_path = str(Path(__file__).parent/"lollms_core") - if check_module_update_(repo_path, branch_name): - return True - repo_path = str(Path(__file__).parent/"utilities/safe_store") - if check_module_update_(repo_path, branch_name): - return True - return False - except Exception as e: - # Handle any errors that may occur during the fetch process - # trace_exception(e) - return False - - - - log = logging.getLogger('werkzeug') - log.setLevel(logging.ERROR) - - app = Flask("Lollms-WebUI", static_url_path="/static", static_folder="static") - CORS(app) - from flask_compress import Compress - # async_mode='gevent', ping_timeout=1200, ping_interval=120, - socketio = SocketIO(app, cors_allowed_origins="*", async_mode='gevent', ping_timeout=1200, ping_interval=120, path='/socket.io') - #socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading',engineio_options={'websocket_compression': True, 'websocket_ping_interval': 20, 'websocket_ping_timeout': 120, 'websocket_max_queue': 100}) - compress = Compress(app) - app.config['SECRET_KEY'] = 'secret!' - # Set the logging level to WARNING or higher - logging.getLogger('socketio').setLevel(logging.WARNING) - logging.getLogger('engineio').setLevel(logging.WARNING) - logging.getLogger('werkzeug').setLevel(logging.ERROR) - logging.basicConfig(level=logging.WARNING) - - - def get_ip_address(): - # Create a socket object - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - - try: - # Connect to a remote host (doesn't matter which one) - sock.connect(('8.8.8.8', 80)) - - # Get the local IP address of the socket - ip_address = sock.getsockname()[0] - return ip_address - except socket.error: - return None - finally: - # Close the socket - sock.close() - - - - - - def run_restart_script(args): - restart_script = Path(__file__).parent/"restart_script.py" - - # Convert Namespace object to a dictionary - args_dict = vars(args) - - # Filter out any key-value pairs where the value is None - valid_args = {key: value for key, value in args_dict.items() if value is not None} - - # Save the arguments to a temporary file - temp_file = Path(__file__).parent/"temp_args.txt" - with open(temp_file, "w") as file: - # Convert the valid_args dictionary to a string in the format "key1 value1 key2 value2 ..." - arg_string = " ".join([f"--{key} {value}" for key, value in valid_args.items()]) - file.write(arg_string) - - os.system(f"python {restart_script}") - sys.exit(0) - - - - - class LoLLMsWebUI(LoLLMsAPI): - def __init__(self, args, _app, _socketio, config:LOLLMSConfig, config_file_path:Path|str, lollms_paths:LollmsPaths) -> None: - self.args = args - if config.auto_update: - if check_update_(): - ASCIIColors.info("New version found. Updating!") - run_update_script() - - if len(config.personalities)==0: - config.personalities.append("generic/lollms") - config["active_personality_id"] = 0 - config.save_config() - - if config["active_personality_id"]>=len(config["personalities"]) or config["active_personality_id"]<0: - config["active_personality_id"] = 0 - super().__init__(config, _socketio, config_file_path, lollms_paths) - - - self.app = _app - self.cancel_gen = False - - app.template_folder = "web/dist" - - if len(config["personalities"])>0: - self.personality_category= config["personalities"][config["active_personality_id"]].split("/")[0] - self.personality_name= config["personalities"][config["active_personality_id"]].split("/")[1] - else: - self.personality_category = "generic" - self.personality_name = "lollms" - - # ========================================================================================= - # Endpoints - # ========================================================================================= - - self.add_endpoint("/get_current_personality_files_list", "get_current_personality_files_list", self.get_current_personality_files_list, methods=["GET"]) - self.add_endpoint("/clear_personality_files_list", "clear_personality_files_list", self.clear_personality_files_list, methods=["GET"]) - - self.add_endpoint("/start_training", "start_training", self.start_training, methods=["POST"]) - self.add_endpoint("/get_lollms_version", "get_lollms_version", self.get_lollms_version, methods=["GET"]) - self.add_endpoint("/get_lollms_webui_version", "get_lollms_webui_version", self.get_lollms_webui_version, methods=["GET"]) - - self.add_endpoint("/reload_binding", "reload_binding", self.reload_binding, methods=["POST"]) - - - self.add_endpoint("/restart_program", "restart_program", self.restart_program, methods=["GET"]) - self.add_endpoint("/update_software", "update_software", self.update_software, methods=["GET"]) - self.add_endpoint("/clear_uploads", "clear_uploads", self.clear_uploads, methods=["GET"]) - - self.add_endpoint("/check_update", "check_update", self.check_update, methods=["GET"]) - - self.add_endpoint("/disk_usage", "disk_usage", self.disk_usage, methods=["GET"]) - self.add_endpoint("/ram_usage", "ram_usage", self.ram_usage, methods=["GET"]) - self.add_endpoint("/vram_usage", "vram_usage", self.vram_usage, methods=["GET"]) - - - self.add_endpoint("/list_bindings", "list_bindings", self.list_bindings, methods=["GET"]) - self.add_endpoint("/install_binding", "install_binding", self.install_binding, methods=["POST"]) - self.add_endpoint("/unInstall_binding", "unInstall_binding", self.unInstall_binding, methods=["POST"]) - self.add_endpoint("/reinstall_binding", "reinstall_binding", self.reinstall_binding, methods=["POST"]) - self.add_endpoint("/get_active_binding_settings", "get_active_binding_settings", self.get_active_binding_settings, methods=["GET"]) - self.add_endpoint("/set_active_binding_settings", "set_active_binding_settings", self.set_active_binding_settings, methods=["POST"]) - - - self.add_endpoint("/list_models", "list_models", self.list_models, methods=["GET"]) - self.add_endpoint("/get_active_model", "get_active_model", self.get_active_model, methods=["GET"]) - self.add_endpoint("/add_reference_to_local_model", "add_reference_to_local_model", self.add_reference_to_local_model, methods=["POST"]) - self.add_endpoint("/get_model_status", "get_model_status", self.get_model_status, methods=["GET"]) - self.add_endpoint("/get_available_models", "get_available_models", self.get_available_models, methods=["GET"]) - - self.add_endpoint("/post_to_personality", "post_to_personality", self.post_to_personality, methods=["POST"]) - self.add_endpoint("/reinstall_personality", "reinstall_personality", self.reinstall_personality, methods=["POST"]) - - - self.add_endpoint("/list_mounted_personalities", "list_mounted_personalities", self.list_mounted_personalities, methods=["POST"]) - self.add_endpoint("/list_personalities_categories", "list_personalities_categories", self.list_personalities_categories, methods=["GET"]) - self.add_endpoint("/list_personalities", "list_personalities", self.list_personalities, methods=["GET"]) - - self.add_endpoint("/mount_personality", "mount_personality", self.p_mount_personality, methods=["POST"]) - self.add_endpoint("/remount_personality", "remount_personality", self.p_remount_personality, methods=["POST"]) - self.add_endpoint("/unmount_personality", "unmount_personality", self.p_unmount_personality, methods=["POST"]) - self.add_endpoint("/unmount_all_personalities", "unmount_all_personalities", self.unmount_all_personalities, methods=["GET"]) - self.add_endpoint("/select_personality", "select_personality", self.p_select_personality, methods=["POST"]) - self.add_endpoint("/get_personality_settings", "get_personality_settings", self.get_personality_settings, methods=["POST"]) - self.add_endpoint("/get_active_personality_settings", "get_active_personality_settings", self.get_active_personality_settings, methods=["GET"]) - self.add_endpoint("/set_active_personality_settings", "set_active_personality_settings", self.set_active_personality_settings, methods=["POST"]) - self.add_endpoint("/get_current_personality_path_infos", "get_current_personality_path_infos", self.get_current_personality_path_infos, methods=["GET"]) - self.add_endpoint("/get_personality", "get_personality", self.get_personality, methods=["GET"]) - self.add_endpoint("/get_current_personality", "get_current_personality", self.get_current_personality, methods=["GET"]) - self.add_endpoint("/get_all_personalities", "get_all_personalities", self.get_all_personalities, methods=["GET"]) - - - self.add_endpoint("/uploads/", "serve_uploads", self.serve_uploads, methods=["GET"]) - self.add_endpoint("/", "serve_static", self.serve_static, methods=["GET"]) - self.add_endpoint("/user_infos/", "serve_user_infos", self.serve_user_infos, methods=["GET"]) - - self.add_endpoint("/bindings/", "serve_bindings", self.serve_bindings, methods=["GET"]) - self.add_endpoint("/personalities/", "serve_personalities", self.serve_personalities, methods=["GET"]) - self.add_endpoint("/extensions/", "serve_extensions", self.serve_extensions, methods=["GET"]) - self.add_endpoint("/outputs/", "serve_outputs", self.serve_outputs, methods=["GET"]) - self.add_endpoint("/data/", "serve_data", self.serve_data, methods=["GET"]) - self.add_endpoint("/help/", "serve_help", self.serve_help, methods=["GET"]) - - self.add_endpoint("/audio/", "serve_audio", self.serve_audio, methods=["GET"]) - self.add_endpoint("/images/", "serve_images", self.serve_images, methods=["GET"]) - - - - self.add_endpoint("/install_extension", "install_extension", self.install_extension, methods=["POST"]) - self.add_endpoint("/reinstall_extension", "reinstall_extension", self.reinstall_extension, methods=["POST"]) - self.add_endpoint("/mount_extension", "mount_extension", self.p_mount_extension, methods=["POST"]) - self.add_endpoint("/remount_extension", "remount_extension", self.p_remount_extension, methods=["POST"]) - self.add_endpoint("/unmount_extension", "unmount_extension", self.p_unmount_extension, methods=["POST"]) - self.add_endpoint("/list_extensions_categories", "list_extensions_categories", self.list_extensions_categories, methods=["GET"]) - self.add_endpoint("/list_extensions", "list_extensions", self.list_extensions, methods=["GET"]) - self.add_endpoint("/get_all_extensions", "get_all_extensions", self.get_all_extensions, methods=["GET"]) - - - self.add_endpoint("/list_discussions", "list_discussions", self.list_discussions, methods=["GET"]) - self.add_endpoint("/export_discussion", "export_discussion", self.export_discussion, methods=["GET"]) - self.add_endpoint("/list_databases", "list_databases", self.list_databases, methods=["GET"]) - self.add_endpoint("/select_database", "select_database", self.select_database, methods=["POST"]) - self.add_endpoint("/rename_discussion", "rename_discussion", self.rename_discussion, methods=["POST"]) - self.add_endpoint("/delete_discussion","delete_discussion",self.delete_discussion,methods=["POST"]) - self.add_endpoint("/edit_title", "edit_title", self.edit_title, methods=["POST"]) - self.add_endpoint("/make_title", "make_title", self.make_title, methods=["POST"]) - self.add_endpoint("/export", "export", self.export, methods=["GET"]) - - self.add_endpoint("/export_multiple_discussions", "export_multiple_discussions", self.export_multiple_discussions, methods=["POST"]) - self.add_endpoint("/import_multiple_discussions", "import_multiple_discussions", self.import_multiple_discussions, methods=["POST"]) - - - self.add_endpoint("/get_generation_status", "get_generation_status", self.get_generation_status, methods=["GET"]) - self.add_endpoint("/stop_gen", "stop_gen", self.stop_gen, methods=["GET"]) - - - self.add_endpoint("/", "", self.index, methods=["GET"]) - self.add_endpoint("/settings/", "", self.index, methods=["GET"]) - self.add_endpoint("/playground/", "", self.index, methods=["GET"]) - self.add_endpoint("/extensions", "extensions", self.extensions, methods=["GET"]) - self.add_endpoint("/training", "training", self.training, methods=["GET"]) - self.add_endpoint("/main", "main", self.main, methods=["GET"]) - self.add_endpoint("/settings", "settings", self.settings, methods=["GET"]) - self.add_endpoint("/help", "help", self.help, methods=["GET"]) - - self.add_endpoint("/switch_personal_path", "switch_personal_path", self.switch_personal_path, methods=["POST"]) - self.add_endpoint("/upload_avatar", "upload_avatar", self.upload_avatar, methods=["POST"]) - - - self.add_endpoint("/edit_message", "edit_message", self.edit_message, methods=["GET"]) - self.add_endpoint("/message_rank_up", "message_rank_up", self.message_rank_up, methods=["GET"]) - self.add_endpoint("/message_rank_down", "message_rank_down", self.message_rank_down, methods=["GET"]) - self.add_endpoint("/delete_message", "delete_message", self.delete_message, methods=["GET"]) - - - self.add_endpoint("/get_config", "get_config", self.get_config, methods=["GET"]) - self.add_endpoint("/update_setting", "update_setting", self.update_setting, methods=["POST"]) - self.add_endpoint("/apply_settings", "apply_settings", self.apply_settings, methods=["POST"]) - - self.add_endpoint("/save_settings", "save_settings", self.save_settings, methods=["POST"]) - - - - self.add_endpoint("/open_code_folder", "open_code_folder", self.open_code_folder, methods=["POST"]) - self.add_endpoint("/open_code_folder_in_vs_code", "open_code_folder_in_vs_code", self.open_code_folder_in_vs_code, methods=["POST"]) - self.add_endpoint("/open_code_in_vs_code", "open_code_in_vs_code", self.open_code_in_vs_code, methods=["POST"]) - self.add_endpoint("/open_file", "open_file", self.open_file, methods=["GET"]) - - - self.add_endpoint("/reset", "reset", self.reset, methods=["GET"]) - self.add_endpoint("/get_server_address", "get_server_address", self.get_server_address, methods=["GET"]) - - - - self.add_endpoint("/list_voices", "list_voices", self.list_voices, methods=["GET"]) - self.add_endpoint("/set_voice", "set_voice", self.set_voice, methods=["POST"]) - self.add_endpoint("/text2Audio", "text2Audio", self.text2Audio, methods=["POST"]) - self.add_endpoint("/install_xtts", "install_xtts", self.install_xtts, methods=["GET"]) - - - - self.add_endpoint("/install_sd", "install_sd", self.install_sd, methods=["GET"]) - - - self.add_endpoint("/get_presets", "get_presets", self.get_presets, methods=["GET"]) - self.add_endpoint("/add_preset", "add_preset", self.add_preset, methods=["POST"]) - - self.add_endpoint("/save_presets", "save_presets", self.save_presets, methods=["POST"]) - - self.add_endpoint("/execute_code", "execute_code", self.execute_code, methods=["POST"]) - - self.add_endpoint("/update_binding_settings", "update_binding_settings", self.update_binding_settings, methods=["GET"]) - - # ---- - - - - - - - def update_binding_settings(self): - if self.binding: - self.binding.settings_updated() - ASCIIColors.green("Binding setting updated successfully") - return jsonify({"status":True}) - else: - return jsonify({"status":False, 'error':"no binding found"}) - - def reload_binding(self, data): - print(f"Roloading binding selected : {data['binding_name']}") - self.config["binding_name"]=data['binding_name'] - try: - if self.binding: - self.binding.destroy_model() - self.binding = None - self.model = None - for per in self.mounted_personalities: - if per is not None: - per.model = None - gc.collect() - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, InstallOption.INSTALL_IF_NECESSARY, lollmsCom=self) - self.model = None - self.config.save_config() - ASCIIColors.green("Binding loaded successfully") - except Exception as ex: - ASCIIColors.error(f"Couldn't build binding: [{ex}]") - trace_exception(ex) - return jsonify({"status":False, 'error':str(ex)}) - - def get_model_status(self): - return jsonify({"status":self.model is not None}) - - def get_server_address(self): - server_address = request.host_url - return server_address - - - def install_xtts(self): - try: - self.ShowBlockingMessage("Installing xTTS api server\nPlease stand by") - PackageManager.install_package("xtts-api-server") - self.HideBlockingMessage() - return jsonify({"status":True}) - except Exception as ex: - self.HideBlockingMessage() - return jsonify({"status":False, 'error':str(ex)}) - - def install_sd(self): - try: - self.ShowBlockingMessage("Installing SD api server\nPlease stand by") - from lollms.services.sd.lollms_sd import install_sd - install_sd() - ASCIIColors.success("Done") - self.HideBlockingMessage() - return jsonify({"status":True}) - except Exception as ex: - self.HideBlockingMessage() - return jsonify({"status":False, 'error':str(ex)}) - - def execute_python(self, code, discussion_id, message_id): - def spawn_process(code): - """Executes Python code and returns the output as JSON.""" - - # Start the timer. - start_time = time.time() - - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}" - root_folder.mkdir(parents=True,exist_ok=True) - tmp_file = root_folder/f"ai_code_{message_id}.py" - with open(tmp_file,"w",encoding="utf8") as f: - f.write(code) - - try: - # Execute the Python code in a temporary file. - process = subprocess.Popen( - ["python", str(tmp_file)], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - cwd=root_folder - ) - - # Get the output and error from the process. - output, error = process.communicate() - except Exception as ex: - # Stop the timer. - execution_time = time.time() - start_time - error_message = f"Error executing Python code: {ex}" - error_json = {"output": "
"+ex+"\n"+get_trace_exception(ex)+"
", "execution_time": execution_time} - return json.dumps(error_json) - - # Stop the timer. - execution_time = time.time() - start_time - - # Check if the process was successful. - if process.returncode != 0: - # The child process threw an exception. - error_message = f"Error executing Python code: {error.decode('utf8')}" - error_json = {"output": "
"+error_message+"
", "execution_time": execution_time} - return json.dumps(error_json) - - # The child process was successful. - output_json = {"output": output.decode("utf8"), "execution_time": execution_time} - return json.dumps(output_json) - return spawn_process(code) - - def execute_latex(self, code, discussion_id, message_id): - def spawn_process(code): - """Executes Python code and returns the output as JSON.""" - - # Start the timer. - start_time = time.time() - - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}" - root_folder.mkdir(parents=True,exist_ok=True) - tmp_file = root_folder/f"latex_file_{message_id}.tex" - with open(tmp_file,"w",encoding="utf8") as f: - f.write(code) - try: - # Determine the pdflatex command based on the provided or default path - if self.config.pdf_latex_path: - pdflatex_command = self.config.pdf_latex_path - else: - pdflatex_command = 'pdflatex' - # Set the execution path to the folder containing the tmp_file - execution_path = tmp_file.parent - # Run the pdflatex command with the file path - result = subprocess.run([pdflatex_command, "-interaction=nonstopmode", tmp_file], check=True, capture_output=True, text=True, cwd=execution_path) - # Check the return code of the pdflatex command - if result.returncode != 0: - error_message = result.stderr.strip() - execution_time = time.time() - start_time - error_json = {"output": f"Error occurred while compiling LaTeX: {error_message}", "execution_time": execution_time} - return json.dumps(error_json) - # If the compilation is successful, you will get a PDF file - pdf_file = tmp_file.with_suffix('.pdf') - print(f"PDF file generated: {pdf_file}") - - except subprocess.CalledProcessError as ex: - self.error(f"Error occurred while compiling LaTeX: {ex}") - error_json = {"output": "
"+str(ex)+"\n"+get_trace_exception(ex)+"
", "execution_time": execution_time} - return json.dumps(error_json) - - # Stop the timer. - execution_time = time.time() - start_time - - # The child process was successful. - pdf_file=str(pdf_file) - url = f"{url_for('main')[:-4]}{pdf_file[pdf_file.index('outputs'):]}" - output_json = {"output": f"Pdf file generated at: {pdf_file}\nClick here to show", "execution_time": execution_time} - return json.dumps(output_json) - return spawn_process(code) - - def execute_bash(self, code, discussion_id, message_id): - def spawn_process(code): - """Executes Python code and returns the output as JSON.""" - - # Start the timer. - start_time = time.time() - - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}" - root_folder.mkdir(parents=True,exist_ok=True) - try: - # Execute the Python code in a temporary file. - process = subprocess.Popen( - code, - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - - # Get the output and error from the process. - output, error = process.communicate() - except Exception as ex: - # Stop the timer. - execution_time = time.time() - start_time - error_message = f"Error executing shell cmmands: {ex}" - error_json = {"output": "
"+str(ex)+"\n"+get_trace_exception(ex)+"
", "execution_time": execution_time} - return json.dumps(error_json) - - # Stop the timer. - execution_time = time.time() - start_time - - # Check if the process was successful. - if process.returncode != 0: - # The child process threw an exception. - error_message = f"Error executing Python code: {error.decode('utf8')}" - error_json = {"output": "
"+error_message+"
", "execution_time": execution_time} - return json.dumps(error_json) - - # The child process was successful. - output_json = {"output": output.decode("utf8"), "execution_time": execution_time} - return json.dumps(output_json) - return spawn_process(code) - - def execute_code(self): - """Executes Python code and returns the output.""" - - data = request.get_json() - code = data["code"] - discussion_id = data.get("discussion_id","unknown_discussion") - message_id = data.get("message_id","unknown_message") - language = data.get("language","python") - - - ASCIIColors.info("Executing code:") - ASCIIColors.yellow(code) - - if language=="python": - return self.execute_python(code, discussion_id, message_id) - elif language=="latex": - return self.execute_latex(code, discussion_id, message_id) - elif language in ["bash","shell","cmd","powershell","sh"]: - return self.execute_bash(code, discussion_id, message_id) - return {"output": "Unsupported language", "execution_time": 0} - - - def open_code_folder_in_vs_code(self): - """Opens code folder in vs code.""" - - data = request.get_json() - code = data["code"] - discussion_id = data.get("discussion_id","unknown_discussion") - message_id = data.get("message_id","unknown_message") - language = data.get("language","python") - - ASCIIColors.info("Opening folder:") - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}" - root_folder.mkdir(parents=True,exist_ok=True) - tmp_file = root_folder/f"ai_code_{message_id}.py" - with open(tmp_file,"w") as f: - f.write(code) - - os.system('code ' + str(root_folder)) - return {"output": "OK", "execution_time": 0} - - def open_file(self): - """Opens code in vs code.""" - path = request.args.get('path') - os.system("start "+path) - return {"output": "OK", "execution_time": 0} - - def open_code_in_vs_code(self): - """Opens code in vs code.""" - - data = request.get_json() - discussion_id = data.get("discussion_id","unknown_discussion") - message_id = data.get("message_id","") - code = data["code"] - discussion_id = data.get("discussion_id","unknown_discussion") - message_id = data.get("message_id","unknown_message") - language = data.get("language","python") - - ASCIIColors.info("Opening folder:") - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}"/f"{message_id}.py" - root_folder.mkdir(parents=True,exist_ok=True) - tmp_file = root_folder/f"ai_code_{message_id}.py" - with open(tmp_file,"w") as f: - f.write(code) - os.system('code ' + str(root_folder)) - return {"output": "OK", "execution_time": 0} - - def open_code_folder(self): - """Opens code folder.""" - - data = request.get_json() - discussion_id = data.get("discussion_id","unknown_discussion") - - ASCIIColors.info("Opening folder:") - # Create a temporary file. - root_folder = self.lollms_paths.personal_outputs_path/"discussions"/f"d_{discussion_id}" - root_folder.mkdir(parents=True,exist_ok=True) - if platform.system() == 'Windows': - os.startfile(str(root_folder)) - elif platform.system() == 'Linux': - os.system('xdg-open ' + str(root_folder)) - elif platform.system() == 'Darwin': - os.system('open ' + str(root_folder)) - return {"output": "OK", "execution_time": 0} - - def copy_files(self, src, dest): - for item in os.listdir(src): - src_file = os.path.join(src, item) - dest_file = os.path.join(dest, item) - - if os.path.isfile(src_file): - shutil.copy2(src_file, dest_file) - - def get_presets(self): - presets = [] - presets_folder = Path("__file__").parent/"presets" - for filename in presets_folder.glob('*.yaml'): - with open(filename, 'r', encoding='utf-8') as file: - preset = yaml.safe_load(file) - if preset is not None: - presets.append(preset) - presets_folder = self.lollms_paths.personal_databases_path/"lollms_playground_presets" - presets_folder.mkdir(exist_ok=True, parents=True) - for filename in presets_folder.glob('*.yaml'): - with open(filename, 'r', encoding='utf-8') as file: - preset = yaml.safe_load(file) - if preset is not None: - presets.append(preset) - return jsonify(presets) - - - def list_voices(self): - ASCIIColors.yellow("Listing voices") - voices=["main_voice"] - voices_dir:Path=lollms_paths.custom_voices_path - voices += [v.stem for v in voices_dir.iterdir() if v.suffix==".wav"] - return jsonify({"voices":voices}) - - def set_voice(self): - data = request.get_json() - self.config.current_voice=data["voice"] - if self.config.auto_save: - self.config.save_config() - return jsonify({"status":True}) - - - def text2Audio(self): - # Get the JSON data from the POST request. - try: - from lollms.services.xtts.lollms_xtts import LollmsXTTS - if self.tts is None: - self.tts = LollmsXTTS(self, voice_samples_path=Path(__file__).parent/"voices", xtts_base_url= self.config.xtts_base_url) - except: - return jsonify({"url": None}) - - data = request.get_json() - voice=data.get("voice",self.config.current_voice) - index = find_first_available_file_index(self.tts.output_folder, "voice_sample_",".wav") - output_fn=data.get("fn",f"voice_sample_{index}.wav") - if voice is None: - voice = "main_voice" - self.info("Starting to build voice") - try: - from lollms.services.xtts.lollms_xtts import LollmsXTTS - if self.tts is None: - self.tts = LollmsXTTS(self, voice_samples_path=Path(__file__).parent/"voices") - language = self.config.current_language# convert_language_name() - if voice!="main_voice": - voices_folder = self.lollms_paths.custom_voices_path - else: - voices_folder = Path(__file__).parent/"voices" - self.tts.set_speaker_folder(voices_folder) - url = f"audio/{output_fn}" - preprocessed_text= add_period(data['text']) - - self.tts.tts_to_file(preprocessed_text, f"{voice}.wav", f"{output_fn}", language=language) - self.info("Voice file ready") - return jsonify({"url": url}) - except: - return jsonify({"url": None}) - - def add_preset(self): - # Get the JSON data from the POST request. - preset_data = request.get_json() - presets_folder = self.lollms_paths.personal_databases_path/"lollms_playground_presets" - if not presets_folder.exists(): - presets_folder.mkdir(exist_ok=True, parents=True) - - fn = preset_data["name"].lower().replace(" ","_") - filename = presets_folder/f"{fn}.yaml" - with open(filename, 'w', encoding='utf-8') as file: - yaml.dump(preset_data, file) - return jsonify({"status": True}) - - def del_preset(self): - presets_folder = self.lollms_paths.personal_databases_path/"lollms_playground_presets" - if not presets_folder.exists(): - presets_folder.mkdir(exist_ok=True, parents=True) - self.copy_files("presets",presets_folder) - presets = [] - for filename in presets_folder.glob('*.yaml'): - print(filename) - with open(filename, 'r') as file: - preset = yaml.safe_load(file) - if preset is not None: - presets.append(preset) - return jsonify(presets) - - - def save_presets(self): - """Saves a preset to a file. - - Args: - None. - - Returns: - None. - """ - - # Get the JSON data from the POST request. - preset_data = request.get_json() - - presets_file = self.lollms_paths.personal_databases_path/"presets.json" - # Save the JSON data to a file. - with open(presets_file, "w") as f: - json.dump(preset_data, f, indent=4) - - return jsonify({"status":True,"message":"Preset saved successfully!"}) - - def export_multiple_discussions(self): - data = request.get_json() - discussion_ids = data["discussion_ids"] - export_format = data["export_format"] - - if export_format=="json": - discussions = self.db.export_discussions_to_json(discussion_ids) - elif export_format=="markdown": - discussions = self.db.export_discussions_to_markdown(discussion_ids) - else: - discussions = self.db.export_discussions_to_markdown(discussion_ids) - return jsonify(discussions) - - def import_multiple_discussions(self): - discussions = request.get_json()["jArray"] - self.db.import_from_json(discussions) - return jsonify(discussions) - - def reset(self): - os.kill(os.getpid(), signal.SIGINT) # Send the interrupt signal to the current process - subprocess.Popen(['python', 'app.py']) # Restart the app using subprocess - - return 'App is resetting...' - - def save_settings(self): - self.config.save_config(self.config_file_path) - if self.config["debug"]: - print("Configuration saved") - # Tell that the setting was changed - self.sio.emit('save_settings', {"status":True}) - return jsonify({"status":True}) - - - def get_current_personality(self): - return jsonify({"personality":self.personality.as_dict()}) - - def get_all_personalities(self): - ASCIIColors.yellow("Listing all personalities") - personalities_folder = self.lollms_paths.personalities_zoo_path - personalities = {} - - for category_folder in [self.lollms_paths.custom_personalities_path] + list(personalities_folder.iterdir()): - cat = category_folder.stem - if category_folder.is_dir() and not category_folder.stem.startswith('.'): - personalities[cat if category_folder!=self.lollms_paths.custom_personalities_path else "custom_personalities"] = [] - for personality_folder in category_folder.iterdir(): - pers = personality_folder.stem - if personality_folder.is_dir() and not personality_folder.stem.startswith('.'): - personality_info = {"folder":personality_folder.stem} - config_path = personality_folder / 'config.yaml' - if not config_path.exists(): - """ - try: - shutil.rmtree(str(config_path.parent)) - ASCIIColors.warning(f"Deleted useless personality: {config_path.parent}") - except Exception as ex: - ASCIIColors.warning(f"Couldn't delete personality ({ex})") - """ - continue - try: - scripts_path = personality_folder / 'scripts' - personality_info['has_scripts'] = scripts_path.exists() - with open(config_path) as config_file: - config_data = yaml.load(config_file, Loader=yaml.FullLoader) - personality_info['name'] = config_data.get('name',"No Name") - personality_info['description'] = config_data.get('personality_description',"") - personality_info['disclaimer'] = config_data.get('disclaimer',"") - - personality_info['author'] = config_data.get('author', 'ParisNeo') - personality_info['version'] = config_data.get('version', '1.0.0') - personality_info['installed'] = (self.lollms_paths.personal_configuration_path/f"personality_{personality_folder.stem}.yaml").exists() or personality_info['has_scripts'] - personality_info['help'] = config_data.get('help', '') - personality_info['commands'] = config_data.get('commands', '') - - languages_path = personality_folder/ 'languages' - - real_assets_path = personality_folder/ 'assets' - assets_path = Path("personalities") / cat / pers / 'assets' - gif_logo_path = assets_path / 'logo.gif' - webp_logo_path = assets_path / 'logo.webp' - png_logo_path = assets_path / 'logo.png' - jpg_logo_path = assets_path / 'logo.jpg' - jpeg_logo_path = assets_path / 'logo.jpeg' - svg_logo_path = assets_path / 'logo.svg' - bmp_logo_path = assets_path / 'logo.bmp' - - gif_logo_path_ = real_assets_path / 'logo.gif' - webp_logo_path_ = real_assets_path / 'logo.webp' - png_logo_path_ = real_assets_path / 'logo.png' - jpg_logo_path_ = real_assets_path / 'logo.jpg' - jpeg_logo_path_ = real_assets_path / 'logo.jpeg' - svg_logo_path_ = real_assets_path / 'logo.svg' - bmp_logo_path_ = real_assets_path / 'logo.bmp' - - if languages_path.exists(): - personality_info['languages']= [""]+[f.stem for f in languages_path.iterdir() if f.suffix==".yaml"] - else: - personality_info['languages']=None - - personality_info['has_logo'] = png_logo_path.is_file() or gif_logo_path.is_file() - - if gif_logo_path_.exists(): - personality_info['avatar'] = str(gif_logo_path).replace("\\","/") - elif webp_logo_path_.exists(): - personality_info['avatar'] = str(webp_logo_path).replace("\\","/") - elif png_logo_path_.exists(): - personality_info['avatar'] = str(png_logo_path).replace("\\","/") - elif jpg_logo_path_.exists(): - personality_info['avatar'] = str(jpg_logo_path).replace("\\","/") - elif jpeg_logo_path_.exists(): - personality_info['avatar'] = str(jpeg_logo_path).replace("\\","/") - elif svg_logo_path_.exists(): - personality_info['avatar'] = str(svg_logo_path).replace("\\","/") - elif bmp_logo_path_.exists(): - personality_info['avatar'] = str(bmp_logo_path).replace("\\","/") - else: - personality_info['avatar'] = "" - - personalities[cat if category_folder!=self.lollms_paths.custom_personalities_path else "custom_personalities"].append(personality_info) - except Exception as ex: - ASCIIColors.warning(f"Couldn't load personality from {personality_folder} [{ex}]") - trace_exception(ex) - ASCIIColors.green("OK") - - return json.dumps(personalities) - - def get_personality(self): - category = request.args.get('category') - name = request.args.get('name') - if category == "custom_personalities": - personality_folder = self.lollms_paths.custom_personalities_path/f"{name}" - else: - personality_folder = self.lollms_paths.personalities_zoo_path/f"{category}"/f"{name}" - personality_path = personality_folder/f"config.yaml" - personality_info = {} - with open(personality_path) as config_file: - config_data = yaml.load(config_file, Loader=yaml.FullLoader) - personality_info['name'] = config_data.get('name',"unnamed") - personality_info['description'] = config_data.get('personality_description',"") - personality_info['author'] = config_data.get('creator', 'ParisNeo') - personality_info['version'] = config_data.get('version', '1.0.0') - scripts_path = personality_folder / 'scripts' - personality_info['has_scripts'] = scripts_path.is_dir() - assets_path = personality_folder / 'assets' - gif_logo_path = assets_path / 'logo.gif' - webp_logo_path = assets_path / 'logo.webp' - png_logo_path = assets_path / 'logo.png' - jpg_logo_path = assets_path / 'logo.jpg' - jpeg_logo_path = assets_path / 'logo.jpeg' - bmp_logo_path = assets_path / 'logo.bmp' - - personality_info['has_logo'] = png_logo_path.is_file() or gif_logo_path.is_file() - - if gif_logo_path.exists(): - personality_info['avatar'] = str(gif_logo_path).replace("\\","/") - elif webp_logo_path.exists(): - personality_info['avatar'] = str(webp_logo_path).replace("\\","/") - elif png_logo_path.exists(): - personality_info['avatar'] = str(png_logo_path).replace("\\","/") - elif jpg_logo_path.exists(): - personality_info['avatar'] = str(jpg_logo_path).replace("\\","/") - elif jpeg_logo_path.exists(): - personality_info['avatar'] = str(jpeg_logo_path).replace("\\","/") - elif bmp_logo_path.exists(): - personality_info['avatar'] = str(bmp_logo_path).replace("\\","/") - else: - personality_info['avatar'] = "" - return json.dumps(personality_info) - - # Settings (data: {"setting_name":,"setting_value":}) - def update_setting(self): - data = request.get_json() - setting_name = data['setting_name'] - - ASCIIColors.info(f"Requested updating of setting {data['setting_name']} to {data['setting_value']}") - if setting_name== "temperature": - self.config["temperature"]=float(data['setting_value']) - elif setting_name== "n_predict": - self.config["n_predict"]=int(data['setting_value']) - elif setting_name== "top_k": - self.config["top_k"]=int(data['setting_value']) - elif setting_name== "top_p": - self.config["top_p"]=float(data['setting_value']) - - elif setting_name== "repeat_penalty": - self.config["repeat_penalty"]=float(data['setting_value']) - elif setting_name== "repeat_last_n": - self.config["repeat_last_n"]=int(data['setting_value']) - - elif setting_name== "n_threads": - self.config["n_threads"]=int(data['setting_value']) - elif setting_name== "ctx_size": - self.config["ctx_size"]=int(data['setting_value']) - - elif setting_name== "personality_folder": - self.personality_name=data['setting_value'] - if len(self.config["personalities"])>0: - if self.config["active_personality_id"] Optional[dict]: - try: - output = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.total,memory.used,gpu_name', '--format=csv,nounits,noheader']) - lines = output.decode().strip().split('\n') - vram_info = [line.split(',') for line in lines] - except (subprocess.CalledProcessError, FileNotFoundError): - return { - "nb_gpus": 0 - } - - ram_usage = { - "nb_gpus": len(vram_info) - } - - if vram_info is not None: - for i, gpu in enumerate(vram_info): - ram_usage[f"gpu_{i}_total_vram"] = int(gpu[0])*1024*1024 - ram_usage[f"gpu_{i}_used_vram"] = int(gpu[1])*1024*1024 - ram_usage[f"gpu_{i}_model"] = gpu[2].strip() - else: - # Set all VRAM-related entries to None - ram_usage["gpu_0_total_vram"] = None - ram_usage["gpu_0_used_vram"] = None - ram_usage["gpu_0_model"] = None - - return jsonify(ram_usage) - - def disk_usage(self): - current_drive = Path.cwd().anchor - drive_disk_usage = psutil.disk_usage(current_drive) - try: - models_folder_disk_usage = psutil.disk_usage(str(self.lollms_paths.personal_models_path/f'{self.config["binding_name"]}')) - return jsonify( { - "total_space":drive_disk_usage.total, - "available_space":drive_disk_usage.free, - "usage":drive_disk_usage.used, - "percent_usage":drive_disk_usage.percent, - - "binding_disk_total_space":models_folder_disk_usage.total, - "binding_disk_available_space":models_folder_disk_usage.free, - "binding_models_usage": models_folder_disk_usage.used, - "binding_models_percent_usage": models_folder_disk_usage.percent, - }) - except Exception as ex: - return jsonify({ - "total_space":drive_disk_usage.total, - "available_space":drive_disk_usage.free, - "percent_usage":drive_disk_usage.percent, - - "binding_disk_total_space": None, - "binding_disk_available_space": None, - "binding_models_usage": None, - "binding_models_percent_usage": None, - }) - - def find_extension(self, path:Path, filename:str, exts:list)->Path: - for ext in exts: - full_path = path/(filename+ext) - if full_path.exists(): - return full_path - return None - - def list_bindings(self): - bindings_dir = self.lollms_paths.bindings_zoo_path # replace with the actual path to the models folder - bindings=[] - for f in bindings_dir.iterdir(): - if f.stem!="binding_template": - card = f/"binding_card.yaml" - if card.exists(): - try: - bnd = load_config(card) - bnd["folder"]=f.stem - installed = (self.lollms_paths.personal_configuration_path/"bindings"/f.stem/f"config.yaml").exists() - bnd["installed"]=installed - ui_file_path = f/"ui.html" - if ui_file_path.exists(): - with ui_file_path.open("r") as file: - text_content = file.read() - bnd["ui"]=text_content - else: - bnd["ui"]=None - disclaimer_file_path = f/"disclaimer.md" - if disclaimer_file_path.exists(): - with disclaimer_file_path.open("r") as file: - text_content = file.read() - bnd["disclaimer"]=text_content - else: - bnd["disclaimer"]=None - icon_file = self.find_extension(self.lollms_paths.bindings_zoo_path/f"{f.name}", "logo", [".svg",".gif",".png"]) - if icon_file is not None: - icon_path = Path(f"bindings/{f.name}/logo{icon_file.suffix}") - bnd["icon"]=str(icon_path) - - bindings.append(bnd) - except Exception as ex: - print(f"Couldn't load backend card : {f}\n\t{ex}") - return jsonify(bindings) - - - - def list_extensions(self): - return self.config.extensions - - def get_all_extensions(self): - ASCIIColors.yellow("Gatting all extensions") - extensions_folder = self.lollms_paths.extensions_zoo_path - extensions = {} - - for category_folder in extensions_folder.iterdir(): - cat = category_folder.stem - if category_folder.is_dir() and not category_folder.stem.startswith('.'): - extensions[category_folder.name] = [] - for extensions_folder in category_folder.iterdir(): - ext = extensions_folder.stem - if extensions_folder.is_dir() and not extensions_folder.stem.startswith('.'): - extension_info = {"folder":extensions_folder.stem} - config_path = extensions_folder / 'config.yaml' - if not config_path.exists(): - continue - try: - with open(config_path) as config_file: - config_data = yaml.load(config_file, Loader=yaml.FullLoader) - extension_info['name'] = config_data.get('name',"No Name") - extension_info['author'] = config_data.get('author', 'ParisNeo') - extension_info['based_on'] = config_data.get('based_on',"") - extension_info['description'] = config_data.get('description',"") - extension_info['version'] = config_data.get('version', '1.0.0') - extension_info['installed'] = (self.lollms_paths.personal_configuration_path/f"personality_{extensions_folder.stem}.yaml").exists() - extension_info['help'] = config_data.get('help', '') - - real_assets_path = extensions_folder/ 'assets' - assets_path = Path("extensions") / cat / ext / 'assets' - gif_logo_path = assets_path / 'logo.gif' - webp_logo_path = assets_path / 'logo.webp' - png_logo_path = assets_path / 'logo.png' - jpg_logo_path = assets_path / 'logo.jpg' - jpeg_logo_path = assets_path / 'logo.jpeg' - svg_logo_path = assets_path / 'logo.svg' - bmp_logo_path = assets_path / 'logo.bmp' - - gif_logo_path_ = real_assets_path / 'logo.gif' - webp_logo_path_ = real_assets_path / 'logo.webp' - png_logo_path_ = real_assets_path / 'logo.png' - jpg_logo_path_ = real_assets_path / 'logo.jpg' - jpeg_logo_path_ = real_assets_path / 'logo.jpeg' - svg_logo_path_ = real_assets_path / 'logo.svg' - bmp_logo_path_ = real_assets_path / 'logo.bmp' - - extension_info['has_logo'] = png_logo_path.is_file() or gif_logo_path.is_file() - - if gif_logo_path_.exists(): - extension_info['avatar'] = str(gif_logo_path).replace("\\","/") - elif webp_logo_path_.exists(): - extension_info['avatar'] = str(webp_logo_path).replace("\\","/") - elif png_logo_path_.exists(): - extension_info['avatar'] = str(png_logo_path).replace("\\","/") - elif jpg_logo_path_.exists(): - extension_info['avatar'] = str(jpg_logo_path).replace("\\","/") - elif jpeg_logo_path_.exists(): - extension_info['avatar'] = str(jpeg_logo_path).replace("\\","/") - elif svg_logo_path_.exists(): - extension_info['avatar'] = str(svg_logo_path).replace("\\","/") - elif bmp_logo_path_.exists(): - extension_info['avatar'] = str(bmp_logo_path).replace("\\","/") - else: - extension_info['avatar'] = "" - - extensions[category_folder.name].append(extension_info) - except Exception as ex: - ASCIIColors.warning(f"Couldn't load personality from {extensions_folder} [{ex}]") - trace_exception(ex) - return extensions - - def list_models(self): - if self.binding is not None: - ASCIIColors.yellow("Listing models") - models = self.binding.list_models() - ASCIIColors.green("ok") - return jsonify(models) - else: - return jsonify([]) - - def get_active_model(self): - if self.binding is not None: - try: - ASCIIColors.yellow("Getting active model") - models = self.binding.list_models() - index = models.index(self.config.model_name) - ASCIIColors.green("ok") - return jsonify({"status":True,"model":models[index],"index":index}) - except Exception as ex: - return jsonify({"status":False}) - else: - return jsonify({"status":False}) - - def list_personalities_categories(self): - personalities_categories_dir = self.lollms_paths.personalities_zoo_path # replace with the actual path to the models folder - personalities_categories = ["custom_personalities"]+[f.stem for f in personalities_categories_dir.iterdir() if f.is_dir() and not f.name.startswith(".")] - return jsonify(personalities_categories) - - def list_personalities(self): - category = request.args.get('category') - if not category: - return jsonify([]) - try: - if category=="custom_personalities": - personalities_dir = self.lollms_paths.custom_personalities_path # replace with the actual path to the models folder - else: - personalities_dir = self.lollms_paths.personalities_zoo_path/f'{category}' # replace with the actual path to the models folder - personalities = [f.stem for f in personalities_dir.iterdir() if f.is_dir() and not f.name.startswith(".")] - except Exception as ex: - personalities=[] - ASCIIColors.error(f"No personalities found. Using default one {ex}") - return jsonify(personalities) - - def list_databases(self): - databases = [f.name for f in self.lollms_paths.personal_databases_path.iterdir() if f.suffix==".db"] - return jsonify(databases) - - def select_database(self): - data = request.get_json() - if not data["name"].endswith(".db"): - data["name"] += ".db" - print(f'Selecting database {data["name"]}') - # Create database object - self.db = DiscussionsDB(self.lollms_paths.personal_databases_path/data["name"]) - ASCIIColors.info("Checking discussions database... ",end="") - self.db.create_tables() - self.db.add_missing_columns() - self.config.db_path = data["name"] - ASCIIColors.success("ok") - - if self.config.auto_save: - self.config.save_config() - - if self.config.data_vectorization_activate and self.config.use_discussions_history: - try: - ASCIIColors.yellow("0- Detected discussion vectorization request") - folder = self.lollms_paths.personal_databases_path/"vectorized_dbs" - folder.mkdir(parents=True, exist_ok=True) - self.long_term_memory = TextVectorizer( - vectorization_method=VectorizationMethod.TFIDF_VECTORIZER,#=VectorizationMethod.BM25_VECTORIZER, - database_path=folder/self.config.db_path, - data_visualization_method=VisualizationMethod.PCA,#VisualizationMethod.PCA, - save_db=True - ) - ASCIIColors.yellow("1- Exporting discussions") - self.info("Exporting discussions") - discussions = self.db.export_all_as_markdown_list_for_vectorization() - ASCIIColors.yellow("2- Adding discussions to vectorizer") - self.info("Adding discussions to vectorizer") - index = 0 - nb_discussions = len(discussions) - - for (title,discussion) in tqdm(discussions): - self.sio.emit('update_progress',{'value':int(100*(index/nb_discussions))}) - index += 1 - if discussion!='': - skill = self.learn_from_discussion(title, discussion) - self.long_term_memory.add_document(title, skill, chunk_size=self.config.data_vectorization_chunk_size, overlap_size=self.config.data_vectorization_overlap_size, force_vectorize=False, add_as_a_bloc=False) - ASCIIColors.yellow("3- Indexing database") - self.info("Indexing database",True, None) - self.long_term_memory.index() - ASCIIColors.yellow("Ready") - except Exception as ex: - self.error(f"Couldn't vectorize the database:{ex}") - - - return jsonify({"status":True}) - - - - - def list_discussions(self): - discussions = self.db.get_discussions() - return jsonify(discussions) - - - def add_endpoint( - self, - endpoint=None, - endpoint_name=None, - handler=None, - methods=["GET"], - *args, - **kwargs, - ): - self.app.add_url_rule( - endpoint, endpoint_name, handler, methods=methods, *args, **kwargs - ) - - def index(self): - return render_template("index.html") - - def serve_static(self, filename): - root_dir = os.getcwd() - path = os.path.join(root_dir, 'web/dist/')+"/".join(filename.split("/")[:-1]) - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - - def serve_images(self, filename): - root_dir = os.getcwd() - path = os.path.join(root_dir, 'images/')+"/".join(filename.split("/")[:-1]) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_audio(self, filename): - root_dir = self.lollms_paths.personal_outputs_path - path = os.path.join(root_dir, 'audio_out/')+"/".join(filename.split("/")[:-1]) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - - - def serve_extensions(self, filename): - path = str(self.lollms_paths.extensions_zoo_path/("/".join(filename.split("/")[:-1]))) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - - - def serve_bindings(self, filename): - path = str(self.lollms_paths.bindings_zoo_path/("/".join(filename.split("/")[:-1]))) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_user_infos(self, filename): - path = str(self.lollms_paths.personal_user_infos_path/("/".join(filename.split("/")[:-1]))) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - - - def serve_personalities(self, filename): - if "custom_personalities" in filename: - path = str(self.lollms_paths.custom_personalities_path/("/".join(filename.split("/")[1:-1]))) - else: - path = str(self.lollms_paths.personalities_zoo_path/("/".join(filename.split("/")[:-1]))) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_outputs(self, filename): - root_dir = self.lollms_paths.personal_path / "outputs" - root_dir.mkdir(exist_ok=True, parents=True) - path = str(root_dir/"/".join(filename.split("/")[:-1])) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_help(self, filename): - root_dir = Path(__file__).parent/f"help" - root_dir.mkdir(exist_ok=True, parents=True) - path = str(root_dir/"/".join(filename.split("/")[:-1])) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_data(self, filename): - root_dir = self.lollms_paths.personal_path / "data" - root_dir.mkdir(exist_ok=True, parents=True) - path = str(root_dir/"/".join(filename.split("/")[:-1])) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - def serve_uploads(self, filename): - root_dir = self.lollms_paths.personal_path / "uploads" - root_dir.mkdir(exist_ok=True, parents=True) - - path = str(root_dir/"/".join(filename.split("/")[:-1])) - - fn = filename.split("/")[-1] - return send_from_directory(path, fn) - - - - def export(self): - return jsonify(self.db.export_to_json()) - - def export_discussion(self): - return jsonify({"discussion_text":self.get_discussion_to()}) - - - - def get_generation_status(self): - return jsonify({"status":self.busy}) - - def stop_gen(self): - self.cancel_gen = True - return jsonify({"status": True}) - - - def switch_personal_path(self): - data = request.get_json() - path = data["path"] - global_paths_cfg = Path("./global_paths_cfg.yaml") - if global_paths_cfg.exists(): - try: - cfg = BaseConfig() - cfg.load_config(global_paths_cfg) - cfg.lollms_personal_path = path - cfg.save_config(global_paths_cfg) - return jsonify({"status": True}) - except Exception as ex: - print(ex) - return jsonify({"status": False, 'error':f"Couldn't switch path: {ex}"}) - - def add_reference_to_local_model(self): - data = request.get_json() - if data["path"]=="": - return jsonify({"status": False, "error":"Empty model path"}) - - path = Path(data["path"]) - if path.exists(): - self.config.reference_model(path) - return jsonify({"status": True}) - else: - return jsonify({"status": False, "error":"Model not found"}) - - def list_mounted_personalities(self): - ASCIIColors.yellow("- Listing mounted personalities") - return jsonify({"status": True, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - - - - def reinstall_personality(self): - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return jsonify({"status":False, 'error':str(e)}) - if not 'name' in data: - data['name']=self.config.personalities[self.config["active_personality_id"]] - try: - personality_path = self.lollms_paths.personalities_zoo_path / data['name'] - ASCIIColors.info(f"- Reinstalling personality {data['name']}...") - ASCIIColors.info("Unmounting personality") - idx = self.config.personalities.index(data['name']) - print(f"index = {idx}") - self.mounted_personalities[idx] = None - gc.collect() - try: - self.mounted_personalities[idx] = AIPersonality(personality_path, - self.lollms_paths, - self.config, - model=self.model, - app=self, - run_scripts=True,installation_option=InstallOption.FORCE_INSTALL) - return jsonify({"status":True}) - except Exception as ex: - ASCIIColors.error(f"Personality file not found or is corrupted ({data['name']}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.") - ASCIIColors.info("Trying to force reinstall") - return jsonify({"status":False, 'error':str(e)}) - - except Exception as e: - return jsonify({"status":False, 'error':str(e)}) - - def post_to_personality(self): - data = request.get_json() - if hasattr(self.personality.processor,'handle_request'): - return await self.personality.processor.handle_request(data) - else: - return jsonify({}) - - def install_binding(self): - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return jsonify({"status":False, 'error':str(e)}) - ASCIIColors.info(f"- Reinstalling binding {data['name']}...") - try: - self.info("Unmounting binding and model") - self.info("Reinstalling binding") - old_bn = self.config.binding_name - self.config.binding_name = data['name'] - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, InstallOption.FORCE_INSTALL, lollmsCom=self) - self.success("Binding installed successfully") - del self.binding - self.binding = None - self.config.binding_name = old_bn - if old_bn is not None: - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, lollmsCom=self) - self.model = self.binding.build_model() - for per in self.mounted_personalities: - if per is not None: - per.model = self.model - return jsonify({"status": True}) - except Exception as ex: - self.error(f"Couldn't build binding: [{ex}]") - trace_exception(ex) - return jsonify({"status":False, 'error':str(ex)}) - - def reinstall_binding(self): - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return jsonify({"status":False, 'error':str(e)}) - ASCIIColors.info(f"- Reinstalling binding {data['name']}...") - try: - ASCIIColors.info("Unmounting binding and model") - del self.binding - self.binding = None - gc.collect() - ASCIIColors.info("Reinstalling binding") - old_bn = self.config.binding_name - self.config.binding_name = data['name'] - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, InstallOption.FORCE_INSTALL, lollmsCom=self) - self.success("Binding reinstalled successfully") - self.config.binding_name = old_bn - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, lollmsCom=self) - self.model = self.binding.build_model() - for per in self.mounted_personalities: - if per is not None: - per.model = self.model - - return jsonify({"status": True}) - except Exception as ex: - ASCIIColors.error(f"Couldn't build binding: [{ex}]") - trace_exception(ex) - return jsonify({"status":False, 'error':str(ex)}) - - def unInstall_binding(self): - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - ASCIIColors.error(f"Error occurred while parsing JSON: {e}") - return jsonify({"status":False, 'error':str(e)}) - ASCIIColors.info(f"- Reinstalling binding {data['name']}...") - try: - ASCIIColors.info("Unmounting binding and model") - if self.binding is not None: - del self.binding - self.binding = None - gc.collect() - ASCIIColors.info("Uninstalling binding") - old_bn = self.config.binding_name - self.config.binding_name = data['name'] - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, InstallOption.NEVER_INSTALL, lollmsCom=self) - self.binding.uninstall() - ASCIIColors.green("Uninstalled successful") - if old_bn!=self.config.binding_name: - self.config.binding_name = old_bn - self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths, lollmsCom=self) - self.model = self.binding.build_model() - for per in self.mounted_personalities: - if per is not None: - per.model = self.model - else: - self.config.binding_name = None - if self.config.auto_save: - ASCIIColors.info("Saving configuration") - self.config.save_config() - - return jsonify({"status": True}) - except Exception as ex: - ASCIIColors.error(f"Couldn't build binding: [{ex}]") - trace_exception(ex) - return jsonify({"status":False, 'error':str(ex)}) - - def clear_uploads(self): - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info(" ╔══════════════════════════════════════════════════╗") - ASCIIColors.info(" ║ Removing all uploads ║") - ASCIIColors.info(" ╚══════════════════════════════════════════════════╝") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - try: - folder_path = self.lollms_paths.personal_uploads_path - # Iterate over all files and directories in the folder - for entry in folder_path.iterdir(): - if entry.is_file(): - # Remove file - entry.unlink() - elif entry.is_dir(): - # Remove directory (recursively) - shutil.rmtree(entry) - print(f"All files and directories inside '{folder_path}' have been removed successfully.") - return {"status": True} - except OSError as e: - ASCIIColors.error(f"Couldn't clear the upload folder.\nMaybe some files are opened somewhere else.\Try doing it manually") - return {"status": False, 'error': "Couldn't clear the upload folder.\nMaybe some files are opened somewhere else.\Try doing it manually"} - - def check_update(self): - if self.config.auto_update: - res = check_update_() - return jsonify({'update_availability':res}) - else: - return jsonify({'update_availability':False}) - - def restart_program(self): - socketio.reboot=True - self.sio.stop() - self.sio.sleep(1) - - - def update_software(self): - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info(" ╔══════════════════════════════════════════════════╗") - ASCIIColors.info(" ║ Updating backend ║") - ASCIIColors.info(" ╚══════════════════════════════════════════════════╝") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - self.sio.stop() - run_update_script(self.args) - sys.exit() - - def get_current_personality_files_list(self): - if self.personality is None: - return jsonify({"state":False, "error":"No personality selected"}) - return jsonify({"state":True, "files":[{"name":Path(f).name, "size":Path(f).stat().st_size} for f in self.personality.text_files]+[{"name":Path(f).name, "size":Path(f).stat().st_size} for f in self.personality.image_files]}) - - def clear_personality_files_list(self): - if self.personality is None: - return jsonify({"state":False, "error":"No personality selected"}) - self.personality.remove_all_files() - return jsonify({"state":True}) - - def start_training(self): - if self.config.hardware_mode=="nvidia-tensorcores" or self.config.hardware_mode=="nvidia" or self.config.hardware_mode=="apple-intel" or self.config.hardware_mode=="apple-silicon": - if not self.lollms_paths.gptqlora_path.exists(): - # Clone the repository to the target path - ASCIIColors.info("No gptqlora found in your personal space.\nCloning the gptqlora repo") - subprocess.run(["git", "clone", gptqlora_repo, self.lollms_paths.gptqlora_path]) - subprocess.run(["pip", "install", "-r", "requirements.txt"], cwd=self.lollms_paths.gptqlora_path) - - data = request.get_json() - ASCIIColors.info(f"--- Trainging of model {data['model_name']} requested ---") - ASCIIColors.info(f"Cleaning memory:") - fn = self.binding.binding_folder_name - del self.binding - self.binding = None - self.model = None - for per in self.mounted_personalities: - if per is not None: - per.model = None - gc.collect() - ASCIIColors.info(f"issuing command : python gptqlora.py --model_path {self.lollms_paths.personal_models_path/fn/data['model_name']}") - subprocess.run(["python", "gptqlora.py", "--model_path", self.lollms_paths.personal_models_path/fn/data["model_name"]],cwd=self.lollms_paths.gptqlora_path) - return jsonify({'status':True}) - - def get_lollms_version(self): - version = pkg_resources.get_distribution('lollms').version - ASCIIColors.yellow("Lollms version : "+ version) - return jsonify({"version":version}) - - def get_lollms_webui_version(self): - version = __version__ - ASCIIColors.yellow("Lollms webui version : "+ version) - return jsonify({"version":version}) - - def p_mount_personality(self): - print("- Mounting personality") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - - language = data.get('language', None) - - package_path = f"{category}/{name}" - if category=="custom_personalities": - package_full_path = self.lollms_paths.custom_personalities_path/f"{name}" - else: - package_full_path = self.lollms_paths.personalities_zoo_path/package_path - - config_file = package_full_path / "config.yaml" - if config_file.exists(): - if language: - package_path += ":" + language - """ - if package_path in self.config["personalities"]: - ASCIIColors.error("Can't mount exact same personality twice") - return jsonify({"status": False, - "error":"Can't mount exact same personality twice", - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - """ - self.config["personalities"].append(package_path) - self.mounted_personalities = self.rebuild_personalities() - self.config["active_personality_id"]= len(self.config["personalities"])-1 - self.personality = self.mounted_personalities[self.config["active_personality_id"]] - ASCIIColors.success("ok") - if self.config["active_personality_id"]<0: - ASCIIColors.error("error:active_personality_id<0") - return jsonify({"status": False, - "error":"active_personality_id<0", - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - if self.config.auto_save: - ASCIIColors.info("Saving configuration") - self.config.save_config() - ASCIIColors.success(f"Personality {name} mounted successfully") - return jsonify({"status": True, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - pth = str(config_file).replace('\\','/') - ASCIIColors.error(f"nok : Personality not found @ {pth}") - ASCIIColors.yellow(f"Available personalities: {[p.name for p in self.mounted_personalities]}") - return jsonify({"status": False, "error":f"Personality not found @ {pth}"}) - - - - def p_remount_personality(self): - print("- Remounting personality") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - - package_path = f"{category}/{name}" - if category=="custom_personalities": - package_full_path = self.lollms_paths.custom_personalities_path/f"{name}" - else: - package_full_path = self.lollms_paths.personalities_zoo_path/package_path - - config_file = package_full_path / "config.yaml" - if config_file.exists(): - ASCIIColors.info(f"Unmounting personality {package_path}") - index = self.config["personalities"].index(f"{category}/{name}") - self.config["personalities"].remove(f"{category}/{name}") - if self.config["active_personality_id"]>=index: - self.config["active_personality_id"]=0 - if len(self.config["personalities"])>0: - self.mounted_personalities = self.rebuild_personalities() - self.personality = self.mounted_personalities[self.config["active_personality_id"]] - else: - self.personalities = ["generic/lollms"] - self.mounted_personalities = self.rebuild_personalities() - self.personality = self.mounted_personalities[self.config["active_personality_id"]] - - - ASCIIColors.info(f"Mounting personality {package_path}") - self.config["personalities"].append(package_path) - self.config["active_personality_id"]= len(self.config["personalities"])-1 - self.mounted_personalities = self.rebuild_personalities() - self.personality = self.mounted_personalities[self.config["active_personality_id"]] - ASCIIColors.success("ok") - if self.config["active_personality_id"]<0: - return jsonify({"status": False, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - return jsonify({"status": True, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - pth = str(config_file).replace('\\','/') - ASCIIColors.error(f"nok : Personality not found @ {pth}") - ASCIIColors.yellow(f"Available personalities: {[p.name for p in self.mounted_personalities]}") - return jsonify({"status": False, "error":f"Personality not found @ {pth}"}) - - def p_unmount_personality(self): - print("- Unmounting personality ...") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - language = data.get('language',None) - try: - personality_id = f"{category}/{name}" if language is None or language=="" else f"{category}/{name}:{language}" - index = self.config["personalities"].index(personality_id) - self.config["personalities"].remove(personality_id) - if self.config["active_personality_id"]>=index: - self.config["active_personality_id"]=0 - if len(self.config["personalities"])>0: - self.mounted_personalities = self.rebuild_personalities() - self.personality = self.mounted_personalities[self.config["active_personality_id"]] - else: - self.personalities = ["generic/lollms"] - self.mounted_personalities = self.rebuild_personalities() - if self.config["active_personality_id"]idx: - del self.mounted_extensions[idx] - gc.collect() - try: - self.mounted_extensions.append(ExtensionBuilder().build_extension(extension_path,self.lollms_paths, self, InstallOption.FORCE_INSTALL)) - return jsonify({"status":True}) - except Exception as ex: - ASCIIColors.error(f"Extension file not found or is corrupted ({data['name']}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.") - trace_exception(ex) - ASCIIColors.info("Trying to force reinstall") - return jsonify({"status":False, 'error':str(e)}) - - except Exception as e: - return jsonify({"status":False, 'error':str(e)}) - - def p_mount_extension(self): - print("- Mounting extension") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - - package_path = f"{category}/{name}" - package_full_path = self.lollms_paths.extensions_zoo_path/package_path - config_file = package_full_path / "config.yaml" - if config_file.exists(): - self.config["extensions"].append(package_path) - self.mounted_extensions = self.rebuild_extensions() - ASCIIColors.success("ok") - if self.config.auto_save: - ASCIIColors.info("Saving configuration") - self.config.save_config() - ASCIIColors.success(f"Extension {name} mounted successfully") - return jsonify({"status": True, - "extensions":self.config["extensions"], - }) - else: - pth = str(config_file).replace('\\','/') - ASCIIColors.error(f"nok : Extension not found @ {pth}") - return jsonify({"status": False, "error":f"Extension not found @ {pth}"}) - - - - def p_remount_extension(self): - print("- Remounting extension") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - - - - - package_path = f"{category}/{name}" - package_full_path = self.lollms_paths.extensions_zoo_path/package_path - config_file = package_full_path / "config.yaml" - if config_file.exists(): - ASCIIColors.info(f"Unmounting personality {package_path}") - index = self.config["extensions"].index(f"{category}/{name}") - self.config["extensions"].remove(f"{category}/{name}") - if len(self.config["extensions"])>0: - self.mounted_personalities = self.rebuild_extensions() - else: - self.personalities = ["generic/lollms"] - self.mounted_personalities = self.rebuild_extensions() - - - ASCIIColors.info(f"Mounting personality {package_path}") - self.config["personalities"].append(package_path) - self.mounted_personalities = self.rebuild_extensions() - ASCIIColors.success("ok") - if self.config["active_personality_id"]<0: - return jsonify({"status": False, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - return jsonify({"status": True, - "personalities":self.config["personalities"], - "active_personality_id":self.config["active_personality_id"] - }) - else: - pth = str(config_file).replace('\\','/') - ASCIIColors.error(f"nok : Personality not found @ {pth}") - ASCIIColors.yellow(f"Available personalities: {[p.name for p in self.mounted_personalities]}") - return jsonify({"status": False, "error":f"Personality not found @ {pth}"}) - - def p_unmount_extension(self): - print("- Unmounting extension ...") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - language = data.get('language',None) - try: - personality_id = f"{category}/{name}" if language is None else f"{category}/{name}:{language}" - index = self.config["personalities"].index(personality_id) - self.config["extensions"].remove(personality_id) - self.mounted_extensions = self.rebuild_extensions() - ASCIIColors.success("ok") - if self.config.auto_save: - ASCIIColors.info("Saving configuration") - self.config.save_config() - return jsonify({ - "status": True, - "extensions":self.config["extensions"] - }) - except: - if language: - ASCIIColors.error(f"nok : Personality not found @ {category}/{name}:{language}") - else: - ASCIIColors.error(f"nok : Personality not found @ {category}/{name}") - - ASCIIColors.yellow(f"Available personalities: {[p.name for p in self.mounted_personalities]}") - return jsonify({"status": False, "error":"Couldn't unmount personality"}) - - - def list_extensions_categories(self): - extensions_categories_dir = self.lollms_paths.extensions_zoo_path # replace with the actual path to the models folder - extensions_categories = [f.stem for f in extensions_categories_dir.iterdir() if f.is_dir() and not f.name.startswith(".")] - return jsonify(extensions_categories) - - - def set_active_binding_settings(self): - print("- Setting binding settings") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - - if self.binding is not None: - if hasattr(self.binding,"binding_config"): - for entry in data: - if entry["type"]=="list" and type(entry["value"])==str: - try: - v = json.loads(entry["value"]) - except: - v= "" - if type(v)==list: - entry["value"] = v - else: - entry["value"] = [entry["value"]] - self.binding.binding_config.update_template(data) - self.binding.binding_config.config.save_config() - self.binding.settings_updated() - if self.config.auto_save: - ASCIIColors.info("Saving configuration") - self.config.save_config() - return jsonify({'status':True}) - else: - return jsonify({'status':False}) - else: - return jsonify({'status':False}) - - - def get_personality_settings(self): - print("- Retreiving personality settings") - try: - data = request.get_json() - # Further processing of the data - except Exception as e: - print(f"Error occurred while parsing JSON: {e}") - return - category = data['category'] - name = data['folder'] - - if category.startswith("personal"): - personality_folder = self.lollms_paths.personal_personalities_path/f"{category}"/f"{name}" - else: - personality_folder = self.lollms_paths.personalities_zoo_path/f"{category}"/f"{name}" - - personality = AIPersonality(personality_folder, - self.lollms_paths, - self.config, - model=self.model, - app=self, - run_scripts=True) - if personality.processor is not None: - if hasattr(personality.processor,"personality_config"): - return jsonify(personality.processor.personality_config.config_template.template) - else: - return jsonify({}) - else: - return jsonify({}) - - - def p_select_personality(self): - ASCIIColors.info("Selecting personality") - data = request.get_json() - id = data['id'] - print(f"- Selecting active personality {id} ...",end="") - if id= {len(self.mounted_personalities)}") - return jsonify({"status": False, "error":"Invalid ID"}) - - - def upload_avatar(self): - file = request.files['avatar'] - file.save(self.lollms_paths.personal_user_infos_path/file.filename) - return jsonify({"status": True,"fileName":file.filename}) - - - - def rename_discussion(self): - data = request.get_json() - client_id = data["client_id"] - title = data["title"] - self.connections[client_id]["current_discussion"].rename(title) - return {"status":True} - - def edit_title(self): - data = request.get_json() - client_id = data["client_id"] - title = data["title"] - discussion_id = data["id"] - self.connections[client_id]["current_discussion"] = Discussion(discussion_id, self.db) - self.connections[client_id]["current_discussion"].rename(title) - return jsonify({'status':True}) - - def make_title(self): - ASCIIColors.info("Making title") - data = request.get_json() - discussion_id = data["id"] - discussion = Discussion(discussion_id, self.db) - title = self.make_discussion_title(discussion) - discussion.rename(title) - return jsonify({'status':True, 'title':title}) - - - def delete_discussion(self): - data = request.get_json() - client_id = data["client_id"] - discussion_id = data["id"] - self.connections[client_id]["current_discussion"] = Discussion(discussion_id, self.db) - self.connections[client_id]["current_discussion"].delete_discussion() - self.connections[client_id]["current_discussion"] = None - return jsonify({'status':True}) - - def edit_message(self): - client_id = request.args.get("client_id") - message_id = request.args.get("id") - new_message = request.args.get("message") - metadata = request.args.get("metadata",None) - try: - self.connections[client_id]["current_discussion"].edit_message(message_id, new_message,new_metadata=metadata) - return jsonify({"status": True}) - except Exception as ex: - trace_exception(ex) - return jsonify({"status": False, "error":str(ex)}) - - - def message_rank_up(self): - client_id = request.args.get("client_id") - discussion_id = request.args.get("id") - try: - new_rank = self.connections[client_id]["current_discussion"].message_rank_up(discussion_id) - return jsonify({"status": True, "new_rank": new_rank}) - except Exception as ex: - return jsonify({"status": False, "error":str(ex)}) - - def message_rank_down(self): - client_id = request.args.get("client_id") - discussion_id = request.args.get("id") - try: - new_rank = self.connections[client_id]["current_discussion"].message_rank_down(discussion_id) - return jsonify({"status": True, "new_rank": new_rank}) - except Exception as ex: - return jsonify({"status": False, "error":str(ex)}) - - def delete_message(self): - client_id = request.args.get("client_id") - discussion_id = request.args.get("id") - if self.connections[client_id]["current_discussion"] is None: - return jsonify({"status": False,"message":"No discussion is selected"}) - else: - new_rank = self.connections[client_id]["current_discussion"].delete_message(discussion_id) - ASCIIColors.yellow("Message deleted") - return jsonify({"status":True,"new_rank": new_rank}) - - - def get_available_models(self): - """Get the available models - - Returns: - _type_: _description_ - """ - if self.binding is None: - return jsonify([]) - try: - model_list = self.binding.get_available_models(self) - except Exception as ex: - self.error("Coudln't list models. Please reinstall the binding or notify ParisNeo on the discord server") - return jsonify([]) - - return jsonify(model_list) - - - def train(self): - form_data = request.form - - # Create and populate the config file - config = { - 'model_name': form_data['model_name'], - 'tokenizer_name': form_data['tokenizer_name'], - 'dataset_path': form_data['dataset_path'], - 'max_length': form_data['max_length'], - 'batch_size': form_data['batch_size'], - 'lr': form_data['lr'], - 'num_epochs': form_data['num_epochs'], - 'output_dir': form_data['output_dir'], - } - - with open('train/configs/train/local_cfg.yaml', 'w') as f: - yaml.dump(config, f) - - # Trigger the train.py script - # Place your code here to run the train.py script with the created config file - # accelerate launch --dynamo_backend=inductor --num_processes=8 --num_machines=1 --machine_rank=0 --deepspeed_multinode_launcher standard --mixed_precision=bf16 --use_deepspeed --deepspeed_config_file=configs/deepspeed/ds_config_gptj.json train.py --config configs/train/finetune_gptj.yaml - - subprocess.check_call(["accelerate","launch", "--dynamo_backend=inductor", "--num_processes=8", "--num_machines=1", "--machine_rank=0", "--deepspeed_multinode_launcher standard", "--mixed_precision=bf16", "--use_deepspeed", "--deepspeed_config_file=train/configs/deepspeed/ds_config_gptj.json", "train/train.py", "--config", "train/configs/train/local_cfg.yaml"]) - - return jsonify({'message': 'Training started'}) - - def get_config(self): - return jsonify(self.config.to_dict()) - - def get_current_personality_path_infos(self): - if self.personality is None: - return jsonify({ - "personality_category":"", - "personality_name":"" - }) - else: - return jsonify({ - "personality_category":self.personality_category, - "personality_name":self.personality_name - }) - - def main(self): - return render_template("main.html") - - def settings(self): - return render_template("settings.html") - - def help(self): - return render_template("help.html") - - def training(self): - return render_template("training.html") - - def extensions(self): - return render_template("extensions.html") - - def sync_cfg(default_config, config): - """Syncs a configuration with the default configuration - - Args: - default_config (_type_): _description_ - config (_type_): _description_ - - Returns: - _type_: _description_ - """ - added_entries = [] - removed_entries = [] - - # Ensure all fields from default_config exist in config - for key, value in default_config.items(): - if key not in config: - config[key] = value - added_entries.append(key) - - # Remove fields from config that don't exist in default_config - for key in list(config.config.keys()): - if key not in default_config: - del config.config[key] - removed_entries.append(key) - - config["version"]=default_config["version"] - - return config, added_entries, removed_entries - - if __name__ == "__main__": - db_folder = lollms_paths.personal_path/"databases" - db_folder.mkdir(parents=True, exist_ok=True) - - # Parsong parameters - parser = argparse.ArgumentParser(description="Start the chatbot Flask app.") - - parser.add_argument( - "-c", "--config", type=str, default="local_config", help="Sets the configuration file to be used." - ) - - parser.add_argument( - "-p", "--personality", type=str, default=None, help="Selects the personality to be using." - ) - - parser.add_argument( - "-s", "--seed", type=int, default=None, help="Force using a specific seed value." - ) - - parser.add_argument( - "-m", "--model", type=str, default=None, help="Force using a specific model." - ) - parser.add_argument( - "--temp", type=float, default=None, help="Temperature parameter for the model." - ) - parser.add_argument( - "--n_predict", - type=int, - default=None, - help="Number of tokens to predict at each step.", - ) - parser.add_argument( - "--n_threads", - type=int, - default=None, - help="Number of threads to use.", - ) - parser.add_argument( - "--top_k", type=int, default=None, help="Value for the top-k sampling." - ) - parser.add_argument( - "--top_p", type=float, default=None, help="Value for the top-p sampling." - ) - parser.add_argument( - "--repeat_penalty", type=float, default=None, help="Penalty for repeated tokens." - ) - parser.add_argument( - "--repeat_last_n", - type=int, - default=None, - help="Number of previous tokens to consider for the repeat penalty.", - ) - parser.add_argument( - "--ctx_size", - type=int, - default=None,#2048, - help="Size of the context window for the model.", - ) - parser.add_argument( - "--debug", - dest="debug", - action="store_true", - default=None, - help="launch Flask server in debug mode", - ) - parser.add_argument( - "--host", type=str, default=None, help="the hostname to listen on" - ) - parser.add_argument("--port", type=int, default=None, help="the port to listen on") - parser.add_argument( - "--db_path", type=str, default=None, help="Database path" - ) - args = parser.parse_args() - - # Configuration loading part - config = LOLLMSConfig.autoload(lollms_paths) - - # Override values in config with command-line arguments - for arg_name, arg_value in vars(args).items(): - if arg_value is not None: - config[arg_name] = arg_value - - # Copy user - # Assuming the current file's directory contains the 'assets' subfolder - current_file_dir = Path(__file__).parent - assets_dir = current_file_dir / "assets" - default_user_avatar = assets_dir / "default_user.svg" - user_avatar_path = lollms_paths.personal_user_infos_path / "default_user.svg" - if not user_avatar_path.exists(): - # If the user avatar doesn't exist, copy the default avatar from the assets folder - shutil.copy(default_user_avatar, user_avatar_path) - - bot = LoLLMsWebUI(args, app, socketio, config, config.file_path, lollms_paths) - - # chong Define custom WebSocketHandler with error handling - class CustomWebSocketHandler(WebSocketHandler): - def handle_error(self, environ, start_response, e): - # Handle the error here - print("WebSocket error:", e) - super().handle_error(environ, start_response, e) - - - - # chong -add socket server - app.config['debug'] = config["debug"] - - if config["debug"]: - ASCIIColors.info("debug mode:true") - else: - ASCIIColors.info("debug mode:false") - - - url = f'http://{config["host"]}:{config["port"]}' - if config["host"]!="localhost": - print(f'Please open your browser and go to http://localhost:{config["port"]} to view the ui') - ASCIIColors.success(f'This server is visible from a remote PC. use this address http://{get_ip_address()}:{config["port"]}') - else: - print(f"Please open your browser and go to {url} to view the ui") - - # if autoshow - if config.auto_show_browser: - if config['host']=="0.0.0.0": - webbrowser.open(f"http://localhost:{config['port']}") - else: - webbrowser.open(f"http://{config['host']}:{config['port']}") - - - try: - socketio.reboot = False - socketio.run(app, host=config["host"], port=config["port"], - # prevent error: The Werkzeug web server is not designed to run in production - allow_unsafe_werkzeug=True) - if socketio.reboot: - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info(" ╔══════════════════════════════════════════════════╗") - ASCIIColors.info(" ║ Restarting backend ║") - ASCIIColors.info(" ╚══════════════════════════════════════════════════╝") - ASCIIColors.info("") - ASCIIColors.info("") - ASCIIColors.info("") - run_restart_script(args) - - except Exception as ex: - trace_exception(ex) - # http_server = WSGIServer((config["host"], config["port"]), app, handler_class=WebSocketHandler) - # http_server.serve_forever() -except Exception as ex: - trace_exception(ex) - run_update_script() diff --git a/lollms_core b/lollms_core index feeae244..b5de353d 160000 --- a/lollms_core +++ b/lollms_core @@ -1 +1 @@ -Subproject commit feeae2441113aa7f88d3f3e305ff7692acdeabb1 +Subproject commit b5de353df365b18250518bc486cc80eb2aefe82c diff --git a/lollms_webui.py b/lollms_webui.py index 98f27105..706e6a25 100644 --- a/lollms_webui.py +++ b/lollms_webui.py @@ -7,7 +7,6 @@ This class provides a singleton instance of the LoLLMS web UI, allowing access t """ from lollms.server.elf_server import LOLLMSElfServer -from flask import request from datetime import datetime from api.db import DiscussionsDB, Discussion from pathlib import Path diff --git a/requirements.txt b/requirements.txt index b8e9f5f6..299e5de0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,6 @@ setuptools pyyaml numpy -flask -flask_socketio -flask_compress gevent-websocket websocket-client eventlet diff --git a/requirements_dev.txt b/requirements_dev.txt index 50c12a9a..d88309fe 100644 --- a/requirements_dev.txt +++ b/requirements_dev.txt @@ -1,7 +1,5 @@ tqdm psutil -flask -flask_socketio pytest pyyaml markdown diff --git a/web/vite.config.mjs b/web/vite.config.mjs index 5e8df82b..166cd21f 100644 --- a/web/vite.config.mjs +++ b/web/vite.config.mjs @@ -6,34 +6,6 @@ import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default async ({ mode }) => { - /* - async function getFlaskServerURL() { - try { - console.log("Loading") - const response = await fetch('/get_server_address'); // Replace with the actual endpoint on your Flask server - const serverAddress = await response.text(); - if(serverAddress.includes('<') || !serverAddress.startsWith("http")){ - console.log(`Server address not found`) - return process.env.VITE_LOLLMS_API - - } - console.log(`Server address: ${serverAddress}`) - return `${serverAddress}`; // Construct the full server address dynamically - } catch (error) { - // console.error('Error fetching server address:', error); - // Handle error if necessary - return process.env.VITE_LOLLMS_API - } - } - let serverURL = undefined; - try{ - serverURL = await getFlaskServerURL() - console.log(serverURL) - }catch{ - serverURL = process.env.VITE_LOLLMS_API - console.log(`Server address: ${serverAddress}`) - } - */ // Load app-level env vars to node-level env vars. process.env = {...process.env, ...loadEnv(mode, process.cwd())}; diff --git a/zoos/personalities_zoo b/zoos/personalities_zoo index c1702841..39159519 160000 --- a/zoos/personalities_zoo +++ b/zoos/personalities_zoo @@ -1 +1 @@ -Subproject commit c1702841b3f72f367ead691b67f02fc06cf2d7a6 +Subproject commit 3915951920cf483388360e0b890019e938ec516b