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

1. 简介

上次更新时间:2023 年 10 月 12 日

Imagegen 图片生成

Google Imagen 是 Google 推出的一款强大的大语言模型,可以根据文本描述生成逼真且富有创意的图片。借助 Vertex AI 上的 Imagen,用户可以构建新一代 AI 产品,这类产品可在几秒钟内将用户的想象力转化为高品质的视觉素材资源。除了根据文本生成图片之外,它还支持通过文本提示进行图片修改、图片标注、视觉问答,以及基于主题和样式的图片模型调优。

提示生成

如需使用 Imagen 创建图片,您需要提供图片说明(称为提示),Imagen 会根据该说明生成图片。不过,要生成高画质的逼真图像,需要具备提示方面的专业知识。如果您想生成与零售、制造等特定业务领域相关的图片,提示也可以取决于网域。设计提示的更简单方法是向 Text Bison 模型提供一组关键字。

总体方法如下:

fbb3826592b2816d.png

Gradio 界面

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

构建内容

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

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

学习内容

  • 如何以编程方式将零样本学习和少量样本学习与 text-bison 模型搭配使用,以生成用于图片生成的 imagen 特定提示。
  • 如何通过 API 和提示使用 Imagen 模型生成图片。
  • 如何从 Vertex AI Workbench 笔记本构建、部署和测试 Gradio 应用。

所需条件

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

2. 准备工作

创建笔记本

  • 登录项目
  • 通过左侧导航菜单前往工作台
  • 在“用户管理的笔记本”下,使用默认选项创建新的笔记本。
  • 实例完成预配后,点击“打开 JUPYTERLAB”。

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

获取代码

我们已将代码文件放在此处。此笔记本可在您的环境中导入并按原样运行(只需更改项目详细信息)。

3. 运行代码

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

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

使用 Text-Bison 生成提示

使用包含关键字和/或短语的用户输入,即以英文逗号分隔的关键字或短语列表,可用于构建描述要生成的所需图片的句子。

例如 - 人物角色、正文、背景、光线和其他说明。

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

def prompt_generation(persona,signal,theme, lighting, quality, 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 模型生成的提示。

from vertexai.preview.vision_models import 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

提示:一位年轻女子正在展示并销售一棵未装饰的新鲜圣诞树,这棵树来自一大堆树。冷色调灯光,由专业摄影师从远处拍摄的高品质、细节丰富的图片。

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

generated_images_list = image_generation(user_prompt,negative_prompt)

#显示生成的图片之一

generated_images_list[0].show()

输出 -

db04a6bfdd78693b.jpeg

4. 部署 Gradio 应用

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

with gr.Blocks() as demo:

#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, inputs=[Persona, Signals,Theme, photo_modifiers, quality_modifiers, other_desc], outputs = returned_prompts)

为了处理用户输入和输出,Gradio 提供了多个组件,例如 Image、Video、Slider、Dropdown、Textbox、Radio 和其他选项。这些组件使开发者能够灵活地控制如何接受用户输入并将其馈送到 Test-bison、Imagen 或任何其他机器学习模型。

对于此项目,应用是使用 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 应用上的提示生成功能的屏幕截图。

70331c9645b1e91b.png

下图是 Gradio 应用上的图片生成功能界面截图。

a7261e8fafab7073.png

一些示例 -

示例 1 -

[左侧图片] 提示(使用简单的关键字作为提示):一对朋友在划船。

[右侧图片] 提示(使用 Text-Bison 生成的提示):一张照片,画面中 2 位年轻男子在船上钓鱼,周围是树林中深色的树木。男士们穿着衬衫,站在船上。自然光线、高画质、专业摄影师拍摄的 4K 照片。

c2f5fabd10baf42.jpeg abc9b8204a9fdf7f.jpeg

示例 2 -

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

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

f10cf9f52ffd92c7.jpeg cce36df7a439b309.jpeg

5. 清理

如需清理资源,请执行以下操作:

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

6. 恭喜

恭喜,您已成功部署一个 Gradio 应用,用于通过 Google Text-Bison API 和 Imagen API 创建提示和图片。