GenAI Image Description API

使用 ML Kit 的 GenAI 圖像說明 API,即可為圖片生成簡短的內容說明。這項功能在下列情況中相當實用:

  • 生成圖片標題
  • 生成替代文字,協助視障使用者更瞭解圖片內容
  • 使用生成的說明做為中繼資料,協助使用者搜尋或整理圖片
  • 在使用者無法查看螢幕時 (例如開車或收聽 Podcast),提供圖片的簡短說明

主要功能

  • 傳回輸入圖片的簡短說明

搜尋結果範例

輸入功率 輸出內容
綠色 Android 機器人外觀類似仙人掌,坐在黑色表面上。 綠色 Android 機器人坐在黑色表面上,設計類似仙人掌。
一隻白色小狗,黑鼻子、粉紅色舌頭,在草地上奔跑,背景是橋。 一隻白色小狗在草地上奔跑,牠有黑色鼻子和粉紅色舌頭,背景是橋樑。

開始使用

如要開始使用 GenAI Image Description API,請將這個依附元件新增至專案的建構檔案。

implementation("com.google.mlkit:genai-image-description:1.0.0-beta1")

如要將 Image Description API 整合到應用程式中,請先取得 ImageDescriber 用戶端。接著,請檢查裝置上必要模型功能的狀態,並下載模型 (如果裝置上還沒有的話)。在 ImageDescriptionRequest 中準備好圖片輸入內容後,請使用用戶端執行推論,取得圖片說明文字,最後記得關閉用戶端以釋放資源。

Kotlin

// Create an image describer
val options = ImageDescriberOptions.builder(context).build()
val imageDescriber = ImageDescription.getClient(options)

suspend fun prepareAndStartImageDescription(
    bitmap: Bitmap
) {
  // Check feature availability, status will be one of the following:
  // UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
  val featureStatus = imageDescriber.checkFeatureStatus().await()

  if (featureStatus == FeatureStatus.DOWNLOADABLE) {
      // Download feature if necessary.
      // If downloadFeature is not called, the first inference request
      // will also trigger the feature to be downloaded if it's not
      // already downloaded.
      imageDescriber.downloadFeature(object : DownloadCallback {
          override fun onDownloadStarted(bytesToDownload: Long) { }

          override fun onDownloadFailed(e: GenAiException) { }

          override fun onDownloadProgress(totalBytesDownloaded: Long) {}

          override fun onDownloadCompleted() {
              startImageDescriptionRequest(bitmap, imageDescriber)
          }
      })
  } else if (featureStatus == FeatureStatus.DOWNLOADING) {
      // Inference request will automatically run once feature is
      // downloaded.
      // If Gemini Nano is already downloaded on the device, the
      // feature-specific LoRA adapter model will be downloaded
      // very quickly. However, if Gemini Nano is not already
      // downloaded, the download process may take longer.
      startImageDescriptionRequest(bitmap, imageDescriber)
  } else if (featureStatus == FeatureStatus.AVAILABLE) {
      startImageDescriptionRequest(bitmap, imageDescriber)
  }
}

fun startImageDescriptionRequest(
    bitmap: Bitmap,
    imageDescriber: ImageDescriber
) {
    // Create task request
    val imageDescriptionRequest = ImageDescriptionRequest
        .builder(bitmap)
        .build()
}

  // Run inference with a streaming callback
  val imageDescriptionResultStreaming =
      imageDescriber.runInference(imageDescriptionRequest) { outputText ->
          // Append new output text to show in UI
          // This callback is called incrementally as the description
          // is generated
      }

  // You can also get a non-streaming response from the request
  // val imageDescription = imageDescriber.runInference(
  //        imageDescriptionRequest).await().description
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
imageDescriber.close()

Java

// Create an image describer
ImageDescriberOptions options = ImageDescriberOptions.builder(context).build();
ImageDescriber imageDescriber = ImageDescription.getClient(options);

void prepareAndStartImageDescription(
      Bitmap bitmap
) throws ExecutionException, InterruptedException {
  // Check feature availability, status will be one of the following:
  // UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
  try {
      int featureStatus = imageDescriber.checkFeatureStatus().get();
      if (featureStatus == FeatureStatus.DOWNLOADABLE) {
          // Download feature if necessary.
          // If downloadFeature is not called, the first inference request
          // will also trigger the feature to be downloaded if it's not
          // already downloaded.
          imageDescriber.downloadFeature(new DownloadCallback() {
              @Override
              public void onDownloadCompleted() {
                  startImageDescriptionRequest(bitmap, imageDescriber);
              }

              @Override
              public void onDownloadFailed(GenAIException e) {}

              @Override
              public void onDownloadProgress(long totalBytesDownloaded) {}

              @Override
              public void onDownloadStarted(long bytesDownloaded) {}
          });
      } else if (featureStatus == FeatureStatus.DOWNLOADING) {
          // Inference request will automatically run once feature is
          // downloaded.
          // If Gemini Nano is already downloaded on the device, the
          // feature-specific LoRA adapter model will be downloaded
          // very quickly. However, if Gemini Nano is not already
          // downloaded, the download process may take longer.
          startImageDescriptionRequest(bitmap, imageDescriber);
      } else if (featureStatus == FeatureStatus.AVAILABLE) {
          startImageDescriptionRequest(bitmap, imageDescriber);
      }
  } catch (ExecutionException | InterruptedException e) {
      e.printStackTrace();
  }
}

void startImageDescriptionRequest(
     Bitmap bitmap,
     ImageDescriber imageDescriber
) {
  // Create task request
  ImageDescriptionRequest imageDescriptionRequest =
          ImageDescriptionRequest.builder(bitmap).build();

  // Start image description request with streaming response
  imageDescriber.runInference(imageDescriptionRequest, newText -> {
      // Append new output text to show in UI
      // This callback is called incrementally as the description
      // is generated
  });

  // You can also get a non-streaming response from the request
  // String imageDescription = imageDescriber.runInference(
  //        imageDescriptionRequest).get().getDescription();
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
imageDescriber.close();

支援的功能和限制

GenAI 圖片說明 API 支援英文,日後將支援更多語言。API 會傳回圖片的簡短說明。

特定功能設定 (由 ImageDescriberOptions 指定) 的可用性可能因特定裝置的設定,以及已下載至裝置的模型而異。

如要確保裝置支援所要求的 ImageDescriberOptions,開發人員最可靠的方式是呼叫 checkFeatureStatus() 方法。這個方法會在執行階段提供裝置上功能可用性的明確狀態。

常見設定問題

ML Kit GenAI API 會透過 Android AICore 應用程式存取 Gemini Nano。如果裝置剛完成設定 (包括重設),或是 AICore 應用程式剛重設 (例如清除資料、解除安裝後重新安裝),AICore 應用程式可能沒有足夠時間完成初始化 (包括從伺服器下載最新設定)。因此 ML Kit GenAI API 可能無法正常運作。以下是您可能會看到的常見設定錯誤訊息及處理方式:

錯誤訊息範例 如何處理
AICore 發生錯誤,錯誤類型為 4-CONNECTION_ERROR,錯誤代碼為 601-BINDING_FAILURE:AICore 服務繫結失敗。 如果裝置設定完成後,您立即使用 ML Kit GenAI API 安裝應用程式,或是應用程式安裝完成後解除安裝 AICore,就可能發生這種情況。更新 AICore 應用程式,然後重新安裝應用程式,應該就能修正問題。
AICore 失敗,錯誤類型為 3-PREPARATION_ERROR,錯誤代碼為 606-FEATURE_NOT_FOUND:功能「...」無法使用。 如果 AICore 尚未完成下載最新設定,就可能發生這種情況。裝置連上網際網路後,通常會在幾分鐘到幾小時內完成更新。重新啟動裝置可加快更新速度。

請注意,如果裝置的系統啟動載入程式處於解鎖狀態,您也會看到這項錯誤訊息,因為這項 API 不支援系統啟動載入程式處於解鎖狀態的裝置。
AICore failed with error type 1-DOWNLOAD_ERROR and error code 0-UNKNOWN: Feature ... failed with failure status 0 and error esz: UNAVAILABLE: Unable to resolve host ... 保持網路連線,稍待幾分鐘後再試一次。