forked from OE-LUCIFER/Webscout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebai.py
2590 lines (2415 loc) · 85.7 KB
/
webai.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 webscout
import click
import cmd
import logging
import os
import sys
import clipman
import re
import rich
import getpass
import json
import re
import sys
import datetime
import time
import subprocess
from threading import Thread as thr
from functools import wraps
from rich.panel import Panel
from rich.style import Style
from rich.markdown import Markdown
from rich.console import Console
from rich.live import Live
from rich.table import Table
from rich.prompt import Prompt
from rich.progress import Progress
from typing import Iterator
from .AIutel import Optimizers
from .AIutel import default_path
from .AIutel import AwesomePrompts
from .AIutel import RawDog
from .AIutel import Audio
from .AIutel import available_providers
from colorama import Fore
from colorama import init as init_colorama
from dotenv import load_dotenv
import g4f
import webscout
import webscout.AIutel
from pyfiglet import figlet_format
init_colorama(autoreset=True)
load_dotenv() # loads .env variables
console = Console()
logging.basicConfig(
format="%(asctime)s - %(levelname)s : %(message)s ",
datefmt="%H:%M:%S",
level=logging.INFO,
)
try:
clipman.init()
except Exception as e:
logging.debug(f"Dropping clipman in favor of pyperclip - {(e)}")
import pyperclip
clipman.set = pyperclip.copy
clipman.get = pyperclip.paste
class this:
"""Console's common variables"""
rich_code_themes = ["monokai", "paraiso-dark", "igor", "vs", "fruity", "xcode"]
default_provider = "phind"
getExc = lambda e: e.args[1] if len(e.args) > 1 else str(e)
context_settings = dict(auto_envvar_prefix="Webscout")
"""Console utils"""
@staticmethod
def run_system_command(
command: str, exit_on_error: bool = True, stdout_error: bool = True
):
"""Run commands against system
Args:
command (str): shell command
exit_on_error (bool, optional): Exit on error. Defaults to True.
stdout_error (bool, optional): Print out the error. Defaults to True.
Returns:
tuple : (is_successfull, object[Exception|Subprocess.run])
"""
try:
# Run the command and capture the output
result = subprocess.run(
command,
shell=True,
check=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return (True, result)
except subprocess.CalledProcessError as e:
# Handle error if the command returns a non-zero exit code
if stdout_error:
click.secho(f"Error Occurred: while running '{command}'", fg="yellow")
click.secho(e.stderr, fg="red")
sys.exit(e.returncode) if exit_on_error else None
return (False, e)
def g4f_providers_in_dict(
url=True,
working=True,
stream=False,
context=False,
gpt35=False,
gpt4=False,
selenium=False,
):
from webscout.g4f import GPT4FREE
import g4f.Provider.selenium as selenium_based
selenium_based_providers: list = dir(selenium_based)
hunted_providers = []
required_attrs = (
"url",
"working",
"supports_gpt_35_turbo",
"supports_gpt_4",
"supports_stream",
"supports_message_history",
)
def sanitize_provider(provider: object):
for attr in required_attrs:
if not hasattr(provider, attr):
setattr(provider, attr, False)
return provider
for provider_name, provider_class in g4f.Provider.__map__.items():
provider = sanitize_provider(provider_class)
provider_meta = dict(name=provider_name)
if url:
provider_meta["url"] = provider.url
if working:
provider_meta["working"] = provider.working
if stream:
provider_meta["stream"] = provider.supports_stream
if context:
provider_meta["context"] = provider.supports_message_history
if gpt35:
provider_meta["gpt35_turbo"] = provider.supports_gpt_35_turbo
if gpt4:
provider_meta["gpt4"] = provider.supports_gpt_4
if selenium:
try:
selenium_based_providers.index(provider_meta["name"])
value = True
except ValueError:
value = False
provider_meta["non_selenium"] = value
hunted_providers.append(provider_meta)
return hunted_providers
@staticmethod
def stream_output(
iterable: Iterator,
title: str = "",
is_markdown: bool = True,
style: object = Style(),
transient: bool = False,
title_generator: object = None,
title_generator_params: dict = {},
code_theme: str = "monokai",
vertical_overflow: str = "ellipsis",
) -> None:
"""Stdout streaming response
Args:
iterable (Iterator): Iterator containing contents to be stdout
title (str, optional): Content title. Defaults to ''.
is_markdown (bool, optional): Flag for markdown content. Defaults to True.
style (object, optional): `rich.style` instance. Defaults to Style().
transient (bool, optional): Flag for transient. Defaults to False.
title_generator (object, optional): Function for generating title. Defaults to None.
title_generator_params (dict, optional): Kwargs for `title_generator` function. Defaults to {}.
code_theme (str, optional): Theme for styling codes. Defaults to `monokai`
vertical_overflow (str, optional): Vertical overflow behaviour on content display. Defaultss to ellipsis.
"""
render_this = ""
with Live(
render_this,
transient=transient,
refresh_per_second=8,
vertical_overflow=vertical_overflow,
) as live:
for entry in iterable:
render_this += entry
live.update(
Panel(
(
Markdown(entry, code_theme=code_theme)
if is_markdown
else entry
),
title=title,
style=style,
)
)
if title_generator:
title = title_generator(**title_generator_params)
live.update(
Panel(
Markdown(entry, code_theme=code_theme) if is_markdown else entry,
title=title,
style=style,
)
)
@staticmethod
def clear_history_file(file_path, is_true):
"""When --new flag is True"""
if is_true and os.path.isfile(file_path):
try:
os.remove(file_path)
except Exception as e:
logging.error(
f"Failed to clear previous chat history - {this.getExc(e)}"
)
@staticmethod
def handle_exception(func):
"""Safely handles cli-based exceptions and exit status-codes"""
@wraps(func)
def decorator(*args, **kwargs):
try:
exit_status = func(*args, **kwargs)
except Exception as e:
exit_status = False
logging.error(this.getExc(e))
finally:
sys.exit(0 if exit_status not in (False, "") else 1)
return decorator
class busy_bar:
querying = None
__spinner = (
(),
("-", "\\", "|", "/"),
(
"█■■■■",
"■█■■■",
"■■█■■",
"■■■█■",
"■■■■█",
),
("⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "),
)
spin_index = 0
sleep_time = 0.1
@classmethod
def __action(
cls,
):
while cls.querying:
for spin in cls.__spinner[cls.spin_index]:
print(" " + spin, end="\r", flush=True)
if not cls.querying:
break
time.sleep(cls.sleep_time)
@classmethod
def start_spinning(
cls,
):
try:
cls.querying = True
t1 = thr(
target=cls.__action,
args=(),
)
t1.start()
except Exception as e:
cls.querying = False
logging.debug(this.getExc(e))
t1.join()
@classmethod
def stop_spinning(cls):
"""Stop displaying busy-bar"""
if cls.querying:
cls.querying = False
time.sleep(cls.sleep_time)
@classmethod
def run(cls, help: str = "Exception", index: int = None, immediate: bool = False):
"""Handle function exceptions safely why showing busy bar
Args:
help (str, optional): Message to be shown incase of an exception. Defaults to ''.
index (int, optional): Busy bars spin index. Defaults to `default`.
immediate (bool, optional): Start the spinning immediately. Defaults to False.
"""
if isinstance(index, int):
cls.spin_index = index
def decorator(func):
@wraps(func) # Preserves function metadata
def main(*args, **kwargs):
try:
if immediate:
cls.start_spinning()
return func(*args, **kwargs)
except KeyboardInterrupt:
cls.stop_spinning()
return
except EOFError:
cls.querying = False
sys.exit(logging.info("Stopping program"))
except Exception as e:
logging.error(f"{help} - {this.getExc(e)}")
finally:
cls.stop_spinning()
return main
return decorator
class Main(cmd.Cmd):
intro = (
"Welcome to webai Chat in terminal. "
"Type 'help' or 'h' for usage info.\n"
)
def __init__(
self,
max_tokens,
temperature,
top_k,
top_p,
model,
auth,
timeout,
disable_conversation,
filepath,
update_file,
intro,
history_offset,
awesome_prompt,
proxy_path,
provider,
quiet=False,
chat_completion=False,
ignore_working=False,
rawdog=False,
internal_exec=False,
confirm_script=False,
interpreter="python",
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
if proxy_path:
with open(proxy_path) as fh:
proxies = json.load(fh)
else:
proxies = {}
try:
getOr = lambda option, default: option if option else default
if rawdog:
self.RawDog = RawDog(
quiet=quiet,
internal_exec=internal_exec,
confirm_script=confirm_script,
interpreter=interpreter,
prettify=True,
)
intro = self.RawDog.intro_prompt
getpass.getuser = lambda: "RawDog"
if provider == "g4fauto":
from webscout.g4f import TestProviders
test = TestProviders(quiet=quiet, timeout=timeout)
g4fauto = test.best if ignore_working else test.auto
if isinstance(g4fauto, str):
provider = "g4fauto+" + g4fauto
from webscout.g4f import GPT4FREE
self.bot = GPT4FREE(
provider=g4fauto,
auth=auth,
max_tokens=max_tokens,
model=model,
chat_completion=chat_completion,
ignore_working=ignore_working,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
else:
raise Exception(
"No working g4f provider found. "
"Consider running 'webscout gpt4free test -y' first"
)
elif provider == "poe":
assert auth, (
"Path to poe.com.cookies.json file or 'p-b' cookie-value is required. "
"Use the flag `--key` or `-k`"
)
from webscout import POE
self.bot = POE(
cookie=auth,
model=getOr(model, "Assistant"),
proxy=bool(proxies),
timeout=timeout,
filepath=filepath,
update_file=update_file,
intro=intro,
act=awesome_prompt,
)
elif provider == "openai":
assert auth, (
"OpenAI's API-key is required. " "Use the flag `--key` or `-k`"
)
from webscout import OPENAI
self.bot = OPENAI(
api_key=auth,
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
presence_penalty=top_p,
frequency_penalty=top_k,
top_p=top_p,
model=getOr(model, model),
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
if provider == "auto":
from webscout import AUTO
self.bot = AUTO(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "opengpt":
from webscout import OPENGPT
self.bot = OPENGPT(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
assistant_id="bca37014-6f97-4f2b-8928-81ea8d478d88"
)
elif provider == "thinkany":
from webscout import ThinkAnyAI
self.bot = ThinkAnyAI(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "llama3":
from webscout import LLAMA3
self.bot = LLAMA3(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
model=getOr(model, "llama3-8b"),
)
elif provider == "berlin4h":
from webscout import Berlin4h
self.bot = Berlin4h(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "yepchat":
from webscout import YEPCHAT
self.bot = YEPCHAT(
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
presence_penalty=top_p,
frequency_penalty=top_k,
top_p=top_p,
model=getOr(model, "Mixtral-8x7B-Instruct-v0.1"),
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "groq":
assert auth, (
"GROQ's API-key is required. " "Use the flag `--key` or `-k`"
)
from webscout import GROQ
self.bot = GROQ(
api_key=auth,
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
presence_penalty=top_p,
frequency_penalty=top_k,
top_p=top_p,
model=getOr(model, "mixtral-8x7b-32768"),
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "cohere":
assert auth, (
"Cohere's API-key is required. Use the flag `--key` or `-k`"
)
from webscout import Cohere
self.bot = Cohere(
api_key=auth,
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
model=getOr(model, "command-r-plus"),
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "reka":
from webscout import REKA
self.bot = REKA(
api_key=auth,
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
model=getOr(model, "reka-core"),
# quiet=quiet,
)
elif provider == "deepseek":
from webscout import DeepSeek
self.bot = DeepSeek(
api_key=auth,
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
model=getOr(model, "deepseek_chat"),
# quiet=quiet,
)
elif provider == "koboldai":
from webscout import KOBOLDAI
self.bot = KOBOLDAI(
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "deepinfra":
from webscout import DeepInfra
self.bot = DeepInfra(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
model=getOr(model, "Qwen/Qwen2-72B-Instruct"),
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "xjai":
from webscout import Xjai
self.bot = Xjai(
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "vtlchat":
from webscout import VTLchat
self.bot = VTLchat(
is_conversation=disable_conversation,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "gemini":
from webscout import GEMINI
assert auth, (
"Path to gemini.google.com.cookies.json file is required. "
"Use the flag `--key` or `-k`"
)
self.bot = GEMINI(
cookie_file=auth,
proxy=proxies,
timeout=timeout,
)
elif provider == "phind":
from webscout import PhindSearch
self.bot = PhindSearch(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
model=getOr(model, "Phind Model"),
quiet=quiet,
)
elif provider == "andi":
from webscout import AndiSearch
self.bot = AndiSearch(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "blackboxai":
from webscout import BLACKBOXAI
self.bot = BLACKBOXAI(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "you":
from webscout import YouChat
self.bot = YouChat(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider in webscout.gpt4free_providers:
from webscout.g4f import GPT4FREE
self.bot = GPT4FREE(
provider=provider,
is_conversation=disable_conversation,
auth=auth,
max_tokens=max_tokens,
model=model,
chat_completion=chat_completion,
ignore_working=ignore_working,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)
elif provider == "perplexity":
from webscout import Perplexity
self.bot = Perplexity(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
quiet=quiet,
)
elif provider == "ollama":
from webscout import OLLAMA
self.bot = OLLAMA(
is_conversation=disable_conversation,
max_tokens=max_tokens,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
model=getOr(model, "qwen2:0.5b")
)
else:
raise NotImplementedError(
f"The provider `{provider}` is not yet implemented."
)
except Exception as e:
logging.error(this.getExc(e))
click.secho("Quitting", fg="red")
sys.exit(1)
self.prettify = True
self.color = "cyan"
self.code_theme = "monokai"
self.quiet = quiet
self.vertical_overflow = "ellipsis"
self.disable_stream = False
self.provider = provider
self.disable_coloring = False
self.internal_exec = internal_exec
self.confirm_script = confirm_script
self.interpreter = interpreter
self.rawdog = rawdog
self.read_aloud = False
self.read_aloud_voice = "Brian"
self.path_to_last_response_audio = None
self.__init_time = time.time()
self.__start_time = time.time()
self.__end_time = time.time()
@property
def get_provider(self):
if self.provider == "auto" and self.bot.provider_name is not None:
return self.bot.provider_name
else:
return self.provider
@property
def prompt(self):
current_time = datetime.datetime.now().strftime("%H:%M:%S")
def find_range(start, end, hms: bool = False):
in_seconds = round(end - start, 1)
return (
str(datetime.timedelta(seconds=in_seconds)).split(".")[0].zfill(8)
if hms
else in_seconds
)
if not self.disable_coloring:
cmd_prompt = (
f"╭─[`{Fore.GREEN}{getpass.getuser().capitalize()}@webai]`"
f"(`{Fore.YELLOW}{self.get_provider})`"
f"~[`{Fore.LIGHTWHITE_EX}⏰{Fore.MAGENTA}{current_time}-`"
f"{Fore.LIGHTWHITE_EX}💻{Fore.BLUE}{find_range(self.__init_time, time.time(), True)}-`"
f"{Fore.LIGHTWHITE_EX}⚡️{Fore.RED}{find_range(self.__start_time, self.__end_time)}s]`"
f"\n╰─>"
)
whitelist = ["[", "]", "~", "-", "(", ")"]
for character in whitelist:
cmd_prompt = cmd_prompt.replace(character + "`", Fore.RESET + character)
return cmd_prompt
else:
return (
f"╭─[{getpass.getuser().capitalize()}@webscout]({self.get_provider})"
f"~[⏰{current_time}"
f"-💻{find_range(self.__init_time, time.time(), True)}"
f"-⚡️{find_range(self.__start_time, self.__end_time)}s]"
f"~[⏰{current_time}"
f"-💻{find_range(self.__init_time, time.time(), True)}"
f"-⚡️{find_range(self.__start_time, self.__end_time)}s]"
"\n╰─>"
)
def output_bond(
self,
title: str,
text: str,
color: str = "cyan",
frame: bool = True,
is_json: bool = False,
):
"""Print prettified output
Args:
title (str): Title
text (str): Info to be printed
color (str, optional): Output color. Defaults to "cyan".
frame (bool, optional): Add frame. Defaults to True.
"""
if is_json:
text = f"""
```json
{json.dumps(text,indent=4)}
```
"""
rich.print(
Panel(
Markdown(text, code_theme=self.code_theme),
title=title.title(),
style=Style(
color=color,
frame=frame,
),
),
)
if is_json and click.confirm("Do you wish to save this"):
default_path = title + ".json"
save_to = click.prompt(
"Enter path to save to", default=default_path, type=click.STRING
)
with open(save_to, "a") as fh:
json.dump(text, fh, indent=4)
click.secho(f"Successfuly saved to `{save_to}`", fg="green")
def do_h(self, line):
"""Show help info in tabular form"""
table = Table(
title="Help info",
show_lines=True,
)
table.add_column("No.", style="white", justify="center")
table.add_column("Command", style="yellow", justify="left")
table.add_column("Function", style="cyan")
command_methods = [
getattr(self, method)
for method in dir(self)
if callable(getattr(self, method)) and method.startswith("do_")
]
command_methods.append(self.default)
command_methods.reverse()
for no, method in enumerate(command_methods):
table.add_row(
str(no + 1),
method.__name__[3:] if not method == self.default else method.__name__,
method.__doc__,
)
Console().print(table)
@busy_bar.run("Settings saved")
def do_settings(self, line):
"""Configure settings"""
self.prettify = click.confirm(
"\nPrettify markdown response", default=self.prettify
)
busy_bar.spin_index = click.prompt(
"Spin bar index [0: None, 1:/, 2:■█■■■, 3:⣻]",
default=busy_bar.spin_index,
type=click.IntRange(0, 3),
)
self.color = click.prompt(
"Response stdout font color", default=self.color or "white"
)
self.code_theme = Prompt.ask(
"Enter code_theme", choices=this.rich_code_themes, default=self.code_theme
)
self.vertical_overflow = Prompt.ask(
"\nVertical overflow behaviour",
choices=["ellipsis", "visible", "crop"],
default=self.vertical_overflow,
)
self.bot.max_tokens_to_sample = click.prompt(
"\nMaximum tokens to sample",
type=click.INT,
default=self.bot.max_tokens_to_sample,
)
self.bot.temperature = click.prompt(
"Temperature", type=click.FLOAT, default=self.bot.temperature
)
self.bot.top_k = click.prompt(
"Chance of topic being repeated, top_k",
type=click.FLOAT,
default=self.bot.top_k,
)
self.bot.top_p = click.prompt(
"Sampling threshold during inference time, top_p",
type=click.FLOAT,
default=self.bot.top_p,
)
self.bot.model = click.prompt(
"Model name", type=click.STRING, default=self.bot.model
)
@busy_bar.run(help="System error")
def do_copy_this(self, line):
"""Copy last response
Usage:
copy_this: