Identificar o idioma do texto com o Kit de ML no iOS

É possível usar o Kit de ML para identificar o idioma de uma string de texto. É possível verificar o idioma mais provável da string, bem como as pontuações de confiança para todos os idiomas possíveis.

O Kit de ML reconhece texto em mais de 100 idiomas diferentes nos scripts nativos. Além disso, o texto romanizado pode ser reconhecido em árabe, búlgaro, chinês, grego, hindi, japonês e russo. Veja a lista completa de linguagens e scripts compatíveis.

Testar

Antes de começar

  1. Inclua os seguintes pods do Kit de ML no seu Podfile:
    pod 'GoogleMLKit/LanguageID', '3.2.0'
    
  2. Depois de instalar ou atualizar os pods do projeto, abra o projeto Xcode usando o .xcworkspace. O Kit de ML é compatível com a versão 12.4 ou mais recente do Xcode.

Identificar o idioma de uma string

Para identificar o idioma de uma string, acesse uma instância de LanguageIdentification e transmita a string para o método identifyLanguage(for:).

Exemplo:

Swift

let languageId = NaturalLanguage.languageIdentification()

languageId.identifyLanguage(for: text) { (languageCode, error) in
  if let error = error {
    print("Failed with error: \(error)")
    return
  }
  if let languageCode = languageCode, languageCode != "und" {
    print("Identified Language: \(languageCode)")
  } else {
    print("No language was identified")
  }
}

Objective-C

MLKLanguageIdentification *languageId = [MLKLanguageIdentification languageIdentification];

[languageId identifyLanguageForText:text
                         completion:^(NSString * _Nullable languageCode,
                                      NSError * _Nullable error) {
                           if (error != nil) {
                             NSLog(@"Failed with error: %@", error.localizedDescription);
                             return;
                           }
                           if (![languageCode isEqualToString:@"und"] ) {
                             NSLog(@"Identified Language: %@", languageCode);
                           } else {
                             NSLog(@"No language was identified");
                           }
                         }];

Se a chamada for bem-sucedida, um código de idioma BCP-47 (link em inglês) será transmitido para o gerenciador de conclusão, indicando o idioma do texto. Se nenhum idioma puder ser detectado com confiança, o código und (indeterminado) será transmitido.

Por padrão, o Kit de ML retorna um valor diferente de und somente quando identifica o idioma com um valor de confiança de pelo menos 0,5. Para alterar esse limite, transmita um objeto LanguageIdentificationOptions para languageIdentification(options:):

Swift

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.languageIdentification(options: options)

Objective-C

MLKLanguageIdentificationOptions *options =
    [[MLKLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
MLKLanguageIdentification *languageId =
    [MLKLanguageIdentification languageIdentificationWithOptions:options];

Identificar os possíveis idiomas de uma string

Para receber os valores de confiança dos idiomas mais prováveis de uma string, receba uma instância de LanguageIdentification e, em seguida, transmita a string para o método identifyPossibleLanguages(for:).

Exemplo:

Swift

let languageId = NaturalLanguage.languageIdentification()

languageId.identifyPossibleLanguages(for: text) { (identifiedLanguages, error) in
  if let error = error {
    print("Failed with error: \(error)")
    return
  }
  guard let identifiedLanguages = identifiedLanguages,
    !identifiedLanguages.isEmpty,
    identifiedLanguages[0].languageCode != "und"
  else {
    print("No language was identified")
    return
  }

  print("Identified Languages:\n" +
    identifiedLanguages.map {
      String(format: "(%@, %.2f)", $0.languageCode, $0.confidence)
      }.joined(separator: "\n"))
}

Objective-C

MLKLanguageIdentification *languageId = [MLKLanguageIdentification languageIdentification];

[languageId identifyPossibleLanguagesForText:text
                                  completion:^(NSArray * _Nonnull identifiedLanguages,
                                               NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"Failed with error: %@", error.localizedDescription);
    return;
  }
  if (identifiedLanguages.count == 1
      && [identifiedLanguages[0].languageCode isEqualToString:@"und"] ) {
    NSLog(@"No language was identified");
    return;
  }
  NSMutableString *outputText = [NSMutableString stringWithFormat:@"Identified Languages:"];
  for (MLKIdentifiedLanguage *language in identifiedLanguages) {
    [outputText appendFormat:@"\n(%@, %.2f)", language.languageCode, language.confidence];
  }
  NSLog(outputText);
}];

Se a chamada for bem-sucedida, uma lista de objetos IdentifiedLanguage será transmitida para o gerenciador de continuação. Você pode receber o código de idioma BCP-47 de cada objeto e a confiança de que a string está nesse idioma. Observe que esses valores indicam a confiança de que toda a string está no idioma especificado. O Kit de ML não identifica vários idiomas em uma única string.

Por padrão, o Kit de ML retorna apenas idiomas com valores de confiança de pelo menos 0,01. Para alterar esse limite, transmita um objeto LanguageIdentificationOptions para languageIdentification(options:):

Swift

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.languageIdentification(options: options)

Objective-C

MLKLanguageIdentificationOptions *options =
    [[MLKLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
MLKLanguageIdentification *languageId =
    [MLKLanguageIdentification languageIdentificationWithOptions:options];

Se nenhum idioma atingir esse limite, a lista terá um item com o valor und.