"An error occured: 'url' " error I'm trying to run GUI image generation Python script

As the title says, I’m trying to make a python script that uses a GUI interface with a text prompt that can connect to OpenAI’s servers. However, whenever I enter the prompt, the script freezes for a bit before giving me the following error: "An error occured: ‘url’ ". I’m not sure what’s causing the error, and I’m looking for suggestions that could help me find out what’s causing it. Here’s my code:

import openai
import tkinter as tk
from tkinter import Label, PhotoImage, Entry, Button, messagebox
from PIL import Image, ImageTk
import io

# Set your OpenAI API key
openai.api_key = "[REDACTED]"

def generate_image(description):
    try:
        response = openai.Image.create(
            model="image-alpha-001",
            prompt=description
        )

        image_url = response['url']
        image_data = requests.get(image_url).content
        image = Image.open(io.BytesIO(image_data))
        return image

    except Exception as e:
        messagebox.showerror("Error", f"An error occurred: {e}")
        return None

def generate_and_display_image():
    description = entry.get()
    if not description:
        messagebox.showwarning("Warning", "Please enter a description.")
        return

    image = generate_image(description)
    if image:
        image.thumbnail((300, 300))
        photo = ImageTk.PhotoImage(image)

        image_label.config(image=photo)
        image_label.image = photo

# Create the main Tkinter window
root = tk.Tk()
root.title("DALL-E Image Generator")

# Create GUI components
entry = Entry(root, width=40)
generate_button = Button(root, text="Generate Image", command=generate_and_display_image)
image_label = Label(root)

# Place GUI components using grid layout
entry.grid(row=0, column=0, padx=10, pady=10)
generate_button.grid(row=0, column=1, padx=10, pady=10)
image_label.grid(row=1, columnspan=2, padx=10, pady=10)

# Start the Tkinter main loop
root.mainloop()

You don’t need to specify a model. What you show is an AI hallucination.

I also would make very small try/except sections, one for every instruction that could go wrong, so you can capture the error. Inserted print() statements can let you track the progress.

API image documentation - python example:

response = openai.Image.create(
  prompt="a white siamese cat",
  n=1,
  size="1024x1024"
)
image_url = response['data'][0]['url']
1 Like

I made a simpler script that does the same thing I wanted it to originally do:

import openai
openai.api_key = "[Redacted]"

input1 = input("Enter your input: ")
response = openai.Image.create(
    prompt=input1,
    n=4,
    model="image-alpha-001",
    size="1024x1024",
    response_format="url"
)
print(response["data"][0]["url"])

But now my script completely ignores the value of n, and only spits out one image URL as opposed to all 4 like I specified. Any advice?

As the title says, my Dall-E script ignores the n value I set in my code. Instead of generating the 4 images I specified, it only generates one. Can Dall-E only send one image URL at a time? Am I missing something?
Here’s the code:

import openai

# Your DALL-E API key
openai.api_key = "[REDACTED]"

input1 = input("Enter your input: ")

# Generate an image
response = openai.Image.create(
    prompt=input1,
    n=4,
    model="image-alpha-001",
    size="1024x1024",
    response_format="url"
)

# Print the URL of the generated image
print(response["data"][0]["url"])

I think it has something to do with the print function at the bottom, but I’m not exactly sure

You can only do 1 to 3 images… Try with a smaller number.

Additionally, you don’t send a model as there’s just one live… Did ChatGPT generate your code, by chance?

No, I used the example from the openai website

Do you have a link so we can check docs? Thanks.

As far as I know, it’s always been limited to 3 images and there is no model called. Would love to see the docs to make sure there’s not a mistake.

Thanks!

This is the link I used, but it seems like I misremembered. I swear it asked to specify model, but apparently I’m wrong. It does state that the n parameter can generate 1-10 images.
Open AI API Reference

1 Like

Huh. They must’ve upped the limit. Thanks!

If you take the model out, you should be good to go.

ETA: Also…

You need to grab the other URLs too…

print(response["data"][1]["url"])
print(response["data"][2]["url"])

etc etc

Thanks! It finally worked! Now I can finally finish this!

1 Like

Now the big thing to do is to convert into an executable file that people not comfortable with cmd can use. Pyinstaller and other exe convertors don’t work :confused:

Nice. Just remember, you don’t want to store the API key in the application, of course.

I’m assuming you’re building a BYOK app?

Nope, it’s part of a kiosk where people can generate AI images to print onto stuff like shirts. I kinda need to store our own key. The hope is that converting it to an exe can obfuscate it, especially when it’s compiled into one file as opposed to a directory

1 Like

Hrm. Be super careful here. As it’s a kiosk, they likely won’t have access to the code at all?

You really want to be handling it on a server on the backend… If they get to the code, they can likely decompile… if not they can just capture the network traffic and read the key… Just trying to save you some headaches later!

1 Like

I think leaving an API key in the source code is inherently risky now that I think about it. It’s for a small store, but it doesn’t mean people won’t try to steal the API key. Money’s kinda tight as it’s for a non-profit, so I’m looking into more practical options like compiling it as an alternative executable or code obfuscation.

2 Likes

And when the key IS stolen…update every kiosk.

1 Like

Maybe use Zapier or similar as a go-between no-server solution?

Sounds like it might be just one for non-profit… still, good to think about security beforehand…

That could work, I’ll look into that. It’s simpler than anything I could do on my own

I tried it out by using something that’s based off Google Forms and emailing, and it was easier to make and more reliable than my setup -_-. Thanks for the help! I think I can consider this project finished after I make some minor adjustments.

1 Like