OpenAI API 错误:“您试图访问 openai.Image,但在 openai>=1.0.0 中不再支持”

0 投票
1 回答
74 浏览
提问于 2025-04-14 15:21

我正在做一个项目,目的是根据用户提供的信息制作名片。我使用的是Streamlit和OpenAI。

但是我一直遇到这个错误:

APIRemovedInV1: 你尝试访问openai.Image,但在openai版本1.0.0及以上中,这个功能已经不再支持了 - 你可以查看https://github.com/openai/openai-python上的说明。你可以运行openai migrate来自动升级你的代码,以使用1.0.0的接口。或者,你可以把你的安装固定在旧版本,比如pip install openai==0.28。这里有一个详细的迁移指南: https://github.com/openai/openai-python/discussions/742

这是我的代码:

import streamlit as st
import openai
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import numpy as np

# Set up your OpenAI API key
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# Function to calculate the brightness of an image
def calculate_brightness(image):
    # Convert image to grayscale
    gray_image = image.convert("L")
    # Calculate average pixel brightness
    brightness = np.mean(np.array(gray_image))
    return brightness

# Function to determine text color based on brightness
def get_text_color(background_image):
    brightness_threshold = 127.5
    brightness = calculate_brightness(background_image)
    if brightness < brightness_threshold:
        return "white"
    else:
        return "black"

# Function to generate logo image based on organization name
def generate_logo_image(organization_name):
    # Split organization name into words
    words = organization_name.split()
    # If organization name has more than one word, take the first letter of each word
    if len(words) > 1:
        logo_text = "".join(word[0] for word in words)
    # If organization name has only one word, take the first letter
    else:
        logo_text = organization_name[0]

    # Define font and size for logo
    logo_font_size = 64
    logo_font = ImageFont.truetype("arialbd.ttf", logo_font_size)  # Use a bold font for the logo

    # Create a blank white image for the logo
    logo_image = Image.new("RGB", (logo_font.getbbox(logo_text)[2], logo_font.getbbox(logo_text)[3]), "white")
    draw = ImageDraw.Draw(logo_image)

    # Calculate text position to center the logo
    text_x = (logo_image.width - draw.textlength(logo_text, font=logo_font)) / 2
    text_y = (logo_image.height - logo_font_size) / 2

    # Add text to the logo image
    draw.text((text_x, text_y), logo_text, fill="black", font=logo_font)

    return logo_image

# Function to generate business card image
def generate_business_card(name, designation, contact_number, email_address, logo_image, background_image):
    # Create a blank white image
    card_width, card_height = 3.5 * 300, 2 * 300  # Standard business card size: 3.5 x 2 inches at 300 DPI
    business_card = Image.new("RGB", (int(card_width), int(card_height)), "white")

    # Add background image if provided
    if background_image:
        business_card.paste(background_image, (0, 0))

    draw = ImageDraw.Draw(business_card)

    # Determine text color based on background image brightness
    text_color = get_text_color(background_image)

    # Add logo image to the header
    if logo_image:
        logo_width, logo_height = logo_image.size
        logo_x = (card_width - logo_width) / 2
        logo_y = 20
        business_card.paste(logo_image, (int(logo_x), int(logo_y)))

    # Define font and size for text
    font_size = 36
    font = ImageFont.truetype("arialbd.ttf", font_size)  # Use a bold font

    # Define contact information
    contact_info = f"{name}\n{designation}\n{contact_number}\n{email_address}"

    # Calculate text width for contact information
    contact_text_width = max(draw.textlength(line, font=font) for line in contact_info.split("\n"))

    # Add contact information to the card
    contact_text_x = (card_width - contact_text_width) / 2
    contact_text_y = (card_height - font_size * 4) / 2
    draw.multiline_text((contact_text_x, contact_text_y), contact_info, fill=text_color, font=font, align="center")

    return business_card

# Define Streamlit app
def main():
    st.title("Business Card Generator")

    # Input fields for user information
    name = st.text_input("Enter Name:")
    designation = st.text_input("Enter Designation:")
    contact_number = st.text_input("Enter Contact Number:")
    email_address = st.text_input("Enter Email Address:")
    organization_name = st.text_input("Enter Organization Name:")

    # Generate logo image based on organization name
    if organization_name:
        logo_image = generate_logo_image(organization_name)
    else:
        logo_image = None

    # Prompt for background image generation
    st.header("Background Image Generation")
    background_prompt = st.text_area("Provide a prompt for the background image generation:")

    # Button to generate business card
    if st.button("Generate Business Card"):
        if name and designation and contact_number and email_address:
            # Generate background image
            if background_prompt:
                background_response = openai.Image.create(prompt=background_prompt)
                background_image = Image.open(background_response.url)
            else:
                background_image = None

            # Generate business card image
            business_card_image = generate_business_card(name, designation, contact_number, email_address, logo_image, background_image)

            # Display business card image
            st.image(business_card_image, caption="Business Card", use_column_width=True)

# Run the app
if __name__ == "__main__":
    main()

我尝试根据网上找到的资源来修复我的代码,其中包括迁移指南,我了解到有一些重大变化,比如openai.Image.create()变成了client.images.generate()

我尝试根据这个来修复我的代码,但我搞得整个流程都乱了,所以我不得不把它恢复到我之前工作的基础代码,我已经在帖子中添加了这部分。

有没有人能帮我解决这个问题?我知道我快成功了,但又觉得离目标还很远。提前谢谢大家!

1 个回答

0

问题是你安装的OpenAI Python SDK版本是大于等于v1的,但你使用的代码是适用于小于等于v0.28的。

选项 1:迁移你的代码

运行openai migrate命令,这样会把你的代码改成和大于等于v1版本兼容的。简单来说,这个命令会把某个方法的名字从这样...

openai.Image.create

...改成这样。

openai.images.generate

当然,你也可以手动修改这部分代码。可以参考官方的OpenAI文档

选项 2:降级你的OpenAI Python SDK

把OpenAI Python SDK降级到v0.28,然后保持你的代码不变。

撰写回答