חילוץ ישויות באמצעות ערכת ML ב-Android

כדי לנתח קטע טקסט ולחלץ את הישויות שבו, מפעילים את ה-method annotate() ומעבירים לה את מחרוזת הטקסט או את המופע של EntityExtractionParams, שיכול לציין אפשרויות נוספות כמו זמן הפניה, אזור זמן או מסנן להגבלת החיפוש של קבוצת משנה של סוגי ישויות. ה-API מחזיר רשימה של אובייקטים מסוג EntityAnnotation שמכילים מידע על כל ישות.

שם ה-SDKחילוץ ישויות
הטמעההנכסים של המזהה הבסיסי מקושרים לאפליקציה באופן סטטי בזמן ה-build.
ההשפעה של גודל הנכסלחילוץ הישויות יש השפעה על גודל האפליקציה עד כ-5.6MB.

אני רוצה לנסות

לפני שמתחילים

  1. בקובץ build.gradle ברמת הפרויקט, מוודאים שמאגר Maven של Google כלול גם בקטע buildscript וגם בקטע allprojects.
  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 שהוגדר על ידי המשתמש, אחרת הוא ישתמש בברירת המחדל Executor ב-ML Kit

מוודאים שהורדתם למכשיר את המודל הנדרש.

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

אחרי שמוודאים שהמודל הורד, מעבירים את המחרוזת EntityExtractionParams אל annotate(). אל תתקשרו אל 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.
          }
        });

PreferredLocale, ReferenceTime ו-ReferenceTimeZone ישפיעו רק על ישויות מסוג 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);
    }
  }
}

קוראים ל-method close() כשלא צריכים יותר את האובייקט EntityExtractor. אם משתמשים ב-EntityExtractor ב-Fragment או ב-AppCompatActivity, אפשר לקרוא ל-LifecycleOwner.getLifecycle() ב-Fragment או ב-AppCompatActivity, ואז ל-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()). אפשר גם לנהל באופן מפורש את המודלים שרוצים שיהיו זמינים במכשיר באמצעות ממשק ה-API לניהול מודלים של ML Kit. האפשרות הזו יכולה להיות שימושית אם אתם רוצים להוריד מודלים מראש. ה-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.
          }
        });