webscout 6.3__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.
- webscout/AIauto.py +191 -176
- webscout/AIbase.py +0 -197
- webscout/AIutel.py +488 -1130
- webscout/Bing_search.py +250 -153
- webscout/DWEBS.py +151 -19
- webscout/Extra/__init__.py +2 -1
- webscout/Extra/autocoder/__init__.py +9 -0
- webscout/Extra/autocoder/autocoder_utiles.py +121 -0
- webscout/Extra/autocoder/rawdog.py +681 -0
- webscout/Extra/autollama.py +246 -195
- webscout/Extra/gguf.py +441 -416
- webscout/LLM.py +206 -43
- webscout/Litlogger/__init__.py +681 -0
- webscout/Provider/DARKAI.py +1 -1
- webscout/Provider/EDITEE.py +1 -1
- webscout/Provider/NinjaChat.py +1 -1
- webscout/Provider/PI.py +221 -207
- webscout/Provider/Perplexity.py +598 -598
- webscout/Provider/RoboCoders.py +206 -0
- webscout/Provider/TTI/AiForce/__init__.py +22 -0
- webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
- webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
- webscout/Provider/TTI/Nexra/__init__.py +22 -0
- webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
- webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
- webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
- webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
- webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
- webscout/Provider/TTI/__init__.py +2 -4
- webscout/Provider/TTI/artbit/__init__.py +22 -0
- webscout/Provider/TTI/artbit/async_artbit.py +184 -0
- webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
- webscout/Provider/TTI/blackbox/__init__.py +4 -0
- webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
- webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
- webscout/Provider/TTI/deepinfra/__init__.py +4 -0
- webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
- webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
- webscout/Provider/TTI/huggingface/__init__.py +22 -0
- webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
- webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
- webscout/Provider/TTI/imgninza/__init__.py +4 -0
- webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
- webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
- webscout/Provider/TTI/talkai/__init__.py +4 -0
- webscout/Provider/TTI/talkai/async_talkai.py +229 -0
- webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
- webscout/Provider/__init__.py +146 -139
- webscout/Provider/askmyai.py +2 -2
- webscout/Provider/cerebras.py +227 -219
- webscout/Provider/llama3mitril.py +0 -1
- webscout/Provider/mhystical.py +176 -0
- webscout/Provider/perplexitylabs.py +265 -0
- webscout/Provider/twitterclone.py +251 -245
- webscout/Provider/typegpt.py +359 -0
- webscout/__init__.py +28 -23
- webscout/__main__.py +5 -5
- webscout/cli.py +252 -280
- webscout/conversation.py +227 -0
- webscout/exceptions.py +161 -29
- webscout/litagent/__init__.py +172 -0
- webscout/litprinter/__init__.py +831 -0
- webscout/optimizers.py +270 -0
- webscout/prompt_manager.py +279 -0
- webscout/swiftcli/__init__.py +810 -0
- webscout/transcriber.py +479 -551
- webscout/update_checker.py +125 -0
- webscout/version.py +1 -1
- {webscout-6.3.dist-info → webscout-6.4.dist-info}/METADATA +26 -45
- {webscout-6.3.dist-info → webscout-6.4.dist-info}/RECORD +75 -45
- webscout/Provider/TTI/AIuncensoredimage.py +0 -103
- webscout/Provider/TTI/Nexra.py +0 -120
- webscout/Provider/TTI/PollinationsAI.py +0 -138
- webscout/Provider/TTI/WebSimAI.py +0 -142
- webscout/Provider/TTI/aiforce.py +0 -160
- webscout/Provider/TTI/artbit.py +0 -141
- webscout/Provider/TTI/deepinfra.py +0 -148
- webscout/Provider/TTI/huggingface.py +0 -155
- webscout/Provider/TTI/talkai.py +0 -116
- webscout/models.py +0 -23
- /webscout/{g4f.py → gpt4free.py} +0 -0
- {webscout-6.3.dist-info → webscout-6.4.dist-info}/LICENSE.md +0 -0
- {webscout-6.3.dist-info → webscout-6.4.dist-info}/WHEEL +0 -0
- {webscout-6.3.dist-info → webscout-6.4.dist-info}/entry_points.txt +0 -0
- {webscout-6.3.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
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
self.
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
"
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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,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())
|