GenAI Image Description API

Dengan GenAI Image Description API ML Kit, Anda dapat membuat deskripsi konten singkat untuk gambar. Hal ini dapat berguna dalam kasus penggunaan berikut:

  • Membuat judul gambar
  • Membuat teks alternatif (alt text) untuk membantu pengguna penyandang gangguan penglihatan lebih memahami konten gambar
  • Menggunakan deskripsi yang dibuat sebagai metadata untuk membantu pengguna menelusuri atau mengatur gambar
  • Menggunakan deskripsi singkat gambar saat pengguna tidak dapat melihat layar, seperti saat mereka sedang mengemudi atau mendengarkan podcast

Kemampuan utama

  • Menampilkan deskripsi singkat untuk gambar input

Hasil contoh

Input Output
Robot Android hijau kecil dengan desain seperti kaktus duduk di atas permukaan hitam. Robot Android hijau kecil dengan desain seperti kaktus duduk di atas permukaan hitam.
Seekor kecil berwarna putih dengan hidung hitam dan lidah merah muda berlari di padang rumput dengan jembatan di latar belakang. Seekor kecil berwarna putih dengan hidung hitam dan lidah merah muda berlari melintasi padang rumput dengan jembatan di latar belakang.

Memulai

Untuk mulai menggunakan GenAI Image Description API, tambahkan dependensi ini ke file build project Anda.

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

Untuk mengintegrasikan Image Description API ke dalam aplikasi, Anda akan memulai dengan mendapatkan klien ImageDescriber. Kemudian, Anda harus memeriksa status fitur model di perangkat yang diperlukan dan mendownload model jika belum ada di perangkat. Setelah menyiapkan input gambar dalam ImageDescriptionRequest, Anda menjalankan inferensi menggunakan klien untuk mendapatkan teks deskripsi gambar, dan terakhir, jangan lupa untuk menutup klien guna melepaskan resource.

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();

Fitur yang didukung dan batasan

GenAI Image Description API mendukung bahasa Inggris, dan dukungan untuk bahasa lainnya akan ditambahkan pada masa mendatang. API menampilkan satu deskripsi singkat gambar.

Ketersediaan konfigurasi fitur tertentu (yang ditentukan oleh ImageDescriberOptions) dapat bervariasi bergantung pada konfigurasi perangkat tertentu dan model yang telah didownload ke perangkat.

Cara paling andal bagi developer untuk memastikan bahwa fitur API yang dimaksud didukung di perangkat dengan ImageDescriberOptions yang diminta adalah dengan memanggil metode checkFeatureStatus(). Metode ini memberikan status pasti ketersediaan fitur di perangkat saat runtime.

Masalah penyiapan umum

API GenAI ML Kit mengandalkan aplikasi Android AICore untuk mengakses Gemini Nano. Saat perangkat baru disiapkan (termasuk direset), atau aplikasi AICore baru direset (misalnya, hapus data, di-uninstal lalu diinstal ulang), aplikasi AICore mungkin tidak memiliki cukup waktu untuk menyelesaikan inisialisasi (termasuk mendownload konfigurasi terbaru dari server). Akibatnya, API GenAI ML Kit mungkin tidak berfungsi seperti yang diharapkan. Berikut adalah pesan error penyiapan umum yang mungkin Anda lihat dan cara menanganinya:

Contoh pesan error Cara menangani
AICore gagal dengan jenis error 4-CONNECTION_ERROR dan kode error 601-BINDING_FAILURE: Layanan AICore gagal terikat. Hal ini dapat terjadi saat Anda menginstal aplikasi menggunakan ML Kit GenAI API segera setelah penyiapan perangkat atau saat AICore di-uninstal setelah aplikasi Anda diinstal. Mengupdate aplikasi AICore, lalu menginstal ulang aplikasi Anda akan memperbaiki masalah ini.
AICore gagal dengan jenis error 3-PREPARATION_ERROR dan kode error 606-FEATURE_NOT_FOUND: Fitur ... tidak tersedia. Hal ini dapat terjadi saat AICore belum selesai mendownload konfigurasi terbaru. Saat perangkat terhubung ke internet, biasanya perlu waktu beberapa menit hingga beberapa jam untuk melakukan update. Memulai ulang perangkat dapat mempercepat update.

Perhatikan bahwa jika bootloader perangkat tidak terkunci, Anda juga akan melihat error ini—API ini tidak mendukung perangkat dengan bootloader yang tidak terkunci.
AICore gagal dengan jenis error 1-DOWNLOAD_ERROR dan kode error 0-UNKNOWN: Fitur ... gagal dengan status kegagalan 0 dan error esz: UNAVAILABLE: Unable to resolve host ... Pertahankan koneksi jaringan, tunggu beberapa menit, lalu coba lagi.