-
Notifications
You must be signed in to change notification settings - Fork 91
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create images for blogs - Stability AI
- Loading branch information
Showing
11 changed files
with
107 additions
and
70 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
STABILITY_API_KEY=sk-Jdu0BrFe4tta19PDpU1AlpVAtE3eJlmGZiAYx61bNUZkAl4d | ||
STABILITY_API_KEY=sk-Jdu0BrFe4tta19PDpU1AlpVAtE3eJlmGZiAYx61bNUZkAl4d | ||
STABILITY_API_KEY=asada | ||
STABILITY_API_KEY=sk-Jdu0BrFe4tta19PDpU1AlpVAtE3eJlmGZiAYx61bNUZkAl4d | ||
STABILITY_API_KEY=sdsa | ||
STABILITY_API_KEY=sk-Jdu0BrFe4tta19PDpU1AlpVAtE3eJlmGZiAYx61bNUZkAl4d |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 42 additions & 27 deletions
69
lib/gpt_providers/text_to_image_generation/gen_stabl_diff_img.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,56 @@ | ||
from PIL import Image | ||
import requests | ||
|
||
# Ensure you sign up for an account to obtain an API key: | ||
# https://platform.stability.ai/ | ||
# Your API key can be found here after account creation: | ||
# https://platform.stability.ai/account/keys | ||
|
||
import base64 | ||
import os | ||
import requests | ||
from PIL import Image | ||
from io import BytesIO | ||
|
||
def generate_stable_diffusion_image(prompt): | ||
""" | ||
Generate images using Stable Diffusion API based on a given prompt. | ||
Args: | ||
prompt (str): The prompt to generate the image. | ||
image_dir (str): The directory where the image will be saved. | ||
from .save_image import save_generated_image | ||
|
||
Raises: | ||
Warning: If the adult content classifier is triggered. | ||
Exception: For any issues during image generation or saving. | ||
""" | ||
api_key = os.getenv('STABILITY_API_KEY') | ||
|
||
def generate_stable_diffusion_image(prompt): | ||
engine_id = "stable-diffusion-xl-1024-v1-0" | ||
api_host = os.getenv('API_HOST', 'https://api.stability.ai') | ||
api_key = os.getenv("STABILITY_API_KEY") | ||
|
||
if api_key is None: | ||
raise Exception("Missing Stability API key.") | ||
|
||
response = requests.post( | ||
f"https://api.stability.ai/v2beta/stable-image/generate/sd3", | ||
f"{api_host}/v1/generation/{engine_id}/text-to-image", | ||
headers={ | ||
"authorization": f"Bearer {api_key}", | ||
"accept": "image/*" | ||
"Content-Type": "application/json", | ||
"Accept": "application/json", | ||
"Authorization": f"Bearer {api_key}" | ||
}, | ||
files={"none": ''}, | ||
data={ | ||
"prompt": prompt, | ||
"output_format": "webp", | ||
json={ | ||
"text_prompts": [ | ||
{ | ||
"text": prompt | ||
} | ||
], | ||
"cfg_scale": 7, | ||
"height": 1024, | ||
"width": 1024, | ||
"samples": 1, | ||
"steps": 30, | ||
}, | ||
) | ||
|
||
if response.status_code != 200: | ||
raise Exception("Non-200 response: " + str(response.text)) | ||
|
||
data = response.json() | ||
save_generated_image(data) | ||
|
||
if response.status_code == 200: | ||
with open("./dog-wearing-glasses.jpeg", 'wb') as file: | ||
file.write(response.content) | ||
else: | ||
raise Exception(str(response.json())) | ||
for i, image in enumerate(data["artifacts"]): | ||
# Decode base64 image data | ||
img_data = base64.b64decode(image["base64"]) | ||
# Open image using PIL | ||
img = Image.open(BytesIO(img_data)) | ||
# Display the image | ||
img.show() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,28 @@ | ||
import base64 | ||
import datetime | ||
import os | ||
import requests | ||
from PIL import Image | ||
import logging | ||
|
||
def save_generated_image(img_generation_response, image_dir): | ||
def save_generated_image(img_generation_response): | ||
""" | ||
Save generated images for blog, ensuring unique names for SEO. | ||
""" | ||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger(__name__) | ||
|
||
generated_image_name = f"generated_image_{datetime.datetime.now():%Y-%m-%d-%H-%M-%S}.png" | ||
generated_image_filepath = os.path.join(image_dir, generated_image_name) | ||
generated_image_url = img_generation_response.data[0].url | ||
generated_image_name = f"generated_image_{datetime.datetime.now():%Y-%m-%d-%H-%M-%S}.webp" | ||
generated_image_filepath = os.path.join(os.getenv('IMG_SAVE_DIR'), generated_image_name) | ||
|
||
logger.info(f"Fetch the image from url: {generated_image_url}") | ||
try: | ||
response = requests.get(generated_image_url, stream=True) | ||
response.raise_for_status() | ||
with open(generated_image_filepath, "wb", encoding="utf-8") as image_file: | ||
image_file.write(response.content) | ||
for i, image in enumerate(img_generation_response["artifacts"]): | ||
with open(generated_image_filepath, "wb") as f: | ||
f.write(base64.b64decode(image["base64"])) | ||
except requests.exceptions.RequestException as e: | ||
logger.error(f"Failed to get generated image content: {e}") | ||
return None | ||
|
||
logger.info(f"Saved image at path: {generated_image_filepath}") | ||
|
||
if os.environ.get('DISPLAY', ''): # Check if display is supported | ||
img = Image.open(generated_image_filepath) | ||
img.show() | ||
|
||
return generated_image_filepath | ||
|
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes