ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Generative AI for Beginners 第 9 课:使用 DALL-E 与 Azure OpenAI 构建图像生成应用

Generative AI for Beginners 第 9 课:使用 DALL-E 与 Azure OpenAI 构建图像生成应用 Generative AI for Beginners 第 9 课使用 DALL-E 与 Azure OpenAI 构建图像生成应用【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners本课聚焦于生成式 AI 的图像生成能力从文本描述生成图像并围绕 DALL-E / gpt-image-1 这类图像模型构建可运行的 Python 应用。文章以 translations/id/09-building-image-applications/README.md对应英文原版 09-building-image-applications/README.md为骨架结合 09-building-image-applications/python/ 下的仓库源码展开。你将掌握搭建 Azure OpenAI 图像生成环境、调用client.images.generate生成图片、使用 temperature 控制输出随机性、利用 meta prompt 划定内容边界以及图片编辑与变体等进阶能力。为什么构建图像生成应用LLM 的价值不止于文本生成——从文字描述生成图像的能力为 MedTech、建筑、旅游、游戏开发等众多领域带来新的可能性。图像生成应用是探索生成式 AI 能力的绝佳载体典型用途包括图像编辑与合成为多种场景生成图像例如对现有图片进行局部修改或合成新内容跨行业应用医疗科技、旅游、游戏开发等行业都可以借助文本生成图像。教学场景Edu4All本课延续项目中的创业公司场景 Edu4All学生们需要为作业生成图像例如为自己写的童话绘制插图、为故事设计新角色或把抽象的想法与概念可视化。比如当学生正在学习世界著名纪念碑时他们可以生成这样的图像使用的提示词很简单Dog next to Eiffel Tower in early morning sunlight清晨阳光下埃菲尔铁塔旁的一只狗这一场景将在后面的任务与解决方案中再次出现届时我们会用 meta prompt 约束输出生成巴黎凯旋门主题的图片。DALL-E 与 Midjourney 是什么DALL-E 与 Midjourney 是两款最流行的图像生成模型都允许你通过 prompt 生成图像。DALL-EDALL-E 是一个由文本描述生成图像的生成式 AI 模型。它由两个模型组合而成CLIP与diffused attentionCLIP从图像与文本中生成 embeddings数据的数值表示Diffused attention从 embeddings 生成图像。DALL-E 在图像-文本数据集上训练因此可以把文本描述映射为图像例如戴帽子的猫或莫霍克发型的狗。从架构上看DALL-E 基于 transformer 架构中的autoregressive transformer自回归 Transformer它逐像素生成图像——先生成一个像素再基于已生成的像素预测下一个像素依次穿过神经网络的多个层直到图像完成。通过这一过程DALL-E 可以控制生成图像中的属性、对象、特征等而 DALL-E 2 与 DALL-E 3 对生成图像拥有更强的控制力。MidjourneyMidjourney 的工作方式与 DALL-E 类似从文本 prompt 生成图像同样支持戴帽子的猫、莫霍克发型的狗这类描述。两者定位不同——DALL-E 通过 API 编程调用适合嵌入应用Midjourney 更常用于对话式/交互式创作本课以可编程的 API 方案Azure OpenAI为主。搭建第一个图像生成应用构建图像生成应用需要以下 Python 库python-dotenv强烈建议用它把密钥存放在与代码分离的.env文件中openai用于与 OpenAI / Azure OpenAI API 交互pillow在 Python 中处理图像requests发起 HTTP 请求用于下载生成的图片。创建并部署 Azure OpenAI 模型若尚未创建请按 Microsoft Learn 指引创建 Azure OpenAI 资源与模型。当前一代 Azure OpenAI 图像模型为gpt-image-1DALL-E 3 属旧版新部署已不再提供仓库中 aoai-app.py 与 TypeScript 版 main.ts 均默认采用该模型。创建应用1. 配置.env环境变量AZURE_OPENAI_ENDPOINTyour endpoint AZURE_OPENAI_API_KEYyour key AZURE_OPENAI_DEPLOYMENTgpt-image-1这些信息可在 Azure OpenAI Foundry 门户的 Deployments 部分找到。2. 编写requirements.txtpython-dotenv openai pillow requests与仓库根目录的 requirements.txt 及 09-building-image-applications/requirements.txt 保持一致。3. 创建虚拟环境并安装依赖python3 -m venv venv source venv/bin/activate pip install -r requirements.txtWindows 下创建与激活虚拟环境的命令python3 -m venv venv venv\Scripts\activate.bat4. 编写app.pyimport openai import os import requests from PIL import Image import dotenv from openai import OpenAI, AzureOpenAI # import dotenv dotenv.load_dotenv() # configure Azure OpenAI service client client AzureOpenAI( azure_endpoint os.environ[AZURE_OPENAI_ENDPOINT], api_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 ) try: # Create an image by using the image generation API generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1, modelos.environ[AZURE_OPENAI_DEPLOYMENT] ) # Set the directory for the stored image image_dir os.path.join(os.curdir, images) # If the directory doesnt exist, create it if not os.path.isdir(image_dir): os.mkdir(image_dir) # Initialize the image path (note the filetype should be png) image_path os.path.join(image_dir, generated-image.png) # Retrieve the generated image image_url generation_response.data[0].url # extract image URL from response generated_image requests.get(image_url).content # download the image with open(image_path, wb) as image_file: image_file.write(generated_image) # Display the image in the default image viewer image Image.open(image_path) image.show() # catch exceptions except openai.BadRequestError as err: print(err)仓库中的 aoai-app.py 提供了几乎一致的实现并额外展示了用result.model_dump_json()把响应序列化为 JSON 后再提取data[0][url]的写法同时把模型名放入model os.environ[AZURE_OPENAI_DEPLOYMENT]变量中复用代码结构更便于维护。逐段解读这段代码导入依赖引入 OpenAI 库、dotenv 库、requests 库与 Pillow 库import openai import os import requests from PIL import Image import dotenv加载环境变量dotenv.load_dotenv()配置 Azure OpenAI 客户端从环境变量读取 endpoint 与 key。注意api_version需与所选模型匹配——仓库代码使用2024-10-21旧版文档中的2024-02-01对应 DALL-E 3 时代具体以 Microsoft Foundry 文档为准client AzureOpenAI( azure_endpoint os.environ[AZURE_OPENAI_ENDPOINT], api_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 )生成图像调用client.images.generate响应是包含生成图像 URL 的 JSON 对象generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1, modelos.environ[AZURE_OPENAI_DEPLOYMENT] )下载并展示用 URL 下载图片保存为 PNG 文件再用系统默认查看器打开image Image.open(image_path) image.show()生成图片的更多细节核心调用client.images.generate的参数含义prompt用于生成图像的文本提示。本例为 Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils雾霭草地上长满水仙花、小兔骑在马背上举着棒棒糖size生成图像的尺寸本例为 1024x1024 像素n生成的图片数量temperature控制生成式 AI 模型输出的随机性取值 010 表示输出确定1 表示输出随机默认 0.7详细实验见下文Temperature一节。TypeScript 版本的仓库示例 main.ts 展示了同样的调用模式new AzureOpenAI({ endpoint, apiKey, deployment, apiVersion })后调用client.images.generate({ model, prompt, n, size })并遍历imageGenerations.data打印每张图片的 URL——与 Python 端接口一一对应。图像生成的进阶能力除了基础生成还可以对图片做更多操作执行编辑Edit提供一张已有图片、一个 mask标识需要修改的区域和一个 prompt即可改变图片。例如给兔子图片戴上帽子提供原图、mask 与文字 prompt。注意DALL-E 3 不支持此功能。使用 GPT Imagegpt-image-1的编辑示例response client.images.edit( modelgpt-image-1, imageopen(sunlit_lounge.png, rb), maskopen(mask.png, rb), promptA sunlit indoor lounge area with a pool containing a flamingo ) image_url response.data[0].url基础图片只包含带泳池的休息室最终图片会多出一只火烈鸟创建变体Variation思路是拿一张已有图片请求生成变体。需要提供图片与文字 prompt示例代码response client.images.create_variation( imageopen(bunny-lollipop.png, rb), n1, size1024x1024 ) image_url response.data[0].url注意变体功能仅由 OpenAI 的 DALL-E 2 模型支持gpt-image-1 不支持。仓库中 oai-app.py 在生成完成后追加了client.images.create_variation(imageopen(image_path, rb), n1, size1024x1024)oai-app-variation.py 则把变体写成独立流程先打开之前生成的generated-image.png调用变体接口把结果保存为generated_variation.png并展示。需要留意的是DALL-E 3 生成的图片目前还不能直接作为变体输入使用前请确认所选模型的能力边界。Temperature控制输出的随机性temperature是控制生成式 AI 模型输出随机性的参数取值 010 表示输出确定deterministic1 表示输出随机random默认值为 0.7。实验方法把下面这条 prompt 连续运行两次——Prompt: Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils再运行一次相同的 prompt你会看到结果并不相同两张图片相似但不相同。为了让输出更确定把 temperature 设为 0generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, # Enter your prompt text here size1024x1024, n2, temperature0 )运行后得到两张图可以明显看到temperature 设为 0 后两张图彼此更接近说明随机性被显著压低。用 Meta Prompt 为应用划定边界演示应用已能为客户生成图片但还需要为应用设定边界——例如不能生成不适合工作场合not safe for work或不适合儿童观看的图片。Meta prompt元提示词就是用来控制生成式 AI 模型输出的文本 prompt。它的工作方式是置于用户 prompt 之前与应用集成将用户输入 prompt与meta prompt 输入封装进同一个文本 prompt 中从而约束模型的输出。一个典型的 meta prompt 示例You are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. (Input)把它应用到演示中——先声明一个disallow_list禁用词列表再与 meta prompt 模板拼接disallow_list swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult meta_prompt fYou are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} prompt f{meta_prompt} Create an image of a bunny on a horse, holding a lollipop # TODO add request to generate image从上面的 prompt 可以看到所有生成的图片都会把 meta prompt 作为约束纳入考虑禁用词列表直接注入 meta prompt 中即使用户输入里出现这些词模型也会拒绝生成不安全/不适合儿童的内容。这正是元提示词把规则与用户输入封装在单一文本 prompt 中的实际体现。任务帮学生生成纪念碑图片回到开头介绍的 Edu4All 场景帮助学生为作业生成包含纪念碑的图片具体生成哪座纪念碑由学生自行决定鼓励发挥创意把纪念碑放在不同的情境中。参考解决方案如下见 aoai-solution.py响应序列化方式与带model参数的主应用一致import openai import os import requests from PIL import Image import dotenv from openai import AzureOpenAI # import dotenv dotenv.load_dotenv() # Get endpoint and key from environment variables client AzureOpenAI( azure_endpoint os.environ[AZURE_OPENAI_ENDPOINT], api_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 ) disallow_list swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult meta_prompt fYou are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} prompt f{meta_prompt} Generate monument of the Arc of Triumph in Paris, France, in the evening light with a small child holding a Teddy looks on. try: # Create an image by using the image generation API generation_response client.images.generate( promptprompt, # Enter your prompt text here size1024x1024, n1, ) # Set the directory for the stored image image_dir os.path.join(os.curdir, images) # If the directory doesnt exist, create it if not os.path.isdir(image_dir): os.mkdir(image_dir) # Initialize the image path (note the filetype should be png) image_path os.path.join(image_dir, generated-image.png) # Retrieve the generated image image_url generation_response.data[0].url # extract image URL from response generated_image requests.get(image_url).content # download the image with open(image_path, wb) as image_file: image_file.write(generated_image) # Display the image in the default image viewer image Image.open(image_path) image.show() # catch exceptions except openai.BadRequestError as err: print(err)这段代码把本课的全部知识点串成了一条完整流水线dotenv 加载密钥 → 配置 AzureOpenAI 客户端 → 组装 meta prompt 用户 prompt黄昏光线下巴黎凯旋门一个抱着泰迪熊的小男孩在旁观看→client.images.generate生成 → 下载保存 → 展示。仓库中的 aoai-app.py 与 aoai-solution.py 均使用try/finally结构并在结束打印 completed!异常处理则通过except BadRequestError捕获非法请求。小结本课带你走完了文本 → 图像的完整链路理解 DALL-E 的 CLIP diffused attention 架构与自回归生成原理 → 配置 Azure OpenAIgpt-image-1→ 用client.images.generate生成并保存图片 → 通过 temperature 调节随机性 → 用 meta prompt 禁用词列表划定内容边界 → 掌握编辑edit与变体variation进阶能力。想继续深入可以对照阅读仓库中的相关实现Python 主应用、变体应用、带 meta prompt 的解决方案、TypeScript 版本以及本课作业 aoai-assignment.ipynb 与 oai-assignment.ipynb。下一步可继续学习第 10 课构建低代码 AI 应用见 10-building-low-code-ai-applications/README.md。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表