webscout 1.2.4__py3-none-any.whl → 1.2.6__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/AI.py CHANGED
@@ -21,9 +21,199 @@ import yaml
21
21
  from webscout.AIutel import Optimizers
22
22
  from webscout.AIutel import Conversation
23
23
  from webscout.AIutel import AwesomePrompts
24
+ from webscout.AIbase import Provider
24
25
  from Helpingai_T2 import Perplexity
25
26
  from typing import Any
26
27
  import logging
28
+ #------------------------------------------------------KOBOLDAI-----------------------------------------------------------
29
+ class KOBOLDAI(Provider):
30
+ def __init__(
31
+ self,
32
+ is_conversation: bool = True,
33
+ max_tokens: int = 600,
34
+ temperature: float = 1,
35
+ top_p: float = 1,
36
+ timeout: int = 30,
37
+ intro: str = None,
38
+ filepath: str = None,
39
+ update_file: bool = True,
40
+ proxies: dict = {},
41
+ history_offset: int = 10250,
42
+ act: str = None,
43
+ ):
44
+ """Instantiate TGPT
45
+
46
+ Args:
47
+ is_conversation (str, optional): Flag for chatting conversationally. Defaults to True.
48
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
49
+ temperature (float, optional): Charge of the generated text's randomness. Defaults to 0.2.
50
+ top_p (float, optional): Sampling threshold during inference time. Defaults to 0.999.
51
+ timeout (int, optional): Http requesting timeout. Defaults to 30
52
+ intro (str, optional): Conversation introductory prompt. Defaults to `Conversation.intro`.
53
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
54
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
55
+ proxies (dict, optional) : Http reqiuest proxies (socks). Defaults to {}.
56
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
57
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
58
+ """
59
+ self.session = requests.Session()
60
+ self.is_conversation = is_conversation
61
+ self.max_tokens_to_sample = max_tokens
62
+ self.temperature = temperature
63
+ self.top_p = top_p
64
+ self.chat_endpoint = (
65
+ "https://koboldai-koboldcpp-tiefighter.hf.space/api/extra/generate/stream"
66
+ )
67
+ self.stream_chunk_size = 64
68
+ self.timeout = timeout
69
+ self.last_response = {}
70
+ self.headers = {
71
+ "Content-Type": "application/json",
72
+ "Accept": "application/json",
73
+ }
74
+
75
+ self.__available_optimizers = (
76
+ method
77
+ for method in dir(Optimizers)
78
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
79
+ )
80
+ self.session.headers.update(self.headers)
81
+ Conversation.intro = (
82
+ AwesomePrompts().get_act(
83
+ act, raise_not_found=True, default=None, case_insensitive=True
84
+ )
85
+ if act
86
+ else intro or Conversation.intro
87
+ )
88
+ self.conversation = Conversation(
89
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
90
+ )
91
+ self.conversation.history_offset = history_offset
92
+ self.session.proxies = proxies
93
+
94
+ def ask(
95
+ self,
96
+ prompt: str,
97
+ stream: bool = False,
98
+ raw: bool = False,
99
+ optimizer: str = None,
100
+ conversationally: bool = False,
101
+ ) -> dict:
102
+ """Chat with AI
103
+
104
+ Args:
105
+ prompt (str): Prompt to be send.
106
+ stream (bool, optional): Flag for streaming response. Defaults to False.
107
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
108
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
109
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
110
+ Returns:
111
+ dict : {}
112
+ ```json
113
+ {
114
+ "token" : "How may I assist you today?"
115
+ }
116
+ ```
117
+ """
118
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
119
+ if optimizer:
120
+ if optimizer in self.__available_optimizers:
121
+ conversation_prompt = getattr(Optimizers, optimizer)(
122
+ conversation_prompt if conversationally else prompt
123
+ )
124
+ else:
125
+ raise Exception(
126
+ f"Optimizer is not one of {self.__available_optimizers}"
127
+ )
128
+
129
+ self.session.headers.update(self.headers)
130
+ payload = {
131
+ "prompt": conversation_prompt,
132
+ "temperature": self.temperature,
133
+ "top_p": self.top_p,
134
+ }
135
+
136
+ def for_stream():
137
+ response = self.session.post(
138
+ self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
139
+ )
140
+ if not response.ok:
141
+ raise Exception(
142
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
143
+ )
144
+
145
+ message_load = ""
146
+ for value in response.iter_lines(
147
+ decode_unicode=True,
148
+ delimiter="" if raw else "event: message\ndata:",
149
+ chunk_size=self.stream_chunk_size,
150
+ ):
151
+ try:
152
+ resp = json.loads(value)
153
+ message_load += self.get_message(resp)
154
+ resp["token"] = message_load
155
+ self.last_response.update(resp)
156
+ yield value if raw else resp
157
+ except json.decoder.JSONDecodeError:
158
+ pass
159
+ self.conversation.update_chat_history(
160
+ prompt, self.get_message(self.last_response)
161
+ )
162
+
163
+ def for_non_stream():
164
+ # let's make use of stream
165
+ for _ in for_stream():
166
+ pass
167
+ return self.last_response
168
+
169
+ return for_stream() if stream else for_non_stream()
170
+
171
+ def chat(
172
+ self,
173
+ prompt: str,
174
+ stream: bool = False,
175
+ optimizer: str = None,
176
+ conversationally: bool = False,
177
+ ) -> str:
178
+ """Generate response `str`
179
+ Args:
180
+ prompt (str): Prompt to be send.
181
+ stream (bool, optional): Flag for streaming response. Defaults to False.
182
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
183
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
184
+ Returns:
185
+ str: Response generated
186
+ """
187
+
188
+ def for_stream():
189
+ for response in self.ask(
190
+ prompt, True, optimizer=optimizer, conversationally=conversationally
191
+ ):
192
+ yield self.get_message(response)
193
+
194
+ def for_non_stream():
195
+ return self.get_message(
196
+ self.ask(
197
+ prompt,
198
+ False,
199
+ optimizer=optimizer,
200
+ conversationally=conversationally,
201
+ )
202
+ )
203
+
204
+ return for_stream() if stream else for_non_stream()
205
+
206
+ def get_message(self, response: dict) -> str:
207
+ """Retrieves message only from response
208
+
209
+ Args:
210
+ response (dict): Response generated by `self.ask`
211
+
212
+ Returns:
213
+ str: Message extracted
214
+ """
215
+ assert isinstance(response, dict), "Response should be of dict data-type only"
216
+ return response.get("token")
27
217
  #------------------------------------------------------OpenGPT-----------------------------------------------------------
28
218
  class OPENGPT:
29
219
  def __init__(
@@ -1237,5 +1427,19 @@ def opengpt(prompt, stream):
1237
1427
  else:
1238
1428
  response_str = opengpt.chat(prompt)
1239
1429
  print(response_str)
1430
+
1431
+ @cli.command()
1432
+ @click.option('--prompt', prompt='Enter your prompt', help='The prompt to send.')
1433
+ @click.option('--stream', is_flag=True, help='Flag for streaming response.')
1434
+ @click.option('--raw', is_flag=True, help='Stream back raw response as received.')
1435
+ @click.option('--optimizer', type=str, help='Prompt optimizer name.')
1436
+ @click.option('--conversationally', is_flag=True, help='Chat conversationally when using optimizer.')
1437
+ def koboldai_cli(prompt, stream, raw, optimizer, conversationally):
1438
+ """Chat with KOBOLDAI using the provided prompt."""
1439
+ koboldai_instance = KOBOLDAI() # Initialize a KOBOLDAI instance
1440
+ response = koboldai_instance.ask(prompt, stream, raw, optimizer, conversationally)
1441
+ processed_response = koboldai_instance.get_message(response) # Process the response
1442
+ print(processed_response)
1443
+
1240
1444
  if __name__ == '__main__':
1241
1445
  cli()
webscout/AIutel.py CHANGED
@@ -11,7 +11,7 @@ import click
11
11
  from rich.markdown import Markdown
12
12
  from rich.console import Console
13
13
 
14
- appdir = appdirs.AppDirs("pytgpt", "Smartwa")
14
+ appdir = appdirs.AppDirs("AIWEBS", "vortex")
15
15
 
16
16
  default_path = appdir.user_cache_dir
17
17
 
webscout/__init__.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Webscout.
2
2
 
3
3
  Search for words, documents, images, videos, news, maps and text translation
4
- using the DuckDuckGo.com search engine.
4
+ using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
5
5
  """
6
6
 
7
7
  import logging
@@ -9,7 +9,10 @@ from .webscout_search import WEBS
9
9
  from .webscout_search_async import AsyncWEBS
10
10
  from .version import __version__
11
11
  from .DWEBS import DeepWEBS
12
- from .offlineAI import GPT4ALL
12
+ from .AIutel import appdir
13
+ from .transcriber import transcriber
14
+
15
+
13
16
  __all__ = ["WEBS", "AsyncWEBS", "__version__", "cli"]
14
17
 
15
18
  logging.getLogger("webscout").addHandler(logging.NullHandler())
@@ -0,0 +1,498 @@
1
+ import requests
2
+ import http.cookiejar as cookiejar
3
+ import sys
4
+ import json
5
+ from xml.etree import ElementTree
6
+ import re
7
+ from requests import HTTPError
8
+ import html.parser
9
+
10
+ html_parser = html.parser.HTMLParser()
11
+ import html
12
+
13
+ def unescape(string):
14
+ return html.unescape(string)
15
+ WATCH_URL = 'https://www.youtube.com/watch?v={video_id}'
16
+
17
+ class TranscriptRetrievalError(Exception):
18
+ """
19
+ Base class for exceptions raised when a transcript cannot be retrieved.
20
+ """
21
+ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!'
22
+ CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}'
23
+ CAUSE_MESSAGE = ''
24
+ GITHUB_REFERRAL = (
25
+ '\n\nIf you are sure that the described cause is not responsible for this error '
26
+ 'and that a transcript should be retrievable, please create an issue at '
27
+ 'https://github.com/OE-LUCIFER/Webscout/issues. '
28
+ 'Please add which version of youtube_transcript_api you are using '
29
+ 'and provide the information needed to replicate the error. '
30
+ 'Also make sure that there are no open issues which already describe your problem!'
31
+ )
32
+
33
+ def __init__(self, video_id):
34
+ self.video_id = video_id
35
+ super(TranscriptRetrievalError, self).__init__(self._build_error_message())
36
+
37
+ def _build_error_message(self):
38
+ cause = self.cause
39
+ error_message = self.ERROR_MESSAGE.format(video_url=WATCH_URL.format(video_id=self.video_id))
40
+
41
+ if cause:
42
+ error_message += self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL
43
+
44
+ return error_message
45
+
46
+ @property
47
+ def cause(self):
48
+ return self.CAUSE_MESSAGE
49
+
50
+ class YouTubeRequestFailedError(TranscriptRetrievalError):
51
+ CAUSE_MESSAGE = 'Request to YouTube failed: {reason}'
52
+
53
+ def __init__(self, video_id, http_error):
54
+ self.reason = str(http_error)
55
+ super(YouTubeRequestFailedError, self).__init__(video_id)
56
+
57
+ @property
58
+ def cause(self):
59
+ return self.CAUSE_MESSAGE.format(reason=self.reason)
60
+
61
+ class VideoUnavailableError(TranscriptRetrievalError):
62
+ CAUSE_MESSAGE = 'The video is no longer available'
63
+
64
+ class InvalidVideoIdError(TranscriptRetrievalError):
65
+ CAUSE_MESSAGE = (
66
+ 'You provided an invalid video id. Make sure you are using the video id and NOT the url!\n\n'
67
+ 'Do NOT run: `YouTubeTranscriptApi.get_transcript("https://www.youtube.com/watch?v=1234")`\n'
68
+ 'Instead run: `YouTubeTranscriptApi.get_transcript("1234")`'
69
+ )
70
+
71
+ class TooManyRequestsError(TranscriptRetrievalError):
72
+ CAUSE_MESSAGE = (
73
+ 'YouTube is receiving too many requests from this IP and now requires solving a captcha to continue. '
74
+ 'One of the following things can be done to work around this:\n\
75
+ - Manually solve the captcha in a browser and export the cookie. '
76
+ 'Read here how to use that cookie with '
77
+ 'youtube-transcript-api: https://github.com/jdepoix/youtube-transcript-api#cookies\n\
78
+ - Use a different IP address\n\
79
+ - Wait until the ban on your IP has been lifted'
80
+ )
81
+
82
+ class TranscriptsDisabledError(TranscriptRetrievalError):
83
+ CAUSE_MESSAGE = 'Subtitles are disabled for this video'
84
+
85
+ class NoTranscriptAvailableError(TranscriptRetrievalError):
86
+ CAUSE_MESSAGE = 'No transcripts are available for this video'
87
+
88
+ class NotTranslatableError(TranscriptRetrievalError):
89
+ CAUSE_MESSAGE = 'The requested language is not translatable'
90
+
91
+ class TranslationLanguageNotAvailableError(TranscriptRetrievalError):
92
+ CAUSE_MESSAGE = 'The requested translation language is not available'
93
+
94
+ class CookiePathInvalidError(TranscriptRetrievalError):
95
+ CAUSE_MESSAGE = 'The provided cookie file was unable to be loaded'
96
+
97
+ class CookiesInvalidError(TranscriptRetrievalError):
98
+ CAUSE_MESSAGE = 'The cookies provided are not valid (may have expired)'
99
+
100
+ class FailedToCreateConsentCookieError(TranscriptRetrievalError):
101
+ CAUSE_MESSAGE = 'Failed to automatically give consent to saving cookies'
102
+
103
+ class NoTranscriptFoundError(TranscriptRetrievalError):
104
+ CAUSE_MESSAGE = (
105
+ 'No transcripts were found for any of the requested language codes: {requested_language_codes}\n\n'
106
+ '{transcript_data}'
107
+ )
108
+
109
+ def __init__(self, video_id, requested_language_codes, transcript_data):
110
+ self._requested_language_codes = requested_language_codes
111
+ self._transcript_data = transcript_data
112
+ super(NoTranscriptFoundError, self).__init__(video_id)
113
+
114
+ @property
115
+ def cause(self):
116
+ return self.CAUSE_MESSAGE.format(
117
+ requested_language_codes=self._requested_language_codes,
118
+ transcript_data=str(self._transcript_data),
119
+ )
120
+
121
+
122
+
123
+ def _raise_http_errors(response, video_id):
124
+ try:
125
+ response.raise_for_status()
126
+ return response
127
+ except HTTPError as error:
128
+ raise YouTubeRequestFailedError(error, video_id)
129
+
130
+
131
+ class TranscriptListFetcher(object):
132
+ def __init__(self, http_client):
133
+ self._http_client = http_client
134
+
135
+ def fetch(self, video_id):
136
+ return TranscriptList.build(
137
+ self._http_client,
138
+ video_id,
139
+ self._extract_captions_json(self._fetch_video_html(video_id), video_id),
140
+ )
141
+
142
+ def _extract_captions_json(self, html, video_id):
143
+ splitted_html = html.split('"captions":')
144
+
145
+ if len(splitted_html) <= 1:
146
+ if video_id.startswith('http://') or video_id.startswith('https://'):
147
+ raise InvalidVideoIdError(video_id)
148
+ if 'class="g-recaptcha"' in html:
149
+ raise TooManyRequestsError(video_id)
150
+ if '"playabilityStatus":' not in html:
151
+ raise VideoUnavailableError(video_id)
152
+
153
+ raise TranscriptsDisabledError(video_id)
154
+
155
+ captions_json = json.loads(
156
+ splitted_html[1].split(',"videoDetails')[0].replace('\n', '')
157
+ ).get('playerCaptionsTracklistRenderer')
158
+ if captions_json is None:
159
+ raise TranscriptsDisabledError(video_id)
160
+
161
+ if 'captionTracks' not in captions_json:
162
+ raise TranscriptsDisabledError(video_id)
163
+
164
+ return captions_json
165
+
166
+ def _create_consent_cookie(self, html, video_id):
167
+ match = re.search('name="v" value="(.*?)"', html)
168
+ if match is None:
169
+ raise FailedToCreateConsentCookieError(video_id)
170
+ self._http_client.cookies.set('CONSENT', 'YES+' + match.group(1), domain='.youtube.com')
171
+
172
+ def _fetch_video_html(self, video_id):
173
+ html = self._fetch_html(video_id)
174
+ if 'action="https://consent.youtube.com/s"' in html:
175
+ self._create_consent_cookie(html, video_id)
176
+ html = self._fetch_html(video_id)
177
+ if 'action="https://consent.youtube.com/s"' in html:
178
+ raise FailedToCreateConsentCookieError(video_id)
179
+ return html
180
+
181
+ def _fetch_html(self, video_id):
182
+ response = self._http_client.get(WATCH_URL.format(video_id=video_id), headers={'Accept-Language': 'en-US'})
183
+ return unescape(_raise_http_errors(response, video_id).text)
184
+
185
+
186
+ class TranscriptList(object):
187
+ """
188
+ This object represents a list of transcripts. It can be iterated over to list all transcripts which are available
189
+ for a given YouTube video. Also it provides functionality to search for a transcript in a given language.
190
+ """
191
+
192
+ def __init__(self, video_id, manually_created_transcripts, generated_transcripts, translation_languages):
193
+ """
194
+ The constructor is only for internal use. Use the static build method instead.
195
+
196
+ :param video_id: the id of the video this TranscriptList is for
197
+ :type video_id: str
198
+ :param manually_created_transcripts: dict mapping language codes to the manually created transcripts
199
+ :type manually_created_transcripts: dict[str, Transcript]
200
+ :param generated_transcripts: dict mapping language codes to the generated transcripts
201
+ :type generated_transcripts: dict[str, Transcript]
202
+ :param translation_languages: list of languages which can be used for translatable languages
203
+ :type translation_languages: list[dict[str, str]]
204
+ """
205
+ self.video_id = video_id
206
+ self._manually_created_transcripts = manually_created_transcripts
207
+ self._generated_transcripts = generated_transcripts
208
+ self._translation_languages = translation_languages
209
+
210
+ @staticmethod
211
+ def build(http_client, video_id, captions_json):
212
+ """
213
+ Factory method for TranscriptList.
214
+
215
+ :param http_client: http client which is used to make the transcript retrieving http calls
216
+ :type http_client: requests.Session
217
+ :param video_id: the id of the video this TranscriptList is for
218
+ :type video_id: str
219
+ :param captions_json: the JSON parsed from the YouTube pages static HTML
220
+ :type captions_json: dict
221
+ :return: the created TranscriptList
222
+ :rtype TranscriptList:
223
+ """
224
+ translation_languages = [
225
+ {
226
+ 'language': translation_language['languageName']['simpleText'],
227
+ 'language_code': translation_language['languageCode'],
228
+ } for translation_language in captions_json.get('translationLanguages', [])
229
+ ]
230
+
231
+ manually_created_transcripts = {}
232
+ generated_transcripts = {}
233
+
234
+ for caption in captions_json['captionTracks']:
235
+ if caption.get('kind', '') == 'asr':
236
+ transcript_dict = generated_transcripts
237
+ else:
238
+ transcript_dict = manually_created_transcripts
239
+
240
+ transcript_dict[caption['languageCode']] = Transcript(
241
+ http_client,
242
+ video_id,
243
+ caption['baseUrl'],
244
+ caption['name']['simpleText'],
245
+ caption['languageCode'],
246
+ caption.get('kind', '') == 'asr',
247
+ translation_languages if caption.get('isTranslatable', False) else [],
248
+ )
249
+
250
+ return TranscriptList(
251
+ video_id,
252
+ manually_created_transcripts,
253
+ generated_transcripts,
254
+ translation_languages,
255
+ )
256
+
257
+ def __iter__(self):
258
+ return iter(list(self._manually_created_transcripts.values()) + list(self._generated_transcripts.values()))
259
+
260
+ def find_transcript(self, language_codes):
261
+ """
262
+ Finds a transcript for a given language code. Manually created transcripts are returned first and only if none
263
+ are found, generated transcripts are used. If you only want generated transcripts use
264
+ `find_manually_created_transcript` instead.
265
+
266
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
267
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
268
+ it fails to do so.
269
+ :type languages: list[str]
270
+ :return: the found Transcript
271
+ :rtype Transcript:
272
+ :raises: NoTranscriptFound
273
+ """
274
+ return self._find_transcript(language_codes, [self._manually_created_transcripts, self._generated_transcripts])
275
+
276
+ def find_generated_transcript(self, language_codes):
277
+ """
278
+ Finds an automatically generated transcript for a given language code.
279
+
280
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
281
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
282
+ it fails to do so.
283
+ :type languages: list[str]
284
+ :return: the found Transcript
285
+ :rtype Transcript:
286
+ :raises: NoTranscriptFound
287
+ """
288
+ return self._find_transcript(language_codes, [self._generated_transcripts])
289
+
290
+ def find_manually_created_transcript(self, language_codes):
291
+ """
292
+ Finds a manually created transcript for a given language code.
293
+
294
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
295
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
296
+ it fails to do so.
297
+ :type languages: list[str]
298
+ :return: the found Transcript
299
+ :rtype Transcript:
300
+ :raises: NoTranscriptFound
301
+ """
302
+ return self._find_transcript(language_codes, [self._manually_created_transcripts])
303
+
304
+ def _find_transcript(self, language_codes, transcript_dicts):
305
+ for language_code in language_codes:
306
+ for transcript_dict in transcript_dicts:
307
+ if language_code in transcript_dict:
308
+ return transcript_dict[language_code]
309
+
310
+ raise NoTranscriptFoundError(
311
+ self.video_id,
312
+ language_codes,
313
+ self
314
+ )
315
+
316
+ def __str__(self):
317
+ return (
318
+ 'For this video ({video_id}) transcripts are available in the following languages:\n\n'
319
+ '(MANUALLY CREATED)\n'
320
+ '{available_manually_created_transcript_languages}\n\n'
321
+ '(GENERATED)\n'
322
+ '{available_generated_transcripts}\n\n'
323
+ '(TRANSLATION LANGUAGES)\n'
324
+ '{available_translation_languages}'
325
+ ).format(
326
+ video_id=self.video_id,
327
+ available_manually_created_transcript_languages=self._get_language_description(
328
+ str(transcript) for transcript in self._manually_created_transcripts.values()
329
+ ),
330
+ available_generated_transcripts=self._get_language_description(
331
+ str(transcript) for transcript in self._generated_transcripts.values()
332
+ ),
333
+ available_translation_languages=self._get_language_description(
334
+ '{language_code} ("{language}")'.format(
335
+ language=translation_language['language'],
336
+ language_code=translation_language['language_code'],
337
+ ) for translation_language in self._translation_languages
338
+ )
339
+ )
340
+
341
+ def _get_language_description(self, transcript_strings):
342
+ description = '\n'.join(' - {transcript}'.format(transcript=transcript) for transcript in transcript_strings)
343
+ return description if description else 'None'
344
+
345
+
346
+ class Transcript(object):
347
+ def __init__(self, http_client, video_id, url, language, language_code, is_generated, translation_languages):
348
+ """
349
+ You probably don't want to initialize this directly. Usually you'll access Transcript objects using a
350
+ TranscriptList.
351
+
352
+ :param http_client: http client which is used to make the transcript retrieving http calls
353
+ :type http_client: requests.Session
354
+ :param video_id: the id of the video this TranscriptList is for
355
+ :type video_id: str
356
+ :param url: the url which needs to be called to fetch the transcript
357
+ :param language: the name of the language this transcript uses
358
+ :param language_code:
359
+ :param is_generated:
360
+ :param translation_languages:
361
+ """
362
+ self._http_client = http_client
363
+ self.video_id = video_id
364
+ self._url = url
365
+ self.language = language
366
+ self.language_code = language_code
367
+ self.is_generated = is_generated
368
+ self.translation_languages = translation_languages
369
+ self._translation_languages_dict = {
370
+ translation_language['language_code']: translation_language['language']
371
+ for translation_language in translation_languages
372
+ }
373
+
374
+ def fetch(self, preserve_formatting=False):
375
+ """
376
+ Loads the actual transcript data.
377
+ :param preserve_formatting: whether to keep select HTML text formatting
378
+ :type preserve_formatting: bool
379
+ :return: a list of dictionaries containing the 'text', 'start' and 'duration' keys
380
+ :rtype [{'text': str, 'start': float, 'end': float}]:
381
+ """
382
+ response = self._http_client.get(self._url, headers={'Accept-Language': 'en-US'})
383
+ return _TranscriptParser(preserve_formatting=preserve_formatting).parse(
384
+ _raise_http_errors(response, self.video_id).text,
385
+ )
386
+
387
+ def __str__(self):
388
+ return '{language_code} ("{language}"){translation_description}'.format(
389
+ language=self.language,
390
+ language_code=self.language_code,
391
+ translation_description='[TRANSLATABLE]' if self.is_translatable else ''
392
+ )
393
+
394
+ @property
395
+ def is_translatable(self):
396
+ return len(self.translation_languages) > 0
397
+
398
+ def translate(self, language_code):
399
+ if not self.is_translatable:
400
+ raise NotTranslatableError(self.video_id)
401
+
402
+ if language_code not in self._translation_languages_dict:
403
+ raise TranslationLanguageNotAvailableError(self.video_id)
404
+
405
+ return Transcript(
406
+ self._http_client,
407
+ self.video_id,
408
+ '{url}&tlang={language_code}'.format(url=self._url, language_code=language_code),
409
+ self._translation_languages_dict[language_code],
410
+ language_code,
411
+ True,
412
+ [],
413
+ )
414
+
415
+
416
+ class _TranscriptParser(object):
417
+ _FORMATTING_TAGS = [
418
+ 'strong', # important
419
+ 'em', # emphasized
420
+ 'b', # bold
421
+ 'i', # italic
422
+ 'mark', # marked
423
+ 'small', # smaller
424
+ 'del', # deleted
425
+ 'ins', # inserted
426
+ 'sub', # subscript
427
+ 'sup', # superscript
428
+ ]
429
+
430
+ def __init__(self, preserve_formatting=False):
431
+ self._html_regex = self._get_html_regex(preserve_formatting)
432
+
433
+ def _get_html_regex(self, preserve_formatting):
434
+ if preserve_formatting:
435
+ formats_regex = '|'.join(self._FORMATTING_TAGS)
436
+ formats_regex = r'<\/?(?!\/?(' + formats_regex + r')\b).*?\b>'
437
+ html_regex = re.compile(formats_regex, re.IGNORECASE)
438
+ else:
439
+ html_regex = re.compile(r'<[^>]*>', re.IGNORECASE)
440
+ return html_regex
441
+
442
+ def parse(self, plain_data):
443
+ return [
444
+ {
445
+ 'text': re.sub(self._html_regex, '', unescape(xml_element.text)),
446
+ 'start': float(xml_element.attrib['start']),
447
+ 'duration': float(xml_element.attrib.get('dur', '0.0')),
448
+ }
449
+ for xml_element in ElementTree.fromstring(plain_data)
450
+ if xml_element.text is not None
451
+ ]
452
+
453
+ WATCH_URL = 'https://www.youtube.com/watch?v={video_id}'
454
+
455
+ class transcriber(object):
456
+ @classmethod
457
+ def list_transcripts(cls, video_id, proxies=None, cookies=None):
458
+ with requests.Session() as http_client:
459
+ if cookies:
460
+ http_client.cookies = cls._load_cookies(cookies, video_id)
461
+ http_client.proxies = proxies if proxies else {}
462
+ return TranscriptListFetcher(http_client).fetch(video_id)
463
+
464
+ @classmethod
465
+ def get_transcripts(cls, video_ids, languages=('en',), continue_after_error=False, proxies=None,
466
+ cookies=None, preserve_formatting=False):
467
+
468
+ assert isinstance(video_ids, list), "`video_ids` must be a list of strings"
469
+
470
+ data = {}
471
+ unretrievable_videos = []
472
+
473
+ for video_id in video_ids:
474
+ try:
475
+ data[video_id] = cls.get_transcript(video_id, languages, proxies, cookies, preserve_formatting)
476
+ except Exception as exception:
477
+ if not continue_after_error:
478
+ raise exception
479
+
480
+ unretrievable_videos.append(video_id)
481
+
482
+ return data, unretrievable_videos
483
+
484
+ @classmethod
485
+ def get_transcript(cls, video_id, languages=('en',), proxies=None, cookies=None, preserve_formatting=False):
486
+ assert isinstance(video_id, str), "`video_id` must be a string"
487
+ return cls.list_transcripts(video_id, proxies, cookies).find_transcript(languages).fetch(preserve_formatting=preserve_formatting)
488
+
489
+ @classmethod
490
+ def _load_cookies(cls, cookies, video_id):
491
+ try:
492
+ cookie_jar = cookiejar.MozillaCookieJar()
493
+ cookie_jar.load(cookies)
494
+ if not cookie_jar:
495
+ raise CookiesInvalidError(video_id)
496
+ return cookie_jar
497
+ except:
498
+ raise CookiePathInvalidError(video_id)
webscout/version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version__ = "1.2.4"
1
+ __version__ = "1.2.7"
2
2
 
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: webscout
3
- Version: 1.2.4
4
- Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
3
+ Version: 1.2.6
4
+ Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
5
5
  Author: OEvortex
6
6
  Author-email: helpingai5@gmail.com
7
7
  License: HelpingAI Simplified Universal License
@@ -45,7 +45,6 @@ Requires-Dist: sse-starlette
45
45
  Requires-Dist: termcolor
46
46
  Requires-Dist: tiktoken
47
47
  Requires-Dist: tldextract
48
- Requires-Dist: gpt4all
49
48
  Requires-Dist: orjson
50
49
  Provides-Extra: dev
51
50
  Requires-Dist: ruff >=0.1.6 ; extra == 'dev'
@@ -57,8 +56,7 @@ Requires-Dist: pytest >=7.4.2 ; extra == 'dev'
57
56
  <a href="#"><img alt="Python version" src="https://img.shields.io/pypi/pyversions/webscout"/></a>
58
57
  <a href="https://pepy.tech/project/webscout"><img alt="Downloads" src="https://static.pepy.tech/badge/webscout"></a>
59
58
 
60
- Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
61
- Also containes AI models that you can use
59
+ Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
62
60
 
63
61
 
64
62
  ## Table of Contents
@@ -69,6 +67,7 @@ Also containes AI models that you can use
69
67
  - [CLI version of webscout.AI](#cli-version-of-webscoutai)
70
68
  - [CLI to use LLM](#cli-to-use-llm)
71
69
  - [Regions](#regions)
70
+ - [Transcriber](#transcriber)
72
71
  - [DeepWEBS: Advanced Web Searches](#deepwebs-advanced-web-searches)
73
72
  - [Activating DeepWEBS](#activating-deepwebs)
74
73
  - [Point to remember before using `DeepWEBS`](#point-to-remember-before-using-deepwebs)
@@ -94,7 +93,7 @@ Also containes AI models that you can use
94
93
  - [6. `BlackBox` - Search/chat With BlackBox](#6-blackbox---searchchat-with-blackbox)
95
94
  - [7. `PERPLEXITY` - Search With PERPLEXITY](#7-perplexity---search-with-perplexity)
96
95
  - [8. `OpenGPT` - chat With OPENGPT](#8-opengpt---chat-with-opengpt)
97
- - [9. `GPT4ALL` - chat offline with Language models using gpt4all from webscout](#9-gpt4all---chat-offline-with-language-models-using-gpt4all-from-webscout)
96
+ - [9. `KOBOLDIA` -](#9-koboldia--)
98
97
  - [usage of special .LLM file from webscout (webscout.LLM)](#usage-of-special-llm-file-from-webscout-webscoutllm)
99
98
  - [`LLM`](#llm)
100
99
 
@@ -219,7 +218,55 @@ ___
219
218
  [Go To TOP](#TOP)
220
219
 
221
220
 
221
+ ## Transcriber
222
+ The transcriber function in webscout is a handy tool that transcribes YouTube videos. Here's an example code demonstrating its usage:
223
+ ```python
224
+ import sys
225
+ from webscout import transcriber
226
+
227
+ def extract_transcript(video_id):
228
+ """Extracts the transcript from a YouTube video."""
229
+ try:
230
+ transcript_list = transcriber.list_transcripts(video_id)
231
+ for transcript in transcript_list:
232
+ transcript_text_list = transcript.fetch()
233
+ lang = transcript.language
234
+ transcript_text = ""
235
+ if transcript.language_code == 'en':
236
+ for line in transcript_text_list:
237
+ transcript_text += " " + line["text"]
238
+ return transcript_text
239
+ elif transcript.is_translatable:
240
+ english_transcript_list = transcript.translate('en').fetch()
241
+ for line in english_transcript_list:
242
+ transcript_text += " " + line["text"]
243
+ return transcript_text
244
+ print("Transcript extraction failed. Please check the video URL.")
245
+ except Exception as e:
246
+ print(f"Error: {e}")
222
247
 
248
+ def main():
249
+ video_url = input("Enter the video link: ")
250
+
251
+ if video_url:
252
+ video_id = video_url.split("=")[1]
253
+ print("Video URL:", video_url)
254
+ submit = input("Press 'Enter' to get the transcript or type 'exit' to quit: ")
255
+ if submit == '':
256
+ print("Extracting Transcript...")
257
+ transcript = extract_transcript(video_id)
258
+ print('Transcript:')
259
+ print(transcript)
260
+ print("__________________________________________________________________________________")
261
+ elif submit.lower() == 'exit':
262
+ print("Exiting...")
263
+ sys.exit()
264
+ else:
265
+ print("Invalid input. Please try again.")
266
+
267
+ if __name__ == "__main__":
268
+ main()
269
+ ```
223
270
  ## DeepWEBS: Advanced Web Searches
224
271
 
225
272
  `DeepWEBS` is a standalone feature designed to perform advanced web searches with enhanced capabilities. It is particularly powerful in extracting relevant information directly from webpages and Search engine, focusing exclusively on text (web) searches. Unlike the `WEBS` , which provides a broader range of search functionalities, `DeepWEBS` is specifically tailored for in-depth web searches.
@@ -608,36 +655,23 @@ prompt = "tell me about india"
608
655
  response_str = opengpt.chat(prompt)
609
656
  print(response_str)
610
657
  ```
611
- ### 9. `GPT4ALL` - chat offline with Language models using gpt4all from webscout
658
+ ### 9. `KOBOLDIA` -
612
659
  ```python
613
- from webscout import GPT4ALL
660
+ from webscout.AI import KOBOLDAI
614
661
 
615
- # Initialize the GPT4ALL class with your model path and other optional parameters
616
- gpt4all_instance = GPT4ALL(
617
- model="path/to/your/model/file", # Replace with the actual path to your model file
618
- is_conversation=True,
619
- max_tokens=800,
620
- temperature=0.7,
621
- presence_penalty=0,
622
- frequency_penalty=1.18,
623
- top_p=0.4,
624
- intro="Hello, how can I assist you today?",
625
- filepath="path/to/conversation/history/file", # Optional, for conversation history
626
- update_file=True,
627
- history_offset=10250,
628
- act=None # Optional, for using an awesome prompt as intro
629
- )
662
+ # Instantiate the KOBOLDAI class with default parameters
663
+ koboldai = KOBOLDAI()
630
664
 
631
- # Generate a response from the AI model
632
- response = gpt4all_instance.chat(
633
- prompt="What is the weather like today?",
634
- stream=False, # Set to True if you want to stream the response
635
- optimizer=None, # Optional, specify an optimizer if needed
636
- conversationally=False # Set to True for conversationally generated responses
637
- )
665
+ # Define a prompt to send to the AI
666
+ prompt = "What is the capital of France?"
667
+
668
+ # Use the 'ask' method to get a response from the AI
669
+ response = koboldai.ask(prompt)
670
+
671
+ # Extract and print the message from the response
672
+ message = koboldai.get_message(response)
673
+ print(message)
638
674
 
639
- # Print the generated response
640
- print(response)
641
675
  ```
642
676
 
643
677
  ## usage of special .LLM file from webscout (webscout.LLM)
@@ -10,25 +10,25 @@ DeepWEBS/networks/webpage_fetcher.py,sha256=d5paDTB3wa_w6YWmLV7RkpAj8Lh8ztuUuyfe
10
10
  DeepWEBS/utilsdw/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  DeepWEBS/utilsdw/enver.py,sha256=vstxg_5P3Rwo1en6oPcuc2SBiATJqxi4C7meGmw5w0M,1754
12
12
  DeepWEBS/utilsdw/logger.py,sha256=Z0nFUcEGyU8r28yKiIyvEtO26xxpmJgbvNToTfwZecc,8174
13
- webscout/AI.py,sha256=CwUCeGnNRL9STd5bAZSyIiLysorBMu065HrkY8UCzAQ,49618
13
+ webscout/AI.py,sha256=WYi-JbbiXtQM14juJ-WgsahgQEEb7U82YElDX9TfHAI,57985
14
14
  webscout/AIbase.py,sha256=vQi2ougu5bG-QdmoYmxCQsOg7KTEgG7EF6nZh5qqUGw,2343
15
- webscout/AIutel.py,sha256=cvsuw57hq3GirAiT-PjqwhAiLPf1urOzDb2szJ4bwmo,24124
15
+ webscout/AIutel.py,sha256=fNN4mmjXcxjJGq2CVJP1MU2oQ78p8OyExQBjVif6e-k,24123
16
16
  webscout/DWEBS.py,sha256=QT-7-dUgWhQ_H7EVZD53AVyXxyskoPMKCkFIpzkN56Q,7332
17
17
  webscout/HelpingAI.py,sha256=YeZw0zYVHMcBFFPNdd3_Ghpm9ebt_EScQjHO_IIs4lg,8103
18
18
  webscout/LLM.py,sha256=XByJPiATLA_57FBWKw18Xx_PGRCPOj-GJE96aQH1k2Y,3309
19
- webscout/__init__.py,sha256=auv4OtSXPzH_Bcocya1179UvX4CTLmUqVg3cVXszjaA,457
19
+ webscout/__init__.py,sha256=qp-sVvWjKW-GRuvompu1arfDtARPr_G40ttfJk68dDo,547
20
20
  webscout/__main__.py,sha256=ZtTRgsRjUi2JOvYFLF1ZCh55Sdoz94I-BS-TlJC7WDU,126
21
21
  webscout/cli.py,sha256=F888fdrFUQgczMBN4yMOSf6Nh-IbvkqpPhDsbnA2FtQ,17059
22
22
  webscout/exceptions.py,sha256=4AOO5wexeL96nvUS-badcckcwrPS7UpZyAgB9vknHZE,276
23
23
  webscout/models.py,sha256=5iQIdtedT18YuTZ3npoG7kLMwcrKwhQ7928dl_7qZW0,692
24
- webscout/offlineAI.py,sha256=ieF9fQU-bWFZz5aBAQ8ZNxaCj1O1mI_w5AaAM9E3e8Y,7607
24
+ webscout/transcriber.py,sha256=LMYD1B3y48Gc_DFoDsv1K177yzBJEt40F2MfX9L2f9k,20232
25
25
  webscout/utils.py,sha256=c_98M4oqpb54pUun3fpGGlCerFD6ZHUbghyp5b7Mwgo,2605
26
- webscout/version.py,sha256=w3Y48JpCJLB-DvbXBfEkRgyEnrQoRiXGnyHDTl9pG5M,25
26
+ webscout/version.py,sha256=ew1ocUjDA6hjEFVQgKG7KIx8DxAerG_0lxIzujjDBsc,25
27
27
  webscout/webscout_search.py,sha256=3_lli-hDb8_kCGwscK29xuUcOS833ROgpNhDzrxh0dk,3085
28
28
  webscout/webscout_search_async.py,sha256=Y5frH0k3hLqBCR-8dn7a_b7EvxdYxn6wHiKl3jWosE0,40670
29
- webscout-1.2.4.dist-info/LICENSE.md,sha256=mRVwJuT4SXC5O93BFdsfWBjlXjGn2Np90Zm5SocUzM0,3150
30
- webscout-1.2.4.dist-info/METADATA,sha256=Zh6yfh9n8U_C2QZUYkpluwAk04H7Hj2bcsyd0EHfP9w,23100
31
- webscout-1.2.4.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
32
- webscout-1.2.4.dist-info/entry_points.txt,sha256=8-93eRslYrzTHs5E-6yFRJrve00C9q-SkXJD113jzRY,197
33
- webscout-1.2.4.dist-info/top_level.txt,sha256=OD5YKy6Y3hldL7SmuxsiEDxAG4LgdSSWwzYk22MF9fk,18
34
- webscout-1.2.4.dist-info/RECORD,,
29
+ webscout-1.2.6.dist-info/LICENSE.md,sha256=mRVwJuT4SXC5O93BFdsfWBjlXjGn2Np90Zm5SocUzM0,3150
30
+ webscout-1.2.6.dist-info/METADATA,sha256=zhXnNwF8vdiaqOLj2mrq-T_vPutgA5A8P7q05etlJ_o,24261
31
+ webscout-1.2.6.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
32
+ webscout-1.2.6.dist-info/entry_points.txt,sha256=8-93eRslYrzTHs5E-6yFRJrve00C9q-SkXJD113jzRY,197
33
+ webscout-1.2.6.dist-info/top_level.txt,sha256=OD5YKy6Y3hldL7SmuxsiEDxAG4LgdSSWwzYk22MF9fk,18
34
+ webscout-1.2.6.dist-info/RECORD,,
webscout/offlineAI.py DELETED
@@ -1,206 +0,0 @@
1
- from webscout.AIutel import Optimizers
2
- from webscout.AIutel import Conversation
3
- from webscout.AIutel import AwesomePrompts
4
- from webscout.AIbase import Provider
5
- from gpt4all import GPT4All
6
- from gpt4all.gpt4all import empty_chat_session
7
- from gpt4all.gpt4all import append_extension_if_missing
8
-
9
-
10
- import logging
11
-
12
- my_logger = logging.getLogger("gpt4all")
13
- my_logger.setLevel(logging.CRITICAL)
14
-
15
-
16
- class GPT4ALL(Provider):
17
- def __init__(
18
- self,
19
- model: str,
20
- is_conversation: bool = True,
21
- max_tokens: int = 800,
22
- temperature: float = 0.7,
23
- presence_penalty: int = 0,
24
- frequency_penalty: int = 1.18,
25
- top_p: float = 0.4,
26
- intro: str = None,
27
- filepath: str = None,
28
- update_file: bool = True,
29
- history_offset: int = 10250,
30
- act: str = None,
31
- ):
32
- """Instantiates GPT4ALL
33
-
34
- Args:
35
- model (str, optional): Path to LLM model (.gguf or .bin).
36
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
37
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 800.
38
- temperature (float, optional): Charge of the generated text's randomness. Defaults to 0.7.
39
- presence_penalty (int, optional): Chances of topic being repeated. Defaults to 0.
40
- frequency_penalty (int, optional): Chances of word being repeated. Defaults to 1.18.
41
- top_p (float, optional): Sampling threshold during inference time. Defaults to 0.4.
42
- intro (str, optional): Conversation introductory prompt. Defaults to None.
43
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
44
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
45
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
46
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
47
- """
48
- self.is_conversation = is_conversation
49
- self.max_tokens_to_sample = max_tokens
50
- self.model = model
51
- self.temperature = temperature
52
- self.presence_penalty = presence_penalty
53
- self.frequency_penalty = frequency_penalty
54
- self.top_p = top_p
55
- self.last_response = {}
56
-
57
- self.__available_optimizers = (
58
- method
59
- for method in dir(Optimizers)
60
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
61
- )
62
- Conversation.intro = (
63
- AwesomePrompts().get_act(
64
- act, raise_not_found=True, default=None, case_insensitive=True
65
- )
66
- if act
67
- else intro or Conversation.intro
68
- )
69
- self.conversation = Conversation(
70
- is_conversation, self.max_tokens_to_sample, filepath, update_file
71
- )
72
- self.conversation.history_offset = history_offset
73
-
74
- def get_model_name_path():
75
- import os
76
- from pathlib import Path
77
-
78
- initial_model_path = Path(append_extension_if_missing(model))
79
- if initial_model_path.exists:
80
- if not initial_model_path.is_absolute():
81
- initial_model_path = Path(os.getcwd()) / initial_model_path
82
- return os.path.split(initial_model_path.as_posix())
83
- else:
84
- raise FileNotFoundError(
85
- "File does not exist " + initial_model_path.as_posix()
86
- )
87
-
88
- model_dir, model_name = get_model_name_path()
89
-
90
- self.gpt4all = GPT4All(
91
- model_name=model_name,
92
- model_path=model_dir,
93
- allow_download=False,
94
- verbose=False,
95
- )
96
-
97
- def ask(
98
- self,
99
- prompt: str,
100
- stream: bool = False,
101
- raw: bool = False,
102
- optimizer: str = None,
103
- conversationally: bool = False,
104
- ) -> dict:
105
- """Chat with AI
106
-
107
- Args:
108
- prompt (str): Prompt to be send.
109
- stream (bool, optional): Flag for streaming response. Defaults to False.
110
- raw (bool, optional): Stream back raw response as received. Defaults to False.
111
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
112
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
113
- Returns:
114
- dict : {}
115
- ```json
116
- {
117
- "text" : "How may I help you today?"
118
- }
119
- ```
120
- """
121
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
122
- if optimizer:
123
- if optimizer in self.__available_optimizers:
124
- conversation_prompt = getattr(Optimizers, optimizer)(
125
- conversation_prompt if conversationally else prompt
126
- )
127
- else:
128
- raise Exception(
129
- f"Optimizer is not one of {self.__available_optimizers}"
130
- )
131
-
132
- def for_stream():
133
- response = self.gpt4all.generate(
134
- prompt=conversation_prompt,
135
- max_tokens=self.max_tokens_to_sample,
136
- temp=self.temperature,
137
- top_p=self.top_p,
138
- repeat_penalty=self.frequency_penalty,
139
- streaming=True,
140
- )
141
-
142
- message_load: str = ""
143
- for token in response:
144
- message_load += token
145
- resp: dict = dict(text=message_load)
146
- yield token if raw else resp
147
- self.last_response.update(resp)
148
-
149
- self.conversation.update_chat_history(
150
- prompt, self.get_message(self.last_response)
151
- )
152
- self.gpt4all.current_chat_session = empty_chat_session()
153
-
154
- def for_non_stream():
155
- for _ in for_stream():
156
- pass
157
- return self.last_response
158
-
159
- return for_stream() if stream else for_non_stream()
160
-
161
- def chat(
162
- self,
163
- prompt: str,
164
- stream: bool = False,
165
- optimizer: str = None,
166
- conversationally: bool = False,
167
- ) -> str:
168
- """Generate response `str`
169
- Args:
170
- prompt (str): Prompt to be send.
171
- stream (bool, optional): Flag for streaming response. Defaults to False.
172
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
173
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
174
- Returns:
175
- str: Response generated
176
- """
177
-
178
- def for_stream():
179
- for response in self.ask(
180
- prompt, True, optimizer=optimizer, conversationally=conversationally
181
- ):
182
- yield self.get_message(response)
183
-
184
- def for_non_stream():
185
- return self.get_message(
186
- self.ask(
187
- prompt,
188
- False,
189
- optimizer=optimizer,
190
- conversationally=conversationally,
191
- )
192
- )
193
-
194
- return for_stream() if stream else for_non_stream()
195
-
196
- def get_message(self, response: dict) -> str:
197
- """Retrieves message only from response
198
-
199
- Args:
200
- response (str): Response generated by `self.ask`
201
-
202
- Returns:
203
- str: Message extracted
204
- """
205
- assert isinstance(response, dict), "Response should be of dict data-type only"
206
- return response["text"]