2023-05-22 07:17:59 +00:00
|
|
|
import base64
|
|
|
|
from io import BytesIO
|
|
|
|
|
2023-12-10 00:33:39 +00:00
|
|
|
from imaginairy.api import imagine
|
2023-05-22 07:17:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def generate_image(prompt):
|
2023-09-29 06:32:30 +00:00
|
|
|
"""ImaginePrompt to generated image."""
|
2023-05-22 07:17:59 +00:00
|
|
|
result = next(imagine([prompt]))
|
|
|
|
img = result.images["generated"]
|
|
|
|
img_io = BytesIO()
|
|
|
|
img.save(img_io, "JPEG")
|
|
|
|
img_io.seek(0)
|
|
|
|
return img_io
|
|
|
|
|
|
|
|
|
|
|
|
def generate_image_b64(prompt):
|
2023-05-29 17:54:07 +00:00
|
|
|
"""ImaginePrompt to generated base64 encoded image."""
|
2023-05-22 07:17:59 +00:00
|
|
|
img_io = generate_image(prompt)
|
|
|
|
img_base64 = base64.b64encode(img_io.getvalue())
|
|
|
|
return img_base64
|
|
|
|
|
|
|
|
|
|
|
|
class Base64Bytes(bytes):
|
|
|
|
@classmethod
|
|
|
|
def __get_validators__(cls):
|
|
|
|
yield cls.validate
|
|
|
|
|
|
|
|
@classmethod
|
2023-09-29 06:32:30 +00:00
|
|
|
def validate(cls, v, info):
|
2023-05-22 07:17:59 +00:00
|
|
|
if isinstance(v, bytes):
|
|
|
|
return v
|
|
|
|
if isinstance(v, str):
|
|
|
|
return base64.b64decode(v)
|
|
|
|
raise ValueError("Byte value must be either str or bytes")
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return base64.b64encode(self).decode()
|