webscout 6.3__py3-none-any.whl → 6.5__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 (131) hide show
  1. webscout/AIauto.py +191 -176
  2. webscout/AIbase.py +0 -197
  3. webscout/AIutel.py +441 -1130
  4. webscout/DWEBS.py +189 -35
  5. webscout/{YTdownloader.py → Extra/YTToolkit/YTdownloader.py} +990 -1103
  6. webscout/Extra/YTToolkit/__init__.py +3 -0
  7. webscout/{transcriber.py → Extra/YTToolkit/transcriber.py} +479 -551
  8. webscout/Extra/YTToolkit/ytapi/__init__.py +6 -0
  9. webscout/Extra/YTToolkit/ytapi/channel.py +307 -0
  10. webscout/Extra/YTToolkit/ytapi/errors.py +13 -0
  11. webscout/Extra/YTToolkit/ytapi/extras.py +45 -0
  12. webscout/Extra/YTToolkit/ytapi/https.py +88 -0
  13. webscout/Extra/YTToolkit/ytapi/patterns.py +61 -0
  14. webscout/Extra/YTToolkit/ytapi/playlist.py +59 -0
  15. webscout/Extra/YTToolkit/ytapi/pool.py +8 -0
  16. webscout/Extra/YTToolkit/ytapi/query.py +37 -0
  17. webscout/Extra/YTToolkit/ytapi/stream.py +60 -0
  18. webscout/Extra/YTToolkit/ytapi/utils.py +62 -0
  19. webscout/Extra/YTToolkit/ytapi/video.py +102 -0
  20. webscout/Extra/__init__.py +3 -1
  21. webscout/Extra/autocoder/__init__.py +9 -0
  22. webscout/Extra/autocoder/autocoder_utiles.py +121 -0
  23. webscout/Extra/autocoder/rawdog.py +680 -0
  24. webscout/Extra/autollama.py +246 -195
  25. webscout/Extra/gguf.py +81 -56
  26. webscout/Extra/markdownlite/__init__.py +862 -0
  27. webscout/Extra/weather_ascii.py +2 -2
  28. webscout/LLM.py +206 -43
  29. webscout/Litlogger/__init__.py +681 -0
  30. webscout/Provider/DARKAI.py +1 -1
  31. webscout/Provider/EDITEE.py +1 -1
  32. webscout/Provider/NinjaChat.py +1 -1
  33. webscout/Provider/PI.py +120 -35
  34. webscout/Provider/Perplexity.py +590 -598
  35. webscout/Provider/Reka.py +0 -1
  36. webscout/Provider/RoboCoders.py +206 -0
  37. webscout/Provider/TTI/AiForce/__init__.py +22 -0
  38. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
  39. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
  40. webscout/Provider/TTI/Nexra/__init__.py +22 -0
  41. webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
  42. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
  43. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
  44. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
  45. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
  46. webscout/Provider/TTI/__init__.py +2 -4
  47. webscout/Provider/TTI/artbit/__init__.py +22 -0
  48. webscout/Provider/TTI/artbit/async_artbit.py +184 -0
  49. webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
  50. webscout/Provider/TTI/blackbox/__init__.py +4 -0
  51. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
  52. webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
  53. webscout/Provider/TTI/deepinfra/__init__.py +4 -0
  54. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
  55. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
  56. webscout/Provider/TTI/huggingface/__init__.py +22 -0
  57. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
  58. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
  59. webscout/Provider/TTI/imgninza/__init__.py +4 -0
  60. webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
  61. webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
  62. webscout/Provider/TTI/talkai/__init__.py +4 -0
  63. webscout/Provider/TTI/talkai/async_talkai.py +229 -0
  64. webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
  65. webscout/Provider/TTS/__init__.py +5 -1
  66. webscout/Provider/TTS/deepgram.py +183 -0
  67. webscout/Provider/TTS/elevenlabs.py +137 -0
  68. webscout/Provider/TTS/gesserit.py +151 -0
  69. webscout/Provider/TTS/murfai.py +139 -0
  70. webscout/Provider/TTS/parler.py +134 -107
  71. webscout/Provider/TTS/streamElements.py +360 -275
  72. webscout/Provider/TTS/utils.py +280 -0
  73. webscout/Provider/TTS/voicepod.py +116 -116
  74. webscout/Provider/__init__.py +8 -1
  75. webscout/Provider/askmyai.py +2 -2
  76. webscout/Provider/cerebras.py +227 -219
  77. webscout/Provider/llama3mitril.py +0 -1
  78. webscout/Provider/meta.py +794 -779
  79. webscout/Provider/mhystical.py +176 -0
  80. webscout/Provider/perplexitylabs.py +265 -0
  81. webscout/Provider/twitterclone.py +251 -245
  82. webscout/Provider/typegpt.py +358 -0
  83. webscout/__init__.py +9 -8
  84. webscout/__main__.py +5 -5
  85. webscout/cli.py +252 -280
  86. webscout/conversation.py +227 -0
  87. webscout/exceptions.py +161 -29
  88. webscout/litagent/__init__.py +172 -0
  89. webscout/litprinter/__init__.py +832 -0
  90. webscout/optimizers.py +270 -0
  91. webscout/prompt_manager.py +279 -0
  92. webscout/scout/__init__.py +11 -0
  93. webscout/scout/core.py +884 -0
  94. webscout/scout/element.py +459 -0
  95. webscout/scout/parsers/__init__.py +69 -0
  96. webscout/scout/parsers/html5lib_parser.py +172 -0
  97. webscout/scout/parsers/html_parser.py +236 -0
  98. webscout/scout/parsers/lxml_parser.py +178 -0
  99. webscout/scout/utils.py +38 -0
  100. webscout/swiftcli/__init__.py +810 -0
  101. webscout/update_checker.py +125 -0
  102. webscout/version.py +1 -1
  103. webscout/zeroart/__init__.py +55 -0
  104. webscout/zeroart/base.py +61 -0
  105. webscout/zeroart/effects.py +99 -0
  106. webscout/zeroart/fonts.py +816 -0
  107. webscout/zerodir/__init__.py +225 -0
  108. {webscout-6.3.dist-info → webscout-6.5.dist-info}/METADATA +37 -112
  109. webscout-6.5.dist-info/RECORD +179 -0
  110. webscout/Agents/Onlinesearcher.py +0 -182
  111. webscout/Agents/__init__.py +0 -2
  112. webscout/Agents/functioncall.py +0 -248
  113. webscout/Bing_search.py +0 -154
  114. webscout/Provider/TTI/AIuncensoredimage.py +0 -103
  115. webscout/Provider/TTI/Nexra.py +0 -120
  116. webscout/Provider/TTI/PollinationsAI.py +0 -138
  117. webscout/Provider/TTI/WebSimAI.py +0 -142
  118. webscout/Provider/TTI/aiforce.py +0 -160
  119. webscout/Provider/TTI/artbit.py +0 -141
  120. webscout/Provider/TTI/deepinfra.py +0 -148
  121. webscout/Provider/TTI/huggingface.py +0 -155
  122. webscout/Provider/TTI/talkai.py +0 -116
  123. webscout/g4f.py +0 -666
  124. webscout/models.py +0 -23
  125. webscout/requestsHTMLfix.py +0 -775
  126. webscout/webai.py +0 -2590
  127. webscout-6.3.dist-info/RECORD +0 -124
  128. {webscout-6.3.dist-info → webscout-6.5.dist-info}/LICENSE.md +0 -0
  129. {webscout-6.3.dist-info → webscout-6.5.dist-info}/WHEEL +0 -0
  130. {webscout-6.3.dist-info → webscout-6.5.dist-info}/entry_points.txt +0 -0
  131. {webscout-6.3.dist-info → webscout-6.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,258 @@
1
+ import requests
2
+ import json
3
+ import os
4
+ import time
5
+ from typing import List, Optional, Union
6
+ from pathlib import Path
7
+ from requests.exceptions import RequestException
8
+
9
+ from webscout.AIbase import ImageProvider
10
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
11
+ from webscout.litagent import LitAgent
12
+
13
+ # Initialize our fire logger and agent 🔥
14
+ logger = LitLogger(
15
+ "Nexra",
16
+ format=LogFormat.MODERN_EMOJI,
17
+ color_scheme=ColorScheme.CYBERPUNK
18
+ )
19
+ agent = LitAgent()
20
+
21
+ class NexraImager(ImageProvider):
22
+ """Your go-to provider for generating fire images with Nexra! 🔥
23
+
24
+ Examples:
25
+ >>> # Basic usage
26
+ >>> provider = NexraImager()
27
+ >>> images = provider.generate("Cool art")
28
+ >>> paths = provider.save(images)
29
+ >>>
30
+ >>> # Advanced usage
31
+ >>> provider = NexraImager(timeout=120)
32
+ >>> images = provider.generate(
33
+ ... prompt="Epic dragon",
34
+ ... model="midjourney",
35
+ ... additional_params={
36
+ ... "data": {
37
+ ... "steps": 30,
38
+ ... "cfg_scale": 8
39
+ ... }
40
+ ... }
41
+ ... )
42
+ >>> paths = provider.save(images, name="dragon", dir="my_art")
43
+ """
44
+
45
+ AVAILABLE_MODELS = {
46
+ "standard": [
47
+ "emi",
48
+ "stablediffusion-1.5",
49
+ "stablediffusion-2.1",
50
+ "sdxl-lora",
51
+ "dalle",
52
+ "dalle2",
53
+ "dalle-mini",
54
+ "flux",
55
+ "midjourney"
56
+ ],
57
+ "prodia": [
58
+ "dreamshaperXL10_alpha2.safetensors [c8afe2ef]",
59
+ "dynavisionXL_0411.safetensors [c39cc051]",
60
+ "juggernautXL_v45.safetensors [e75f5471]",
61
+ "realismEngineSDXL_v10.safetensors [af771c3f]",
62
+ "sd_xl_base_1.0.safetensors [be9edd61]",
63
+ "animagineXLV3_v30.safetensors [75f2f05b]",
64
+ "sd_xl_base_1.0_inpainting_0.1.safetensors [5679a81a]",
65
+ "turbovisionXL_v431.safetensors [78890989]",
66
+ "devlishphotorealism_sdxl15.safetensors [77cba69f]",
67
+ "realvisxlV40.safetensors [f7fdcb51]"
68
+ ]
69
+ }
70
+
71
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
72
+ """Initialize your Nexra provider with custom settings! ⚙️
73
+
74
+ Args:
75
+ timeout (int): Request timeout in seconds (default: 60)
76
+ proxies (dict): Proxy settings for requests (default: {})
77
+ logging (bool): Enable fire logging (default: True)
78
+ """
79
+ self.url = "https://nexra.aryahcr.cc/api/image/complements"
80
+ self.headers = {
81
+ "Content-Type": "application/json",
82
+ "Accept": "application/json",
83
+ "User-Agent": agent.random()
84
+ }
85
+ self.session = requests.Session()
86
+ self.session.headers.update(self.headers)
87
+ self.session.proxies.update(proxies)
88
+ self.timeout = timeout
89
+ self.prompt: str = "AI-generated image - webscout"
90
+ self.image_extension: str = "png"
91
+ self.logging = logging
92
+ if self.logging:
93
+ logger.info("Nexra provider initialized! 🚀")
94
+
95
+ def generate(
96
+ self,
97
+ prompt: str,
98
+ model: str = "midjourney",
99
+ amount: int = 1,
100
+ max_retries: int = 3,
101
+ retry_delay: int = 5,
102
+ additional_params: Optional[dict] = None
103
+ ) -> List[bytes]:
104
+ """Generate some fire images from your prompt! 🎨
105
+
106
+ Examples:
107
+ >>> provider = NexraImager()
108
+ >>> # Basic usage
109
+ >>> images = provider.generate("Cool art")
110
+ >>> # Advanced usage
111
+ >>> images = provider.generate(
112
+ ... prompt="Epic dragon",
113
+ ... model="midjourney",
114
+ ... amount=3,
115
+ ... additional_params={"data": {"steps": 30}}
116
+ ... )
117
+
118
+ Args:
119
+ prompt (str): Your image description
120
+ model (str): Model to use (default: "midjourney")
121
+ amount (int): How many images you want (default: 1)
122
+ max_retries (int): Max retry attempts if something fails (default: 3)
123
+ retry_delay (int): Seconds to wait between retries (default: 5)
124
+ additional_params (dict, optional): Extra params for the API
125
+
126
+ Returns:
127
+ List[bytes]: Your generated images
128
+
129
+ Raises:
130
+ ValueError: If the inputs ain't valid
131
+ RequestException: If the API calls fail after retries
132
+ json.JSONDecodeError: If the API response is invalid
133
+ """
134
+ assert bool(prompt), "Prompt cannot be null"
135
+ assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
136
+
137
+ all_models = self.AVAILABLE_MODELS["standard"] + self.AVAILABLE_MODELS["prodia"]
138
+ assert model in all_models, f"Model should be one of {all_models}"
139
+
140
+ self.prompt = prompt
141
+ response = []
142
+
143
+ payload = {
144
+ "prompt": prompt,
145
+ "model": "prodia" if model in self.AVAILABLE_MODELS["prodia"] else model,
146
+ }
147
+
148
+ if model in self.AVAILABLE_MODELS["prodia"]:
149
+ payload["data"] = {
150
+ "model": model,
151
+ "steps": 25,
152
+ "cfg_scale": 7,
153
+ "sampler": "DPM++ 2M Karras",
154
+ "negative_prompt": ""
155
+ }
156
+ if additional_params:
157
+ payload.update(additional_params)
158
+
159
+ if self.logging:
160
+ logger.info(f"Generating {amount} images with {model}... 🎨")
161
+ for attempt in range(max_retries):
162
+ try:
163
+ resp = self.session.post(self.url, json=payload, timeout=self.timeout)
164
+ resp.raise_for_status()
165
+
166
+ # Remove leading underscores and then parse JSON
167
+ response_data = json.loads(resp.text.lstrip("_"))
168
+
169
+ if response_data.get("status") and "images" in response_data:
170
+ for image_url in response_data["images"]:
171
+ img_resp = requests.get(image_url)
172
+ img_resp.raise_for_status()
173
+ response.append(img_resp.content)
174
+ if self.logging:
175
+ logger.success("Images generated successfully! 🎉")
176
+ break
177
+ else:
178
+ raise Exception("Failed to generate image: " + str(response_data))
179
+ except json.JSONDecodeError as json_err:
180
+ if self.logging:
181
+ logger.error(f"JSON Decode Error: {json_err} 😢")
182
+ logger.debug(f"Raw response: {resp.text}")
183
+ if attempt == max_retries - 1:
184
+ raise
185
+ except RequestException as e:
186
+ if self.logging:
187
+ logger.error(f"Failed to generate images: {e} 😢")
188
+ if attempt == max_retries - 1:
189
+ raise
190
+ if self.logging:
191
+ logger.warning(f"Retrying in {retry_delay} seconds... 🔄")
192
+ time.sleep(retry_delay)
193
+
194
+ return response
195
+
196
+ def save(
197
+ self,
198
+ response: List[bytes],
199
+ name: Optional[str] = None,
200
+ dir: Optional[Union[str, Path]] = None,
201
+ filenames_prefix: str = "",
202
+ ) -> List[str]:
203
+ """Save your fire generated images! 💾
204
+
205
+ Examples:
206
+ >>> provider = NexraImager()
207
+ >>> images = provider.generate("Cool art")
208
+ >>> # Save with default settings
209
+ >>> paths = provider.save(images)
210
+ >>> # Save with custom name and directory
211
+ >>> paths = provider.save(
212
+ ... images,
213
+ ... name="my_art",
214
+ ... dir="my_images",
215
+ ... filenames_prefix="test_"
216
+ ... )
217
+
218
+ Args:
219
+ response (List[bytes]): Your generated images
220
+ name (Optional[str]): Custom name for your images
221
+ dir (Optional[Union[str, Path]]): Where to save the images (default: current directory)
222
+ filenames_prefix (str): Prefix for your image files
223
+
224
+ Returns:
225
+ List[str]: Paths to your saved images
226
+ """
227
+ save_dir = dir if dir else os.getcwd()
228
+ if not os.path.exists(save_dir):
229
+ os.makedirs(save_dir)
230
+ if self.logging:
231
+ logger.info(f"Created directory: {save_dir} 📁")
232
+
233
+ name = self.prompt if name is None else name
234
+ filenames = []
235
+
236
+ if self.logging:
237
+ logger.info(f"Saving {len(response)} images... 💾")
238
+ for i, image in enumerate(response):
239
+ filename = f"{filenames_prefix}{name}_{i}.{self.image_extension}"
240
+ filepath = os.path.join(save_dir, filename)
241
+
242
+ with open(filepath, "wb") as fh:
243
+ fh.write(image)
244
+ filenames.append(filename)
245
+ if self.logging:
246
+ logger.success(f"Saved image to: {filepath} 💾")
247
+
248
+ if self.logging:
249
+ logger.success(f"Images saved successfully! Check {dir} 🎉")
250
+ return filenames
251
+
252
+ if __name__ == "__main__":
253
+ bot = NexraImager()
254
+ try:
255
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", "midjourney")
256
+ print(bot.save(resp))
257
+ except Exception as e:
258
+ logger.error(f"An error occurred: {e} 😢")
@@ -0,0 +1,23 @@
1
+ """PollinationsAI Provider Package - Your go-to for text-to-image generation! 🎨
2
+
3
+ Examples:
4
+ >>> # Synchronous usage
5
+ >>> from webscout import PollinationsAI
6
+ >>> provider = PollinationsAI()
7
+ >>> images = provider.generate("A cool cyberpunk city")
8
+ >>> provider.save(images, dir="my_images")
9
+ >>>
10
+ >>> # Asynchronous usage
11
+ >>> import asyncio
12
+ >>> from webscout import AsyncPollinationsAI
13
+ >>> async def main():
14
+ ... provider = AsyncPollinationsAI()
15
+ ... images = await provider.generate("A cool cyberpunk city")
16
+ ... await provider.save(images, dir="my_images")
17
+ >>> asyncio.run(main())
18
+ """
19
+
20
+ from .sync_pollinations import PollinationsAI
21
+ from .async_pollinations import AsyncPollinationsAI
22
+
23
+ __all__ = ["PollinationsAI", "AsyncPollinationsAI"]
@@ -0,0 +1,330 @@
1
+ """PollinationsAI Async Provider - Same fire, but async! ⚡
2
+
3
+ Examples:
4
+ >>> from webscout import AsyncPollinationsAI
5
+ >>> import asyncio
6
+ >>>
7
+ >>> async def main():
8
+ ... provider = AsyncPollinationsAI()
9
+ ... # Generate a single image
10
+ ... images = await provider.generate("A cool cyberpunk city at night")
11
+ ... paths = await provider.save(images, dir="my_images")
12
+ ... print(f"Saved images to: {paths}")
13
+ ...
14
+ >>> asyncio.run(main())
15
+ """
16
+
17
+ import aiohttp
18
+ import asyncio
19
+ import os
20
+ import time
21
+ from typing import List, Optional, Union
22
+ from string import punctuation
23
+ from random import choice
24
+ from pathlib import Path
25
+ from typing import AsyncGenerator
26
+
27
+ from webscout.AIbase import AsyncImageProvider
28
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
29
+ from webscout.litagent import LitAgent
30
+
31
+ # Set up logging with cyberpunk style! 🎨
32
+ logger = LitLogger(
33
+ name="AsyncPollinationsAI",
34
+ format=LogFormat.MODERN_EMOJI,
35
+ color_scheme=ColorScheme.CYBERPUNK
36
+ )
37
+
38
+ # Get a fresh user agent! 🔄
39
+ agent = LitAgent()
40
+
41
+ class AsyncPollinationsAI(AsyncImageProvider):
42
+ """Your async homie for generating fire images using pollinations.ai! 🎨
43
+
44
+ This provider supports various models and image sizes, with built-in retry logic
45
+ and error handling to make sure you get your images no cap! 💯
46
+
47
+ Examples:
48
+ >>> provider = AsyncPollinationsAI()
49
+ >>>
50
+ >>> # Generate one image with default model
51
+ >>> async def single_image():
52
+ ... image = await provider.generate("A futuristic city")
53
+ ... await provider.save(image, "city.jpg")
54
+ >>>
55
+ >>> # Generate multiple with specific model
56
+ >>> async def multiple_images():
57
+ ... images = await provider.generate(
58
+ ... prompt="Space station",
59
+ ... amount=3,
60
+ ... width=1024,
61
+ ... height=1024,
62
+ ... model="flux-3d" # For 3D-style images
63
+ ... )
64
+ ... await provider.save(images, dir="space_pics")
65
+ >>>
66
+ >>> # Try different models
67
+ >>> async def try_models():
68
+ ... # Anime style
69
+ ... anime = await provider.generate(
70
+ ... prompt="Anime character",
71
+ ... model="flux-anime"
72
+ ... )
73
+ ... # Realistic style
74
+ ... real = await provider.generate(
75
+ ... prompt="Portrait photo",
76
+ ... model="flux-realism"
77
+ ... )
78
+ ... # Fast generation
79
+ ... quick = await provider.generate(
80
+ ... prompt="Quick sketch",
81
+ ... model="turbo"
82
+ ... )
83
+
84
+ Attributes:
85
+ AVAILABLE_MODELS (list): Available models to use:
86
+ - "flux": Default model, good for general use
87
+ - "flux-realism": Enhanced realism
88
+ - "flux-cablyai": CablyAI style
89
+ - "flux-anime": Anime/manga style
90
+ - "flux-3d": 3D-style renders
91
+ - "any-dark": Dark/gothic style
92
+ - "flux-pro": Professional quality
93
+ - "turbo": Fast generation
94
+ DEFAULT_MODEL (str): Default model to use ("flux")
95
+ """
96
+
97
+ AVAILABLE_MODELS = [
98
+ "flux",
99
+ "flux-realism",
100
+ "flux-cablyai",
101
+ "flux-anime",
102
+ "flux-3d",
103
+ "any-dark",
104
+ "flux-pro",
105
+ "turbo"
106
+ ]
107
+ DEFAULT_MODEL = "flux"
108
+
109
+ def __init__(
110
+ self,
111
+ timeout: int = 60,
112
+ proxies: Optional[dict] = None
113
+ ):
114
+ """Initialize your AsyncPollinationsAI provider with custom settings
115
+
116
+ Examples:
117
+ >>> provider = AsyncPollinationsAI(timeout=30)
118
+ >>> provider = AsyncPollinationsAI(proxies={"http": "http://proxy:8080"})
119
+
120
+ Args:
121
+ timeout (int): HTTP request timeout in seconds (default: 60)
122
+ proxies (dict, optional): Proxy configuration for requests
123
+ """
124
+ self.image_gen_endpoint = "https://image.pollinations.ai/prompt/{prompt}"
125
+ self.headers = {
126
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
127
+ "Accept-Language": "en-US,en;q=0.5",
128
+ "Accept-Encoding": "gzip, deflate",
129
+ "User-Agent": agent.random(),
130
+ }
131
+
132
+ self.timeout = aiohttp.ClientTimeout(total=timeout)
133
+ self.proxies = proxies
134
+ self.prompt: str = "AI-generated image - webscout"
135
+ self.image_extension: str = "jpeg"
136
+
137
+ async def generate(
138
+ self,
139
+ prompt: str,
140
+ amount: int = 1,
141
+ additives: bool = True,
142
+ width: int = 768,
143
+ height: int = 768,
144
+ model: str = DEFAULT_MODEL,
145
+ max_retries: int = 3,
146
+ retry_delay: int = 5,
147
+ negative_prompt: Optional[str] = None,
148
+ seed: Optional[int] = None,
149
+ ) -> List[bytes]:
150
+ """Generate some fire images from your prompt asynchronously! ⚡
151
+
152
+ Examples:
153
+ >>> provider = AsyncPollinationsAI()
154
+ >>> async def example():
155
+ ... # Basic usage
156
+ ... images = await provider.generate("Cool art")
157
+ ... # Advanced usage
158
+ ... images = await provider.generate(
159
+ ... prompt="Epic dragon",
160
+ ... amount=3,
161
+ ... model="flux-3d"
162
+ ... )
163
+
164
+ Args:
165
+ prompt (str): Your image description
166
+ amount (int): How many images you want (default: 1)
167
+ additives (bool): Make each prompt unique for variety (default: True)
168
+ width (int): Image width (default: 768)
169
+ height (int): Image height (default: 768)
170
+ model (str): Model to use - check AVAILABLE_MODELS (default: "flux")
171
+ max_retries (int): Max retry attempts if something fails (default: 3)
172
+ retry_delay (int): Seconds to wait between retries (default: 5)
173
+ negative_prompt (str, optional): What you don't want in the image
174
+ seed (int, optional): Seed for reproducible results
175
+
176
+ Returns:
177
+ List[bytes]: Your generated images as bytes
178
+
179
+ Raises:
180
+ ValueError: If the inputs ain't valid
181
+ aiohttp.ClientError: If the API calls fail after retries
182
+ """
183
+ # Input validation
184
+ if not prompt:
185
+ raise ValueError("Yo fam, the prompt can't be empty! 🤔")
186
+ if not isinstance(amount, int) or amount < 1:
187
+ raise ValueError("Amount needs to be a positive number! 📈")
188
+ if model not in self.AVAILABLE_MODELS:
189
+ raise ValueError(f"Model must be one of {self.AVAILABLE_MODELS}! 🎯")
190
+
191
+ # Function to add random characters for variety
192
+ def add_variety():
193
+ return "" if not additives else "".join(choice(punctuation) for _ in range(5))
194
+
195
+ self.prompt = prompt
196
+ response = []
197
+
198
+ # Build base URL with parameters
199
+ base_params = {
200
+ "width": width,
201
+ "height": height,
202
+ "model": model
203
+ }
204
+
205
+ if negative_prompt:
206
+ base_params["negative"] = negative_prompt
207
+ if seed is not None:
208
+ base_params["seed"] = seed
209
+
210
+ async with aiohttp.ClientSession(headers=self.headers, timeout=self.timeout) as session:
211
+ tasks = []
212
+ for _ in range(amount):
213
+ current_prompt = f"{prompt}{add_variety()}"
214
+ params_str = "&".join(f"{k}={v}" for k, v in base_params.items())
215
+ url = f"{self.image_gen_endpoint.format(prompt=current_prompt)}?{params_str}"
216
+
217
+ logger.info(f"Queueing image {_ + 1}/{amount} generation... ⚡")
218
+ tasks.append(self._generate_single(session, url, max_retries, retry_delay))
219
+
220
+ response = await asyncio.gather(*tasks)
221
+ logger.success(f"Successfully generated {amount} images! 🎨")
222
+
223
+ return response
224
+
225
+ async def _generate_single(
226
+ self,
227
+ session: aiohttp.ClientSession,
228
+ url: str,
229
+ max_retries: int,
230
+ retry_delay: int
231
+ ) -> bytes:
232
+ """Helper method to generate a single image with retries"""
233
+ for attempt in range(max_retries):
234
+ try:
235
+ async with session.get(url, proxy=self.proxies) as resp:
236
+ resp.raise_for_status()
237
+ return await resp.read()
238
+ except aiohttp.ClientError as e:
239
+ if attempt == max_retries - 1:
240
+ logger.error(f"Failed to generate image: {e} 😢")
241
+ raise
242
+ logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
243
+ await asyncio.sleep(retry_delay)
244
+
245
+ async def save(
246
+ self,
247
+ response: Union[AsyncGenerator[bytes, None], List[bytes]],
248
+ name: Optional[str] = None,
249
+ dir: Optional[Union[str, Path]] = None,
250
+ filenames_prefix: str = "",
251
+ ) -> List[str]:
252
+ """Save your fire generated images asynchronously! 💾
253
+
254
+ Examples:
255
+ >>> provider = AsyncPollinationsAI()
256
+ >>> async def example():
257
+ ... images = await provider.generate("Cool art")
258
+ ... # Save with default settings
259
+ ... paths = await provider.save(images)
260
+ ... # Save with custom name and directory
261
+ ... paths = await provider.save(
262
+ ... images,
263
+ ... name="my_art",
264
+ ... dir="my_images",
265
+ ... filenames_prefix="test_"
266
+ ... )
267
+
268
+ Args:
269
+ response (Union[AsyncGenerator[bytes, None], List[bytes]]): Your generated images
270
+ name (Optional[str]): Custom name for your images
271
+ dir (Optional[Union[str, Path]]): Where to save the images (default: current directory)
272
+ filenames_prefix (str): Prefix for your image files
273
+
274
+ Returns:
275
+ List[str]: Paths to your saved images
276
+ """
277
+ save_dir = dir if dir else os.getcwd()
278
+ if not os.path.exists(save_dir):
279
+ os.makedirs(save_dir)
280
+ logger.info(f"Created directory: {save_dir} 📁")
281
+
282
+ saved_paths = []
283
+ timestamp = int(time.time())
284
+
285
+ async def save_single_image(image_bytes: bytes, index: int) -> str:
286
+ if name:
287
+ filename = f"{filenames_prefix}{name}_{index}.{self.image_extension}"
288
+ else:
289
+ filename = f"{filenames_prefix}pollinations_{timestamp}_{index}.{self.image_extension}"
290
+
291
+ filepath = os.path.join(save_dir, filename)
292
+
293
+ # Write file using asyncio
294
+ async with asyncio.Lock():
295
+ with open(filepath, "wb") as f:
296
+ f.write(image_bytes)
297
+
298
+ logger.success(f"Saved image to: {filepath} 💾")
299
+ return filepath
300
+
301
+ # Handle both List[bytes] and AsyncGenerator
302
+ if isinstance(response, list):
303
+ image_list = response
304
+ else:
305
+ image_list = [chunk async for chunk in response]
306
+
307
+ tasks = [save_single_image(img, i) for i, img in enumerate(image_list)]
308
+ saved_paths = await asyncio.gather(*tasks)
309
+ logger.success(f"Successfully saved all {len(saved_paths)} images! 🎉")
310
+ return saved_paths
311
+
312
+
313
+ if __name__ == "__main__":
314
+ # Example usage
315
+ async def main():
316
+ provider = AsyncPollinationsAI()
317
+ try:
318
+ images = await provider.generate(
319
+ prompt="A cyberpunk city at night with neon lights",
320
+ amount=2,
321
+ width=1024,
322
+ height=1024,
323
+ model="sdxl"
324
+ )
325
+ paths = await provider.save(images, dir="generated_images")
326
+ print(f"Successfully saved images to: {paths}")
327
+ except Exception as e:
328
+ print(f"Oops, something went wrong: {e}")
329
+
330
+ asyncio.run(main())