建構網站:使用 Gemini 模型將想像力轉化為網站!

1. 簡介

在網頁開發的領域中,將設計概念轉換成功能性網站的程序可能相當耗時又複雜。不過,隨著 Gemini 等生成式 AI 模型問世,這項程序將變得更簡單且易於存取。我們會打造解決方案,將手繪線框轉換成網站程式碼。這個強大的工具能協助設計人員和開發人員以前所未有的效率,實現網站願景。

在本研究室中,我們將建構網頁應用程式,讓使用者透過線框和提示,讓使用者透過 Vertex AI 的生成式 AI 模型 (Gemini 1.5 Flash、Gemini 1.5 Pro 等) 輸入網站程式碼 (HTML、css 和 JavaScript)。這個應用程式會使用熱門的 Python 網路架構 Flask 建構,並透過 Vertex AI 用戶端程式庫與生成式模型服務互動。

建構項目

完成這個研究室後,您將擁有可正常運作的網頁應用程式,應用程式可透過線框和提示產生圖片。也能更瞭解如何使用 Vertex AI 的生成式 AI 模型。

您的網頁應用程式將如下所示:

5bccb261882c1bf0.png

應用程式流程

  1. 上傳手繪線框圖:使用者可以將手繪線框的圖片上傳到應用程式。
  2. 選取模型:應用程式提供多種預先訓練的 Gemini 模型,已針對不同設計風格進行最佳化。
  3. 提供提示:使用者可選擇提供文字提示,引導模型生成。
  4. 產生網站程式碼:應用程式將版面配置和提示傳送至 Gemini,以便產生相應的網站程式碼。
  5. 顯示結果:產生的程式碼會顯示在應用程式的回應頁面中。

我們會先討論版面配置和提示的基本概念,以及如何運用這些內容產生網站程式碼。接著,我們會逐步說明建立網頁應用程式的步驟,包括如何處理使用者輸入內容、產生回應,以及顯示結果。

2. 事前準備

  1. Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案
  2. 確認 Google Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用帳單功能
  3. 您將使用 Cloud Shell,這是在 Google Cloud 中執行的指令列環境。如要使用這個叢集,請按一下 Google Cloud 控制台頂端的「啟用 Cloud Shell」。

1829c3759227c19b.png

  1. 連線至 Cloud Shell 後,請使用下列指令來檢查是否已通過驗證,以及專案是否已設為專案 ID:
gcloud auth list
  1. 在 Cloud Shell 中執行下列指令,確認 gcloud 指令知道您的專案。
gcloud config list project
  1. 如果尚未設定專案,請使用下列指令進行設定:
gcloud config set project <YOUR_PROJECT_ID>
  1. 請確認您已啟用下列 API:
  • Cloud Run
  • Vertex AI

使用 gcloud 指令的替代方法,是透過這個連結透過主控台。如要瞭解 gcloud 指令和使用方式,請參閱說明文件

3. 步驟 1:啟動 Python Cloud Run 網頁應用程式

我們會先透過 Cloud Shell 建立 Python Cloud Run 網頁應用程式範本。

前往 Cloud Shell 終端機,然後按一下「開啟編輯器」按鈕。b16d56e4979ec951.png

確認 Cloud Code 專案是在 Cloud Shell 編輯器的左下角 (狀態列),如下圖中醒目顯示,且已設為您已啟用帳單的有效 Google Cloud 專案。如果出現提示訊息,請授權

f5003b9c38b43262.png

按一下狀態列中的當前專案,然後等待 Cloud Code 彈出。在彈出式視窗中選取「New Application」。70f80078e01a02d8.png

在應用程式清單中,選擇「Cloud Run Application」

39abad102a72ae74.png

針對第 2/2 頁,選取 Python Flask 範本:

a78b3a0311403ad.png

視需要提供專案名稱 (例如「amazing-gemini-app」),然後按一下「確定」

4d8f77279d9509cb.png

系統隨即會開啟您剛才設定的新專案範本。

e85a020a20d38e17.png

使用 Google Cloud Shell 啟動網頁應用程式就是這麼簡單。

4. 步驟 2:建構前端

為此,我們需要 HTML 網頁。該頁面所含的程式碼定義了網頁應用程式的使用者介面。其中包含表單,可讓使用者上傳手繪線框圖片、選取生成式模型,以及提供文字提示。提交表單後,結果會顯示在另一個分頁中。

複製下方程式碼,並取代 templates 資料夾中的 index.html 檔案:

<!DOCTYPE html>
<html>
<head>
   <title>Draw a Website</title>
   <style>
       body {
           font-family: sans-serif;
           display: flex;
           justify-content: center;
           align-items: center;
           min-height: 100vh; /* Ensure form is centered vertically */
           background-color: #f4f4f4;
       }
       .container {
           background-color: white;
           padding: 30px;
           border-radius: 8px;
           box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
           text-align: center;
       }
       h2 {
           text-align: center;
           margin-bottom: 20px;
       }
       input[type="file"], textarea, select {
           width: 100%;
           padding:10px;
           margin-bottom: 15px;
           border: 1px solid #ccc;
           border-radius: 4px;
           box-sizing: border-box;
       }
       button {
           background-color: #4CAF50;
           color: white;
           padding: 12px 20px;
           border: none;
           border-radius: 4px;
           cursor: pointer;
       }
   </style>
</head>
<body>
   <div class="container">
       <h2>Draw a Website</h2>
       <form action="/response" target="_blank" method="post" enctype="multipart/form-data">
           <input type="file" id="image-upload" name="image-upload" accept=".png, .jpg, .jpeg">
           <select name="model">
               <option value="gemini-1.5-flash-001">Gemini 1.5 Flash</option>
               <option value="gemini-1.5-pro-001">Gemini 1.5 Pro</option>
               <option value="gemini-1.0-pro-vision-001">Gemini 1.0 Pro Vision</option>
               </select>
           <textarea name="prompt" placeholder="Write your prompt here. For example: 'Convert this drawing into an html page'">Convert this drawing into an html page</textarea>
           <button type="submit">Submit</button>
       </form>
   </div>
</body>
</html>

使用者與應用程式互動時,會發生以下動作:

  1. 使用者選取版面配置圖片、選取模型並輸入提示。
  2. 當使用者按一下「提交」按鈕時,系統會使用 HTTP POST 方法將表單資料 (圖片、模型和提示) 傳送至 /response 網址。
  3. 伺服器端程式碼 (在 app.py 中實作) 會處理表單資料,並使用指定的模型和提示產生回應。
  4. 產生的回應會顯示在新分頁中。

我們現已準備好網頁應用程式的前端。

5. 步驟 3:建構後端 (生成式 AI)

我們來編寫這個網頁應用程式的主要部分。app.py 檔案,該檔案會擷取使用者輸入圖片、所選模型和提示,並轉換為網站程式碼。

複製 app.py 的完整程式碼:

# Import the necessary libraries.
import os
import random
from flask import (
    Flask,
    render_template,
    request,
    redirect
)

import vertexai
from vertexai.generative_models import (
    GenerativeModel,
    Image
)

# Initialize the Flask app.
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB per image

# TODO: Replace "YOUR_PROJECT_ID" before running
# Initialize the Vertex AI client library.
vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")

# Define a function to generate response from a wireframe and a prompt.
def generate(wireframe, model, prompt):
    '''Generates a response from a wireframe and a prompt.
    Args:
    wireframe: The wireframe image.
    model: The generative model to use.
    prompt: The prompt to use.
    Returns:The generated response.
    '''
    # Create a GenerativeModel object.
    model = GenerativeModel(model)

    # Create a list of contents to pass to the model.
    contents = [
        wireframe,
        prompt
    ]
   
    # Generate the response.
    responses = model.generate_content(
        contents=contents,
        stream=True,
    )

    # Concatenate the response text.
    response = ""
    for res in responses:
        response += res.text.strip()
   
    # Return the generated response.
    return response

# Define the home page route.
@app.route('/', methods=['GET'])
def index():
    '''Renders the home page.
    Returns:The rendered template.
    '''
    return render_template('index.html')

# Define the response route.
@app.route('/response', methods=['GET', 'POST'])
def response():
    '''Handles the response to the user's input.
    Returns:The rendered template.
    '''
    # If the request is a POST request, process the form data.
    if request.method == 'POST':
        # Get the uploaded image from the request.
        uploaded_image = request.files['image-upload']
       
        # Convert the uploaded image to a wireframe image.
        wireframe = Image.from_bytes(uploaded_image.read())

        # Get the model and prompt from the request.
        model = request.form['model']
        prompt = request.form['prompt']
       
        # Generate the response and render the response.
        try:
            response = generate(wireframe, model, prompt)
            response = response.replace("```html", "").replace("```", "").strip()
            return response
        except ValueError as e:
            raise e
   
    # If the request is a GET request, redirect to the home page.
    else:
        return redirect('/')

# Run the app.
if __name__ == '__main__':
    # Get the server port from the environment variables.
    server_port = os.environ.get('PORT', '8080')

    # Run the app.
    app.run(debug=False, port=server_port, host='0.0.0.0')

以下為程式碼的用途:

  1. 這個程式碼會為應用程式匯入必要的程式庫:

Flask:適用於 Python 的輕量級網路架構。

os:用於與作業系統互動。

隨機:用於產生隨機數字。

vertexai:Vertex AI 用戶端程式庫

GenerativeModel 和 Image:Vertex AI 生成式模型程式庫中的類別。

  1. 初始化 flask 應用程式:

接著,它會初始化 Flask 應用程式,並將上傳圖片的大小上限設為 16 MB。

  1. 初始化 Vertex AI 用戶端

並使用指定的專案 ID 和位置初始化 Vertex AI 用戶端程式庫。請務必將 YOUR_PROJECT_ID 換成您的專案 ID。

  1. 定義產生的函式

這個函式會使用版面配置圖片、生成式模型和提示做為輸入內容。然後使用指定的模型和提示產生網站 HTML。產生的回應會以字串的形式傳回。

  1. 定義首頁路徑

這個函式會定義首頁路徑。當使用者造訪應用程式的根網址時,系統就會呼叫此函式。這會呈現 index.html 範本,也就是應用程式的首頁。

  1. 定義回應路徑

這個函式會定義回應路徑。當使用者在首頁提交表單時,系統會呼叫此函式。這個 API 會處理上傳的圖片、模型和提示,然後產生網站程式碼。產生的回應會顯示在新分頁中。

  1. 執行應用程式

這部分的程式碼會檢查指令碼是否做為主要程式執行。如果是的話,它會從環境變數取得伺服器通訊埠,並在指定的通訊埠執行應用程式。

6. 步驟 4:準備依附元件和 Dockerfile

請確認 requirements.txt 檔案含有下列依附元件:

Flask==2.3.3
requests==2.31.0
debugpy # Required for debugging.
google-cloud-aiplatform>=1.38

請將 Dockerfile 內容換成以下內容:

# Python image to use.
FROM python:3.11-slim

# Set the working directory to /app
WORKDIR /app

# copy the requirements file used for dependencies
COPY requirements.txt .

# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt

# Copy the rest of the working directory contents into the container at /app
COPY . .

# Run app.py when the container launches
ENTRYPOINT ["python", "app.py"]

7. 步驟 5:部署網頁應用程式

建立應用程式元件後,接著就來部署應用程式。

前往 Cloud Shell 終端機,並確認目前專案已設為使用中的專案。如果您沒有使用 gcloud setup 指令設定專案 ID,請按照下列步驟操作:

gcloud config set project [PROJECT_ID]

然後依序輸入下列指令:

cd draw-a-website
gcloud run deploy --source .

系統會提示您輸入服務名稱,例如「draw-website」。選擇區域「us-central1」的對應數字。在系統詢問您是否要允許未經驗證的叫用時,說出「y」。請注意,我們允許未經驗證的存取,因為這是試用版應用程式。建議您為企業和生產應用程式採用適當的驗證機制。

部署作業完成後,您應該會收到類似下方的連結:

**https://draw-website-*****eua-uc.a.run.app/

繼續測試應用程式:

6ca7b67b7fce97de.png

8. 清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取這個程式碼研究室所用資源的費用,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,前往「管理資源」頁面。
  2. 在專案清單中選取要刪除的專案,然後按一下「Delete」(刪除)
  3. 在對話方塊中輸入專案 ID,然後按一下「Shut down」(關閉) 即可刪除專案。
  4. 您也可以前往控制台的「Cloud Run」,選取您剛部署及刪除的服務。

9. 恭喜

恭喜!您已成功使用 Python Flask 在 Cloud Run 上建構快速網頁應用程式,這個應用程式可將繪圖轉換成網站。如需完整的存放區,請按這裡。繪圖式網站應用程式展現了 Gemini 強大的創新功能,可簡化網站開發流程。只要使用 AI 技術,我們就能協助設計人員和開發人員更迅速、精準且有效地建立網站。生成式 AI 模型不斷演進,未來我們預期將有更多創新的應用程式。