Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

feat: lyrics translate on the iPhone, with Apple's Translate or Apple Intelligence

My-Name-Is-Jeff86065ee4c139
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 84d5301e..253c8431 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -128,9 +128,14 @@ Shared:
no translation of their own take Musixmatch's community translations (Musixmatch.m), whichever
source won, Spotify's own included: matched by the line's folded text, as copies kept in place of the
lines (KaraokeSource.x), which the view picks up
- LyricsTranslation/ a song's lines translated by Gemini on the user's own key (Keychain), from the lyrics' corner
- menu, for the lines no source translated; the key's prompt and the menu item say the lyrics go to
- Google. The reply read and checked on the Mac against harness/lyrics-translation/
+ LyricsTranslation/ a song's lines translated from the lyrics' corner menu, for the lines no source translated, three
+ ways, each its own item: on the iPhone by Apple's Translate (iOS 26, the song's language told by
+ NaturalLanguage, both languages downloaded in the Translate app or the item says where to) and by Apple
+ Intelligence's model (iOS 26 where it is on and speaks the language; permissive guardrails for changing
+ the user's own text, 40 lines a session, exactly one string a line by a generation schema), both in
+ OnDeviceTranslation.swift, the frameworks weak linked; and by Gemini on the user's own key (Keychain),
+ whose prompt and menu item say the lyrics go to Google. Gemini's reply read and checked on the Mac
+ against harness/lyrics-translation/
LockScreenLyrics/ the line being sung in the system's now playing, and on iOS 26 the lyrics as the lock screen's
full-screen artwork (LyricsArtwork.x): a new artwork ID per line, its 3:4 H.264 clip (the line and the
next one dimmed over the blurred cover, SGLyricsClip.m) written only when the lock screen asks for it,
diff --git a/harness/lyrics/main.m b/harness/lyrics/main.m
index c81b1175..8028084b 100644
--- a/harness/lyrics/main.m
+++ b/harness/lyrics/main.m
@@ -23,6 +23,8 @@
// Musixmatch's community translations come in after the lines on the phone
// -gemini 1 a Gemini key is set, so the menu offers Translate with Gemini (stubs.m answers it)
// -geminiDelay S stubs.m's Gemini answers S seconds later instead of at once
+// -onDevice 1 Translate on iPhone is offered (stubs.m answers it)
+// -intelligence 1 Translate with Apple Intelligence is offered (stubs.m answers it)
// -seekLag S the player reports a seek S seconds after it is asked for (stubs.m)
// -check 1 asserts the view's fixes (see runChecks), prints PASS and FAIL lines and quits with the
// number of failures; run it with -song duet -at 20000 -gemini 1 -geminiDelay 1 -seekLag 0.4
diff --git a/harness/lyrics/stubs.m b/harness/lyrics/stubs.m
index e470e321..f677bfce 100644
--- a/harness/lyrics/stubs.m
+++ b/harness/lyrics/stubs.m
@@ -54,6 +54,26 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *li
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ done(translations, nil); });
}
+// -onDevice 1 / -intelligence 1: Translate on iPhone and Apple Intelligence are offered, each answering every
+// line with itself, marked.
+@interface SGOnDeviceTranslation : NSObject
+@end
+@implementation SGOnDeviceTranslation
++ (BOOL)translationAvailable { return [NSUserDefaults.standardUserDefaults boolForKey:@"onDevice"]; }
++ (BOOL)appleIntelligenceAvailable:(NSString *)languageTag { return [NSUserDefaults.standardUserDefaults boolForKey:@"intelligence"]; }
++ (void)answer:(NSArray<NSString *> *)lines as:(NSString *)mark done:(void (^)(NSArray<NSString *> *, NSString *))done {
+ NSMutableArray<NSString *> *out = [NSMutableArray array];
+ for (NSString *line in lines) [out addObject:line.length ? [mark stringByAppendingString:line] : @""];
+ dispatch_async(dispatch_get_main_queue(), ^{ done(out, nil); });
+}
++ (void)translate:(NSArray<NSString *> *)lines to:(NSString *)languageTag done:(void (^)(NSArray<NSString *> *, NSString *))done {
+ [self answer:lines as:@"iPhone: " done:done];
+}
++ (void)translateWithAppleIntelligence:(NSArray<NSString *> *)lines to:(NSString *)languageTag done:(void (^)(NSArray<NSString *> *, NSString *))done {
+ [self answer:lines as:@"Intelligence: " done:done];
+}
+@end
+
// Line meanings: -title and -artist name the track Genius is searched for, and the setting's key
// (-spotifyglass.lyricsMeanings 3) turns them on.
@interface SGHarnessTrack : NSObject
diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
index 984e13a2..dce0ccf8 100644
--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
@@ -1700,6 +1700,18 @@ static BOOL hasWords(SGKaraokeLine *line) {
return NO;
}
+// A way to translate a song: the lines, the track and the language in, one translation per line out, or a
+// message to show. Main queue.
+typedef void (^SGRTranslated)(NSArray<NSString *> *translations, NSString *error);
+typedef void (^SGRTranslator)(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *language, SGRTranslated done);
+
+// The lines' text for a translator, "" for a line with no words.
+static NSArray<NSString *> *textsOf(NSArray<SGKaraokeLine *> *lines) {
+ NSMutableArray<NSString *> *texts = [NSMutableArray arrayWithCapacity:lines.count];
+ for (SGKaraokeLine *line in lines) [texts addObject:hasWords(line) ? SGKaraokeLineText(line) ?: @"" : @""];
+ return texts;
+}
+
// When each line is sung and where the breaks are, worked out once per song for the frames to read.
- (void)timeLines {
free(_spans);
@@ -1801,8 +1813,10 @@ static BOOL hasWords(SGKaraokeLine *line) {
// The button shows only for a song with a pronunciation or a translation to show, and its menu only
// what the song has: a switch for each, reading what tapping it will do.
- (void)offerExtras {
- BOOL gemini = SGGeminiKeySet();
- BOOL offered = _lines && !_sample && (_hasSpoken || _hasTranslation || gemini);
+ NSString *language = SGLyricsGeminiLanguage();
+ BOOL gemini = SGGeminiKeySet(), onDevice = SGOnDeviceTranslation.translationAvailable;
+ BOOL intelligence = [SGOnDeviceTranslation appleIntelligenceAvailable:language];
+ BOOL offered = _lines && !_sample && (_hasSpoken || _hasTranslation || gemini || onDevice || intelligence);
if (!offered) {
_extrasBox.hidden = YES;
[self setNeedsLayout];
@@ -1827,7 +1841,7 @@ static BOOL hasWords(SGKaraokeLine *line) {
[self addSubview:_extrasBox];
self.extrasHidden = _extrasHidden;
}
- // While Gemini works the glyph turns into a spinner, and the menu has nothing to ask it a second time.
+ // While a translation is worked out the glyph turns into a spinner, and the menu has nothing to ask a second time.
BOOL translating = _translating && _translating == _lines;
UIButtonConfiguration *config = _extras.configuration;
if (config.showsActivityIndicator != translating) {
@@ -1848,14 +1862,31 @@ static BOOL hasWords(SGKaraokeLine *line) {
image:[UIImage systemImageNamed:@"character.bubble"] identifier:nil
handler:^(UIAction *action) { SGRSetLyricsTextShown(SGRLyricsTextTranslation, !on); }]];
}
- // Also for a song a source translated in part, as Musixmatch's community often has: Gemini fills in the rest.
- // Said in the item itself: the song's words leave the phone for Google's servers.
- if (gemini && _untranslated && !translating) {
+ // Also for a song a source translated in part, as Musixmatch's community often has: the rest is filled in.
+ // Said in each item: whether the song's words stay on the phone.
+ if (_untranslated && !translating) {
__weak SGRKaraokeView *weakSelf = self;
- UIAction *gemini = [UIAction actionWithTitle:@"Translate with Gemini" image:[UIImage systemImageNamed:@"sparkles"]
- identifier:nil handler:^(UIAction *action) { [weakSelf translateWithGemini]; }];
- gemini.subtitle = @"Sends the lyrics to Google";
- [items addObject:gemini];
+ void (^offer)(NSString *, NSString *, NSString *, SGRTranslator) = ^(NSString *title, NSString *glyph, NSString *subtitle, SGRTranslator translator) {
+ UIAction *action = [UIAction actionWithTitle:title image:[UIImage systemImageNamed:glyph] identifier:nil
+ handler:^(UIAction *action) { [weakSelf translateWith:translator]; }];
+ action.subtitle = subtitle;
+ [items addObject:action];
+ };
+ if (onDevice) {
+ offer(@"Translate on iPhone", @"translate", @"Apple's Translate, on this iPhone",
+ ^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated done) {
+ [SGOnDeviceTranslation translate:textsOf(lines) to:to done:done];
+ });
+ }
+ if (intelligence) {
+ offer(@"Translate with Apple Intelligence", @"apple.intelligence", @"On this iPhone",
+ ^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated done) {
+ [SGOnDeviceTranslation translateWithAppleIntelligence:textsOf(lines) to:to done:done];
+ });
+ }
+ if (gemini) offer(@"Translate with Gemini", @"sparkles", @"Sends the lyrics to Google", ^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated done) {
+ SGLyricsTranslateWithGemini(track, lines, to, done);
+ });
}
_extras.menu = [UIMenu menuWithChildren:items];
_extrasBox.hidden = NO;
@@ -1863,14 +1894,14 @@ static BOOL hasWords(SGKaraokeLine *line) {
}
// The song's lines into the Lyrics page's language, or the phone's: each line without a translation takes
-// Gemini's, and translations are switched on so the answer shows. The whole song is sent, for the sense.
-- (void)translateWithGemini {
+// the translator's, and translations are switched on so the answer shows. The whole song goes, for the sense.
+- (void)translateWith:(SGRTranslator)translator {
NSArray<SGKaraokeLine *> *lines = _lines;
NSString *track = _track;
if (!lines.count || _translating == lines) return;
_translating = lines;
[self offerExtras];
- SGLyricsTranslateWithGemini(track, lines, SGLyricsGeminiLanguage(), ^(NSArray<NSString *> *translations, NSString *error) {
+ translator(lines, track, SGLyricsGeminiLanguage(), ^(NSArray<NSString *> *translations, NSString *error) {
if (self->_translating == lines) self->_translating = nil;
[self offerExtras];
if (!translations) {
@@ -1884,7 +1915,7 @@ static BOOL hasWords(SGKaraokeLine *line) {
}
if (lines != self->_lines) return; // the song moved on meanwhile
[lines enumerateObjectsUsingBlock:^(SGKaraokeLine *line, NSUInteger i, BOOL *stop) {
- if (translations[i].length && !line.translation.length) line.translation = translations[i];
+ if (i < translations.count && translations[i].length && !line.translation.length) line.translation = translations[i];
}];
self->_hasTranslation = YES;
self->_untranslated = NO;
diff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
index b5d923aa..e449b080 100644
--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
@@ -21,3 +21,14 @@ NSArray<NSString *> *SGGeminiTranslationsIn(id root, NSInteger status, NSError *
// The Lyrics page's row: shows whether a key is set, and sets or removes it.
SGModRow *SGGeminiKeyRow(void);
+
+// On the iPhone itself (OnDeviceTranslation.swift): Apple's Translate, with both languages downloaded in the
+// Translate app, and Apple Intelligence's model. Each gives one translation per line ("" for a line with no
+// words), or nil and a message to show, on the main queue.
+@interface SGOnDeviceTranslation : NSObject
+@property (class, readonly) BOOL translationAvailable;
++ (BOOL)appleIntelligenceAvailable:(NSString *)languageTag;
++ (void)translate:(NSArray<NSString *> *)lines to:(NSString *)languageTag done:(void (^)(NSArray<NSString *> *lines, NSString *error))done;
++ (void)translateWithAppleIntelligence:(NSArray<NSString *> *)lines to:(NSString *)languageTag
+ done:(void (^)(NSArray<NSString *> *lines, NSString *error))done;
+@end
diff --git a/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift b/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift
new file mode 100644
index 00000000..853e0400
--- /dev/null
+++ b/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift
@@ -0,0 +1,145 @@
+// The two ways to translate a song on the iPhone itself, for LyricsTranslation.h: Apple's Translation
+// framework (iOS 26, with the languages downloaded in the Translate app) and Apple Intelligence's language
+// model (iOS 26, on the iPhones that have it). Both are Swift only. Nothing leaves the phone.
+import Foundation
+import FoundationModels
+import NaturalLanguage
+import Translation
+
+@objc(SGOnDeviceTranslation)
+public final class SGOnDeviceTranslation: NSObject {
+ // The model asked fresh for each run of this many lines, so a long song stays inside its context.
+ private static let chunkLines = 40
+
+ private static func finish(_ done: @escaping ([String]?, String?) -> Void, _ lines: [String]?, _ error: String?) {
+ DispatchQueue.main.async { done(lines, error) }
+ }
+
+ private static func name(_ language: Locale.Language) -> String {
+ Locale.current.localizedString(forIdentifier: language.minimalIdentifier) ?? language.minimalIdentifier
+ }
+
+ // The song's language, from its words.
+ private static func sourceLanguage(_ lines: [String]) -> Locale.Language? {
+ let recognizer = NLLanguageRecognizer()
+ recognizer.processString(lines.joined(separator: "\n"))
+ guard let found = recognizer.dominantLanguage, found != .undetermined else { return nil }
+ return Locale.Language(identifier: found.rawValue)
+ }
+
+ private static func same(_ a: Locale.Language, _ b: Locale.Language) -> Bool {
+ a.languageCode == b.languageCode
+ }
+
+ // MARK: Translation framework
+
+ @objc public static var translationAvailable: Bool {
+ if #available(iOS 26.0, *) { return true }
+ return false
+ }
+
+ // One translation per line, "" for a line with no words; or nil and why not.
+ @objc public static func translate(_ lines: [String], to languageTag: String, done: @escaping ([String]?, String?) -> Void) {
+ guard #available(iOS 26.0, *) else { return finish(done, nil, "Translating on this iPhone needs iOS 26.") }
+ let target = Locale.Language(identifier: languageTag)
+ guard let source = sourceLanguage(lines) else { return finish(done, nil, "The song's language could not be told from its words.") }
+ if same(source, target) { return finish(done, nil, "The song is already in \(name(target)).") }
+ Task {
+ switch await LanguageAvailability().status(from: source, to: target) {
+ case .unsupported:
+ return finish(done, nil, "Apple's Translate does not translate \(name(source)) into \(name(target)).")
+ case .supported:
+ return finish(done, nil, "Download \(name(source)) and \(name(target)) in Settings > Apps > Translate > Languages, then try again.")
+ case .installed:
+ break
+ @unknown default:
+ break
+ }
+ let requests = lines.enumerated().compactMap { index, line in
+ line.trimmingCharacters(in: .whitespaces).isEmpty || line == "♪" ? nil
+ : TranslationSession.Request(sourceText: line, clientIdentifier: String(index))
+ }
+ do {
+ let session = TranslationSession(installedSource: source, target: target)
+ var out = [String](repeating: "", count: lines.count)
+ for response in try await session.translations(from: requests) {
+ if let id = response.clientIdentifier, let index = Int(id) { out[index] = response.targetText }
+ }
+ finish(done, out, nil)
+ } catch {
+ finish(done, nil, "Apple's Translate could not translate the song (\(error.localizedDescription)).")
+ }
+ }
+ }
+
+ // MARK: Apple Intelligence
+
+ @available(iOS 26.0, *)
+ private static var model: SystemLanguageModel {
+ // Lyrics are often explicit: the guardrails for changing text the user already has, not for writing new.
+ SystemLanguageModel(useCase: .general, guardrails: .permissiveContentTransformations)
+ }
+
+ @objc public static func appleIntelligenceAvailable(_ languageTag: String) -> Bool {
+ guard #available(iOS 26.0, *) else { return false }
+ let target = Locale.Language(identifier: languageTag)
+ return model.availability == .available && model.supportedLanguages.contains { same($0, target) }
+ }
+
+ @objc public static func translateWithAppleIntelligence(_ lines: [String], to languageTag: String, done: @escaping ([String]?, String?) -> Void) {
+ guard #available(iOS 26.0, *) else { return finish(done, nil, "Apple Intelligence needs iOS 26.") }
+ let language = name(Locale.Language(identifier: languageTag))
+ Task {
+ var out: [String] = []
+ do {
+ for start in stride(from: 0, to: lines.count, by: chunkLines) {
+ let chunk = Array(lines[start..<min(start + chunkLines, lines.count)])
+ out += try await translateChunk(chunk, into: language)
+ }
+ finish(done, out, nil)
+ } catch {
+ finish(done, nil, problem(error))
+ }
+ }
+ }
+
+ // iOS 27 throws LanguageModelError, iOS 26 the session's GenerationError.
+ @available(iOS 26.0, *)
+ private static func problem(_ error: Error) -> String {
+ let declined = "Apple Intelligence declined to translate this song's lyrics."
+ let tooLong = "The song is too long for Apple Intelligence."
+ let language = "Apple Intelligence does not work in this language."
+ if #available(iOS 27.0, *), let error = error as? LanguageModelError {
+ switch error {
+ case .guardrailViolation, .refusal: return declined
+ case .contextSizeExceeded: return tooLong
+ case .unsupportedLanguageOrLocale: return language
+ default: break
+ }
+ } else if let error = error as? LanguageModelSession.GenerationError {
+ switch error {
+ case .guardrailViolation, .refusal: return declined
+ case .exceededContextWindowSize: return tooLong
+ case .unsupportedLanguageOrLocale: return language
+ default: break
+ }
+ }
+ return "Apple Intelligence could not translate the song (\(error.localizedDescription))."
+ }
+
+ // Exactly one string per line, held to the count by the schema rather than read out of free text.
+ @available(iOS 26.0, *)
+ private static func translateChunk(_ lines: [String], into language: String) async throws -> [String] {
+ let session = LanguageModelSession(model: model, instructions: """
+ You translate song lyrics into \(language). You get a JSON array of lines and answer with an array of \
+ the same length: each line's translation at the same place, natural as sung, keeping the meaning of \
+ slang and idioms. A line that is empty, a sound or already in \(language) is given back as it is.
+ """)
+ let line = DynamicGenerationSchema(type: String.self)
+ let schema = try GenerationSchema(root: DynamicGenerationSchema(arrayOf: line, minimumElements: lines.count, maximumElements: lines.count),
+ dependencies: [])
+ let prompt = String(decoding: try JSONSerialization.data(withJSONObject: lines), as: UTF8.self)
+ let answer = try await session.respond(to: prompt, schema: schema).content.value([String].self)
+ return answer.count == lines.count ? answer : lines.indices.map { $0 < answer.count ? answer[$0] : "" }
+ }
+}