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

Files changed (132) hide show
  1. webscout/AIauto.py +5 -53
  2. webscout/AIutel.py +8 -318
  3. webscout/DWEBS.py +460 -489
  4. webscout/Extra/YTToolkit/YTdownloader.py +14 -53
  5. webscout/Extra/YTToolkit/transcriber.py +12 -13
  6. webscout/Extra/YTToolkit/ytapi/video.py +0 -1
  7. webscout/Extra/__init__.py +0 -1
  8. webscout/Extra/autocoder/__init__.py +9 -9
  9. webscout/Extra/autocoder/autocoder_utiles.py +193 -199
  10. webscout/Extra/autocoder/rawdog.py +789 -677
  11. webscout/Extra/gguf.py +682 -428
  12. webscout/Extra/weather.py +178 -156
  13. webscout/Extra/weather_ascii.py +70 -17
  14. webscout/Litlogger/core/logger.py +1 -2
  15. webscout/Litlogger/handlers/file.py +1 -1
  16. webscout/Litlogger/styles/formats.py +0 -2
  17. webscout/Litlogger/utils/detectors.py +0 -1
  18. webscout/Provider/AISEARCH/DeepFind.py +0 -1
  19. webscout/Provider/AISEARCH/ISou.py +1 -22
  20. webscout/Provider/AISEARCH/felo_search.py +0 -1
  21. webscout/Provider/AllenAI.py +28 -30
  22. webscout/Provider/C4ai.py +29 -11
  23. webscout/Provider/ChatGPTClone.py +226 -0
  24. webscout/Provider/ChatGPTGratis.py +24 -56
  25. webscout/Provider/DeepSeek.py +25 -17
  26. webscout/Provider/Deepinfra.py +115 -48
  27. webscout/Provider/Gemini.py +1 -1
  28. webscout/Provider/Glider.py +33 -12
  29. webscout/Provider/HF_space/qwen_qwen2.py +2 -2
  30. webscout/Provider/HeckAI.py +23 -7
  31. webscout/Provider/Hunyuan.py +272 -0
  32. webscout/Provider/Jadve.py +20 -5
  33. webscout/Provider/LambdaChat.py +391 -0
  34. webscout/Provider/Netwrck.py +42 -19
  35. webscout/Provider/OLLAMA.py +256 -32
  36. webscout/Provider/PI.py +4 -2
  37. webscout/Provider/Perplexitylabs.py +26 -6
  38. webscout/Provider/PizzaGPT.py +10 -51
  39. webscout/Provider/TTI/AiForce/async_aiforce.py +4 -37
  40. webscout/Provider/TTI/AiForce/sync_aiforce.py +41 -38
  41. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -9
  42. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +179 -206
  43. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +180 -192
  44. webscout/Provider/TTI/MagicStudio/__init__.py +2 -0
  45. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +111 -0
  46. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +109 -0
  47. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +5 -24
  48. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +2 -22
  49. webscout/Provider/TTI/__init__.py +2 -3
  50. webscout/Provider/TTI/aiarta/async_aiarta.py +14 -14
  51. webscout/Provider/TTI/aiarta/sync_aiarta.py +52 -21
  52. webscout/Provider/TTI/artbit/async_artbit.py +3 -32
  53. webscout/Provider/TTI/artbit/sync_artbit.py +3 -31
  54. webscout/Provider/TTI/fastflux/__init__.py +22 -0
  55. webscout/Provider/TTI/fastflux/async_fastflux.py +261 -0
  56. webscout/Provider/TTI/fastflux/sync_fastflux.py +252 -0
  57. webscout/Provider/TTI/piclumen/__init__.py +22 -22
  58. webscout/Provider/TTI/piclumen/sync_piclumen.py +232 -232
  59. webscout/Provider/TTS/__init__.py +2 -2
  60. webscout/Provider/TTS/deepgram.py +12 -39
  61. webscout/Provider/TTS/elevenlabs.py +14 -40
  62. webscout/Provider/TTS/gesserit.py +11 -35
  63. webscout/Provider/TTS/murfai.py +13 -39
  64. webscout/Provider/TTS/parler.py +17 -40
  65. webscout/Provider/TTS/speechma.py +180 -0
  66. webscout/Provider/TTS/streamElements.py +17 -44
  67. webscout/Provider/TextPollinationsAI.py +39 -59
  68. webscout/Provider/Venice.py +25 -8
  69. webscout/Provider/WebSim.py +227 -0
  70. webscout/Provider/WiseCat.py +27 -5
  71. webscout/Provider/Youchat.py +64 -37
  72. webscout/Provider/__init__.py +12 -7
  73. webscout/Provider/akashgpt.py +20 -5
  74. webscout/Provider/flowith.py +33 -7
  75. webscout/Provider/freeaichat.py +32 -45
  76. webscout/Provider/koala.py +20 -5
  77. webscout/Provider/labyrinth.py +239 -0
  78. webscout/Provider/learnfastai.py +28 -15
  79. webscout/Provider/llamatutor.py +1 -1
  80. webscout/Provider/llmchat.py +30 -8
  81. webscout/Provider/multichat.py +65 -9
  82. webscout/Provider/sonus.py +208 -0
  83. webscout/Provider/talkai.py +1 -0
  84. webscout/Provider/turboseek.py +3 -0
  85. webscout/Provider/tutorai.py +2 -0
  86. webscout/Provider/typegpt.py +155 -65
  87. webscout/Provider/uncovr.py +297 -0
  88. webscout/Provider/x0gpt.py +3 -1
  89. webscout/Provider/yep.py +102 -20
  90. webscout/__init__.py +3 -0
  91. webscout/cli.py +53 -40
  92. webscout/conversation.py +1 -10
  93. webscout/litagent/__init__.py +2 -2
  94. webscout/litagent/agent.py +356 -20
  95. webscout/litagent/constants.py +34 -5
  96. webscout/litprinter/__init__.py +0 -3
  97. webscout/models.py +181 -0
  98. webscout/optimizers.py +1 -1
  99. webscout/prompt_manager.py +2 -8
  100. webscout/scout/core/scout.py +1 -4
  101. webscout/scout/core/search_result.py +1 -1
  102. webscout/scout/core/text_utils.py +1 -1
  103. webscout/scout/core.py +2 -5
  104. webscout/scout/element.py +1 -1
  105. webscout/scout/parsers/html_parser.py +1 -1
  106. webscout/scout/utils.py +0 -1
  107. webscout/swiftcli/__init__.py +1 -3
  108. webscout/tempid.py +1 -1
  109. webscout/update_checker.py +1 -3
  110. webscout/version.py +1 -1
  111. webscout/webscout_search_async.py +1 -2
  112. webscout/yep_search.py +297 -297
  113. {webscout-7.5.dist-info → webscout-7.7.dist-info}/LICENSE.md +4 -4
  114. {webscout-7.5.dist-info → webscout-7.7.dist-info}/METADATA +127 -405
  115. {webscout-7.5.dist-info → webscout-7.7.dist-info}/RECORD +118 -117
  116. webscout/Extra/autollama.py +0 -231
  117. webscout/Provider/Amigo.py +0 -274
  118. webscout/Provider/Bing.py +0 -243
  119. webscout/Provider/DiscordRocks.py +0 -253
  120. webscout/Provider/TTI/blackbox/__init__.py +0 -4
  121. webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
  122. webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
  123. webscout/Provider/TTI/deepinfra/__init__.py +0 -4
  124. webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
  125. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
  126. webscout/Provider/TTI/imgninza/__init__.py +0 -4
  127. webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
  128. webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
  129. webscout/Provider/TTS/voicepod.py +0 -117
  130. {webscout-7.5.dist-info → webscout-7.7.dist-info}/WHEEL +0 -0
  131. {webscout-7.5.dist-info → webscout-7.7.dist-info}/entry_points.txt +0 -0
  132. {webscout-7.5.dist-info → webscout-7.7.dist-info}/top_level.txt +0 -0
@@ -1,253 +0,0 @@
1
- from typing import Any, Dict
2
- import requests
3
- import json
4
-
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts
8
- from webscout.AIbase import Provider
9
- from webscout import exceptions
10
-
11
- class DiscordRocks(Provider):
12
- """
13
- A class to interact with the Airforce API.
14
- """
15
-
16
- AVAILABLE_MODELS = [
17
- 'claude-3-haiku-20240307', 'claude-3-sonnet-20240229', 'claude-3-5-sonnet-20240620',
18
- 'claude-3-opus-20240229', 'chatgpt-4o-latest', 'gpt-4', 'gpt-4-0613', 'gpt-4-turbo',
19
- 'gpt-4o-mini-2024-07-18', 'gpt-4o-mini', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0125',
20
- 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-16k-0613',
21
- 'gpt-4o', 'llama-3-70b-chat', 'llama-3-70b-chat-turbo', 'llama-3-8b-chat',
22
- 'llama-3-8b-chat-turbo', 'llama-3-70b-chat-lite', 'llama-3-8b-chat-lite',
23
- 'llama-2-13b-chat', 'llama-3.1-405b-turbo', 'llama-3.1-70b-turbo', 'llama-3.1-8b-turbo',
24
- 'LlamaGuard-2-8b', 'Llama-Guard-7b', 'Meta-Llama-Guard-3-8B', 'Mixtral-8x7B-v0.1',
25
- 'Mixtral-8x7B-Instruct-v0.1', 'Mixtral-8x22B-Instruct-v0.1', 'Mistral-7B-Instruct-v0.1',
26
- 'Mistral-7B-Instruct-v0.2', 'Mistral-7B-Instruct-v0.3', 'Qwen1.5-72B-Chat',
27
- 'Qwen1.5-110B-Chat', 'Qwen2-72B-Instruct', 'gemma-2b-it', 'dbrx-instruct',
28
- 'deepseek-coder-33b-instruct', 'deepseek-llm-67b-chat', 'Nous-Hermes-2-Mixtral-8x7B-DPO',
29
- 'Nous-Hermes-2-Yi-34B', 'WizardLM-2-8x22B', 'CodeLlama-7b-Python',
30
- 'snowflake-arctic-instruct', 'SOLAR-10.7B-Instruct-v1.0', 'StripedHyena-Nous-7B',
31
- 'CodeLlama-13b-Instruct', 'MythoMax-L2-13b', 'gemma-2-9b-it', 'gemma-2-27b-it',
32
- 'gemini-1.5-flash', 'gemini-1.5-pro', 'sparkdesk', 'cosmosrp'
33
- ]
34
-
35
- def __init__(
36
- self,
37
- is_conversation: bool = True,
38
- max_tokens: int = 600,
39
- timeout: int = 30,
40
- intro: str = None,
41
- filepath: str = None,
42
- update_file: bool = True,
43
- proxies: dict = {},
44
- history_offset: int = 10250,
45
- act: str = None,
46
- system_prompt: str = "You are a helpful AI assistant.",
47
- model: str = "chatgpt-4o-latest",
48
- temperature: float = 1,
49
- top_p: float = 1,
50
- ):
51
- """
52
- Initializes the Airforce API with given parameters.
53
-
54
- Args:
55
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
56
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
57
- timeout (int, optional): Http request timeout. Defaults to 30.
58
- intro (str, optional): Conversation introductory prompt. Defaults to None.
59
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
60
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
61
- proxies (dict, optional): Http request proxies. Defaults to {}.
62
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
63
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
64
- system_prompt (str, optional): System prompt for Airforce. Defaults to "You are a helpful AI assistant.".
65
- model (str, optional): AI model to use. Defaults to "chatgpt-4o-latest".
66
- temperature (float, optional): Temperature parameter for the model. Defaults to 1.
67
- top_p (float, optional): Top_p parameter for the model. Defaults to 1.
68
- """
69
- if model not in self.AVAILABLE_MODELS:
70
- raise ValueError(f'Error: Invalid model. Please choose from {self.AVAILABLE_MODELS}')
71
-
72
- self.session = requests.Session()
73
- self.is_conversation = is_conversation
74
- self.max_tokens_to_sample = max_tokens
75
- self.api_endpoint = "https://api.airforce/chat/completions"
76
- self.stream_chunk_size = 1024
77
- self.timeout = timeout
78
- self.last_response = {}
79
- self.system_prompt = system_prompt
80
- self.model = model
81
- self.temperature = temperature
82
- self.top_p = top_p
83
- self.headers = {
84
- 'accept': '*/*',
85
- 'accept-encoding': 'gzip, deflate, br, zstd',
86
- 'accept-language': 'en-US,en;q=0.9,en-IN;q=0.8',
87
- 'authorization': 'Bearer missing api key',
88
- 'content-type': 'application/json',
89
- 'dnt': '1',
90
- 'origin': 'https://llmplayground.net',
91
- 'referer': 'https://llmplayground.net/',
92
- 'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
93
- 'sec-ch-ua-mobile': '?0',
94
- 'sec-ch-ua-platform': '"Windows"',
95
- 'sec-fetch-dest': 'empty',
96
- 'sec-fetch-mode': 'cors',
97
- 'sec-fetch-site': 'cross-site',
98
- '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'
99
- }
100
-
101
- self.__available_optimizers = (
102
- method
103
- for method in dir(Optimizers)
104
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
105
- )
106
- self.session.headers.update(self.headers)
107
- Conversation.intro = (
108
- AwesomePrompts().get_act(
109
- act, raise_not_found=True, default=None, case_insensitive=True
110
- )
111
- if act
112
- else intro or Conversation.intro
113
- )
114
- self.conversation = Conversation(
115
- is_conversation, self.max_tokens_to_sample, filepath, update_file
116
- )
117
- self.conversation.history_offset = history_offset
118
- self.session.proxies = proxies
119
-
120
- def ask(
121
- self,
122
- prompt: str,
123
- stream: bool = False,
124
- raw: bool = False,
125
- optimizer: str = None,
126
- conversationally: bool = False,
127
- ) -> Dict[str, Any]:
128
- """Chat with AI"""
129
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
130
- if optimizer:
131
- if optimizer in self.__available_optimizers:
132
- conversation_prompt = getattr(Optimizers, optimizer)(
133
- conversation_prompt if conversationally else prompt
134
- )
135
- else:
136
- raise Exception(
137
- f"Optimizer is not one of {self.__available_optimizers}"
138
- )
139
-
140
- # Define the payload
141
- payload = {
142
- 'messages': [{'role': 'user', 'content': conversation_prompt}],
143
- 'model': self.model,
144
- 'max_tokens': self.max_tokens_to_sample,
145
- 'temperature': self.temperature,
146
- 'top_p': self.top_p,
147
- 'stream': stream
148
- }
149
-
150
- def for_stream():
151
- try:
152
- # Send the POST request
153
- response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True)
154
-
155
- # Check if the request was successful
156
- response.raise_for_status()
157
-
158
- full_content = ''
159
- for line in response.iter_lines():
160
- if line:
161
- decoded_line = line.decode('utf-8')
162
- if decoded_line.startswith('data:'):
163
- if decoded_line.strip() == 'data: [DONE]':
164
- break
165
- try:
166
- json_data = json.loads(decoded_line[5:])
167
- content = json_data['choices'][0]['delta'].get('content', '')
168
- if content:
169
- full_content += content
170
- yield content if raw else dict(text=content)
171
- except json.JSONDecodeError:
172
- print(f'Error decoding JSON: {decoded_line}')
173
- except KeyError:
174
- print(f'Unexpected JSON structure: {json_data}')
175
- self.last_response.update(dict(text=full_content))
176
- self.conversation.update_chat_history(
177
- prompt, self.get_message(self.last_response)
178
- )
179
- except requests.exceptions.RequestException as e:
180
- raise exceptions.FailedToGenerateResponseError(f'An error occurred: {e}')
181
-
182
- def for_non_stream():
183
- try:
184
- # Send the POST request
185
- response = self.session.post(self.api_endpoint, headers=self.headers, json=payload)
186
-
187
- # Check if the request was successful
188
- response.raise_for_status()
189
-
190
- resp = response.json()
191
- self.last_response.update(dict(text=resp.get("choices", [{}])[0].get('message', {}).get('content', '')))
192
- self.conversation.update_chat_history(
193
- prompt, self.get_message(self.last_response)
194
- )
195
- return self.last_response
196
- except requests.exceptions.RequestException as e:
197
- raise exceptions.FailedToGenerateResponseError(f'An error occurred: {e}')
198
-
199
- return for_stream() if stream else for_non_stream()
200
-
201
- def chat(
202
- self,
203
- prompt: str,
204
- stream: bool = False,
205
- optimizer: str = None,
206
- conversationally: bool = False,
207
- ) -> str:
208
- """Generate response `str`
209
- Args:
210
- prompt (str): Prompt to be send.
211
- stream (bool, optional): Flag for streaming response. Defaults to False.
212
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
213
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
214
- Returns:
215
- str: Response generated
216
- """
217
-
218
- def for_stream():
219
- for response in self.ask(
220
- prompt, True, optimizer=optimizer, conversationally=conversationally
221
- ):
222
- yield self.get_message(response)
223
-
224
- def for_non_stream():
225
- return self.get_message(
226
- self.ask(
227
- prompt,
228
- False,
229
- optimizer=optimizer,
230
- conversationally=conversationally,
231
- )
232
- )
233
-
234
- return for_stream() if stream else for_non_stream()
235
-
236
- def get_message(self, response: dict) -> str:
237
- """Retrieves message only from response
238
-
239
- Args:
240
- response (dict): Response generated by `self.ask`
241
-
242
- Returns:
243
- str: Message extracted
244
- """
245
- assert isinstance(response, dict), "Response should be of dict data-type only"
246
- return response["text"]
247
-
248
- if __name__ == '__main__':
249
- from rich import print
250
- ai = DiscordRocks(timeout=5000)
251
- response = ai.chat("write a poem about AI", stream=True)
252
- for chunk in response:
253
- print(chunk, end="", flush=True)
@@ -1,4 +0,0 @@
1
- from .sync_blackbox import BlackboxAIImager
2
- from .async_blackbox import AsyncBlackboxAIImager
3
-
4
- __all__ = ["BlackboxAIImager", "AsyncBlackboxAIImager"]
@@ -1,212 +0,0 @@
1
- import aiohttp
2
- import asyncio
3
- import json
4
- import uuid
5
- import os
6
- from typing import List, Union, AsyncGenerator
7
- import aiofiles
8
-
9
- from webscout.AIbase import AsyncImageProvider
10
- from webscout.litagent import LitAgent # Import our fire user agent generator 🔥
11
- from webscout.Litlogger import Logger # For that cyberpunk logging swag ⚡
12
-
13
- # Initialize our fire logger 🚀
14
- logger = Logger("AsyncBlackboxAIImager")
15
-
16
- class AsyncBlackboxAIImager(AsyncImageProvider):
17
- """
18
- Async BlackboxAI Image Provider - Your go-to for fire AI art! 🎨
19
-
20
- >>> # Generate some fire art asynchronously! 🔥
21
- >>> async def generate_art():
22
- ... imager = AsyncBlackboxAIImager(logging=True)
23
- ... images = await imager.generate("Epic dragon breathing fire", amount=2)
24
- ... paths = await imager.save(images)
25
- ... print(paths)
26
- >>> asyncio.run(generate_art())
27
- ['epic_dragon_0.jpg', 'epic_dragon_1.jpg']
28
-
29
- >>> # Turn off logging for stealth mode 🥷
30
- >>> async def stealth_art():
31
- ... quiet_imager = AsyncBlackboxAIImager(logging=False)
32
- ... images = await quiet_imager.generate("Cyberpunk city at night")
33
- ... paths = await quiet_imager.save(images)
34
- >>> asyncio.run(stealth_art())
35
- """
36
-
37
- def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
38
- """Initialize your async BlackboxAI provider with custom settings! ⚙️
39
-
40
- Args:
41
- timeout (int): Request timeout in seconds (default: 60)
42
- proxies (dict): Proxy settings for requests (default: {})
43
- logging (bool): Enable fire logging (default: True)
44
- """
45
- self.url = "https://www.blackbox.ai/api/chat"
46
- self.headers = {
47
- "Content-Type": "application/json",
48
- "Accept": "application/json, text/plain, */*",
49
- "Accept-Language": "en-US,en;q=0.9",
50
- "Accept-Encoding": "gzip, deflate, br",
51
- "User-Agent": LitAgent().random(), # Using our fire random agent! 🔥
52
- "DNT": "1",
53
- "Origin": "https://www.blackbox.ai",
54
- "Referer": "https://www.blackbox.ai/agent/ImageGenerationLV45LJp"
55
- }
56
- self.timeout = timeout
57
- self.proxies = proxies
58
- self.prompt: str = "AI-generated image - webscout"
59
- self.image_extension: str = "jpg"
60
- self.logging = logging
61
- if self.logging:
62
- logger.info("AsyncBlackboxAIImager initialized! Ready to create some fire art! 🚀")
63
-
64
- async def generate(
65
- self, prompt: str, amount: int = 1,
66
- max_retries: int = 3, retry_delay: int = 5
67
- ) -> List[bytes]:
68
- """Generate some fire images from your prompt! 🎨
69
-
70
- Args:
71
- prompt (str): Your creative prompt
72
- amount (int): How many images to generate
73
- max_retries (int): Max retry attempts if generation fails
74
- retry_delay (int): Seconds to wait between retries
75
-
76
- Returns:
77
- List[bytes]: Your generated images as bytes
78
- """
79
- assert bool(prompt), "Prompt cannot be null"
80
- assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
81
- assert amount > 0, "Amount should be greater than 0"
82
-
83
- self.prompt = prompt
84
- response = []
85
-
86
- if self.logging:
87
- logger.info(f"Generating {amount} images... 🎨")
88
-
89
- async with aiohttp.ClientSession(headers=self.headers) as session:
90
- for _ in range(amount):
91
- message_id = str(uuid.uuid4())
92
- payload = {
93
- "messages": [
94
- {
95
- "id": message_id,
96
- "content": prompt,
97
- "role": "user"
98
- }
99
- ],
100
- "id": message_id,
101
- "previewToken": None,
102
- "userId": None,
103
- "codeModelMode": True,
104
- "agentMode": {
105
- "mode": True,
106
- "id": "ImageGenerationLV45LJp",
107
- "name": "Image Generation"
108
- },
109
- "trendingAgentMode": {},
110
- "isMicMode": False,
111
- "maxTokens": 1024,
112
- "isChromeExt": False,
113
- "githubToken": None,
114
- "clickedAnswer2": False,
115
- "clickedAnswer3": False,
116
- "clickedForceWebSearch": False,
117
- "visitFromDelta": False,
118
- "mobileClient": False
119
- }
120
-
121
- for attempt in range(max_retries):
122
- try:
123
- async with session.post(self.url, json=payload, timeout=self.timeout) as resp:
124
- resp.raise_for_status()
125
- response_data = await resp.text()
126
- image_url = response_data.split("(")[1].split(")")[0]
127
-
128
- async with session.get(image_url) as image_resp:
129
- image_resp.raise_for_status()
130
- response.append(await image_resp.read())
131
- if self.logging:
132
- logger.success(f"Generated image {len(response)}/{amount}! 🎨")
133
- break
134
- except aiohttp.ClientError as e:
135
- if attempt == max_retries - 1:
136
- if self.logging:
137
- logger.error(f"Failed to generate image after {max_retries} attempts: {e} 😢")
138
- raise
139
- else:
140
- if self.logging:
141
- logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
142
- await asyncio.sleep(retry_delay)
143
-
144
- if self.logging:
145
- logger.success("All images generated successfully! 🎉")
146
- return response
147
-
148
- async def save(
149
- self,
150
- response: Union[List[bytes], AsyncGenerator[bytes, None]],
151
- name: str = None,
152
- dir: str = os.getcwd(),
153
- filenames_prefix: str = "",
154
- ) -> List[str]:
155
- """Save your fire images! 💾
156
-
157
- Args:
158
- response (Union[List[bytes], AsyncGenerator[bytes, None]]): Image data
159
- name (str, optional): Base name for saved files
160
- dir (str, optional): Where to save the images
161
- filenames_prefix (str, optional): Prefix for filenames
162
-
163
- Returns:
164
- List[str]: List of saved filenames
165
- """
166
- if not os.path.exists(dir):
167
- os.makedirs(dir)
168
- if self.logging:
169
- logger.info(f"Created directory: {dir} 📁")
170
-
171
- name = self.prompt if name is None else name
172
- saved_paths = []
173
-
174
- async def save_single_image(image_bytes: bytes, index: int) -> str:
175
- filename = f"{filenames_prefix}{name}_{index}.{self.image_extension}"
176
- filepath = os.path.join(dir, filename)
177
-
178
- async with aiofiles.open(filepath, "wb") as f:
179
- await f.write(image_bytes)
180
-
181
- if self.logging:
182
- logger.success(f"Saved image to: {filepath} 💾")
183
- return filename
184
-
185
- if isinstance(response, list):
186
- image_list = response
187
- else:
188
- image_list = [chunk async for chunk in response]
189
-
190
- if self.logging:
191
- logger.info(f"Saving {len(image_list)} images... 💾")
192
-
193
- tasks = [save_single_image(img, i) for i, img in enumerate(image_list)]
194
- saved_paths = await asyncio.gather(*tasks)
195
-
196
- if self.logging:
197
- logger.success(f"All images saved successfully! Check {dir} 🎉")
198
- return saved_paths
199
-
200
-
201
- if __name__ == "__main__":
202
- async def main():
203
- bot = AsyncBlackboxAIImager()
204
- try:
205
- resp = await bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
206
- paths = await bot.save(resp)
207
- print(paths)
208
- except Exception as e:
209
- if bot.logging:
210
- logger.error(f"An error occurred: {e} 😢")
211
-
212
- asyncio.run(main())
@@ -1,199 +0,0 @@
1
- import requests
2
- import json
3
- import uuid
4
- import os
5
- import time
6
- from typing import List
7
- from requests.exceptions import RequestException
8
-
9
- from webscout.AIbase import ImageProvider
10
- from webscout.litagent import LitAgent # Import our fire user agent generator 🔥
11
- from webscout.Litlogger import Logger # For that cyberpunk logging swag ⚡
12
-
13
- # Initialize our fire logger 🚀
14
- logger = Logger("BlackboxAIImager")
15
-
16
- class BlackboxAIImager(ImageProvider):
17
- """
18
- BlackboxAI Image Provider - Your go-to for fire AI art! 🎨
19
-
20
- >>> # Generate some fire art! 🔥
21
- >>> imager = BlackboxAIImager(logging=True)
22
- >>> images = imager.generate("Epic dragon breathing fire", amount=2)
23
- >>> paths = imager.save(images)
24
- >>> print(paths)
25
- ['epic_dragon_0.jpg', 'epic_dragon_1.jpg']
26
-
27
- >>> # Turn off logging for stealth mode 🥷
28
- >>> quiet_imager = BlackboxAIImager(logging=False)
29
- >>> images = quiet_imager.generate("Cyberpunk city at night")
30
- >>> paths = quiet_imager.save(images)
31
- """
32
-
33
- def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
34
- """Initialize your BlackboxAI provider with custom settings! ⚙️
35
-
36
- Args:
37
- timeout (int): Request timeout in seconds (default: 60)
38
- proxies (dict): Proxy settings for requests (default: {})
39
- logging (bool): Enable fire logging (default: True)
40
- """
41
- self.url = "https://www.blackbox.ai/api/chat"
42
- self.headers = {
43
- "Content-Type": "application/json",
44
- "User-Agent": LitAgent().random(), # Using our fire random agent! 🔥
45
- "Origin": "https://www.blackbox.ai",
46
- "Referer": "https://www.blackbox.ai/agent/ImageGenerationLV45LJp"
47
- }
48
- self.session = requests.Session()
49
- self.session.headers.update(self.headers)
50
- self.session.proxies.update(proxies)
51
- self.timeout = timeout
52
- self.prompt: str = "AI-generated image - webscout"
53
- self.image_extension: str = "jpg"
54
- self.logging = logging
55
- if self.logging:
56
- logger.info("BlackboxAIImager initialized! Ready to create some fire art! 🚀")
57
-
58
- def generate(
59
- self, prompt: str, amount: int = 1,
60
- max_retries: int = 3, retry_delay: int = 5
61
- ) -> List[bytes]:
62
- """Generate some fire images from your prompt! 🎨
63
-
64
- Args:
65
- prompt (str): Your creative prompt
66
- amount (int): How many images to generate
67
- max_retries (int): Max retry attempts if generation fails
68
- retry_delay (int): Seconds to wait between retries
69
-
70
- Returns:
71
- List[bytes]: Your generated images as bytes
72
- """
73
- assert bool(prompt), "Prompt cannot be null"
74
- assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
75
- assert amount > 0, "Amount should be greater than 0"
76
-
77
- self.prompt = prompt
78
- response = []
79
-
80
- if self.logging:
81
- logger.info(f"Generating {amount} images... 🎨")
82
-
83
- for _ in range(amount):
84
- message_id = str(uuid.uuid4())
85
- payload = {
86
- "messages": [
87
- {
88
- "id": message_id,
89
- "content": prompt,
90
- "role": "user"
91
- }
92
- ],
93
- "id": message_id,
94
- "previewToken": None,
95
- "userId": None,
96
- "codeModelMode": True,
97
- "agentMode": {
98
- "mode": True,
99
- "id": "ImageGenerationLV45LJp",
100
- "name": "Image Generation"
101
- },
102
- "trendingAgentMode": {},
103
- "isMicMode": False,
104
- "maxTokens": 1024,
105
- "isChromeExt": False,
106
- "githubToken": None,
107
- "clickedAnswer2": False,
108
- "clickedAnswer3": False,
109
- "clickedForceWebSearch": False,
110
- "visitFromDelta": False,
111
- "mobileClient": False
112
- }
113
-
114
- for attempt in range(max_retries):
115
- try:
116
- resp = self.session.post(self.url, json=payload, timeout=self.timeout)
117
- resp.raise_for_status()
118
- response_data = resp.text
119
- image_url = response_data.split("(")[1].split(")")[0]
120
- image_response = requests.get(image_url)
121
- image_response.raise_for_status()
122
- response.append(image_response.content)
123
- if self.logging:
124
- logger.success(f"Generated image {len(response)}/{amount}! 🎨")
125
- break
126
- except RequestException as e:
127
- if attempt == max_retries - 1:
128
- if self.logging:
129
- logger.error(f"Failed to generate image after {max_retries} attempts: {e} 😢")
130
- raise
131
- else:
132
- if self.logging:
133
- logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
134
- time.sleep(retry_delay)
135
-
136
- if self.logging:
137
- logger.success("All images generated successfully! 🎉")
138
- return response
139
-
140
- def save(
141
- self,
142
- response: List[bytes],
143
- name: str = None,
144
- dir: str = os.getcwd(),
145
- filenames_prefix: str = "",
146
- ) -> List[str]:
147
- """Save your fire images! 💾
148
-
149
- Args:
150
- response (List[bytes]): List of image data
151
- name (str, optional): Base name for saved files
152
- dir (str, optional): Where to save the images
153
- filenames_prefix (str, optional): Prefix for filenames
154
-
155
- Returns:
156
- List[str]: List of saved filenames
157
- """
158
- assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
159
- name = self.prompt if name is None else name
160
-
161
- if not os.path.exists(dir):
162
- os.makedirs(dir)
163
- if self.logging:
164
- logger.info(f"Created directory: {dir} 📁")
165
-
166
- if self.logging:
167
- logger.info(f"Saving {len(response)} images... 💾")
168
-
169
- filenames = []
170
- count = 0
171
- for image in response:
172
- def complete_path():
173
- count_value = "" if count == 0 else f"_{count}"
174
- return os.path.join(dir, name + count_value + "." + self.image_extension)
175
-
176
- while os.path.isfile(complete_path()):
177
- count += 1
178
-
179
- absolute_path_to_file = complete_path()
180
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
181
-
182
- with open(absolute_path_to_file, "wb") as fh:
183
- fh.write(image)
184
- if self.logging:
185
- logger.success(f"Saved image to: {absolute_path_to_file} 💾")
186
-
187
- if self.logging:
188
- logger.success(f"All images saved successfully! Check {dir} 🎉")
189
- return filenames
190
-
191
-
192
- if __name__ == "__main__":
193
- bot = BlackboxAIImager()
194
- try:
195
- resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
196
- print(bot.save(resp))
197
- except Exception as e:
198
- if bot.logging:
199
- logger.error(f"An error occurred: {e} 😢")
@@ -1,4 +0,0 @@
1
- from .sync_deepinfra import DeepInfraImager
2
- from .async_deepinfra import AsyncDeepInfraImager
3
-
4
- __all__ = ["DeepInfraImager", "AsyncDeepInfraImager"]