使用 BigQuery DataFrames 在 Python 中分析多模態資料

本教學課程將說明如何使用 BigQuery DataFrames 類別和方法,在 Python 筆記本中分析多模態資料

本教學課程使用公開的 Cymbal 寵物商店資料集產品目錄。

如要上傳已填入本教學課程所涵蓋任務的筆記本,請參閱 BigFrames 多模態 DataFrame

目標

  • 建立多模態資料框架。
  • 在 DataFrame 中結合結構化和非結構化資料。
  • 轉換圖片。
  • 根據圖片資料產生文字和嵌入項目。
  • 將 PDF 分割成多個部分,以利進一步分析。

費用

In this document, you use the following billable components of Google Cloud:

  • BigQuery: you incur costs for the data that you process in BigQuery.
  • BigQuery Python UDFs: you incur costs for using BigQuery DataFrames image transformation and chunk PDF methods.
  • Cloud Storage: you incur costs for the objects stored in Cloud Storage.
  • Vertex AI: you incur costs for calls to Vertex AI models.

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

如需詳細資訊,請參閱下列定價頁面:

事前準備

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  2. Make sure that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery, BigQuery Connection, Cloud Storage, and Vertex AI APIs.

    Enable the APIs

必要的角色

如要取得完成本教學課程所需的權限,請管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

設定

在本節中,您將建立本教學課程中使用的 Cloud Storage 值區、連線和筆記本。

建立值區

建立 Cloud Storage 值區來儲存轉換後的物件:

  1. 前往 Google Cloud 控制台的「Bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 按一下 「Create」(建立)

  3. 在「Create a bucket」(建立值區) 頁面的「Get started」(開始使用) 專區中,輸入符合值區名稱規定的全球專屬名稱。

  4. 按一下 [建立]。

建立連線

建立 Cloud 資源連線,並取得連線的服務帳戶。BigQuery 會使用這個連線存取 Cloud Storage 中的物件。

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中,按一下 「Add data」(新增資料)

    「Add data」對話方塊隨即開啟。

  3. 在「Filter By」窗格中的「Data Source Type」部分,選取「Business Applications」

    或者,您也可以在「Search for data sources」欄位中輸入 Vertex AI

  4. 在「精選資料來源」部分,按一下「Vertex AI」

  5. 按一下「Vertex AI 模型:BigQuery 聯盟」解決方案資訊卡。

  6. 在「連線類型」清單中,選取「Vertex AI 遠端模型、遠端函式和 BigLake (Cloud 資源)」

  7. 在「連線 ID」欄位中輸入 bigframes-default-connection

  8. 點選「建立連線」

  9. 按一下「前往連線」

  10. 在「連線資訊」窗格中,複製服務帳戶 ID,以便在後續步驟中使用。

將權限授予連線的服務帳戶

將連線的服務帳戶所需的角色授予 Cloud Storage 和 Vertex AI。您必須在開始前一節中建立或選取的專案中授予這些角色。

如要授予角色,請按照下列步驟操作:

  1. 前往「IAM & Admin」(IAM 與管理) 頁面。

    前往「IAM & Admin」(IAM 與管理)

  2. 按一下「授予存取權」

  3. 在「新增主體」欄位,輸入先前複製的服務帳戶 ID。

  4. 在「請選擇角色」欄位中,依序選取「Cloud Storage」和「Storage Object User」

  5. 按一下 [Add another role] (新增其他角色)

  6. 在「請選擇角色」欄位中,依序選取「Vertex AI」和「Vertex AI 使用者」

  7. 按一下 [儲存]

建立筆記本

建立可執行 Python 程式碼的筆記本:

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在編輯器窗格中的分頁列,按一下 「SQL 查詢」旁邊的 下拉式箭頭,然後點選「Notebook」

  3. 在「從範本開始」窗格中,點選「關閉」

  4. 依序按一下「連線」>「連線到執行階段」

  5. 如果您已使用現有的執行階段,請接受預設設定,然後按一下「連線」。如果您沒有現有的執行階段,請選取「建立新的執行階段」,然後按一下「連結」

    執行階段可能需要幾分鐘才能設定完成。

建立多模態資料框

使用 Session 類別的 from_glob_path 方法,建立整合結構化和非結構化資料的多模態 DataFrame:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    import bigframes
    
    # Flags to control preview image/video preview size
    bigframes.options.display.blob_display_width = 300
    
    import bigframes.pandas as bpd
    
    # Create blob columns from wildcard path.
    df_image = bpd.from_glob_path(
        "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*", name="image"
    )
    # Other ways are: from string uri column
    # df = bpd.DataFrame({"uri": ["gs://<my_bucket>/<my_file_0>", "gs://<my_bucket>/<my_file_1>"]})
    # df["blob_col"] = df["uri"].str.to_blob()
    
    # From an existing object table
    # df = bpd.read_gbq_object_table("<my_object_table>", name="blob_col")
    
    # Take only the 5 images to deal with. Preview the content of the Mutimodal DataFrame
    df_image = df_image.head(5)
    df_image
  2. 按一下「Run」

    最後一次呼叫 df_image 會傳回已新增至 DataFrame 的圖片。或者,您也可以呼叫 .display 方法。

在 DataFrame 中結合結構化和非結構化資料

在多模態資料框架中合併文字和圖片資料:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    # Combine unstructured data with structured data
    df_image["author"] = ["alice", "bob", "bob", "alice", "bob"]  # type: ignore
    df_image["content_type"] = df_image["image"].blob.content_type()
    df_image["size"] = df_image["image"].blob.size()
    df_image["updated"] = df_image["image"].blob.updated()
    df_image
  2. 按一下「Run」

    程式碼會傳回 DataFrame 資料。

  3. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:

    # Filter images and display, you can also display audio and video types. Use width/height parameters to constrain window sizes.
    df_image[df_image["author"] == "alice"]["image"].blob.display()
  4. 按一下「Run」

    程式碼會從 author 資料欄值為 alice 的 DataFrame 中傳回圖片。

執行圖片轉換作業

使用 Series.BlobAccessor 類別的下列方法轉換圖片資料:

轉換後的圖片會寫入 Cloud Storage。

轉換圖片:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    df_image["blurred"] = df_image["image"].blob.image_blur(
        (20, 20), dst=f"{dst_bucket}/image_blur_transformed/"
    )
    df_image["resized"] = df_image["image"].blob.image_resize(
        (300, 200), dst=f"{dst_bucket}/image_resize_transformed/"
    )
    df_image["normalized"] = df_image["image"].blob.image_normalize(
        alpha=50.0,
        beta=150.0,
        norm_type="minmax",
        dst=f"{dst_bucket}/image_normalize_transformed/",
    )
    
    # You can also chain functions together
    df_image["blur_resized"] = df_image["blurred"].blob.image_resize(
        (300, 200), dst=f"{dst_bucket}/image_blur_resize_transformed/"
    )
    df_image
  2. 將所有 {dst_bucket} 參照更新為 您建立的儲存體,格式為 gs://mybucket
  3. 按一下「Run」

    程式碼會傳回原始圖片以及所有轉換。

生成文字

使用 GeminiTextGenerator 類別的 predict 方法,從多模態資料產生文字:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    from bigframes.ml import llm
    
    gemini = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001")
    
    # Deal with first 2 images as example
    df_image = df_image.head(2)
    
    # Ask the same question on the images
    df_image = df_image.head(2)
    answer = gemini.predict(df_image, prompt=["what item is it?", df_image["image"]])
    answer[["ml_generate_text_llm_result", "image"]]
  2. 按一下「Run」

    程式碼會傳回 df_image 中的前兩張圖片,以及針對兩張圖片的 what item is it? 問題產生的文字。

  3. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:

    # Ask different questions
    df_image["question"] = [  # type: ignore
        "what item is it?",
        "what color is the picture?",
    ]
    answer_alt = gemini.predict(
        df_image, prompt=[df_image["question"], df_image["image"]]
    )
    answer_alt[["ml_generate_text_llm_result", "image"]]
  4. 按一下「Run」

    程式碼會傳回 df_image 中的前兩張圖片,並根據第一張圖片的 what item is it? 問題產生文字,以及根據第二張圖片的 what color is the picture? 問題產生文字。

生成嵌入項目

使用 MultimodalEmbeddingGenerator 類別的 predict 方法,為多模態資料產生嵌入:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    # Generate embeddings on images
    embed_model = llm.MultimodalEmbeddingGenerator()
    embeddings = embed_model.predict(df_image["image"])
    embeddings
  2. 按一下「Run」

    程式碼會傳回呼叫嵌入模型所產生的嵌入。

分割 PDF

使用 Series.BlobAccessor 類別的 pdf_chunk 方法分割 PDF 物件:

  1. 在筆記本中,建立程式碼儲存格並將下列程式碼複製到該儲存格中:
    # PDF chunking
    df_pdf = bpd.from_glob_path(
        "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*", name="pdf"
    )
    df_pdf["chunked"] = df_pdf["pdf"].blob.pdf_chunk()
    chunked = df_pdf["chunked"].explode()
    chunked
  2. 按一下「Run」

    程式碼會傳回分割的 PDF 資料。

清除所用資源

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.