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.

Files changed (85) hide show
  1. webscout/AIauto.py +191 -176
  2. webscout/AIbase.py +0 -197
  3. webscout/AIutel.py +488 -1130
  4. webscout/Bing_search.py +250 -153
  5. webscout/DWEBS.py +151 -19
  6. webscout/Extra/__init__.py +2 -1
  7. webscout/Extra/autocoder/__init__.py +9 -0
  8. webscout/Extra/autocoder/autocoder_utiles.py +121 -0
  9. webscout/Extra/autocoder/rawdog.py +681 -0
  10. webscout/Extra/autollama.py +246 -195
  11. webscout/Extra/gguf.py +441 -416
  12. webscout/LLM.py +206 -43
  13. webscout/Litlogger/__init__.py +681 -0
  14. webscout/Provider/DARKAI.py +1 -1
  15. webscout/Provider/EDITEE.py +1 -1
  16. webscout/Provider/NinjaChat.py +1 -1
  17. webscout/Provider/PI.py +221 -207
  18. webscout/Provider/Perplexity.py +598 -598
  19. webscout/Provider/RoboCoders.py +206 -0
  20. webscout/Provider/TTI/AiForce/__init__.py +22 -0
  21. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
  22. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
  23. webscout/Provider/TTI/Nexra/__init__.py +22 -0
  24. webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
  25. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
  26. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
  27. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
  28. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
  29. webscout/Provider/TTI/__init__.py +2 -4
  30. webscout/Provider/TTI/artbit/__init__.py +22 -0
  31. webscout/Provider/TTI/artbit/async_artbit.py +184 -0
  32. webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
  33. webscout/Provider/TTI/blackbox/__init__.py +4 -0
  34. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
  35. webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
  36. webscout/Provider/TTI/deepinfra/__init__.py +4 -0
  37. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
  38. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
  39. webscout/Provider/TTI/huggingface/__init__.py +22 -0
  40. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
  41. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
  42. webscout/Provider/TTI/imgninza/__init__.py +4 -0
  43. webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
  44. webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
  45. webscout/Provider/TTI/talkai/__init__.py +4 -0
  46. webscout/Provider/TTI/talkai/async_talkai.py +229 -0
  47. webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
  48. webscout/Provider/__init__.py +146 -139
  49. webscout/Provider/askmyai.py +2 -2
  50. webscout/Provider/cerebras.py +227 -219
  51. webscout/Provider/llama3mitril.py +0 -1
  52. webscout/Provider/mhystical.py +176 -0
  53. webscout/Provider/perplexitylabs.py +265 -0
  54. webscout/Provider/twitterclone.py +251 -245
  55. webscout/Provider/typegpt.py +359 -0
  56. webscout/__init__.py +28 -23
  57. webscout/__main__.py +5 -5
  58. webscout/cli.py +252 -280
  59. webscout/conversation.py +227 -0
  60. webscout/exceptions.py +161 -29
  61. webscout/litagent/__init__.py +172 -0
  62. webscout/litprinter/__init__.py +831 -0
  63. webscout/optimizers.py +270 -0
  64. webscout/prompt_manager.py +279 -0
  65. webscout/swiftcli/__init__.py +810 -0
  66. webscout/transcriber.py +479 -551
  67. webscout/update_checker.py +125 -0
  68. webscout/version.py +1 -1
  69. {webscout-6.3.dist-info → webscout-6.4.dist-info}/METADATA +26 -45
  70. {webscout-6.3.dist-info → webscout-6.4.dist-info}/RECORD +75 -45
  71. webscout/Provider/TTI/AIuncensoredimage.py +0 -103
  72. webscout/Provider/TTI/Nexra.py +0 -120
  73. webscout/Provider/TTI/PollinationsAI.py +0 -138
  74. webscout/Provider/TTI/WebSimAI.py +0 -142
  75. webscout/Provider/TTI/aiforce.py +0 -160
  76. webscout/Provider/TTI/artbit.py +0 -141
  77. webscout/Provider/TTI/deepinfra.py +0 -148
  78. webscout/Provider/TTI/huggingface.py +0 -155
  79. webscout/Provider/TTI/talkai.py +0 -116
  80. webscout/models.py +0 -23
  81. /webscout/{g4f.py → gpt4free.py} +0 -0
  82. {webscout-6.3.dist-info → webscout-6.4.dist-info}/LICENSE.md +0 -0
  83. {webscout-6.3.dist-info → webscout-6.4.dist-info}/WHEEL +0 -0
  84. {webscout-6.3.dist-info → webscout-6.4.dist-info}/entry_points.txt +0 -0
  85. {webscout-6.3.dist-info → webscout-6.4.dist-info}/top_level.txt +0 -0
@@ -1,120 +0,0 @@
1
- import requests
2
- import json
3
- import os
4
- import time
5
- from typing import List, Optional
6
- from requests.exceptions import RequestException
7
-
8
- from webscout.AIbase import ImageProvider
9
-
10
- class NexraImager(ImageProvider):
11
- """Image provider for Nexra API"""
12
-
13
- AVAILABLE_MODELS = {
14
- "standard": ["emi", "stablediffusion-1.5", "stablediffusion-2.1", "sdxl-lora", "dalle", "dalle2", "dalle-mini", "flux", "midjourney"],
15
- "prodia": [
16
- "dreamshaperXL10_alpha2.safetensors [c8afe2ef]",
17
- "dynavisionXL_0411.safetensors [c39cc051]",
18
- "juggernautXL_v45.safetensors [e75f5471]",
19
- "realismEngineSDXL_v10.safetensors [af771c3f]",
20
- "sd_xl_base_1.0.safetensors [be9edd61]",
21
- "animagineXLV3_v30.safetensors [75f2f05b]",
22
- "sd_xl_base_1.0_inpainting_0.1.safetensors [5679a81a]",
23
- "turbovisionXL_v431.safetensors [78890989]",
24
- "devlishphotorealism_sdxl15.safetensors [77cba69f]",
25
- "realvisxlV40.safetensors [f7fdcb51]"
26
- ]
27
- }
28
-
29
- def __init__(self, timeout: int = 60, proxies: dict = {}):
30
- self.url = "https://nexra.aryahcr.cc/api/image/complements"
31
- self.headers = {"Content-Type": "application/json"}
32
- self.session = requests.Session()
33
- self.session.headers.update(self.headers)
34
- self.session.proxies.update(proxies)
35
- self.timeout = timeout
36
- self.prompt: str = "AI-generated image - webscout"
37
- self.image_extension: str = "png"
38
-
39
- def generate(
40
- self, prompt: str, model: str = "flux", amount: int = 1,
41
- max_retries: int = 3, retry_delay: int = 5,
42
- additional_params: Optional[dict] = None
43
- ) -> List[bytes]:
44
- assert bool(prompt), "Prompt cannot be null"
45
- assert isinstance(amount, int) and amount > 0, "Amount should be a positive integer"
46
-
47
- self.prompt = prompt
48
- response = []
49
-
50
- payload = {
51
- "prompt": prompt,
52
- "model": "prodia" if model in self.AVAILABLE_MODELS["prodia"] else model,
53
- }
54
-
55
- if model in self.AVAILABLE_MODELS["prodia"]:
56
- payload["data"] = {
57
- "model": model,
58
- "steps": 25,
59
- "cfg_scale": 7,
60
- "sampler": "DPM++ 2M Karras",
61
- "negative_prompt": ""
62
- }
63
- if additional_params:
64
- payload.update(additional_params)
65
-
66
- for _ in range(max_retries):
67
- try:
68
- resp = self.session.post(self.url, json=payload, timeout=self.timeout)
69
- resp.raise_for_status()
70
-
71
- # Remove leading underscores and then parse JSON
72
- response_data = json.loads(resp.text.lstrip("_"))
73
-
74
- if response_data.get("status") and "images" in response_data:
75
- for image_url in response_data["images"]:
76
- img_resp = requests.get(image_url)
77
- img_resp.raise_for_status()
78
- response.append(img_resp.content)
79
- break
80
- else:
81
- raise Exception("Failed to generate image: " + str(response_data))
82
- except json.JSONDecodeError as json_err:
83
- print(f"JSON Decode Error: {json_err}")
84
- print(f"Raw response: {resp.text}")
85
- if _ == max_retries - 1:
86
- raise
87
- except RequestException as e:
88
- print(f"Request Exception: {e}")
89
- if _ == max_retries - 1:
90
- raise
91
- print(f"Retrying in {retry_delay} seconds...")
92
- time.sleep(retry_delay)
93
-
94
- return response
95
-
96
- def save(
97
- self,
98
- response: List[bytes],
99
- name: str = None,
100
- dir: str = os.getcwd(),
101
- filenames_prefix: str = "",
102
- ) -> List[str]:
103
- assert isinstance(response, list), f"Response should be a list, not {type(response)}"
104
- name = self.prompt if name is None else name
105
-
106
- filenames = []
107
- for i, image in enumerate(response):
108
- filename = f"{filenames_prefix}{name}_{i}.{self.image_extension}"
109
- filepath = os.path.join(dir, filename)
110
-
111
- with open(filepath, "wb") as fh:
112
- fh.write(image)
113
- filenames.append(filename)
114
-
115
- return filenames
116
-
117
- if __name__ == "__main__":
118
- bot = NexraImager()
119
- resp_standard = bot.generate("AI-generated image - webscout", "midjourney", 1)
120
- print(bot.save(resp_standard))
@@ -1,138 +0,0 @@
1
- import requests
2
- import os
3
- import time
4
- from typing import List
5
- from string import punctuation
6
- from random import choice
7
- from requests.exceptions import RequestException
8
-
9
- from webscout.AIbase import ImageProvider
10
-
11
- class PollinationsAI(ImageProvider):
12
- """Image provider for pollinations.ai"""
13
-
14
- def __init__(self, timeout: int = 60, proxies: dict = {}):
15
- """Initializes the PollinationsAI class.
16
-
17
- Args:
18
- timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
19
- proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
20
- """
21
- self.image_gen_endpoint = "https://image.pollinations.ai/prompt/{prompt}?width={width}&height={height}&model={model}"
22
- self.headers = {
23
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
24
- "Accept-Language": "en-US,en;q=0.5",
25
- "Accept-Encoding": "gzip, deflate",
26
- "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
27
- }
28
- self.session = requests.Session()
29
- self.session.headers.update(self.headers)
30
- self.session.proxies.update(proxies)
31
- self.timeout = timeout
32
- self.prompt: str = "AI-generated image - webscout"
33
- self.image_extension: str = "jpeg"
34
-
35
- def generate(
36
- self, prompt: str, amount: int = 1, additives: bool = True,
37
- width: int = 768, height: int = 768, model: str = "flux",
38
- max_retries: int = 3, retry_delay: int = 5
39
- ) -> List[bytes]:
40
- """Generate image from prompt
41
-
42
- Args:
43
- prompt (str): Image description.
44
- amount (int): Total images to be generated. Defaults to 1.
45
- additives (bool, optional): Try to make each prompt unique. Defaults to True.
46
- width (int, optional): Width of the generated image. Defaults to 768.
47
- height (int, optional): Height of the generated image. Defaults to 768.
48
- model (str, optional): The model to use for image generation. Defaults to "flux".
49
- max_retries (int, optional): Maximum number of retry attempts. Defaults to 3.
50
- retry_delay (int, optional): Delay between retries in seconds. Defaults to 5.
51
-
52
- Returns:
53
- List[bytes]: List of generated images as bytes.
54
- """
55
- assert bool(prompt), "Prompt cannot be null"
56
- assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
57
- assert amount > 0, "Amount should be greater than 0"
58
-
59
- ads = lambda: (
60
- ""
61
- if not additives
62
- else choice(punctuation)
63
- + choice(punctuation)
64
- + choice(punctuation)
65
- + choice(punctuation)
66
- + choice(punctuation)
67
- )
68
-
69
- self.prompt = prompt
70
- response = []
71
- for _ in range(amount):
72
- url = self.image_gen_endpoint.format(
73
- prompt=prompt + ads(), width=width, height=height, model=model
74
- )
75
-
76
- for attempt in range(max_retries):
77
- try:
78
- resp = self.session.get(url, timeout=self.timeout)
79
- resp.raise_for_status()
80
- response.append(resp.content)
81
- break
82
- except RequestException as e:
83
- if attempt == max_retries - 1:
84
- print(f"Failed to generate image after {max_retries} attempts: {e}")
85
- raise
86
- else:
87
- print(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds...")
88
- time.sleep(retry_delay)
89
-
90
- return response
91
-
92
- def save(
93
- self,
94
- response: List[bytes],
95
- name: str = None,
96
- dir: str = os.getcwd(),
97
- filenames_prefix: str = "",
98
- ) -> List[str]:
99
- """Save generated images
100
-
101
- Args:
102
- response (List[bytes]): List of generated images as bytes.
103
- name (str): Filename for the images. Defaults to the last prompt.
104
- dir (str, optional): Directory for saving images. Defaults to os.getcwd().
105
- filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
106
-
107
- Returns:
108
- List[str]: List of saved filenames.
109
- """
110
- assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
111
- name = self.prompt if name is None else name
112
-
113
- filenames = []
114
- count = 0
115
- for image in response:
116
- def complete_path():
117
- count_value = "" if count == 0 else f"_{count}"
118
- return os.path.join(dir, name + count_value + "." + self.image_extension)
119
-
120
- while os.path.isfile(complete_path()):
121
- count += 1
122
-
123
- absolute_path_to_file = complete_path()
124
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
125
-
126
- with open(absolute_path_to_file, "wb") as fh:
127
- fh.write(image)
128
-
129
- return filenames
130
-
131
-
132
- if __name__ == "__main__":
133
- bot = PollinationsAI()
134
- try:
135
- resp = bot.generate("AI-generated image - webscout", 1)
136
- print(bot.save(resp))
137
- except Exception as e:
138
- print(f"An error occurred: {e}")
@@ -1,142 +0,0 @@
1
- import requests
2
- import os
3
- from typing import List
4
-
5
- from webscout.AIbase import ImageProvider
6
-
7
- class WebSimAI(ImageProvider):
8
- """
9
- Image provider for WebSim.ai.
10
- """
11
-
12
- def __init__(self, timeout: int = 60, proxies: dict = {}):
13
- """Initializes the WebSimAI class.
14
-
15
- Args:
16
- timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
17
- proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
18
- """
19
- self.url = "https://websim.ai/api/image_gen"
20
- self.headers = {
21
- "Accept": "*/*",
22
- "Accept-Encoding": "gzip, deflate, br, zstd",
23
- "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
24
- "Content-Type": "application/json",
25
- "User-Agent": (
26
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
27
- "AppleWebKit/537.36 (KHTML, like Gecko) "
28
- "Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
29
- ),
30
- "Origin": "https://websim.ai",
31
- "Referer": "https://websim.ai/p/a5yvwmtj8qz6ayx4tlg1"
32
- }
33
- self.session = requests.Session()
34
- self.session.headers.update(self.headers)
35
- self.session.proxies.update(proxies)
36
- self.timeout = timeout
37
- self.prompt: str = "AI-generated image - Webscout"
38
- self.image_extension: str = "png"
39
-
40
- def generate(
41
- self,
42
- prompt: str,
43
- amount: int = 1,
44
- width: int = 1024,
45
- height: int = 756
46
- ) -> List[bytes]:
47
- """Generate image from prompt
48
-
49
- Args:
50
- prompt (str): Image description.
51
- amount (int, optional): Total images to be generated. Defaults to 1.
52
- width (int, optional): Width of the generated image. Defaults to 1024.
53
- height (int, optional): Height of the generated image. Defaults to 756.
54
-
55
- Returns:
56
- List[bytes]: List of generated images as bytes.
57
- """
58
- assert bool(prompt), "Prompt cannot be null"
59
- assert isinstance(amount, int), f"Amount should be an integer only, not {type(amount)}"
60
- assert amount > 0, "Amount should be greater than 0"
61
-
62
- self.prompt = prompt
63
- response = []
64
-
65
- for _ in range(amount):
66
- payload = {
67
- "prompt": prompt,
68
- "width": width,
69
- "height": height,
70
- "site_id": "KcWvHOHNBP2PmWUYZ",
71
- }
72
-
73
- try:
74
- resp = self.session.post(self.url, headers=self.headers, json=payload, timeout=self.timeout)
75
- resp.raise_for_status() # Raises HTTPError for bad responses
76
-
77
- response_data = resp.json()
78
- image_url = response_data.get("url")
79
- if not image_url:
80
- print("No image URL found in the response.")
81
- continue
82
-
83
- image_response = requests.get(image_url)
84
- image_response.raise_for_status()
85
- response.append(image_response.content)
86
-
87
- except requests.exceptions.HTTPError as http_err:
88
- print(f"HTTP error occurred: {http_err} - {response.text}")
89
- return [] # Return an empty list on error
90
- except requests.exceptions.RequestException as req_err:
91
- print(f"Request error occurred: {req_err}")
92
- return [] # Return an empty list on error
93
-
94
- return response
95
-
96
- def save(
97
- self,
98
- response: List[bytes],
99
- name: str = None,
100
- dir: str = os.getcwd(),
101
- filenames_prefix: str = "",
102
- ) -> List[str]:
103
- """Save generated images
104
-
105
- Args:
106
- response (List[bytes]): List of generated images as bytes.
107
- name (str): Filename for the images. Defaults to the last prompt.
108
- dir (str, optional): Directory for saving images. Defaults to os.getcwd().
109
- filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
110
-
111
- Returns:
112
- List[str]: List of saved filenames.
113
- """
114
- assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
115
- name = self.prompt if name is None else name
116
-
117
- filenames = []
118
- count = 0
119
- for image in response:
120
- def complete_path():
121
- count_value = "" if count == 0 else f"_{count}"
122
- return os.path.join(dir, name + count_value + "." + self.image_extension)
123
-
124
- while os.path.isfile(complete_path()):
125
- count += 1
126
-
127
- absolute_path_to_file = complete_path()
128
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
129
-
130
- with open(absolute_path_to_file, "wb") as fh:
131
- fh.write(image)
132
-
133
- return filenames
134
-
135
-
136
- if __name__ == "__main__":
137
- bot = WebSimAI()
138
- try:
139
- resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
140
- print(bot.save(resp))
141
- except Exception as e:
142
- print(f"An error occurred: {e}")
@@ -1,160 +0,0 @@
1
- import requests
2
- import os
3
- import time
4
- from typing import List, Optional
5
- from string import punctuation
6
- from random import choice
7
- from requests.exceptions import RequestException
8
-
9
- from webscout.AIbase import ImageProvider
10
-
11
- class AiForceimager(ImageProvider):
12
- """Image provider for Airforce API"""
13
-
14
- AVAILABLE_MODELS = [
15
- "flux",
16
- "flux-realism",
17
- "flux-anime",
18
- "flux-3d",
19
- "flux-disney",
20
- "flux-pixel",
21
- "flux-4o",
22
- "any-dark"
23
- ]
24
-
25
- def __init__(self, timeout: int = 60, proxies: dict = {}):
26
- """Initializes the AiForceimagger class.
27
-
28
- Args:
29
- api_token (str, optional): Your Airforce API token. If None, it will use the environment variable "AIRFORCE_API_TOKEN".
30
- Defaults to None.
31
- timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
32
- proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
33
- """
34
- self.api_endpoint = "https://api.airforce/imagine2"
35
- self.headers = {
36
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
37
- "Accept-Language": "en-US,en;q=0.5",
38
- "Accept-Encoding": "gzip, deflate",
39
- "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
40
- }
41
- self.session = requests.Session()
42
- self.session.headers.update(self.headers)
43
- self.session.proxies.update(proxies)
44
- self.timeout = timeout
45
- self.prompt: str = "AI-generated image - webscout"
46
- self.image_extension: str = "png"
47
-
48
- def generate(
49
- self,
50
- prompt: str,
51
- amount: int = 1,
52
- additives: bool = True,
53
- model: str = "flux-realism",
54
- width: int = 768,
55
- height: int = 768,
56
- seed: Optional[int] = None,
57
- max_retries: int = 3,
58
- retry_delay: int = 5
59
- ) -> List[bytes]:
60
- """Generate image from prompt
61
-
62
- Args:
63
- prompt (str): Image description.
64
- amount (int, optional): Total images to be generated. Defaults to 1.
65
- additives (bool, optional): Try to make each prompt unique. Defaults to True.
66
- model (str, optional): The model to use for image generation.
67
- Defaults to "flux". Available options: "flux", "flux-realism".
68
- width (int, optional): Width of the generated image. Defaults to 768.
69
- height (int, optional): Height of the generated image. Defaults to 768.
70
- seed (int, optional): Seed for the random number generator. Defaults to None.
71
- max_retries (int, optional): Maximum number of retry attempts. Defaults to 3.
72
- retry_delay (int, optional): Delay between retries in seconds. Defaults to 5.
73
-
74
- Returns:
75
- List[bytes]: List of generated images as bytes.
76
- """
77
- assert bool(prompt), "Prompt cannot be null"
78
- assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
79
- assert amount > 0, "Amount should be greater than 0"
80
- assert model in self.AVAILABLE_MODELS, f"Model should be one of {self.AVAILABLE_MODELS}"
81
-
82
- ads = lambda: (
83
- ""
84
- if not additives
85
- else choice(punctuation)
86
- + choice(punctuation)
87
- + choice(punctuation)
88
- + choice(punctuation)
89
- + choice(punctuation)
90
- )
91
-
92
- self.prompt = prompt
93
- response = []
94
- for _ in range(amount):
95
- url = f"{self.api_endpoint}?model={model}&prompt={prompt}&size={width}:{height}"
96
- if seed:
97
- url += f"&seed={seed}"
98
-
99
- for attempt in range(max_retries):
100
- try:
101
- resp = self.session.get(url, timeout=self.timeout)
102
- resp.raise_for_status()
103
- response.append(resp.content)
104
- break
105
- except RequestException as e:
106
- if attempt == max_retries - 1:
107
- print(f"Failed to generate image after {max_retries} attempts: {e}")
108
- raise
109
- else:
110
- print(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds...")
111
- time.sleep(retry_delay)
112
-
113
- return response
114
-
115
- def save(
116
- self,
117
- response: List[bytes],
118
- name: str = None,
119
- dir: str = os.getcwd(),
120
- filenames_prefix: str = "",
121
- ) -> List[str]:
122
- """Save generated images
123
-
124
- Args:
125
- response (List[bytes]): List of generated images as bytes.
126
- name (str): Filename for the images. Defaults to the last prompt.
127
- dir (str, optional): Directory for saving images. Defaults to os.getcwd().
128
- filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
129
-
130
- Returns:
131
- List[str]: List of saved filenames.
132
- """
133
- assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
134
- name = self.prompt if name is None else name
135
-
136
- filenames = []
137
- count = 0
138
- for image in response:
139
- def complete_path():
140
- count_value = "" if count == 0 else f"_{count}"
141
- return os.path.join(dir, name + count_value + "." + self.image_extension)
142
-
143
- while os.path.isfile(complete_path()):
144
- count += 1
145
-
146
- absolute_path_to_file = complete_path()
147
- filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
148
-
149
- with open(absolute_path_to_file, "wb") as fh:
150
- fh.write(image)
151
-
152
- return filenames
153
-
154
- if __name__ == "__main__":
155
- bot = AiForceimager()
156
- try:
157
- resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1, model="flux-realism")
158
- print(bot.save(resp))
159
- except Exception as e:
160
- print(f"An error occurred: {e}")