Tłumaczenie tekstu za pomocą ML Kit na iOS

Do tłumaczenia tekstu między językami możesz używać pakietu ML Kit. ML Kit obsługuje obecnie tłumaczenie między 59 językami.

Zanim zaczniesz

  1. Jeśli nie masz jeszcze dodanej usługi Firebase do swojej aplikacji, wykonaj czynności opisane we wprowadzeniu.
  2. Dodaj biblioteki ML Kit do pliku Podfile:
    pod 'Firebase/MLNLTranslate', '6.25.0'
    
    Po zainstalowaniu lub zaktualizowaniu podów projektu pamiętaj, aby otworzyć projekt Xcode za pomocą pliku .xcworkspace.
  3. W aplikacji zaimportuj Firebase:

    Swift

    import Firebase

    Objective-C

    @import Firebase;

Tłumaczenie ciągu tekstowego

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

  1. Utwórz obiekt Translator, konfigurując go z językami źródłowymi i docelowymi:

    Swift

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

    Objective-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 wpisanego tekstu, możesz najpierw skorzystać z interfejsu languageidentification API. (Sprawdź jednak, czy nie masz na urządzeniu zbyt wielu modeli językowych jednocześnie).

  2. Upewnij się, że wymagany model tłumaczenia został pobrany na urządzenie. Nie dzwoń pod numer translate(_:completion:), dopóki nie upewnisz się, że model jest dostępny.

    Swift

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

    Objective-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 mają około 30 MB, więc nie pobieraj ich niepotrzebnie i pobieraj tylko przez Wi-Fi, chyba że użytkownik określi inaczej. Należy też usunąć niepotrzebne modele. Zobacz Bezpośrednie zarządzanie modelami tłumaczenia.

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

    Swift

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

    Objective-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 przez Ciebie język docelowy i przekazuje przetłumaczony tekst do modułu obsługi uzupełniania.

Bezpośrednie zarządzanie modelami translacji

Jeśli używasz interfejsu Translation API w sposób opisany powyżej, ML Kit automatycznie pobiera do urządzenia modele tłumaczenia w konkretnym języku. Możesz też bezpośrednio zarządzać modelami translacji, które mają być dostępne na urządzeniu, za pomocą interfejsu ML Kit do zarządzania modelami modeli. Jest to przydatne, jeśli chcesz pobrać modele z wyprzedzeniem lub usunąć z urządzenia niepotrzebne modele.

Aby pobrać modele tłumaczenia zapisane na urządzeniu:

Swift

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

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

Aby usunąć model:

Swift

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

Objective-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:

Swift

// 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ć stan pobierania w usłudze NotificationCenter, zarejestruj obserwatorzy usługi firebaseMLModelDownloadDidSucceed i firebaseMLModelDownloadDidFail. Pamiętaj, aby w bloku obserwatora używać słabego odniesienia do self, ponieważ pobieranie może trochę potrwać, a obiekt źródłowy może zostać uwolniony przed zakończeniem. 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]
    // ...
}

Objective-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ć stan pobierania w usłudze NSNotificationCenter, zarejestruj obserwatorzy usługi FIRModelDownloadDidSucceedNotification i FIRModelDownloadDidFailNotification. Pamiętaj, aby w bloku obserwatora używać słabego odniesienia do self, ponieważ pobieranie może trochę potrwać, a obiekt źródłowy może zostać zwolniony do 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];
 }];