webscout 4.6__py3-none-any.whl → 4.7__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.

@@ -44,6 +44,8 @@ from .Llama3 import *
44
44
  from .DARKAI import *
45
45
  from .koala import *
46
46
  from .RUBIKSAI import *
47
+ from .meta import *
48
+
47
49
  __all__ = [
48
50
  'ThinkAnyAI',
49
51
  'Xjai',
@@ -90,5 +92,6 @@ __all__ = [
90
92
  'LLAMA3',
91
93
  'DARKAI',
92
94
  'KOALA',
93
- 'RUBIKSAI'
95
+ 'RUBIKSAI',
96
+ 'Meta',
94
97
  ]
@@ -0,0 +1,778 @@
1
+ import json
2
+ import logging
3
+ import time
4
+ import urllib
5
+ import uuid
6
+ from typing import Dict, Generator, Iterator, List, Union
7
+
8
+ import random
9
+
10
+
11
+ from requests_html import HTMLSession
12
+ import requests
13
+ from bs4 import BeautifulSoup
14
+
15
+ import requests
16
+
17
+
18
+ from webscout.AIutel import Optimizers
19
+ from webscout.AIutel import Conversation
20
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
21
+ from webscout.AIbase import Provider
22
+ from webscout import exceptions
23
+
24
+ MAX_RETRIES = 3
25
+
26
+ def generate_offline_threading_id() -> str:
27
+ """
28
+ Generates an offline threading ID.
29
+
30
+ Returns:
31
+ str: The generated offline threading ID.
32
+ """
33
+ # Maximum value for a 64-bit integer in Python
34
+ max_int = (1 << 64) - 1
35
+ mask22_bits = (1 << 22) - 1
36
+
37
+ # Function to get the current timestamp in milliseconds
38
+ def get_current_timestamp():
39
+ return int(time.time() * 1000)
40
+
41
+ # Function to generate a random 64-bit integer
42
+ def get_random_64bit_int():
43
+ return random.getrandbits(64)
44
+
45
+ # Combine timestamp and random value
46
+ def combine_and_mask(timestamp, random_value):
47
+ shifted_timestamp = timestamp << 22
48
+ masked_random = random_value & mask22_bits
49
+ return (shifted_timestamp | masked_random) & max_int
50
+
51
+ timestamp = get_current_timestamp()
52
+ random_value = get_random_64bit_int()
53
+ threading_id = combine_and_mask(timestamp, random_value)
54
+
55
+ return str(threading_id)
56
+
57
+
58
+ def extract_value(text: str, start_str: str, end_str: str) -> str:
59
+ """
60
+ Helper function to extract a specific value from the given text using a key.
61
+
62
+ Args:
63
+ text (str): The text from which to extract the value.
64
+ start_str (str): The starting key.
65
+ end_str (str): The ending key.
66
+
67
+ Returns:
68
+ str: The extracted value.
69
+ """
70
+ start = text.find(start_str) + len(start_str)
71
+ end = text.find(end_str, start)
72
+ return text[start:end]
73
+
74
+
75
+ def format_response(response: dict) -> str:
76
+ """
77
+ Formats the response from Meta AI to remove unnecessary characters.
78
+
79
+ Args:
80
+ response (dict): The dictionnary containing the response to format.
81
+
82
+ Returns:
83
+ str: The formatted response.
84
+ """
85
+ text = ""
86
+ for content in (
87
+ response.get("data", {})
88
+ .get("node", {})
89
+ .get("bot_response_message", {})
90
+ .get("composed_text", {})
91
+ .get("content", [])
92
+ ):
93
+ text += content["text"] + "\n"
94
+ return text
95
+
96
+
97
+ # Function to perform the login
98
+ def get_fb_session(email, password, proxies=None):
99
+ login_url = "https://mbasic.facebook.com/login/"
100
+ headers = {
101
+ "authority": "mbasic.facebook.com",
102
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
103
+ "accept-language": "en-US,en;q=0.9",
104
+ "sec-ch-ua": '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
105
+ "sec-ch-ua-mobile": "?0",
106
+ "sec-ch-ua-platform": '"macOS"',
107
+ "sec-fetch-dest": "document",
108
+ "sec-fetch-mode": "navigate",
109
+ "sec-fetch-site": "none",
110
+ "sec-fetch-user": "?1",
111
+ "upgrade-insecure-requests": "1",
112
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
113
+ }
114
+ # Send the GET request
115
+ response = requests.get(login_url, headers=headers, proxies=proxies)
116
+ soup = BeautifulSoup(response.text, "html.parser")
117
+
118
+ # Parse necessary parameters from the login form
119
+ lsd = soup.find("input", {"name": "lsd"})["value"]
120
+ jazoest = soup.find("input", {"name": "jazoest"})["value"]
121
+ li = soup.find("input", {"name": "li"})["value"]
122
+ m_ts = soup.find("input", {"name": "m_ts"})["value"]
123
+
124
+ # Define the URL and body for the POST request to submit the login form
125
+ post_url = "https://mbasic.facebook.com/login/device-based/regular/login/?refsrc=deprecated&lwv=100"
126
+ data = {
127
+ "lsd": lsd,
128
+ "jazoest": jazoest,
129
+ "m_ts": m_ts,
130
+ "li": li,
131
+ "try_number": "0",
132
+ "unrecognized_tries": "0",
133
+ "email": email,
134
+ "pass": password,
135
+ "login": "Log In",
136
+ "bi_xrwh": "0",
137
+ }
138
+
139
+ headers = {
140
+ "authority": "mbasic.facebook.com",
141
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
142
+ "accept-language": "en-US,en;q=0.9",
143
+ "cache-control": "no-cache",
144
+ "content-type": "application/x-www-form-urlencoded",
145
+ "cookie": f"datr={response.cookies.get('datr')}; sb={response.cookies.get('sb')}; ps_n=1; ps_l=1",
146
+ "dpr": "2",
147
+ "origin": "https://mbasic.facebook.com",
148
+ "pragma": "no-cache",
149
+ "referer": "https://mbasic.facebook.com/login/",
150
+ "sec-fetch-site": "same-origin",
151
+ "sec-fetch-user": "?1",
152
+ "upgrade-insecure-requests": "1",
153
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
154
+ "viewport-width": "1728",
155
+ }
156
+
157
+ # Send the POST request
158
+ session = requests.session()
159
+ session.proxies = proxies
160
+
161
+ result = session.post(post_url, headers=headers, data=data)
162
+ if "sb" not in session.cookies:
163
+ raise exceptions.FacebookInvalidCredentialsException(
164
+ "Was not able to login to Facebook. Please check your credentials. "
165
+ "You may also have been rate limited. Try to connect to Facebook manually."
166
+ )
167
+
168
+ cookies = {
169
+ **result.cookies.get_dict(),
170
+ "sb": session.cookies["sb"],
171
+ "xs": session.cookies["xs"],
172
+ "fr": session.cookies["fr"],
173
+ "c_user": session.cookies["c_user"],
174
+ }
175
+
176
+ response_login = {
177
+ "cookies": cookies,
178
+ "headers": result.headers,
179
+ "response": response.text,
180
+ }
181
+ meta_ai_cookies = get_cookies()
182
+
183
+ url = "https://www.meta.ai/state/"
184
+
185
+ payload = f'__a=1&lsd={meta_ai_cookies["lsd"]}'
186
+ headers = {
187
+ "authority": "www.meta.ai",
188
+ "accept": "*/*",
189
+ "accept-language": "en-US,en;q=0.9",
190
+ "cache-control": "no-cache",
191
+ "content-type": "application/x-www-form-urlencoded",
192
+ "cookie": f'ps_n=1; ps_l=1; dpr=2; _js_datr={meta_ai_cookies["_js_datr"]}; abra_csrf={meta_ai_cookies["abra_csrf"]}; datr={meta_ai_cookies["datr"]};; ps_l=1; ps_n=1',
193
+ "origin": "https://www.meta.ai",
194
+ "pragma": "no-cache",
195
+ "referer": "https://www.meta.ai/",
196
+ "sec-fetch-mode": "cors",
197
+ "sec-fetch-site": "same-origin",
198
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
199
+ }
200
+
201
+ response = requests.request("POST", url, headers=headers, data=payload, proxies=proxies)
202
+
203
+ state = extract_value(response.text, start_str='"state":"', end_str='"')
204
+
205
+ url = f"https://www.facebook.com/oidc/?app_id=1358015658191005&scope=openid%20linking&response_type=code&redirect_uri=https%3A%2F%2Fwww.meta.ai%2Fauth%2F&no_universal_links=1&deoia=1&state={state}"
206
+ payload = {}
207
+ headers = {
208
+ "authority": "www.facebook.com",
209
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
210
+ "accept-language": "en-US,en;q=0.9",
211
+ "cache-control": "no-cache",
212
+ "cookie": f"datr={response_login['cookies']['datr']}; sb={response_login['cookies']['sb']}; c_user={response_login['cookies']['c_user']}; xs={response_login['cookies']['xs']}; fr={response_login['cookies']['fr']}; m_page_voice={response_login['cookies']['m_page_voice']}; abra_csrf={meta_ai_cookies['abra_csrf']};",
213
+ "sec-fetch-dest": "document",
214
+ "sec-fetch-mode": "navigate",
215
+ "sec-fetch-site": "cross-site",
216
+ "sec-fetch-user": "?1",
217
+ "upgrade-insecure-requests": "1",
218
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
219
+ }
220
+ session = requests.session()
221
+ session.proxies = proxies
222
+ response = session.get(url, headers=headers, data=payload, allow_redirects=False)
223
+
224
+ next_url = response.headers["Location"]
225
+
226
+ url = next_url
227
+
228
+ payload = {}
229
+ headers = {
230
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:125.0) Gecko/20100101 Firefox/125.0",
231
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
232
+ "Accept-Language": "en-US,en;q=0.5",
233
+ "Accept-Encoding": "gzip, deflate, br",
234
+ "Referer": "https://www.meta.ai/",
235
+ "Connection": "keep-alive",
236
+ "Cookie": f'dpr=2; abra_csrf={meta_ai_cookies["abra_csrf"]}; datr={meta_ai_cookies["_js_datr"]}',
237
+ "Upgrade-Insecure-Requests": "1",
238
+ "Sec-Fetch-Dest": "document",
239
+ "Sec-Fetch-Mode": "navigate",
240
+ "Sec-Fetch-Site": "cross-site",
241
+ "Sec-Fetch-User": "?1",
242
+ "TE": "trailers",
243
+ }
244
+ session.get(url, headers=headers, data=payload)
245
+ cookies = session.cookies.get_dict()
246
+ if "abra_sess" not in cookies:
247
+ raise exceptions.FacebookInvalidCredentialsException(
248
+ "Was not able to login to Facebook. Please check your credentials. "
249
+ "You may also have been rate limited. Try to connect to Facebook manually."
250
+ )
251
+ logging.info("Successfully logged in to Facebook.")
252
+ return cookies
253
+
254
+
255
+ def get_cookies() -> dict:
256
+ """
257
+ Extracts necessary cookies from the Meta AI main page.
258
+
259
+ Returns:
260
+ dict: A dictionary containing essential cookies.
261
+ """
262
+ session = HTMLSession()
263
+ response = session.get("https://www.meta.ai/")
264
+ return {
265
+ "_js_datr": extract_value(
266
+ response.text, start_str='_js_datr":{"value":"', end_str='",'
267
+ ),
268
+ "abra_csrf": extract_value(
269
+ response.text, start_str='abra_csrf":{"value":"', end_str='",'
270
+ ),
271
+ "datr": extract_value(
272
+ response.text, start_str='datr":{"value":"', end_str='",'
273
+ ),
274
+ "lsd": extract_value(
275
+ response.text, start_str='"LSD",[],{"token":"', end_str='"}'
276
+ ),
277
+ }
278
+ class Meta(Provider):
279
+ """
280
+ A class to interact with the Meta AI API to obtain and use access tokens for sending
281
+ and receiving messages from the Meta AI Chat API.
282
+ """
283
+
284
+ def __init__(
285
+ self,
286
+ fb_email: str = None,
287
+ fb_password: str = None,
288
+ proxy: dict = None,
289
+ is_conversation: bool = True,
290
+ max_tokens: int = 600,
291
+ timeout: int = 30,
292
+ intro: str = None,
293
+ filepath: str = None,
294
+ update_file: bool = True,
295
+ proxies: dict = {},
296
+ history_offset: int = 10250,
297
+ act: str = None,
298
+ ):
299
+ """
300
+ Initializes the Meta AI API with given parameters.
301
+
302
+ Args:
303
+ fb_email (str, optional): Your Facebook email address. Defaults to None.
304
+ fb_password (str, optional): Your Facebook password. Defaults to None.
305
+ proxy (dict, optional): Proxy settings for requests. Defaults to None.
306
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
307
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
308
+ timeout (int, optional): Http request timeout. Defaults to 30.
309
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
310
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
311
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
312
+ proxies (dict, optional): Http request proxies. Defaults to {}.
313
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
314
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
315
+ """
316
+ self.session = requests.Session()
317
+ self.session.headers.update(
318
+ {
319
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
320
+ "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
321
+ }
322
+ )
323
+ self.access_token = None
324
+ self.fb_email = fb_email
325
+ self.fb_password = fb_password
326
+ self.proxy = proxy
327
+ if self.proxy and not self.check_proxy():
328
+ raise ConnectionError(
329
+ "Unable to connect to proxy. Please check your proxy settings."
330
+ )
331
+ self.is_conversation = is_conversation
332
+ self.max_tokens_to_sample = max_tokens
333
+ self.timeout = timeout
334
+ self.last_response = {}
335
+ self.is_authed = fb_password is not None and fb_email is not None
336
+ self.cookies = self.get_cookies()
337
+ self.external_conversation_id = None
338
+ self.offline_threading_id = None
339
+
340
+ self.__available_optimizers = (
341
+ method
342
+ for method in dir(Optimizers)
343
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
344
+ )
345
+ Conversation.intro = (
346
+ AwesomePrompts().get_act(
347
+ act, raise_not_found=True, default=None, case_insensitive=True
348
+ )
349
+ if act
350
+ else intro or Conversation.intro
351
+ )
352
+ self.conversation = Conversation(
353
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
354
+ )
355
+ self.conversation.history_offset = history_offset
356
+ self.session.proxies = proxies
357
+
358
+ def check_proxy(self, test_url: str = "https://api.ipify.org/?format=json") -> bool:
359
+ """
360
+ Checks the proxy connection by making a request to a test URL.
361
+
362
+ Args:
363
+ test_url (str): A test site from which we check that the proxy is installed correctly.
364
+
365
+ Returns:
366
+ bool: True if the proxy is working, False otherwise.
367
+ """
368
+ try:
369
+ response = self.session.get(test_url, proxies=self.proxy, timeout=10)
370
+ if response.status_code == 200:
371
+ self.session.proxies = self.proxy
372
+ return True
373
+ return False
374
+ except requests.RequestException:
375
+ return False
376
+
377
+ def get_access_token(self) -> str:
378
+ """
379
+ Retrieves an access token using Meta's authentication API.
380
+
381
+ Returns:
382
+ str: A valid access token.
383
+ """
384
+
385
+ if self.access_token:
386
+ return self.access_token
387
+
388
+ url = "https://www.meta.ai/api/graphql/"
389
+ payload = {
390
+ "lsd": self.cookies["lsd"],
391
+ "fb_api_caller_class": "RelayModern",
392
+ "fb_api_req_friendly_name": "useAbraAcceptTOSForTempUserMutation",
393
+ "variables": {
394
+ "dob": "1999-01-01",
395
+ "icebreaker_type": "TEXT",
396
+ "__relay_internal__pv__WebPixelRatiorelayprovider": 1,
397
+ },
398
+ "doc_id": "7604648749596940",
399
+ }
400
+ payload = urllib.parse.urlencode(payload) # noqa
401
+ headers = {
402
+ "content-type": "application/x-www-form-urlencoded",
403
+ "cookie": f'_js_datr={self.cookies["_js_datr"]}; '
404
+ f'abra_csrf={self.cookies["abra_csrf"]}; datr={self.cookies["datr"]};',
405
+ "sec-fetch-site": "same-origin",
406
+ "x-fb-friendly-name": "useAbraAcceptTOSForTempUserMutation",
407
+ }
408
+
409
+ response = self.session.post(url, headers=headers, data=payload)
410
+
411
+ try:
412
+ auth_json = response.json()
413
+ except json.JSONDecodeError:
414
+ raise exceptions.FacebookRegionBlocked(
415
+ "Unable to receive a valid response from Meta AI. This is likely due to your region being blocked. "
416
+ "Try manually accessing https://www.meta.ai/ to confirm."
417
+ )
418
+
419
+ access_token = auth_json["data"]["xab_abra_accept_terms_of_service"][
420
+ "new_temp_user_auth"
421
+ ]["access_token"]
422
+
423
+ # Need to sleep for a bit, for some reason the API doesn't like it when we send request too quickly
424
+ # (maybe Meta needs to register Cookies on their side?)
425
+ time.sleep(1)
426
+
427
+ return access_token
428
+
429
+ def ask(
430
+ self,
431
+ prompt: str,
432
+ stream: bool = False,
433
+ raw: bool = False,
434
+ optimizer: str = None,
435
+ conversationally: bool = False,
436
+ ) -> Union[Dict, Generator[Dict, None, None]]:
437
+ """
438
+ Sends a message to the Meta AI and returns the response.
439
+
440
+ Args:
441
+ prompt (str): The prompt to send.
442
+ stream (bool): Whether to stream the response or not. Defaults to False.
443
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
444
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
445
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
446
+ Returns:
447
+ Union[Dict, Generator[Dict, None, None]]: A dictionary containing the response message and sources, or a generator yielding such dictionaries.
448
+ """
449
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
450
+ if optimizer:
451
+ if optimizer in self.__available_optimizers:
452
+ conversation_prompt = getattr(Optimizers, optimizer)(
453
+ conversation_prompt if conversationally else prompt
454
+ )
455
+ else:
456
+ raise Exception(
457
+ f"Optimizer is not one of {self.__available_optimizers}"
458
+ )
459
+
460
+ if not self.is_authed:
461
+ self.access_token = self.get_access_token()
462
+ auth_payload = {"access_token": self.access_token}
463
+ url = "https://graph.meta.ai/graphql?locale=user"
464
+
465
+ else:
466
+ auth_payload = {"fb_dtsg": self.cookies["fb_dtsg"]}
467
+ url = "https://www.meta.ai/api/graphql/"
468
+
469
+ if not self.external_conversation_id:
470
+ external_id = str(uuid.uuid4())
471
+ self.external_conversation_id = external_id
472
+ payload = {
473
+ **auth_payload,
474
+ "fb_api_caller_class": "RelayModern",
475
+ "fb_api_req_friendly_name": "useAbraSendMessageMutation",
476
+ "variables": json.dumps(
477
+ {
478
+ "message": {"sensitive_string_value": conversation_prompt},
479
+ "externalConversationId": self.external_conversation_id,
480
+ "offlineThreadingId": generate_offline_threading_id(),
481
+ "suggestedPromptIndex": None,
482
+ "flashVideoRecapInput": {"images": []},
483
+ "flashPreviewInput": None,
484
+ "promptPrefix": None,
485
+ "entrypoint": "ABRA__CHAT__TEXT",
486
+ "icebreaker_type": "TEXT",
487
+ "__relay_internal__pv__AbraDebugDevOnlyrelayprovider": False,
488
+ "__relay_internal__pv__WebPixelRatiorelayprovider": 1,
489
+ }
490
+ ),
491
+ "server_timestamps": "true",
492
+ "doc_id": "7783822248314888",
493
+ }
494
+ payload = urllib.parse.urlencode(payload) # noqa
495
+ headers = {
496
+ "content-type": "application/x-www-form-urlencoded",
497
+ "x-fb-friendly-name": "useAbraSendMessageMutation",
498
+ }
499
+ if self.is_authed:
500
+ headers["cookie"] = f'abra_sess={self.cookies["abra_sess"]}'
501
+ # Recreate the session to avoid cookie leakage when user is authenticated
502
+ self.session = requests.Session()
503
+ self.session.proxies = self.proxy
504
+
505
+ if stream:
506
+
507
+ def for_stream():
508
+ response = self.session.post(
509
+ url, headers=headers, data=payload, stream=True, timeout=self.timeout
510
+ )
511
+ if not response.ok:
512
+ raise exceptions.FailedToGenerateResponseError(
513
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
514
+ )
515
+
516
+ lines = response.iter_lines()
517
+ is_error = json.loads(next(lines))
518
+ if len(is_error.get("errors", [])) > 0:
519
+ raise exceptions.FailedToGenerateResponseError(
520
+ f"Failed to generate response - {response.text}"
521
+ )
522
+ for line in lines:
523
+ if line:
524
+ json_line = json.loads(line)
525
+ extracted_data = self.extract_data(json_line)
526
+ if not extracted_data.get("message"):
527
+ continue
528
+ self.last_response.update(extracted_data)
529
+ yield line if raw else extracted_data
530
+ self.conversation.update_chat_history(
531
+ prompt, self.get_message(self.last_response)
532
+ )
533
+
534
+ return for_stream()
535
+ else:
536
+ response = self.session.post(
537
+ url, headers=headers, data=payload, timeout=self.timeout
538
+ )
539
+ if not response.ok:
540
+ raise exceptions.FailedToGenerateResponseError(
541
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
542
+ )
543
+ raw_response = response.text
544
+ last_streamed_response = self.extract_last_response(raw_response)
545
+ if not last_streamed_response:
546
+ raise exceptions.FailedToGenerateResponseError(
547
+ f"Failed to generate response - {response.text}"
548
+ )
549
+
550
+ extracted_data = self.extract_data(last_streamed_response)
551
+ self.last_response.update(extracted_data)
552
+ self.conversation.update_chat_history(
553
+ prompt, self.get_message(self.last_response)
554
+ )
555
+ return extracted_data
556
+
557
+ def chat(
558
+ self,
559
+ prompt: str,
560
+ stream: bool = False,
561
+ optimizer: str = None,
562
+ conversationally: bool = False,
563
+ ) -> str:
564
+ """
565
+ Sends a message to the Meta AI and returns the response.
566
+
567
+ Args:
568
+ prompt (str): The message to send.
569
+ stream (bool): Whether to stream the response or not. Defaults to False.
570
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
571
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
572
+
573
+ Returns:
574
+ str: The response message.
575
+ """
576
+
577
+ def for_stream():
578
+ for response in self.ask(
579
+ prompt, True, optimizer=optimizer, conversationally=conversationally
580
+ ):
581
+ yield self.get_message(response)
582
+
583
+ def for_non_stream():
584
+ return self.get_message(
585
+ self.ask(
586
+ prompt,
587
+ False,
588
+ optimizer=optimizer,
589
+ conversationally=conversationally,
590
+ )
591
+ )
592
+
593
+ return for_stream() if stream else for_non_stream()
594
+
595
+ def extract_last_response(self, response: str) -> Dict:
596
+ """
597
+ Extracts the last response from the Meta AI API.
598
+
599
+ Args:
600
+ response (str): The response to extract the last response from.
601
+
602
+ Returns:
603
+ dict: A dictionary containing the last response.
604
+ """
605
+ last_streamed_response = None
606
+ for line in response.split("\n"):
607
+ try:
608
+ json_line = json.loads(line)
609
+ except json.JSONDecodeError:
610
+ continue
611
+
612
+ bot_response_message = (
613
+ json_line.get("data", {})
614
+ .get("node", {})
615
+ .get("bot_response_message", {})
616
+ )
617
+ chat_id = bot_response_message.get("id")
618
+ if chat_id:
619
+ external_conversation_id, offline_threading_id, _ = chat_id.split("_")
620
+ self.external_conversation_id = external_conversation_id
621
+ self.offline_threading_id = offline_threading_id
622
+
623
+ streaming_state = bot_response_message.get("streaming_state")
624
+ if streaming_state == "OVERALL_DONE":
625
+ last_streamed_response = json_line
626
+
627
+ return last_streamed_response
628
+
629
+ def extract_data(self, json_line: dict) -> Dict:
630
+ """
631
+ Extract data and sources from a parsed JSON line.
632
+
633
+ Args:
634
+ json_line (dict): Parsed JSON line.
635
+
636
+ Returns:
637
+ dict: A dictionary containing the response message, sources, and media.
638
+ """
639
+ bot_response_message = (
640
+ json_line.get("data", {}).get("node", {}).get("bot_response_message", {})
641
+ )
642
+ response = format_response(response=json_line)
643
+ fetch_id = bot_response_message.get("fetch_id")
644
+ sources = self.fetch_sources(fetch_id) if fetch_id else []
645
+ medias = self.extract_media(bot_response_message)
646
+ return {"message": response, "sources": sources, "media": medias}
647
+
648
+ def extract_media(self, json_line: dict) -> List[Dict]:
649
+ """
650
+ Extract media from a parsed JSON line.
651
+
652
+ Args:
653
+ json_line (dict): Parsed JSON line.
654
+
655
+ Returns:
656
+ list: A list of dictionaries containing the extracted media.
657
+ """
658
+ medias = []
659
+ imagine_card = json_line.get("imagine_card", {})
660
+ session = imagine_card.get("session", {}) if imagine_card else {}
661
+ media_sets = (
662
+ (json_line.get("imagine_card", {}).get("session", {}).get("media_sets", []))
663
+ if imagine_card and session
664
+ else []
665
+ )
666
+ for media_set in media_sets:
667
+ imagine_media = media_set.get("imagine_media", [])
668
+ for media in imagine_media:
669
+ medias.append(
670
+ {
671
+ "url": media.get("uri"),
672
+ "type": media.get("media_type"),
673
+ "prompt": media.get("prompt"),
674
+ }
675
+ )
676
+ return medias
677
+
678
+ def get_cookies(self) -> dict:
679
+ """
680
+ Extracts necessary cookies from the Meta AI main page.
681
+
682
+ Returns:
683
+ dict: A dictionary containing essential cookies.
684
+ """
685
+ session = HTMLSession()
686
+ headers = {}
687
+ if self.fb_email is not None and self.fb_password is not None:
688
+ fb_session = get_fb_session(self.fb_email, self.fb_password, self.proxy)
689
+ headers = {"cookie": f"abra_sess={fb_session['abra_sess']}"}
690
+ response = session.get(
691
+ "https://www.meta.ai/",
692
+ headers=headers,
693
+ proxies=self.proxy,
694
+ )
695
+ cookies = {
696
+ "_js_datr": extract_value(
697
+ response.text, start_str='_js_datr":{"value":"', end_str='",'
698
+ ),
699
+ "datr": extract_value(
700
+ response.text, start_str='datr":{"value":"', end_str='",'
701
+ ),
702
+ "lsd": extract_value(
703
+ response.text, start_str='"LSD",[],{"token":"', end_str='"}'
704
+ ),
705
+ "fb_dtsg": extract_value(
706
+ response.text, start_str='DTSGInitData",[],{"token":"', end_str='"'
707
+ ),
708
+ }
709
+
710
+ if len(headers) > 0:
711
+ cookies["abra_sess"] = fb_session["abra_sess"]
712
+ else:
713
+ cookies["abra_csrf"] = extract_value(
714
+ response.text, start_str='abra_csrf":{"value":"', end_str='",'
715
+ )
716
+ return cookies
717
+
718
+ def fetch_sources(self, fetch_id: str) -> List[Dict]:
719
+ """
720
+ Fetches sources from the Meta AI API based on the given query.
721
+
722
+ Args:
723
+ fetch_id (str): The fetch ID to use for the query.
724
+
725
+ Returns:
726
+ list: A list of dictionaries containing the fetched sources.
727
+ """
728
+
729
+ url = "https://graph.meta.ai/graphql?locale=user"
730
+ payload = {
731
+ "access_token": self.access_token,
732
+ "fb_api_caller_class": "RelayModern",
733
+ "fb_api_req_friendly_name": "AbraSearchPluginDialogQuery",
734
+ "variables": json.dumps({"abraMessageFetchID": fetch_id}),
735
+ "server_timestamps": "true",
736
+ "doc_id": "6946734308765963",
737
+ }
738
+
739
+ payload = urllib.parse.urlencode(payload) # noqa
740
+
741
+ headers = {
742
+ "authority": "graph.meta.ai",
743
+ "accept-language": "en-US,en;q=0.9,fr-FR;q=0.8,fr;q=0.7",
744
+ "content-type": "application/x-www-form-urlencoded",
745
+ "cookie": f'dpr=2; abra_csrf={self.cookies.get("abra_csrf")}; datr={self.cookies.get("datr")}; ps_n=1; ps_l=1',
746
+ "x-fb-friendly-name": "AbraSearchPluginDialogQuery",
747
+ }
748
+
749
+ response = self.session.post(url, headers=headers, data=payload)
750
+ response_json = response.json()
751
+ message = response_json.get("data", {}).get("message", {})
752
+ search_results = (
753
+ (response_json.get("data", {}).get("message", {}).get("searchResults"))
754
+ if message
755
+ else None
756
+ )
757
+ if search_results is None:
758
+ return []
759
+
760
+ references = search_results["references"]
761
+ return references
762
+
763
+ def get_message(self, response: dict) -> str:
764
+ """Retrieves message only from response
765
+
766
+ Args:
767
+ response (dict): Response generated by `self.ask`
768
+
769
+ Returns:
770
+ str: Message extracted
771
+ """
772
+ assert isinstance(response, dict), "Response should be of dict data-type only"
773
+ return response["message"]
774
+
775
+ if __name__ == "__main__":
776
+ Meta = Meta()
777
+ ai = Meta.chat(input(">>> "))
778
+ print(ai)
webscout/exceptions.py CHANGED
@@ -14,5 +14,11 @@ class FailedToGenerateResponseError(Exception):
14
14
  """Provider failed to fetch response"""
15
15
  class AllProvidersFailure(Exception):
16
16
  """None of the providers generated response successfully"""
17
+ pass
17
18
 
19
+ class FacebookInvalidCredentialsException(Exception):
20
+ pass
21
+
22
+
23
+ class FacebookRegionBlocked(Exception):
18
24
  pass
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: webscout
3
- Version: 4.6
3
+ Version: 4.7
4
4
  Summary: Search for anything using Google, DuckDuckGo, brave, qwant, phind.com, Contains AI models, can transcribe yt videos, temporary email and phone number generation, has TTS support, webai (terminal gpt and open interpreter) and offline LLMs and more
5
5
  Author: OEvortex
6
6
  Author-email: helpingai5@gmail.com
@@ -62,6 +62,7 @@ Requires-Dist: ollama
62
62
  Requires-Dist: pyfiglet
63
63
  Requires-Dist: yaspin
64
64
  Requires-Dist: pillow
65
+ Requires-Dist: requests-html
65
66
  Provides-Extra: dev
66
67
  Requires-Dist: ruff >=0.1.6 ; extra == 'dev'
67
68
  Requires-Dist: pytest >=7.4.2 ; extra == 'dev'
@@ -1176,55 +1177,36 @@ prompt = "Explain the concept of recursion in simple terms."
1176
1177
  response = perplexity.chat(prompt)
1177
1178
  print(response)
1178
1179
  ```
1179
- ### 8. `OpenGPT` - chat With OPENGPT
1180
+ ### 8. `meta ai` - chat With meta ai
1180
1181
  ```python
1181
- from webscout import OPENGPT
1182
+ from webscout import Meta
1183
+ from rich import print
1184
+ # **For unauthenticated usage**
1185
+ meta_ai = Meta()
1182
1186
 
1183
- opengpt = OPENGPT(is_conversation=True, max_tokens=8000, timeout=30, assistant_id="bca37014-6f97-4f2b-8928-81ea8d478d88")
1184
- while True:
1185
- # Prompt the user for input
1186
- prompt = input("Enter your prompt: ")
1187
- # Send the prompt to the OPENGPT model and print the response
1188
- response_str = opengpt.chat(prompt)
1189
- print(response_str)
1190
- ```
1191
- ```python
1192
- from webscout import OPENGPTv2
1193
-
1194
- # Initialize the bot with all specified settings
1195
- bot = OPENGPTv2(
1196
- generate_new_agents=True, # Set to True to generate new IDs, False to load from file
1197
- assistant_name="My Custom Assistant",
1198
- retrieval_description="Helpful information from my files.",
1199
- agent_system_message="",
1200
- enable_action_server=False, # Assuming you want to disable Action Server by Robocorp
1201
- enable_ddg_search=False, # Enable DuckDuckGo search tool
1202
- enable_arxiv=False, # Assuming you want to disable Arxiv
1203
- enable_press_releases=False, # Assuming you want to disable Press Releases (Kay.ai)
1204
- enable_pubmed=False, # Assuming you want to disable PubMed
1205
- enable_sec_filings=False, # Assuming you want to disable SEC Filings (Kay.ai)
1206
- enable_retrieval=False, # Assuming you want to disable Retrieval
1207
- enable_search_tavily=False, # Assuming you want to disable Search (Tavily)
1208
- enable_search_short_answer_tavily=False, # Assuming you want to disable Search (short answer, Tavily)
1209
- enable_you_com_search=True, # Assuming you want to disable You.com Search
1210
- enable_wikipedia=False, # Enable Wikipedia tool
1211
- is_public=True,
1212
- is_conversation=True,
1213
- max_tokens=800,
1214
- timeout=40,
1215
- filepath="opengpt_conversation_history.txt",
1216
- update_file=True,
1217
- history_offset=10250,
1218
- act=None,
1219
- )
1187
+ # Simple text prompt
1188
+ response = meta_ai.chat("What is the capital of France?")
1189
+ print(response)
1220
1190
 
1221
- # Example interaction loop
1222
- while True:
1223
- prompt = input("You: ")
1224
- if prompt.strip().lower() == 'exit':
1225
- break
1226
- response = bot.chat(prompt)
1227
- print(response)
1191
+ # Streaming response
1192
+ for chunk in meta_ai.chat("Tell me a story about a cat."):
1193
+ print(chunk, end="", flush=True)
1194
+
1195
+ # **For authenticated usage (including image generation)**
1196
+ fb_email = "abcd@abc.com"
1197
+ fb_password = "qwertfdsa"
1198
+ meta_ai = Meta(fb_email=fb_email, fb_password=fb_password)
1199
+
1200
+ # Text prompt with web search
1201
+ response = meta_ai.ask("what is currently happning in bangladesh in aug 2024")
1202
+ print(response["message"]) # Access the text message
1203
+ print("Sources:", response["sources"]) # Access sources (if any)
1204
+
1205
+ # Image generation
1206
+ response = meta_ai.ask("Create an image of a cat wearing a hat.")
1207
+ print(response["message"]) # Print the text message from the response
1208
+ for media in response["media"]:
1209
+ print(media["url"]) # Access image URLs
1228
1210
 
1229
1211
  ```
1230
1212
  ### 9. `KOBOLDAI` -
@@ -9,7 +9,7 @@ webscout/__init__.py,sha256=NK2atRuAg26zcT1g5bkwOwPDZyBbTud1mjbrDexjvhI,2282
9
9
  webscout/__main__.py,sha256=ZtTRgsRjUi2JOvYFLF1ZCh55Sdoz94I-BS-TlJC7WDU,126
10
10
  webscout/async_providers.py,sha256=MRj0klEhBYVQXnzZGG_15d0e-TPA0nOc2nn735H-wR4,622
11
11
  webscout/cli.py,sha256=RlBKeS9CSIsiBMqlzxevWtKjbY9htkZvA7J0bM_hHE8,14999
12
- webscout/exceptions.py,sha256=YtIs-vXBwcjbt9TZ_wB7yI0dO7ANYIZAmEEeLmoQ2fI,487
12
+ webscout/exceptions.py,sha256=GMeOdYqWKmuFU6Uq8MHKCInXQmJc7a_7AanKdyVcYTM,607
13
13
  webscout/g4f.py,sha256=NNcnlOtIWV9R93UsBN4jBGBEJ9sJ-Np1WbgjkGVDcYc,24487
14
14
  webscout/models.py,sha256=5iQIdtedT18YuTZ3npoG7kLMwcrKwhQ7928dl_7qZW0,692
15
15
  webscout/tempid.py,sha256=5oc3UbXhPGKxrMRTfRABT-V-dNzH_hOKWtLYM6iCWd4,5896
@@ -69,11 +69,12 @@ webscout/Provider/VTLchat.py,sha256=_sErGr-wOi16ZAfiGOo0bPsAEMkjzzwreEsIqjIZMIU,
69
69
  webscout/Provider/Xjai.py,sha256=BIlk2ouz9Kh_0Gg9hPvTqhI7XtcmWdg5vHSX_4uGrIs,9039
70
70
  webscout/Provider/Yepchat.py,sha256=2Eit-A7w1ph1GQKNQuur_yaDzI64r0yBGxCIjDefJxQ,19875
71
71
  webscout/Provider/Youchat.py,sha256=fhMpt94pIPE_XDbC4z9xyfgA7NbkNE2wlRFJabsjv90,8069
72
- webscout/Provider/__init__.py,sha256=MBOhedREt8-ic3CrNoq952u5ytMl6-Wa_MgtnQwx1QM,2204
72
+ webscout/Provider/__init__.py,sha256=oBdZqgg3oQQztSLF0kVS-kFF-Kr7J5IpFXBTJUR0vQI,2241
73
73
  webscout/Provider/koala.py,sha256=uBYJU_3YmC1qyCugDOrMSLoUR8my76zt_WqIUiGgf2Q,9840
74
- webscout-4.6.dist-info/LICENSE.md,sha256=9P0imsudI7MEvZe2pOcg8rKBn6E5FGHQ-riYozZI-Bk,2942
75
- webscout-4.6.dist-info/METADATA,sha256=lBjTpCHhckbEcAKYzIkW5ng5R8kgrpEIgJNM3uM42KE,57059
76
- webscout-4.6.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
77
- webscout-4.6.dist-info/entry_points.txt,sha256=Hh4YIIjvkqB9SVxZ2ri4DZUkgEu_WF_5_r_nZDIvfG8,73
78
- webscout-4.6.dist-info/top_level.txt,sha256=nYIw7OKBQDr_Z33IzZUKidRD3zQEo8jOJYkMVMeN334,9
79
- webscout-4.6.dist-info/RECORD,,
74
+ webscout/Provider/meta.py,sha256=vTJQtor91R5hrogCWOwiE422syjM-rFMn-s_8kURBnc,30664
75
+ webscout-4.7.dist-info/LICENSE.md,sha256=9P0imsudI7MEvZe2pOcg8rKBn6E5FGHQ-riYozZI-Bk,2942
76
+ webscout-4.7.dist-info/METADATA,sha256=stcOxQWhpH2_4NZlnIyJoY35MkSgjgEJuwn6JJIVdpU,56101
77
+ webscout-4.7.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
78
+ webscout-4.7.dist-info/entry_points.txt,sha256=Hh4YIIjvkqB9SVxZ2ri4DZUkgEu_WF_5_r_nZDIvfG8,73
79
+ webscout-4.7.dist-info/top_level.txt,sha256=nYIw7OKBQDr_Z33IzZUKidRD3zQEo8jOJYkMVMeN334,9
80
+ webscout-4.7.dist-info/RECORD,,
File without changes