Python Dreamstudio AI – Create art using Python code

In this post we will be creating a Python script that will generate art using the Dreamstudio AI API. Dreamstudio is a new AI system powered by Stable Diffusion and is able to create arts and graphics. These are based on prompts provided by the user, prompts are descriptive sentences that describe the image.

See the sample of Python code below where we utilize the Dreamstudio AI to generate our own art pieces. The prerequisite of this project is that you have a Dreamstudio account along with an API key. The below uses a while loop, where the user may enter a prompt and generate an image repeatedly, the image is then saved as a PNG image.

Find out how you can generate your own Dreamstudio API key by clicking here.

import os
import io
import warnings
from PIL import Image
from stability_sdk import client
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation

os.environ['STABILITY_HOST'] = 'grpc.stability.ai:443'
os.environ['STABILITY_KEY'] = 'YOUR-API-KEY!!!!!!!'

stability_api = client.StabilityInference(
    key=os.environ['STABILITY_KEY'], 
    engine="stable-diffusion-v1-5", 
)

User_input=input("Enter inspiration for Art: ")
answers = stability_api.generate(
    prompt=User_input,
)


for resp in answers:
    for artifact in resp.artifacts:
        if artifact.finish_reason == generation.FILTER:
            warnings.warn(
                "Your request activated the API's safety filters and could not be processed."
                "Please modify the prompt and try again.")
        if artifact.type == generation.ARTIFACT_IMAGE:
            img = Image.open(io.BytesIO(artifact.binary))
            img.save(str(User_input)+ ".png") 

See some examples below.

For the below the prompt was ‘heavenly scene, concept art, matte painting, 4k’

For the below the prompt was ‘hellish scene, Realism art, 4k’.

image created using Dreamstudio AI with prompt 'hellish scene, Realism art, 4k'

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply