Identifique o idioma do texto com o ML Kit no iOS

Você pode usar o ML Kit para identificar o idioma de uma sequência de texto. Você pode obter o idioma mais provável da string ou obter pontuações de confiança para todos os idiomas possíveis da string.

O ML Kit reconhece texto em 103 idiomas diferentes em seus scripts nativos. Além disso, o texto romanizado pode ser reconhecido em árabe, búlgaro, chinês, grego, hindi, japonês e russo.

Antes de você começar

  1. Se você ainda não adicionou o Firebase ao seu aplicativo, faça isso seguindo as etapas do guia de primeiros passos .
  2. Inclua as bibliotecas do ML Kit em seu Podfile:
    pod 'Firebase/MLNaturalLanguage', '6.25.0'
    pod 'Firebase/MLNLLanguageID', '6.25.0'
    
    Depois de instalar ou atualizar os pods do seu projeto, certifique-se de abrir seu projeto Xcode usando seu .xcworkspace .
  3. No seu aplicativo, importe o Firebase:
    import Firebase
    @import Firebase;

Identifique o idioma de uma string

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

Por exemplo:

let languageId = NaturalLanguage.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")
 
}
}
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];

[languageId identifyLanguageForText:text
                         completion
:^(NSString * _Nullable languageCode,
                                     
NSError * _Nullable error) {
                           
if (error != nil) {
                             
NSLog(@"Failed with error: %@", error.localizedDescription);
                             
return;
                           
}
                           
if (languageCode != nil
                               
&& ![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 será passado para o manipulador de conclusão, indicando o idioma do texto. Veja a lista completa de idiomas suportados . Se nenhum idioma puder ser detectado com segurança, o código und (indeterminado) será passado.

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

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentificationOptions *options =
   
[[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
FIRLanguageIdentification *languageId =
   
[naturalLanguage languageIdentificationWithOptions:options];

Obtenha os idiomas possíveis de uma string

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

Por exemplo:

let languageId = NaturalLanguage.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"))
}
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];

[languageId identifyPossibleLanguagesForText:text
                                  completion
:^(NSArray<FIRIdentifiedLanguage *> * _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 (FIRIdentifiedLanguage *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á passada para o manipulador de continuação. De cada objeto, você pode obter o código BCP-47 da linguagem e a confiança de que a string está nessa linguagem. Veja a lista completa de idiomas suportados . Observe que esses valores indicam a confiança de que toda a string está no idioma determinado; O Kit de ML não identifica vários idiomas em uma única string.

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

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentificationOptions *options =
   
[[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
FIRLanguageIdentification *languageId =
   
[naturalLanguage languageIdentificationWithOptions:options];

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