webscout 5.7__py3-none-any.whl → 5.9__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.

@@ -0,0 +1,141 @@
1
+ import cloudscraper
2
+ import os
3
+ import requests
4
+
5
+ from typing import List
6
+
7
+ from webscout.AIbase import ImageProvider
8
+
9
+ class ArtbitImager(ImageProvider):
10
+ """
11
+ Image provider for Artbit.ai.
12
+ """
13
+
14
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
15
+ """Initializes the ArtbitImager class.
16
+
17
+ Args:
18
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
19
+ proxies (dict, optional): HTTP request proxies. Defaults to {}.
20
+ """
21
+ self.url = "https://artbit.ai/api/generateImage"
22
+ self.scraper = cloudscraper.create_scraper()
23
+ self.scraper.proxies.update(proxies)
24
+ self.timeout = timeout
25
+ self.prompt: str = "AI-generated image - webscout"
26
+ self.image_extension: str = "png"
27
+
28
+ def generate(
29
+ self,
30
+ prompt: str,
31
+ amount: int = 1,
32
+ caption_model: str = "sdxl",
33
+ selected_ratio: str = "1024",
34
+ negative_prompt: str = ""
35
+ ) -> List[str]:
36
+ """Generate image from prompt
37
+
38
+ Args:
39
+ prompt (str): Image description.
40
+ amount (int, optional): Total images to be generated. Defaults to 1.
41
+ caption_model (str, optional): Caption model to use. Defaults to "sdxl".
42
+ selected_ratio (str, optional): Image ratio. Defaults to "1024".
43
+ negative_prompt (str, optional): Negative prompt. Defaults to "".
44
+
45
+ Returns:
46
+ List[str]: List of generated image URLs.
47
+ """
48
+ assert bool(prompt), "Prompt cannot be null"
49
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
50
+ assert amount > 0, "Amount should be greater than 0"
51
+
52
+ self.prompt = prompt
53
+ response: List[str] = []
54
+
55
+ payload = {
56
+ "captionInput": prompt,
57
+ "captionModel": caption_model,
58
+ "selectedRatio": selected_ratio,
59
+ "selectedSamples": str(amount),
60
+ "negative_prompt": negative_prompt
61
+ }
62
+
63
+ try:
64
+ # Sending the POST request using CloudScraper
65
+ resp = self.scraper.post(self.url, json=payload, timeout=self.timeout)
66
+ resp.raise_for_status() # Check for HTTP errors
67
+
68
+ # Parsing the JSON response
69
+ response_data = resp.json()
70
+
71
+ # Extracting image URLs from the response
72
+ imgs = response_data.get("imgs", [])
73
+ if imgs:
74
+ response.extend(imgs)
75
+ else:
76
+ print("No images found in the response.")
77
+
78
+ except requests.RequestException as e:
79
+ print(f"An error occurred while making the request: {e}")
80
+ raise
81
+
82
+ return response
83
+
84
+ def save(
85
+ self,
86
+ response: List[str], # List of image URLs
87
+ name: str = None,
88
+ dir: str = os.getcwd(),
89
+ filenames_prefix: str = "",
90
+ ) -> List[str]:
91
+ """Save generated images
92
+
93
+ Args:
94
+ response (List[str]): List of generated image URLs.
95
+ name (str): Filename for the images. Defaults to the last prompt.
96
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
97
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
98
+
99
+ Returns:
100
+ List[str]: List of saved filenames.
101
+ """
102
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
103
+ name = self.prompt if name is None else name
104
+
105
+ filenames = []
106
+ count = 0
107
+ for img_url in response:
108
+ def complete_path():
109
+ count_value = "" if count == 0 else f"_{count}"
110
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
111
+
112
+ while os.path.isfile(complete_path()):
113
+ count += 1
114
+
115
+ absolute_path_to_file = complete_path()
116
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
117
+
118
+ # Download and save the image
119
+ try:
120
+ img_response = requests.get(img_url, stream=True, timeout=self.timeout)
121
+ img_response.raise_for_status()
122
+
123
+ with open(absolute_path_to_file, "wb") as fh:
124
+ for chunk in img_response.iter_content(chunk_size=8192):
125
+ fh.write(chunk)
126
+ except requests.exceptions.RequestException as e:
127
+ print(f"An error occurred while downloading image from {img_url}: {e}")
128
+ raise
129
+
130
+ return filenames
131
+
132
+ if __name__ == "__main__":
133
+ bot = ArtbitImager()
134
+ try:
135
+ resp = bot.generate(
136
+ "A shiny red sports car speeding down a scenic mountain road with a clear blue sky in the background, surrounded by lush green trees.",
137
+ amount=3
138
+ )
139
+ print(bot.save(resp))
140
+ except Exception as e:
141
+ print(f"An error occurred: {e}")
@@ -0,0 +1,155 @@
1
+ import os
2
+ import requests
3
+ import io
4
+ from PIL import Image
5
+ from typing import Any, List, Optional, Dict
6
+ from webscout.AIbase import ImageProvider
7
+
8
+ class HFimager(ImageProvider):
9
+ """
10
+ Image provider for Hugging Face Inference API.
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ api_token: str = None,
16
+ timeout: int = 60,
17
+ proxies: dict = {}
18
+ ):
19
+ """Initializes the HFimager class.
20
+
21
+ Args:
22
+ api_token (str, optional): Hugging Face API token. If None, it will use the environment variable "HUGGINGFACE_API_TOKEN".
23
+ Defaults to None.
24
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
25
+ proxies (dict, optional): HTTP request proxies. Defaults to {}.
26
+ """
27
+ self.base_url = "https://api-inference.huggingface.co/models/"
28
+ self.api_token = api_token or os.environ["HUGGINGFACE_API_TOKEN"]
29
+ self.headers = {"Authorization": f"Bearer {self.api_token}"}
30
+ self.session = requests.Session()
31
+ self.session.headers.update(self.headers)
32
+ self.session.proxies.update(proxies)
33
+ self.timeout = timeout
34
+ self.prompt: str = "AI-generated image - webscout"
35
+ self.image_extension: str = "jpg"
36
+
37
+ def generate(
38
+ self,
39
+ prompt: str,
40
+ amount: int = 1,
41
+ model: str = "black-forest-labs/FLUX.1-dev",
42
+ guidance_scale: Optional[float] = None,
43
+ negative_prompt: Optional[str] = None,
44
+ num_inference_steps: Optional[int] = None,
45
+ width: Optional[int] = None,
46
+ height: Optional[int] = None,
47
+ scheduler: Optional[str] = None,
48
+ seed: Optional[int] = None,
49
+ ) -> List[bytes]:
50
+ """
51
+ Generate image from prompt.
52
+
53
+ Args:
54
+ prompt (str): Image description.
55
+ amount (int): Total images to be generated. Defaults to 1.
56
+ model (str): Hugging Face model name. Defaults to "black-forest-labs/FLUX.1-dev".
57
+ guidance_scale (float, optional): Guidance scale value. Defaults to None.
58
+ negative_prompt (str, optional): Negative prompt. Defaults to None.
59
+ num_inference_steps (int, optional): Number of inference steps. Defaults to None.
60
+ width (int, optional): Width of the output image. Defaults to None.
61
+ height (int, optional): Height of the output image. Defaults to None.
62
+ scheduler (str, optional): Scheduler to use. Defaults to None.
63
+ seed (int, optional): Seed for random number generator. Defaults to None.
64
+
65
+ Returns:
66
+ List[bytes]: List of generated images as bytes.
67
+ """
68
+ assert bool(prompt), "Prompt cannot be null"
69
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
70
+ assert amount > 0, "Amount should be greater than 0"
71
+
72
+ self.prompt = prompt
73
+ response = []
74
+
75
+ for _ in range(amount):
76
+ url = self.base_url + model
77
+
78
+ # Create the base payload with the prompt
79
+ payload: Dict[str, Any] = {"inputs": prompt}
80
+
81
+ # Add optional parameters to the payload if provided
82
+ parameters = {}
83
+ if guidance_scale is not None:
84
+ parameters["guidance_scale"] = guidance_scale
85
+ if negative_prompt is not None:
86
+ parameters["negative_prompt"] = negative_prompt
87
+ if num_inference_steps is not None:
88
+ parameters["num_inference_steps"] = num_inference_steps
89
+ if width is not None and height is not None:
90
+ parameters["target_size"] = {"width": width, "height": height}
91
+ if scheduler is not None:
92
+ parameters["scheduler"] = scheduler
93
+ if seed is not None:
94
+ parameters["seed"] = seed
95
+
96
+ # Add the parameters to the payload if any are set
97
+ if parameters:
98
+ payload["parameters"] = parameters
99
+
100
+ try:
101
+ resp = self.session.post(url, headers=self.headers, json=payload, timeout=self.timeout)
102
+ resp.raise_for_status()
103
+ response.append(resp.content)
104
+ except requests.RequestException as e:
105
+ print(f"Failed to generate image: {e}")
106
+ raise
107
+
108
+ return response
109
+
110
+ def save(
111
+ self,
112
+ response: List[bytes],
113
+ name: str = None,
114
+ dir: str = os.getcwd(),
115
+ filenames_prefix: str = "",
116
+ ) -> List[str]:
117
+ """Save generated images
118
+
119
+ Args:
120
+ response (List[bytes]): List of generated images as bytes.
121
+ name (str): Filename for the images. Defaults to the last prompt.
122
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
123
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
124
+
125
+ Returns:
126
+ List[str]: List of saved filenames.
127
+ """
128
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
129
+ name = self.prompt if name is None else name
130
+
131
+ filenames = []
132
+ count = 0
133
+ for image_bytes in response:
134
+ def complete_path():
135
+ count_value = "" if count == 0 else f"_{count}"
136
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
137
+
138
+ while os.path.isfile(complete_path()):
139
+ count += 1
140
+
141
+ absolute_path_to_file = complete_path()
142
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
143
+
144
+ with open(absolute_path_to_file, "wb") as fh:
145
+ fh.write(image_bytes)
146
+
147
+ return filenames
148
+
149
+ if __name__ == "__main__":
150
+ bot = HFimager(api_token='your huggingface API')
151
+ try:
152
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road with a clear blue sky in the background, surrounded by lush green trees.", 1)
153
+ print(bot.save(resp, name="test"))
154
+ except Exception as e:
155
+ print(f"An error occurred: {e}")
@@ -1,2 +1,3 @@
1
1
  from .streamElements import *
2
- from .voicepod import *
2
+ from .voicepod import *
3
+ from .parler import *
@@ -0,0 +1,108 @@
1
+ import time
2
+ from pathlib import Path
3
+ from typing import Generator
4
+ from playsound import playsound
5
+ from webscout import exceptions
6
+ from webscout.AIbase import TTSProvider
7
+
8
+ from gradio_client import Client
9
+ import os
10
+
11
+
12
+ class ParlerTTS(TTSProvider):
13
+ """
14
+ A class to interact with the Parler TTS API through Gradio Client.
15
+ """
16
+
17
+ def __init__(self, timeout: int = 20, proxies: dict = None):
18
+ """Initializes the Parler TTS client."""
19
+ self.api_endpoint = "/gen_tts"
20
+ self.client = Client("parler-tts/parler_tts") # Initialize the Gradio client
21
+ self.timeout = timeout
22
+ self.audio_cache_dir = Path("./audio_cache")
23
+
24
+ def tts(self, text: str, description: str = "", use_large: bool = False) -> str:
25
+ """
26
+ Converts text to speech using the Parler TTS API.
27
+
28
+ Args:
29
+ text (str): The text to be converted to speech.
30
+ description (str, optional): Description of the desired voice characteristics. Defaults to "".
31
+ use_large (bool, optional): Whether to use the large model variant. Defaults to False.
32
+
33
+ Returns:
34
+ str: The filename of the saved audio file.
35
+
36
+ Raises:
37
+ exceptions.FailedToGenerateResponseError: If there is an error generating or saving the audio.
38
+ """
39
+ filename = self.audio_cache_dir / f"{int(time.time())}.wav"
40
+
41
+ try:
42
+ result = self.client.predict(
43
+ text=text,
44
+ description=description,
45
+ use_large=use_large,
46
+ api_name=self.api_endpoint,
47
+ )
48
+
49
+ if isinstance(result, bytes):
50
+ audio_bytes = result
51
+ elif isinstance(result, str) and os.path.isfile(result):
52
+ with open(result, "rb") as f:
53
+ audio_bytes = f.read()
54
+ else:
55
+ raise ValueError(f"Unexpected response from API: {result}")
56
+
57
+ self._save_audio(audio_bytes, filename)
58
+ return filename.as_posix()
59
+
60
+ except Exception as e:
61
+ raise exceptions.FailedToGenerateResponseError(
62
+ f"Error generating audio after multiple retries: {e}"
63
+ ) from e
64
+
65
+ def _save_audio(self, audio_data: bytes, filename: Path):
66
+ """Saves the audio data to a WAV file in the audio cache directory."""
67
+ try:
68
+ self.audio_cache_dir.mkdir(parents=True, exist_ok=True)
69
+ with open(filename, "wb") as f:
70
+ f.write(audio_data)
71
+
72
+ except Exception as e:
73
+ raise exceptions.FailedToGenerateResponseError(f"Error saving audio: {e}")
74
+
75
+ def play_audio(self, filename: str):
76
+ """
77
+ Plays an audio file using playsound.
78
+
79
+ Args:
80
+ filename (str): The path to the audio file.
81
+
82
+ Raises:
83
+ RuntimeError: If there is an error playing the audio.
84
+ """
85
+ try:
86
+ playsound(filename)
87
+ except Exception as e:
88
+ raise RuntimeError(f"Error playing audio: {e}")
89
+
90
+
91
+ # Example usage
92
+ if __name__ == "__main__":
93
+ parlertts = ParlerTTS()
94
+ text = (
95
+ "All of the data, pre-processing, training code, and weights are released "
96
+ "publicly under a permissive license, enabling the community to build on our work "
97
+ "and develop their own powerful models."
98
+ )
99
+ voice_description = (
100
+ "Laura's voice is monotone yet slightly fast in delivery, with a very close "
101
+ "recording that almost has no background noise."
102
+ )
103
+
104
+ print("Generating audio...")
105
+ audio_file = parlertts.tts(text, description=voice_description, use_large=False)
106
+
107
+ print("Playing audio...")
108
+ parlertts.play_audio(audio_file)
@@ -53,6 +53,14 @@ from .upstage import *
53
53
  from .Bing import *
54
54
  from .GPTWeb import *
55
55
  from .aigames import *
56
+ from .llamatutor import *
57
+ from .promptrefine import *
58
+ from .twitterclone import *
59
+ from .tutorai import *
60
+ from .bixin import *
61
+ from .ChatGPTES import *
62
+ from .Amigo import *
63
+ from .prefind import *
56
64
  __all__ = [
57
65
  'Farfalle',
58
66
  'LLAMA',
@@ -110,5 +118,15 @@ __all__ = [
110
118
  'Bing',
111
119
  'GPTWeb',
112
120
  'AIGameIO',
121
+ 'LlamaTutor',
122
+ 'PromptRefine',
123
+ 'AIUncensored',
124
+ 'TutorAI',
125
+ 'Bixin',
126
+ 'ChatGPTES',
127
+ 'AmigoChat',
128
+ 'PrefindAI',
129
+ # 'LearnFast',
130
+
113
131
 
114
132
  ]