استخراج عناصر با ML Kit در Android

برای تجزیه‌وتحلیل یک قطعه نوشتار و استخراج نهادهای موجود در آن، روش annotate() را فراخوانی کنید و رشته نوشتار یا نمونه‌ای از EntityExtractionParams را به آن ارسال کنید که می‌تواند گزینه‌های اضافی مثل زمان مرجع، منطقه زمانی، یا فیلتری را برای محدود کردن جستجو برای زیرمجموعه‌ای از انواع نهاد مشخص کند. این API فهرستی از EntityAnnotation شیء برمی‌گرداند که حاوی اطلاعاتی درباره هر نهاد است.

نام کیت توسعه نرم‌افزاراستخراج نهاد
پیاده‌سازیدارایی‌های آشکارساز پایه در زمان ساخت به‌صورت ایستا به برنامه‌تان پیوند داده می‌شوند.
تأثیر اندازه داراییاستخراج نهاد تأثیری تا حدود ۵٫۶ مگابایت بر اندازه برنامه دارد.

امتحان کنید

  • با برنامه نمونه بازی کنید تا نمونه‌ای از استفاده از این API را ببینید.

قبل‌از شروع

  1. در فایل build.gradle سطح پروژه، مطمئن شوید که مخزن Maven در Google در هر دو بخش buildscript و allprojects اضافه شده باشد.
  2. وابستگی کتابخانه استخراج نهاد ML Kit را به فایل gradle سطح برنامه واحدتان اضافه کنید، که معمولاً app/build.gradle نام دارد:

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

استخراج نهادها

شیء EntityExtractor را ایجاد کنید و آن را با EntityExtractorOptions پیکربندی کنید

Kotlin

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

جاوا

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. */ }

جاوا

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

جاوا

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 فقط بر نهادهای «تاریخ و زمان» تأثیر می‌گذارند. اگر این موارد به‌طور صریح تنظیم نشده باشند، به‌طور پیش‌فرض از مقادیر دستگاه کاربر استفاده می‌کنند.

برای بازیابی اطلاعات درباره نهادهای تشخیص‌داده‌شده، روی نتایج گزارمان حلقه بزنید.

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

جاوا

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() را فراخوانی کنید. اگر از EntityExtractor در Fragment یا AppCompatActivity استفاده می‌کنید، می‌توانید LifecycleOwner.getLifecycle() را در Fragment یا AppCompatActivity و سپس Lifecycle.addObserver را فراخوانی کنید. برای مثال:

Kotlin

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

جاوا

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

مدیریت صریح مدل‌های استخراج نهاد

وقتی از Entity Extraction API به‌صورتی که در بالا شرح داده شد استفاده می‌کنید، ML Kit به‌طور خودکار مدل‌های خاص زبان را درصورت نیاز به دستگاه بارگیری می‌کند (وقتی downloadModelIfNeeded() را فراخوانی می‌کنید). همچنین می‌توانید بااستفاده از Model Management API در ML Kit، مدل‌هایی را که می‌خواهید در دستگاه دردسترس باشد به‌طور صریح مدیریت کنید. این کار می‌تواند درصورتی‌که بخواهید مدل‌ها را ازقبل بارگیری کنید مفید باشد. این «میانای برنامه‌سازی کاربردی» همچنین به شما امکان می‌دهد مدل‌هایی را که دیگر موردنیاز نیستند حذف کنید.

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

جاوا

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