建構 Gemini 技術輔助的 YouTube 摘要工具

1. 簡介

在現今快速變化的數位世界中,時間是珍貴的資源。YouTube 是龐大的資訊寶庫,但長篇影片可能會耗費大量時間。這時 YouTube 摘要就派上用場。這些工具可將長篇影片濃縮為精簡摘要,讓使用者不必觀看整部影片,也能快速掌握核心內容。這項功能特別適合學生、專業人士,以及想從線上影片內容中有效擷取重要資訊的使用者。基本上,YouTube 摘要工具可讓使用者盡可能吸收學習內容和資訊,同時減少浪費的時間。

完成本研究室後,您將擁有可從 YouTube 影片產生摘要的網頁應用程式。您也會更瞭解如何使用 Gemini API、Google Gen AI SDK,並將這兩者整合,以建構網路應用程式。

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

13a0825947f9892b.png

只要提供 YouTube 影片連結,Gemini 就會負責處理其他事宜。

2. 事前準備

本程式碼研究室假設您已擁有已啟用計費功能的 Google Cloud 專案。如果您尚未安裝,請按照下方說明操作。

  1. Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案
  2. 請確認 Google Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用計費功能
  3. 您將使用 Cloud Shell,這是在 Google Cloud 中執行的指令列環境。如要存取 Cloud Shell,請按一下 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 指令和用法,請參閱說明文件

必要條件

課程內容

  • 如何使用 Flask API 程式庫建立 Gemini 技術輔助的後端 API
  • 如何建構 GenAI 應用程式,將前端和後端連結在一起
  • 如何在 Cloud Run 上部署開發的生成式 AI 應用程式

軟硬體需求

  • 可正常運作的電腦和穩定的 Wi-Fi 網路
  • 好奇心

3. 在 Cloud Run 上建立 Python Flask 應用程式

我們會先使用 Cloud Shell 自動產生的範本,在 Cloud Run 上建立 Python Flask 應用程式。

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

請確認 Cloud Code 專案已設在 Cloud Shell 編輯器的左下角 (狀態列),如下圖所示,並設為已啟用計費功能的有效 Google Cloud 專案。如果出現提示訊息,請點選「授權」

f5003b9c38b43262.png

按一下狀態列中的該個正在執行的專案,然後等候 Cloud Code 彈出式視窗開啟。在彈出式視窗中,選取「新應用程式」。70f80078e01a02d8.png

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

39abad102a72ae74.png

在第 2/2 頁中,選取 Python Flask 範本:

a78b3a0311403ad.png

輸入專案名稱 (例如「amazing-gemini-app」),然後按一下「OK」

4d8f77279d9509cb.png

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

e85a020a20d38e17.png

在 Cloud Run 上使用 Google Cloud Shell 建立 Python Flask 應用程式,就是這麼簡單。

4. 建構前端

如先前所述,最終網頁應用程式會如下所示:

13a0825947f9892b.png

這項內容包含輸入欄位 (可讓使用者輸入 YouTube 連結)、可選擇其他模型群組的選項、可視需要提供額外提示的文字方塊,以及可提交表單的按鈕。

如果您喜歡這項挑戰,歡迎自行設計表單或編輯 CSS 屬性。您也可以複製下方的程式碼,並用該程式碼取代 templates 資料夾中 index.html 檔案的內容。

<!DOCTYPE html>
<html>
 <head>
   <title>YouTube Summarizer</title>
   <style>
     body {
       font-family: sans-serif;
       display: flex;
       justify-content: center;
       align-items: center;
       min-height: 100vh;
       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="text"], 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>YouTube Summarizer</h2>
     <form action="/summarize" target="_blank" method="post">
       <input type="text" name="youtube_link" placeholder="Enter YouTube Link">
       <select name="model">
         <option value="gemini-2.0-flash-001">Gemini 2.0 Flash</option>
       </select>
       <textarea name="additional_prompt" placeholder="Write your additional prompt here. For example: 'explain to me like I am five years old'"></textarea>
       <button type="submit">Summarize</button>
     </form>
   </div>
 </body>
</html>

如要測試是否正確完成這個步驟,請在 app.py 上按一下滑鼠右鍵,然後選擇「在終端機中執行 Python 檔案」

690765473f94db9c.png

如果一切順利,您應該可以透過 http://127.0.0.1:8080 存取網路應用程式。

5. 建構後端

設定完前端之後,您需要建立後端服務,利用 Gemini 模型摘要使用者提供的 YouTube 影片。請注意,您將覆寫 app.py 來完成此任務。

在變更程式碼前,您必須建立虛擬環境,並安裝必要的程式庫來執行 Gemini 元件。

首先,您必須將 Google Gen AI SDK 程式庫新增至 requirements.txt 檔案。應該會如下所示:

Flask==2.3.3
requests==2.31.0
debugpy # Required for debugging.
google-genai==1.2.0

其次,您需要建立虛擬環境,並從 requirements.txt 安裝套件,才能順利執行後端程式碼。

  1. 按一下左上角的橫條,然後選擇「Terminal」>「New Terminal」

2cda225f0cd71e7e.png 2. 在終端機中輸入指令建立虛擬環境,然後等待安裝作業完成

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

再次提醒您,歡迎挑戰自己,自行使用 Flask API 建立 Gemini 端點。您的程式碼應如下所示。

import os

from flask import Flask, render_template, request
from google import genai
from google.genai import types

app = Flask(__name__)

PROJECT_ID = "REPLACE_WITH_YOUR_PROJECT_ID"

client = genai.Client(
   vertexai=True,
   project=PROJECT_ID,
   location="us-central1",
)

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


def generate(youtube_link, model, additional_prompt):

   # Prepare youtube video using the provided link
   youtube_video = types.Part.from_uri(
       file_uri=youtube_link,
       mime_type="video/*",
   )

   # If addtional prompt is not provided, just append a space
   if not additional_prompt:
       additional_prompt = " "

   # Prepare content to send to the model
   contents = [
       youtube_video,
       types.Part.from_text(text="""Provide a summary of the video."""),
       additional_prompt,
   ]

   # Define content configuration
   generate_content_config = types.GenerateContentConfig(
       temperature = 1,
       top_p = 0.95,
       max_output_tokens = 8192,
       response_modalities = ["TEXT"],
   )

   return client.models.generate_content(
       model = model,
       contents = contents,
       config = generate_content_config,
   ).text

@app.route('/summarize', methods=['GET', 'POST'])
def summarize():
   '''
   Summarize the user provided YouTube video.
   Returns: Summary.
   '''

   # If the request is a POST request, process the form data.
   if request.method == 'POST':
       youtube_link = request.form['youtube_link']
       model = request.form['model']
       additional_prompt = request.form['additional_prompt']
     
       # Generate the summary.
       try:
           summary = generate(youtube_link, model, additional_prompt)
           return summary

       except ValueError as e:
           raise e
 
   # If the request is a GET request, redirect to the home page.
   else:
       return redirect('/')


if __name__ == '__main__':
   server_port = os.environ.get('PORT', '8080')
   app.run(debug=False, port=server_port, host='0.0.0.0')

這個程式碼會執行以下操作:

匯入必要程式庫:

  • Flask:用於建立網頁應用程式。
  • os:用於存取環境變數。
  • google.genai:用於與 Google 的 Gemini AI 互動。
  • google.genai.types:用於定義 Gemini 的資料結構。

初始化 Gemini 用戶端:

  • 它會設定連至 Google Vertex AI 的連線,讓應用程式能夠使用 Gemini AI 模型。請務必將「REPLACE_WITH_YOUR_PROJECT_ID」替換為您的專案 ID。

定義產生函式:

  • 這個函式會將 YouTube 影片連結、Gemini 模型 ID 和額外提示做為輸入內容。接著,系統會將影片和提示傳送至 Gemini,並傳回產生的摘要文字。

定義首頁路徑 (/):

  • 這個函式會轉譯 index.html 範本,並顯示表單,讓使用者輸入 YouTube 連結。

定義摘要路徑 (/summarize):

  • 這個函式會處理表單提交作業。它會從表單中擷取 YouTube 連結、模型和提示,呼叫產生函式以取得摘要,然後在 result.html 範本中顯示摘要。

執行應用程式:

  • 它會從環境變數擷取伺服器連接埠,並啟動 Flask 網路伺服器。

您可以透過在終端機中執行 app.py 來測試程式碼。與測試前端相同的方法。在 app.py 上按一下滑鼠右鍵,然後選擇「Run Python File in Terminal」

請繼續測試應用程式。應該會正常運作。

6. 部署網頁應用程式

您現在已擁有可運作的 GenAI 應用程式,請將應用程式部署至 Cloud Run,以便與朋友和同事分享試用。

前往 Cloud Shell 終端機,確認目前的專案已設為有效的專案,如果沒有,請使用 gcloud configure 指令設定專案 ID:

gcloud config set project [PROJECT_ID]

請務必將 [PROJECT_ID] 替換為您自己的專案 ID。然後依序輸入下列指令:

cd amazing-gemini-app
gcloud run deploy --source .

系統會提示您輸入服務名稱,例如「youtube-summarizer」。為「us-central1」地區選擇相對應的編號。系統詢問是否要允許未經驗證的叫用時,請說「y」。請注意,由於這是示範應用程式,因此我們允許未經驗證的存取權。建議您為企業和正式版應用程式使用適當的驗證機制。

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

https://amazing-gemini-app-*******.a.run.app/

請在 Inconito 視窗或行動裝置上使用應用程式。應該已經上線了。

7. 挑戰

大展身手的機會來了。你是否有變更程式碼的必要,才能直接從電腦上傳影片?

8. 清理

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

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