-
Notifications
You must be signed in to change notification settings - Fork 31
/
__webgui_server__.py
1767 lines (1641 loc) · 74.7 KB
/
__webgui_server__.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
import os
import sys
import time
import json
import signal
import argparse
import asyncio
import platform
import langchain
import threading
import multiprocessing as mp
from datetime import datetime
from multiprocessing import Process
from WebUI.Server.llm_api_stale import (LOG_PATH)
from WebUI.Server.utils import (set_httpx_config, get_model_worker_config, get_httpx_client,
FastAPI, MakeFastAPIOffline, fschat_controller_address,
fschat_model_worker_address, get_vtot_worker_config, get_speech_worker_config,
get_image_recognition_worker_config, get_image_generation_worker_config,
get_music_generation_worker_config)
from __about__ import __title__, __summary__, __version__, __author__, __email__, __license__, __copyright__
from webuisrv import InnerLlmAIRobotWebUIServer
from WebUI.Server.knowledge_base.utils import SCORE_THRESHOLD
from WebUI.configs.serverconfig import (FSCHAT_MODEL_WORKERS, FSCHAT_CONTROLLER, HTTPX_LOAD_TIMEOUT, HTTPX_RELEASE_TIMEOUT,
HTTPX_LOAD_VOICE_TIMEOUT, HTTPX_RELEASE_VOICE_TIMEOUT, FSCHAT_OPENAI_API, API_SERVER)
from fastchat.protocol.openai_api_protocol import ChatCompletionRequest
from WebUI.configs.voicemodels import (init_voice_models, translate_voice_data, cloud_voice_data, init_speech_models, translate_speech_data)
from WebUI.configs.imagemodels import (init_image_recognition_models, translate_image_recognition_data, init_image_generation_models, translate_image_generation_data)
from WebUI.configs.musicmodels import (init_music_generation_models, translate_music_generation_data)
from WebUI.configs.webuiconfig import InnerJsonConfigWebUIParse
from WebUI.configs.basicconfig import (ModelType, ModelSize, ModelSubType, GetModelInfoByName, SaveCurrentRunningCfg, load_env)
from WebUI.configs.specialmodels import (init_cloud_models, init_multimodal_models, init_special_models, model_chat, model_search_engine_chat, model_knowledge_base_chat)
from WebUI.configs.codemodels import init_code_models
from typing import (Union, Optional, AsyncIterable, List, Dict)
from fastapi.responses import StreamingResponse
def parse_args() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument(
"-a",
"--webui",
action="store_true",
help="run webui servers.",
dest="webui",
)
parser.add_argument(
"-c",
"--controller",
type=str,
help="specify controller address the worker is registered to. default is FSCHAT_CONTROLLER",
dest="controller_address",
)
parser.add_argument(
"-n",
"--model-name",
type=str,
nargs="+",
default=[""],
help="specify model name for model worker. "
"add addition names with space seperated to start multiple model workers.",
dest="model_name",
)
args = parser.parse_args()
return args, parser
def dump_server_info(after_start=False, args=None):
print("\n")
print("=" * 30 + f"{__title__} Configuration" + "=" * 30)
print(f"OS: {platform.platform()}.")
print(f"python: {sys.version}")
print(f"langchain: {langchain.__version__}.")
print(f"Version: {__version__}")
print(f"Summary: {__summary__}")
print(f"Author: {__author__}")
print(f"Email: {__email__}")
print(f"License: {__license__}")
print(f"Copyright: {__copyright__}")
def handler(signalname):
def f(signal_received, frame):
raise KeyboardInterrupt(f"{signalname} received")
return f
def create_controller_app(
dispatch_method: str,
) -> FastAPI:
import fastchat.constants
fastchat.constants.LOGDIR = LOG_PATH
from fastchat.serve.controller import app, Controller
controller = Controller(dispatch_method)
sys.modules["fastchat.serve.controller"].controller = controller
MakeFastAPIOffline(app)
app.title = "FastChat Controller"
app._controller = controller
return app
def run_webui(started_event: mp.Event = None, run_mode: str = None):
set_httpx_config()
webui = InnerLlmAIRobotWebUIServer()
webui.launch(started_event, run_mode)
def _set_app_event(app: FastAPI, started_event: mp.Event = None):
@app.on_event("startup")
async def on_startup():
if started_event is not None:
started_event.set()
def run_controller(started_event: mp.Event = None, q: mp.Queue = None):
import uvicorn
from fastapi import Body
import time
set_httpx_config()
glob_minor_models = {
"voicemodel": {
"model_name": ""
},
"speechmodel": {
"model_name": "",
"speaker": ""
},
"imagerecognition": {
"model_name": ""
},
"imagegeneration": {
"model_name": ""
},
"musicgeneration": {
"model_name": ""
}
}
app = create_controller_app(
dispatch_method=FSCHAT_CONTROLLER.get("dispatch_method"),
)
_set_app_event(app, started_event)
# add interface to release and load model worker
@app.post("/release_worker")
def release_worker(
model_name: str = Body(..., description="Unload the model", samples=["chatglm-6b"]),
# worker_address: str = Body(None, description="Unload the model address", samples=[FSCHAT_CONTROLLER_address()]),
new_model_name: str = Body(None, description="New model"),
keep_origin: bool = Body(False, description="Second model")
) -> Dict:
configinst = InnerJsonConfigWebUIParse()
webui_config = configinst.dump()
modelinfo : Dict[str, any] = {"mtype": ModelType.Unknown, "msize": ModelSize.Unknown, "msubtype": ModelSubType.Unknown, "mname": str, "config": dict}
modelinfo["mtype"], modelinfo["msize"], modelinfo["msubtype"] = GetModelInfoByName(webui_config, new_model_name)
available_models = []
if modelinfo["mtype"] == ModelType.Local:
available_models = app._controller.list_models()
if new_model_name in available_models:
msg = f"The model {new_model_name} has been loaded."
print(msg)
return {"code": 500, "msg": msg}
if new_model_name:
print(f"Change model: from {model_name} to {new_model_name}")
else:
print(f"Stoping model: {model_name}")
if model_name != "":
worker_address = app._controller.get_worker_address(model_name)
if not worker_address:
workerconfig = get_model_worker_config(model_name)
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
else:
workerconfig = get_model_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
r = client.post(worker_address + "/release",
json={"new_model_name": new_model_name, "keep_origin": keep_origin})
if r.status_code != 200:
msg = f"failed to release model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
if new_model_name:
timer = HTTPX_LOAD_TIMEOUT # wait for new model_worker register
while timer > 0:
if modelinfo["mtype"] == ModelType.Local:
models = app._controller.list_models()
if new_model_name in models:
break
else:
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_name",
json={})
name = r.json().get("name", "")
if new_model_name == name:
break
except Exception:
pass
time.sleep(1)
timer -= 1
app._controller.refresh_all_workers()
if timer > 0:
msg = f"success change model from {model_name} to {new_model_name}"
print(msg)
return {"code": 200, "msg": msg}
msg = f"failed change model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
else:
timer = HTTPX_RELEASE_TIMEOUT # wait for release model
modelinfo["mtype"], modelinfo["msize"], modelinfo["msubtype"] = GetModelInfoByName(webui_config, model_name)
while timer > 0:
if modelinfo["mtype"] == ModelType.Local:
models = app._controller.list_models()
if model_name not in models:
break
elif modelinfo["mtype"] == ModelType.Special or modelinfo["mtype"] == ModelType.Code or modelinfo["mtype"] == ModelType.Online:
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_name",
json={})
name = r.json().get("name", "")
if model_name != name:
break
except Exception:
break
elif modelinfo["mtype"] == ModelType.Multimodal:
break
time.sleep(1)
timer -= 1
app._controller.refresh_all_workers()
if timer > 0:
msg = f"success to release model: {model_name}"
print(msg)
return {"code": 200, "msg": msg}
msg = f"failed to release model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
@app.post("/text_chat")
def text_chat(
query: str = Body(..., description="User input: ", examples=["chat"]),
imagesdata: List[str] = Body([], description="image data", examples=["image"]),
audiosdata: List[str] = Body([], description="audio data", examples=["audio"]),
videosdata: List[str] = Body([], description="video data", examples=["video"]),
imagesprompt: List[str] = Body([], description="prompt data", examples=["prompt"]),
history: List[dict] = Body([],
description="History chat",
examples=[[
{"role": "user", "content": "Who are you?"},
{"role": "assistant", "content": "I am AI."}]]
),
stream: bool = Body(False, description="stream output"),
model_name: str = Body("", description="model name"),
speechmodel: dict = Body({}, description="speech model"),
temperature: float = Body(0.7, description="LLM Temperature", ge=0.0, le=1.0),
max_tokens: Optional[int] = Body(None, description="max tokens."),
prompt_name: str = Body("default", description=""),
):
workerconfig = get_model_worker_config(model_name)
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
async def fake_json_streamer() -> AsyncIterable[str]:
with get_httpx_client() as client:
response = client.stream("POST",
url=worker_address + "/text_chat",
json={
"query": query,
"imagesdata": imagesdata,
"audiosdata": audiosdata,
"videosdata": videosdata,
"imagesprompt": imagesprompt,
"history": history,
"stream": stream,
"speechmodel": speechmodel,
"temperature": temperature,
"max_tokens": max_tokens,
"prompt_name": prompt_name,
},
)
with response as r:
for chunk in r.iter_text(None):
if not chunk:
continue
yield chunk
await asyncio.sleep(0.1)
return StreamingResponse(fake_json_streamer(), media_type="text/event-stream")
@app.post("/knowledge_base_chat")
def knowledge_base_chat(
query: str = Body(..., description="User input: ", examples=["chat"]),
knowledge_base_name: str = Body(..., description="knowledge base name"),
top_k: int = Body(3, description="matching vector count"),
score_threshold: float = Body(
SCORE_THRESHOLD,
description="Knowledge base matching relevance threshold, with a range between 0 and 1. A smaller SCORE indicates higher relevance, and setting it to 1 is equivalent to no filtering. It is recommended to set it around 0.5"),
history: List[dict] = Body([],
description="History chat",
examples=[[
{"role": "user", "content": "Who are you?"},
{"role": "assistant", "content": "I am AI."}]]
),
stream: bool = Body(False, description="stream output"),
model_name: str = Body("", description="model name"),
imagesdata: List[str] = Body([], description="image data", examples=["image"]),
speechmodel: dict = Body({}, description="speech model"),
temperature: float = Body(0.7, description="LLM Temperature", ge=0.0, le=1.0),
max_tokens: Optional[int] = Body(None, description="max tokens."),
prompt_name: str = Body("default", description=""),
):
workerconfig = get_model_worker_config(model_name)
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
async def fake_json_streamer() -> AsyncIterable[str]:
with get_httpx_client() as client:
response = client.stream("POST",
url=worker_address + "/knowledge_base_chat",
json={
"query": query,
"knowledge_base_name": knowledge_base_name,
"top_k": top_k,
"score_threshold": score_threshold,
"history": history,
"stream": stream,
"imagesdata": imagesdata,
"speechmodel": speechmodel,
"temperature": temperature,
"max_tokens": max_tokens,
"prompt_name": prompt_name,
},
)
with response as r:
for chunk in r.iter_text(None):
if not chunk:
continue
yield chunk
await asyncio.sleep(0.1)
return StreamingResponse(fake_json_streamer(), media_type="text/event-stream")
@app.post("/llm_search_engine_chat")
def llm_search_engine_chat(
query: str = Body(..., description="User input: ", examples=["chat"]),
search_engine_name: str = Body(..., description="Search engine name"),
history: List[dict] = Body([],
description="History chat",
examples=[[
{"role": "user", "content": "Who are you?"},
{"role": "assistant", "content": "I am AI."}]]
),
stream: bool = Body(False, description="stream output"),
model_name: str = Body("", description="model name"),
temperature: float = Body(0.7, description="LLM Temperature", ge=0.0, le=1.0),
max_tokens: Optional[int] = Body(None, description="max tokens."),
prompt_name: str = Body("default", description=""),
):
workerconfig = get_model_worker_config(model_name)
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
async def fake_json_streamer() -> AsyncIterable[str]:
with get_httpx_client() as client:
response = client.stream("POST",
url=worker_address + "/llm_search_engine_chat",
json={
"query": query,
"search_engine_name": search_engine_name,
"history": history,
"stream": stream,
"temperature": temperature,
"max_tokens": max_tokens,
"prompt_name": prompt_name,
},
)
with response as r:
for chunk in r.iter_text(None):
if not chunk:
continue
yield chunk
await asyncio.sleep(0.1)
return StreamingResponse(fake_json_streamer(), media_type="text/event-stream")
@app.post("/get_vtot_model")
def get_vtot_model(
) -> Dict:
model_name = glob_minor_models["voicemodel"]["model_name"]
return {"code": 200, "model": model_name}
@app.post("/release_vtot_model")
def release_vtot_model(
model_name: str = Body(..., description="Unload the model", samples=""),
new_model_name: str = Body(None, description="New model"),
) -> Dict:
if new_model_name:
print(f"Change voice model: from {model_name} to {new_model_name}")
else:
print(f"Stoping voice model: {model_name}")
workerconfig = get_vtot_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
if model_name:
q.put([model_name, "stop_vtot_model", None])
timer = HTTPX_RELEASE_VOICE_TIMEOUT # wait for release model
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
except Exception:
break
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed to stop voice model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["voicemodel"]["model_name"] = ""
if new_model_name:
q.put([model_name, "start_vtot_model", new_model_name])
timer = HTTPX_LOAD_VOICE_TIMEOUT # wait for new vtot_worker register
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
break
except Exception:
pass
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed change voice model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["voicemodel"]["model_name"] = new_model_name
msg = f"success change voice model from {model_name} to {new_model_name}"
return {"code": 200, "msg": msg}
else:
msg = f"success stop voice model {model_name}"
return {"code": 200, "msg": msg}
@app.post("/get_vtot_data")
def get_vtot_data(
voice_data: str = Body(..., description="voice data", samples=""),
voice_type: str = Body(None, description="voice type"),
) -> Dict:
if len(voice_data) == 0:
msg = "failed translate voice to text, because voice data is incorrect."
return {"code": 500, "msg": msg}
workerconfig = get_vtot_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_vtot_data",
json={"voice_data": voice_data, "voice_type": voice_type},
)
data = r.json()["text"]
return {"code": 200, "text": data}
except Exception:
return {"code": 500, "text": ""}
@app.post("/get_speech_model")
def get_speech_model(
) -> Dict:
model_name = glob_minor_models["speechmodel"]["model_name"]
speaker = glob_minor_models["speechmodel"]["speaker"]
return {"code": 200, "model": model_name, "speaker": speaker}
@app.post("/release_speech_model")
def release_speech_model(
model_name: str = Body(..., description="Unload the model", samples=""),
new_model_name: str = Body(None, description="New model"),
speaker: str = Body(None, description="Speaker"),
) -> Dict:
if new_model_name:
print(f"Change speech model: from {model_name} to {new_model_name}, speaker({speaker})")
else:
print(f"Stoping speech model: {model_name}")
workerconfig = get_speech_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
if model_name:
q.put([model_name, "stop_speech_model", None])
timer = HTTPX_RELEASE_VOICE_TIMEOUT # wait for release model
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
except Exception:
break
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed to stop speech model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["speechmodel"]["model_name"] = ""
glob_minor_models["speechmodel"]["speaker"] = ""
if new_model_name:
q.put([speaker, "start_speech_model", new_model_name])
timer = HTTPX_LOAD_VOICE_TIMEOUT # wait for new vtot_worker register
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
break
except Exception:
pass
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed change speech model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["speechmodel"]["model_name"] = new_model_name
glob_minor_models["speechmodel"]["speaker"] = speaker
msg = f"success change speech model from {model_name} to {new_model_name}"
return {"code": 200, "msg": msg}
else:
msg = f"success stop speech model {model_name}"
return {"code": 200, "msg": msg}
@app.post("/get_speech_data")
def get_speech_data(
text_data: str = Body(..., description="speech data", samples=""),
speech_type: str = Body(None, description="speech type"),
) -> Dict:
if len(text_data) == 0:
msg = "failed translate text to speech."
return {"code": 500, "msg": msg}
workerconfig = get_speech_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_speech_data",
json={"text_data": text_data, "speech_type": speech_type},
)
return r.json()
except Exception:
return {"code": 500, "channels": 0, "sample_width": 0, "frame_rate": 0, "speech_data": ""}
@app.post("/get_image_recognition_model")
def get_image_recognition_model(
) -> Dict:
model_name = glob_minor_models["imagerecognition"]["model_name"]
return {"code": 200, "model": model_name}
@app.post("/release_image_recognition_model")
def release_image_recognition_model(
model_name: str = Body(..., description="Unload the model", samples=""),
new_model_name: str = Body(None, description="New model"),
) -> Dict:
if new_model_name:
print(f"Change image recognition model: from {model_name} to {new_model_name})")
else:
print(f"Stoping image recognition model: {model_name}")
workerconfig = get_image_recognition_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
if model_name:
q.put([model_name, "stop_image_recognition_model", None])
timer = HTTPX_RELEASE_VOICE_TIMEOUT # wait for release model
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
except Exception:
break
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed to stop image recognition model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["imagerecognition"]["model_name"] = ""
if new_model_name:
q.put([model_name, "start_image_recognition_model", new_model_name])
timer = HTTPX_LOAD_VOICE_TIMEOUT # wait for new vtot_worker register
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
break
except Exception:
pass
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed change image recognition model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["imagerecognition"]["model_name"] = new_model_name
msg = f"success change image recognition model from {model_name} to {new_model_name}"
return {"code": 200, "msg": msg}
else:
msg = f"success stop image recognition model {model_name}"
return {"code": 200, "msg": msg}
@app.post("/get_image_recognition_data")
def get_image_recognition_data(
imagedata: str = Body(..., description="image recognition data"),
imagetype: str = Body(None, description="type"),
) -> Dict:
if len(imagedata) == 0:
msg = "failed translate image to text."
return {"code": 500, "msg": msg}
workerconfig = get_image_recognition_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_image_recognition_data",
json={"imagedata": imagedata, "imagetype": imagetype},
)
return r.json()
except Exception:
return {"code": 500, "text": ""}
@app.post("/get_image_generation_model")
def get_image_generation_model(
) -> Dict:
model_name = glob_minor_models["imagegeneration"]["model_name"]
return {"code": 200, "model": model_name}
@app.post("/release_image_generation_model")
def release_image_generation_model(
model_name: str = Body(..., description="Unload the model", samples=""),
new_model_name: str = Body(None, description="New model"),
) -> Dict:
if new_model_name:
print(f"Change image generation model: from {model_name} to {new_model_name})")
else:
print(f"Stoping image generation model: {model_name}")
workerconfig = get_image_generation_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
if model_name:
q.put([model_name, "stop_image_generation_model", None])
timer = HTTPX_RELEASE_VOICE_TIMEOUT # wait for release model
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
except Exception:
break
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed to stop image generation model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["imagegeneration"]["model_name"] = ""
if new_model_name:
q.put([model_name, "start_image_generation_model", new_model_name])
timer = HTTPX_LOAD_VOICE_TIMEOUT # wait for new vtot_worker register
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
break
except Exception:
pass
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed change image generation model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["imagegeneration"]["model_name"] = new_model_name
msg = f"success change image generation model from {model_name} to {new_model_name}"
return {"code": 200, "msg": msg}
else:
msg = f"success stop image generation model {model_name}"
return {"code": 200, "msg": msg}
@app.post("/get_image_generation_data")
def get_image_generation_data(
prompt_data: str = Body(..., description="prompt data"),
negative_prompt: str = Body(..., description="negative prompt"),
btranslate_prompt: bool = Body(False, description=""),
) -> Dict:
if len(prompt_data) == 0:
msg = "failed translate prompt to image."
return {"code": 500, "msg": msg}
workerconfig = get_image_generation_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_image_generation_data",
json={"prompt_data": prompt_data, "negative_prompt": negative_prompt, "btranslate_prompt": btranslate_prompt},
)
return r.json()
except Exception:
return {"code": 500, "image": ""}
@app.post("/get_music_generation_model")
def get_music_generation_model(
) -> Dict:
model_name = glob_minor_models["musicgeneration"]["model_name"]
return {"code": 200, "model": model_name}
@app.post("/release_music_generation_model")
def release_music_generation_model(
model_name: str = Body(..., description="Unload the model", samples=""),
new_model_name: str = Body(None, description="New model"),
) -> Dict:
if new_model_name:
print(f"Change music generation model: from {model_name} to {new_model_name})")
else:
print(f"Stoping music generation model: {model_name}")
workerconfig = get_music_generation_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
if model_name:
q.put([model_name, "stop_music_generation_model", None])
timer = HTTPX_RELEASE_VOICE_TIMEOUT # wait for release model
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
except Exception:
break
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed to stop music generation model: {model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["musicgeneration"]["model_name"] = ""
if new_model_name:
q.put([model_name, "start_music_generation_model", new_model_name])
timer = HTTPX_LOAD_VOICE_TIMEOUT # wait for new vtot_worker register
while timer > 0:
with get_httpx_client() as client:
try:
_ = client.post(worker_address + "/get_name",
json={})
break
except Exception:
pass
time.sleep(1)
timer -= 1
if timer <= 0:
msg = f"failed change music generation model from {model_name} to {new_model_name}"
print(msg)
return {"code": 500, "msg": msg}
glob_minor_models["musicgeneration"]["model_name"] = new_model_name
msg = f"success change music generation model from {model_name} to {new_model_name}"
return {"code": 200, "msg": msg}
else:
msg = f"success stop music generation model {model_name}"
return {"code": 200, "msg": msg}
@app.post("/get_music_generation_data")
def get_music_generation_data(
prompt_data: str = Body(..., description="prompt data"),
btranslate_prompt: bool = Body(False, description=""),
) -> Dict:
if len(prompt_data) == 0:
msg = "failed translate prompt to music."
return {"code": 500, "msg": msg}
workerconfig = get_music_generation_worker_config()
worker_address = "http://" + workerconfig["host"] + ":" + str(workerconfig["port"])
with get_httpx_client() as client:
try:
r = client.post(worker_address + "/get_music_generation_data",
json={"prompt_data": prompt_data, "btranslate_prompt": btranslate_prompt},
)
return r.json()
except Exception:
return {"code": 500, "audio": ""}
@app.post("/download_llm_model")
def download_llm_model(
model_name: str = Body(..., description="model name"),
hugg_path: str = Body("", description="huggingface path"),
local_path: str = Body("", description="local path"),
):
from huggingface_hub import snapshot_download
async def fake_json_streamer() -> AsyncIterable[str]:
def running_download(repo_id, local_dir):
snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=False)
print("running_download exit!")
thread = threading.Thread(target=running_download, args=(hugg_path, local_path))
thread.start()
percentage = 0.0
while True:
yield json.dumps(
{"text": "percentage", "percentage": percentage},
ensure_ascii=False)
await asyncio.sleep(2)
if percentage < 100.0:
percentage += 1.0
if not thread.is_alive():
print("async_callback exit!")
break
return StreamingResponse(fake_json_streamer(), media_type="text/event-stream")
host = FSCHAT_CONTROLLER["host"]
port = FSCHAT_CONTROLLER["port"]
uvicorn.run(app, host=host, port=port)
def create_empty_worker_app() -> FastAPI:
from fastchat.serve.base_model_worker import app
MakeFastAPIOffline(app)
app.title = "FastChat empty Model"
app._worker = ""
app._model = None
app._model_name = ""
return app
def create_model_worker_app(log_level: str = "INFO", **kwargs) -> Union[FastAPI, None]:
import fastchat.constants
from fastchat.serve.base_model_worker import app
fastchat.constants.LOGDIR = LOG_PATH
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args([])
app._model = None
app._streamer = None
app._tokenizer = None
app._model_name = ""
for k, v in kwargs.items():
setattr(args, k, v)
if _ := kwargs.get("langchain_model"):
worker = ""
# Online model
elif kwargs.get("online_model", False):
cloud_model = init_cloud_models(args.model_names[0])
app._model = cloud_model
app._model_name = args.model_names[0]
MakeFastAPIOffline(app)
app.title = f"Online Model ({args.model_names[0]})"
return app
# Multimodal model
elif kwargs.get("multimodal_model", False) is True:
init_multimodal_models(app, args)
MakeFastAPIOffline(app)
app.title = f"Multimodal Model ({args.model_names[0]})"
return app
# Code model
elif kwargs.get("code_model", False) is True:
init_code_models(app, args)
MakeFastAPIOffline(app)
app.title = f"Code Model ({args.model_names[0]})"
return app
# Special model
elif kwargs.get("special_model", False) is True:
init_special_models(app, args)
MakeFastAPIOffline(app)
app.title = f"Special Model ({args.model_names[0]})"
return app
# fastchat model
else:
#from WebUI.configs.modelconfig import VLLM_MODEL_DICT
from fastchat.serve.model_worker import app, GptqConfig, AWQConfig, ModelWorker, worker_id
args.gpus = "0"
args.num_gpus = 1
args.cpu_offloading = None
args.gptq_ckpt = None
args.gptq_wbits = 16
args.gptq_groupsize = -1
args.gptq_act_order = False
args.awq_ckpt = None
args.awq_wbits = 16
args.awq_groupsize = -1
args.model_names = [""]
args.conv_template = None
args.limit_worker_concurrency = 5
args.stream_interval = 2
args.no_register = False
args.embed_in_truncate = False
for k, v in kwargs.items():
setattr(args, k, v)
if args.gpus:
if args.num_gpus is None:
args.num_gpus = len(args.gpus.split(','))
if len(args.gpus.split(",")) < args.num_gpus:
raise ValueError(
f"Larger --num-gpus ({args.num_gpus}) than --gpus {args.gpus}!"
)
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
gptq_config = GptqConfig(
ckpt=args.gptq_ckpt or args.model_path,
wbits=args.gptq_wbits,
groupsize=args.gptq_groupsize,
act_order=args.gptq_act_order,
)
awq_config = AWQConfig(
ckpt=args.awq_ckpt or args.model_path,
wbits=args.awq_wbits,
groupsize=args.awq_groupsize,
)
try:
worker = ModelWorker(
controller_addr=args.controller_address,
worker_addr=args.worker_address,
worker_id=worker_id,
model_path=args.model_path,
model_names=args.model_names,
limit_worker_concurrency=args.limit_worker_concurrency,
no_register=args.no_register,
device=args.device,
num_gpus=args.num_gpus,
max_gpu_memory=args.max_gpu_memory,
load_8bit=args.load_8bit,
cpu_offloading=args.cpu_offloading,
gptq_config=gptq_config,
awq_config=awq_config,
stream_interval=args.stream_interval,
conv_template=args.conv_template,
embed_in_truncate=args.embed_in_truncate,
)
except Exception as e:
print(e)
return None
sys.modules["fastchat.serve.model_worker"].args = args
sys.modules["fastchat.serve.model_worker"].gptq_config = gptq_config
# sys.modules["fastchat.serve.model_worker"].worker = worker
sys.modules["fastchat.serve.model_worker"].logger.setLevel(log_level)
MakeFastAPIOffline(app)
app.title = f"FastChat LLM Server ({args.model_names[0]})"
app._worker = worker
return app
def create_openai_api_app(
controller_address: str,
api_keys: List = [],
log_level: str = "INFO",
) -> FastAPI:
import fastchat.constants
fastchat.constants.LOGDIR = LOG_PATH
from fastchat.serve.openai_api_server import app, CORSMiddleware, app_settings
from fastchat.utils import build_logger
logger = build_logger("openai_api", "openai_api.log")
logger.setLevel(log_level)
app.add_middleware(
CORSMiddleware,
allow_credentials=True,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
sys.modules["fastchat.serve.openai_api_server"].logger = logger
app_settings.controller_address = controller_address
app_settings.api_keys = api_keys
MakeFastAPIOffline(app)
app.title = "FastChat OpeanAI API Server"
return app
def run_openai_api(started_event: mp.Event = None):
import uvicorn
set_httpx_config()
controller_addr = fschat_controller_address()
app = create_openai_api_app(controller_addr, log_level="INFO") # TODO: not support keys yet.
_set_app_event(app, started_event)
host = FSCHAT_OPENAI_API["host"]
port = FSCHAT_OPENAI_API["port"]
uvicorn.run(app, host=host, port=port)
def create_voice_worker_app(log_level: str = "INFO", **kwargs) -> Union[FastAPI, None]:
app = FastAPI()
parser = argparse.ArgumentParser()
args = parser.parse_args([])
for k, v in kwargs.items():
setattr(args, k, v)
try:
config = {
"model_path": args.model_path,
"device": args.device,
"loadbits": args.loadbits,
}
voice_model = init_voice_models(config)
if voice_model is None:
return None
except Exception as e:
print(e)
return None
app.title = f"Voice model worker ({args.model_name})"
app._worker = ""
return app
def run_voice_worker(