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

คุณใช้ ML Kit เพื่อแปลข้อความระหว่างภาษาได้ ML Kit แปลได้มากกว่า 50 ภาษา

ลองเลย

ก่อนเริ่มต้น

  1. รวมพ็อด ML Kit ต่อไปนี้ใน Podfile:
    pod 'GoogleMLKit/Translate', '3.2.0'
    
  2. หลังจากติดตั้งหรืออัปเดตพ็อดของโปรเจ็กต์แล้ว ให้เปิดโปรเจ็กต์ Xcode โดยใช้ .xcworkspace ของโปรเจ็กต์นั้น Xcode เวอร์ชัน 12.4 ขึ้นไปรองรับ ML Kit

แปลข้อความ

วิธีแปลสตริงระหว่าง 2 ภาษา

  1. สร้างออบเจ็กต์ Translator ซึ่งกำหนดค่าด้วยภาษาต้นฉบับและภาษาเป้าหมาย ดังนี้

    Swift

        // Create an English-German translator:
        let options = TranslatorOptions(sourceLanguage: .english, targetLanguage: .german)
        let englishGermanTranslator = Translator.translator(options: options)

    Objective-C

        // Create an English-German translator:
        MLKTranslatorOptions *options =
            [[MLKTranslatorOptions alloc] initWithSourceLanguage:MLKTranslateLanguageEnglish
                                                  targetLanguage:MLKTranslateLanguageGerman];
        MLKTranslator *englishGermanTranslator =
            [MLKTranslator translatorwithOptions:options];

    หากไม่ทราบภาษาของข้อความที่อินพุต คุณสามารถใช้ Language Identification API ซึ่งมีแท็กภาษาให้คุณได้ จากนั้นแปลงแท็กภาษา เป็น ML Kit enum โดยโค้ดจะขึ้นอยู่กับภาษาที่คุณใช้ ดังนี้

    หลีกเลี่ยงการเก็บโมเดลภาษาจำนวนมากเกินไปในอุปกรณ์พร้อมกัน

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

    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

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

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

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

    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 จะแปลข้อความเป็นภาษาเป้าหมายที่คุณกำหนดค่าไว้ และส่งข้อความที่แปลแล้วไปยังเครื่องจัดการการเสร็จสมบูรณ์

วงจรชีวิตของนักแปลจะควบคุมโดย ARC (การนับการอ้างอิงอัตโนมัติ) ซึ่งเป็นรูปแบบที่แนะนำสำหรับการพัฒนา iOS นักพัฒนาซอฟต์แวร์สามารถคาดหวังให้นักแปลได้รับการจัดการเมื่อนำข้อมูลอ้างอิงที่แข็งแกร่งออกทั้งหมดแล้ว

เครื่องแปลภาษาอาจใช้พื้นที่ 30 MB-150 MB เมื่อโหลดในหน่วยความจำ นักพัฒนาซอฟต์แวร์ควรคำนึงถึงงบประมาณของหน่วยความจำของอุปกรณ์/แอปเมื่อสร้างอินสแตนซ์ตัวแปลภาษาที่ทำงานพร้อมกัน และหลีกเลี่ยงการเก็บโมเดลภาษาหลายๆ ภาษาไว้ในอุปกรณ์พร้อมกันมากเกินไป

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

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

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

Swift

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

NSSet *localModels =
    [MLKModelManager modelManager].downloadedTranslateModels;

วิธีลบโมเดล

Swift

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

Objective-C

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

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

Swift

// Download the French model.
let frenchModel = TranslateRemoteModel.translateRemoteModel(language: .french)

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

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

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidSucceed,
    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 == frenchModel
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidFail,
    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.
MLKModelDownloadConditions *conditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                         allowsBackgroundDownloading:YES];
MLKTranslateRemoteModel *frenchModel =
    [MLKTranslateRemoteModel translateRemoteModelWithLanguage:MLKTranslateLanguageFrench];

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

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

__block MyViewController *weakSelf = self;

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

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

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

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