forked from ParisNeo/lollms-webui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
2417 lines (2010 loc) · 105 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######
# Project : lollms-webui
# Author : ParisNeo with the help of the community
# 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
######
__author__ = "parisneo"
__github__ = "https://github.com/ParisNeo/lollms-webui"
__copyright__ = "Copyright 2023, "
__license__ = "Apache 2.0"
__version__ ="6.7"
main_repo = "https://github.com/ParisNeo/lollms-webui.git"
import os
import sys
from flask import request, jsonify
import io
import sys
import time
import traceback
import webbrowser
from pathlib import Path
import os
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.config import InstallOption
from lollms.binding import LOLLMSConfig, BindingBuilder
from lollms.personality import AIPersonality
from lollms.config import BaseConfig
from lollms.paths import LollmsPaths, gptqlora_repo
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 LoLLMsAPPI
import shutil
import socket
from api.db import DiscussionsDB, Discussion
from safe_store import TextVectorizer, VectorizationMethod, VisualizationMethod
except Exception as ex:
trace_exception(ex)
run_update_script()
try:
import mimetypes
mimetypes.add_type('application/javascript', '.js')
mimetypes.add_type('text/css', '.css')
except:
ASCIIColors.yellow("Couldn't set mimetype")
def check_update_(branch_name="main"):
try:
# Open the repository
repo_path = str(Path(__file__).parent)
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: {not 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
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = Flask("Lollms-WebUI", static_url_path="/static", static_folder="static")
# async_mode='gevent', ping_timeout=1200, ping_interval=120,
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading',engineio_options={'websocket_compression': False, 'websocket_ping_interval': 20, 'websocket_ping_timeout': 120, 'websocket_max_queue': 100})
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(LoLLMsAPPI):
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!")
self.update_software()
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("/update_software", "update_software", self.update_software, methods=["GET"])
self.add_endpoint("/clear_uploads", "clear_uploads", self.clear_uploads, methods=["GET"])
self.add_endpoint("/selectdb", "selectdb", self.selectdb, methods=["GET"])
self.add_endpoint("/restart_program", "restart_program", self.restart_program, methods=["GET"])
self.add_endpoint("/check_update", "check_update", self.check_update, methods=["GET"])
self.add_endpoint("/post_to_personality", "post_to_personality", self.post_to_personality, methods=["POST"])
self.add_endpoint("/install_model_from_path", "install_model_from_path", self.install_model_from_path, methods=["GET"])
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("/reinstall_personality", "reinstall_personality", self.reinstall_personality, methods=["POST"])
self.add_endpoint("/switch_personal_path", "switch_personal_path", self.switch_personal_path, methods=["POST"])
self.add_endpoint("/add_reference_to_local_model", "add_reference_to_local_model", self.add_reference_to_local_model, methods=["POST"])
self.add_endpoint("/add_model_reference", "add_model_reference", self.add_model_reference, methods=["POST"])
self.add_endpoint("/upload_model", "upload_model", self.upload_model, methods=["POST"])
self.add_endpoint("/upload_avatar", "upload_avatar", self.upload_avatar, methods=["POST"])
self.add_endpoint("/list_mounted_personalities", "list_mounted_personalities", self.list_mounted_personalities, methods=["POST"])
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("/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_personality", "unmount_personality", self.p_unmount_personality, methods=["POST"])
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("/get_active_binding_settings", "get_active_binding_settings", self.get_active_binding_settings, methods=["GET"])
self.add_endpoint("/set_active_personality_settings", "set_active_personality_settings", self.set_active_personality_settings, methods=["POST"])
self.add_endpoint("/set_active_binding_settings", "set_active_binding_settings", self.set_active_binding_settings, methods=["POST"])
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(
"/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(
"/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(
"/list_databases", "list_databases", self.list_databases, methods=["GET"]
)
self.add_endpoint("/select_database", "select_database", self.select_database, 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(
"/list_discussions", "list_discussions", self.list_discussions, methods=["GET"]
)
self.add_endpoint("/delete_personality", "delete_personality", self.delete_personality, 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("/<path:filename>", "serve_static", self.serve_static, methods=["GET"])
self.add_endpoint("/user_infos/<path:filename>", "serve_user_infos", self.serve_user_infos, methods=["GET"])
self.add_endpoint("/images/<path:filename>", "serve_images", self.serve_images, methods=["GET"])
self.add_endpoint("/extensions/<path:filename>", "serve_extensions", self.serve_extensions, methods=["GET"])
self.add_endpoint("/bindings/<path:filename>", "serve_bindings", self.serve_bindings, methods=["GET"])
self.add_endpoint("/personalities/<path:filename>", "serve_personalities", self.serve_personalities, methods=["GET"])
self.add_endpoint("/outputs/<path:filename>", "serve_outputs", self.serve_outputs, methods=["GET"])
self.add_endpoint("/data/<path:filename>", "serve_data", self.serve_data, methods=["GET"])
self.add_endpoint("/help/<path:filename>", "serve_help", self.serve_help, methods=["GET"])
self.add_endpoint("/uploads/<path:filename>", "serve_uploads", self.serve_uploads, methods=["GET"])
self.add_endpoint("/export_discussion", "export_discussion", self.export_discussion, methods=["GET"])
self.add_endpoint("/export", "export", self.export, methods=["GET"])
self.add_endpoint("/stop_gen", "stop_gen", self.stop_gen, methods=["GET"])
self.add_endpoint("/rename", "rename", self.rename, methods=["POST"])
self.add_endpoint("/edit_title", "edit_title", self.edit_title, methods=["POST"])
self.add_endpoint(
"/delete_discussion",
"delete_discussion",
self.delete_discussion,
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(
"/get_current_personality_path_infos", "get_current_personality_path_infos", self.get_current_personality_path_infos, methods=["GET"]
)
self.add_endpoint(
"/get_available_models", "get_available_models", self.get_available_models, methods=["GET"]
)
self.add_endpoint(
"/extensions", "extensions", self.extensions, methods=["GET"]
)
self.add_endpoint(
"/upgrade_to_gpu", "upgrade_to_gpu", self.upgrade_to_gpu, 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(
"/get_generation_status", "get_generation_status", self.get_generation_status, 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(
"/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(
"/get_personality", "get_personality", self.get_personality, methods=["GET"]
)
self.add_endpoint(
"/reset", "reset", self.reset, 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_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_python_code", "execute_python_code", self.execute_python_code, methods=["POST"]
)
def execute_python_code(self):
"""Executes Python code and returns the output."""
data = request.get_json()
code = data["code"]
ASCIIColors.info("Executing python code:")
ASCIIColors.yellow(code)
def spawn_process(code):
"""Executes Python code and returns the output as JSON."""
# Start the timer.
start_time = time.time()
# Create a temporary file.
tmp_file = self.lollms_paths.personal_data_path/"ai_code.py"
with open(tmp_file,"w") 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,
)
# 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": "<div class='text-red-500'>"+ex+"\n"+get_trace_exception(ex)+"</div>", "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": "<div class='text-red-500'>"+error_message+"</div>", "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 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 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"]
discussions = self.db.export_discussions_to_json(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.socketio.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 personalities_folder.iterdir():
cat = category_folder.stem
if category_folder.is_dir() and not category_folder.stem.startswith('.'):
personalities[category_folder.name] = []
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['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[category_folder.name].append(personality_info)
except Exception as ex:
ASCIIColors.warning(f"Couldn't load personality from {personality_folder} [{ex}]")
trace_exception(ex)
return json.dumps(personalities)
def get_personality(self):
category = request.args.get('category')
name = request.args.get('name')
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":<the setting name>,"setting_value":<the 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"]<len(self.config["personalities"]):
self.config["personalities"][self.config["active_personality_id"]] = f"{self.personality_category}/{self.personality_name}"
else:
self.config["active_personality_id"] = 0
self.config["personalities"][self.config["active_personality_id"]] = f"{self.personality_category}/{self.personality_name}"
if self.personality_category!="Custom":
personality_fn = self.lollms_paths.personalities_zoo_path/self.config["personalities"][self.config["active_personality_id"]]
else:
personality_fn = self.lollms_paths.personal_personalities_path/self.config["personalities"][self.config["active_personality_id"]].split("/")[-1]
self.personality.load_personality(personality_fn)
else:
self.config["personalities"].append(f"{self.personality_category}/{self.personality_name}")
elif setting_name== "override_personality_model_parameters":
self.config["override_personality_model_parameters"]=bool(data['setting_value'])
elif setting_name == "model_name":
self.config["model_name"]=data['setting_value']
if self.config["model_name"] is not None:
try:
self.model = None
if self.binding:
del self.binding
self.binding = None
for per in self.mounted_personalities:
per.model = None
gc.collect()
self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths)
self.model = self.binding.build_model()
for per in self.mounted_personalities:
if per is not None:
per.model = self.model
except Exception as 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"Couldn't load model: [{ex}]")
ASCIIColors.error(traceback_text)
return jsonify({ "status":False, 'error':str(ex)})
else:
ASCIIColors.warning("Trying to set a None model. Please select a model for the binding")
print("update_settings : New model selected")
elif setting_name== "binding_name":
if self.config['binding_name']!= data['setting_value']:
print(f"New binding selected : {data['setting_value']}")
self.config["binding_name"]=data['setting_value']
try:
if self.binding:
self.binding.destroy_model()
self.binding = None
self.model = None
for per in self.mounted_personalities:
per.model = None
gc.collect()
self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths)
self.model = None
self.config.save_config()
ASCIIColors.green("Model loaded successfully")
except Exception as ex:
ASCIIColors.error(f"Couldn't build binding: [{ex}]")
trace_exception(ex)
return jsonify({"status":False, 'error':str(ex)})
else:
if self.config["debug"]:
print(f"Configuration {data['setting_name']} set to {data['setting_value']}")
return jsonify({'setting_name': data['setting_name'], "status":True})
else:
if data['setting_name'] in self.config.config.keys():
self.config[data['setting_name']] = data['setting_value']
else:
if self.config["debug"]:
print(f"Configuration {data['setting_name']} couldn't be set to {data['setting_value']}")
return jsonify({'setting_name': data['setting_name'], "status":False})
if self.config["debug"]:
print(f"Configuration {data['setting_name']} set to {data['setting_value']}")
ASCIIColors.success(f"Configuration {data['setting_name']} updated")
if self.config.auto_save:
self.config.save_config()
# Tell that the setting was changed
return jsonify({'setting_name': data['setting_name'], "status":True})
def apply_settings(self):
data = request.get_json()
try:
for key in self.config.config.keys():
self.config.config[key] = data["config"].get(key, self.config.config[key])
ASCIIColors.success("OK")
self.rebuild_personalities()
if self.config.auto_save:
self.config.save_config()
if self.config.data_vectorization_activate and self.config.use_discussions_history:
ASCIIColors.yellow("0- Detected discussion vectorization request")
folder = self.lollms_paths.personal_databases_path/"vectorized_dbs"
folder.mkdir(parents=True, exist_ok=True)
self.discussions_store = 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")
discussions = self.db.export_all_as_markdown_list_for_vectorization()
ASCIIColors.yellow("2- Adding discussions to vectorizer")
for (title,discussion) in discussions:
if discussion!='':
self.discussions_store.add_document(title, discussion, 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.discussions_store.index()
ASCIIColors.yellow("3- Saving database")
self.discussions_store.save_to_json()
ASCIIColors.yellow("Ready")
return jsonify({"status":True})
except Exception as ex:
trace_exception(ex)
return jsonify({"status":False,"error":str(ex)})
def upgrade_to_gpu(self):
ASCIIColors.yellow("Received command to upgrade to GPU")
ASCIIColors.info("Installing cuda toolkit")
res = subprocess.check_call(["conda", "install", "-c", "nvidia/label/cuda-11.7.0", "-c", "nvidia", "-c", "conda-forge", "cuda-toolkit", "ninja", "git", "--force-reinstall", "-y"])
if res!=0:
ASCIIColors.red("Couldn't install cuda toolkit")
return jsonify({'status':False, "error": "Couldn't install cuda toolkit. Make sure you are running from conda environment"})
ASCIIColors.green("Cuda toolkit installed successfully")
ASCIIColors.yellow("Removing pytorch")
try:
res = subprocess.check_call(["pip","uninstall","torch", "torchvision", "torchaudio", "-y"])
except :
pass
ASCIIColors.green("PyTorch unstalled successfully")
ASCIIColors.yellow("Installing pytorch with cuda support")
res = subprocess.check_call(["pip","install","--upgrade","torch==2.0.1+cu117", "torchvision", "torchaudio", "--index-url", "https://download.pytorch.org/whl/cu117","--no-cache"])
if res==0:
ASCIIColors.green("PyTorch installed successfully")
import torch
if torch.cuda.is_available():
ASCIIColors.success("CUDA is supported.")
else:
ASCIIColors.warning("CUDA is not supported. This may mean that the upgrade didn't succeed. Try rebooting the application")
else:
ASCIIColors.green("An error hapened")
self.config.enable_gpu=True
return jsonify({'status':res==0})
def ram_usage(self):
"""
Returns the RAM usage in bytes.
"""
ram = psutil.virtual_memory()
return jsonify({
"total_space":ram.total,
"available_space":ram.free,
"percent_usage":ram.percent,
"ram_usage": ram.used
})
def vram_usage(self) -> 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,