แปลข้อความด้วย ML Kit ใน iOS

คุณสามารถใช้ ML Kit เพื่อแปลข้อความระหว่างภาษาต่างๆ ได้ ปัจจุบัน ML Kit รองรับการแปลระหว่าง 59 ภาษา

ก่อนที่คุณจะเริ่ม

  1. หากคุณยังไม่ได้เพิ่ม Firebase ลงในแอปของคุณ ให้ทำตามขั้นตอนใน คู่มือการเริ่มต้นใช้งาน
  2. รวมไลบรารี ML Kit ไว้ใน Podfile ของคุณ:
    pod 'Firebase/MLNLTranslate', '6.25.0'
    
    หลังจากที่คุณติดตั้งหรืออัปเดต Pod ของโปรเจ็กต์แล้ว อย่าลืมเปิดโปรเจ็กต์ Xcode โดยใช้ .xcworkspace
  3. ในแอปของคุณ ให้นำเข้า Firebase:

    สวิฟท์

    import Firebase

    วัตถุประสงค์-C

    @import Firebase;

แปลสตริงข้อความ

หากต้องการแปลสตริงระหว่างสองภาษา:

  1. สร้างวัตถุ Translator กำหนดค่าด้วยภาษาต้นฉบับและภาษาเป้าหมาย:

    สวิฟท์

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

    วัตถุประสงค์-C

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

    หากคุณไม่ทราบภาษาของข้อความที่ป้อน คุณสามารถใช้ API การระบุภาษา ก่อนได้ (แต่ต้องแน่ใจว่าคุณไม่ได้เก็บโมเดลภาษาไว้มากเกินไปในอุปกรณ์ในคราวเดียว)

  2. ตรวจสอบให้แน่ใจว่าได้ดาวน์โหลดโมเดลการแปลที่จำเป็นลงในอุปกรณ์แล้ว อย่าเรียก translate(_:completion:) จนกว่าคุณจะรู้ว่ามีโมเดลนี้อยู่

    สวิฟท์

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

    วัตถุประสงค์-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.
    }];
    

    โมเดลภาษามีขนาดประมาณ 30MB ดังนั้นอย่าดาวน์โหลดโดยไม่จำเป็น และดาวน์โหลดโดยใช้ WiFi เท่านั้น เว้นแต่ผู้ใช้จะระบุไว้เป็นอย่างอื่น คุณควรลบโมเดลที่ไม่จำเป็นออกด้วย ดู จัดการโมเดลการแปลอย่างชัดเจน

  3. หลังจากที่คุณยืนยันว่าดาวน์โหลดโมเดลแล้ว ให้ส่งสตริงข้อความในภาษาต้นฉบับเพื่อ translate(_:completion:) :

    สวิฟท์

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

    วัตถุประสงค์-C

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

    ML Kit แปลข้อความเป็นภาษาเป้าหมายที่คุณกำหนดค่า และส่งข้อความที่แปลแล้วไปยังตัวจัดการการเสร็จสิ้น

จัดการโมเดลการแปลอย่างชัดเจน

เมื่อคุณใช้ API การแปลตามที่อธิบายไว้ข้างต้น ML Kit จะดาวน์โหลดโมเดลการแปลเฉพาะภาษาไปยังอุปกรณ์โดยอัตโนมัติตามต้องการ คุณยังสามารถจัดการโมเดลการแปลที่คุณต้องการให้ใช้งานได้บนอุปกรณ์ได้อย่างชัดเจนโดยใช้ API การจัดการโมเดลการแปลของ ML Kit สิ่งนี้มีประโยชน์หากคุณต้องการดาวน์โหลดโมเดลล่วงหน้า หรือลบโมเดลที่ไม่จำเป็นออกจากอุปกรณ์

วิธีรับโมเดลการแปลที่จัดเก็บไว้ในอุปกรณ์:

สวิฟท์

let localModels = ModelManager.modelManager().downloadedTranslateModels

วัตถุประสงค์-C

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

หากต้องการลบโมเดล:

สวิฟท์

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

วัตถุประสงค์-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.
                                           }];

วิธีดาวน์โหลดโมเดล:

สวิฟท์

// 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
    )
)

หากคุณต้องการรับสถานะการดาวน์โหลดด้วย NotificationCenter ให้ลงทะเบียนผู้สังเกตการณ์สำหรับ firebaseMLModelDownloadDidSucceed และ firebaseMLModelDownloadDidFail ตรวจสอบให้แน่ใจว่าใช้การอ้างอิงถึง self ที่ไม่ชัดเจนในบล็อกผู้สังเกตการณ์ เนื่องจากการดาวน์โหลดอาจใช้เวลาสักครู่ และวัตถุต้นทางสามารถปล่อยออกได้เมื่อการดาวน์โหลดเสร็จสิ้น ตัวอย่างเช่น:

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

วัตถุประสงค์-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];

หากคุณต้องการรับสถานะการดาวน์โหลดด้วย NSNotificationCenter ให้ลงทะเบียนผู้สังเกตการณ์สำหรับ FIRModelDownloadDidSucceedNotification และ FIRModelDownloadDidFailNotification ตรวจสอบให้แน่ใจว่าใช้การอ้างอิงถึง self ที่ไม่ชัดเจนในบล็อกผู้สังเกตการณ์ เนื่องจากการดาวน์โหลดอาจใช้เวลาสักครู่ และวัตถุต้นทางสามารถปล่อยออกได้เมื่อการดาวน์โหลดเสร็จสิ้น

__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];
 }];