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,242 @@
1
+ import requests
2
+ import os
3
+ import time
4
+ from typing import List, Optional, Union
5
+ from string import punctuation
6
+ from random import choice
7
+ from requests.exceptions import RequestException
8
+ from pathlib import Path
9
+
10
+ from webscout.AIbase import ImageProvider
11
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
12
+ from webscout.litagent import LitAgent
13
+
14
+ # Initialize our fire logger and agent 🔥
15
+ logger = LitLogger(
16
+ "AiForce",
17
+ format=LogFormat.MODERN_EMOJI,
18
+ color_scheme=ColorScheme.CYBERPUNK
19
+ )
20
+ agent = LitAgent()
21
+
22
+ class AiForceimager(ImageProvider):
23
+ """Your go-to provider for generating fire images with AiForce! 🔥
24
+
25
+ Examples:
26
+ >>> # Basic usage
27
+ >>> provider = AiForceimager()
28
+ >>> images = provider.generate("Cool art")
29
+ >>> paths = provider.save(images)
30
+ >>>
31
+ >>> # Advanced usage
32
+ >>> provider = AiForceimager(timeout=120)
33
+ >>> images = provider.generate(
34
+ ... prompt="Epic dragon",
35
+ ... amount=3,
36
+ ... model="Flux-1.1-Pro",
37
+ ... width=1024,
38
+ ... height=1024
39
+ ... )
40
+ >>> paths = provider.save(images, name="dragon", dir="my_art")
41
+ """
42
+
43
+ AVAILABLE_MODELS = [
44
+ "stable-diffusion-xl-lightning",
45
+ "stable-diffusion-xl-base",
46
+ "Flux-1.1-Pro",
47
+ "ideogram",
48
+ "flux",
49
+ "flux-realism",
50
+ "flux-anime",
51
+ "flux-3d",
52
+ "flux-disney",
53
+ "flux-pixel",
54
+ "flux-4o",
55
+ "any-dark"
56
+ ]
57
+
58
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
59
+ """Initialize your AiForce provider with custom settings! ⚙️
60
+
61
+ Args:
62
+ timeout (int): Request timeout in seconds (default: 60)
63
+ proxies (dict): Proxy settings for requests (default: {})
64
+ logging (bool): Enable fire logging (default: True)
65
+ """
66
+ self.api_endpoint = "https://api.airforce/imagine2"
67
+ self.headers = {
68
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
69
+ "Accept-Language": "en-US,en;q=0.5",
70
+ "Accept-Encoding": "gzip, deflate",
71
+ "User-Agent": agent.random()
72
+ }
73
+ self.session = requests.Session()
74
+ self.session.headers.update(self.headers)
75
+ self.session.proxies.update(proxies)
76
+ self.timeout = timeout
77
+ self.prompt: str = "AI-generated image - webscout"
78
+ self.image_extension: str = "png"
79
+ self.logging = logging
80
+ if self.logging:
81
+ logger.info("AiForce provider initialized! 🚀")
82
+
83
+ def generate(
84
+ self,
85
+ prompt: str,
86
+ amount: int = 1,
87
+ additives: bool = True,
88
+ model: str = "Flux-1.1-Pro",
89
+ width: int = 768,
90
+ height: int = 768,
91
+ seed: Optional[int] = None,
92
+ max_retries: int = 3,
93
+ retry_delay: int = 5
94
+ ) -> List[bytes]:
95
+ """Generate some fire images from your prompt! 🎨
96
+
97
+ Examples:
98
+ >>> provider = AiForceimager()
99
+ >>> # Basic usage
100
+ >>> images = provider.generate("Cool art")
101
+ >>> # Advanced usage
102
+ >>> images = provider.generate(
103
+ ... prompt="Epic dragon",
104
+ ... amount=3,
105
+ ... model="Flux-1.1-Pro"
106
+ ... )
107
+
108
+ Args:
109
+ prompt (str): Your image description
110
+ amount (int): How many images you want (default: 1)
111
+ additives (bool): Make each prompt unique (default: True)
112
+ model (str): Model to use - check AVAILABLE_MODELS (default: "Flux-1.1-Pro")
113
+ width (int): Image width (default: 768)
114
+ height (int): Image height (default: 768)
115
+ seed (int, optional): Seed for reproducible results
116
+ max_retries (int): Max retry attempts if something fails (default: 3)
117
+ retry_delay (int): Seconds to wait between retries (default: 5)
118
+
119
+ Returns:
120
+ List[bytes]: Your generated images
121
+
122
+ Raises:
123
+ ValueError: If the inputs ain't valid
124
+ RequestException: If the API calls fail after retries
125
+ """
126
+ assert bool(prompt), "Prompt cannot be null"
127
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
128
+ assert amount > 0, "Amount should be greater than 0"
129
+ assert model in self.AVAILABLE_MODELS, f"Model should be one of {self.AVAILABLE_MODELS}"
130
+
131
+ ads = lambda: (
132
+ ""
133
+ if not additives
134
+ else choice(punctuation)
135
+ + choice(punctuation)
136
+ + choice(punctuation)
137
+ + choice(punctuation)
138
+ + choice(punctuation)
139
+ )
140
+
141
+ self.prompt = prompt
142
+ if self.logging:
143
+ logger.info(f"Generating {amount} images with {model}... 🎨")
144
+ response = []
145
+ for _ in range(amount):
146
+ url = f"{self.api_endpoint}?model={model}&prompt={prompt}&size={width}:{height}"
147
+ if seed:
148
+ url += f"&seed={seed}"
149
+
150
+ for attempt in range(max_retries):
151
+ try:
152
+ resp = self.session.get(url, timeout=self.timeout)
153
+ resp.raise_for_status()
154
+ response.append(resp.content)
155
+ if self.logging:
156
+ logger.success(f"Generated image {_ + 1}/{amount}! 🎨")
157
+ break
158
+ except RequestException as e:
159
+ if attempt == max_retries - 1:
160
+ if self.logging:
161
+ logger.error(f"Failed to generate image after {max_retries} attempts: {e} 😢")
162
+ raise
163
+ else:
164
+ if self.logging:
165
+ logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
166
+ time.sleep(retry_delay)
167
+
168
+ if self.logging:
169
+ logger.success("Images generated successfully! 🎉")
170
+ return response
171
+
172
+ def save(
173
+ self,
174
+ response: List[bytes],
175
+ name: Optional[str] = None,
176
+ dir: Optional[Union[str, Path]] = None,
177
+ filenames_prefix: str = "",
178
+ ) -> List[str]:
179
+ """Save your fire generated images! 💾
180
+
181
+ Examples:
182
+ >>> provider = AiForceimager()
183
+ >>> images = provider.generate("Cool art")
184
+ >>> # Save with default settings
185
+ >>> paths = provider.save(images)
186
+ >>> # Save with custom name and directory
187
+ >>> paths = provider.save(
188
+ ... images,
189
+ ... name="my_art",
190
+ ... dir="my_images",
191
+ ... filenames_prefix="test_"
192
+ ... )
193
+
194
+ Args:
195
+ response (List[bytes]): Your generated images
196
+ name (Optional[str]): Custom name for your images
197
+ dir (Optional[Union[str, Path]]): Where to save the images (default: current directory)
198
+ filenames_prefix (str): Prefix for your image files
199
+
200
+ Returns:
201
+ List[str]: Paths to your saved images
202
+ """
203
+ save_dir = dir if dir else os.getcwd()
204
+ if not os.path.exists(save_dir):
205
+ os.makedirs(save_dir)
206
+ if self.logging:
207
+ logger.info(f"Created directory: {save_dir} 📁")
208
+
209
+ name = self.prompt if name is None else name
210
+ if self.logging:
211
+ logger.info(f"Saving {len(response)} images... 💾")
212
+ filenames = []
213
+ count = 0
214
+
215
+ for image in response:
216
+ def complete_path():
217
+ count_value = "" if count == 0 else f"_{count}"
218
+ return os.path.join(save_dir, name + count_value + "." + self.image_extension)
219
+
220
+ while os.path.isfile(complete_path()):
221
+ count += 1
222
+
223
+ absolute_path_to_file = complete_path()
224
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
225
+
226
+ with open(absolute_path_to_file, "wb") as fh:
227
+ fh.write(image)
228
+ if self.logging:
229
+ logger.success(f"Saved image to: {absolute_path_to_file} 💾")
230
+
231
+ if self.logging:
232
+ logger.success(f"Images saved successfully! Check {dir} 🎉")
233
+ return filenames
234
+
235
+ if __name__ == "__main__":
236
+ bot = AiForceimager()
237
+ try:
238
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
239
+ print(bot.save(resp))
240
+ except Exception as e:
241
+ if bot.logging:
242
+ logger.error(f"An error occurred: {e} 😢")
@@ -0,0 +1,22 @@
1
+ """
2
+ Nexra - Your go-to provider for generating fire images! 🔥
3
+
4
+ Examples:
5
+ >>> # Sync Usage
6
+ >>> from webscout import NexraImager
7
+ >>> provider = NexraImager()
8
+ >>> images = provider.generate("Cool art")
9
+ >>> paths = provider.save(images)
10
+ >>>
11
+ >>> # Async Usage
12
+ >>> from webscout import AsyncNexraImager
13
+ >>> async def example():
14
+ ... provider = AsyncNexraImager()
15
+ ... images = await provider.generate("Epic dragon")
16
+ ... paths = await provider.save(images)
17
+ """
18
+
19
+ from .sync_nexra import NexraImager
20
+ from .async_nexra import AsyncNexraImager
21
+
22
+ __all__ = ["NexraImager", "AsyncNexraImager"]
@@ -0,0 +1,286 @@
1
+ import aiohttp
2
+ import asyncio
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import List, Optional, Union, AsyncGenerator
7
+ from pathlib import Path
8
+ from aiohttp import ClientError
9
+
10
+ from webscout.AIbase import AsyncImageProvider
11
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
12
+ from webscout.litagent import LitAgent
13
+
14
+ # Initialize our fire logger and agent 🔥
15
+ logger = LitLogger(
16
+ "AsyncNexra",
17
+ format=LogFormat.MODERN_EMOJI,
18
+ color_scheme=ColorScheme.CYBERPUNK
19
+ )
20
+ agent = LitAgent()
21
+
22
+ class AsyncNexraImager(AsyncImageProvider):
23
+ """Your go-to async provider for generating fire images with Nexra! ⚡
24
+
25
+ Examples:
26
+ >>> # Basic usage
27
+ >>> provider = AsyncNexraImager()
28
+ >>> async def example():
29
+ ... images = await provider.generate("Cool art")
30
+ ... paths = await provider.save(images)
31
+ >>>
32
+ >>> # Advanced usage
33
+ >>> provider = AsyncNexraImager(timeout=120)
34
+ >>> async def example():
35
+ ... images = await provider.generate(
36
+ ... prompt="Epic dragon",
37
+ ... model="midjourney",
38
+ ... additional_params={
39
+ ... "data": {
40
+ ... "steps": 30,
41
+ ... "cfg_scale": 8
42
+ ... }
43
+ ... }
44
+ ... )
45
+ ... paths = await provider.save(images, name="dragon", dir="my_art")
46
+ """
47
+
48
+ AVAILABLE_MODELS = {
49
+ "standard": [
50
+ "emi",
51
+ "stablediffusion-1.5",
52
+ "stablediffusion-2.1",
53
+ "sdxl-lora",
54
+ "dalle",
55
+ "dalle2",
56
+ "dalle-mini",
57
+ "flux",
58
+ "midjourney"
59
+ ],
60
+ "prodia": [
61
+ "dreamshaperXL10_alpha2.safetensors [c8afe2ef]",
62
+ "dynavisionXL_0411.safetensors [c39cc051]",
63
+ "juggernautXL_v45.safetensors [e75f5471]",
64
+ "realismEngineSDXL_v10.safetensors [af771c3f]",
65
+ "sd_xl_base_1.0.safetensors [be9edd61]",
66
+ "animagineXLV3_v30.safetensors [75f2f05b]",
67
+ "sd_xl_base_1.0_inpainting_0.1.safetensors [5679a81a]",
68
+ "turbovisionXL_v431.safetensors [78890989]",
69
+ "devlishphotorealism_sdxl15.safetensors [77cba69f]",
70
+ "realvisxlV40.safetensors [f7fdcb51]"
71
+ ]
72
+ }
73
+
74
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
75
+ """Initialize your async Nexra provider with custom settings! ⚙️
76
+
77
+ Args:
78
+ timeout (int): Request timeout in seconds (default: 60)
79
+ proxies (dict): Proxy settings for requests (default: {})
80
+ logging (bool): Enable fire logging (default: True)
81
+ """
82
+ self.url = "https://nexra.aryahcr.cc/api/image/complements"
83
+ self.headers = {
84
+ "Content-Type": "application/json",
85
+ "Accept": "application/json",
86
+ "User-Agent": agent.random()
87
+ }
88
+ self.timeout = timeout
89
+ self.proxies = proxies
90
+ self.prompt: str = "AI-generated image - webscout"
91
+ self.image_extension: str = "png"
92
+ self.logging = logging
93
+ if self.logging:
94
+ logger.info("AsyncNexra provider initialized! 🚀")
95
+
96
+ async def generate(
97
+ self,
98
+ prompt: str,
99
+ model: str = "midjourney",
100
+ amount: int = 1,
101
+ max_retries: int = 3,
102
+ retry_delay: int = 5,
103
+ additional_params: Optional[dict] = None
104
+ ) -> List[bytes]:
105
+ """Generate some fire images from your prompt asynchronously! ⚡
106
+
107
+ Examples:
108
+ >>> provider = AsyncNexraImager()
109
+ >>> async def example():
110
+ ... # Basic usage
111
+ ... images = await provider.generate("Cool art")
112
+ ... # Advanced usage
113
+ ... images = await provider.generate(
114
+ ... prompt="Epic dragon",
115
+ ... model="midjourney",
116
+ ... amount=3,
117
+ ... additional_params={"data": {"steps": 30}}
118
+ ... )
119
+
120
+ Args:
121
+ prompt (str): Your image description
122
+ model (str): Model to use (default: "midjourney")
123
+ amount (int): How many images you want (default: 1)
124
+ max_retries (int): Max retry attempts if something fails (default: 3)
125
+ retry_delay (int): Seconds to wait between retries (default: 5)
126
+ additional_params (dict, optional): Extra params for the API
127
+
128
+ Returns:
129
+ List[bytes]: Your generated images
130
+
131
+ Raises:
132
+ ValueError: If the inputs ain't valid
133
+ ClientError: If the API calls fail after retries
134
+ json.JSONDecodeError: If the API response is invalid
135
+ """
136
+ assert bool(prompt), "Prompt cannot be null"
137
+ assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
138
+
139
+ all_models = self.AVAILABLE_MODELS["standard"] + self.AVAILABLE_MODELS["prodia"]
140
+ assert model in all_models, f"Model should be one of {all_models}"
141
+
142
+ self.prompt = prompt
143
+ response = []
144
+
145
+ payload = {
146
+ "prompt": prompt,
147
+ "model": "prodia" if model in self.AVAILABLE_MODELS["prodia"] else model,
148
+ }
149
+
150
+ if model in self.AVAILABLE_MODELS["prodia"]:
151
+ payload["data"] = {
152
+ "model": model,
153
+ "steps": 25,
154
+ "cfg_scale": 7,
155
+ "sampler": "DPM++ 2M Karras",
156
+ "negative_prompt": ""
157
+ }
158
+ if additional_params:
159
+ payload.update(additional_params)
160
+
161
+ async with aiohttp.ClientSession(headers=self.headers) as session:
162
+ for attempt in range(max_retries):
163
+ try:
164
+ if self.logging:
165
+ logger.info(f"Generating {amount} images with {model}... 🎨")
166
+ async with session.post(
167
+ self.url,
168
+ json=payload,
169
+ timeout=self.timeout,
170
+ proxy=self.proxies.get('http')
171
+ ) as resp:
172
+ resp.raise_for_status()
173
+ text = await resp.text()
174
+
175
+ # Remove leading underscores and then parse JSON
176
+ response_data = json.loads(text.lstrip("_"))
177
+
178
+ if response_data.get("status") and "images" in response_data:
179
+ for image_url in response_data["images"]:
180
+ async with session.get(image_url) as img_resp:
181
+ img_resp.raise_for_status()
182
+ response.append(await img_resp.read())
183
+ if self.logging:
184
+ logger.success(f"Generated image {len(response)}/{amount}! 🎨")
185
+ break
186
+ else:
187
+ raise Exception("Failed to generate image: " + str(response_data))
188
+ except json.JSONDecodeError as json_err:
189
+ if self.logging:
190
+ logger.error(f"JSON Decode Error: {json_err} 😢")
191
+ logger.debug(f"Raw response: {text}")
192
+ if attempt == max_retries - 1:
193
+ raise
194
+ except ClientError as e:
195
+ if self.logging:
196
+ logger.error(f"Failed to generate images: {e} 😢")
197
+ if attempt == max_retries - 1:
198
+ raise
199
+ if self.logging:
200
+ logger.warning(f"Retrying in {retry_delay} seconds... 🔄")
201
+ await asyncio.sleep(retry_delay)
202
+
203
+ if self.logging:
204
+ logger.success("Images generated successfully! 🎉")
205
+ return response
206
+
207
+ async def save(
208
+ self,
209
+ response: Union[AsyncGenerator[bytes, None], List[bytes]],
210
+ name: Optional[str] = None,
211
+ dir: Optional[Union[str, Path]] = None,
212
+ filenames_prefix: str = "",
213
+ ) -> List[str]:
214
+ """Save your fire generated images asynchronously! 💾
215
+
216
+ Examples:
217
+ >>> provider = AsyncNexraImager()
218
+ >>> async def example():
219
+ ... images = await provider.generate("Cool art")
220
+ ... # Save with default settings
221
+ ... paths = await provider.save(images)
222
+ ... # Save with custom name and directory
223
+ ... paths = await provider.save(
224
+ ... images,
225
+ ... name="my_art",
226
+ ... dir="my_images",
227
+ ... filenames_prefix="test_"
228
+ ... )
229
+
230
+ Args:
231
+ response (Union[AsyncGenerator[bytes, None], List[bytes]]): Your generated images
232
+ name (Optional[str]): Custom name for your images
233
+ dir (Optional[Union[str, Path]]): Where to save the images (default: current directory)
234
+ filenames_prefix (str): Prefix for your image files
235
+
236
+ Returns:
237
+ List[str]: Paths to your saved images
238
+ """
239
+ save_dir = dir if dir else os.getcwd()
240
+ if not os.path.exists(save_dir):
241
+ os.makedirs(save_dir)
242
+ if self.logging:
243
+ logger.info(f"Created directory: {save_dir} 📁")
244
+
245
+ name = self.prompt if name is None else name
246
+ saved_paths = []
247
+ timestamp = int(time.time())
248
+
249
+ async def save_single_image(image_bytes: bytes, index: int) -> str:
250
+ filename = f"{filenames_prefix}{name}_{index}.{self.image_extension}"
251
+ filepath = os.path.join(save_dir, filename)
252
+
253
+ # Write file using asyncio
254
+ async with asyncio.Lock():
255
+ with open(filepath, "wb") as f:
256
+ f.write(image_bytes)
257
+
258
+ if self.logging:
259
+ logger.success(f"Saved image to: {filepath} 💾")
260
+ return filepath
261
+
262
+ # Handle both List[bytes] and AsyncGenerator
263
+ if isinstance(response, list):
264
+ image_list = response
265
+ else:
266
+ image_list = [chunk async for chunk in response]
267
+
268
+ if self.logging:
269
+ logger.info(f"Saving {len(image_list)} images... 💾")
270
+ tasks = [save_single_image(img, i) for i, img in enumerate(image_list)]
271
+ saved_paths = await asyncio.gather(*tasks)
272
+ if self.logging:
273
+ logger.success(f"Images saved successfully! Check {dir} 🎉")
274
+ return saved_paths
275
+
276
+ if __name__ == "__main__":
277
+ async def main():
278
+ bot = AsyncNexraImager()
279
+ try:
280
+ resp = await bot.generate("A shiny red sports car speeding down a scenic mountain road", "midjourney")
281
+ paths = await bot.save(resp)
282
+ print(paths)
283
+ except Exception as e:
284
+ logger.error(f"An error occurred: {e} 😢")
285
+
286
+ asyncio.run(main())