Mengekstrak entity dengan ML Kit di Android

Untuk menganalisis potongan teks dan mengekstrak entitas di dalamnya, panggil metode annotate() dan teruskan string teks atau instance EntityExtractionParams yang dapat menentukan opsi tambahan seperti waktu referensi, zona waktu, atau filter untuk membatasi penelusuran untuk sebagian jenis entitas. API menampilkan daftar objek EntityAnnotation yang berisi informasi tentang setiap entity.

Nama SDKentity-extraction
PenerapanAset untuk pendeteksi dasar ditautkan secara statis ke aplikasi Anda pada waktu build.
Dampak Ukuran AsetEkstraksi entitas memiliki dampak ukuran aplikasi hingga ~5,6 MB.

Cobalah

Sebelum memulai

  1. Dalam file build.gradle level project, pastikan repositori Maven Google disertakan di bagian buildscript dan allprojects.
  2. Tambahkan dependensi untuk library ekstraksi entitas ML Kit ke file gradle level aplikasi modul Anda, yang biasanya bernama app/build.gradle:

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

Mengekstrak entity

Buat objek EntityExtractor, lalu konfigurasikan dengan EntityExtractorOptions

Kotlin

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

Java

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

EntityExtractorOptions juga menerima Executor yang ditentukan pengguna jika Anda memerlukannya. Jika tidak, Executor default akan digunakan di ML Kit

Pastikan model yang diperlukan telah didownload ke perangkat.

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.
        });

Setelah Anda mengonfirmasi bahwa model telah didownload, teruskan string atau EntityExtractionParams ke annotate(). Jangan panggil annotate() sebelum Anda mengetahui ketersediaan model tersebut.

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.
          }
        });

PreferredLocale, ReferenceTime, dan ReferenceTimeZone hanya akan memengaruhi entity DateTime. Jika tidak ditetapkan secara eksplisit, nilai ini akan ditetapkan secara default ke nilai dari perangkat pengguna.

Lakukan loop pada hasil anotasi untuk mengambil informasi tentang entitas yang dikenali.

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

Panggil metode close() saat Anda tidak lagi memerlukan objek EntityExtractor. Jika menggunakan EntityExtractor di Fragment atau AppCompatActivity, Anda dapat memanggil LifecycleOwner.getLifecycle() di Fragment atau AppCompatActivity, lalu Lifecycle.addObserver. Contoh:

Kotlin

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

Java

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

Mengelola model ekstraksi entity secara eksplisit

Saat Anda menggunakan API ekstraksi entitas seperti yang dijelaskan di atas, ML Kit akan otomatis mendownload model khusus bahasa ke perangkat sesuai kebutuhan (saat Anda memanggil downloadModelIfNeeded()). Anda juga dapat secara eksplisit mengelola model yang Anda inginkan agar tersedia di perangkat menggunakan API pengelolaan model ML Kit. Hal ini berguna jika Anda ingin mendownload model lebih awal. API ini juga memungkinkan Anda menghapus model yang tidak lagi diperlukan.

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.
          }
        });