webscout 1.3.0__py3-none-any.whl → 1.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

webscout/webai.py ADDED
@@ -0,0 +1,2306 @@
1
+ import webscout
2
+ import click
3
+ import cmd
4
+ import logging
5
+ import os
6
+ import sys
7
+ import clipman
8
+ import re
9
+ import rich
10
+ import getpass
11
+ import json
12
+ import re
13
+ import sys
14
+ import datetime
15
+ import time
16
+ import subprocess
17
+ from threading import Thread as thr
18
+ from functools import wraps
19
+ from rich.panel import Panel
20
+ from rich.style import Style
21
+ from rich.markdown import Markdown
22
+ from rich.console import Console
23
+ from rich.live import Live
24
+ from rich.table import Table
25
+ from rich.prompt import Prompt
26
+ from rich.progress import Progress
27
+ from typing import Iterator
28
+ from webscout.AIutel import Optimizers
29
+ from webscout.AIutel import default_path
30
+ from webscout.AIutel import AwesomePrompts
31
+ from webscout.AIutel import RawDog
32
+ from colorama import Fore
33
+ from colorama import init as init_colorama
34
+ from dotenv import load_dotenv
35
+ import g4f
36
+
37
+ import webscout.AIutel
38
+
39
+ init_colorama(autoreset=True)
40
+
41
+ load_dotenv() # loads .env variables
42
+
43
+ logging.basicConfig(
44
+ format="%(asctime)s - %(levelname)s : %(message)s ", # [%(module)s,%(lineno)s]", # for debug purposes
45
+ datefmt="%H:%M:%S",
46
+ level=logging.INFO,
47
+ )
48
+
49
+ try:
50
+ clipman.init()
51
+ except Exception as e:
52
+ logging.debug(f"Dropping clipman in favor of pyperclip - {(e)}")
53
+ import pyperclip
54
+
55
+ clipman.set = pyperclip.copy
56
+ clipman.get = pyperclip.paste
57
+
58
+
59
+ class this:
60
+ """Console's common variables"""
61
+
62
+ rich_code_themes = ["monokai", "paraiso-dark", "igor", "vs", "fruity", "xcode"]
63
+
64
+ default_provider = "sean"
65
+
66
+ getExc = lambda e: e.args[1] if len(e.args) > 1 else str(e)
67
+
68
+ context_settings = dict(auto_envvar_prefix="Webscout")
69
+
70
+ """Console utils"""
71
+
72
+ @staticmethod
73
+ def run_system_command(
74
+ command: str, exit_on_error: bool = True, stdout_error: bool = True
75
+ ):
76
+ """Run commands against system
77
+ Args:
78
+ command (str): shell command
79
+ exit_on_error (bool, optional): Exit on error. Defaults to True.
80
+ stdout_error (bool, optional): Print out the error. Defaults to True.
81
+
82
+ Returns:
83
+ tuple : (is_successfull, object[Exception|Subprocess.run])
84
+ """
85
+ try:
86
+ # Run the command and capture the output
87
+ result = subprocess.run(
88
+ command,
89
+ shell=True,
90
+ check=True,
91
+ text=True,
92
+ stdout=subprocess.PIPE,
93
+ stderr=subprocess.PIPE,
94
+ )
95
+ return (True, result)
96
+ except subprocess.CalledProcessError as e:
97
+ # Handle error if the command returns a non-zero exit code
98
+ if stdout_error:
99
+ click.secho(f"Error Occurred: while running '{command}'", fg="yellow")
100
+ click.secho(e.stderr, fg="red")
101
+ sys.exit(e.returncode) if exit_on_error else None
102
+ return (False, e)
103
+
104
+ def g4f_providers_in_dict(
105
+ url=True,
106
+ working=True,
107
+ stream=False,
108
+ context=False,
109
+ gpt35=False,
110
+ gpt4=False,
111
+ selenium=False,
112
+ ):
113
+ from webscout.g4f import GPT4FREE
114
+ import g4f.Provider.selenium as selenium_based
115
+
116
+ selenium_based_providers: list = dir(selenium_based)
117
+ hunted_providers = []
118
+ required_attrs = (
119
+ "url",
120
+ "working",
121
+ "supports_gpt_35_turbo",
122
+ "supports_gpt_4",
123
+ "supports_stream",
124
+ "supports_message_history",
125
+ )
126
+
127
+ def sanitize_provider(provider: object):
128
+ for attr in required_attrs:
129
+ if not hasattr(provider, attr):
130
+ setattr(provider, attr, False)
131
+
132
+ return provider
133
+
134
+ for provider_name, provider_class in g4f.Provider.__map__.items():
135
+ provider = sanitize_provider(provider_class)
136
+ provider_meta = dict(name=provider_name)
137
+ if url:
138
+ provider_meta["url"] = provider.url
139
+ if working:
140
+ provider_meta["working"] = provider.working
141
+ if stream:
142
+ provider_meta["stream"] = provider.supports_stream
143
+ if context:
144
+ provider_meta["context"] = provider.supports_message_history
145
+ if gpt35:
146
+ provider_meta["gpt35_turbo"] = provider.supports_gpt_35_turbo
147
+ if gpt4:
148
+ provider_meta["gpt4"] = provider.supports_gpt_4
149
+ if selenium:
150
+ try:
151
+ selenium_based_providers.index(provider_meta["name"])
152
+ value = True
153
+ except ValueError:
154
+ value = False
155
+ provider_meta["non_selenium"] = value
156
+
157
+ hunted_providers.append(provider_meta)
158
+
159
+ return hunted_providers
160
+
161
+ @staticmethod
162
+ def stream_output(
163
+ iterable: Iterator,
164
+ title: str = "",
165
+ is_markdown: bool = True,
166
+ style: object = Style(),
167
+ transient: bool = False,
168
+ title_generator: object = None,
169
+ title_generator_params: dict = {},
170
+ code_theme: str = "monokai",
171
+ vertical_overflow: str = "ellipsis",
172
+ ) -> None:
173
+ """Stdout streaming response
174
+
175
+ Args:
176
+ iterable (Iterator): Iterator containing contents to be stdout
177
+ title (str, optional): Content title. Defaults to ''.
178
+ is_markdown (bool, optional): Flag for markdown content. Defaults to True.
179
+ style (object, optional): `rich.style` instance. Defaults to Style().
180
+ transient (bool, optional): Flag for transient. Defaults to False.
181
+ title_generator (object, optional): Function for generating title. Defaults to None.
182
+ title_generator_params (dict, optional): Kwargs for `title_generator` function. Defaults to {}.
183
+ code_theme (str, optional): Theme for styling codes. Defaults to `monokai`
184
+ vertical_overflow (str, optional): Vertical overflow behaviour on content display. Defaultss to ellipsis.
185
+ """
186
+ render_this = ""
187
+ with Live(
188
+ render_this,
189
+ transient=transient,
190
+ refresh_per_second=8,
191
+ vertical_overflow=vertical_overflow,
192
+ ) as live:
193
+ for entry in iterable:
194
+ render_this += entry
195
+ live.update(
196
+ Panel(
197
+ (
198
+ Markdown(entry, code_theme=code_theme)
199
+ if is_markdown
200
+ else entry
201
+ ),
202
+ title=title,
203
+ style=style,
204
+ )
205
+ )
206
+ if title_generator:
207
+ title = title_generator(**title_generator_params)
208
+ live.update(
209
+ Panel(
210
+ Markdown(entry, code_theme=code_theme) if is_markdown else entry,
211
+ title=title,
212
+ style=style,
213
+ )
214
+ )
215
+
216
+ @staticmethod
217
+ def clear_history_file(file_path, is_true):
218
+ """When --new flag is True"""
219
+ if is_true and os.path.isfile(file_path):
220
+ try:
221
+ os.remove(file_path)
222
+ except Exception as e:
223
+ logging.error(
224
+ f"Failed to clear previous chat history - {this.getExc(e)}"
225
+ )
226
+
227
+ @staticmethod
228
+ def handle_exception(func):
229
+ """Safely handles cli-based exceptions and exit status-codes"""
230
+
231
+ @wraps(func)
232
+ def decorator(*args, **kwargs):
233
+ try:
234
+ exit_status = func(*args, **kwargs)
235
+ except Exception as e:
236
+ exit_status = False
237
+ logging.error(this.getExc(e))
238
+ finally:
239
+ sys.exit(0 if exit_status not in (False, "") else 1)
240
+
241
+ return decorator
242
+
243
+
244
+ class busy_bar:
245
+ querying = None
246
+ __spinner = (
247
+ (),
248
+ ("-", "\\", "|", "/"),
249
+ (
250
+ "█■■■■",
251
+ "■█■■■",
252
+ "■■█■■",
253
+ "■■■█■",
254
+ "■■■■█",
255
+ ),
256
+ ("⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "),
257
+ )
258
+ spin_index = 0
259
+ sleep_time = 0.1
260
+
261
+ @classmethod
262
+ def __action(
263
+ cls,
264
+ ):
265
+ while cls.querying:
266
+ for spin in cls.__spinner[cls.spin_index]:
267
+ print(" " + spin, end="\r", flush=True)
268
+ if not cls.querying:
269
+ break
270
+ time.sleep(cls.sleep_time)
271
+
272
+ @classmethod
273
+ def start_spinning(
274
+ cls,
275
+ ):
276
+ try:
277
+ cls.querying = True
278
+ t1 = thr(
279
+ target=cls.__action,
280
+ args=(),
281
+ )
282
+ t1.start()
283
+ except Exception as e:
284
+ cls.querying = False
285
+ logging.debug(this.getExc(e))
286
+ t1.join()
287
+
288
+ @classmethod
289
+ def stop_spinning(cls):
290
+ """Stop displaying busy-bar"""
291
+ if cls.querying:
292
+ cls.querying = False
293
+ time.sleep(cls.sleep_time)
294
+
295
+ @classmethod
296
+ def run(cls, help: str = "Exception", index: int = None, immediate: bool = False):
297
+ """Handle function exceptions safely why showing busy bar
298
+
299
+ Args:
300
+ help (str, optional): Message to be shown incase of an exception. Defaults to ''.
301
+ index (int, optional): Busy bars spin index. Defaults to `default`.
302
+ immediate (bool, optional): Start the spinning immediately. Defaults to False.
303
+ """
304
+ if isinstance(index, int):
305
+ cls.spin_index = index
306
+
307
+ def decorator(func):
308
+ @wraps(func) # Preserves function metadata
309
+ def main(*args, **kwargs):
310
+ try:
311
+ if immediate:
312
+ cls.start_spinning()
313
+ return func(*args, **kwargs)
314
+ except KeyboardInterrupt:
315
+ cls.stop_spinning()
316
+ return
317
+ except EOFError:
318
+ cls.querying = False
319
+ sys.exit(logging.info("Stopping program"))
320
+ except Exception as e:
321
+ logging.error(f"{help} - {this.getExc(e)}")
322
+ finally:
323
+ cls.stop_spinning()
324
+
325
+ return main
326
+
327
+ return decorator
328
+
329
+
330
+ class Main(cmd.Cmd):
331
+ intro = (
332
+ "Welcome to webai Chat in terminal. "
333
+ "Type 'help' or 'h' for usage info.\n"
334
+ )
335
+
336
+ def __init__(
337
+ self,
338
+ max_tokens,
339
+ temperature,
340
+ top_k,
341
+ top_p,
342
+ model,
343
+ auth,
344
+ timeout,
345
+ disable_conversation,
346
+ filepath,
347
+ update_file,
348
+ intro,
349
+ history_offset,
350
+ awesome_prompt,
351
+ proxy_path,
352
+ provider,
353
+ quiet=False,
354
+ chat_completion=False,
355
+ ignore_working=False,
356
+ rawdog=False,
357
+ internal_exec=False,
358
+ confirm_script=False,
359
+ interpreter="python",
360
+ *args,
361
+ **kwargs,
362
+ ):
363
+ super().__init__(*args, **kwargs)
364
+ if proxy_path:
365
+ with open(proxy_path) as fh:
366
+ proxies = json.load(fh)
367
+ else:
368
+ proxies = {}
369
+
370
+ try:
371
+ getOr = lambda option, default: option if option else default
372
+
373
+ if rawdog:
374
+
375
+ self.RawDog = RawDog(
376
+ quiet=quiet,
377
+ internal_exec=internal_exec,
378
+ confirm_script=confirm_script,
379
+ interpreter=interpreter,
380
+ prettify=True,
381
+ )
382
+ intro = self.RawDog.intro_prompt
383
+ getpass.getuser = lambda: "RawDog"
384
+
385
+ if provider == "g4fauto":
386
+ from webscout.g4f import TestProviders
387
+
388
+ test = TestProviders(quiet=quiet, timeout=timeout)
389
+ g4fauto = test.best if ignore_working else test.auto
390
+ if isinstance(g4fauto, str):
391
+ provider = "g4fauto+" + g4fauto
392
+ from webscout.g4f import GPT4FREE
393
+
394
+ self.bot = GPT4FREE(
395
+ provider=g4fauto,
396
+ auth=auth,
397
+ max_tokens=max_tokens,
398
+ model=model,
399
+ chat_completion=chat_completion,
400
+ ignore_working=ignore_working,
401
+ timeout=timeout,
402
+ intro=intro,
403
+ filepath=filepath,
404
+ update_file=update_file,
405
+ proxies=proxies,
406
+ history_offset=history_offset,
407
+ act=awesome_prompt,
408
+ )
409
+ else:
410
+ raise Exception(
411
+ "No working g4f provider found. "
412
+ "Consider running 'webscout gpt4free test -y' first"
413
+ )
414
+
415
+ elif provider == "leo":
416
+ from webscout.AI import LEO
417
+
418
+ self.bot = LEO.LEO(
419
+ is_conversation=disable_conversation,
420
+ max_tokens=max_tokens,
421
+ temperature=temperature,
422
+ top_k=top_k,
423
+ top_p=top_p,
424
+ model=getOr(model, LEO.model),
425
+ brave_key=getOr(auth, LEO.key),
426
+ timeout=timeout,
427
+ intro=intro,
428
+ filepath=filepath,
429
+ update_file=update_file,
430
+ proxies=proxies,
431
+ history_offset=history_offset,
432
+ act=awesome_prompt,
433
+ )
434
+
435
+ elif provider == "openai":
436
+ assert auth, (
437
+ "OpenAI's API-key is required. " "Use the flag `--key` or `-k`"
438
+ )
439
+ from webscout.AI import OPENAI
440
+
441
+ self.bot = OPENAI(
442
+ api_key=auth,
443
+ is_conversation=disable_conversation,
444
+ max_tokens=max_tokens,
445
+ temperature=temperature,
446
+ presence_penalty=top_p,
447
+ frequency_penalty=top_k,
448
+ top_p=top_p,
449
+ model=getOr(model, model),
450
+ timeout=timeout,
451
+ intro=intro,
452
+ filepath=filepath,
453
+ update_file=update_file,
454
+ proxies=proxies,
455
+ history_offset=history_offset,
456
+ act=awesome_prompt,
457
+ )
458
+
459
+ elif provider == "opengpt":
460
+ from webscout.AI import OPENGPT
461
+
462
+ self.bot = OPENGPT(
463
+ is_conversation=disable_conversation,
464
+ max_tokens=max_tokens,
465
+ timeout=timeout,
466
+ intro=intro,
467
+ filepath=filepath,
468
+ update_file=update_file,
469
+ proxies=proxies,
470
+ history_offset=history_offset,
471
+ act=awesome_prompt,
472
+ )
473
+ elif provider == "sean":
474
+ from webscout.AI import Sean
475
+
476
+ self.bot = Sean(
477
+ is_conversation=disable_conversation,
478
+ max_tokens=max_tokens,
479
+ timeout=timeout,
480
+ intro=intro,
481
+ filepath=filepath,
482
+ update_file=update_file,
483
+ proxies=proxies,
484
+ history_offset=history_offset,
485
+ act=awesome_prompt,
486
+ )
487
+
488
+ elif provider == "koboldai":
489
+ from webscout.AI import KOBOLDAI
490
+
491
+ self.bot = KOBOLDAI(
492
+ is_conversation=disable_conversation,
493
+ max_tokens=max_tokens,
494
+ temperature=temperature,
495
+ top_p=top_p,
496
+ timeout=timeout,
497
+ intro=intro,
498
+ filepath=filepath,
499
+ update_file=update_file,
500
+ proxies=proxies,
501
+ history_offset=history_offset,
502
+ act=awesome_prompt,
503
+ )
504
+
505
+ elif provider == "gemini":
506
+ from webscout.AI import GEMINI
507
+
508
+ assert auth, (
509
+ "Path to gemini.google.com.cookies.json file is required. "
510
+ "Use the flag `--key` or `-k`"
511
+ )
512
+ self.bot = GEMINI(
513
+ cookie_file=auth,
514
+ proxy=proxies,
515
+ timeout=timeout,
516
+ )
517
+
518
+ elif provider == "phind":
519
+ from webscout.AI import PhindSearch
520
+
521
+ self.bot = PhindSearch(
522
+ is_conversation=disable_conversation,
523
+ max_tokens=max_tokens,
524
+ timeout=timeout,
525
+ intro=intro,
526
+ filepath=filepath,
527
+ update_file=update_file,
528
+ proxies=proxies,
529
+ history_offset=history_offset,
530
+ act=awesome_prompt,
531
+ model=getOr(model, "Phind Model"),
532
+ quiet=quiet,
533
+ )
534
+
535
+ elif provider == "blackboxai":
536
+
537
+ from webscout.AI import BLACKBOXAI
538
+
539
+ self.bot = BLACKBOXAI(
540
+ is_conversation=disable_conversation,
541
+ max_tokens=max_tokens,
542
+ timeout=timeout,
543
+ intro=intro,
544
+ filepath=filepath,
545
+ update_file=update_file,
546
+ proxies=proxies,
547
+ history_offset=history_offset,
548
+ act=awesome_prompt,
549
+ )
550
+
551
+
552
+ elif provider in webscout.gpt4free_providers:
553
+ from webscout.g4f import GPT4FREE
554
+
555
+ self.bot = GPT4FREE(
556
+ provider=provider,
557
+ is_conversation=disable_conversation,
558
+ auth=auth,
559
+ max_tokens=max_tokens,
560
+ model=model,
561
+ chat_completion=chat_completion,
562
+ ignore_working=ignore_working,
563
+ timeout=timeout,
564
+ intro=intro,
565
+ filepath=filepath,
566
+ update_file=update_file,
567
+ proxies=proxies,
568
+ history_offset=history_offset,
569
+ act=awesome_prompt,
570
+ )
571
+
572
+
573
+ elif provider == "perplexity":
574
+ from webscout.AI import PERPLEXITY
575
+
576
+ self.bot = PERPLEXITY(
577
+ is_conversation=disable_conversation,
578
+ max_tokens=max_tokens,
579
+ timeout=timeout,
580
+ intro=intro,
581
+ filepath=filepath,
582
+ update_file=update_file,
583
+ proxies=proxies,
584
+ history_offset=history_offset,
585
+ act=awesome_prompt,
586
+ quiet=quiet,
587
+ )
588
+
589
+ else:
590
+ raise NotImplementedError(
591
+ f"The provider `{provider}` is not yet implemented."
592
+ )
593
+
594
+ except Exception as e:
595
+ logging.error(this.getExc(e))
596
+ click.secho("Quitting", fg="red")
597
+ sys.exit(1)
598
+ self.prettify = True
599
+ self.color = "cyan"
600
+ self.code_theme = "monokai"
601
+ self.quiet = quiet
602
+ self.vertical_overflow = "ellipsis"
603
+ self.disable_stream = False
604
+ self.provider = provider
605
+ self.disable_coloring = False
606
+ self.internal_exec = internal_exec
607
+ self.confirm_script = confirm_script
608
+ self.interpreter = interpreter
609
+ self.rawdog = rawdog
610
+ self.__init_time = time.time()
611
+ self.__start_time = time.time()
612
+ self.__end_time = time.time()
613
+
614
+ @property
615
+ def prompt(self):
616
+ current_time = datetime.datetime.now().strftime("%H:%M:%S")
617
+
618
+ def find_range(start, end, hms: bool = False):
619
+ in_seconds = round(end - start, 1)
620
+ return (
621
+ str(datetime.timedelta(seconds=in_seconds)).split(".")[0].zfill(8)
622
+ if hms
623
+ else in_seconds
624
+ )
625
+ if not self.disable_coloring:
626
+ cmd_prompt = (
627
+ f"╭─[`{Fore.GREEN}{getpass.getuser().capitalize()}@webai]`"
628
+ f"(`{Fore.YELLOW}{self.provider})`"
629
+ f"~[`{Fore.LIGHTWHITE_EX}⏰{Fore.MAGENTA}{current_time}-`"
630
+ f"{Fore.LIGHTWHITE_EX}💻{Fore.BLUE}{find_range(self.__init_time, time.time(), True)}-`"
631
+ f"{Fore.LIGHTWHITE_EX}⚡️{Fore.RED}{find_range(self.__start_time, self.__end_time)}s]`"
632
+ f"\n╰─>"
633
+ )
634
+ whitelist = ["[", "]", "~", "-", "(", ")"]
635
+ for character in whitelist:
636
+ cmd_prompt = cmd_prompt.replace(character + "`", Fore.RESET + character)
637
+ return cmd_prompt
638
+
639
+ else:
640
+ return (
641
+ f"╭─[{getpass.getuser().capitalize()}@webscout]({self.provider})"
642
+ f"~[⏰{current_time}"
643
+ f"-💻{find_range(self.__init_time, time.time(), True)}"
644
+ f"-⚡️{find_range(self.__start_time, self.__end_time)}s]"
645
+ f"~[⏰{current_time}"
646
+ f"-💻{find_range(self.__init_time, time.time(), True)}"
647
+ f"-⚡️{find_range(self.__start_time, self.__end_time)}s]"
648
+ "\n╰─>"
649
+ )
650
+
651
+ def output_bond(
652
+ self,
653
+ title: str,
654
+ text: str,
655
+ color: str = "cyan",
656
+ frame: bool = True,
657
+ is_json: bool = False,
658
+ ):
659
+ """Print prettified output
660
+
661
+ Args:
662
+ title (str): Title
663
+ text (str): Info to be printed
664
+ color (str, optional): Output color. Defaults to "cyan".
665
+ frame (bool, optional): Add frame. Defaults to True.
666
+ """
667
+ if is_json:
668
+ text = f"""
669
+ ```json
670
+ {json.dumps(text,indent=4)}
671
+ ```
672
+ """
673
+ rich.print(
674
+ Panel(
675
+ Markdown(text, code_theme=self.code_theme),
676
+ title=title.title(),
677
+ style=Style(
678
+ color=color,
679
+ frame=frame,
680
+ ),
681
+ ),
682
+ )
683
+ if is_json and click.confirm("Do you wish to save this"):
684
+ default_path = title + ".json"
685
+ save_to = click.prompt(
686
+ "Enter path to save to", default=default_path, type=click.STRING
687
+ )
688
+ with open(save_to, "a") as fh:
689
+ json.dump(text, fh, indent=4)
690
+ click.secho(f"Successfuly saved to `{save_to}`", fg="green")
691
+
692
+ def do_h(self, line):
693
+ """Show help info in tabular form"""
694
+ table = Table(
695
+ title="Help info",
696
+ show_lines=True,
697
+ )
698
+ table.add_column("No.", style="white", justify="center")
699
+ table.add_column("Command", style="yellow", justify="left")
700
+ table.add_column("Function", style="cyan")
701
+ command_methods = [
702
+ getattr(self, method)
703
+ for method in dir(self)
704
+ if callable(getattr(self, method)) and method.startswith("do_")
705
+ ]
706
+ command_methods.append(self.default)
707
+ command_methods.reverse()
708
+ for no, method in enumerate(command_methods):
709
+ table.add_row(
710
+ str(no + 1),
711
+ method.__name__[3:] if not method == self.default else method.__name__,
712
+ method.__doc__,
713
+ )
714
+ Console().print(table)
715
+
716
+ @busy_bar.run("Settings saved")
717
+ def do_settings(self, line):
718
+ """Configure settings"""
719
+ self.prettify = click.confirm(
720
+ "\nPrettify markdown response", default=self.prettify
721
+ )
722
+ busy_bar.spin_index = click.prompt(
723
+ "Spin bar index [0: None, 1:/, 2:■█■■■, 3:⣻]",
724
+ default=busy_bar.spin_index,
725
+ type=click.IntRange(0, 3),
726
+ )
727
+ self.color = click.prompt(
728
+ "Response stdout font color", default=self.color or "white"
729
+ )
730
+ self.code_theme = Prompt.ask(
731
+ "Enter code_theme", choices=this.rich_code_themes, default=self.code_theme
732
+ )
733
+ self.vertical_overflow = Prompt.ask(
734
+ "\nVertical overflow behaviour",
735
+ choices=["ellipsis", "visible", "crop"],
736
+ default=self.vertical_overflow,
737
+ )
738
+ self.bot.max_tokens_to_sample = click.prompt(
739
+ "\nMaximum tokens to sample",
740
+ type=click.INT,
741
+ default=self.bot.max_tokens_to_sample,
742
+ )
743
+ self.bot.temperature = click.prompt(
744
+ "Temperature", type=click.FLOAT, default=self.bot.temperature
745
+ )
746
+ self.bot.top_k = click.prompt(
747
+ "Chance of topic being repeated, top_k",
748
+ type=click.FLOAT,
749
+ default=self.bot.top_k,
750
+ )
751
+ self.bot.top_p = click.prompt(
752
+ "Sampling threshold during inference time, top_p",
753
+ type=click.FLOAT,
754
+ default=self.bot.top_p,
755
+ )
756
+ self.bot.model = click.prompt(
757
+ "Model name", type=click.STRING, default=self.bot.model
758
+ )
759
+
760
+ @busy_bar.run(help="System error")
761
+ def do_copy_this(self, line):
762
+ """Copy last response
763
+ Usage:
764
+ copy_this:
765
+ text-copied = {whole last-response}
766
+ copy_this code:
767
+ text-copied = {All codes in last response}
768
+ """
769
+ if self.bot.last_response:
770
+ global last_response
771
+ last_response = self.bot.get_message(self.bot.last_response)
772
+ if not "code" in line:
773
+ clipman.set(last_response)
774
+ click.secho("Last response copied successfully!", fg="cyan")
775
+ return
776
+
777
+ # Copies just code
778
+ sanitized_codes = []
779
+ code_blocks = re.findall(r"```.*?```", last_response, re.DOTALL)
780
+ for code_block in code_blocks:
781
+ new_code_block = re.sub(
782
+ "^```.*$", "", code_block.strip(), flags=re.MULTILINE
783
+ )
784
+ if bool(new_code_block.strip()):
785
+ sanitized_codes.append(new_code_block)
786
+ if sanitized_codes:
787
+ if len(sanitized_codes) > 1:
788
+ if not click.confirm("Do you wish to copy all codes"):
789
+ for index, code in enumerate(sanitized_codes):
790
+ rich.print(
791
+ Panel(
792
+ Markdown(
793
+ code_blocks[index], code_theme=self.code_theme
794
+ ),
795
+ title=f"Index : {index}",
796
+ title_align="left",
797
+ )
798
+ )
799
+
800
+ clipman.set(
801
+ sanitized_codes[
802
+ click.prompt(
803
+ "Enter code index",
804
+ type=click.IntRange(0, len(sanitized_codes) - 1),
805
+ )
806
+ ]
807
+ )
808
+ click.secho("Code copied successfully", fg="cyan")
809
+ else:
810
+ clipman.set("\n\n".join(sanitized_codes))
811
+ click.secho(
812
+ f"All {len(sanitized_codes)} codes copied successfully!",
813
+ fg="cyan",
814
+ )
815
+ else:
816
+ clipman.set(sanitized_codes[0])
817
+ click.secho("Code copied successfully!", fg="cyan")
818
+ else:
819
+ click.secho("No code found in the last response!", fg="red")
820
+ else:
821
+ click.secho("Chat with AI first.", fg="yellow")
822
+
823
+ @busy_bar.run()
824
+ def do_with_copied(self, line):
825
+ """Attach last copied text to the prompt
826
+ Usage:
827
+ from_copied:
828
+ prompt = {text-copied}
829
+ from_copied Debug this code:
830
+ prompt = Debug this code {newline} {text-copied}
831
+ """
832
+ issued_prompt = (
833
+ f"{line}\n{clipman.get()}" if bool(line.strip()) else clipman.get()
834
+ )
835
+ click.secho(issued_prompt, fg="yellow")
836
+ if click.confirm("Do you wish to proceed"):
837
+ self.default(issued_prompt)
838
+
839
+ @busy_bar.run()
840
+ def do_code(self, line):
841
+ """Enhance prompt for code generation
842
+ usage :
843
+ code <Code description>
844
+ """
845
+ self.default(Optimizers.code(line))
846
+
847
+ @busy_bar.run()
848
+ def do_shell(self, line):
849
+ """Enhance prompt for system command (shell) generation
850
+ Usage:
851
+ shell <Action to be accomplished>
852
+ """
853
+ self.default(Optimizers.shell_command(line))
854
+ if click.confirm("Do you wish to run the command(s) generated in your system"):
855
+ self.do_sys(self.bot.get_message(self.bot.last_response))
856
+
857
+ @busy_bar.run("While changing directory")
858
+ def do_cd(self, line):
859
+ """Change directory
860
+ Usage :
861
+ cd <path-to-directory>
862
+ """
863
+ assert line, "File path is required"
864
+ os.chdir(line)
865
+
866
+ def do_clear(self, line):
867
+ """Clear console"""
868
+ sys.stdout.write("\u001b[2J\u001b[H")
869
+ sys.stdout.flush()
870
+
871
+ @busy_bar.run("While handling history")
872
+ def do_history(self, line):
873
+ """Show current conversation history"""
874
+ history = self.bot.conversation.chat_history
875
+ formatted_history = re.sub(
876
+ "\nLLM :",
877
+ "\n\n**LLM** :",
878
+ re.sub("\nUser :", "\n\n**User** :", history),
879
+ )
880
+ self.output_bond("Chat History", formatted_history, self.color)
881
+ if click.confirm("Do you wish to save this chat"):
882
+ save_to = click.prompt(
883
+ "Enter path/file-name", default="llama-conversation.txt"
884
+ )
885
+ with open(save_to, "a") as fh:
886
+ fh.write(history)
887
+ click.secho(f"Conversation saved successfully to '{save_to}'", fg="cyan")
888
+
889
+ @busy_bar.run("while resetting conversation")
890
+ def do_reset(self, line):
891
+ """Start new conversation thread"""
892
+ self.bot.conversation.chat_history = click.prompt(
893
+ "Introductory prompt", default=self.bot.conversation.intro
894
+ )
895
+ if hasattr(self.bot, "reset"):
896
+ self.bot.reset()
897
+ click.secho("Conversation reset successfully. New one created.", fg="cyan")
898
+
899
+ @busy_bar.run("while loading conversation")
900
+ def do_load(self, line):
901
+ """Load conversation history from file"""
902
+ history_file = click.prompt("Enter path to history path", default=line)
903
+ if not os.path.isfile(history_file):
904
+ click.secho(f"Path `{history_file}` does not exist!", fg="red")
905
+ return
906
+ with open(history_file) as fh:
907
+ self.bot.conversation.chat_history = fh.read()
908
+ click.secho("Conversation loaded successfully.", fg="cyan")
909
+
910
+ def do_last_response(self, line):
911
+ """Show whole last response in json format"""
912
+ self.output_bond(
913
+ "Last Response",
914
+ self.bot.last_response,
915
+ is_json=True,
916
+ )
917
+
918
+ @busy_bar.run()
919
+ def do_exec(self, line):
920
+ """Exec python code in last response with RawDog"""
921
+ last_response = self.bot.get_message(self.bot.last_response)
922
+ assert last_response, "Last response is null"
923
+ assert "```python" in last_response, "Last response has no python code"
924
+ if self.rawdog:
925
+ self.RawDog.main(last_response)
926
+ else:
927
+ rawdog = RawDog(
928
+ quiet=self.quiet,
929
+ internal_exec=self.internal_exec,
930
+ confirm_script=self.confirm_script,
931
+ interpreter=self.interpreter,
932
+ prettify=self.prettify,
933
+ )
934
+ rawdog.main(last_response)
935
+
936
+ @busy_bar.run()
937
+ def do_rawdog(self, line):
938
+ """Repeat executing last rawdog's python code"""
939
+ assert self.rawdog, "Session not in rawdog mode. Restart with --rawdog"
940
+ self.default(self.bot.get_message(self.bot.last_response))
941
+
942
+ @busy_bar.run()
943
+ def default(self, line, exit_on_error: bool = False, normal_stdout: bool = False):
944
+ """Chat with LLM"""
945
+ if not bool(line):
946
+ return
947
+ if line.startswith("./"):
948
+ os.system(line[2:])
949
+
950
+ elif self.rawdog:
951
+ self.__start_time = time.time()
952
+ busy_bar.start_spinning()
953
+ ai_response = self.bot.chat(line, stream=False)
954
+ busy_bar.stop_spinning()
955
+ is_feedback = self.RawDog.main(ai_response)
956
+ if is_feedback:
957
+ return self.default(is_feedback)
958
+ self.__end_time = time.time()
959
+
960
+ else:
961
+ self.__start_time = time.time()
962
+ try:
963
+
964
+ def generate_response():
965
+ # Ensure response is yielded
966
+ def for_stream():
967
+ return self.bot.chat(line, stream=True)
968
+
969
+ def for_non_stream():
970
+ yield self.bot.chat(line, stream=False)
971
+
972
+ return for_non_stream() if self.disable_stream else for_stream()
973
+
974
+ busy_bar.start_spinning()
975
+ generated_response = generate_response()
976
+
977
+ if normal_stdout or not self.prettify and not self.disable_stream:
978
+ cached_response: str = ""
979
+ if not normal_stdout:
980
+ busy_bar.stop_spinning()
981
+ for response in generated_response:
982
+ offset = len(cached_response)
983
+ print(response[offset:], end="")
984
+ cached_response = response
985
+ if not normal_stdout:
986
+ print("")
987
+ return
988
+
989
+ if self.quiet:
990
+ busy_bar.stop_spinning()
991
+ console_ = Console()
992
+ with Live(
993
+ console=console_,
994
+ refresh_per_second=16,
995
+ vertical_overflow=self.vertical_overflow,
996
+ ) as live:
997
+ for response in generated_response:
998
+ live.update(
999
+ Markdown(response, code_theme=self.code_theme)
1000
+ if self.prettify
1001
+ else response
1002
+ )
1003
+ else:
1004
+ busy_bar.stop_spinning()
1005
+ this.stream_output(
1006
+ generated_response,
1007
+ title="AI Response",
1008
+ is_markdown=self.prettify,
1009
+ style=Style(
1010
+ color=self.color,
1011
+ ),
1012
+ code_theme=self.code_theme,
1013
+ vertical_overflow=self.vertical_overflow,
1014
+ )
1015
+ except (KeyboardInterrupt, EOFError):
1016
+ busy_bar.stop_spinning()
1017
+ print("")
1018
+ return False # Exit cmd
1019
+
1020
+ except Exception as e:
1021
+ # logging.exception(e)
1022
+ busy_bar.stop_spinning()
1023
+ logging.error(this.getExc(e))
1024
+ if exit_on_error:
1025
+ sys.exit(1)
1026
+ finally:
1027
+ self.__end_time = time.time()
1028
+
1029
+ def do_sys(self, line):
1030
+ """Execute system commands
1031
+ shortcut [./<command>]
1032
+ Usage:
1033
+ sys <System command>
1034
+ or
1035
+ ./<System command>
1036
+ """
1037
+ os.system(line)
1038
+
1039
+ def do_exit(self, line):
1040
+ """Quit this program"""
1041
+ if click.confirm("Are you sure to exit"):
1042
+ click.secho("Okay Goodbye!", fg="yellow")
1043
+ return True
1044
+
1045
+
1046
+ class EntryGroup:
1047
+ """Entry commands"""
1048
+
1049
+ # @staticmethod
1050
+ @click.group()
1051
+ @click.version_option(
1052
+ webscout.__version__, "-v", "--version", package_name="Webscout"
1053
+ )
1054
+ @click.help_option("-h", "--help")
1055
+ def webai_():
1056
+ pass
1057
+
1058
+ @staticmethod
1059
+ @webai_.group()
1060
+ @click.help_option("-h", "--help")
1061
+ def utils():
1062
+ """Utility endpoint for webscout"""
1063
+ pass
1064
+
1065
+ @staticmethod
1066
+ @webai_.group()
1067
+ @click.help_option("-h", "--help")
1068
+ def gpt4free():
1069
+ """Discover gpt4free models, providers etc"""
1070
+ pass
1071
+
1072
+ @staticmethod
1073
+ @webai_.group()
1074
+ @click.help_option("-h", "--help")
1075
+ def awesome():
1076
+ """Perform CRUD operations on awesome-prompts"""
1077
+ pass
1078
+
1079
+
1080
+
1081
+ class Chatwebai:
1082
+ """webai command"""
1083
+
1084
+ @staticmethod
1085
+ @click.command(context_settings=this.context_settings)
1086
+ @click.option(
1087
+ "-m",
1088
+ "--model",
1089
+ help="Model name for text-generation", # default="llama-2-13b-chat"
1090
+ )
1091
+ @click.option(
1092
+ "-t",
1093
+ "--temperature",
1094
+ help="Charge of the generated text's randomness",
1095
+ type=click.FloatRange(0, 1),
1096
+ default=0.2,
1097
+ )
1098
+ @click.option(
1099
+ "-mt",
1100
+ "--max-tokens",
1101
+ help="Maximum number of tokens to be generated upon completion",
1102
+ type=click.INT,
1103
+ default=600,
1104
+ )
1105
+ @click.option(
1106
+ "-tp",
1107
+ "--top-p",
1108
+ help="Sampling threshold during inference time",
1109
+ type=click.FLOAT,
1110
+ default=0.999,
1111
+ )
1112
+ @click.option(
1113
+ "-tk",
1114
+ "--top-k",
1115
+ help="Chance of topic being repeated",
1116
+ type=click.FLOAT,
1117
+ default=0,
1118
+ )
1119
+ @click.option(
1120
+ "-k",
1121
+ "--key",
1122
+ help="LLM API access key or auth value or path to LLM with provider.",
1123
+ )
1124
+ @click.option(
1125
+ "-ct",
1126
+ "--code-theme",
1127
+ help="Theme for displaying codes in response",
1128
+ type=click.Choice(this.rich_code_themes),
1129
+ default="monokai",
1130
+ )
1131
+ @click.option(
1132
+ "-bi",
1133
+ "--busy-bar-index",
1134
+ help="Index of busy bar icon : [0: None, 1:/, 2:■█■■■, 3:⣻]",
1135
+ type=click.IntRange(0, 3),
1136
+ default=3,
1137
+ )
1138
+ @click.option("-fc", "--font-color", help="Stdout font color")
1139
+ @click.option(
1140
+ "-to", "--timeout", help="Http requesting timeout", type=click.INT, default=30
1141
+ )
1142
+ @click.argument("prompt", required=False)
1143
+ @click.option(
1144
+ "--prettify/--raw",
1145
+ help="Flag for prettifying markdowned response",
1146
+ default=True,
1147
+ )
1148
+ @click.option(
1149
+ "-dc",
1150
+ "--disable-conversation",
1151
+ is_flag=True,
1152
+ default=True, # is_conversation = True
1153
+ help="Disable chatting conversationally (Stable)",
1154
+ )
1155
+ @click.option(
1156
+ "-fp",
1157
+ "--filepath",
1158
+ type=click.Path(),
1159
+ default=os.path.join(default_path, "chat-history.txt"),
1160
+ help="Path to chat history - new will be created incase doesn't exist",
1161
+ )
1162
+ @click.option(
1163
+ "--update-file/--retain-file",
1164
+ help="Controls updating chat history in file",
1165
+ default=True,
1166
+ )
1167
+ @click.option(
1168
+ "-i",
1169
+ "--intro",
1170
+ help="Conversation introductory prompt",
1171
+ )
1172
+ @click.option(
1173
+ "-ho",
1174
+ "--history-offset",
1175
+ help="Limit conversation history to this number of last texts",
1176
+ type=click.IntRange(100, 16000),
1177
+ default=10250,
1178
+ )
1179
+ @click.option(
1180
+ "-ap",
1181
+ "--awesome-prompt",
1182
+ default="0",
1183
+ callback=lambda ctx, param, value: (
1184
+ int(value) if str(value).isdigit() else value
1185
+ ),
1186
+ help="Awesome prompt key or index. Alt. to intro",
1187
+ )
1188
+ @click.option(
1189
+ "-pp",
1190
+ "--proxy-path",
1191
+ type=click.Path(exists=True),
1192
+ help="Path to .json file containing proxies",
1193
+ )
1194
+ @click.option(
1195
+ "-p",
1196
+ "--provider",
1197
+ type=click.Choice(webscout.available_providers),
1198
+ default=this.default_provider,
1199
+ help="Name of LLM provider.",
1200
+ metavar=(
1201
+ f"[{'|'.join(webscout.webai)}] etc, "
1202
+ "run 'webscout gpt4free list providers -w' to "
1203
+ "view more providers and 'webscout gpt4free test -y' "
1204
+ "for advanced g4f providers test"
1205
+ ),
1206
+ )
1207
+ @click.option(
1208
+ "-vo",
1209
+ "--vertical-overflow",
1210
+ help="Vertical overflow behaviour on content display",
1211
+ type=click.Choice(["visible", "crop", "ellipsis"]),
1212
+ default="ellipsis",
1213
+ )
1214
+ @click.option(
1215
+ "-w",
1216
+ "--whole",
1217
+ is_flag=True,
1218
+ default=False,
1219
+ help="Disable streaming response",
1220
+ )
1221
+ @click.option(
1222
+ "-q",
1223
+ "--quiet",
1224
+ is_flag=True,
1225
+ help="Flag for controlling response-framing and response verbosity",
1226
+ default=False,
1227
+ )
1228
+ @click.option(
1229
+ "-n",
1230
+ "--new",
1231
+ help="Overwrite the filepath contents",
1232
+ is_flag=True,
1233
+ )
1234
+ @click.option(
1235
+ "-wc",
1236
+ "--with-copied",
1237
+ is_flag=True,
1238
+ help="Postfix prompt with last copied text",
1239
+ )
1240
+ @click.option(
1241
+ "-nc", "--no-coloring", is_flag=True, help="Disable intro prompt font-coloring"
1242
+ )
1243
+ @click.option(
1244
+ "-cc",
1245
+ "--chat-completion",
1246
+ is_flag=True,
1247
+ help="Provide native context for gpt4free providers",
1248
+ )
1249
+ @click.option(
1250
+ "-iw",
1251
+ "--ignore-working",
1252
+ is_flag=True,
1253
+ help="Ignore working status of the provider",
1254
+ )
1255
+ @click.option(
1256
+ "-rd",
1257
+ "--rawdog",
1258
+ is_flag=True,
1259
+ help="Generate and auto-execute Python scripts - (experimental)",
1260
+ )
1261
+ @click.option(
1262
+ "-ix",
1263
+ "--internal-exec",
1264
+ is_flag=True,
1265
+ help="RawDog : Execute scripts with exec function instead of out-of-script interpreter",
1266
+ )
1267
+ @click.option(
1268
+ "-cs",
1269
+ "--confirm-script",
1270
+ is_flag=True,
1271
+ help="RawDog : Give consent to generated scripts prior to execution",
1272
+ )
1273
+ @click.option(
1274
+ "-int",
1275
+ "--interpreter",
1276
+ default="python",
1277
+ help="RawDog : Python's interpreter name",
1278
+ )
1279
+ @click.help_option("-h", "--help")
1280
+ def webai(
1281
+ model,
1282
+ temperature,
1283
+ max_tokens,
1284
+ top_p,
1285
+ top_k,
1286
+ key,
1287
+ code_theme,
1288
+ busy_bar_index,
1289
+ font_color,
1290
+ timeout,
1291
+ prompt,
1292
+ prettify,
1293
+ disable_conversation,
1294
+ filepath,
1295
+ update_file,
1296
+ intro,
1297
+ history_offset,
1298
+ awesome_prompt,
1299
+ proxy_path,
1300
+ provider,
1301
+ vertical_overflow,
1302
+ whole,
1303
+ quiet,
1304
+ new,
1305
+ with_copied,
1306
+ no_coloring,
1307
+ chat_completion,
1308
+ ignore_working,
1309
+ rawdog,
1310
+ internal_exec,
1311
+ confirm_script,
1312
+ interpreter,
1313
+ ):
1314
+ """Chat with AI webaily (Default)"""
1315
+ this.clear_history_file(filepath, new)
1316
+ bot = Main(
1317
+ max_tokens,
1318
+ temperature,
1319
+ top_k,
1320
+ top_p,
1321
+ model,
1322
+ key,
1323
+ timeout,
1324
+ disable_conversation,
1325
+ filepath,
1326
+ update_file,
1327
+ intro,
1328
+ history_offset,
1329
+ awesome_prompt,
1330
+ proxy_path,
1331
+ provider,
1332
+ quiet,
1333
+ chat_completion,
1334
+ ignore_working,
1335
+ rawdog=rawdog,
1336
+ internal_exec=internal_exec,
1337
+ confirm_script=confirm_script,
1338
+ interpreter=interpreter,
1339
+ )
1340
+ busy_bar.spin_index = busy_bar_index
1341
+ bot.code_theme = code_theme
1342
+ bot.color = font_color
1343
+ bot.disable_coloring = no_coloring
1344
+ bot.prettify = prettify
1345
+ bot.vertical_overflow = vertical_overflow
1346
+ bot.disable_stream = whole
1347
+ if prompt:
1348
+ if with_copied:
1349
+ prompt = prompt + "\n" + clipman.get()
1350
+ bot.default(prompt)
1351
+ bot.cmdloop()
1352
+
1353
+
1354
+ class ChatGenerate:
1355
+ """Generate command"""
1356
+
1357
+ @staticmethod
1358
+ @click.command(context_settings=this.context_settings)
1359
+ @click.option(
1360
+ "-m",
1361
+ "--model",
1362
+ help="Model name for text-generation",
1363
+ )
1364
+ @click.option(
1365
+ "-t",
1366
+ "--temperature",
1367
+ help="Charge of the generated text's randomness",
1368
+ type=click.FloatRange(0, 1),
1369
+ default=0.2,
1370
+ )
1371
+ @click.option(
1372
+ "-mt",
1373
+ "--max-tokens",
1374
+ help="Maximum number of tokens to be generated upon completion",
1375
+ type=click.INT,
1376
+ default=600,
1377
+ )
1378
+ @click.option(
1379
+ "-tp",
1380
+ "--top-p",
1381
+ help="Sampling threshold during inference time",
1382
+ type=click.FLOAT,
1383
+ default=0.999,
1384
+ )
1385
+ @click.option(
1386
+ "-tk",
1387
+ "--top-k",
1388
+ help="Chance of topic being repeated",
1389
+ type=click.FLOAT,
1390
+ default=0,
1391
+ )
1392
+ @click.option(
1393
+ "-k",
1394
+ "--key",
1395
+ help="LLM API access key or auth value or path to LLM with provider.",
1396
+ )
1397
+ @click.option(
1398
+ "-ct",
1399
+ "--code-theme",
1400
+ help="Theme for displaying codes in response",
1401
+ type=click.Choice(this.rich_code_themes),
1402
+ default="monokai",
1403
+ )
1404
+ @click.option(
1405
+ "-bi",
1406
+ "--busy-bar-index",
1407
+ help="Index of busy bar icon : [0: None, 1:/, 2:■█■■■, 3:⣻]",
1408
+ type=click.IntRange(0, 3),
1409
+ default=3,
1410
+ )
1411
+ @click.option(
1412
+ "-fc",
1413
+ "--font-color",
1414
+ help="Stdout font color",
1415
+ )
1416
+ @click.option(
1417
+ "-to", "--timeout", help="Http requesting timeout", type=click.INT, default=30
1418
+ )
1419
+ @click.argument("prompt", required=False)
1420
+ @click.option(
1421
+ "--prettify/--raw",
1422
+ help="Flag for prettifying markdowned response",
1423
+ default=True,
1424
+ )
1425
+ @click.option(
1426
+ "-w",
1427
+ "--whole",
1428
+ is_flag=True,
1429
+ default=False,
1430
+ help="Disable streaming response",
1431
+ )
1432
+ @click.option(
1433
+ "-c",
1434
+ "--code",
1435
+ is_flag=True,
1436
+ default=False,
1437
+ help="Optimize prompt for code generation",
1438
+ )
1439
+ @click.option(
1440
+ "-s",
1441
+ "--shell",
1442
+ is_flag=True,
1443
+ default=False,
1444
+ help="Optimize prompt for shell command generation",
1445
+ )
1446
+ @click.option(
1447
+ "-dc",
1448
+ "--disable-conversation",
1449
+ is_flag=True,
1450
+ default=True, # is_conversation = True
1451
+ help="Disable chatting conversationally (Stable)",
1452
+ )
1453
+ @click.option(
1454
+ "-fp",
1455
+ "--filepath",
1456
+ type=click.Path(),
1457
+ default=os.path.join(default_path, "chat-history.txt"),
1458
+ help="Path to chat history - new will be created incase doesn't exist",
1459
+ )
1460
+ @click.option(
1461
+ "--update-file/--retain-file",
1462
+ help="Controls updating chat history in file",
1463
+ default=True,
1464
+ )
1465
+ @click.option(
1466
+ "-i",
1467
+ "--intro",
1468
+ help="Conversation introductory prompt",
1469
+ )
1470
+ @click.option(
1471
+ "-ho",
1472
+ "--history-offset",
1473
+ help="Limit conversation history to this number of last texts",
1474
+ type=click.IntRange(100, 16000),
1475
+ default=10250,
1476
+ )
1477
+ @click.option(
1478
+ "-ap",
1479
+ "--awesome-prompt",
1480
+ default="0",
1481
+ callback=lambda ctx, param, value: (
1482
+ int(value) if str(value).isdigit() else value
1483
+ ),
1484
+ help="Awesome prompt key or index. Alt. to intro",
1485
+ )
1486
+ @click.option(
1487
+ "-pp",
1488
+ "--proxy-path",
1489
+ type=click.Path(exists=True),
1490
+ help="Path to .json file containing proxies",
1491
+ )
1492
+ @click.option(
1493
+ "-p",
1494
+ "--provider",
1495
+ type=click.Choice(webscout.available_providers),
1496
+ default=this.default_provider,
1497
+ help="Name of LLM provider.",
1498
+ metavar=(
1499
+ f"[{'|'.join(webscout.webai)}] etc, "
1500
+ "run 'webscout gpt4free list providers -w' to "
1501
+ "view more providers and 'webscout gpt4free test -y' "
1502
+ "for advanced g4f providers test"
1503
+ ),
1504
+ )
1505
+ @click.option(
1506
+ "-vo",
1507
+ "--vertical-overflow",
1508
+ help="Vertical overflow behaviour on content display",
1509
+ type=click.Choice(["visible", "crop", "ellipsis"]),
1510
+ default="ellipsis",
1511
+ )
1512
+ @click.option(
1513
+ "-q",
1514
+ "--quiet",
1515
+ is_flag=True,
1516
+ help="Flag for controlling response-framing and response verbosity",
1517
+ default=False,
1518
+ )
1519
+ @click.option(
1520
+ "-n",
1521
+ "--new",
1522
+ help="Override the filepath contents",
1523
+ is_flag=True,
1524
+ )
1525
+ @click.option(
1526
+ "-wc",
1527
+ "--with-copied",
1528
+ is_flag=True,
1529
+ help="Postfix prompt with last copied text",
1530
+ )
1531
+ @click.option(
1532
+ "-iw",
1533
+ "--ignore-working",
1534
+ is_flag=True,
1535
+ help="Ignore working status of the provider",
1536
+ )
1537
+ @click.option(
1538
+ "-rd",
1539
+ "--rawdog",
1540
+ is_flag=True,
1541
+ help="Generate and auto-execute Python scripts - (experimental)",
1542
+ )
1543
+ @click.option(
1544
+ "-ix",
1545
+ "--internal-exec",
1546
+ is_flag=True,
1547
+ help="RawDog : Execute scripts with exec function instead of out-of-script interpreter",
1548
+ )
1549
+ @click.option(
1550
+ "-cs",
1551
+ "--confirm-script",
1552
+ is_flag=True,
1553
+ help="RawDog : Give consent to generated scripts prior to execution",
1554
+ )
1555
+ @click.option(
1556
+ "-int",
1557
+ "--interpreter",
1558
+ default="python",
1559
+ help="RawDog : Python's interpreter name",
1560
+ )
1561
+ @click.help_option("-h", "--help")
1562
+ def generate(
1563
+ model,
1564
+ temperature,
1565
+ max_tokens,
1566
+ top_p,
1567
+ top_k,
1568
+ key,
1569
+ code_theme,
1570
+ busy_bar_index,
1571
+ font_color,
1572
+ timeout,
1573
+ prompt,
1574
+ prettify,
1575
+ whole,
1576
+ code,
1577
+ shell,
1578
+ disable_conversation,
1579
+ filepath,
1580
+ update_file,
1581
+ intro,
1582
+ history_offset,
1583
+ awesome_prompt,
1584
+ proxy_path,
1585
+ provider,
1586
+ vertical_overflow,
1587
+ quiet,
1588
+ new,
1589
+ with_copied,
1590
+ ignore_working,
1591
+ rawdog,
1592
+ internal_exec,
1593
+ confirm_script,
1594
+ interpreter,
1595
+ ):
1596
+ """Generate a quick response with AI"""
1597
+ this.clear_history_file(filepath, new)
1598
+ bot = Main(
1599
+ max_tokens,
1600
+ temperature,
1601
+ top_k,
1602
+ top_p,
1603
+ model,
1604
+ key,
1605
+ timeout,
1606
+ disable_conversation,
1607
+ filepath,
1608
+ update_file,
1609
+ intro,
1610
+ history_offset,
1611
+ awesome_prompt,
1612
+ proxy_path,
1613
+ provider,
1614
+ quiet,
1615
+ ignore_working=ignore_working,
1616
+ rawdog=rawdog,
1617
+ internal_exec=internal_exec,
1618
+ confirm_script=confirm_script,
1619
+ interpreter=interpreter,
1620
+ )
1621
+ prompt = prompt if prompt else ""
1622
+ copied_placeholder = "{{copied}}"
1623
+ stream_placeholder = "{{stream}}"
1624
+
1625
+ if with_copied or copied_placeholder in prompt:
1626
+ last_copied_text = clipman.get()
1627
+ assert last_copied_text, "No copied text found, issue prompt"
1628
+
1629
+ if copied_placeholder in prompt:
1630
+ prompt = prompt.replace(copied_placeholder, last_copied_text)
1631
+
1632
+ else:
1633
+ sep = "\n" if prompt else ""
1634
+ prompt = prompt + sep + last_copied_text
1635
+
1636
+ if not prompt and sys.stdin.isatty(): # No prompt issued and no piped input
1637
+ help_info = (
1638
+ "Usage: webscout generate [OPTIONS] PROMPT\n"
1639
+ "Try 'webscout generate --help' for help.\n"
1640
+ "Error: Missing argument 'PROMPT'."
1641
+ )
1642
+ click.secho(
1643
+ help_info
1644
+ ) # Let's try to mimic the click's missing argument help info
1645
+ sys.exit(1)
1646
+
1647
+ if not sys.stdin.isatty(): # Piped input detected - True
1648
+ # Let's try to read piped input
1649
+ stream_text = click.get_text_stream("stdin").read()
1650
+ if stream_placeholder in prompt:
1651
+ prompt = prompt.replace(stream_placeholder, stream_text)
1652
+ else:
1653
+ prompt = prompt + "\n" + stream_text if prompt else stream_text
1654
+
1655
+ assert stream_placeholder not in prompt, (
1656
+ "No piped input detected ~ " + stream_placeholder
1657
+ )
1658
+ assert copied_placeholder not in prompt, (
1659
+ "No copied text found ~ " + copied_placeholder
1660
+ )
1661
+
1662
+ prompt = Optimizers.code(prompt) if code else prompt
1663
+ prompt = Optimizers.shell_command(prompt) if shell else prompt
1664
+ busy_bar.spin_index = (
1665
+ 0 if any([quiet, sys.stdout.isatty() == False]) else busy_bar_index
1666
+ )
1667
+ bot.code_theme = code_theme
1668
+ bot.color = font_color
1669
+ bot.prettify = prettify
1670
+ bot.vertical_overflow = vertical_overflow
1671
+ bot.disable_stream = whole
1672
+ bot.default(prompt, True, normal_stdout=(sys.stdout.isatty() == False))
1673
+
1674
+
1675
+ class Awesome:
1676
+ """Awesome commands"""
1677
+
1678
+ @staticmethod
1679
+ @click.command(context_settings=this.context_settings)
1680
+ @click.option(
1681
+ "-r",
1682
+ "--remote",
1683
+ help="Remote source to update from",
1684
+ default=AwesomePrompts.awesome_prompt_url,
1685
+ )
1686
+ @click.option(
1687
+ "-o",
1688
+ "--output",
1689
+ help="Path to save the prompts",
1690
+ default=AwesomePrompts.awesome_prompt_path,
1691
+ )
1692
+ @click.option(
1693
+ "-n", "--new", is_flag=True, help="Override the existing contents in path"
1694
+ )
1695
+ @click.help_option("-h", "--help")
1696
+ @this.handle_exception
1697
+ def update(remote, output, new):
1698
+ """Update awesome-prompts from remote source."""
1699
+ AwesomePrompts.awesome_prompt_url = remote
1700
+ AwesomePrompts.awesome_prompt_path = output
1701
+ AwesomePrompts().update_prompts_from_online(new)
1702
+ click.secho(
1703
+ f"Prompts saved to - '{AwesomePrompts.awesome_prompt_path}'", fg="cyan"
1704
+ )
1705
+
1706
+ @staticmethod
1707
+ @click.command(context_settings=this.context_settings)
1708
+ @click.argument(
1709
+ "key",
1710
+ required=True,
1711
+ type=click.STRING,
1712
+ )
1713
+ @click.option(
1714
+ "-d", "--default", help="Return this value if not found", default=None
1715
+ )
1716
+ @click.option(
1717
+ "-c",
1718
+ "--case-sensitive",
1719
+ default=True,
1720
+ flag_value=False,
1721
+ help="Perform case-sensitive search",
1722
+ )
1723
+ @click.option(
1724
+ "-f",
1725
+ "--file",
1726
+ type=click.Path(exists=True),
1727
+ help="Path to existing prompts",
1728
+ default=AwesomePrompts.awesome_prompt_path,
1729
+ )
1730
+ @click.help_option("-h", "--help")
1731
+ @this.handle_exception
1732
+ def search(
1733
+ key,
1734
+ default,
1735
+ case_sensitive,
1736
+ file,
1737
+ ):
1738
+ """Search for a particular awesome-prompt by key or index"""
1739
+ AwesomePrompts.awesome_prompt_path = file
1740
+ resp = AwesomePrompts().get_act(
1741
+ key,
1742
+ default=default,
1743
+ case_insensitive=case_sensitive,
1744
+ )
1745
+ if resp:
1746
+ click.secho(resp)
1747
+ return resp != default
1748
+
1749
+ @staticmethod
1750
+ @click.command(context_settings=this.context_settings)
1751
+ @click.option("-n", "--name", required=True, help="Prompt name")
1752
+ @click.option("-p", "--prompt", required=True, help="Prompt value")
1753
+ @click.option(
1754
+ "-f",
1755
+ "--file",
1756
+ type=click.Path(exists=True),
1757
+ help="Path to existing prompts",
1758
+ default=AwesomePrompts.awesome_prompt_path,
1759
+ )
1760
+ @click.help_option("-h", "--help")
1761
+ @this.handle_exception
1762
+ def add(name, prompt, file):
1763
+ """Add new prompt to awesome-prompt list"""
1764
+ AwesomePrompts.awesome_prompt_path = file
1765
+ return AwesomePrompts().add_prompt(name, prompt)
1766
+
1767
+ @staticmethod
1768
+ @click.command(context_settings=this.context_settings)
1769
+ @click.argument("name")
1770
+ @click.option(
1771
+ "--case-sensitive",
1772
+ is_flag=True,
1773
+ flag_value=False,
1774
+ default=True,
1775
+ help="Perform name case-sensitive search",
1776
+ )
1777
+ @click.option(
1778
+ "-f",
1779
+ "--file",
1780
+ type=click.Path(exists=True),
1781
+ help="Path to existing prompts",
1782
+ default=AwesomePrompts.awesome_prompt_path,
1783
+ )
1784
+ @click.help_option("-h", "--help")
1785
+ @this.handle_exception
1786
+ def delete(name, case_sensitive, file):
1787
+ """Delete a specific awesome-prompt"""
1788
+ AwesomePrompts.awesome_prompt_path = file
1789
+ return AwesomePrompts().delete_prompt(name, case_sensitive)
1790
+
1791
+ @staticmethod
1792
+ @click.command(context_settings=this.context_settings)
1793
+ @click.option(
1794
+ "-j",
1795
+ "--json",
1796
+ is_flag=True,
1797
+ help="Display prompts in json format",
1798
+ )
1799
+ @click.option(
1800
+ "-i",
1801
+ "--indent",
1802
+ type=click.IntRange(1, 20),
1803
+ help="Json format indentation level",
1804
+ default=4,
1805
+ )
1806
+ @click.option(
1807
+ "-x",
1808
+ "--index",
1809
+ is_flag=True,
1810
+ help="Display prompts with their corresponding indexes",
1811
+ )
1812
+ @click.option("-c", "--color", help="Prompts stdout font color")
1813
+ @click.option("-o", "--output", type=click.Path(), help="Path to save the prompts")
1814
+ @click.help_option("-h", "--help")
1815
+ def whole(json, indent, index, color, output):
1816
+ """Stdout all awesome prompts"""
1817
+ ap = AwesomePrompts()
1818
+ awesome_prompts = ap.all_acts if index else ap.get_acts()
1819
+
1820
+ if json:
1821
+ # click.secho(formatted_awesome_prompts, fg=color)
1822
+ rich.print_json(data=awesome_prompts, indent=indent)
1823
+
1824
+ else:
1825
+ awesome_table = Table(show_lines=True, title="All Awesome-Prompts")
1826
+ awesome_table.add_column("index", justify="center", style="yellow")
1827
+ awesome_table.add_column("Act Name/Index", justify="left", style="cyan")
1828
+ awesome_table.add_column(
1829
+ "Prompt",
1830
+ style=color,
1831
+ )
1832
+ for index, key_value in enumerate(awesome_prompts.items()):
1833
+ awesome_table.add_row(str(index), str(key_value[0]), key_value[1])
1834
+ rich.print(awesome_table)
1835
+
1836
+ if output:
1837
+ from json import dump
1838
+
1839
+ with open(output, "w") as fh:
1840
+ dump(awesome_prompts, fh, indent=4)
1841
+
1842
+
1843
+ class Gpt4free:
1844
+ """Commands for gpt4free"""
1845
+
1846
+ @staticmethod
1847
+ @click.command(context_settings=this.context_settings)
1848
+ @busy_bar.run(index=1, immediate=True)
1849
+ @click.help_option("-h", "--help")
1850
+ def version():
1851
+ """Check current installed version of gpt4free"""
1852
+ version_string = this.run_system_command("pip show g4f")[1].stdout.split("\n")[
1853
+ 1
1854
+ ]
1855
+ click.secho(version_string, fg="cyan")
1856
+
1857
+ @staticmethod
1858
+ @click.command(context_settings=this.context_settings)
1859
+ @click.help_option("-h", "--help")
1860
+ @click.option(
1861
+ "-e",
1862
+ "--extra",
1863
+ help="Extra required dependencies category",
1864
+ multiple=True,
1865
+ type=click.Choice(
1866
+ ["all", "image", "webdriver", "openai", "api", "gui", "none"]
1867
+ ),
1868
+ default=["all"],
1869
+ )
1870
+ @click.option("-l", "--log", is_flag=True, help="Stdout installation logs")
1871
+ @click.option(
1872
+ "-s",
1873
+ "--sudo",
1874
+ is_flag=True,
1875
+ flag_value="sudo ",
1876
+ help="Install with sudo privileges",
1877
+ )
1878
+ @busy_bar.run(index=1, immediate=True)
1879
+ def update(extra, log, sudo):
1880
+ """Update GPT4FREE package (Models, Providers etc)"""
1881
+ if "none" in extra:
1882
+ command = f"{sudo or ''}pip install --upgrade g4f"
1883
+ else:
1884
+ command = f"{sudo or ''}pip install --upgrade g4f[{','.join(extra)}]"
1885
+ is_successful, response = this.run_system_command(command)
1886
+ if log and is_successful:
1887
+ click.echo(response.stdout)
1888
+ version_string = this.run_system_command("pip show g4f")[1].stdout.split("\n")[
1889
+ 1
1890
+ ]
1891
+ click.secho(f"GPT4FREE updated successfully - {version_string}", fg="cyan")
1892
+
1893
+ @staticmethod
1894
+ @click.command("list", context_settings=this.context_settings)
1895
+ @click.argument("target")
1896
+ @click.option("-w", "--working", is_flag=True, help="Restrict to working providers")
1897
+ @click.option("-u", "--url", is_flag=True, help="Restrict to providers with url")
1898
+ @click.option(
1899
+ "-s", "--stream", is_flag=True, help="Restrict to providers supporting stream"
1900
+ )
1901
+ @click.option(
1902
+ "-c",
1903
+ "--context",
1904
+ is_flag=True,
1905
+ help="Restrict to providers supporing context natively",
1906
+ )
1907
+ @click.option(
1908
+ "-35",
1909
+ "--gpt35",
1910
+ is_flag=True,
1911
+ help="Restrict to providers supporting gpt3.5_turbo model",
1912
+ )
1913
+ @click.option(
1914
+ "-4", "--gpt4", is_flag=True, help="Restrict to providers supporting gpt4 model"
1915
+ )
1916
+ @click.option(
1917
+ "-se",
1918
+ "--selenium",
1919
+ is_flag=True,
1920
+ help="Restrict to selenium dependent providers",
1921
+ )
1922
+ @click.option("-j", "--json", is_flag=True, help="Format output in json")
1923
+ @click.help_option("-h", "--help")
1924
+ def show(target, working, url, stream, context, gpt35, gpt4, selenium, json):
1925
+ """List available models and providers"""
1926
+ available_targets = ["models", "providers"]
1927
+ assert (
1928
+ target in available_targets
1929
+ ), f"Target must be one of [{', '.join(available_targets)}]"
1930
+ if target == "providers":
1931
+ hunted_providers = list(
1932
+ set(
1933
+ map(
1934
+ lambda provider: (
1935
+ provider["name"] if all(list(provider.values())) else None
1936
+ ),
1937
+ this.g4f_providers_in_dict(
1938
+ url=url,
1939
+ working=working,
1940
+ stream=stream,
1941
+ context=context,
1942
+ gpt35=gpt35,
1943
+ gpt4=gpt4,
1944
+ selenium=selenium,
1945
+ ),
1946
+ )
1947
+ )
1948
+ )
1949
+ while None in hunted_providers:
1950
+ hunted_providers.remove(None)
1951
+
1952
+ hunted_providers.sort()
1953
+ if json:
1954
+ rich.print_json(data=dict(providers=hunted_providers), indent=4)
1955
+
1956
+ else:
1957
+ table = Table(show_lines=True)
1958
+ table.add_column("No.", style="yellow", justify="center")
1959
+ table.add_column("Provider", style="cyan")
1960
+ for no, provider in enumerate(hunted_providers):
1961
+ table.add_row(str(no), provider)
1962
+ rich.print(table)
1963
+ else:
1964
+ models = dict(
1965
+ Bard=[
1966
+ "palm",
1967
+ ],
1968
+ HuggingFace=[
1969
+ "h2ogpt-gm-oasst1-en-2048-falcon-7b-v3",
1970
+ "h2ogpt-gm-oasst1-en-2048-falcon-40b-v1",
1971
+ "h2ogpt-gm-oasst1-en-2048-open-llama-13b",
1972
+ "gpt-neox-20b",
1973
+ "oasst-sft-1-pythia-12b",
1974
+ "oasst-sft-4-pythia-12b-epoch-3.5",
1975
+ "santacoder",
1976
+ "bloom",
1977
+ "flan-t5-xxl",
1978
+ ],
1979
+ Anthropic=[
1980
+ "claude-instant-v1",
1981
+ "claude-v1",
1982
+ "claude-v2",
1983
+ ],
1984
+ Cohere=[
1985
+ "command-light-nightly",
1986
+ "command-nightly",
1987
+ ],
1988
+ OpenAI=[
1989
+ "code-davinci-002",
1990
+ "text-ada-001",
1991
+ "text-babbage-001",
1992
+ "text-curie-001",
1993
+ "text-davinci-002",
1994
+ "text-davinci-003",
1995
+ "gpt-3.5-turbo-16k",
1996
+ "gpt-3.5-turbo-16k-0613",
1997
+ "gpt-4-0613",
1998
+ ],
1999
+ Replicate=[
2000
+ "llama13b-v2-chat",
2001
+ "llama7b-v2-chat",
2002
+ ],
2003
+ )
2004
+ for provider in webscout.g4f.Provider.__providers__:
2005
+ if hasattr(provider, "models"):
2006
+ models[provider.__name__] = provider.models
2007
+ if json:
2008
+ for key, value in models.items():
2009
+ while None in value:
2010
+ value.remove(None)
2011
+ value.sort()
2012
+ models[key] = value
2013
+
2014
+ rich.print_json(data=models, indent=4)
2015
+ else:
2016
+ table = Table(show_lines=True)
2017
+ table.add_column("No.", justify="center", style="white")
2018
+ table.add_column("Base Provider", style="cyan")
2019
+ table.add_column("Model(s)", style="yellow")
2020
+ for count, provider_models in enumerate(models.items()):
2021
+ models = provider_models[1]
2022
+ models.sort()
2023
+ table.add_row(str(count), provider_models[0], "\n".join(models))
2024
+ rich.print(table)
2025
+
2026
+ @staticmethod
2027
+ @click.command(context_settings=this.context_settings)
2028
+ @click.argument("port", type=click.INT, required=False)
2029
+ @click.option(
2030
+ "-a", "--address", help="Host on this particular address", default="127.0.0.1"
2031
+ )
2032
+ @click.option("-d", "--debug", is_flag=True, help="Start server in debug mode")
2033
+ @click.option(
2034
+ "-o", "--open", is_flag=True, help="Proceed to the interface immediately"
2035
+ )
2036
+ @click.help_option("-h", "--help")
2037
+ def gui(port, address, debug, open):
2038
+ """Launch gpt4free web interface"""
2039
+ from g4f.gui import run_gui
2040
+
2041
+ port = port or 8000
2042
+ t1 = thr(
2043
+ target=run_gui,
2044
+ args=(
2045
+ address,
2046
+ port,
2047
+ debug,
2048
+ ),
2049
+ )
2050
+ # run_gui(host=address, port=port, debug=debug)
2051
+ t1.start()
2052
+ if open:
2053
+ click.launch(f"http://{address}:{port}")
2054
+ t1.join()
2055
+
2056
+ @staticmethod
2057
+ @click.command(context_settings=this.context_settings)
2058
+ @click.option(
2059
+ "-t",
2060
+ "--timeout",
2061
+ type=click.INT,
2062
+ help="Provider's response generation timeout",
2063
+ default=20,
2064
+ )
2065
+ @click.option(
2066
+ "-r",
2067
+ "--thread",
2068
+ type=click.INT,
2069
+ help="Test n amount of providers at once",
2070
+ default=5,
2071
+ )
2072
+ @click.option("-q", "--quiet", is_flag=True, help="Suppress progress bar")
2073
+ @click.option(
2074
+ "-j", "--json", is_flag=True, help="Stdout test results in json format"
2075
+ )
2076
+ @click.option("-d", "--dry-test", is_flag=True, help="Return previous test results")
2077
+ @click.option(
2078
+ "-b", "--best", is_flag=True, help="Stdout the fastest provider <name only>"
2079
+ )
2080
+ @click.option(
2081
+ "-se",
2082
+ "--selenium",
2083
+ help="Test even selenium dependent providers",
2084
+ is_flag=True,
2085
+ )
2086
+ @click.option(
2087
+ "-dl",
2088
+ "--disable-logging",
2089
+ is_flag=True,
2090
+ help="Disable logging",
2091
+ )
2092
+ @click.option("-y", "--yes", is_flag=True, help="Okay to all confirmations")
2093
+ @click.help_option("-h", "--help")
2094
+ def test(
2095
+ timeout, thread, quiet, json, dry_test, best, selenium, disable_logging, yes
2096
+ ):
2097
+ """Test and save working providers"""
2098
+ from webscout.g4f import TestProviders
2099
+
2100
+ test = TestProviders(
2101
+ test_at_once=thread,
2102
+ quiet=quiet,
2103
+ timeout=timeout,
2104
+ selenium=selenium,
2105
+ do_log=disable_logging == False,
2106
+ )
2107
+ if best:
2108
+ click.secho(test.best)
2109
+ return
2110
+ elif dry_test:
2111
+ results = test.get_results(
2112
+ run=False,
2113
+ )
2114
+ else:
2115
+ if (
2116
+ yes
2117
+ or os.path.isfile(webscout.AIutel.results_path)
2118
+ and click.confirm("Are you sure to run new test")
2119
+ ):
2120
+ results = test.get_results(run=True)
2121
+ else:
2122
+ results = test.get_results(
2123
+ run=False,
2124
+ )
2125
+ if json:
2126
+ rich.print_json(data=dict(results=results))
2127
+ else:
2128
+ table = Table(
2129
+ title="G4f Providers Test Results",
2130
+ show_lines=True,
2131
+ )
2132
+ table.add_column("No.", style="white", justify="center")
2133
+ table.add_column("Provider", style="yellow", justify="left")
2134
+ table.add_column("Response Time(s)", style="cyan")
2135
+
2136
+ for no, provider in enumerate(results, start=1):
2137
+ table.add_row(
2138
+ str(no), provider["name"], str(round(provider["time"], 2))
2139
+ )
2140
+ rich.print(table)
2141
+
2142
+
2143
+
2144
+ @staticmethod
2145
+ @click.command(context_settings=this.context_settings)
2146
+ @click.argument("prompt")
2147
+ @click.option(
2148
+ "-d",
2149
+ "--directory",
2150
+ type=click.Path(exists=True),
2151
+ help="Folder for saving the images",
2152
+ default=os.getcwd(),
2153
+ )
2154
+ @click.option(
2155
+ "-a",
2156
+ "--amount",
2157
+ type=click.IntRange(1, 100),
2158
+ help="Total images to be generated",
2159
+ default=1,
2160
+ )
2161
+ @click.option("-n", "--name", help="Name for the generated images")
2162
+ @click.option(
2163
+ "-t",
2164
+ "--timeout",
2165
+ type=click.IntRange(5, 300),
2166
+ help="Http request timeout in seconds",
2167
+ )
2168
+ @click.option("-p", "--proxy", help="Http request proxy")
2169
+ @click.option(
2170
+ "-nd",
2171
+ "--no-additives",
2172
+ is_flag=True,
2173
+ help="Disable prompt altering for effective image generation",
2174
+ )
2175
+ @click.option("-q", "--quiet", is_flag=True, help="Suppress progress bar")
2176
+ @click.help_option("-h", "--help")
2177
+ def generate_image(
2178
+ prompt, directory, amount, name, timeout, proxy, no_additives, quiet
2179
+ ):
2180
+ """Generate images with pollinations.ai"""
2181
+ with Progress() as progress:
2182
+ task = progress.add_task(
2183
+ f"[cyan]Generating ...[{amount}]",
2184
+ total=amount,
2185
+ visible=quiet == False,
2186
+ )
2187
+ imager = Imager(timeout=timeout, proxies=proxy if proxy else {})
2188
+ for image in imager.generate(
2189
+ prompt=prompt,
2190
+ amount=amount,
2191
+ additives=no_additives == False,
2192
+ stream=True,
2193
+ ):
2194
+ imager.save([image], name=name, dir=directory)
2195
+ progress.update(task, advance=1)
2196
+
2197
+
2198
+ class Utils:
2199
+ """Utilities command"""
2200
+
2201
+ @staticmethod
2202
+ @click.command(context_settings=this.context_settings)
2203
+ @click.argument("source", required=False)
2204
+ @click.option(
2205
+ "-d", "--dev", is_flag=True, help="Update from version control (development)"
2206
+ )
2207
+ @click.option(
2208
+ "-s",
2209
+ "--sudo",
2210
+ is_flag=True,
2211
+ flag_value="sudo ",
2212
+ help="Install with sudo privileges",
2213
+ )
2214
+ @click.help_option("-h", "--help")
2215
+ @busy_bar.run(index=1, immediate=True)
2216
+ def update(source, dev, sudo):
2217
+ """Install latest version of webscout"""
2218
+ if dev:
2219
+ source = "git+" + webscout.__repo__ + ".git"
2220
+ source = "python-tgpt" if source is None else source
2221
+ assert (
2222
+ "tgpt" in source or source == "."
2223
+ ), f"Cannot update webscout from the source '{source}'"
2224
+ click.secho(
2225
+ f"[*] Updating from '{'pip' if source=='python-tgpt' else source}'",
2226
+ fg="yellow",
2227
+ )
2228
+ this.run_system_command(f"{sudo or ''}pip install --upgrade {source}")
2229
+ response = this.run_system_command("pip show python-tgpt")[1]
2230
+ click.secho(response.stdout)
2231
+ click.secho("Congratulations! webscout updated successfully.", fg="cyan")
2232
+
2233
+ @staticmethod
2234
+ @click.command(context_settings=this.context_settings)
2235
+ @click.option("-w", "--whole", is_flag=True, help="Stdout whole json info")
2236
+ @click.option(
2237
+ "-v", "--version", is_flag=True, help="Stdout latest version name only"
2238
+ )
2239
+ @click.option("-b", "--body", is_flag=True, help="Stdout changelog info only")
2240
+ @click.option(
2241
+ "-e", "--executable", is_flag=True, help="Stdout url to binary for your system"
2242
+ )
2243
+ @click.help_option("-h", "--help")
2244
+ def latest(whole, version, body, executable):
2245
+ """Check webscout latest version info"""
2246
+ from webscout.utils import Updates
2247
+
2248
+ update = Updates()
2249
+ if whole:
2250
+ rich.print_json(data=update.latest(whole=True))
2251
+
2252
+ elif version:
2253
+ rich.print(update.latest_version)
2254
+ elif body:
2255
+ rich.print(Markdown(update.latest()["body"]))
2256
+ elif executable:
2257
+ rich.print(update.executable())
2258
+ else:
2259
+ rich.print_json(data=update.latest())
2260
+
2261
+
2262
+ def make_commands():
2263
+ """Make webscout chained commands"""
2264
+
2265
+ # generate
2266
+ EntryGroup.webai_.add_command(ChatGenerate.generate)
2267
+
2268
+ # webai
2269
+ EntryGroup.webai_.add_command(Chatwebai.webai)
2270
+
2271
+ # utils
2272
+ EntryGroup.utils.add_command(Utils.update)
2273
+ EntryGroup.utils.add_command(Utils.latest)
2274
+
2275
+ # gpt4free
2276
+ EntryGroup.gpt4free.add_command(Gpt4free.version)
2277
+ EntryGroup.gpt4free.add_command(Gpt4free.update)
2278
+ EntryGroup.gpt4free.add_command(Gpt4free.show)
2279
+ EntryGroup.gpt4free.add_command(Gpt4free.gui)
2280
+ EntryGroup.gpt4free.add_command(Gpt4free.test)
2281
+
2282
+ # Awesome
2283
+ EntryGroup.awesome.add_command(Awesome.add)
2284
+ EntryGroup.awesome.add_command(Awesome.delete)
2285
+ EntryGroup.awesome.add_command(Awesome.search)
2286
+ EntryGroup.awesome.add_command(Awesome.update)
2287
+ EntryGroup.awesome.add_command(Awesome.whole)
2288
+
2289
+
2290
+ # @this.handle_exception
2291
+ def main(*args):
2292
+ """Fireup console programmically"""
2293
+ sys.argv += list(args)
2294
+ args = sys.argv
2295
+ if len(args) == 1:
2296
+ sys.argv.insert(1, "webai") # Just a hack to make default command
2297
+ try:
2298
+ make_commands()
2299
+ return EntryGroup.webai_()
2300
+ except Exception as e:
2301
+ logging.error(this.getExc(e))
2302
+ sys.exit(1)
2303
+
2304
+
2305
+ if __name__ == "__main__":
2306
+ main()