webscout 7.4__py3-none-any.whl → 7.6__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 (137) hide show
  1. webscout/AIauto.py +5 -53
  2. webscout/AIutel.py +8 -318
  3. webscout/DWEBS.py +460 -489
  4. webscout/Extra/YTToolkit/YTdownloader.py +14 -53
  5. webscout/Extra/YTToolkit/transcriber.py +12 -13
  6. webscout/Extra/YTToolkit/ytapi/video.py +0 -1
  7. webscout/Extra/__init__.py +0 -1
  8. webscout/Extra/autocoder/autocoder_utiles.py +0 -4
  9. webscout/Extra/autocoder/rawdog.py +13 -41
  10. webscout/Extra/gguf.py +652 -428
  11. webscout/Extra/weather.py +178 -156
  12. webscout/Extra/weather_ascii.py +70 -17
  13. webscout/Litlogger/core/logger.py +1 -2
  14. webscout/Litlogger/handlers/file.py +1 -1
  15. webscout/Litlogger/styles/formats.py +0 -2
  16. webscout/Litlogger/utils/detectors.py +0 -1
  17. webscout/Provider/AISEARCH/DeepFind.py +0 -1
  18. webscout/Provider/AISEARCH/ISou.py +1 -1
  19. webscout/Provider/AISEARCH/felo_search.py +0 -1
  20. webscout/Provider/AllenAI.py +24 -9
  21. webscout/Provider/C4ai.py +432 -0
  22. webscout/Provider/ChatGPTGratis.py +24 -56
  23. webscout/Provider/Cloudflare.py +18 -21
  24. webscout/Provider/DeepSeek.py +27 -48
  25. webscout/Provider/Deepinfra.py +129 -53
  26. webscout/Provider/Gemini.py +1 -1
  27. webscout/Provider/GithubChat.py +362 -0
  28. webscout/Provider/Glider.py +25 -8
  29. webscout/Provider/HF_space/qwen_qwen2.py +2 -2
  30. webscout/Provider/HeckAI.py +38 -5
  31. webscout/Provider/HuggingFaceChat.py +462 -0
  32. webscout/Provider/Jadve.py +20 -5
  33. webscout/Provider/Marcus.py +7 -50
  34. webscout/Provider/Netwrck.py +43 -67
  35. webscout/Provider/PI.py +4 -2
  36. webscout/Provider/Perplexitylabs.py +26 -6
  37. webscout/Provider/Phind.py +29 -3
  38. webscout/Provider/PizzaGPT.py +10 -51
  39. webscout/Provider/TTI/AiForce/async_aiforce.py +4 -37
  40. webscout/Provider/TTI/AiForce/sync_aiforce.py +41 -38
  41. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -9
  42. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +206 -206
  43. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -192
  44. webscout/Provider/TTI/MagicStudio/__init__.py +2 -0
  45. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +111 -0
  46. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +109 -0
  47. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +5 -24
  48. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +2 -22
  49. webscout/Provider/TTI/__init__.py +2 -3
  50. webscout/Provider/TTI/aiarta/__init__.py +2 -0
  51. webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
  52. webscout/Provider/TTI/aiarta/sync_aiarta.py +440 -0
  53. webscout/Provider/TTI/fastflux/__init__.py +22 -0
  54. webscout/Provider/TTI/fastflux/async_fastflux.py +257 -0
  55. webscout/Provider/TTI/fastflux/sync_fastflux.py +247 -0
  56. webscout/Provider/TTS/__init__.py +2 -2
  57. webscout/Provider/TTS/deepgram.py +12 -39
  58. webscout/Provider/TTS/elevenlabs.py +14 -40
  59. webscout/Provider/TTS/gesserit.py +11 -35
  60. webscout/Provider/TTS/murfai.py +13 -39
  61. webscout/Provider/TTS/parler.py +17 -40
  62. webscout/Provider/TTS/speechma.py +180 -0
  63. webscout/Provider/TTS/streamElements.py +17 -44
  64. webscout/Provider/TextPollinationsAI.py +39 -59
  65. webscout/Provider/Venice.py +217 -200
  66. webscout/Provider/WiseCat.py +27 -5
  67. webscout/Provider/Youchat.py +63 -36
  68. webscout/Provider/__init__.py +13 -8
  69. webscout/Provider/akashgpt.py +28 -10
  70. webscout/Provider/copilot.py +416 -0
  71. webscout/Provider/flowith.py +196 -0
  72. webscout/Provider/freeaichat.py +32 -45
  73. webscout/Provider/granite.py +17 -53
  74. webscout/Provider/koala.py +20 -5
  75. webscout/Provider/llamatutor.py +7 -47
  76. webscout/Provider/llmchat.py +36 -53
  77. webscout/Provider/multichat.py +92 -98
  78. webscout/Provider/talkai.py +1 -0
  79. webscout/Provider/turboseek.py +3 -0
  80. webscout/Provider/tutorai.py +2 -0
  81. webscout/Provider/typegpt.py +154 -64
  82. webscout/Provider/x0gpt.py +3 -1
  83. webscout/Provider/yep.py +102 -20
  84. webscout/__init__.py +3 -0
  85. webscout/cli.py +4 -40
  86. webscout/conversation.py +1 -10
  87. webscout/exceptions.py +19 -9
  88. webscout/litagent/__init__.py +2 -2
  89. webscout/litagent/agent.py +351 -20
  90. webscout/litagent/constants.py +34 -5
  91. webscout/litprinter/__init__.py +0 -3
  92. webscout/models.py +181 -0
  93. webscout/optimizers.py +1 -1
  94. webscout/prompt_manager.py +2 -8
  95. webscout/scout/core/scout.py +1 -4
  96. webscout/scout/core/search_result.py +1 -1
  97. webscout/scout/core/text_utils.py +1 -1
  98. webscout/scout/core.py +2 -5
  99. webscout/scout/element.py +1 -1
  100. webscout/scout/parsers/html_parser.py +1 -1
  101. webscout/scout/utils.py +0 -1
  102. webscout/swiftcli/__init__.py +1 -3
  103. webscout/tempid.py +1 -1
  104. webscout/update_checker.py +55 -95
  105. webscout/version.py +1 -1
  106. webscout/webscout_search_async.py +1 -2
  107. webscout/yep_search.py +297 -297
  108. webscout-7.6.dist-info/LICENSE.md +146 -0
  109. {webscout-7.4.dist-info → webscout-7.6.dist-info}/METADATA +104 -514
  110. {webscout-7.4.dist-info → webscout-7.6.dist-info}/RECORD +113 -120
  111. webscout/Extra/autollama.py +0 -231
  112. webscout/Local/__init__.py +0 -10
  113. webscout/Local/_version.py +0 -3
  114. webscout/Local/formats.py +0 -747
  115. webscout/Local/model.py +0 -1368
  116. webscout/Local/samplers.py +0 -125
  117. webscout/Local/thread.py +0 -539
  118. webscout/Local/ui.py +0 -401
  119. webscout/Local/utils.py +0 -388
  120. webscout/Provider/Amigo.py +0 -274
  121. webscout/Provider/Bing.py +0 -243
  122. webscout/Provider/DiscordRocks.py +0 -253
  123. webscout/Provider/TTI/blackbox/__init__.py +0 -4
  124. webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
  125. webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
  126. webscout/Provider/TTI/deepinfra/__init__.py +0 -4
  127. webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
  128. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
  129. webscout/Provider/TTI/imgninza/__init__.py +0 -4
  130. webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
  131. webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
  132. webscout/Provider/TTS/voicepod.py +0 -117
  133. webscout/Provider/dgaf.py +0 -214
  134. webscout-7.4.dist-info/LICENSE.md +0 -211
  135. {webscout-7.4.dist-info → webscout-7.6.dist-info}/WHEEL +0 -0
  136. {webscout-7.4.dist-info → webscout-7.6.dist-info}/entry_points.txt +0 -0
  137. {webscout-7.4.dist-info → webscout-7.6.dist-info}/top_level.txt +0 -0
@@ -1,199 +0,0 @@
1
- import requests
2
- import os
3
- from typing import List
4
- from string import punctuation
5
- from random import choice
6
- from random import randint
7
- import base64
8
-
9
- from webscout.AIbase import ImageProvider
10
- from webscout.litagent import LitAgent # Import our fire user agent generator 🔥
11
- from webscout.Litlogger import Logger # For that cyberpunk logging swag ⚡
12
-
13
- # Initialize our fire logger 🚀
14
- logger = Logger("DeepInfraImager")
15
-
16
- class DeepInfraImager(ImageProvider):
17
- """
18
- DeepInfra Image Provider - Your go-to for fire AI art! 🎨
19
-
20
- >>> # Generate some fire art! 🔥
21
- >>> imager = DeepInfraImager(logging=True)
22
- >>> images = imager.generate("Epic dragon breathing fire", amount=2)
23
- >>> paths = imager.save(images)
24
- >>> print(paths)
25
- ['epic_dragon_0.png', 'epic_dragon_1.png']
26
-
27
- >>> # Turn off logging for stealth mode 🥷
28
- >>> quiet_imager = DeepInfraImager(logging=False)
29
- >>> images = quiet_imager.generate("Cyberpunk city at night")
30
- >>> paths = quiet_imager.save(images)
31
- """
32
-
33
- def __init__(
34
- self,
35
- model: str = "black-forest-labs/FLUX-1-schnell",
36
- timeout: int = 60,
37
- proxies: dict = {},
38
- logging: bool = True
39
- ):
40
- """Initialize your DeepInfra provider with custom settings! ⚙️
41
-
42
- Args:
43
- model (str): Which model to use (default: black-forest-labs/FLUX-1-schnell)
44
- timeout (int): Request timeout in seconds (default: 60)
45
- proxies (dict): Proxy settings for requests (default: {})
46
- logging (bool): Enable fire logging (default: True)
47
- """
48
- self.image_gen_endpoint: str = f"https://api.deepinfra.com/v1/inference/{model}"
49
- self.headers = {
50
- "Accept": "application/json, text/plain, */*",
51
- "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
52
- "Accept-Encoding": "gzip, deflate, br, zstd",
53
- "User-Agent": LitAgent().random(), # Using our fire random agent! 🔥
54
- "DNT": "1",
55
- "Origin": "https://deepinfra.com",
56
- "Referer": "https://deepinfra.com/",
57
- "Sec-CH-UA": '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
58
- "Sec-CH-UA-Mobile": "?0",
59
- "Sec-CH-UA-Platform": '"Windows"',
60
- "Sec-Fetch-Dest": "empty",
61
- "Sec-Fetch-Mode": "cors",
62
- "Sec-Fetch-Site": "same-site"
63
- }
64
- self.session = requests.Session()
65
- self.session.headers.update(self.headers)
66
- self.session.proxies.update(proxies)
67
- self.timeout = timeout
68
- self.prompt: str = "AI-generated image - webscout"
69
- self.image_extension: str = "png"
70
- self.logging = logging
71
- if self.logging:
72
- logger.info("DeepInfraImager initialized! Ready to create some fire art! 🚀")
73
-
74
- def generate(
75
- self, prompt: str, amount: int = 1, additives: bool = True,
76
- num_inference_steps: int = 25, guidance_scale: float = 7.5,
77
- width: int = 1024, height: int = 1024, seed: int = None
78
- ) -> List[bytes]:
79
- """Generate some fire images from your prompt! 🎨
80
-
81
- Args:
82
- prompt (str): Your creative prompt
83
- amount (int): How many images to generate
84
- additives (bool): Add random characters to make prompts unique
85
- num_inference_steps (int): Number of inference steps
86
- guidance_scale (float): Guidance scale for generation
87
- width (int): Image width
88
- height (int): Image height
89
- seed (int, optional): Random seed for reproducibility
90
-
91
- Returns:
92
- List[bytes]: Your generated images as bytes
93
- """
94
- assert bool(prompt), "Prompt cannot be null"
95
- assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
96
- assert amount > 0, "Amount should be greater than 0"
97
-
98
- ads = lambda: (
99
- ""
100
- if not additives
101
- else choice(punctuation)
102
- + choice(punctuation)
103
- + choice(punctuation)
104
- + choice(punctuation)
105
- + choice(punctuation)
106
- )
107
-
108
- if self.logging:
109
- logger.info(f"Generating {amount} images... 🎨")
110
-
111
- self.prompt = prompt
112
- response = []
113
- for _ in range(amount):
114
- payload = {
115
- "prompt": prompt + ads(),
116
- "num_inference_steps": num_inference_steps,
117
- "guidance_scale": guidance_scale,
118
- "width": width,
119
- "height": height,
120
- "seed": seed if seed is not None else randint(1, 10000),
121
- }
122
- try:
123
- resp = self.session.post(url=self.image_gen_endpoint, json=payload, timeout=self.timeout)
124
- resp.raise_for_status()
125
- # Extract base64 encoded image data and decode it
126
- image_data = resp.json()['images'][0].split(",")[1]
127
- image_bytes = base64.b64decode(image_data)
128
- response.append(image_bytes)
129
- if self.logging:
130
- logger.success(f"Generated image {len(response)}/{amount}! 🎨")
131
- except Exception as e:
132
- if self.logging:
133
- logger.error(f"Failed to generate image: {e} 😢")
134
- raise
135
-
136
- if self.logging:
137
- logger.success("All images generated successfully! 🎉")
138
- return response
139
-
140
- def save(
141
- self,
142
- response: List[bytes],
143
- name: str = None,
144
- dir: str = os.getcwd(),
145
- filenames_prefix: str = "",
146
- ) -> List[str]:
147
- """Save your fire images! 💾
148
-
149
- Args:
150
- response (List[bytes]): List of image data
151
- name (str, optional): Base name for saved files
152
- dir (str, optional): Where to save the images
153
- filenames_prefix (str, optional): Prefix for filenames
154
-
155
- Returns:
156
- List[str]: List of saved filenames
157
- """
158
- assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
159
- name = self.prompt if name is None else name
160
-
161
- if not os.path.exists(dir):
162
- os.makedirs(dir)
163
- if self.logging:
164
- logger.info(f"Created directory: {dir} 📁")
165
-
166
- if self.logging:
167
- logger.info(f"Saving {len(response)} images... 💾")
168
-
169
- filenames = []
170
- count = 0
171
- for image in response:
172
- def complete_path():
173
- count_value = "" if count == 0 else f"_{count}"
174
- return os.path.join(dir, name + count_value + "." + self.image_extension)
175
-
176
- while os.path.isfile(complete_path()):
177
- count += 1
178
-
179
- absolute_path_to_file = complete_path()
180
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
181
-
182
- with open(absolute_path_to_file, "wb") as fh:
183
- fh.write(image)
184
- if self.logging:
185
- logger.success(f"Saved image to: {absolute_path_to_file} 💾")
186
-
187
- if self.logging:
188
- logger.success(f"All images saved successfully! Check {dir} 🎉")
189
- return filenames
190
-
191
-
192
- if __name__ == "__main__":
193
- bot = DeepInfraImager()
194
- try:
195
- resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
196
- print(bot.save(resp))
197
- except Exception as e:
198
- if bot.logging:
199
- logger.error(f"An error occurred: {e} 😢")
@@ -1,4 +0,0 @@
1
- from .sync_ninza import NinjaImager
2
- from .async_ninza import AsyncNinjaImager
3
-
4
- __all__ = ["NinjaImager", "AsyncNinjaImager"]
@@ -1,214 +0,0 @@
1
- import aiohttp
2
- import asyncio
3
- import json
4
- import os
5
- from typing import List, Dict, Optional, Union, AsyncGenerator
6
- import aiofiles
7
-
8
- from webscout.AIbase import AsyncImageProvider
9
- from webscout import exceptions
10
- from webscout.litagent import agent # Import our fire user agent generator 🔥
11
- from webscout.Litlogger import Logger # For that cyberpunk logging swag ⚡
12
-
13
- # Initialize our fire logger 🚀
14
- logger = Logger("AsyncNinjaImager")
15
-
16
- class AsyncNinjaImager(AsyncImageProvider):
17
- """
18
- Async image provider for NinjaChat.ai - Your go-to for fire AI art! 🎨
19
-
20
- >>> # Generate some fire art asynchronously! 🔥
21
- >>> async def generate_art():
22
- ... imager = AsyncNinjaImager(logging=True)
23
- ... images = await imager.generate("Epic dragon breathing fire", amount=2)
24
- ... paths = await imager.save(images)
25
- ... print(paths)
26
- >>> asyncio.run(generate_art())
27
- ['epic_dragon_0.png', 'epic_dragon_1.png']
28
-
29
- >>> # Turn off logging for stealth mode 🥷
30
- >>> async def stealth_art():
31
- ... quiet_imager = AsyncNinjaImager(logging=False)
32
- ... images = await quiet_imager.generate("Cyberpunk city at night")
33
- ... paths = await quiet_imager.save(images)
34
- >>> asyncio.run(stealth_art())
35
- """
36
-
37
- AVAILABLE_MODELS = {
38
- "stable-diffusion": "https://www.ninjachat.ai/api/image-generator",
39
- "flux-dev": "https://www.ninjachat.ai/api/flux-image-generator",
40
- }
41
-
42
- def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
43
- """Initialize your async NinjaChatImager with custom settings! ⚙️
44
-
45
- Args:
46
- timeout (int): Request timeout in seconds (default: 60)
47
- proxies (dict): Proxy settings for requests (default: {})
48
- logging (bool): Enable fire logging (default: True)
49
- """
50
- self.headers = {
51
- "Accept": "*/*",
52
- "Accept-Encoding": "gzip, deflate, br, zstd",
53
- "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
54
- "Content-Type": "application/json",
55
- "DNT": "1",
56
- "Origin": "https://www.ninjachat.ai",
57
- "Priority": "u=1, i",
58
- "Referer": "https://www.ninjachat.ai/image-generation",
59
- "Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
60
- "Sec-CH-UA-Mobile": "?0",
61
- "Sec-CH-UA-Platform": '"Windows"',
62
- "Sec-Fetch-Dest": "empty",
63
- "Sec-Fetch-Mode": "cors",
64
- "Sec-Fetch-Site": "same-origin",
65
- "User-Agent": agent.random() # Using our fire random agent! 🔥
66
- }
67
- self.timeout = timeout
68
- self.proxies = proxies
69
- self.prompt = "AI-generated image - webscout"
70
- self.image_extension = "png"
71
- self.logging = logging
72
- if self.logging:
73
- logger.info("AsyncNinjaImager initialized! Ready to create some fire art! 🚀")
74
-
75
- async def generate(
76
- self, prompt: str, amount: int = 1, model: str = "flux-dev"
77
- ) -> List[bytes]:
78
- """Generate some fire images from your prompt! 🎨
79
-
80
- Args:
81
- prompt (str): Your creative prompt
82
- amount (int): How many images to generate
83
- model (str): Which model to use (default: flux-dev)
84
-
85
- Returns:
86
- List[bytes]: Your generated images as bytes
87
- """
88
- assert bool(prompt), "Prompt cannot be null"
89
- assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
90
-
91
- if model not in self.AVAILABLE_MODELS:
92
- raise exceptions.ModelNotFoundError(
93
- f"Model '{model}' not found. Available models: {', '.join(self.AVAILABLE_MODELS)}"
94
- )
95
-
96
- self.prompt = prompt
97
- url = self.AVAILABLE_MODELS[model]
98
-
99
- payload = {
100
- "prompt": prompt,
101
- "model": model if model == "flux-dev" else "stable-diffusion",
102
- "negativePrompt": "",
103
- "cfg": 7,
104
- "aspectRatio": "1:1",
105
- "outputFormat": self.image_extension,
106
- "numOutputs": amount,
107
- "outputQuality": 90
108
- }
109
-
110
- if self.logging:
111
- logger.info(f"Generating {amount} images with {model}... 🎨")
112
-
113
- response = []
114
- async with aiohttp.ClientSession(headers=self.headers) as session:
115
- try:
116
- async with session.post(url, json=payload, timeout=self.timeout) as resp:
117
- if resp.status != 200:
118
- if self.logging:
119
- logger.error(f"Request failed with status {resp.status} 😢")
120
- raise exceptions.FailedToGenerateResponseError(
121
- f"Request failed with status code: {resp.status}, {await resp.text()}"
122
- )
123
-
124
- data = await resp.json()
125
-
126
- if 'output' not in data:
127
- if self.logging:
128
- logger.error("Invalid API response format 😢")
129
- raise exceptions.InvalidResponseError("Invalid API response format: 'output' key missing.")
130
-
131
- for img_url in data['output']:
132
- async with session.get(img_url) as img_resp:
133
- img_resp.raise_for_status()
134
- response.append(await img_resp.read())
135
- if self.logging:
136
- logger.success(f"Generated image {len(response)}/{amount}! 🎨")
137
-
138
- except aiohttp.ClientError as e:
139
- if self.logging:
140
- logger.error(f"Connection error: {e} 😢")
141
- raise exceptions.APIConnectionError(f"An error occurred during the request: {e}")
142
- except json.JSONDecodeError as e:
143
- if self.logging:
144
- logger.error(f"Failed to parse response: {e} 😢")
145
- raise exceptions.InvalidResponseError(f"Failed to parse JSON response: {e}")
146
-
147
- if self.logging:
148
- logger.success("All images generated successfully! 🎉")
149
- return response
150
-
151
- async def save(
152
- self,
153
- response: Union[List[bytes], AsyncGenerator[bytes, None]],
154
- name: str = None,
155
- dir: str = os.getcwd(),
156
- filenames_prefix: str = "",
157
- ) -> List[str]:
158
- """Save your fire images! 💾
159
-
160
- Args:
161
- response (Union[List[bytes], AsyncGenerator[bytes, None]]): Image data
162
- name (str, optional): Base name for saved files
163
- dir (str, optional): Where to save the images
164
- filenames_prefix (str, optional): Prefix for filenames
165
-
166
- Returns:
167
- List[str]: List of saved filenames
168
- """
169
- if not os.path.exists(dir):
170
- os.makedirs(dir)
171
- if self.logging:
172
- logger.info(f"Created directory: {dir} 📁")
173
-
174
- name = self.prompt if name is None else name
175
- saved_paths = []
176
-
177
- async def save_single_image(image_bytes: bytes, index: int) -> str:
178
- filename = f"{filenames_prefix}{name}_{index}.{self.image_extension}"
179
- filepath = os.path.join(dir, filename)
180
-
181
- async with aiofiles.open(filepath, "wb") as f:
182
- await f.write(image_bytes)
183
-
184
- if self.logging:
185
- logger.success(f"Saved image to: {filepath} 💾")
186
- return filename
187
-
188
- if isinstance(response, list):
189
- image_list = response
190
- else:
191
- image_list = [chunk async for chunk in response]
192
-
193
- if self.logging:
194
- logger.info(f"Saving {len(image_list)} images... 💾")
195
-
196
- tasks = [save_single_image(img, i) for i, img in enumerate(image_list)]
197
- saved_paths = await asyncio.gather(*tasks)
198
-
199
- if self.logging:
200
- logger.success(f"All images saved successfully! Check {dir} 🎉")
201
- return saved_paths
202
-
203
-
204
- if __name__ == "__main__":
205
- async def main():
206
- bot = AsyncNinjaImager()
207
- try:
208
- resp = await bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
209
- paths = await bot.save(resp)
210
- print(paths)
211
- except Exception as e:
212
- print(f"An error occurred: {e}")
213
-
214
- asyncio.run(main())
@@ -1,209 +0,0 @@
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 Logger # For that cyberpunk logging swag ⚡
10
-
11
- # Initialize our fire logger 🚀
12
- logger = Logger("NinjaImager")
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}")