arrow_back

Vertex AI Gemini 1.0 Pro を活用してアプリを開発する

ログイン 参加
知識をテストして、コミュニティで共有しましょう
done
700 を超えるハンズオンラボ、スキルバッジ、コースへのアクセス

Vertex AI Gemini 1.0 Pro を活用してアプリを開発する

ラボ 1時間 30分 universal_currency_alt クレジット: 1 show_chart 入門
info このラボでは、学習をサポートする AI ツールが組み込まれている場合があります。
知識をテストして、コミュニティで共有しましょう
done
700 を超えるハンズオンラボ、スキルバッジ、コースへのアクセス

概要

Gemini は、マルチモーダル ユースケース向けに設計された生成 AI モデルのファミリーで、Ultra、Pro、Nano の 3 つのサイズがあります。Gemini 1.0 Pro は、デベロッパーや企業が独自のユースケースに対応する場合に利用できます。Gemini 1.0 Pro は入力としてテキストを受け入れ、出力としてテキストを生成します。入力としてテキストと画像を受け入れ、出力としてテキストを生成する専用の Gemini 1.0 Pro Vision マルチモーダル エンドポイントもあります。Python、Android(Kotlin)、Node.js、Swift、JavaScript でアプリを構築するために利用できる SDK も用意されています。

Google Cloud の Vertex AI Gemini API は、Gemini モデルを操作するための統合インターフェースを提供します。この API は、入力としてマルチモーダル プロンプトをサポートし、テキストまたはコードを出力します。現在、Gemini API では次の 2 つのモデルを利用できます。

  • Gemini 1.0 Pro モデル(gemini-pro): 自然言語タスク、マルチターン テキストとコードチャット、コード生成を処理するように設計されています。

  • Gemini 1.0 Pro Vision モデル(gemini-pro-vision): マルチモーダル プロンプトをサポートします。プロンプト リクエストにテキスト、画像、動画を含めて、テキストまたはコードのレスポンスを取得できます。

Vertex AI は、ML モデルと AI アプリケーションのトレーニングとデプロイを行い、AI を活用したアプリケーションで使用する大規模言語モデル(LLM)をカスタマイズできる ML プラットフォームです。Vertex AI を使用すれば、データを完全に管理しながら Gemini をカスタマイズできるだけでなく、Google Cloud のその他の機能も利用して、エンタープライズ セキュリティ、安全性、プライバシー、データ ガバナンス、コンプライアンスを確保できます。Vertex AI の詳細については、このラボの最後にある「次のステップ」に記載されているリンクをご覧ください。

このラボでは、Vertex AI SDK for Python を使用して Vertex AI Gemini API を呼び出します。

目標

このラボでは、次のタスクについて学びます。

  • Streamlit フレームワークを使用して Python アプリを開発する
  • Vertex AI SDK for Python をインストールする
  • Vertex AI Gemini API を使用して Gemini 1.0 Pro モデル(gemini-pro)を操作するためのコードを開発する
  • Vertex AI Gemini API を使用して Gemini 1.0 Pro Vision モデル(gemini-pro-vision)を操作するためのコードを開発する
  • アプリケーションをコンテナ化し、Cloud Run にデプロイしてテストする

設定

各ラボでは、新しい Google Cloud プロジェクトとリソースセットを一定時間無料で利用できます。

  1. Qwiklabs にシークレット ウィンドウでログインします。

  2. ラボのアクセス時間(例: 1:15:00)に注意し、時間内に完了できるようにしてください。
    一時停止機能はありません。必要な場合はやり直せますが、最初からになります。

  3. 準備ができたら、[ラボを開始] をクリックします。

  4. ラボの認証情報(ユーザー名パスワード)をメモしておきます。この情報は、Google Cloud Console にログインする際に使用します。

  5. [Google Console を開く] をクリックします。

  6. [別のアカウントを使用] をクリックし、このラボの認証情報をコピーしてプロンプトに貼り付けます。
    他の認証情報を使用すると、エラーが発生したり、料金の請求が発生したりします。

  7. 利用規約に同意し、再設定用のリソースページをスキップします。

Cloud Shell をアクティブにする

Cloud Shell は、開発ツールが組み込まれた仮想マシンです。5 GB の永続ホーム ディレクトリを提供し、Google Cloud 上で実行されます。Cloud Shell を使用すると、コマンドラインで Google Cloud リソースにアクセスできます。gcloud は Google Cloud のコマンドライン ツールで、Cloud Shell にプリインストールされており、Tab キーによる入力補完がサポートされています。

  1. Google Cloud Console のナビゲーション パネルで、「Cloud Shell をアクティブにする」アイコン(Cloud Shell アイコン)をクリックします。

  2. [次へ] をクリックします。
    環境がプロビジョニングされ、接続されるまでしばらく待ちます。接続の際に認証も行われ、プロジェクトは現在のプロジェクト ID に設定されます。次に例を示します。

Cloud Shell ターミナル

サンプル コマンド

  • 有効なアカウント名前を一覧表示する:

gcloud auth list

(出力)

Credentialed accounts: - <myaccount>@<mydomain>.com (active)

(出力例)

Credentialed accounts: - google1623327_student@qwiklabs.net
  • プロジェクト ID を一覧表示する:

gcloud config list project

(出力)

[core] project = <プロジェクト ID>

(出力例)

[core] project = qwiklabs-gcp-44776a13dea667a6

タスク 1. 環境とプロジェクトを構成する

  1. ラボの認証情報を使用して Google Cloud コンソールにログインし、Cloud Shell ターミナル ウィンドウを開きます。

  2. Cloud Shell で次のコマンドを実行して、プロジェクト ID とリージョンの環境変数を設定します。

    PROJECT_ID=$(gcloud config get-value project) REGION={{{project_0.default_region|set at lab start}}} echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  3. このラボでさまざまな Google Cloud サービスを利用できるように、いくつかの API を有効にする必要があります。

    gcloud services enable cloudbuild.googleapis.com cloudfunctions.googleapis.com run.googleapis.com logging.googleapis.com storage-component.googleapis.com aiplatform.googleapis.com

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 関連する API を有効にする

タスク 2. アプリケーションの環境を設定する

このタスクでは、Python 仮想環境を設定してアプリケーションの依存関係をインストールします。

Cloud Shell が承認済みであることを確認する

  1. Cloud Shell で次のコマンドを実行して、Cloud Shell が承認済みであることを確認します。

    gcloud auth list
  2. Cloud Shell を承認するように求められたら、[承認] をクリックします。

アプリのディレクトリを作成する

  1. 次のコマンドを実行して、アプリのディレクトリを作成します。

    mkdir ~/gemini-app
  2. 現在のディレクトリを ~/gemini-app ディレクトリに変更します。

    cd ~/gemini-app

    アプリケーションのファイルは ~/gemini-app ディレクトリ内に作成されます。このディレクトリには、このラボで後ほど使用する Python アプリケーションのソースファイル、依存関係、Dockerfile が格納されます。

Python 仮想環境を設定する

既存の Python インストール環境を基盤に仮想環境を作成して、この仮想環境にインストールされたすべてのパッケージがベース環境内のパッケージから分離されるようにします。仮想環境内で pip などのインストール ツールを使用すると、Python パッケージが仮想環境にインストールされます。

  1. gemini-app フォルダ内で次のコマンドを実行して、Python 仮想環境を作成します。

    python3 -m venv gemini-streamlit venv モジュールは、このモジュール固有の独立した Python パッケージ一式を使用して、軽量の仮想環境を作成します。
  2. Python 仮想環境を有効にします。

    source gemini-streamlit/bin/activate

アプリケーションの依存関係をインストールする

Python の要件ファイルは、プロジェクトに必要な依存関係のリストを含むシンプルなテキスト ファイルです。まず、この例の要件ファイルに含める必要があるモジュールは 3 つあります。

このアプリは Streamlit を使用して作成します。Streamlit はオープンソースの Python ライブラリで、ML やデータ サイエンス向けの Web アプリを作成するために使用されます。このアプリでは、Gemini API とモデルを操作するために Vertex AI SDK for Python ライブラリも使用します。アプリケーションからの情報は、Cloud Logging を使用してログに記録します。

  1. 次のコマンドを実行して、要件ファイルを作成します。

    cat > ~/gemini-app/requirements.txt <<EOF streamlit google-cloud-aiplatform==1.38.1 google-cloud-logging==3.6.0 EOF
  2. アプリケーションの依存関係をインストールします。

    pip install -r requirements.txt

    pip は Python 用のパッケージ インストーラです。

    すべてのパッケージがインストールされるのを待ってから、次のタスクに進みます。

タスク 3. アプリを開発する

アプリのソースコードは複数の .py ソースファイルに記述します。まずは、app.py にメイン エントリ ポイントを記述しましょう。

アプリのメイン エントリ ポイントを記述する

  1. 次のコマンドを実行して、app.py エントリ ポイントコードを作成します。

    cat > ~/gemini-app/app.py <<EOF import os import streamlit as st from app_tab1 import render_story_tab from vertexai.preview.generative_models import GenerativeModel import vertexai import logging from google.cloud import logging as cloud_logging # ロギングを構成する logging.basicConfig(level=logging.INFO) # Cloud Logging ハンドラをルートロガーにアタッチする log_client = cloud_logging.Client() log_client.setup_logging() PROJECT_ID = os.environ.get('PROJECT_ID') # Qwiklabs での実際の Google Cloud プロジェクト ID LOCATION = os.environ.get('REGION') # Qwiklabs での実際の Google Cloud プロジェクトのリージョン vertexai.init(project=PROJECT_ID, location=LOCATION) @st.cache_resource def load_models(): text_model_pro = GenerativeModel("gemini-pro") multimodal_model_pro = GenerativeModel("gemini-pro-vision") return text_model_pro, multimodal_model_pro st.header("Vertex AI Gemini API", divider="rainbow") text_model_pro, multimodal_model_pro = load_models() tab1, tab2, tab3, tab4 = st.tabs(["Story", "Marketing Campaign", "Image Playground", "Video Playground"]) with tab1: render_story_tab(text_model_pro) EOF
  2. app.py ファイルのコンテンツを表示します。

    cat ~/gemini-app/app.py

    このアプリは streamlit を使用して、UI にいくつかのタブを作成します。アプリのこの初期バージョンでは、最初のタブとして、ストーリーの生成機能を含む [Story] タブを作成します。他のタブについては、ラボの以降のタスクで段階的に作成していきます。

    アプリはまず、PROJECT_ID 環境変数と REGION 環境変数の値を渡して Vertex AI SDK を初期化します。

    続いて、Gemini モデルを表す GenerativeModel クラスを使用して gemini-pro モデルと gemini-pro-vision モデルを読み込みます。このクラスには、テキスト、画像、動画からコンテンツを生成するために利用できるメソッドが含まれています。

    アプリは UI に [Story]、[Marketing Campaign]、[Image Playground]、[Video Playground] という 4 つのタブを作成します。

    アプリのコードは次に render_tab1() 関数を呼び出して、アプリの UI に [Story] タブ用の UI を作成します。

tab1 を開発する - Story

  1. 次のコマンドを実行して、アプリの UI に [Story] タブをレンダリングするコードを作成します。

    cat > ~/gemini-app/app_tab1.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel from response_utils import * import logging # ユーザー入力に基づいてモデルのプロンプトを作成するdef generate_prompt(): # ストーリーのキャラクターの入力 character_name = st.text_input("Enter character name: \n\n",key="character_name",value="Mittens") character_type = st.text_input("What type of character is it? \n\n",key="character_type",value="Cat") character_persona = st.text_input("What personality does the character have? \n\n", key="character_persona",value="Mitten is a very friendly cat.") character_location = st.text_input("Where does the character live? \n\n",key="character_location",value="Andromeda Galaxy") # ストーリーの長さと前提 length_of_story = st.radio("Select the length of the story: \n\n",["Short","Long"],key="length_of_story",horizontal=True) story_premise = st.multiselect("What is the story premise? (can select multiple) \n\n",["Love","Adventure","Mystery","Horror","Comedy","Sci-Fi","Fantasy","Thriller"],key="story_premise",default=["Love","Adventure"]) creative_control = st.radio("Select the creativity level: \n\n",["Low","High"],key="creative_control",horizontal=True) if creative_control == "Low": temperature = 0.30 else: temperature = 0.95 prompt = f"""Write a {length_of_story} story based on the following premise: \n character_name: {character_name} \n character_type: {character_type} \n character_persona: {character_persona} \n character_location: {character_location} \n story_premise: {",".join(story_premise)} \n If the story is "short", then make sure to have 5 chapters or else if it is "long" then 10 chapters. Important point is that each chapter should be generated based on the premise given above. First start by giving the book introduction, chapter introductions and then each chapter. It should also have a proper ending. The book should have a prologue and an epilogue. """ return temperature, prompt # [Story] タブをレンダリングしてモデルを呼び出し、モデルのプロンプトとレスポンスを表示する関数 def render_story_tab (text_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate a story") temperature, prompt = generate_prompt() config = { "temperature": temperature, "max_output_tokens": 2048, } generate_t2t = st.button("Generate my story", key="generate_t2t") if generate_t2t and prompt: # st.write(prompt) with st.spinner("Generating your story using Gemini..."): first_tab1, first_tab2 = st.tabs(["Story response", "Prompt"]) with first_tab1: response = get_gemini_pro_text_response(text_model_pro, prompt, generation_config=config) if response: st.write("Your story:") st.write(response) logging.info(response) with first_tab2: st.text(prompt) EOF
  2. app_tab1.py ファイルのコンテンツを表示します。

    cat ~/gemini-app/app_tab1.py

    render_story_tab 関数は、テキスト入力フィールドとその他のオプションをレンダリングする関数を呼び出して、タブ内に UI コントロールを生成します。

    generate_prompt 関数は、Gemini API に渡すテキスト プロンプトを生成します。プロンプト文字列は、ユーザーがタブの UI にストーリーのキャラクターとして入力した値と、ストーリーの長さ(短編、長編)、クリエイティビティ レベル(低、高)、ストーリーの前提などのオプションを連結して作成されます。

    この関数は、選択されたストーリーのクリエイティビティ レベルに基づく temperature の値も返します。この値が temperature 構成パラメータとしてモデルに渡されて、モデルの予測のランダム化が制御されます。max_output_tokens 構成パラメータは、メッセージごとに生成する出力トークンの最大数を指定します。

    タブの UI に、モデルのレスポンスを生成するためのボタンが作成されます。このボタンがクリックされると、get_gemini_pro_text_response 関数が呼び出されます。この関数はラボの次のステップでコーディングします。

response_utils を開発する

response_utils.py ファイルには、モデルのレスポンスを生成する関数が含まれます。

  1. 次のコマンドを実行して、モデルのテキスト プロンプトを生成するコードを作成します。

    cat > ~/gemini-app/response_utils.py <<EOF from vertexai.preview.generative_models import (Content, GenerationConfig, GenerativeModel, GenerationResponse, Image, HarmCategory, HarmBlockThreshold, Part) def get_gemini_pro_text_response( model: GenerativeModel, prompt: str, generation_config: GenerationConfig, stream=True): safety_settings={ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE, } responses = model.generate_content(prompt, generation_config = generation_config, safety_settings = safety_settings, stream=True) final_response = [] for response in responses: try: final_response.append(response.text) except IndexError: final_response.append("") continue return " ".join(final_response) EOF
  2. response_utils.py ファイルのコンテンツを表示します。

    cat ~/gemini-app/response_utils.py

    get_gemini_pro_text_response 関数は、Vertex AI SDK for Python の vertexai.preview.generative_models パッケージに含まれる GenerativeModel と他のいくつかのクラスを使用します。GenerativeModel クラスの generate_content メソッドにより、このメソッドに渡されたテキスト プロンプトを使用してレスポンスが生成されます。

    このメソッドには、安全でないコンテンツをブロックしてモデルのレスポンスを制御するために safety_settings オブジェクトも渡されます。このラボのサンプルコードでは安全性設定の値を使用して、コンテンツが安全でない確率とは関係なく常にコンテンツを返すようにモデルに指示しています。生成されたコンテンツを評価して、アプリケーションにより制限の厳しい構成が必要であると判断した場合は、これらの設定を調整できます。詳細については、安全性設定のドキュメントをご覧ください。

タスク 4. アプリをローカルで実行してテストする

このタスクでは、streamlit を使用してアプリをローカルで実行し、アプリの機能をテストします。

アプリを実行する

  1. Cloud Shell で次のコマンドを実行して、アプリをローカルで実行します。

    streamlit run app.py \ --browser.serverAddress=localhost \ --server.enableCORS=false \ --server.enableXsrfProtection=false \ --server.port 8080

    これによってアプリが起動し、アプリにアクセスするための URL が表示されます。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

    ポート 8080 でのウェブ プレビュー

    アプリの URL をコピーして別のブラウザタブに貼り付けて、アプリにアクセスすることもできます。

アプリをテストする - [Story] タブ

情報を入力してストーリーを生成し、ストーリーの生成に使用されたプロンプトと、Gemini 1.0 Pro モデルによって生成されたレスポンスを確認します。

  1. ストーリーを生成するために、[Story] タブでデフォルトの設定を変えずに [Generate my story] をクリックします。

  2. レスポンスが生成されるまで待ってから、[Story response] タブをクリックします。

  3. レスポンスの生成に使用されたプロンプトを確認するには、[Prompt] タブをクリックします。

  4. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 アプリケーションの [Story] タブを開発する

タスク 5. マーケティング キャンペーンを生成する

このタスクでは、Gemini 1.0 Pro テキストモデルを使用して企業のマーケティング キャンペーンを生成し、アプリの 2 つ目のタブを生成するコードを開発します。

tab2 を開発する - Marketing Campaign

  1. 次のコマンドを実行して、アプリの UI に [Marketing Campaign] タブをレンダリングするコードを作成します。

    cat > ~/gemini-app/app_tab2.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel from response_utils import * import logging # ユーザー入力に基づいてモデルのプロンプトを作成する def generate_prompt(): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate your marketing campaign") product_name = st.text_input("What is the name of the product? \n\n",key="product_name",value="ZomZoo") product_category = st.radio("Select your product category: \n\n",["Clothing","Electronics","Food","Health & Beauty","Home & Garden"],key="product_category",horizontal=True) st.write("Select your target audience: ") target_audience_age = st.radio("Target age: \n\n",["18-24","25-34","35-44","45-54","55-64","65+"],key="target_audience_age",horizontal=True) # target_audience_gender = st.radio("Target gender: \n\n",["male","female","trans","non-binary","others"],key="target_audience_gender",horizontal=True) target_audience_location = st.radio("Target location: \n\n",["Urban", "Suburban","Rural"],key="target_audience_location",horizontal=True) st.write("Select your marketing campaign goal: ") campaign_goal = st.multiselect("Select your marketing campaign goal: \n\n",["Increase brand awareness","Generate leads","Drive sales","Improve brand sentiment"],key="campaign_goal",default=["Increase brand awareness","Generate leads"]) if campaign_goal is None: campaign_goal = ["Increase brand awareness","Generate leads"] brand_voice = st.radio("Select your brand voice: \n\n",["Formal","Informal","Serious","Humorous"],key="brand_voice",horizontal=True) estimated_budget = st.radio("Select your estimated budget ($): \n\n",["1,000-5,000","5,000-10,000","10,000-20,000","20,000+"],key="estimated_budget",horizontal=True) prompt = f"""Generate a marketing campaign for {product_name}, a {product_category} designed for the age group: {target_audience_age}. The target location is this: {target_audience_location}. Aim to primarily achieve {campaign_goal}. Emphasize the product's unique selling proposition while using a {brand_voice} tone of voice. Allocate the total budget of {estimated_budget}. With these inputs, make sure to follow following guidelines and generate the marketing campaign with proper headlines: \n - Briefly describe the company, its values, mission, and target audience. - Highlight any relevant brand guidelines or messaging frameworks. - Provide a concise overview of the campaign's objectives and goals. - Briefly explain the product or service being promoted. - Define your ideal customer with clear demographics, psychographics, and behavioral insights. - Understand their needs, wants, motivations, and pain points. - Clearly articulate the desired outcomes for the campaign. - Use SMART goals (Specific, Measurable, Achievable, Relevant, and Time-bound) for clarity. - Define key performance indicators (KPIs) to track progress and success. - Specify the primary and secondary goals of the campaign. - Examples include brand awareness, lead generation, sales growth, or website traffic. - Clearly define what differentiates your product or service from competitors. - Emphasize the value proposition and unique benefits offered to the target audience. - Define the desired tone and personality of the campaign messaging. - Identify the specific channels you will use to reach your target audience. - Clearly state the desired action you want the audience to take. - Make it specific, compelling, and easy to understand. - Identify and analyze your key competitors in the market. - Understand their strengths and weaknesses, target audience, and marketing strategies. - Develop a differentiation strategy to stand out from the competition. - Define how you will track the success of the campaign. - Use relevant KPIs to measure performance and return on investment (ROI). Provide bullet points and headlines for the marketing campaign. Do not produce any empty lines. Be very succinct and to the point. """ return prompt # [Story] タブをレンダリングし、モデルを呼び出して、モデルのプロンプトとレスポンスを表示する関数 def render_mktg_campaign_tab (text_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate a marketing campaign") prompt = generate_prompt() config = { "temperature": 0.8, "max_output_tokens": 2048, } generate_t2m = st.button("Generate campaign", key="generate_t2m") if generate_t2m and prompt: # st.write(prompt) with st.spinner("Generating a marketing campaign using Gemini..."): first_tab1, first_tab2 = st.tabs(["Campaign response", "Prompt"]) with first_tab1: response = get_gemini_pro_text_response(text_model_pro, prompt, generation_config=config) if response: st.write("Marketing campaign:") st.write(response) logging.info(response) with first_tab2: st.text(prompt) EOF

アプリのメイン エントリ ポイントに変更を加える

  • 次のコマンドを実行して、アプリに tab2 を追加します。

    cat >> ~/gemini-app/app.py <<EOF from app_tab2 import render_mktg_campaign_tab with tab2: render_mktg_campaign_tab(text_model_pro) EOF

アプリをテストする - [Marketing Campaign] タブ

情報を入力してマーケティング キャンペーンを生成し、キャンペーンの生成に使用されたプロンプトと、Gemini 1.0 Pro モデルによって生成されたレスポンスを確認します。

  1. Cloud Shell で次のコマンドを実行して、アプリをローカルで実行します。

    streamlit run app.py \ --browser.serverAddress=localhost \ --server.enableCORS=false \ --server.enableXsrfProtection=false \ --server.port 8080

    これによってアプリが起動し、アプリにアクセスするための URL が表示されます。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. マーケティング キャンペーンを生成するために、[Marketing Campaign] タブでデフォルトの設定を変えずに [Generate campaign] をクリックします。

  4. レスポンスが生成されるまで待ってから、[Campaign response] タブをクリックします。

  5. レスポンスの生成に使用されたプロンプトを確認するには、[Prompt] タブをクリックします。

  6. パラメータ(商品カテゴリ、ターゲット オーディエンス、ロケーション、キャンペーンの目標など)に別の値を使用して上記のステップを繰り返し、マーケティング キャンペーンを生成します

  7. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 アプリケーションの [Marketing Campaign] タブを開発する

タスク 6. 画像プレイグラウンドを生成する

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して画像を処理し、モデルに渡した画像から生成されたレコメンデーションと情報を取得します。

tab3 を開発する - Image Playground

このサブタスクでは、[Image Playground] タブ用のコードと、モデルを操作して画像からレコメンデーションを生成するためのコードを実装します。

  1. 次のコマンドを実行して、アプリの UI に [Image Playground] タブをレンダリングするコードを作成します。

    cat > ~/gemini-app/app_tab3.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel, Part from response_utils import * import logging # 複数の子タブを持つ [Image Playground] タブをレンダリングする def render_image_playground_tab(multimodal_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro Vision - Multimodal model") recommendations, screens, diagrams, equations = st.tabs(["Furniture recommendation", "Oven instructions", "ER diagrams", "Math reasoning"]) with recommendations: room_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/living_room.jpeg" chair_1_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair1.jpeg" chair_2_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair2.jpeg" chair_3_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair3.jpeg" chair_4_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair4.jpeg" room_image_url = "https://storage.googleapis.com/"+room_image_uri.split("gs://")[1] chair_1_image_url = "https://storage.googleapis.com/"+chair_1_image_uri.split("gs://")[1] chair_2_image_url = "https://storage.googleapis.com/"+chair_2_image_uri.split("gs://")[1] chair_3_image_url = "https://storage.googleapis.com/"+chair_3_image_uri.split("gs://")[1] chair_4_image_url = "https://storage.googleapis.com/"+chair_4_image_uri.split("gs://")[1] room_image = Part.from_uri(room_image_uri, mime_type="image/jpeg") chair_1_image = Part.from_uri(chair_1_image_uri,mime_type="image/jpeg") chair_2_image = Part.from_uri(chair_2_image_uri,mime_type="image/jpeg") chair_3_image = Part.from_uri(chair_3_image_uri,mime_type="image/jpeg") chair_4_image = Part.from_uri(chair_4_image_uri,mime_type="image/jpeg") st.image(room_image_url,width=350, caption="Image of a living room") st.image([chair_1_image_url,chair_2_image_url,chair_3_image_url,chair_4_image_url],width=200, caption=["Chair 1","Chair 2","Chair 3","Chair 4"]) st.write("Our expectation: Recommend a chair that would complement the given image of a living room.") prompt_list = ["Consider the following chairs:", "chair 1:", chair_1_image, "chair 2:", chair_2_image, "chair 3:", chair_3_image, "and", "chair 4:", chair_4_image, "\n" "For each chair, explain why it would be suitable or not suitable for the following room:", room_image, "Only recommend for the room provided and not other rooms. Provide your recommendation in a table format with chair name and reason as columns.", ] tab1, tab2 = st.tabs(["Response", "Prompt"]) generate_image_description = st.button("Generate recommendation", key="generate_image_description") with tab1: if generate_image_description and prompt_list: with st.spinner("Generating recommendation using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, prompt_list) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt_list) EOF
  2. app_tab3.py ファイルのコンテンツを表示します。

    cat ~/gemini-app/app_tab3.py

    render_image_playground_tab 関数は、アプリのユーザーが Gemini 1.0 Pro Vision モデルを操作するために使用する UI を作成します。この関数が UI に作成するタブは、[Furniture recommendation]、[Oven instructions]、[ER diagrams]、[Math reasoning] です。残りのタブ用のコードは、このラボの後のタスクで記述します。

    [Furniture recommendation] タブでは、視覚的な理解のためにリビングルームのシーンが使用されます。このコードでは、一連の椅子の画像を追加で使用して Gemini 1.0 Pro Vision マルチモーダル API エンドポイントを呼び出し、リビングルームのシーンに合う椅子のレコメンデーションを取得します。

    リビングルームのシーン

    このコードは複数のテキスト プロンプトを使用し、リビングルームと複数の椅子の画像をリストにしてモデルに渡します。Part クラスを使用して、マルチパート コンテンツ URI で指定された画像を取得します。この画像は Cloud Storage バケットでホストされています。プロンプトでもモデルの出力に表形式を指定し、出力にレコメンデーションの論理的根拠を含めるように指示しています。

response_utils を更新する

response_utils.py ファイルには、モデルのレスポンスを生成する関数が含まれます。

  • このファイルを更新して、モデルのマルチモーダル レスポンスを生成するコードを追加します。

    cat >> ~/gemini-app/response_utils.py <<EOF def get_gemini_pro_vision_response(model: GenerativeModel, prompt_list, generation_config={}, stream=True): generation_config = {'temperature': 0.1, 'max_output_tokens': 2048 } responses = model.generate_content(prompt_list, generation_config = generation_config, stream=True) final_response = [] for response in responses: try: final_response.append(response.text) except IndexError: final_response.append("") continue return(" ".join(final_response)) EOF

アプリのメイン エントリ ポイントに変更を加える

  • 次のコマンドを実行して、アプリに tab3 を追加します。

    cat >> ~/gemini-app/app.py <<EOF from app_tab3 import render_image_playground_tab with tab3: render_image_playground_tab(multimodal_model_pro) EOF

アプリをテストする - [Image Playground] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Image Playground] をクリックし、[Furniture recommendation] をクリックします。

    このタブには、リビングルームと椅子の画像が表示されます。

  4. [Generate recommendation] をクリックします。

    エラー「FailedPrecondition: 400 We are preparing necessary resources. Please wait few minutes and retry.」が表示された場合は、必要なリソースを準備中であるため、数分待ってから再度 [Generate recommendation] をクリックしてください。
  5. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    プロンプトでリクエストされたように、レスポンスは表形式になっています。モデルは 4 脚の椅子のうちの 2 脚を推奨し、このレコメンデーションの論理的根拠を説明します。

  6. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Furniture recommendation] タブを追加した、アプリケーションの画像プレイグラウンドを開発する

タスク 7. 画像レイアウトを分析する

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して、画像のアイコンとテキストのレイアウトを分析した後、その画像から情報を引き出します。

[Image Playground] タブを更新する - オーブンの操作手順

画面上のビジュアル要素から情報を引き出せる Gemini を使用すれば、スクリーンショット、アイコン、レイアウトを分析して、描写されているシーンを包括的に理解できます。このタスクでは、キッチン用オーブンのコントロール パネルの画像をモデルに渡した後、特定の機能の操作手順を生成するようにプロンプトで指示します。

  • 次のコマンドを実行して、アプリの UI で [Image Playground] タブ内に [Oven instructions] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab3.py <<EOF with screens: oven_screen_uri = "gs://cloud-training/OCBL447/gemini-app/images/oven.jpg" oven_screen_url = "https://storage.googleapis.com/"+oven_screen_uri.split("gs://")[1] oven_screen_img = Part.from_uri(oven_screen_uri, mime_type="image/jpeg") st.image(oven_screen_url, width=350, caption="Image of an oven control panel") st.write("Provide instructions for resetting the clock on this appliance in English") prompt = """How can I reset the clock on this appliance? Provide the instructions in English. If instructions include buttons, also explain where those buttons are physically located. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) generate_instructions_description = st.button("Generate instructions", key="generate_instructions_description") with tab1: if generate_instructions_description and prompt: with st.spinner("Generating instructions using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, [oven_screen_img, prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt+"\n"+"input_image") EOF

    上記のコードにより、[Oven instructions] タブの UI が作成されます。キッチン用オーブンのコントロール パネルの画像と併せてテキスト プロンプトを使用して、パネル上にある特定の機能(この場合は、時計のリセット)の操作手順を生成するようにモデルに指示します。

    オーブンのコントロール パネル

アプリをテストする - [Image Playground] - [Oven instructions] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Image Playground]、[Oven instructions] の順にクリックします。

    このタブには、オーブンのコントロール パネルの画像が表示されます。

  4. [Generate instructions] をクリックします。

  5. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、オーブンのコントロール パネルで時計をリセットするための手順が含まれています。この手順には、パネル上のボタンの位置に関する説明も含まれており、このモデルが画像内のパネルのレイアウトを分析できることを示しています。

  6. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Oven instructions] タブを追加した画像プレイグラウンドを開発する

タスク 8. ER 図を分析する

Gemini はそのマルチモーダル機能により、図を理解して、ドキュメントやコードを生成するといった実用的なステップを実行できます。このタスクでは、Gemini 1.0 Pro Vision モデルを使用してエンティティ リレーションシップ(ER)図を分析し、図に示されているエンティティとリレーションシップに関するドキュメントを生成します。

[Image Playground] タブを更新する - ER 図

このタスクでは、ER 図の画像をモデルに渡して、ドキュメントを生成するようにプロンプトで指示します。

  • 次のコマンドを実行して、アプリの UI で [Image Playground] タブ内に [ER diagrams] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab3.py <<EOF with diagrams: er_diag_uri = "gs://cloud-training/OCBL447/gemini-app/images/er.png" er_diag_url = "https://storage.googleapis.com/"+er_diag_uri.split("gs://")[1] er_diag_img = Part.from_uri(er_diag_uri,mime_type="image/png") st.image(er_diag_url, width=350, caption="Image of an ER diagram") st.write("Document the entities and relationships in this ER diagram.") prompt = """Document the entities and relationships in this ER diagram.""" tab1, tab2 = st.tabs(["Response", "Prompt"]) er_diag_img_description = st.button("Generate documentation", key="er_diag_img_description") with tab1: if er_diag_img_description and prompt: with st.spinner("Generating..."): response = get_gemini_pro_vision_response(multimodal_model_pro,[er_diag_img,prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt+"\n"+"input_image") EOF

    上記のコードにより、[ER diagrams] タブの UI が作成されます。ER 図の画像と併せてテキスト プロンプトを使用して、図に示されているエンティティとリレーションシップに関するドキュメントを生成するようにモデルに指示します。

    ER 図

アプリをテストする - [Image Playground] - [ER diagrams] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Image Playground]、[ER diagrams] の順にクリックします。

    このタブには、ER 図の画像が表示されます。

  4. [Generate documentation] をクリックします。

  5. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、図に示されているエンティティとリレーションシップのリストが含まれます。

  6. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [ER diagrams] タブを追加した画像プレイグラウンドを開発する

タスク 9. 数学的推論

Gemini 1.0 Pro Vision では計算式や方程式を認識して、そこから特定の情報を引き出すこともできます。この機能が特に役立つのは、数学の問題についての説明を生成する場合です。

[Image Playground] タブを更新する - 数学的推論

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して、画像から計算式を抽出して解釈します。

  • 次のコマンドを実行して、アプリの UI で [Image Playground] タブ内に [Math reasoning] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab3.py <<EOF with equations: math_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/math_eqn.jpg" math_image_url = "https://storage.googleapis.com/"+math_image_uri.split("gs://")[1] math_image_img = Part.from_uri(math_image_uri,mime_type="image/jpeg") st.image(math_image_url,width=350, caption="Image of a math equation") st.markdown(f""" Ask questions about the math equation as follows: - Extract the formula. - What is the symbol right before Pi? What does it mean? - Is this a famous formula? Does it have a name? """) prompt = """Follow the instructions. Surround math expressions with $. Use a table with a row for each instruction and its result. INSTRUCTIONS: - Extract the formula. - What is the symbol right before Pi? What does it mean? - Is this a famous formula? Does it have a name? """ tab1, tab2 = st.tabs(["Response", "Prompt"]) math_image_description = st.button("Generate answers", key="math_image_description") with tab1: if math_image_description and prompt: with st.spinner("Generating answers for formula using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, [math_image_img, prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt) EOF

    上記のコードにより、[Math reasoning] タブの UI が作成されます。計算式の画像と併せてテキスト プロンプトを使用して、計算式の解答とその他の特徴を生成するようにモデルに指示します。

    計算式

アプリをテストする - [Image playground] - [Math reasoning] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Image playground]、[Math reasoning] の順にクリックします。

    このタブには、計算式が含まれる画像が表示されます。

  4. [Generate answers] をクリックします。

  5. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、モデルへのプロンプトで渡された計算式の解答が含まれます。

  6. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Math reasoning] タブを追加した画像プレイグラウンドを開発する

タスク 10. 動画プレイグラウンドを生成する

このタスクでは Gemini 1.0 Pro Vision モデルを使用して、モデルに渡した動画を処理し、そこからタグと情報を生成します。

tab4 を開発する - Video Playground

Gemini 1.0 Pro Vision モデルでは、動画で何が起こっているかを説明することもできます。このサブタスクでは、[Video Playground] タブ用のコードと、モデルを操作して動画の説明を生成するためのコードを実装します。

  1. 次のコマンドを実行して、アプリの UI に [Video Playground] タブをレンダリングするコードを作成します。

    cat > ~/gemini-app/app_tab4.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel, Part from response_utils import * import logging # 複数の子タブからなる [Video Playground] タブをレンダリングする def render_video_playground_tab(multimodal_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro Vision - Multimodal model") video_desc, video_tags, video_highlights, video_geoloc = st.tabs(["Video description", "Video tags", "Video highlights", "Video geolocation"]) with video_desc: video_desc_uri = "gs://cloud-training/OCBL447/gemini-app/videos/mediterraneansea.mp4" video_desc_url = "https://storage.googleapis.com/"+video_desc_uri.split("gs://")[1] video_desc_vid = Part.from_uri(video_desc_uri, mime_type="video/mp4") st.video(video_desc_url) st.write("Generate a description of the video.") prompt = """Describe what is happening in the video and answer the following questions: \n - What am I looking at? - Where should I go to see it? - What are other top 5 places in the world that look like this? """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_desc_description = st.button("Generate video description", key="video_desc_description") with tab1: if video_desc_description and prompt: with st.spinner("Generating video description"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_desc_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF
  2. app_tab4.py ファイルのコンテンツを表示します。

    cat ~/gemini-app/app_tab4.py

    render_video_playground_tab 関数は、アプリのユーザーが Gemini 1.0 Pro Vision モデルを操作するために使用する UI を作成します。この関数が UI に作成するタブは、[Video description]、[Video tags]、[Video highlights]、[Video geolocation] です。残りのタブ用のコードは、このラボの後のタスクで記述します。

    [Video description] タブでは、動画と併せてプロンプトを使用して動画の説明を生成し、動画に映っている場所と似ている他の場所を特定します。

アプリのメイン エントリ ポイントに変更を加える

  • 次のコマンドを実行して、アプリに tab4 を追加します。

    cat >> ~/gemini-app/app.py <<EOF from app_tab4 import render_video_playground_tab with tab4: render_video_playground_tab(multimodal_model_pro) EOF

アプリをテストする - [Video Playground] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Video Playground]、[Video description] の順にクリックします。

  4. このタブには、場所の動画が表示されます。動画をクリックして再生します。

  5. [Generate video description] をクリックします。

  6. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、場所の説明と、その場所と似ている他の 5 つの場所が含まれます。

  7. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Video description] タブを追加した、アプリケーションの動画プレイグラウンドを開発する

タスク 11. 動画のタグを生成する

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して動画からタグを生成します。

[Video Playground] タブを更新する - 動画のタグ

  • 次のコマンドを実行して、アプリの UI で [Video Playground] タブ内に [Video tags] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_tags: video_tags_uri = "gs://cloud-training/OCBL447/gemini-app/videos/photography.mp4" video_tags_url = "https://storage.googleapis.com/"+video_tags_uri.split("gs://")[1] video_tags_vid = Part.from_uri(video_tags_uri, mime_type="video/mp4") st.video(video_tags_url) st.write("Generate tags for the video.") prompt = """Answer the following questions using the video only: 1. What is in the video? 2. What objects are in the video? 3. What is the action in the video? 4. Provide 5 best tags for this video? Write the answer in table format with the questions and answers in columns. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_tags_desc = st.button("Generate video tags", key="video_tags_desc") with tab1: if video_tags_desc and prompt: with st.spinner("Generating video tags"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_tags_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上記のコードにより、[Video tags] タブの UI が作成されます。動画と併せてテキスト プロンプトを使用して、タグを生成して動画のシーンに関する質問に答えるようにモデルに指示します。

アプリをテストする - [Video Playground] - [Video tags] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Video Playground]、[Video tags] の順にクリックします。

  4. このタグには、モデルへのプロンプトに使用する動画が表示されます。動画をクリックして再生します。

  5. [Generate video tags] をクリックします。

  6. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、プロンプトでモデルに尋ねた質問への答えが含まれます。リクエストしたように質問と答えが表形式で出力され、出力には 5 つのタグが含まれます。

  7. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Video tags] タブを追加した動画プレイグラウンドを開発する

タスク 12. 動画のハイライトを生成する

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して、動画に映っているオブジェクト、人、コンテキストに関する情報を含むハイライトを動画から生成します。

[Video Playground] タブを更新する - 動画のハイライト

  • 次のコマンドを実行して、アプリの UI で [Video Playground] タブ内に [Video highlights] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_highlights: video_highlights_uri = "gs://cloud-training/OCBL447/gemini-app/videos/pixel8.mp4" video_highlights_url = "https://storage.googleapis.com/"+video_highlights_uri.split("gs://")[1] video_highlights_vid = Part.from_uri(video_highlights_uri, mime_type="video/mp4") st.video(video_highlights_url) st.write("Generate highlights for the video.") prompt = """Answer the following questions using the video only: What is the profession of the girl in this video? Which features of the phone are highlighted here? Summarize the video in one paragraph. Write these questions and their answers in table format. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_highlights_description = st.button("Generate video highlights", key="video_highlights_description") with tab1: if video_highlights_description and prompt: with st.spinner("Generating video highlights"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_highlights_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上記のコードにより、[Video highlights] タブの UI が作成されます。動画と併せてテキスト プロンプトを使用して、動画からハイライトを生成するようにモデルに指示します。

アプリをテストする - [Video Playground] - [Video highlights] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Video Playground]、[Video highlight] の順にクリックします。

  4. このタグには、モデルへのプロンプトに使用する動画が表示されます。動画をクリックして再生します。

  5. [Generate video highlights] をクリックします。

  6. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、プロンプトでモデルに尋ねた質問への答えが含まれます。質問と答えが表形式で出力され、動画の特徴(女性の職業、使用されているスマートフォンの機能など)がリストされます。レスポンスには、動画のシーンを要約する説明も含まれます。

  7. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Video highlight] タブを追加した動画プレイグラウンドを開発する

タスク 13. 動画の位置情報を生成する

このタスクでは、Gemini 1.0 Pro Vision モデルを使用して、動画のシーンが繰り広げられている場所を判断します。

[Video Playground] タブを更新する - 動画の位置情報

  • 次のコマンドを実行して、アプリの UI で [Video Playground] タブ内に [Video geolocation] タブをレンダリングするコードを実装します。

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_geoloc: video_geolocation_uri = "gs://cloud-training/OCBL447/gemini-app/videos/bus.mp4" video_geolocation_url = "https://storage.googleapis.com/"+video_geolocation_uri.split("gs://")[1] video_geolocation_vid = Part.from_uri(video_geolocation_uri, mime_type="video/mp4") st.video(video_geolocation_url) st.markdown("""Answer the following questions from the video: - What is this video about? - How do you know which city it is? - What street is this? - What is the nearest intersection? """) prompt = """Answer the following questions using the video only: What is this video about? How do you know which city it is? What street is this? What is the nearest intersection? Answer the following questions using a table format with the questions and answers as columns. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_geolocation_description = st.button("Generate", key="video_geolocation_description") with tab1: if video_geolocation_description and prompt: with st.spinner("Generating location information"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_geolocation_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上記のコードにより、[Video geolocation] タブの UI が作成されます。動画と併せてテキスト プロンプトを使用して、動画に映っているエンティティの位置情報を含む、動画に関する質問に答えるようにモデルに指示します。

アプリをテストする - [Video Playground] - [Video geolocation] タブ

  1. このラボの前のステップで紹介したコマンドを使用して、アプリを実行します。

  2. ブラウザでアプリのホームページを起動するために、Cloud Shell のメニューバーで [ウェブでプレビュー]、[ポート 8080 でプレビュー] の順にクリックします。

  3. [Video Playground]、[Video geolocation] の順にクリックします。

  4. このタグには、モデルへのプロンプトに使用する動画が表示されます。動画をクリックして再生します。

  5. [Generate] をクリックします。

  6. Gemini 1.0 Pro Vision モデルからのレスポンスを確認します。

    レスポンスには、プロンプトでモデルに尋ねた質問への答えが含まれます。リクエストしたように質問と答えが表形式で出力され、出力には位置情報が含まれます。

  7. Cloud Shell ウィンドウでアプリを終了し、Control+C キーを押してコマンド プロンプトに戻ります。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 [Video geolocation] タブを追加した動画プレイグラウンドを開発する

タスク 14. Cloud Run にアプリをデプロイする

アプリをローカルでテストしたので、このアプリを Google Cloud 上の Cloud Run にデプロイして、他のユーザーが利用できるようにします。Cloud Run は、Google のスケーラブルなインフラストラクチャを基盤にアプケーション コンテナを実行できるマネージド コンピューティング プラットフォームです。

環境を設定する

  1. app ディレクトリ内にいることを確認します。

    cd ~/gemini-app
  2. ROJECT_ID 環境変数と REGION 環境変数が設定されていることを確認します。

    echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  3. これらの環境変数が設定されていない場合は、次のコマンドを実行して設定します。

    PROJECT_ID=$(gcloud config get-value project) REGION={{{project_0.default_region|set at lab start}}} echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  4. サービスとアーティファクト リポジトリの環境変数を設定します。

    SERVICE_NAME='gemini-app-playground' # 実際の Cloud Run サービスの名前 AR_REPO='gemini-app-repo' # アプリケーション コンテナ イメージが格納されている、Artifact Registry 内のリポジトリの名前 echo "SERVICE_NAME=${SERVICE_NAME}" echo "AR_REPO=${AR_REPO}"

Docker リポジトリを作成する

  1. 次のコマンドを実行して、Artifact Registry 内にリポジトリを作成します。

    gcloud artifacts repositories create "$AR_REPO" --location="$REGION" --repository-format=Docker Artifact Registry は、ソフトウェア パッケージと Docker コンテナ イメージを一元的に保管して管理するための単一の場所を提供する Google Cloud サービスです。
  2. このリポジトリに対する認証を設定します。

    gcloud auth configure-docker "$REGION-docker.pkg.dev"

コンテナ イメージをビルドする

Dockerfile を使用して、アプリケーションのコンテナ イメージをビルドします。Dockerfile は、コンテナ イメージをアセンブルするためにコマンドラインで呼び出すことのできるすべてのコマンドを含むテキスト ドキュメントです。Dockerfile は、コンテナ イメージをビルドして実行するコンテナ プラットフォームである Docker で使用されます。

  1. 次のコマンドを実行して Dockerfile を作成します。

    cat > ~/gemini-app/Dockerfile <<EOF FROM python:3.8 EXPOSE 8080 WORKDIR /app COPY . ./ RUN pip install -r requirements.txt ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8080", "--server.address=0.0.0.0"] EOF
  2. 次のコマンドを実行して、アプリのコンテナ イメージをビルドします。

    gcloud builds submit --tag "$REGION-docker.pkg.dev/$PROJECT_ID/$AR_REPO/$SERVICE_NAME" gcloud builds submit コマンドは、Cloud Build を使用したビルドを実行依頼します。このコマンドに tag フラグが追加されている場合、Cloud Build は Dockerfile を使用して、ソース ディレクトリ内のアプリケーション ファイルからコンテナ イメージをビルドします。

    Cloud Build は、Google Cloud 上で仕様に基づいてビルドを実行し、Docker コンテナや Java アーカイブなどのアーティファクトを生成するサービスです。

    コマンドが完了するまで待ってから、次のステップに進みます。

アプリを Cloud Run にデプロイしてテストする

最後のタスクでは、先ほどビルドして Artifact Registry のリポジトリに push したイメージとともに、サービスを Cloud Run にデプロイします。

  1. 次のコマンドを実行して、アプリを Cloud Run にデプロイします。

    gcloud run deploy "$SERVICE_NAME" \ --port=8080 \ --image="$REGION-docker.pkg.dev/$PROJECT_ID/$AR_REPO/$SERVICE_NAME" \ --allow-unauthenticated \ --region=$REGION \ --platform=managed \ --project=$PROJECT_ID \ --set-env-vars=PROJECT_ID=$PROJECT_ID,REGION=$REGION
  2. サービスがデプロイされるとサービスの URL が生成されて、前のコマンドの出力に示されます。Cloud Run でアプリをテストするには、別のブラウザタブまたはウィンドウでその URL に移動します。

  3. テストするアプリの機能を選択します。アプリは、レスポンスを生成して表示するよう Vertex AI Gemini API に指示します。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 アプリケーションを Cloud Run にデプロイする

ラボを終了する

ラボでの学習が完了したら、[ラボを終了] をクリックします。ラボで使用したリソースが Qwiklabs から削除され、アカウントの情報も消去されます。

ラボの評価を求めるダイアログが表示されたら、星の数を選択してコメントを入力し、[送信] をクリックします。

星の数は、それぞれ次の評価を表します。

  • 星 1 つ = 非常に不満
  • 星 2 つ = 不満
  • 星 3 つ = どちらともいえない
  • 星 4 つ = 満足
  • 星 5 つ = 非常に満足

フィードバックを送信しない場合は、ダイアログ ボックスを閉じてください。

フィードバック、ご提案、修正が必要な箇所については、[サポート] タブからお知らせください。

お疲れさまでした

このラボでは、次の作業を行いました。

  • Streamlit フレームワークを使用して Python アプリを開発する
  • Vertex AI SDK for Python をインストールする
  • Vertex AI Gemini API を使用して Gemini 1.0 Pro モデル(gemini-pro)を操作するためのコードを開発する
  • モデルでテキスト プロンプトを使用して、ストーリーとマーケティング キャンペーンを生成する
  • Vertex AI Gemini API を使用して Gemini 1.0 Pro Vision モデル(gemini-pro-vision)を操作するためのコードを開発する
  • モデルでテキスト、画像、動画を使用し、画像と動画を処理して情報を抽出する
  • アプリを Cloud Run にデプロイしてテストする

次のステップと詳細情報

Copyright 2023 Google LLC All rights reserved. Google および Google のロゴは、Google LLC の商標です。その他すべての社名および製品名は、それぞれ該当する企業の商標である可能性があります。

このコンテンツは現在ご利用いただけません

We will notify you via email when it becomes available

ありがとうございます。

We will contact you via email if it becomes available