Skip to content

Getting creative with Dall-E3

These pictures were generated by a variant of the Python code provided at Medium – I Ignited Explosive Creativity with AI Automation by Jordan Gibbs, and points to the value of generating prompts dynamically, that could also be used for e.g. generating stories. Due to all requests the code takes some time to process.

You need to create two files as input to the script, where each line will be chosen randomly:

  • style.txt: A list of art styles
  • subject.txt: A list of subject or topics

Note that there needs to be no empty lines, not even at the end.

Pictures

Code

from openai import OpenAI
import random
import requests
import os

client = OpenAI()


def extract_url(input_text):
    images_response = input_text
    url = images_response.data[0].url
    return url


def download_image(style, subject, image_url):
    directory = "IMAGES"
    dir_path = os.path.join(directory)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    path_to_save_image = os.path.join(dir_path, f"{style} - {subject}.png")
    response = requests.get(image_url)

    # Check if the request was successful
    if response.status_code == 200:
        # Open the file in binary write mode and save the image content
        with open(path_to_save_image, 'wb') as f:
            f.write(response.content)
        print(f"Image saved at {path_to_save_image}")
    else:
        print(f"Failed to download image. Status code: {response.status_code}")


def dalle(prompt):
    response = client.images.generate(
      model="dall-e-3",
      prompt=f"{prompt}",
      n=1,
      quality='hd',
      style='vivid',
      size="1792x1024"
    )
    url = extract_url(response)
    return url


def get_random_word(topic, amount):
    if (amount > 0):
        with open(topic + '.txt', 'r') as wordy:
            words = wordy.read().split('\n')

        counter = 0
        word_list = []        
        while counter < amount:
            random_word = random.choice(words)
            if random_word not in word_list:
                word_list.append(random_word)
                counter += 1

    return " and ".join(word_list)


def style_writer(word):
    response = client.chat.completions.create(
            model="gpt-4",
            temperature=0.9,
            messages=[
                {"role": "system", "content": f"You output a highly specific art style or art medium based on the "
                                              f"User's input word. Please think outside the box, and output an art "
                                              f"style or medium that fits the user's input. Be ultra concise, and "
                                              f"don't reference the user's input directly in your output."},
                {"role": "user", "content": f"{word}"}
            ],
    )
    style = response.choices[0].message.content
    print(style)
    return style


def subject_generator(word):
    response = client.chat.completions.create(
            model="gpt-4",
            temperature=0.9,
            messages=[
                {"role": "system", "content": f"You output an interesting or creative scenario, noun, or concept "
                                              f"based on a user input. Please think "
                                              f"outside the box, and be very concise. Only output your idea."},
                {"role": "user", "content": f"{word}"}
            ],
    )
    subject = response.choices[0].message.content
    print(subject)
    return subject


def prompt_generator(style, idea):
    response = client.chat.completions.create(
            model="gpt-4",
            temperature=0.9,
            messages=[
                {"role": "system", "content": f"You will output a highly evocative and concise paragraph "
                                              f"describing a theoretical art piece. This description will be "
                                              f"extremely compelling and interesting. You will be creative and base "
                                              f"this off of the user's inputs. You will only output one short "
                                              f"paragraph, and nothing else, please be very direct in describing the "
                                              f"style given by the user. Please focus very highly on the main subject "
                                              f" of the piece."},
                {"role": "user", "content": f"{idea} in the style of {style}. "}
            ],
    )
    prompt = response.choices[0].message.content
    prompt = f"{prompt} No text on the image."
    print(prompt)
    return prompt


for i in range(1, 6):
    word_style = get_random_word("style", 2)
    style = style_writer(word_style)

    word_subject = get_random_word("subject", 4)
    subject = subject_generator(word_subject)

    prompt = prompt_generator(style, subject)
    url = dalle(prompt)
    download_image(word_style, word_subject, url)