生成式 AI - 根據關鍵字產生圖片

1. 簡介

上次更新時間:2023 年 10 月 12 日

Imagegen 圖像生成

Google Imagen 是 Google 強大的大型語言模型,可根據文字敘述生成逼真且富有創意的圖像。使用者可以運用 Vertex AI 中的 Imagen 建構新一代 AI 產品,在幾秒內將使用者的想像轉化為高品質的視覺素材。除了根據文字生成圖像,還支援透過文字提示編輯圖像、生成圖像說明、視覺問與答,以及根據主題和風格調整圖像模型。

生成提示

如要使用 Imagen 建立圖片,請提供圖片的文字說明 (又稱提示詞),系統會根據提示詞生成圖片。不過,如要生成高品質的擬真圖像,需要具備提示專業知識。如果想生成圖片,也可能需要依據網域調整提示,例如零售、製造等特定業務領域。設計提示的簡單方法是提供一組關鍵字給 Text Bison 模型。

整體方法如下:

fbb3826592b2816d.png

Gradio UI

Gradio 是一個開放原始碼的 Python 程式庫,只要幾行程式碼,就能為機器學習模型、任何 API,甚至是任意 Python 函式,快速建立易於使用且可自訂的 UI 元件。您可以將 Gradio GUI 直接整合到 Jupyter 筆記本中,也可以透過連結與任何人分享。Gradio 支援多種媒體類型,包括文字、圖片、影片和音訊。此外,還提供許多預先建構的 UI 元件,例如輸入欄位、按鈕、滑桿和下拉式選單。

建構項目

在本程式碼研究室中,您將部署 Gradio 應用程式,該應用程式會執行下列操作:

  • 使用關鍵字或詞組生成文字提示。你也可以手動編輯生成的提示。
  • 根據 UI 上生成的提示詞生成圖片。

課程內容

  • 如何以程式輔助方式,搭配 text-bison 模型使用零樣本和少量樣本學習,生成 Imagen 專屬的圖像生成提示。
  • 如何透過 API 和提示,使用 Imagen 模型生成圖片。
  • 如何從 Vertex AI Workbench 筆記本建構、部署及測試 Gradio 應用程式。

軟硬體需求

  • 存取 GCP 專案,例如「Cloud-llm-preview4」
  • 建立 Vertex AI Workbench 的存取權
  • Vertex AI API 已啟用。
  • Gradio 的網路需求:筆記本執行個體存取公開網址

2. 開始設定

建立筆記本

  • 登入專案
  • 從左側導覽選單前往「工作台」
  • 在「使用者自行管理的筆記本」下方,以預設選項建立新的筆記本。
  • 執行個體佈建完成後,按一下「OPEN JUPYTERLAB」

注意:如果筆記本處於停止狀態,可能需要幾分鐘才能啟動。

取得程式碼

我們已將程式碼檔案放在這裡。您可以將這個筆記本匯入環境,並直接執行 (專案詳細資料除外)。

3. 執行程式碼

安裝/匯入必要的依附元件和程式庫

  • 安裝 Gradio 應用程式
  • 匯入 Text-Bison 和圖像生成專用的 Vertex AI API。
  • 匯入所有其他必要程式庫。

使用 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 和 Zero-Shot 提示的程式碼範例。

**# Few Shot Prompt used in the code**

few_shot_prompt = f"""You are an expert in writing prompts for Image Generation Models. 使用提供的詞組和關鍵字,將其串連並加入一些逼真細節,生成可用於圖像生成的邏輯和有意義的提示。

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:

"""

# Zero Shot Prompt used in the code

prompt = f"""You are an expert in writing prompts for Image Generation Models. 請幫我撰寫圖片生成模型的提示清單,內容要包含「{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

提示詞:一名年輕女子展示並販售一棵未裝飾的聖誕樹,樹木來自一堆樹木。Cold Lighting, High Quality and detailed Image Taken By Professional Photographer from far."

negative_prompt = "Distorted and unattractive faces"

generated_images_list = image_generation(user_prompt,negative_prompt)

#show one of the generated image

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")

with gr.Row():

    btn = gr.Button("Submit")

with 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 提供多種元件,例如圖片、影片、滑桿、下拉式選單、文字方塊、單選按鈕和其他選項。開發人員可透過這些元件彈性控管如何接受使用者輸入內容,並將內容提供給 Test-bison、Imagen 或任何其他機器學習模型。

在這個專案中,應用程式是使用「方塊」建立,可增加彈性並處理複雜的

資料會流向應用程式。除了區塊,多個 Gradio 元件也

包括:

以下程式碼片段用於根據輸入內容和負面提示詞生成圖片:

 #Image Generation part

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 應用程式,只要輸入文字提示詞並點選「Generate」按鈕即可。Imagen 會根據提示生成圖片。您可以嘗試不同的提示,看看 Imagen 能生成哪些類型的圖片。

以下是 Gradio 應用程式的提示生成功能螢幕截圖。

70331c9645b1e91b.png

以下是 Gradio 應用程式的圖片生成功能螢幕截圖。

a7261e8fafab7073.png

部分範例:

範例 1 -

[左側圖片] 提示 (使用簡單的關鍵字做為提示):一對朋友在划船。

[右側圖片] 提示 (使用 Text-Bison 生成的提示):兩名年輕男子在船上釣魚,周圍是樹林中深色的樹木。男子穿著襯衫,站在船上。自然光、高畫質、專業攝影師拍攝的 4K 相片。

c2f5fabd10baf42.jpeg abc9b8204a9fdf7f.jpeg

範例 2 -

[左側圖片] 提示 (使用簡單的關鍵字做為提示):聖誕樹

[右圖] 提示 (使用 Text-Bison 生成的提示):房間裡的聖誕樹,旁邊有燈和家具。樹上裝飾著燈飾和裝飾品。裝置放在窗戶附近,背景可見牆壁。暖色調燈光、高畫質、高動態範圍相片,由專業攝影師從遠處拍攝。

f10cf9f52ffd92c7.jpeg cce36df7a439b309.jpeg

5. 清除

如要清理資源,請按照下列步驟操作:

  • 停止 gradio 應用程式。
  • 停止/刪除 Workbench 筆記本。

6. 恭喜

恭喜!您已成功部署 Gradio 應用程式,可使用 Google Text-Bison API 和 Imagen API 建立提示和圖片。