webscout 6.2b0__py3-none-any.whl → 6.4__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 (97) hide show
  1. webscout/AIauto.py +191 -176
  2. webscout/AIbase.py +112 -239
  3. webscout/AIutel.py +488 -1130
  4. webscout/Agents/functioncall.py +248 -198
  5. webscout/Bing_search.py +250 -153
  6. webscout/DWEBS.py +454 -178
  7. webscout/Extra/__init__.py +2 -1
  8. webscout/Extra/autocoder/__init__.py +9 -0
  9. webscout/Extra/autocoder/autocoder_utiles.py +121 -0
  10. webscout/Extra/autocoder/rawdog.py +681 -0
  11. webscout/Extra/autollama.py +246 -195
  12. webscout/Extra/gguf.py +441 -226
  13. webscout/Extra/weather.py +172 -67
  14. webscout/LLM.py +442 -100
  15. webscout/Litlogger/__init__.py +681 -0
  16. webscout/Local/formats.py +4 -2
  17. webscout/Provider/Amigo.py +19 -10
  18. webscout/Provider/Andi.py +0 -33
  19. webscout/Provider/Blackboxai.py +4 -204
  20. webscout/Provider/DARKAI.py +1 -1
  21. webscout/Provider/EDITEE.py +1 -1
  22. webscout/Provider/Llama3.py +1 -1
  23. webscout/Provider/Marcus.py +137 -0
  24. webscout/Provider/NinjaChat.py +1 -1
  25. webscout/Provider/PI.py +221 -207
  26. webscout/Provider/Perplexity.py +598 -598
  27. webscout/Provider/RoboCoders.py +206 -0
  28. webscout/Provider/TTI/AiForce/__init__.py +22 -0
  29. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
  30. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
  31. webscout/Provider/TTI/Nexra/__init__.py +22 -0
  32. webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
  33. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
  34. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
  35. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
  36. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
  37. webscout/Provider/TTI/__init__.py +3 -4
  38. webscout/Provider/TTI/artbit/__init__.py +22 -0
  39. webscout/Provider/TTI/artbit/async_artbit.py +184 -0
  40. webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
  41. webscout/Provider/TTI/blackbox/__init__.py +4 -0
  42. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
  43. webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
  44. webscout/Provider/TTI/deepinfra/__init__.py +4 -0
  45. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
  46. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
  47. webscout/Provider/TTI/huggingface/__init__.py +22 -0
  48. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
  49. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
  50. webscout/Provider/TTI/imgninza/__init__.py +4 -0
  51. webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
  52. webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
  53. webscout/Provider/TTI/talkai/__init__.py +4 -0
  54. webscout/Provider/TTI/talkai/async_talkai.py +229 -0
  55. webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
  56. webscout/Provider/__init__.py +146 -132
  57. webscout/Provider/askmyai.py +158 -0
  58. webscout/Provider/cerebras.py +227 -206
  59. webscout/Provider/geminiapi.py +208 -198
  60. webscout/Provider/llama3mitril.py +180 -0
  61. webscout/Provider/llmchat.py +203 -0
  62. webscout/Provider/mhystical.py +176 -0
  63. webscout/Provider/perplexitylabs.py +265 -0
  64. webscout/Provider/talkai.py +196 -0
  65. webscout/Provider/twitterclone.py +251 -244
  66. webscout/Provider/typegpt.py +359 -0
  67. webscout/__init__.py +28 -23
  68. webscout/__main__.py +5 -5
  69. webscout/cli.py +327 -347
  70. webscout/conversation.py +227 -0
  71. webscout/exceptions.py +161 -29
  72. webscout/litagent/__init__.py +172 -0
  73. webscout/litprinter/__init__.py +831 -0
  74. webscout/optimizers.py +270 -0
  75. webscout/prompt_manager.py +279 -0
  76. webscout/swiftcli/__init__.py +810 -0
  77. webscout/transcriber.py +479 -551
  78. webscout/update_checker.py +125 -0
  79. webscout/version.py +1 -1
  80. webscout-6.4.dist-info/LICENSE.md +211 -0
  81. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/METADATA +34 -55
  82. webscout-6.4.dist-info/RECORD +154 -0
  83. webscout/Provider/TTI/AIuncensored.py +0 -103
  84. webscout/Provider/TTI/Nexra.py +0 -120
  85. webscout/Provider/TTI/PollinationsAI.py +0 -138
  86. webscout/Provider/TTI/WebSimAI.py +0 -142
  87. webscout/Provider/TTI/aiforce.py +0 -160
  88. webscout/Provider/TTI/artbit.py +0 -141
  89. webscout/Provider/TTI/deepinfra.py +0 -148
  90. webscout/Provider/TTI/huggingface.py +0 -155
  91. webscout/models.py +0 -23
  92. webscout-6.2b0.dist-info/LICENSE.md +0 -50
  93. webscout-6.2b0.dist-info/RECORD +0 -118
  94. /webscout/{g4f.py → gpt4free.py} +0 -0
  95. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/WHEEL +0 -0
  96. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/entry_points.txt +0 -0
  97. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/top_level.txt +0 -0
@@ -1,136 +1,209 @@
1
- import requests
2
- import json
3
- import os
4
- from typing import List, Dict, Optional
5
-
6
- from webscout.AIbase import ImageProvider
7
- from webscout import exceptions # Import exceptions module
8
-
9
-
10
- class NinjaImager(ImageProvider):
11
- """
12
- Image provider for NinjaChat.ai.
13
- """
14
-
15
- AVAILABLE_MODELS = {
16
- "stable-diffusion": "https://www.ninjachat.ai/api/image-generator",
17
- "flux-dev": "https://www.ninjachat.ai/api/flux-image-generator",
18
- }
19
-
20
- def __init__(self, timeout: int = 60, proxies: dict = {}):
21
- """Initializes the NinjaChatImager class."""
22
- self.headers = {
23
- "Accept": "*/*",
24
- "Accept-Encoding": "gzip, deflate, br, zstd",
25
- "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
26
- "Content-Type": "application/json",
27
- "DNT": "1",
28
- "Origin": "https://www.ninjachat.ai",
29
- "Priority": "u=1, i",
30
- "Referer": "https://www.ninjachat.ai/image-generation",
31
- "Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
32
- "Sec-CH-UA-Mobile": "?0",
33
- "Sec-CH-UA-Platform": '"Windows"',
34
- "Sec-Fetch-Dest": "empty",
35
- "Sec-Fetch-Mode": "cors",
36
- "Sec-Fetch-Site": "same-origin",
37
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
38
- }
39
- self.session = requests.Session()
40
- self.session.headers.update(self.headers)
41
- self.session.proxies.update(proxies)
42
- self.timeout = timeout
43
- self.prompt = "AI-generated image - webscout"
44
- self.image_extension = "png" # Default extension
45
-
46
- def generate(self, prompt: str, amount: int = 1, model: str = "flux-dev") -> List[str]:
47
- """Generate images from a prompt."""
48
-
49
- assert bool(prompt), "Prompt cannot be null"
50
- assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
51
-
52
- if model not in self.AVAILABLE_MODELS:
53
- raise exceptions.ModelNotFoundError(f"Model '{model}' not found. Available models: {', '.join(self.AVAILABLE_MODELS)}")
54
-
55
- self.prompt = prompt # Store the prompt
56
- url = self.AVAILABLE_MODELS[model]
57
-
58
- payload = {
59
- "prompt": prompt,
60
- "model": model if model == "flux-dev" else "stable-diffusion", # Pass model name to API if needed
61
- "negativePrompt": "", #Use negative prompt from API's data structure
62
- "cfg": 7,
63
- "aspectRatio": "1:1",
64
- "outputFormat": self.image_extension,
65
- "numOutputs": amount,
66
- "outputQuality": 90
67
- }
68
-
69
-
70
- image_urls = []
71
- try:
72
- with requests.post(url, headers=self.headers, json=payload, timeout=self.timeout) as response:
73
- if response.status_code != 200:
74
- raise exceptions.FailedToGenerateResponseError(f"Request failed with status code: {response.status_code}, {response.text}") # Raise Webscout exception
75
-
76
- data = response.json()
77
-
78
- if 'output' not in data:
79
- raise exceptions.InvalidResponseError("Invalid API response format: 'output' key missing.")
80
-
81
- for img_url in data['output']:
82
- image_urls.append(img_url)
83
-
84
- except requests.exceptions.RequestException as e:
85
- raise exceptions.APIConnectionError(f"An error occurred during the request: {e}") # More specific exception
86
- except json.JSONDecodeError as e:
87
- raise exceptions.InvalidResponseError(f"Failed to parse JSON response: {e}")
88
-
89
- return image_urls
90
-
91
-
92
- def save(
93
- self,
94
- response: List[str],
95
- name: str = None,
96
- dir: str = os.getcwd(),
97
- filenames_prefix: str = "",
98
- ) -> List[str]:
99
- """Saves generated images."""
100
-
101
- assert isinstance(response, list), f"Response should be a list, not {type(response)}"
102
- name = self.prompt if name is None else name
103
-
104
- filenames = []
105
- count = 0
106
- for img_url in response:
107
- def complete_path():
108
- count_value = "" if count == 0 else f"_{count}"
109
- return os.path.join(dir, name + count_value + "." + self.image_extension)
110
-
111
- while os.path.isfile(complete_path()):
112
- count += 1
113
-
114
- absolute_path_to_file = complete_path()
115
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
116
- try:
117
- with requests.get(img_url, stream=True, timeout=self.timeout) as img_response:
118
- img_response.raise_for_status()
119
- with open(absolute_path_to_file, "wb") as f:
120
- for chunk in img_response.iter_content(chunk_size=8192):
121
- f.write(chunk)
122
-
123
- except requests.exceptions.RequestException as e:
124
- raise exceptions.FailedToSaveImageError(f"An error occurred while downloading/saving image: {e}")
125
-
126
- return filenames
127
-
128
-
129
-
130
- if __name__ == "__main__":
131
- bot = NinjaImager()
132
- try:
133
- resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
134
- print(bot.save(resp))
135
- except Exception as e:
136
- print(f"An error occurred: {e}")
1
+ import requests
2
+ import json
3
+ import os
4
+ from typing import List, Dict, Optional
5
+
6
+ from webscout.AIbase import ImageProvider
7
+ from webscout import exceptions
8
+ from webscout.litagent import agent # Import our fire user agent generator 🔥
9
+ from webscout.Litlogger import LitLogger # For that cyberpunk logging swag ⚡
10
+
11
+ # Initialize our fire logger 🚀
12
+ logger = LitLogger("NinjaImager", "MODERN_EMOJI")
13
+
14
+ class NinjaImager(ImageProvider):
15
+ """
16
+ Image provider for NinjaChat.ai - Your go-to for fire AI art! 🎨
17
+
18
+ >>> # Generate some fire art! 🔥
19
+ >>> imager = NinjaImager(logging=True)
20
+ >>> images = imager.generate("Epic dragon breathing fire", amount=2)
21
+ >>> paths = imager.save(images)
22
+ >>> print(paths)
23
+ ['epic_dragon_0.png', 'epic_dragon_1.png']
24
+
25
+ >>> # Turn off logging for stealth mode 🥷
26
+ >>> quiet_imager = NinjaImager(logging=False)
27
+ >>> images = quiet_imager.generate("Cyberpunk city at night")
28
+ >>> paths = quiet_imager.save(images)
29
+ """
30
+
31
+ AVAILABLE_MODELS = {
32
+ "stable-diffusion": "https://www.ninjachat.ai/api/image-generator",
33
+ "flux-dev": "https://www.ninjachat.ai/api/flux-image-generator",
34
+ }
35
+
36
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
37
+ """Initialize your NinjaChatImager with custom settings! ⚙️
38
+
39
+ Args:
40
+ timeout (int): Request timeout in seconds (default: 60)
41
+ proxies (dict): Proxy settings for requests (default: {})
42
+ logging (bool): Enable fire logging (default: True)
43
+ """
44
+ self.headers = {
45
+ "Accept": "*/*",
46
+ "Accept-Encoding": "gzip, deflate, br, zstd",
47
+ "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
48
+ "Content-Type": "application/json",
49
+ "DNT": "1",
50
+ "Origin": "https://www.ninjachat.ai",
51
+ "Priority": "u=1, i",
52
+ "Referer": "https://www.ninjachat.ai/image-generation",
53
+ "Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
54
+ "Sec-CH-UA-Mobile": "?0",
55
+ "Sec-CH-UA-Platform": '"Windows"',
56
+ "Sec-Fetch-Dest": "empty",
57
+ "Sec-Fetch-Mode": "cors",
58
+ "Sec-Fetch-Site": "same-origin",
59
+ "User-Agent": agent.random() # Using our fire random agent! 🔥
60
+ }
61
+ self.session = requests.Session()
62
+ self.session.headers.update(self.headers)
63
+ self.session.proxies.update(proxies)
64
+ self.timeout = timeout
65
+ self.prompt = "AI-generated image - webscout"
66
+ self.image_extension = "png"
67
+ self.logging = logging
68
+ if self.logging:
69
+ logger.info("NinjaImager initialized! Ready to create some fire art! 🚀")
70
+
71
+ def generate(self, prompt: str, amount: int = 1, model: str = "flux-dev") -> List[str]:
72
+ """Generate some fire images from your prompt! 🎨
73
+
74
+ Args:
75
+ prompt (str): Your creative prompt
76
+ amount (int): How many images to generate
77
+ model (str): Which model to use (default: flux-dev)
78
+
79
+ Returns:
80
+ List[str]: URLs to your generated images
81
+ """
82
+ assert bool(prompt), "Prompt cannot be null"
83
+ assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
84
+
85
+ if model not in self.AVAILABLE_MODELS:
86
+ raise exceptions.ModelNotFoundError(
87
+ f"Model '{model}' not found. Available models: {', '.join(self.AVAILABLE_MODELS)}"
88
+ )
89
+
90
+ self.prompt = prompt
91
+ url = self.AVAILABLE_MODELS[model]
92
+
93
+ payload = {
94
+ "prompt": prompt,
95
+ "model": model if model == "flux-dev" else "stable-diffusion",
96
+ "negativePrompt": "",
97
+ "cfg": 7,
98
+ "aspectRatio": "1:1",
99
+ "outputFormat": self.image_extension,
100
+ "numOutputs": amount,
101
+ "outputQuality": 90
102
+ }
103
+
104
+ if self.logging:
105
+ logger.info(f"Generating {amount} images with {model}... 🎨")
106
+
107
+ image_urls = []
108
+ try:
109
+ with requests.post(url, headers=self.headers, json=payload, timeout=self.timeout) as response:
110
+ if response.status_code != 200:
111
+ if self.logging:
112
+ logger.error(f"Request failed with status {response.status_code} 😢")
113
+ raise exceptions.FailedToGenerateResponseError(
114
+ f"Request failed with status code: {response.status_code}, {response.text}"
115
+ )
116
+
117
+ data = response.json()
118
+
119
+ if 'output' not in data:
120
+ if self.logging:
121
+ logger.error("Invalid API response format 😢")
122
+ raise exceptions.InvalidResponseError("Invalid API response format: 'output' key missing.")
123
+
124
+ for img_url in data['output']:
125
+ image_urls.append(img_url)
126
+ if self.logging:
127
+ logger.success(f"Generated image {len(image_urls)}/{amount}! 🎨")
128
+
129
+ except requests.exceptions.RequestException as e:
130
+ if self.logging:
131
+ logger.error(f"Connection error: {e} 😢")
132
+ raise exceptions.APIConnectionError(f"An error occurred during the request: {e}")
133
+ except json.JSONDecodeError as e:
134
+ if self.logging:
135
+ logger.error(f"Failed to parse response: {e} 😢")
136
+ raise exceptions.InvalidResponseError(f"Failed to parse JSON response: {e}")
137
+
138
+ if self.logging:
139
+ logger.success("All images generated successfully! 🎉")
140
+ return image_urls
141
+
142
+ def save(
143
+ self,
144
+ response: List[str],
145
+ name: str = None,
146
+ dir: str = os.getcwd(),
147
+ filenames_prefix: str = "",
148
+ ) -> List[str]:
149
+ """Save your fire images! 💾
150
+
151
+ Args:
152
+ response (List[str]): List of image URLs
153
+ name (str, optional): Base name for saved files
154
+ dir (str, optional): Where to save the images
155
+ filenames_prefix (str, optional): Prefix for filenames
156
+
157
+ Returns:
158
+ List[str]: List of saved filenames
159
+ """
160
+ assert isinstance(response, list), f"Response should be a list, not {type(response)}"
161
+ name = self.prompt if name is None else name
162
+
163
+ if not os.path.exists(dir):
164
+ os.makedirs(dir)
165
+ if self.logging:
166
+ logger.info(f"Created directory: {dir} 📁")
167
+
168
+ if self.logging:
169
+ logger.info(f"Saving {len(response)} images... 💾")
170
+
171
+ filenames = []
172
+ count = 0
173
+ for img_url in response:
174
+ def complete_path():
175
+ count_value = "" if count == 0 else f"_{count}"
176
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
177
+
178
+ while os.path.isfile(complete_path()):
179
+ count += 1
180
+
181
+ absolute_path_to_file = complete_path()
182
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
183
+
184
+ try:
185
+ with requests.get(img_url, stream=True, timeout=self.timeout) as img_response:
186
+ img_response.raise_for_status()
187
+ with open(absolute_path_to_file, "wb") as f:
188
+ for chunk in img_response.iter_content(chunk_size=8192):
189
+ f.write(chunk)
190
+ if self.logging:
191
+ logger.success(f"Saved image to: {absolute_path_to_file} 💾")
192
+
193
+ except requests.exceptions.RequestException as e:
194
+ if self.logging:
195
+ logger.error(f"Failed to save image: {e} 😢")
196
+ raise exceptions.FailedToSaveImageError(f"An error occurred while downloading/saving image: {e}")
197
+
198
+ if self.logging:
199
+ logger.success(f"All images saved successfully! Check {dir} 🎉")
200
+ return filenames
201
+
202
+
203
+ if __name__ == "__main__":
204
+ bot = NinjaImager()
205
+ try:
206
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
207
+ print(bot.save(resp))
208
+ except Exception as e:
209
+ print(f"An error occurred: {e}")
@@ -0,0 +1,4 @@
1
+ from .sync_talkai import TalkaiImager
2
+ from .async_talkai import AsyncTalkaiImager
3
+
4
+ __all__ = ["TalkaiImager", "AsyncTalkaiImager"]
@@ -0,0 +1,229 @@
1
+ import uuid
2
+ import json
3
+ import os
4
+ from typing import Any, Dict, List, Union, AsyncGenerator
5
+ import aiohttp
6
+ import asyncio
7
+ import aiofiles
8
+
9
+ from webscout.AIbase import AsyncImageProvider
10
+ from webscout import exceptions
11
+ from webscout.litagent import agent # Import our fire user agent generator 🔥
12
+ from webscout.Litlogger import LitLogger # For that cyberpunk logging swag ⚡
13
+
14
+ # Initialize our fire logger 🚀
15
+ logger = LitLogger("AsyncTalkaiImager")
16
+
17
+ class AsyncTalkaiImager(AsyncImageProvider):
18
+ """
19
+ Async TalkAI Image Provider - Your go-to for fire AI art! 🎨
20
+
21
+ >>> # Generate some fire art asynchronously! 🔥
22
+ >>> async def generate_art():
23
+ ... imager = AsyncTalkaiImager(logging=True)
24
+ ... images = await imager.generate("Epic dragon breathing fire", amount=2)
25
+ ... paths = await imager.save(images)
26
+ ... print(paths)
27
+ >>> asyncio.run(generate_art())
28
+ ['epic_dragon_0.png', 'epic_dragon_1.png']
29
+
30
+ >>> # Turn off logging for stealth mode 🥷
31
+ >>> async def stealth_art():
32
+ ... quiet_imager = AsyncTalkaiImager(logging=False)
33
+ ... images = await quiet_imager.generate("Cyberpunk city at night")
34
+ ... paths = await quiet_imager.save(images)
35
+ >>> asyncio.run(stealth_art())
36
+ """
37
+
38
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
39
+ """Initialize your async TalkAI provider with custom settings! ⚙️
40
+
41
+ Args:
42
+ timeout (int): Request timeout in seconds (default: 60)
43
+ proxies (dict): Proxy settings for requests (default: {})
44
+ logging (bool): Enable fire logging (default: True)
45
+ """
46
+ self.api_endpoint = "https://talkai.info/chat/send/"
47
+ self.headers = {
48
+ 'accept': 'application/json',
49
+ 'accept-language': 'en-US,en;q=0.9',
50
+ 'content-type': 'application/json',
51
+ 'origin': 'https://talkai.info',
52
+ 'referer': 'https://talkai.info/image/',
53
+ 'user-agent': agent.random(), # Using our fire random agent! 🔥
54
+ }
55
+ self.timeout = timeout
56
+ self.proxies = proxies
57
+ self.prompt: str = "AI-generated image - webscout"
58
+ self.image_extension: str = "png"
59
+ self.logging = logging
60
+ if self.logging:
61
+ logger.info("AsyncTalkaiImager initialized! Ready to create some fire art! 🚀")
62
+
63
+ async def generate(
64
+ self, prompt: str, amount: int = 1,
65
+ max_retries: int = 3, retry_delay: int = 5
66
+ ) -> List[str]:
67
+ """Generate some fire images from your prompt! 🎨
68
+
69
+ Args:
70
+ prompt (str): Your creative prompt
71
+ amount (int): How many images to generate
72
+ max_retries (int): Max retry attempts if generation fails
73
+ retry_delay (int): Seconds to wait between retries
74
+
75
+ Returns:
76
+ List[str]: List of image URLs
77
+ """
78
+ assert bool(prompt), "Prompt cannot be empty."
79
+ assert isinstance(amount, int) and amount > 0, "Amount must be a positive integer."
80
+
81
+ self.prompt = prompt
82
+ image_urls = []
83
+
84
+ if self.logging:
85
+ logger.info(f"Generating {amount} images... 🎨")
86
+
87
+ async with aiohttp.ClientSession(headers=self.headers) as session:
88
+ for _ in range(amount):
89
+ for attempt in range(max_retries):
90
+ try:
91
+ async with session.post(
92
+ self.api_endpoint,
93
+ json=self._create_payload(prompt),
94
+ timeout=self.timeout,
95
+ proxy=self.proxies.get('http') if self.proxies else None
96
+ ) as response:
97
+ response.raise_for_status()
98
+ data = await response.json()
99
+
100
+ if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]:
101
+ image_urls.append(data['data'][0]['url'])
102
+ if self.logging:
103
+ logger.success(f"Generated image {len(image_urls)}/{amount}! 🎨")
104
+ break
105
+ else:
106
+ raise exceptions.InvalidResponseError("No image URL found in API response.")
107
+
108
+ except aiohttp.ClientError as e:
109
+ if attempt == max_retries - 1:
110
+ if self.logging:
111
+ logger.error(f"Error making API request: {e} 😢")
112
+ raise exceptions.APIConnectionError(f"Error making API request: {e}") from e
113
+ else:
114
+ if self.logging:
115
+ logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
116
+ await asyncio.sleep(retry_delay)
117
+ except json.JSONDecodeError as e:
118
+ if self.logging:
119
+ logger.error(f"Invalid JSON response: {e} 😢")
120
+ raise exceptions.InvalidResponseError(f"Invalid JSON response: {e}") from e
121
+ except Exception as e:
122
+ if self.logging:
123
+ logger.error(f"An unexpected error occurred: {e} 😢")
124
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred: {e}") from e
125
+
126
+ if self.logging:
127
+ logger.success("All images generated successfully! 🎉")
128
+ return image_urls
129
+
130
+ def _create_payload(self, prompt: str) -> Dict[str, Any]:
131
+ """Create the API request payload 📦
132
+
133
+ Args:
134
+ prompt (str): The image generation prompt
135
+
136
+ Returns:
137
+ Dict[str, Any]: API request payload
138
+ """
139
+ return {
140
+ "type": "image",
141
+ "messagesHistory": [
142
+ {
143
+ "id": str(uuid.uuid4()),
144
+ "from": "you",
145
+ "content": prompt
146
+ }
147
+ ],
148
+ "settings": {
149
+ "model": "gpt-4o-mini" # Or another suitable model if available
150
+ }
151
+ }
152
+
153
+ async def save(
154
+ self,
155
+ response: Union[List[str], AsyncGenerator[str, None]],
156
+ name: str = None,
157
+ dir: str = os.getcwd(),
158
+ filenames_prefix: str = "",
159
+ ) -> List[str]:
160
+ """Save your fire images! 💾
161
+
162
+ Args:
163
+ response (Union[List[str], AsyncGenerator[str, None]]): Image URLs
164
+ name (str, optional): Base name for saved files
165
+ dir (str, optional): Where to save the images
166
+ filenames_prefix (str, optional): Prefix for filenames
167
+
168
+ Returns:
169
+ List[str]: List of saved filenames
170
+ """
171
+ if not os.path.exists(dir):
172
+ os.makedirs(dir)
173
+ if self.logging:
174
+ logger.info(f"Created directory: {dir} 📁")
175
+
176
+ name = self.prompt if name is None else name
177
+ saved_paths = []
178
+
179
+ async def save_single_image(url: str, index: int) -> str:
180
+ filename = f"{filenames_prefix}{name}_{index}.{self.image_extension}"
181
+ filepath = os.path.join(dir, filename)
182
+
183
+ async with aiohttp.ClientSession(headers=self.headers) as session:
184
+ try:
185
+ async with session.get(
186
+ url,
187
+ timeout=self.timeout,
188
+ proxy=self.proxies.get('http') if self.proxies else None
189
+ ) as response:
190
+ response.raise_for_status()
191
+ async with aiofiles.open(filepath, 'wb') as f:
192
+ async for chunk in response.content.iter_chunked(8192):
193
+ await f.write(chunk)
194
+ if self.logging:
195
+ logger.success(f"Saved image to: {filepath} 💾")
196
+ return filename
197
+ except aiohttp.ClientError as e:
198
+ if self.logging:
199
+ logger.error(f"Error downloading image from {url}: {e} 😢")
200
+ return None
201
+
202
+ if isinstance(response, list):
203
+ url_list = response
204
+ else:
205
+ url_list = [url async for url in response]
206
+
207
+ if self.logging:
208
+ logger.info(f"Saving {len(url_list)} images... 💾")
209
+
210
+ tasks = [save_single_image(url, i) for i, url in enumerate(url_list)]
211
+ saved_paths = await asyncio.gather(*tasks)
212
+
213
+ if self.logging:
214
+ logger.success(f"All images saved successfully! Check {dir} 🎉")
215
+ return saved_paths
216
+
217
+
218
+ if __name__ == "__main__":
219
+ async def main():
220
+ bot = AsyncTalkaiImager()
221
+ try:
222
+ resp = await bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
223
+ paths = await bot.save(resp)
224
+ print(paths)
225
+ except Exception as e:
226
+ if bot.logging:
227
+ logger.error(f"An error occurred: {e} 😢")
228
+
229
+ asyncio.run(main())