-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Integrate Translation framework #25089
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+336
−4
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
866bd15
Implement Reader Post translation
kean fb7f6a4
Add an assertion to check if translation is started
kean df10676
Add CancellationError support
kean 3283943
Fix an issue with translation not restarted when cancelled
kean 496e272
Add TranslationAvailability to improve language detection and ensure …
kean 2581508
Improve blur
kean 77adb04
Remove redundant Task
kean 14cb490
Add comments
kean 709dda4
Merge branch 'trunk' into task/integrate-translations
kean File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
133 changes: 133 additions & 0 deletions
133
Modules/Sources/WordPressIntelligence/UseCases/TranslationViewModel.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import Foundation | ||
| import SwiftUI | ||
| import WebKit | ||
| import Translation | ||
| import NaturalLanguage | ||
| import Combine | ||
| import WordPressShared | ||
|
|
||
| @available(iOS 26, *) | ||
| @MainActor | ||
| public final class TranslationViewModel: ObservableObject { | ||
| @Published var configuration: TranslationSession.Configuration? | ||
|
|
||
| private var content: [String] = [] | ||
| private var continuation: CheckedContinuation<[String], Error>? | ||
|
|
||
| public init() {} | ||
|
|
||
| public func translate(_ content: String, to targetLanguage: Locale.Language) async throws -> String { | ||
| let content = try await translate([content], to: targetLanguage) | ||
| guard let first = content.first else { | ||
| throw URLError(.unknown) // Should never happen | ||
| } | ||
| return first | ||
| } | ||
|
|
||
| /// Translate content to the specified target language. | ||
| /// | ||
| /// This method detects the source language automatically and translates each string | ||
| /// in the content array independently. | ||
| public func translate( | ||
| _ content: [String], | ||
| from source: Locale.Language? = nil, | ||
| to target: Locale.Language = Locale.current.language | ||
| ) async throws -> [String] { | ||
| wpAssert(continuation == nil, "Translation in progress") | ||
|
|
||
| self.content = content | ||
| return try await withCheckedThrowingContinuation { continuation in | ||
| self.continuation = continuation | ||
|
|
||
| // This will trigger the .translationTask in TranslationHostView | ||
| if self.configuration != nil { | ||
| // Yes, this is how you restart translation with the existing configuration | ||
| // in the Translation framework. | ||
| self.configuration?.invalidate() | ||
| } else { | ||
| self.configuration = TranslationSession.Configuration(source: source, target: target) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Check if translation is available for the given content. | ||
| public func checkAvailability(for content: String, to targetLanguage: Locale.Language = Locale.current.language) async -> TranslationAvailability { | ||
| // Important. The `Translation` framework is effective at translating | ||
| // HTML, but the `status(...)` method and `NLLanguageRecognizer` | ||
| // incorrectly identify dominant langauge as English if a post has a | ||
| // signifcant amount of HTML tags and/or CSS styles. | ||
| let content = (try? ContentExtractor.extractRelevantText(from: content)) ?? content | ||
|
|
||
| guard let identifier = IntelligenceService.detectLanguage(from: content) else { | ||
| return .unavailable | ||
| } | ||
| let sourceLanguage = Locale.Language(identifier: identifier) | ||
|
|
||
| let availability = LanguageAvailability() | ||
| let status = await availability.status(from: sourceLanguage, to: targetLanguage) | ||
| guard status == .installed || status == .supported else { | ||
| return .unavailable | ||
| } | ||
| return .available(sourceLanguage: sourceLanguage, targetLanguage: targetLanguage) | ||
| } | ||
|
|
||
| fileprivate func performTranslation(session: TranslationSession) async { | ||
| do { | ||
| var output: [String] = [] | ||
| for string in content { | ||
| try Task.checkCancellation() | ||
| let result = try await session.translate(string) | ||
| output.append(result.targetText) | ||
| } | ||
| finish(with: .success(output)) | ||
| } catch { | ||
| if (error as NSError).domain == NSCocoaErrorDomain && (error as NSError).code == NSUserCancelledError { | ||
| finish(with: .failure(CancellationError())) | ||
| } else { | ||
| finish(with: .failure(error)) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private func finish(with result: Result<[String], Error>) { | ||
| content = [] | ||
| if let continuation { | ||
| self.continuation = nil | ||
| continuation.resume(with: result) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public enum TranslationAvailability { | ||
| case unavailable | ||
| case available(sourceLanguage: Locale.Language, targetLanguage: Locale.Language) | ||
| } | ||
|
|
||
| // MARK: - TranslationHostView (SwiftUI) | ||
|
|
||
| /// SwiftUI view that hosts translation functionality using .translationTask() | ||
| /// | ||
| /// This view manages the translation session lifecycle. It observes the view model's | ||
| /// configuration and triggers translation when it changes. | ||
| /// | ||
| /// **IMPORTANT**: The `session` object must NEVER leave the `.translationTask` closure. | ||
| /// Capturing or storing the session causes crashes. | ||
| @available(iOS 26, *) | ||
| public struct TranslationHostView: View { | ||
| @ObservedObject var viewModel: TranslationViewModel | ||
|
|
||
| public init(viewModel: TranslationViewModel) { | ||
| self.viewModel = viewModel | ||
| } | ||
|
|
||
| public var body: some View { | ||
| Color.clear | ||
| .frame(width: 0, height: 0) | ||
| .translationTask(viewModel.configuration) { session in | ||
| await viewModel.performTranslation(session: session) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @available(iOS 18.0, *) | ||
| extension TranslationSession: @retroactive @unchecked(Sendable) {} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems a bit risky to hold the continuation instances at the class level, instead of locally in the function.