Tłumaczenie tekstu za pomocą ML Kit na iOS

Możesz użyć ML Kit do tłumaczenia tekstu między językami. ML Kit obecnie obsługuje tłumaczenie pomiędzy 59 językami .

Zanim zaczniesz

  1. Jeśli nie dodałeś jeszcze Firebase do swojej aplikacji, zrób to, wykonując czynności opisane w przewodniku wprowadzającym .
  2. Dołącz biblioteki ML Kit do swojego Podfile:
    pod 'Firebase/MLNLTranslate', '6.25.0'
    
    Po zainstalowaniu lub zaktualizowaniu Podów swojego projektu pamiętaj o otwarciu projektu Xcode przy użyciu jego .xcworkspace .
  3. W swojej aplikacji zaimportuj Firebase:

    Szybki

    import Firebase

    Cel C

    @import Firebase;

Przetłumacz ciąg tekstu

Aby przetłumaczyć ciąg znaków między dwoma językami:

  1. Utwórz obiekt Translator , konfigurując go za pomocą języka źródłowego i docelowego:

    Szybki

    // Create an English-German translator:
    let options = TranslatorOptions(sourceLanguage: .en, targetLanguage: .de)
    let englishGermanTranslator = NaturalLanguage.naturalLanguage().translator(options: options)
    

    Cel C

    // Create an English-German translator:
    FIRTranslatorOptions *options =
        [[FIRTranslatorOptions alloc] initWithSourceLanguage:FIRTranslateLanguageEN
                                              targetLanguage:FIRTranslateLanguageDE];
    FIRTranslator *englishGermanTranslator =
        [[FIRNaturalLanguage naturalLanguage] translatorWithOptions:options];
    

    Jeśli nie znasz języka tekstu wejściowego, możesz najpierw skorzystać z interfejsu API identyfikacji języka . (Upewnij się jednak, że nie przechowujesz na urządzeniu zbyt wielu modeli językowych jednocześnie.)

  2. Upewnij się, że wymagany model tłumaczenia został pobrany na urządzenie. Nie wywołuj translate(_:completion:) dopóki nie będziesz pewien, że model jest dostępny.

    Szybki

    let conditions = ModelDownloadConditions(
        allowsCellularAccess: false,
        allowsBackgroundDownloading: true
    )
    englishGermanTranslator.downloadModelIfNeeded(with: conditions) { error in
        guard error == nil else { return }
    
        // Model downloaded successfully. Okay to start translating.
    }
    

    Cel C

    FIRModelDownloadConditions *conditions =
        [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                             allowsBackgroundDownloading:YES];
    [englishGermanTranslator downloadModelIfNeededWithConditions:conditions
                                                      completion:^(NSError *_Nullable error) {
      if (error != nil) {
        return;
      }
      // Model downloaded successfully. Okay to start translating.
    }];
    

    Modele językowe zajmują około 30 MB, więc nie pobieraj ich niepotrzebnie, a pobieraj je tylko za pomocą Wi-Fi, chyba że użytkownik określił inaczej. Powinieneś także usunąć niepotrzebne modele. Zobacz Jawne zarządzanie modelami tłumaczeń .

  3. Po potwierdzeniu, że model został pobrany, przekaż ciąg tekstu w języku źródłowym do translate(_:completion:) :

    Szybki

    englishGermanTranslator.translate(text) { translatedText, error in
        guard error == nil, let translatedText = translatedText else { return }
    
        // Translation succeeded.
    }
    

    Cel C

    [englishGermanTranslator translateText:text
                                completion:^(NSString *_Nullable translatedText,
                                             NSError *_Nullable error) {
      if (error != nil || translatedText == nil) {
        return;
      }
    
      // Translation succeeded.
    }];
    

    ML Kit tłumaczy tekst na skonfigurowany język docelowy i przekazuje przetłumaczony tekst do modułu obsługi uzupełniania.

Jawnie zarządzaj modelami tłumaczeń

Gdy korzystasz z interfejsu API tłumaczeń w sposób opisany powyżej, ML Kit automatycznie pobiera na urządzenie modele tłumaczeń specyficzne dla języka, zgodnie z wymaganiami. Możesz także jawnie zarządzać modelami tłumaczeń, które chcesz udostępnić na urządzeniu, korzystając z interfejsu API zarządzania modelami tłumaczeń ML Kit. Może to być przydatne, jeśli chcesz pobrać modele z wyprzedzeniem lub usunąć niepotrzebne modele z urządzenia.

Aby zapisać modele tłumaczeń na urządzeniu:

Szybki

let localModels = ModelManager.modelManager().downloadedTranslateModels

Cel C

NSSet<FIRTranslateRemoteModel *> *localModels =
    [FIRModelManager modelManager].downloadedTranslateModels;

Aby usunąć model:

Szybki

// Delete the German model if it's on the device.
let deModel = TranslateRemoteModel.translateRemoteModel(language: .de)
ModelManager.modelManager().deleteDownloadedModel(deModel) { error in
    guard error == nil else { return }
    // Model deleted.
}

Cel C

// Delete the German model if it's on the device.
FIRTranslateRemoteModel *deModel =
    [FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageDE];
[[FIRModelManager modelManager] deleteDownloadedModel:deModel
                                           completion:^(NSError * _Nullable error) {
                                               if (error != nil) {
                                                   return;
                                               }
                                               // Model deleted.
                                           }];

Aby pobrać model:

Szybki

// Download the French model.
let frModel = TranslateRemoteModel.translateRemoteModel(language: .fr)

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
progress = ModelManager.modelManager().download(
    frModel,
    conditions: ModelDownloadConditions(
        allowsCellularAccess: false,
        allowsBackgroundDownloading: true
    )
)

Jeśli chcesz uzyskać status pobierania za pomocą NotificationCenter , zarejestruj obserwatorów dla firebaseMLModelDownloadDidSucceed i firebaseMLModelDownloadDidFail . Pamiętaj, aby użyć słabego odniesienia do self w bloku obserwatora, ponieważ pobieranie może zająć trochę czasu, a obiekt źródłowy może zostać zwolniony do czasu zakończenia pobierania. Na przykład:

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidSucceed,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? TranslateRemoteModel,
        model == frModel
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidFail,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? TranslateRemoteModel
        else { return }
    let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
    // ...
}

Cel C

// Download the French model.
FIRModelDownloadConditions *conditions =
    [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                         allowsBackgroundDownloading:YES];
FIRTranslateRemoteModel *frModel =
    [FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageFR];

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
self.downloadProgress = [[FIRModelManager modelManager] downloadModel:frModel
                                                           conditions:conditions];

Jeśli chcesz uzyskać status pobierania za pomocą NSNotificationCenter , zarejestruj obserwatorów dla FIRModelDownloadDidSucceedNotification i FIRModelDownloadDidFailNotification . Pamiętaj, aby użyć słabego odniesienia do self w bloku obserwatora, ponieważ pobieranie może zająć trochę czasu, a obiekt źródłowy może zostać zwolniony do czasu zakończenia pobierania.

__block MyViewController *weakSelf = self;

[NSNotificationCenter.defaultCenter
 addObserverForName:FIRModelDownloadDidSucceedNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     FIRTranslateRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];
     if ([model isKindOfClass:[FIRTranslateRemoteModel class]]
         && model == frModel) {
         // The model was downloaded and is available on the device
     }
 }];

[NSNotificationCenter.defaultCenter
 addObserverForName:FIRModelDownloadDidFailNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError];
 }];