在 Android 上使用 ML Kit 擷取實體

如要分析一段文字並擷取當中的實體,請叫用 annotate() 方法,並將文字字串或 EntityExtractionParams,可指定其他選項,例如 參照時間、時區或篩選器,用於限制搜尋部分實體 。API 會傳回 EntityAnnotation 物件清單,其中包含 有關每個實體的資訊

SDK 名稱實體擷取
導入作業基本偵測工具資產會在建構期間以靜態方式連結至您的應用程式。
素材資源大小影響實體擷取作業對應用程式大小的影響上限為 5.6 MB。

立即試用

事前準備

  1. 在專案層級的 build.gradle 檔案中,確認 buildscript 與所有專案部分都包含 Google 的 Maven 存放區。
  2. 將 ML Kit 實體擷取程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案,通常命名為 app/build.gradle

    dependencies {
    // …
    
    implementation 'com.google.mlkit:entity-extraction:16.0.0-beta5'
    }
    

擷取實體

建立 EntityExtractor 物件,並使用 EntityExtractorOptions 進行設定

Kotlin

val entityExtractor =
   EntityExtraction.getClient(
       EntityExtractorOptions.Builder(EntityExtractorOptions.ENGLISH)
           .build())

Java

EntityExtractor entityExtractor =
        EntityExtraction.getClient(
            new EntityExtractorOptions.Builder(EntityExtractorOptions.ENGLISH)
                .build());

EntityExtractorOptions 也會視需要接受使用者定義的 Executor,否則會在 ML Kit 中使用預設的 Executor

確認所需模型已下載到裝置。

Kotlin

entityExtractor
  .downloadModelIfNeeded()
  .addOnSuccessListener { _ ->
    /* Model downloading succeeded, you can call extraction API here. */
  }
  .addOnFailureListener { _ -> /* Model downloading failed. */ }

Java

entityExtractor
    .downloadModelIfNeeded()
    .addOnSuccessListener(
        aVoid -> {
          // Model downloading succeeded, you can call the extraction API here. 
        })
    .addOnFailureListener(
        exception -> {
          // Model downloading failed.
        });

確認已下載模型後,請傳送字串或 EntityExtractionParamsannotate()。 確認模型可供使用前,請勿呼叫 annotate()

Kotlin

val params =
      EntityExtractionParams.Builder("My flight is LX373, please pick me up at 8am tomorrow.")
        .setEntityTypesFilter((/* optional entity type filter */)
        .setPreferredLocale(/* optional preferred locale */)
        .setReferenceTime(/* optional reference date-time */)
        .setReferenceTimeZone(/* optional reference timezone */)
        .build()
entityExtractor
      .annotate(params)
      .addOnSuccessListener {
        // Annotation process was successful, you can parse the EntityAnnotations list here.
      }
      .addOnFailureListener {
        // Check failure message here.
      }

Java

EntityExtractionParams params = new EntityExtractionParams
        .Builder("My flight is LX373, please pick me up at 8am tomorrow.")
        .setEntityTypesFilter(/* optional entity type filter */)
        .setPreferredLocale(/* optional preferred locale */)
        .setReferenceTime(/* optional reference date-time */)
        .setReferenceTimeZone(/* optional reference timezone */)
        .build();
entityExtractor
        .annotate(params)
        .addOnSuccessListener(new OnSuccessListener<List<EntityAnnotation>>() {
          @Override
          public void onSuccess(List<EntityAnnotation> entityAnnotations) {
            // Annotation process was successful, you can parse the EntityAnnotations list here.
          }
        })
        .addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // Check failure message here.
          }
        });

PreferredLocaleReferenceTimeReferenceTimeZone只會影響 DateTime 實體。如果沒有明確設定這些變數,值就會預設為 使用者的裝置。

循環處理註解結果,以擷取 或辨識實體

Kotlin

for (entityAnnotation in entityAnnotations) {
  val entities: List<Entity> = entityAnnotation.entities

  Log.d(TAG, "Range: ${entityAnnotation.start} - ${entityAnnotation.end}")
  for (entity in entities) {
    when (entity) {
      is DateTimeEntity -> {
        Log.d(TAG, "Granularity: ${entity.dateTimeGranularity}")
        Log.d(TAG, "TimeStamp: ${entity.timestampMillis}")
      }
      is FlightNumberEntity -> {
        Log.d(TAG, "Airline Code: ${entity.airlineCode}")
        Log.d(TAG, "Flight number: ${entity.flightNumber}")
      }
      is MoneyEntity -> {
        Log.d(TAG, "Currency: ${entity.unnormalizedCurrency}")
        Log.d(TAG, "Integer part: ${entity.integerPart}")
        Log.d(TAG, "Fractional Part: ${entity.fractionalPart}")
      }
      else -> {
        Log.d(TAG, "  $entity")
      }
    }
  }
}

Java

List<EntityAnnotation> entityAnnotations = /* Get from EntityExtractor */;
for (EntityAnnotation entityAnnotation : entityAnnotations) {
  List<Entity> entities = entityAnnotation.getEntities();

  Log.d(TAG, String.format("Range: [%d, %d)", entityAnnotation.getStart(), entityAnnotation.getEnd()));
  for (Entity entity : entities) {
    switch (entity.getType()) {
      case Entity.TYPE_DATE_TIME:
        DateTimeEntity dateTimeEntity = entity.asDateTimeEntity();
        Log.d(TAG, "Granularity: " + dateTimeEntity.getDateTimeGranularity());
        Log.d(TAG, "Timestamp: " + dateTimeEntity.getTimestampMillis());
      case Entity.TYPE_FLIGHT_NUMBER:
        FlightNumberEntity flightNumberEntity = entity.asFlightNumberEntity();
        Log.d(TAG, "Airline Code: " + flightNumberEntity.getAirlineCode());
        Log.d(TAG, "Flight number: " + flightNumberEntity.getFlightNumber());
      case Entity.TYPE_MONEY:
        MoneyEntity moneyEntity = entity.asMoneyEntity();
        Log.d(TAG, "Currency: " + moneyEntity.getUnnormalizedCurrency());
        Log.d(TAG, "Integer Part: " + moneyEntity.getIntegerPart());
        Log.d(TAG, "Fractional Part: " + moneyEntity.getFractionalPart());
      case Entity.TYPE_UNKNOWN:
      default:
        Log.d(TAG, "Entity: " + entity);
    }
  }
}

不再需要 EntityExtractor 物件時,請呼叫 close() 方法。如果您在 Fragment 或 AppCompatActivity 中使用 EntityExtractor,可以針對 Fragment 或 AppCompatActivity 呼叫 LifecycleOwner.getLifecycle(),然後輕觸 Lifecycle.addObserver。例如:

Kotlin

val options = 
val extractor = EntityExtraction.getClient(options);
getLifecycle().addObserver(extractor);

Java

EntityExtractorOptions options = 
EntityExtractor extractor = EntityExtraction.getClient(options);
getLifecycle().addObserver(extractor);

明確管理實體擷取模型

按照上述方式使用實體擷取 API 時,ML Kit 會視需要自動將特定語言模型下載至裝置 (當您呼叫 downloadModelIfNeeded() 時)。你也可以使用 ML Kit 的 Model Management API,明確管理要在裝置上使用的模型。如要預先下載模型,這項功能就能派上用場。這個 API 也能讓您刪除不再需要的模型。

Kotlin

val modelManager = RemoteModelManager.getInstance()

// Get entity extraction models stored on the device.
modelManager.getDownloadedModels(EntityExtractionRemoteModel::class.java)
  .addOnSuccessListener {
    // ...
  }
  .addOnFailureListener({
    // Error.
  })
    
// Delete the German model if it's on the device.
val germanModel =
  EntityExtractionRemoteModel.Builder(EntityExtractorOptions.GERMAN).build()
modelManager.deleteDownloadedModel(germanModel)
  .addOnSuccessListener({
    // Model deleted.
  })
  .addOnFailureListener({
    // Error.
  })
    
// Download the French model.
val frenchModel =
  EntityExtractionRemoteModel.Builder(EntityExtractorOptions.FRENCH).build()
val conditions =
  DownloadConditions.Builder()
    .requireWifi()
    .build()
modelManager.download(frenchModel, conditions)
  .addOnSuccessListener({
    // Model downloaded.
  })
  .addOnFailureListener({
    // Error.
  })

Java

// Get entity extraction models stored on the device.
modelManager.getDownloadedModels(EntityExtractionRemoteModel.class)
    .addOnSuccessListener(new OnSuccessListener<Set<EntityExtractionRemoteModel>>() {
      @Override
      public void onSuccess(Set<EntityExtractionRemoteModel> models) {
        // ...
      }
    })
    .addOnFailureListener(new OnFailureListener() {
      @Override
      public void onFailure(@NonNull Exception e) {
        // Error.
      }
    });

// Delete the German model if it's on the device.
EntityExtractionRemoteModel germanModel = new EntityExtractionRemoteModel.Builder(EntityExtractorOptions.GERMAN).build();
    modelManager.deleteDownloadedModel(germanModel)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
          @Override
          public void onSuccess(Void v) {
            // Model deleted.
          }
        })
        .addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // Error.
          }
        });

// Download the French model.
EntityExtractionRemoteModel frenchModel = new EntityExtractionRemoteModel.Builder(EntityExtractorOptions.FRENCH).build();
    DownloadConditions conditions = new DownloadConditions.Builder()
        .requireWifi()
        .build();
    modelManager.download(frenchModel, conditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
          @Override
          public void onSuccess(Void v) {
            // Model downloaded.
          }
        })
        .addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // Error.
          }
        });