生成式 AI - 根据关键字生成图片

1. 简介

上次更新日期:2023 年 10 月 12 日

Imagegen 图像生成

Google Imagen 是 Google 强大的大语言模型,可以根据文本说明生成逼真的创意图片。借助 Vertex AI 上的 Imagen,用户可以在几秒钟内构建下一代 AI 产品,将用户的想象力转化为高质量的视觉资源。除了根据文本生成图片外,它还支持通过文本提示、图片字幕、视觉问答以及主题与图片进行图片编辑基于样式的图片模型调整。

提示生成

如需使用 Imagen 创建图片,您需要提供图片的文本说明(称为提示),以便生成图片。不过,要生成优质逼真的图片,需要运用专业技能。如果您想生成与特定业务领域(例如零售、制造业等)相关的图片,它还可能与领域相关。一种较为简单的提示设计方法是为 Text Bison 模型提供一组关键字。

总体方法如下:

fbb3826592b2816d.png

Gradio 界面

Gradio 是一个开源 Python 库,可让您使用几行代码为机器学习模型、任何 API 甚至是任意 Python 函数快速创建易于使用且可自定义的界面组件。您可以将 Gradio GUI 直接集成到您的 Jupyter 笔记本中,或以链接的形式与任何人分享。GRadio 支持多种媒体类型,包括文字、图片、视频和音频。它还提供许多预构建的界面组件,例如输入字段、按钮、滑块和下拉菜单。

构建内容

在此 Codelab 中,您将部署一个 Gradio 应用,该应用将:

  • 使用关键字或短语生成文本提示。您也可以手动修改生成的提示。
  • 根据界面上生成的提示生成图片。

学习内容

  • 如何以编程方式将零样本和少样本学习与 text-bison 模型结合使用,以程序化方式生成与图片生成相关的具体提示。
  • 如何通过 API 和提示,使用 Imagen 模型生成图片。
  • 如何从 Vertex AI Workbench 笔记本构建、部署和测试 Gradio 应用。

所需条件

  • 对 GCP 项目(例如“Cloud-llm-preview4”)的访问权限
  • 拥有创建 Vertex AI Workbench 的权限
  • 已启用 Vertex AI API。
  • Gradio 的网络要求:笔记本实例访问公共网址

2. 准备工作

创建笔记本

  • 登录项目
  • 从左侧导航菜单中前往 workbench
  • 用户管理的笔记本下,使用默认选项创建一个新笔记本。
  • 点击“打开 JUPYTERLAB”在实例预配完成后运行

注意:如果笔记本处于停止状态,则其可能需要几分钟才能启动。

获取代码

我们把代码文件放在这里此笔记本可导入您的环境中,并按原样运行(但更改项目详情除外)。

3. 运行代码

安装/导入所需的依赖项和库

  • 安装 Gradio 应用
  • 导入用于 Text-Bison 和图片生成的 Vertex AI API。
  • 导入所有其他必需的库。

使用 Text-Bison 生成提示

使用包含关键字和/或短语的用户输入,即关键字或短语的逗号分隔列表,它们可用于构造描述所需生成的图像的句子。

例如:角色、正文、背景、光线和其他描述。

生成提示的函数如下所示:

\defPrompt_generation(角色、信号、主题、灯光、质量、extra_desc):

model = TextGenerationModel.from_pretrained("text-bison")

response_few_shot = model.predict(

    few_shot_prompt,

    **parameters

)

response_single_shot = model.predict(

    prompt,

    **parameters

)

少样本和零样本提示

零样本提示是一种文本生成技术,在这种技术中,模型不会提供上下文或示例来生成文本。这可能具有挑战性,因为模型必须依靠自己的知识来生成连贯且信息丰富的文本。

不过,零样本提示也非常有创意,因为模型不受任何现有样本的限制。

少样本提示是一种文本生成技术,向模型提供少量样本来生成文本。这比零样本提示更容易,因为模型对要生成什么内容有一些指导。然而,少样本提示也有局限性,因为模型可能只能生成与给定样本相似的文本。

以下是少样本和零样本提示的示例代码。

?**# 代码中使用了少样本提示**

few_shot_prompt = f"""您是编写图像生成模型提示的专家。使用提供的短语和关键字,将它们串联起来并添加一些真实的细节,以生成可用于图片生成的逻辑且有意义的提示。

input: people, gardening, house garden, colorful plants, Real, HD image, Photo.

output: A Photo of people gardening in a house garden landscape with few coloured flowering plants. Realistic FULL HD Images, Elegant and natural facial and eye features taken by professional photographer

input: plumber, faucet, kitchen, high quality, natural lighting, Photo

output: A Photo of a plumber fixing a faucet in the kitchen. High quality image with natural indoor lighting.

input: house and garden, halloween, warm lighting, high quality image, Sketch

output: A Sketch of Beautiful House and Garden with Halloween Decorations. Warm lighting, High Quality, 4K photograph taken by professional photographer from front.

input: nice living room, warm lighting,Professional Photographer from far, Photo

output: A photo of a Well designed Living Room. Warm lighting, High Quality, 4K photograph taken by Professional Photographer from far

input: {params_list_str}

output:

"""

# 代码中使用了零样本提示

prompt = f"""您是为图像生成模型撰写提示的专家。帮我写一个关于图片生成模型的实用提示列表,其中应包括以下字词:“{params_list_str}”。请务必在提示中添加这些字词,并确保提示含义明确。"""

使用 Imagen 生成图像

使用用户输入提示和负提示(可选),并将相同的内容提供给模型 (imagegeneration@002)。

?def image_generation_completion(input, negative_prompt):

input_prompt = input

model = ImageGenerationModel.from_pretrained("imagegeneration@002")

response = model.generate_images(

    prompt=input_prompt,

    number_of_images=4, #kept to static value of 4

    negative_prompt=negative_prompt

)

包含以下代码,用于根据用户输入提示和否定提示生成图片。最终代码使用 text-bison 模型生成的提示。

从 vertexai.preview.vision_models 导入 ImageGenerationModel

def image_generation(input, negative_prompt):

input_prompt = input

model = ImageGenerationModel.from_pretrained("imagegeneration@002")

response = model.generate_images(

    prompt=input_prompt,

    number_of_images=4, #kept to static value of 4.. can be a max value of 8

    negative_prompt=negative_prompt

)

images = response.images

return images

user_prompt = "提示:一位年轻女子在展示并出售一棵树上未装饰的圣诞树。由专业摄影师从远处拍摄的冷光、高画质和细节丰富的图片。”

negative_prompt = "扭曲且无吸引力的面孔"

generate_images_list = image_generation(user_prompt,negative_prompt)

#show 一张生成的图片

generated_images_list[0].show()

输出 -

db04a6bfdd78693b.jpeg

4. 部署 Gradio 应用

Gradio 用于前端,用户可以在该前端输入关键字并生成结构化提示,这些提示可以直接使用,也可以由用户进一步修改,然后馈送到 Imagen 中,以便根据输入生成图片。Gradio 是一个 Python 库,可用于为机器学习模型创建界面。对于此应用,代码块用于向此应用提高灵活性和复杂的数据流。Blocks 使用行和列提供应用布局管理:

,使用 gr.Blocks() 演示:

#Prompt Generation Part

with gr.Row():

    with gr.Column(scale=1):

        Persona = gr.Textbox(label="Persona", info = "Customer segment such as Plumber, Electrician etc.")

    with gr.Column(scale=1):

        Signals = gr.Textbox(label="Signals", info = "Main content of banner such as Faucet, Lamp etc.")

    with gr.Column(scale=1):

        Theme = gr.Textbox(label="Theme", info = "Context of the banner such as Halloween, Kitchen etc.")

with gr.Row():

    with gr.Column(scale=1):

        photo_modifiers = gr.Textbox(label="Photography Modifiers", info = "Photography specific modifiers and parameters such as Lighting(Dramatic/Natural/Warm/Cold), Camera Proximity etc.")

    with gr.Column(scale=1):

        quality_modifiers =  gr.Textbox(label="Image Quality Modifier", info = "Quality Modifiers like high-quality, beautiful, stylized. 4K, HDR, By a professional etc")

    with gr.Column(scale=1):

        other_desc =  gr.Textbox(label="Any Other Description", info = "Other Descriptions for Image such as Style (Painting/Photo/Sketch), Bakground/Foreground Context")

使用 gr.Row():

    btn = gr.Button("Submit")

使用 gr.Row():

    returned_prompts = gr.Textbox(label="Result Prompts", interactive = True)    

btn.click(fn=prompt_generation, input=[Persona, Signals,Theme, photo_modifiers, quality_modifiers, other_desc], 输出 = return_prompts)

为了处理用户输入和输出,Gradio 提供了多个组件,例如图片、视频、滑块、下拉菜单、文本框、单选按钮等。这些组件使开发者能够灵活控制如何接受用户的输入并将其提供给测试野牛、成像模型或任何其他机器学习模型。

对于此项目,应用是使用 Blocks 创建的,以提高灵活性和复杂程度

数据流向应用除了 Blocks 之外,我们还提供多个 Gradio 组件

包括:

以下代码段用于根据输入和否定提示生成图片:

? #图片生成部分

with gr.Row():

    with gr.Column(scale=1):

        image_prompt = gr.Textbox(label="Image Generation Prompt")

with gr.Accordion("Advanced options", open=False): #Let's hide the advanced options!

    with gr.Row():

        negative_prompt = gr.Textbox(label="Negative prompt", info = "Specify What not to Include in Image ex. Bad Quality Image")

with gr.Row():

    with gr.Column(scale=1):    

        img_btn = gr.Button("Generate Images")

with gr.Row():

    with gr.Column():

        output_image_1 = gr.Image(label = "Result Image 1", visible = False)

    with gr.Column():

        output_image_2 = gr.Image(label = "Result Image 2", visible = False)

with gr.Row():

    with gr.Column():

        output_image_3 = gr.Image(label = "Result Image 3", visible = False)

    with gr.Column():

        output_image_4 = gr.Image(label = "Result Image 4", visible = False)

returned_prompts.select(populate_image_prompt, inputs = [returned_prompts], outputs = image_prompt)

img_btn.click(fn=image_generation_completion, inputs=[image_prompt,negative_prompt], outputs = [output_image_1,output_image_2,output_image_3,output_image_4])       

要运行并测试 Gradio 应用程序,只需输入文本提示并点击 生成 按钮即可。Imagen 将根据您的提示生成图片。您可以尝试不同的提示,看看 Imagen 可以生成哪些类型的图片。

下面是 Gradio 应用 Prompt Generation 的屏幕截图。

70331c9645b1e91b

下面是 Gradio 应用“图片生成”功能的屏幕截图。

a7261e8fafab7073.png

一些示例 -

示例 1 -

[左图] 提示(使用简单的关键字作为提示):几个朋友乘船。

[右图] 提示(使用 Text-Bison 生成的提示):两位年轻男子在船上钓鱼,周围环绕着树林中深色树木的照片。男人身穿衬衫,站在船上。由专业摄影师拍摄的高画质 4K 自然光线照片。

c2f5fabd10baf42.jpeg abc9b8204a9fdf7f.jpeg

示例 2 -

[左图] 提示(使用简单的关键字作为提示):圣诞树

[右图] 提示(使用 Text-Bison 生成的提示):房间里有一棵圣诞树,里面有一盏灯和家具。这棵树上装饰着灯光和装饰品。它放置在窗户附近,背景中有一面墙。由专业摄影师从远处拍摄的暖光、高画质、HDR 照片。

f10cf9f52ffd92c7.jpeg cce36df7a439b309.jpeg

5. 清理

如需清理资源

  • 停止 gradio 应用。
  • 停止/删除 Workbench 笔记本。

6. 恭喜

恭喜!您已成功部署了一个 Gradio 应用,该应用可使用 Google Text-Bison API 和 Imagen API 创建提示和图片。