Skip to content

Latest commit

 

History

History
475 lines (322 loc) · 17.6 KB

File metadata and controls

475 lines (322 loc) · 17.6 KB

建立影像生成應用程式

建立影像生成應用程式

大型語言模型不僅能生成文字,也能從文字描述生成影像。影像作為一種媒介,在醫療科技、建築、旅遊、遊戲開發等多個領域都非常有用。本章節將介紹兩個最受歡迎的影像生成模型:DALL-E 和 Midjourney。

介紹

本課程將涵蓋:

  • 影像生成及其應用價值。
  • DALL-E 和 Midjourney 是什麼,以及它們的運作原理。
  • 如何建立一個影像生成應用程式。

學習目標

完成本課程後,你將能夠:

  • 建立影像生成應用程式。
  • 使用元提示(meta prompts)為應用程式設定界限。
  • 使用 DALL-E 和 Midjourney。

為什麼要建立影像生成應用程式?

影像生成應用程式是探索生成式 AI 能力的絕佳方式。它們可以用於:

  • 影像編輯與合成。你可以生成各種用途的影像,例如影像編輯和合成。

  • 應用於多個產業。也能用於醫療科技、旅遊、遊戲開發等多個產業的影像生成。

情境:Edu4All

在本課程中,我們將繼續與新創公司 Edu4All 合作。學生們將為他們的評量創作影像,影像內容由學生決定,可能是他們自己的童話故事插圖、新角色設計,或幫助他們視覺化想法與概念。

例如,若 Edu4All 的學生在課堂上研究紀念碑,他們可能會生成如下影像:

Edu4All startup, class on monuments, Eiffel Tower

使用的提示語為:

「清晨陽光下,埃菲爾鐵塔旁的一隻狗」

什麼是 DALL-E 和 Midjourney?

DALL-EMidjourney 是兩個最受歡迎的影像生成模型,能透過提示語生成影像。

DALL-E

先從 DALL-E 開始,它是一個從文字描述生成影像的生成式 AI 模型。

DALL-E 是由兩個模型組合而成,CLIP 與 diffused attention

  • CLIP 是一個能從影像和文字中產生嵌入向量(數值化資料表示)的模型。

  • Diffused attention 是一個從嵌入向量生成影像的模型。DALL-E 在大量影像與文字資料集上訓練,能根據文字描述生成影像。例如,DALL-E 可以生成戴帽子的貓或莫霍克髮型的狗的影像。

Midjourney

Midjourney 的運作方式與 DALL-E 類似,能根據文字提示生成影像。Midjourney 也能用提示語如「戴帽子的貓」或「莫霍克髮型的狗」來生成影像。

Image generated by Midjourney, mechanical pigeon 圖片來源 Wikipedia,影像由 Midjourney 生成

DALL-E 和 Midjourney 的運作原理

首先介紹 DALL-E。DALL-E 是基於 transformer 架構的生成式 AI 模型,採用 自回歸 transformer

自回歸 transformer 定義了模型如何從文字描述生成影像,它一次生成一個像素,並利用已生成的像素來生成下一個像素。透過神經網路的多層處理,直到影像完成。

透過此過程,DALL-E 能控制影像中的屬性、物件、特徵等。不過,DALL-E 2 和 3 對生成影像的控制力更強。

建立你的第一個影像生成應用程式

那麼,建立影像生成應用程式需要什麼?你需要以下函式庫:

  • python-dotenv,強烈建議使用此函式庫將機密資訊存放在 .env 檔案中,避免直接寫在程式碼裡。
  • openai,用來與 OpenAI API 互動的函式庫。
  • pillow,用於在 Python 中處理影像。
  • requests,協助發送 HTTP 請求。
  1. 建立一個 .env 檔案,內容如下:

    AZURE_OPENAI_ENDPOINT=<your endpoint>
    AZURE_OPENAI_API_KEY=<your key>
    

    你可以在 Azure 入口網站的「金鑰與端點」區段找到這些資訊。

  2. 將上述函式庫列在 requirements.txt 檔案中,如下:

    python-dotenv
    openai
    pillow
    requests
    
  3. 接著,建立虛擬環境並安裝函式庫:

    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt

    Windows 使用者可用以下指令建立並啟動虛擬環境:

    python3 -m venv venv
    venv\Scripts\activate.bat
  4. app.py 檔案中加入以下程式碼:

    import openai
    import os
    import requests
    from PIL import Image
    import dotenv
    
    # import dotenv
    dotenv.load_dotenv()
    
    # Get endpoint and key from environment variables
    openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT']
    openai.api_key = os.environ['AZURE_OPENAI_API_KEY']
    
    # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only)
    openai.api_version = '2023-06-01-preview'
    openai.api_type = 'azure'
    
    
    try:
        # Create an image by using the image generation API
        generation_response = openai.Image.create(
            prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',    # Enter your prompt text here
            size='1024x1024',
            n=2,
            temperature=0,
        )
        # Set the directory for the stored image
        image_dir = os.path.join(os.curdir, 'images')
    
        # If the directory doesn't 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.InvalidRequestError as err:
        print(err)

讓我們來解釋這段程式碼:

  • 首先,我們匯入所需的函式庫,包括 OpenAI、dotenv、requests 和 Pillow。

    import openai
    import os
    import requests
    from PIL import Image
    import dotenv
  • 接著,我們從 .env 檔案載入環境變數。

    # import dotenv
    dotenv.load_dotenv()
  • 然後,設定 OpenAI API 的端點、金鑰、版本與類型。

    # Get endpoint and key from environment variables
    openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT']
    openai.api_key = os.environ['AZURE_OPENAI_API_KEY']
    
    # add version and type, Azure specific
    openai.api_version = '2023-06-01-preview'
    openai.api_type = 'azure'
  • 接著,我們生成影像:

    # Create an image by using the image generation API
    generation_response = openai.Image.create(
        prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',    # Enter your prompt text here
        size='1024x1024',
        n=2,
        temperature=0,
    )

    上述程式碼會回傳一個 JSON 物件,內含生成影像的 URL。我們可以利用該 URL 下載影像並儲存成檔案。

  • 最後,我們開啟影像並使用標準影像檢視器顯示它:

    image = Image.open(image_path)
    image.show()

生成影像的詳細說明

讓我們更詳細地看生成影像的程式碼:

generation_response = openai.Image.create(
        prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',    # Enter your prompt text here
        size='1024x1024',
        n=2,
        temperature=0,
    )
  • prompt 是用來生成影像的文字提示。這裡使用的提示是「兔子騎馬,手持棒棒糖,站在長滿水仙花的霧氣草地上」。
  • size 是生成影像的尺寸,這裡是 1024x1024 像素。
  • n 是生成影像的數量,這裡是兩張。
  • temperature 是控制生成式 AI 輸出隨機性的參數,介於 0 到 1 之間,0 表示輸出完全確定,1 表示完全隨機,預設值為 0.7。

接下來我們會介紹更多影像相關的功能。

影像生成的額外功能

到目前為止,你已經看到如何用幾行 Python 程式碼生成影像。但影像還能做更多事。

你還可以:

  • 進行編輯。透過提供現有影像、遮罩和提示語,你可以修改影像。例如,你可以在影像的某個區域加上東西。想像我們的兔子影像,你可以幫兔子戴上帽子。做法是提供影像、遮罩(標示要修改的區域)和文字提示說明要做什麼。

    response = openai.Image.create_edit(
      image=open("base_image.png", "rb"),
      mask=open("mask.png", "rb"),
      prompt="An image of a rabbit with a hat on its head.",
      n=1,
      size="1024x1024"
    )
    image_url = response['data'][0]['url']

    原始影像只有兔子,最終影像則是兔子戴上帽子。

  • 創造變體。你可以拿現有影像,要求生成變體。要創造變體,你提供影像和文字提示,並用如下程式碼:

    response = openai.Image.create_variation(
      image=open("bunny-lollipop.png", "rb"),
      n=1,
      size="1024x1024"
    )
    image_url = response['data'][0]['url']

    注意,這功能僅在 OpenAI 支援。

溫度參數

溫度是控制生成式 AI 輸出隨機性的參數,介於 0 到 1 之間,0 表示輸出確定,1 表示輸出隨機,預設為 0.7。

讓我們透過執行同一個提示兩次來看看溫度的影響:

提示語:「兔子騎馬,手持棒棒糖,站在長滿水仙花的霧氣草地上」

Bunny on a horse holding a lollipop, version 1

現在再執行一次相同提示,看看是否會得到相同影像:

Generated image of bunny on horse

如你所見,兩張影像相似但不完全相同。接著,我們將溫度調整為 0.1,看看會發生什麼:

 generation_response = openai.Image.create(
        prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',    # Enter your prompt text here
        size='1024x1024',
        n=2
    )

調整溫度

我們試著讓輸出更確定。從前面兩張影像可見,第一張有兔子,第二張有馬,差異很大。

因此,我們將程式碼中的溫度設為 0,如下:

generation_response = openai.Image.create(
        prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',    # Enter your prompt text here
        size='1024x1024',
        n=2,
        temperature=0
    )

執行後會得到以下兩張影像:

  • Temperature 0, v1
  • Temperature 0 , v2

你可以明顯看到兩張影像更為相似。

如何用元提示為應用程式設定界限

透過我們的示範,已能為客戶生成影像,但我們需要為應用程式設定一些界限。

例如,我們不希望生成不適合工作場合或兒童觀看的影像。

這時可以使用 元提示(metaprompts)。元提示是用來控制生成式 AI 輸出的文字提示。例如,我們可以用元提示確保生成的影像適合工作場合或兒童觀看。

元提示如何運作?

元提示是放在主要提示語之前的文字提示,用來控制模型輸出,並嵌入應用程式中以管理生成結果。它將提示輸入和元提示合併成一個完整的文字提示。

一個元提示範例如下:

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 = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult"

meta_prompt =f"""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.
{disallow_list}
"""

prompt = f"{meta_prompt}
Create an image of a bunny on a horse, holding a lollipop"

# TODO add request to generate image

從上述提示可見,所有生成的影像都會考慮元提示的限制。

作業 - 讓學生開始動手

我們在課程一開始介紹了 Edu4All,現在是時候讓學生為他們的評量生成影像。

學生將為評量創作包含紀念碑的影像,紀念碑的選擇由學生決定。學生被鼓勵發揮創意,將這些紀念碑置於不同情境中。

解答

以下是一個可能的解答:

import openai
import os
import requests
from PIL import Image
import dotenv

# import dotenv
dotenv.load_dotenv()

# Get endpoint and key from environment variables
openai.api_base = "<replace with endpoint>"
openai.api_key = "<replace with api key>"

# Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only)
openai.api_version = '2023-06-01-preview'
openai.api_type = 'azure'

disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult"

meta_prompt = f"""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.
{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 = openai.Image.create(
        prompt=prompt,    # Enter your prompt text here
        size='1024x1024',
        n=2,
        temperature=0,
    )
    # Set the directory for the stored image
    image_dir = os.path.join(os.curdir, 'images')

    # If the directory doesn't 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.InvalidRequestError as err:
    print(err)

做得好!繼續學習

完成本課程後,歡迎參考我們的生成式 AI 學習資源集,持續提升你的生成式 AI 知識!

接著前往第 10 課,我們將探討如何使用低程式碼建立 AI 應用程式

免責聲明
本文件係使用 AI 翻譯服務 Co-op Translator 進行翻譯。雖然我們致力於確保翻譯的準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應視為權威來源。對於重要資訊,建議採用專業人工翻譯。我們不對因使用本翻譯而產生的任何誤解或誤釋負責。