iOS에서 ML Kit를 사용하여 항목 추출

<ph type="x-smartling-placeholder">

텍스트를 분석하여 항목에 있는 경우, 다음 값을 전달하여 ML Kit 항목 추출 API를 호출합니다. 텍스트를 annotateText:completion: 메서드에 직접 추가할 수 있습니다. 또한 다른 EntityExtractionParams 객체를 포함하고 있는 구성 옵션(참조 시간, 시간대, 항목 유형의 하위 집합에 대한 검색을 제한하는 필터 API는 각 항목에 대한 정보가 포함된 EntityAnnotation 객체의 목록을 반환합니다.

항목 추출 기본 감지기 애셋은 앱 런타임 시 정적으로 연결됩니다. 앱에 약 10.7MB가 추가됩니다.

사용해 보기

  • 샘플 앱을 사용하여 이 API의 사용 예를 참조하세요.

시작하기 전에

  1. Podfile에 다음 ML Kit 라이브러리를 포함합니다.

    pod 'GoogleMLKit/EntityExtraction', '3.2.0'
    
  2. 프로젝트의 포드를 설치하거나 업데이트한 후 .xcworkspace를 사용하여 Xcode 프로젝트를 엽니다. ML Kit는 Xcode 버전 13.2.1 이상에서 지원됩니다.

텍스트에서 항목 추출

텍스트에서 항목을 추출하려면 먼저 언어를 지정하여 EntityExtractorOptions 객체를 만들고 이를 사용하여 EntityExtractor를 인스턴스화합니다.

Swift

// Note: You can specify any of the 15 languages entity extraction supports here. 
let options = EntityExtractorOptions(modelIdentifier: 
                                    EntityExtractionModelIdentifier.english)
let entityExtractor = EntityExtractor.entityExtractor(options: options)

Objective-C

// Note: You can specify any of the 15 languages entity extraction supports here. 
MLKEntityExtractorOptions *options = 
    [[MLKEntityExtractorOptions alloc] 
        initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish];

MLKEntityExtractor *entityExtractor = 
    [MLKEntityExtractor entityExtractorWithOptions:options];

그런 다음 필요한 언어 모델이 기기에 다운로드되었는지 확인합니다.

Swift

entityExtractor.downloadModelIfNeeded(completion: {
  // If the error is nil, the download completed successfully.
})

Objective-C

[entityExtractor downloadModelIfNeededWithCompletion:^(NSError *_Nullable error) {
    // If the error is nil, the download completed successfully.
}];

모델이 다운로드되었으면 문자열과 선택적 MLKEntityExtractionParamsannotate 메서드에 추가합니다.

Swift

// The EntityExtractionParams parameter is optional. Only instantiate and
// configure one if you need to customize one or more of its params.
var params = EntityExtractionParams()
// The params object contains the following properties which can be customized on
// each annotateText: call. Please see the class's documentation for a more
// detailed description of what each property represents.
params.referenceTime = Date();
params.referenceTimeZone = TimeZone(identifier: "GMT");
params.preferredLocale = Locale(identifier: "en-US");
params.typesFilter = Set([EntityType.address, EntityType.dateTime])

extractor.annotateText(
    text.string,
    params: params,
    completion: {
      result, error in
      // If the error is nil, the annotation completed successfully and any results 
      // will be contained in the `result` array.
    }
)

Objective-C

// The MLKEntityExtractionParams property is optional. Only instantiate and
// configure one if you need to customize one or more of its params.
MLKEntityExtractionParams *params = [[MLKEntityExtractionParams alloc] init];
// The params object contains the following properties which can be customized on
// each annotateText: call. Please see the class's documentation for a fuller 
// description of what each property represents.
params.referenceTime = [NSDate date];
params.referenceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
params.preferredLocale = [NSLocale localWithLocaleIdentifier:@"en-US"];
params.typesFilter = 
    [NSSet setWithObjects:MLKEntityExtractionEntityTypeAddress, 
                          MLKEntityExtractionEntityTypeDateTime, nil];

[extractor annotateText:text.string
             withParams:params
             completion:^(NSArray *_Nullable result, NSError *_Nullable error) {
  // If the error is nil, the annotation completed successfully and any results 
  // will be contained in the `result` array.
}

주석 결과를 루프 처리하여 다음에 대한 정보를 검색합니다. 인식할 수 있습니다.

Swift

// let annotations be the Array! returned from EntityExtractor
for annotation in annotations {
  let entities = annotation.entities
  for entity in entities {
    switch entity.entityType {
      case EntityType.dateTime:
        guard let dateTimeEntity = entity.dateTimeEntity else {
          print("This field should be populated.")
          return
        }
        print("Granularity: %d", dateTimeEntity.dateTimeGranularity)
        print("DateTime: %@", dateTimeEntity.dateTime)
      case EntityType.flightNumber:
        guard let flightNumberEntity = entity.flightNumberEntity else {
          print("This field should be populated.")
          return
        }
        print("Airline Code: %@", flightNumberEntity.airlineCode)
        print("Flight number: %@", flightNumberEntity.flightNumber)
      case EntityType.money:
        guard let moneyEntity = entity.moneyEntity else {
          print("This field should be populated.")
          return
        }
        print("Currency: %@", moneyEntity.integerPart)
        print("Integer Part: %d", moneyEntity.integerPart)
        print("Fractional Part: %d", moneyEntity.fractionalPart)
      // Add additional cases as needed.
      default:
        print("Entity: %@", entity);
    }
  }
}

Objective-C

NSArray *annotations; // Returned from EntityExtractor

for (MLKEntityAnnotation *annotation in annotations) {
            NSArray *entities = annotation.entities;
            NSLog(@"Range: [%d, %d)", (int)annotation.range.location, (int)(annotation.range.location + annotation.range.length));
            for (MLKEntity *entity in entities) {
              if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeDateTime]) {
                MLKDateTimeEntity *dateTimeEntity = entity.dateTimeEntity;
                NSLog(@"Granularity: %d", (int)dateTimeEntity.dateTimeGranularity);
                NSLog(@"DateTime: %@", dateTimeEntity.dateTime);
                break;
              } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeFlightNumber]) {
                MLKFlightNumberEntity *flightNumberEntity = entity.flightNumberEntity;
                NSLog(@"Airline Code: %@", flightNumberEntity.airlineCode);
                NSLog(@"Flight number: %@", flightNumberEntity.flightNumber);
                break;
              } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeMoney]) {
                MLKMoneyEntity *moneyEntity = entity.moneyEntity;
                NSLog(@"Currency: %@", moneyEntity.unnormalizedCurrency);
                NSLog(@"Integer Part: %d", (int)moneyEntity.integerPart);
                NSLog(@"Fractional Part: %d", (int)moneyEntity.fractionalPart);
                break;
              } else {
                // Add additional cases as needed.
                NSLog(@"Entity: %@", entity);
              }
            }