webscout 5.1__py3-none-any.whl → 5.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.

@@ -0,0 +1,256 @@
1
+ import time
2
+ import uuid
3
+ from selenium import webdriver
4
+ from selenium.webdriver.chrome.options import Options
5
+ from selenium.webdriver.common.by import By
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.webdriver.support.ui import WebDriverWait
8
+ import click
9
+ import requests
10
+ from requests import get
11
+ from uuid import uuid4
12
+ from re import findall
13
+ from requests.exceptions import RequestException
14
+ from curl_cffi.requests import get, RequestsError
15
+ import g4f
16
+ from random import randint
17
+ from PIL import Image
18
+ import io
19
+ import re
20
+ import json
21
+ import yaml
22
+ from webscout.AIutel import Optimizers
23
+ from webscout.AIutel import Conversation
24
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
25
+ from webscout.AIbase import Provider, AsyncProvider
26
+ from webscout import exceptions
27
+ from typing import Any, AsyncGenerator, Dict
28
+ import logging
29
+ import httpx
30
+
31
+ class NetFly(Provider):
32
+ """
33
+ A class to interact with the NetFly API.
34
+ """
35
+
36
+ AVAILABLE_MODELS = ["gpt-3.5-turbo"]
37
+
38
+ def __init__(
39
+ self,
40
+ is_conversation: bool = True,
41
+ max_tokens: int = 600,
42
+ timeout: int = 30,
43
+ intro: str = None,
44
+ filepath: str = None,
45
+ update_file: bool = True,
46
+ proxies: dict = {},
47
+ history_offset: int = 10250,
48
+ act: str = None,
49
+ model: str = "gpt-3.5-turbo",
50
+ system_prompt: str = "You are a helpful and friendly AI assistant.",
51
+ ):
52
+ """
53
+ Initializes the NetFly API with given parameters.
54
+
55
+ Args:
56
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
57
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
58
+ timeout (int, optional): Http request timeout. Defaults to 30.
59
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
60
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
61
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
62
+ proxies (dict, optional): Http request proxies. Defaults to {}.
63
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
64
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
65
+ model (str, optional): AI model to use for text generation. Defaults to "gpt-3.5-turbo".
66
+ system_prompt (str, optional): System prompt for NetFly. Defaults to the provided string.
67
+ """
68
+ if model not in self.AVAILABLE_MODELS:
69
+ raise ValueError(f"Invalid model: {model}. Available model is: {self.AVAILABLE_MODELS[0]}")
70
+
71
+ self.session = requests.Session()
72
+ self.is_conversation = is_conversation
73
+ self.max_tokens_to_sample = max_tokens
74
+ self.api_endpoint = "https://free.netfly.top/api/openai/v1/chat/completions"
75
+ self.stream_chunk_size = 64
76
+ self.timeout = timeout
77
+ self.last_response = {}
78
+ self.model = model
79
+ self.system_prompt = system_prompt
80
+ self.headers = {
81
+ "accept": "application/json, text/event-stream",
82
+ "accept-encoding": "gzip, deflate, br, zstd",
83
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
84
+ "content-type": "application/json",
85
+ "dnt": "1",
86
+ "origin": "https://free.netfly.top",
87
+ "referer": "https://free.netfly.top/",
88
+ "sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
89
+ "sec-ch-ua-mobile": "?0",
90
+ "sec-ch-ua-platform": '"Windows"',
91
+ "sec-fetch-dest": "empty",
92
+ "sec-fetch-mode": "cors",
93
+ "sec-fetch-site": "same-origin",
94
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
95
+ }
96
+
97
+ self.__available_optimizers = (
98
+ method
99
+ for method in dir(Optimizers)
100
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
101
+ )
102
+ self.session.headers.update(self.headers)
103
+ Conversation.intro = (
104
+ AwesomePrompts().get_act(
105
+ act, raise_not_found=True, default=None, case_insensitive=True
106
+ )
107
+ if act
108
+ else intro or Conversation.intro
109
+ )
110
+ self.conversation = Conversation(
111
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
112
+ )
113
+ self.conversation.history_offset = history_offset
114
+ self.session.proxies = proxies
115
+
116
+ def ask(
117
+ self,
118
+ prompt: str,
119
+ stream: bool = False,
120
+ raw: bool = False,
121
+ optimizer: str = None,
122
+ conversationally: bool = False,
123
+ ) -> dict:
124
+ """Chat with AI
125
+
126
+ Args:
127
+ prompt (str): Prompt to be send.
128
+ stream (bool, optional): Whether to stream the response. Defaults to False.
129
+ raw (bool, optional): Whether to return the raw response. Defaults to False.
130
+ optimizer (str, optional): The name of the optimizer to use. Defaults to None.
131
+ conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
132
+
133
+ Returns:
134
+ The response from the API.
135
+ """
136
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
137
+ if optimizer:
138
+ if optimizer in self.__available_optimizers:
139
+ conversation_prompt = getattr(Optimizers, optimizer)(
140
+ conversation_prompt if conversationally else prompt
141
+ )
142
+ else:
143
+ raise Exception(
144
+ f"Optimizer is not one of {self.__available_optimizers}"
145
+ )
146
+
147
+ payload = {
148
+ "messages": [
149
+ {"role": "system", "content": self.system_prompt},
150
+ {"role": "user", "content": conversation_prompt},
151
+ ],
152
+ "stream": True,
153
+ "model": self.model,
154
+ "temperature": 0.5,
155
+ "presence_penalty": 0,
156
+ "frequency_penalty": 0,
157
+ "top_p": 1
158
+ }
159
+
160
+ def for_stream():
161
+ response = self.session.post(
162
+ self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
163
+ )
164
+
165
+ if not response.ok:
166
+ raise exceptions.FailedToGenerateResponseError(
167
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
168
+ )
169
+ buffer = ""
170
+ for line in response.iter_lines(decode_unicode=True):
171
+ if line:
172
+ if line.startswith("data: "):
173
+ json_data = line[6:]
174
+ if json_data == "[DONE]":
175
+ break
176
+ try:
177
+ data = json.loads(json_data)
178
+ # Check if 'content' key exists in 'delta' dictionary
179
+ if 'content' in data["choices"][0]["delta"]:
180
+ content = data["choices"][0]["delta"].get("content", "")
181
+ buffer += content
182
+ # Check for completion marker (period in this case)
183
+ if buffer.endswith(".") or buffer.endswith("\n"):
184
+ yield buffer if raw else dict(text=buffer)
185
+ buffer = "" # Clear the buffer
186
+ except json.decoder.JSONDecodeError:
187
+ continue
188
+
189
+ # Yield any remaining text in the buffer
190
+ if buffer:
191
+ yield buffer if raw else dict(text=buffer)
192
+
193
+ self.last_response.update(dict(text=buffer))
194
+ self.conversation.update_chat_history(
195
+ prompt, self.get_message(self.last_response)
196
+ )
197
+
198
+ def for_non_stream():
199
+ for _ in for_stream():
200
+ pass
201
+ return self.last_response
202
+
203
+ return for_stream() if stream else for_non_stream()
204
+
205
+ def chat(
206
+ self,
207
+ prompt: str,
208
+ stream: bool = False,
209
+ optimizer: str = None,
210
+ conversationally: bool = False,
211
+ ) -> str:
212
+ """Generate response `str`
213
+ Args:
214
+ prompt (str): Prompt to be send.
215
+ stream (bool, optional): Flag for streaming response. Defaults to False.
216
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
217
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
218
+ Returns:
219
+ str: Response generated
220
+ """
221
+
222
+ def for_stream():
223
+ for response in self.ask(
224
+ prompt, True, optimizer=optimizer, conversationally=conversationally
225
+ ):
226
+ yield self.get_message(response)
227
+
228
+ def for_non_stream():
229
+ return self.get_message(
230
+ self.ask(
231
+ prompt,
232
+ False,
233
+ optimizer=optimizer,
234
+ conversationally=conversationally,
235
+ )
236
+ )
237
+
238
+ return for_stream() if stream else for_non_stream()
239
+
240
+ def get_message(self, response: dict) -> str:
241
+ """Retrieves message only from response
242
+
243
+ Args:
244
+ response (dict): Response generated by `self.ask`
245
+
246
+ Returns:
247
+ str: Message extracted
248
+ """
249
+ assert isinstance(response, dict), "Response should be of dict data-type only"
250
+ return response["text"]
251
+ if __name__ == '__main__':
252
+ from rich import print
253
+ ai = NetFly()
254
+ response = ai.chat("tell me about india")
255
+ for chunk in response:
256
+ print(chunk, end="", flush=True)
@@ -0,0 +1,138 @@
1
+ import requests
2
+ import os
3
+ import time
4
+ from typing import List
5
+ from string import punctuation
6
+ from random import choice
7
+ from requests.exceptions import RequestException
8
+
9
+ from webscout.AIbase import ImageProvider
10
+
11
+ class PollinationsAI(ImageProvider):
12
+ """Image provider for pollinations.ai"""
13
+
14
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
15
+ """Initializes the PollinationsAI class.
16
+
17
+ Args:
18
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
19
+ proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
20
+ """
21
+ self.image_gen_endpoint = "https://image.pollinations.ai/prompt/{prompt}?width={width}&height={height}&model={model}"
22
+ self.headers = {
23
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
24
+ "Accept-Language": "en-US,en;q=0.5",
25
+ "Accept-Encoding": "gzip, deflate",
26
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
27
+ }
28
+ self.session = requests.Session()
29
+ self.session.headers.update(self.headers)
30
+ self.session.proxies.update(proxies)
31
+ self.timeout = timeout
32
+ self.prompt: str = "AI-generated image - webscout"
33
+ self.image_extension: str = "jpeg"
34
+
35
+ def generate(
36
+ self, prompt: str, amount: int = 1, additives: bool = True,
37
+ width: int = 768, height: int = 768, model: str = "flux",
38
+ max_retries: int = 3, retry_delay: int = 5
39
+ ) -> List[bytes]:
40
+ """Generate image from prompt
41
+
42
+ Args:
43
+ prompt (str): Image description.
44
+ amount (int): Total images to be generated. Defaults to 1.
45
+ additives (bool, optional): Try to make each prompt unique. Defaults to True.
46
+ width (int, optional): Width of the generated image. Defaults to 768.
47
+ height (int, optional): Height of the generated image. Defaults to 768.
48
+ model (str, optional): The model to use for image generation. Defaults to "flux".
49
+ max_retries (int, optional): Maximum number of retry attempts. Defaults to 3.
50
+ retry_delay (int, optional): Delay between retries in seconds. Defaults to 5.
51
+
52
+ Returns:
53
+ List[bytes]: List of generated images as bytes.
54
+ """
55
+ assert bool(prompt), "Prompt cannot be null"
56
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
57
+ assert amount > 0, "Amount should be greater than 0"
58
+
59
+ ads = lambda: (
60
+ ""
61
+ if not additives
62
+ else choice(punctuation)
63
+ + choice(punctuation)
64
+ + choice(punctuation)
65
+ + choice(punctuation)
66
+ + choice(punctuation)
67
+ )
68
+
69
+ self.prompt = prompt
70
+ response = []
71
+ for _ in range(amount):
72
+ url = self.image_gen_endpoint.format(
73
+ prompt=prompt + ads(), width=width, height=height, model=model
74
+ )
75
+
76
+ for attempt in range(max_retries):
77
+ try:
78
+ resp = self.session.get(url, timeout=self.timeout)
79
+ resp.raise_for_status()
80
+ response.append(resp.content)
81
+ break
82
+ except RequestException as e:
83
+ if attempt == max_retries - 1:
84
+ print(f"Failed to generate image after {max_retries} attempts: {e}")
85
+ raise
86
+ else:
87
+ print(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds...")
88
+ time.sleep(retry_delay)
89
+
90
+ return response
91
+
92
+ def save(
93
+ self,
94
+ response: List[bytes],
95
+ name: str = None,
96
+ dir: str = os.getcwd(),
97
+ filenames_prefix: str = "",
98
+ ) -> List[str]:
99
+ """Save generated images
100
+
101
+ Args:
102
+ response (List[bytes]): List of generated images as bytes.
103
+ name (str): Filename for the images. Defaults to the last prompt.
104
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
105
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
106
+
107
+ Returns:
108
+ List[str]: List of saved filenames.
109
+ """
110
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
111
+ name = self.prompt if name is None else name
112
+
113
+ filenames = []
114
+ count = 0
115
+ for image in response:
116
+ def complete_path():
117
+ count_value = "" if count == 0 else f"_{count}"
118
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
119
+
120
+ while os.path.isfile(complete_path()):
121
+ count += 1
122
+
123
+ absolute_path_to_file = complete_path()
124
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
125
+
126
+ with open(absolute_path_to_file, "wb") as fh:
127
+ fh.write(image)
128
+
129
+ return filenames
130
+
131
+
132
+ if __name__ == "__main__":
133
+ bot = PollinationsAI()
134
+ try:
135
+ resp = bot.generate("AI-generated image - webscout", 1)
136
+ print(bot.save(resp))
137
+ except Exception as e:
138
+ print(f"An error occurred: {e}")
@@ -0,0 +1,2 @@
1
+ from .deepinfra import *
2
+ from .PollinationsAI import *
@@ -0,0 +1,148 @@
1
+ import requests
2
+ import os
3
+ from typing import List
4
+ from string import punctuation
5
+ from random import choice
6
+ from random import randint
7
+ import base64
8
+
9
+ from webscout.AIbase import ImageProvider
10
+
11
+ class DeepInfraImager(ImageProvider):
12
+ """DeepInfra Image provider"""
13
+
14
+ def __init__(
15
+ self,
16
+ model: str = "black-forest-labs/FLUX-1-dev",
17
+ timeout: int = 60,
18
+ proxies: dict = {},
19
+ ):
20
+ """Initializes `DeepInfraImager`
21
+
22
+ Args:
23
+ model (str, optional): The name of the DeepInfra model to use.
24
+ Defaults to "black-forest-labs/FLUX-1-dev".
25
+ timeout (int, optional): Http request timeout. Defaults to 60 seconds.
26
+ proxies (dict, optional): Http request proxies (socks). Defaults to {}.
27
+ """
28
+ self.image_gen_endpoint: str = f"https://api.deepinfra.com/v1/inference/{model}"
29
+ self.headers = {
30
+ "Accept": "application/json, text/plain, */*",
31
+ "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
32
+ "Accept-Encoding": "gzip, deflate, br, zstd",
33
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
34
+ "DNT": "1",
35
+ "Origin": "https://deepinfra.com",
36
+ "Referer": "https://deepinfra.com/",
37
+ "Sec-CH-UA": '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
38
+ "Sec-CH-UA-Mobile": "?0",
39
+ "Sec-CH-UA-Platform": '"Windows"',
40
+ "Sec-Fetch-Dest": "empty",
41
+ "Sec-Fetch-Mode": "cors",
42
+ "Sec-Fetch-Site": "same-site"
43
+ }
44
+ self.session = requests.Session()
45
+ self.session.headers.update(self.headers)
46
+ self.session.proxies.update(proxies)
47
+ self.timeout = timeout
48
+ self.prompt: str = "AI-generated image - webscout"
49
+ self.image_extension: str = "png"
50
+
51
+ def generate(
52
+ self, prompt: str, amount: int = 1, additives: bool = True,
53
+ num_inference_steps: int = 25, guidance_scale: float = 7.5,
54
+ width: int = 1024, height: int = 1024, seed: int = None
55
+ ) -> list[bytes]:
56
+ """Generate image from prompt
57
+
58
+ Args:
59
+ prompt (str): Image description.
60
+ amount (int): Total images to be generated. Defaults to 1.
61
+ additives (bool, optional): Try to make each prompt unique. Defaults to True.
62
+ num_inference_steps (int, optional): Number of inference steps. Defaults to 39.
63
+ guidance_scale (float, optional): Guidance scale for image generation. Defaults to 13.3.
64
+ width (int, optional): Width of the generated image. Defaults to 1024.
65
+ height (int, optional): Height of the generated image. Defaults to 1024.
66
+ seed (int, optional): Random seed for image generation. If None, a random seed is used.
67
+ Defaults to None.
68
+
69
+ Returns:
70
+ list[bytes]: List of generated images as bytes.
71
+ """
72
+ assert bool(prompt), "Prompt cannot be null"
73
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
74
+ assert amount > 0, "Amount should be greater than 0"
75
+
76
+ ads = lambda: (
77
+ ""
78
+ if not additives
79
+ else choice(punctuation)
80
+ + choice(punctuation)
81
+ + choice(punctuation)
82
+ + choice(punctuation)
83
+ + choice(punctuation)
84
+ )
85
+
86
+ self.prompt = prompt
87
+ response = []
88
+ for _ in range(amount):
89
+ payload = {
90
+ "prompt": prompt + ads(),
91
+ "num_inference_steps": num_inference_steps,
92
+ "guidance_scale": guidance_scale,
93
+ "width": width,
94
+ "height": height,
95
+ "seed": seed if seed is not None else randint(1, 10000),
96
+ }
97
+ resp = self.session.post(url=self.image_gen_endpoint, json=payload, timeout=self.timeout)
98
+ resp.raise_for_status()
99
+ # Extract base64 encoded image data and decode it
100
+ image_data = resp.json()['images'][0].split(",")[1]
101
+ image_bytes = base64.b64decode(image_data)
102
+ response.append(image_bytes)
103
+
104
+ return response
105
+
106
+ def save(
107
+ self,
108
+ response: list[bytes],
109
+ name: str = None,
110
+ dir: str = os.getcwd(),
111
+ filenames_prefix: str = "",
112
+ ) -> list[str]:
113
+ """Save generated images
114
+
115
+ Args:
116
+ response (list[bytes]): List of generated images as bytes.
117
+ name (str): Filename for the images. Defaults to last prompt.
118
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
119
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
120
+ """
121
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
122
+ name = self.prompt if name is None else name
123
+
124
+ filenames: list = []
125
+ count = 0
126
+ for image in response:
127
+ def complete_path():
128
+ count_value = "" if count == 0 else f"_{count}"
129
+ return os.path.join(
130
+ dir, name + count_value + "." + self.image_extension
131
+ )
132
+
133
+ while os.path.isfile(complete_path()):
134
+ count += 1
135
+
136
+ absolute_path_to_file = complete_path()
137
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
138
+
139
+ with open(absolute_path_to_file, "wb") as fh:
140
+ fh.write(image)
141
+
142
+ return filenames
143
+
144
+
145
+ if __name__ == "__main__":
146
+ bot = DeepInfraImager()
147
+ resp = bot.generate("AI-generated image - webscout", 1)
148
+ print(bot.save(resp))
@@ -0,0 +1,2 @@
1
+ from .streamElements import *
2
+ from .voicepod import *