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: translate lyrics with an OpenAI-compatible server or Anthropic, and see who made a translation

My-Name-Is-Jeffb21d6e735dc2
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 55d8ba06..77a3f54b 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -148,8 +148,7 @@ Shared:
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, 12 lines a session, greedy and capped at 60 tokens a line, exactly one string a line by a generation schema; Translate retried once, as its first ask can fail while it loads), 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; its model (gemini-flash-latest, two cheaper ones or any id, SGKeyGeminiModel) and its prompt (Vitrine's with {language} and {count}, editable in a sheet, SGKeyGeminiPrompt) are read at each ask, and the log names the model and the prompt's SHA-256 prefix. The translate items show for every song with Translate any song on (SGKeyLyricsTranslateEverySong, off), else only for a song NaturalLanguage finds in another language than the Lyrics page's (or the iPhone's): one distinct line in five it is at least 80% sure of, or two in another script (a verse in Hangul among English), not the whole song's guess (short lines sway that: Havana reads as Dutch), so songs half in English count and a repeated chorus weighs as one line; Translate on iPhone translates from the language most of those lines are in and leaves lines already in the target as they are. Apple Intelligence's lines show and are saved a batch at a time, only lines without a translation are sent, and a batch it turns down is skipped (asking again sends only those lines). Every finished translation is kept by SavedTranslations.m in Caches/Vitrine/Translations, one JSON file a song and language mapping each line's text to its translation, the newest 200, synced when the song's lines are shown: each line knows whether its translation was made here (SGKaraokeLine.translationMade), and a made one with nothing saved is taken off, so the Lyrics page's Saved translations row deletes them at once, posting SGLyricsTranslationsDidChangeNotification as Translate any song does for the open lyrics to sync and redraw. Gemini's reply read and checked on the Mac
+ OnDeviceTranslation.swift, the frameworks weak linked; and by an AI translator on the user's own key, picked on the Lyrics page (SGKeyAITranslator): Gemini, an OpenAI-compatible server (chat completions; OpenAI's unless a server URL is given, such as OpenRouter's or an Ollama on the network, which Spotify's ATS allows for local addresses) or Anthropic (the Messages API). Each provider is one entry of LyricsTranslation.m's table: its Keychain slot (one key each, never in the settings, so an export never has one), its model presets (the cheapest first; OpenAI-compatible has none and needs a model), its request and its reply's reader. The answer's shape is forced where the API can (Gemini a bare array, the others {"lines": [...]} by a strict schema), the reader takes either, and a 400 that names an optional field (Gemini's thinking level, OpenAI's schema or reasoning effort, Anthropic's output_config) is asked once more without them. The prompt is shared (Vitrine's with {language} and {count}, editable in a sheet, SGKeyAIPrompt) and the provider adds its sentence on the answer's shape; the model (spotifyglass.lyrics.<id>.model) and the server are read at each ask and checked as they are read, and the log names the provider, the model, the host and the prompt's SHA-256 prefix, never the key. Temperature is not offered: Anthropic's API turns it down and OpenAI's reasoning models take only the default. The menu item says where the lyrics go. The translate items show for every song with Translate any song on (SGKeyLyricsTranslateEverySong, off), else only for a song NaturalLanguage finds in another language than the Lyrics page's (or the iPhone's): one distinct line in five it is at least 80% sure of, or two in another script (a verse in Hangul among English), not the whole song's guess (short lines sway that: Havana reads as Dutch), so songs half in English count and a repeated chorus weighs as one line; Translate on iPhone translates from the language most of those lines are in and leaves lines already in the target as they are. Apple Intelligence's lines show and are saved a batch at a time, only lines without a translation are sent, and a batch it turns down is skipped (asking again sends only those lines). Every finished translation is kept by SavedTranslations.m in Caches/Vitrine/Translations, one JSON file a song and language with each line's text to its translation under "lines" and who made it and when ("by", "model", "made"; a file from before has the lines alone and reads as Unknown), the newest 200, synced when the song's lines are shown: each line knows whether its translation was made here (SGKaraokeLine.translationMade), and a made one with nothing saved is taken off, so the Lyrics page's Saved translations row deletes them at once, posting SGLyricsTranslationsDidChangeNotification as Translate any song does for the open lyrics to sync and redraw. The translate menu names who made a saved translation and when, and for one an AI made (or no one known) offers Delete This Translation, which removes the song's file and the launch's answer for it, so asking again sends the song. 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
diff --git a/harness/lyrics-translation/README.md b/harness/lyrics-translation/README.md
index 36f8c959..23c17e5e 100644
--- a/harness/lyrics-translation/README.md
+++ b/harness/lyrics-translation/README.md
@@ -2,9 +2,12 @@
`./build.sh` checks the parts of lyrics translation that need no network: Musixmatch's community
translations matched onto a song's lines by their folded text, as copies that leave the lines kept
-before untouched (`SGMusixmatchTranslatedLines`), and Gemini's reply read into one translation per line
-or a reason to show (`SGGeminiTranslationsIn`): a blocked prompt, a recitation or safety stop, a line
-count that does not match, the key, the limit. It runs on the Mac as a Mac Catalyst binary, with no
+before untouched (`SGMusixmatchTranslatedLines`); each AI provider's request (`SGAITranslationRequest`:
+the URL, the key's header, the body, what the plain retry leaves out, a server URL that could carry a
+secret refused) and its reply read into one translation per line or a reason to show
+(`SGAITranslationsIn`): Gemini's blocked prompt, recitation or safety stop, OpenAI-compatible and
+Anthropic refusals and length stops, a line count that does not match, the key, the limit; and saved
+translation files with their source and from before sources were kept (`SGSavedTranslationLines`). It runs on the Mac as a Mac Catalyst binary, with no
simulator and no network.
It does not cover the requests themselves, the lines taking the translations as they are kept
diff --git a/harness/lyrics-translation/build.sh b/harness/lyrics-translation/build.sh
index 4cfb01c5..a7b6d512 100755
--- a/harness/lyrics-translation/build.sh
+++ b/harness/lyrics-translation/build.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# build.sh: builds check.m against this checkout's Musixmatch.m, LyricsTranslation.m and KaraokeTiming.m
+# build.sh: builds check.m against this checkout's Musixmatch.m, LyricsTranslation.m, SavedTranslations.m and KaraokeTiming.m
# (and LocalFiles.m, which Musixmatch.m reads a local file's names from) as a Mac Catalyst binary and runs
# it, so no simulator is needed.
set -e
@@ -7,7 +7,7 @@ HERE=$(cd "$(dirname "$0")" && pwd)
SRC=$(cd "$HERE/../../tweak/Sources" && pwd)
mkdir -p "$HERE/build"
xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$(xcrun --sdk macosx --show-sdk-path)" -iframework "$(xcrun --sdk macosx --show-sdk-path)/System/iOSSupport/System/Library/Frameworks" -fobjc-arc -g -Wall -I"$SRC" \
- "$HERE/check.m" "$SRC/Shared/LyricsSources/Musixmatch.m" "$SRC/Shared/LyricsTranslation/LyricsTranslation.m" \
+ "$HERE/check.m" "$SRC/Shared/LyricsSources/Musixmatch.m" "$SRC/Shared/LyricsTranslation/LyricsTranslation.m" "$SRC/Shared/LyricsTranslation/SavedTranslations.m" \
"$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \
-framework UIKit -framework CoreGraphics -framework Security -framework Foundation -o "$HERE/build/check"
"$HERE/build/check"
diff --git a/harness/lyrics-translation/check.m b/harness/lyrics-translation/check.m
index 4a58d282..60a8f159 100644
--- a/harness/lyrics-translation/check.m
+++ b/harness/lyrics-translation/check.m
@@ -1,6 +1,7 @@
// Checks the parts of lyrics translation that need no network: Musixmatch's community translations
-// matched onto a song's lines as copies, and Gemini's reply read into lines or a reason. Built against
-// this checkout's Musixmatch.m, LyricsTranslation.m and KaraokeTiming.m. Exits non-zero on the first
+// matched onto a song's lines as copies, each AI provider's request and reply (read into lines or a reason),
+// and saved translation files with and without their source. Built against
+// this checkout's Musixmatch.m, LyricsTranslation.m, SavedTranslations.m and KaraokeTiming.m. Exits non-zero on the first
// wrong answer.
#import <UIKit/UIKit.h>
#import "Shared/Lyrics/Lyrics.h"
@@ -17,13 +18,25 @@ SGModRow *SGStatActionRow(NSString *t, NSString *s, NSString *(^v)(void), void (
SGModRow *SGOptionRow(NSString *t, NSString *s, NSString *k) { return nil; }
id SGKaraokeTrackFor(NSString *trackID) { return nil; }
UIViewController *SGTopController(void) { return nil; }
+SGModRow *SGMenuRow(NSString *t, NSArray<NSString *> *c, NSString *(^v)(void), void (^ch)(NSInteger)) { return nil; }
+void SGPresentDark(UIViewController *controller) {}
#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)
static NSArray<NSString *> *readReply(NSString *json, NSInteger status, NSUInteger count, NSString **problem) {
*problem = nil;
id root = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
- return SGGeminiTranslationsIn(root, status, nil, count, problem);
+ return SGAITranslationsIn(@"gemini", root, status, nil, count, problem);
+}
+
+static NSArray<NSString *> *readFrom(NSString *provider, NSString *json, NSInteger status, NSUInteger count, NSString **problem) {
+ *problem = nil;
+ id root = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
+ return SGAITranslationsIn(provider, root, status, nil, count, problem);
+}
+
+static NSDictionary *bodyOf(NSURLRequest *request) {
+ return [NSJSONSerialization JSONObjectWithData:request.HTTPBody options:0 error:nil];
}
int main(void) {
@@ -64,6 +77,77 @@ int main(void) {
CHECK(!readReply(@"{\"error\":{\"status\":\"UNAUTHENTICATED\"}}", 401, 2, &problem) && [problem containsString:@"key"]);
CHECK(!readReply(@"{\"error\":{}}", 429, 2, &problem) && [problem containsString:@"limit"]);
CHECK(!readReply(@"{}", 200, 2, &problem) && [problem containsString:@"could not be read"]);
+ // Gemini's errors name Gemini; a request that never arrived is not the key's fault.
+ CHECK(!SGAITranslationsIn(@"gemini", nil, 0, [NSError errorWithDomain:NSURLErrorDomain code:-1009 userInfo:nil], 2, &problem)
+ && [problem isEqualToString:@"Gemini could not be reached."]);
+
+ // OpenAI-compatible: choices[0].message.content holds {"lines": [...]}, or a bare array, or JSON in a fence.
+ NSString *openAI = @"{\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"content\":\"{\\\"lines\\\":[\\\"a\\\",\\\"b\\\"]}\"}}]}";
+ CHECK([readFrom(@"openai", openAI, 200, 2, &problem) isEqualToArray:(@[@"a", @"b"])] && !problem);
+ CHECK([readFrom(@"openai", @"{\"choices\":[{\"message\":{\"content\":\"```json\\n[\\\"a\\\",\\\"b\\\"]\\n```\"}}]}", 200, 2, &problem)
+ isEqualToArray:(@[@"a", @"b"])]);
+ CHECK(!readFrom(@"openai", openAI, 200, 3, &problem) && [problem containsString:@"2 lines for the song's 3"]
+ && [problem hasPrefix:@"api.openai.com"]);
+ CHECK(!readFrom(@"openai", @"{\"choices\":[{\"message\":{\"content\":null,\"refusal\":\"I can't\"}}]}", 200, 2, &problem)
+ && [problem containsString:@"declined"]);
+ CHECK(!readFrom(@"openai", @"{\"choices\":[{\"finish_reason\":\"length\",\"message\":{\"content\":\"{\\\"lines\\\":[\"}}]}", 200, 2, &problem)
+ && [problem containsString:@"too long"]);
+ CHECK(!readFrom(@"openai", @"{\"choices\":[{\"finish_reason\":\"content_filter\",\"message\":{\"content\":\"\"}}]}", 200, 2, &problem)
+ && [problem containsString:@"filters"]);
+ CHECK(!readFrom(@"openai", @"{\"error\":{\"message\":\"Incorrect API key provided\",\"type\":\"invalid_request_error\"}}", 401, 2, &problem)
+ && [problem containsString:@"turned the key down"]);
+ CHECK(!readFrom(@"openai", @"{\"error\":\"model 'x' not found\"}", 404, 2, &problem) && [problem containsString:@"model 'x' not found"]);
+
+ // Anthropic: the text blocks of content, a refusal or a length stop named.
+ NSString *anthropic = @"{\"stop_reason\":\"end_turn\",\"content\":[{\"type\":\"thinking\",\"thinking\":\"\"},{\"type\":\"text\",\"text\":\"{\\\"lines\\\":[\\\"a\\\",\\\"\\\"]}\"}]}";
+ CHECK([readFrom(@"anthropic", anthropic, 200, 2, &problem) isEqualToArray:(@[@"a", @""])] && !problem);
+ CHECK(!readFrom(@"anthropic", @"{\"stop_reason\":\"refusal\",\"content\":[]}", 200, 2, &problem) && [problem isEqualToString:@"Anthropic declined to translate the song."]);
+ CHECK(!readFrom(@"anthropic", @"{\"stop_reason\":\"max_tokens\",\"content\":[{\"type\":\"text\",\"text\":\"{\"}]}", 200, 2, &problem) && [problem containsString:@"too long"]);
+ CHECK(!readFrom(@"anthropic", @"{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\",\"message\":\"invalid x-api-key\"}}", 401, 2, &problem)
+ && [problem isEqualToString:@"Anthropic turned the key down. Check it on the Lyrics page."]);
+ CHECK(!readFrom(@"anthropic", @"{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", 529, 2, &problem) && [problem containsString:@"busy"]);
+
+ // The requests: where each goes, the key in its header and never in the body, and what plain leaves out.
+ NSURLRequest *gemini = SGAITranslationRequest(@"gemini", @"gemini-3.6-flash", @"P", @"k1", NO);
+ CHECK([gemini.URL.absoluteString isEqualToString:@"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent"]);
+ CHECK([[gemini valueForHTTPHeaderField:@"x-goog-api-key"] isEqualToString:@"k1"] && bodyOf(gemini)[@"generationConfig"][@"thinkingConfig"]);
+ CHECK(!bodyOf(SGAITranslationRequest(@"gemini", @"gemini-3.6-flash", @"P", @"k1", YES))[@"generationConfig"][@"thinkingConfig"]);
+ NSURLRequest *chat = SGAITranslationRequest(@"openai", @"gpt-6-astra", @"P", @"k2", NO);
+ CHECK([chat.URL.absoluteString isEqualToString:@"https://api.openai.com/v1/chat/completions"]);
+ CHECK([[chat valueForHTTPHeaderField:@"Authorization"] isEqualToString:@"Bearer k2"]);
+ CHECK([bodyOf(chat)[@"model"] isEqualToString:@"gpt-6-astra"] && [bodyOf(chat)[@"messages"][0][@"content"] isEqualToString:@"P"]);
+ CHECK([bodyOf(chat)[@"response_format"][@"json_schema"][@"strict"] boolValue]
+ && [bodyOf(chat)[@"response_format"][@"json_schema"][@"schema"][@"required"] isEqualToArray:(@[@"lines"])]);
+ NSDictionary *plainChat = bodyOf(SGAITranslationRequest(@"openai", @"gpt-6-astra", @"P", @"k2", YES));
+ CHECK(!plainChat[@"response_format"] && !plainChat[@"reasoning_effort"] && plainChat[@"messages"]);
+ // A server of the user's own: a pasted /chat/completions is not doubled, and a URL that could carry a
+ // secret is not used at all (and not swapped for OpenAI's).
+ [NSUserDefaults.standardUserDefaults setObject:@"http://192.168.1.5:11434/v1/chat/completions" forKey:@"spotifyglass.lyrics.openai.url"];
+ CHECK([SGAITranslationRequest(@"openai", @"llama3.2:3b", @"P", @"k", NO).URL.absoluteString isEqualToString:@"http://192.168.1.5:11434/v1/chat/completions"]);
+ [NSUserDefaults.standardUserDefaults setObject:@"https://openrouter.ai/api/v1?key=secret" forKey:@"spotifyglass.lyrics.openai.url"];
+ CHECK(!SGAITranslationRequest(@"openai", @"x", @"P", @"k", NO));
+ [NSUserDefaults.standardUserDefaults setObject:@"ftp://example.com" forKey:@"spotifyglass.lyrics.openai.url"];
+ CHECK(!SGAITranslationRequest(@"openai", @"x", @"P", @"k", NO));
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:@"spotifyglass.lyrics.openai.url"];
+ NSURLRequest *messages = SGAITranslationRequest(@"anthropic", @"claude-haiku-5-5", @"P", @"k3", NO);
+ CHECK([messages.URL.absoluteString isEqualToString:@"https://api.anthropic.com/v1/messages"]);
+ CHECK([[messages valueForHTTPHeaderField:@"x-api-key"] isEqualToString:@"k3"] && [messages valueForHTTPHeaderField:@"anthropic-version"]);
+ CHECK([bodyOf(messages)[@"max_tokens"] integerValue] > 0 && [bodyOf(messages)[@"output_config"][@"format"][@"type"] isEqualToString:@"json_schema"]);
+ CHECK(!bodyOf(SGAITranslationRequest(@"anthropic", @"claude-haiku-5-5", @"P", @"k3", YES))[@"output_config"]);
+ CHECK(![[[NSString alloc] initWithData:messages.HTTPBody encoding:NSUTF8StringEncoding] containsString:@"k3"]);
+ CHECK(!SGAITranslationRequest(@"nobody", @"m", @"P", @"k", NO));
+
+ // Saved files: the new shape with its source, and one from before sources were kept, as unknown.
+ SGTranslationSource *source = nil;
+ NSDictionary *saved = SGSavedTranslationLines(@{@"by": @"anthropic", @"model": @"claude-haiku-5-5", @"made": @1792000000,
+ @"lines": @{@"Hola": @"Hello"}}, &source);
+ CHECK([saved isEqualToDictionary:(@{@"Hola": @"Hello"})] && [source.name isEqualToString:@"Anthropic (claude-haiku-5-5)"]
+ && source.made.timeIntervalSince1970 == 1792000000 && source.deletable);
+ saved = SGSavedTranslationLines(@{@"Hola": @"Hello", @"lines": @"a lyric that reads lines"}, &source);
+ CHECK(saved.count == 2 && !source.by && [source.name isEqualToString:@"Unknown"] && !source.made && source.deletable);
+ saved = SGSavedTranslationLines(@{@"by": @"translate", @"lines": @{}}, &source);
+ CHECK(saved && [source.name isEqualToString:@"Translate on iPhone"] && !source.deletable);
+ CHECK(!SGSavedTranslationLines(@[@"not", @"a", @"file"], &source));
puts("lyrics translation: all checks passed");
}
return 0;
diff --git a/harness/lyrics/stubs.m b/harness/lyrics/stubs.m
index 6ba2458f..c9222d98 100644
--- a/harness/lyrics/stubs.m
+++ b/harness/lyrics/stubs.m
@@ -3,6 +3,7 @@
// line's -at at -rate, and holds at -pauseAt for -holdFor seconds before it runs on.
#import <UIKit/UIKit.h>
#import "Shared/Lyrics/Lyrics.h"
+#import "Shared/LyricsTranslation/LyricsTranslation.h"
UIColor *SGRAccentColor(void) { return nil; }
@@ -41,10 +42,24 @@ void SGLyricsOpenCreditLinks(NSArray<SGLyricsLink *> *links, UIView *from) { NSL
NSString *SGLyricsTranslationLanguage(void) { return [NSUserDefaults.standardUserDefaults stringForKey:@"translateTo"]; }
// -gemini 1: a Gemini key is set, and Translate with Gemini answers each line with itself, marked.
-BOOL SGGeminiKeySet(void) { return [NSUserDefaults.standardUserDefaults boolForKey:@"gemini"]; }
+BOOL SGAITranslatorReady(void) { return [NSUserDefaults.standardUserDefaults boolForKey:@"gemini"]; }
+NSString *SGAITranslatorName(void) { return @"Gemini"; }
+NSString *SGAITranslatorRecipient(void) { return @"Google"; }
+@implementation SGTranslationSource
++ (instancetype)by:(NSString *)by model:(NSString *)model made:(NSDate *)made {
+ SGTranslationSource *source = [self new];
+ [source setValue:by forKey:@"by"];
+ [source setValue:model forKey:@"model"];
+ [source setValue:made forKey:@"made"];
+ return source;
+}
+- (NSString *)name { return self.model ? [NSString stringWithFormat:@"%@ (%@)", self.by, self.model] : self.by ?: @"Unknown"; }
+- (BOOL)deletable { return YES; }
+@end
+SGTranslationSource *SGAITranslatorSource(void) { return [SGTranslationSource by:@"gemini" model:@"harness" made:nil]; }
NSString *SGLyricsGeminiLanguage(void) { return SGLyricsTranslationLanguage() ?: @"en"; }
-void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
- void (^done)(NSArray<NSString *> *translations, NSString *error)) {
+void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
+ void (^done)(NSArray<NSString *> *translations, NSString *error)) {
NSMutableArray<NSString *> *translations = [NSMutableArray array];
for (SGKaraokeLine *line in lines) [translations addObject:[@"Gemini: " stringByAppendingString:SGKaraokeLineText(line)]];
// -geminiDelay S: as late as a whole song through the real API can be.
@@ -58,7 +73,8 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *li
// -onDevice 1 / -intelligence 1: Translate on iPhone and Apple Intelligence are offered, each answering every
// line with itself, marked.
-@interface SGOnDeviceTranslation : NSObject
+@interface SGOnDeviceTranslation (Harness)
++ (void)answer:(NSArray<NSString *> *)lines as:(NSString *)mark done:(void (^)(NSArray<NSString *> *, NSString *))done;
@end
@implementation SGOnDeviceTranslation
+ (BOOL)translationAvailable { return [NSUserDefaults.standardUserDefaults boolForKey:@"onDevice"]; }
@@ -83,9 +99,14 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *li
}
@end
// Nothing is kept between runs of the harness.
-void SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) {}
+SGTranslationSource *SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) { return nil; }
NSNotificationName const SGLyricsTranslationsDidChangeNotification = @"spotifyglass.lyricsTranslationsDidChange";
-void SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) {}
+SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines, SGTranslationSource *source) {
+ return [SGTranslationSource by:source.by model:source.model made:[NSDate date]];
+}
+void SGLyricsDeleteSavedTranslation(NSString *track, NSString *language) {
+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];
+}
// Line meanings: -title and -artist name the track Genius is searched for, and the setting's key
// (-spotifyglass.lyricsMeanings 3) turns them on.
diff --git a/harness/mod-settings/stubs.m b/harness/mod-settings/stubs.m
index 5a7d3ae1..2e7213e2 100644
--- a/harness/mod-settings/stubs.m
+++ b/harness/mod-settings/stubs.m
@@ -21,7 +21,8 @@ UIViewController *SGRPlayerSettingsPage(NSArray *more) { return blank(@"SGRPlaye
UIViewController *SGRLyricsSettingsPage(NSString *title, NSString *intro, NSArray<SGModSection *> *sections) { return blank(title); }
#define ROW(name) SGModRow *name(void) { return SGPageRow(@#name, ^UIViewController *{ return nil; }); }
-ROW(SGAppIconRow) ROW(SGGeminiKeyRow) ROW(SGGlassLyricsRow) ROW(SGLockScreenLyricsRow) ROW(SGLyricsMeaningsRow)
+NSArray<SGModRow *> *SGAITranslatorRows(void) { return @[SGPageRow(@"SGAITranslatorRows", ^UIViewController *{ return nil; })]; }
+ROW(SGAppIconRow) ROW(SGGlassLyricsRow) ROW(SGLockScreenLyricsRow) ROW(SGLyricsMeaningsRow)
ROW(SGLyricsTranslationLanguageRow) ROW(SGLyricsWordTimingRow) ROW(SGRLyricsTextSizesRow) ROW(SGLyricsDelayRow)
NSArray<SGModRow *> *SGAppFontRows(void) { return @[]; }
NSArray<SGModRow *> *SGNativeAppearanceRows(void) { return @[]; }
diff --git a/harness/player/stubs.m b/harness/player/stubs.m
index dbacc772..640c4c97 100644
--- a/harness/player/stubs.m
+++ b/harness/player/stubs.m
@@ -128,12 +128,12 @@ void SGRHarnessPlayFrom(NSInteger ms) { SGKaraokeSeek(ms); }
void SGLyricsMeaningsFor(NSString *trackID, NSArray<SGKaraokeLine *> *lines,
void (^done)(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine)) {}
-// Gemini translation and the settings framework's top controller: not part of the harness.
+// AI translation and the settings framework's top controller: not part of the harness.
#import "Shared/LyricsTranslation/LyricsTranslation.h"
-BOOL SGGeminiKeySet(void) { return NO; }
+BOOL SGAITranslatorReady(void) { return NO; }
NSString *SGLyricsGeminiLanguage(void) { return @"en"; }
-void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
- void (^done)(NSArray<NSString *> *translations, NSString *error)) { done(nil, @"harness"); }
+void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
+ void (^done)(NSArray<NSString *> *translations, NSString *error)) { done(nil, @"harness"); }
// Local files: no edits in the harness, so the name is all PlayerLyrics.x needs to watch for one.
#import "Shared/LocalFiles/LocalFiles.h"
diff --git a/tweak/Sources/App/Pages.m b/tweak/Sources/App/Pages.m
index 618e8376..9f9dfcf0 100644
--- a/tweak/Sources/App/Pages.m
+++ b/tweak/Sources/App/Pages.m
@@ -120,7 +120,8 @@ static UIViewController *lyricsPage(void) {
SGSwitchRow(@"Hide the controls", @"A few seconds after the last touch, the lyrics take the whole player", SGRKeyLyricsAutoHide),
SGSwitchRow(@"Landscape lyrics", @"Turn the phone with the lyrics open", SGRKeyLyricsLandscape)]),
timing,
- SGSection(@"Translation", @[SGLyricsTranslationLanguageRow(), SGTranslateEverySongRow(), SGGeminiKeyRow(), SGGeminiModelRow(), SGGeminiPromptRow(), SGSavedTranslationsRow()]),
+ SGSection(@"Translation", [[@[SGLyricsTranslationLanguageRow(), SGTranslateEverySongRow()] arrayByAddingObjectsFromArray:SGAITranslatorRows()]
+ arrayByAddingObject:SGSavedTranslationsRow()]),
SGSection(nil, @[SGLyricsMeaningsRow()]),
]];
} else {
diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
index 5cc503c7..617fce05 100644
--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
@@ -1295,11 +1295,12 @@ typedef struct {
SGRKaraokeStyle *_style; // how the lines were laid out
BOOL _hasSpoken, _hasTranslation; // whether the song has any line with either
BOOL _untranslated; // whether a line with words has no translation, which a translator can fill in
+ SGTranslationSource *_saved; // who made the song's saved translation and when, nil with none saved
BOOL _foreign; // whether the song is in a language other than the one translations are asked in
NSArray<SGKaraokeLine *> *_passedOver; // lines kept for the song that changed nothing here, not looked at again
UIView *_extrasBox; // the Kit's glass and _extras over it, which holds none, so its alpha can fade
UIButton *_extras;
- NSArray<SGKaraokeLine *> *_translating; // the lines Gemini is translating, nil while it is not
+ NSArray<SGKaraokeLine *> *_translating; // the lines a translator is translating, nil while it is not
SGRSingButton *_sing; // across from _extras
CGFloat _builtWidth, _placedHeight;
BOOL _showing;
@@ -1819,7 +1820,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
_breakCount = 0;
_hasSpoken = _hasTranslation = _untranslated = NO;
_plain = SGKaraokeLinesTiming(_lines) == SGKaraokeTimingNone;
- if (!_sample) SGLyricsSyncSavedTranslation(_track, SGLyricsGeminiLanguage(), _lines);
+ _saved = _sample ? nil : SGLyricsSyncSavedTranslation(_track, SGLyricsGeminiLanguage(), _lines);
_foreign = inAnotherLanguage(_lines, SGLyricsGeminiLanguage());
NSInteger sungTo = 0; // the top of the song counts as where the singing before the first line ends
for (NSUInteger i = 0; i < count; i++) {
@@ -1919,10 +1920,10 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
// what the song has: a switch for each, reading what tapping it will do.
- (void)offerExtras {
NSString *language = SGLyricsGeminiLanguage();
- BOOL gemini = SGGeminiKeySet(), onDevice = SGOnDeviceTranslation.translationAvailable;
+ BOOL ai = SGAITranslatorReady(), onDevice = SGOnDeviceTranslation.translationAvailable;
BOOL intelligence = [SGOnDeviceTranslation appleIntelligenceAvailable:language];
// A translator is offered only for a song in another language than the one it would translate into.
- BOOL translatable = (_foreign || SGHidden(SGKeyLyricsTranslateEverySong)) && _untranslated && (gemini || onDevice || intelligence);
+ BOOL translatable = (_foreign || SGHidden(SGKeyLyricsTranslateEverySong)) && _untranslated && (ai || onDevice || intelligence);
BOOL offered = _lines && !_sample && (_hasSpoken || _hasTranslation || translatable);
if (!offered) {
_extrasBox.hidden = YES;
@@ -1969,30 +1970,52 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
image:[UIImage systemImageNamed:@"character.bubble"] identifier:nil
handler:^(UIAction *action) { SGRSetLyricsTextShown(SGRLyricsTextTranslation, !on); }]];
}
+ // Who made the saved translation and when, and for one an AI made (or no one known) a way to have it asked again.
+ if (_saved && _hasTranslation) {
+ UIAction *source = [UIAction actionWithTitle:_saved.name image:[UIImage systemImageNamed:@"info.circle"] identifier:nil handler:^(UIAction *action) {}];
+ source.subtitle = _saved.made ? [NSDateFormatter localizedStringFromDate:_saved.made dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle]
+ : @"Date unknown";
+ source.attributes = UIMenuElementAttributesDisabled;
+ NSMutableArray<UIMenuElement *> *about = [NSMutableArray arrayWithObject:source];
+ if (_saved.deletable) {
+ NSString *track = _track;
+ UIAction *delete = [UIAction actionWithTitle:@"Delete This Translation" image:[UIImage systemImageNamed:@"trash"] identifier:nil
+ handler:^(UIAction *action) { SGLyricsDeleteSavedTranslation(track, SGLyricsGeminiLanguage()); }];
+ delete.attributes = UIMenuElementAttributesDestructive;
+ [about addObject:delete];
+ }
+ [items addObject:[UIMenu menuWithTitle:@"Translated by" image:nil identifier:nil options:UIMenuOptionsDisplayInline children:about]];
+ }
// 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 (translatable && !translating) {
__weak SGRKaraokeView *weakSelf = self;
- void (^offer)(NSString *, NSString *, NSString *, SGRTranslator) = ^(NSString *title, NSString *glyph, NSString *subtitle, SGRTranslator translator) {
+ void (^offer)(NSString *, NSString *, NSString *, SGTranslationSource *(^)(void), SGRTranslator) =
+ ^(NSString *title, NSString *glyph, NSString *subtitle, SGTranslationSource *(^source)(void), SGRTranslator translator) {
UIAction *action = [UIAction actionWithTitle:title image:[UIImage systemImageNamed:glyph] identifier:nil
- handler:^(UIAction *action) { [weakSelf translateWith:translator]; }];
+ handler:^(UIAction *action) { [weakSelf translateWith:translator source:source()]; }];
action.subtitle = subtitle;
[items addObject:action];
};
if (onDevice) {
offer(@"Translate on iPhone", @"translate", @"Apple's Translate, on this iPhone",
+ ^{ return [SGTranslationSource by:SGTranslatedOnDevice model:nil made:nil]; },
^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated progress, SGRTranslated done) {
[SGOnDeviceTranslation translate:textsOf(lines) to:to done:done];
});
}
if (intelligence) {
offer(@"Translate with Apple Intelligence", @"apple.intelligence", @"On this iPhone",
+ ^{ return [SGTranslationSource by:SGTranslatedByAppleIntelligence model:nil made:nil]; },
^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated progress, SGRTranslated done) {
[SGOnDeviceTranslation translateWithAppleIntelligence:textsOf(lines) to:to song:SGLyricsSongName(track) progress:^(NSArray<NSString *> *soFar) { progress(soFar, nil); } done:done];
});
}
- if (gemini) offer(@"Translate with Gemini", @"sparkles", @"Sends the lyrics to Google", ^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated progress, SGRTranslated done) {
- SGLyricsTranslateWithGemini(track, lines, to, done);
+ // The provider and model are read as the item is tapped, which is when the request is made.
+ if (ai) offer([@"Translate with " stringByAppendingString:SGAITranslatorName()], @"sparkles",
+ [@"Sends the lyrics to " stringByAppendingString:SGAITranslatorRecipient()], ^{ return SGAITranslatorSource(); },
+ ^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated progress, SGRTranslated done) {
+ SGLyricsTranslateWithAI(track, lines, to, done);
});
}
_extras.menu = [UIMenu menuWithChildren:items];
@@ -2002,7 +2025,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
// The song's lines into the Lyrics page's language, or the phone's: each line without a translation takes
// the translator's, and translations are switched on so the answer shows. The whole song goes, for the sense.
-- (void)translateWith:(SGRTranslator)translator {
+- (void)translateWith:(SGRTranslator)translator source:(SGTranslationSource *)source {
NSArray<SGKaraokeLine *> *lines = _lines;
NSString *track = _track;
if (!lines.count || _translating == lines) return;
@@ -2012,14 +2035,14 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
// Kept a batch at a time too, so a translation cut off by Spotify closing keeps what was done.
translator(lines, track, language, ^(NSArray<NSString *> *soFar, NSString *error) {
[self takeTranslations:soFar into:lines];
- SGLyricsSaveTranslation(track, language, lines);
+ [self saved:SGLyricsSaveTranslation(track, language, lines, source) for:lines];
}, ^(NSArray<NSString *> *translations, NSString *error) {
if (self->_translating == lines) self->_translating = nil;
// Translations can come with a note, which names the lines left out. Those lines stay untranslated, and
// asking again sends only them.
if (translations) {
[self takeTranslations:translations into:lines];
- SGLyricsSaveTranslation(track, language, lines);
+ [self saved:SGLyricsSaveTranslation(track, language, lines, source) for:lines];
if (lines == self->_lines) self->_untranslated = anyUntranslated(lines);
}
[self offerExtras];
@@ -2050,6 +2073,13 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
[self offerExtras];
}
+// The menu names who made the song's translation as soon as it is saved, if the song is still the one shown.
+- (void)saved:(SGTranslationSource *)source for:(NSArray<SGKaraokeLine *> *)lines {
+ if (!source || lines != _lines) return;
+ _saved = source;
+ [self offerExtras];
+}
+
// The saved translations deleted, or Translate any song switched: the song is synced again and redrawn.
- (void)translationsChanged {
if (!_lines) return;
diff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
index c64d55db..d9fee517 100644
--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
@@ -1,12 +1,11 @@
-// A song's lines translated into any language by Gemini, on the user's own API key, at a tap in the
-// lyrics' corner menu. The key lives in the Keychain, not in the settings, so a settings export never
-// carries it. Only the lyrics' text and the language go out, to Google's Gemini API.
+// A song's lines translated into any language by an AI translator on the user's own API key (Gemini, an
+// OpenAI-compatible server, or Anthropic), at a tap in the lyrics' corner menu. Each key lives in the Keychain,
+// not in the settings, so a settings export never carries it. Only the lyrics' text and the language go out,
+// to the chosen provider.
#import <UIKit/UIKit.h>
@class SGKaraokeLine, SGModRow;
-BOOL SGGeminiKeySet(void);
-
// Posted on the main thread when the saved translations are deleted or Translate any song changes: the lyrics
// page syncs its song again and redraws.
extern NSNotificationName const SGLyricsTranslationsDidChangeNotification;
@@ -15,10 +14,38 @@ extern NSNotificationName const SGLyricsTranslationsDidChangeNotification;
#define SGKeyLyricsTranslateEverySong @"spotifyglass.lyrics.translateEverySong"
SGModRow *SGTranslateEverySongRow(void);
+// The AI translator: a provider's id (gemini, openai, anthropic; unset: gemini), the prompt every provider gets
+// (unset: Vitrine's), and per provider spotifyglass.lyrics.<id>.model, plus spotifyglass.lyrics.openai.url
+// for an OpenAI-compatible server (unset: OpenAI's). All read at each translation.
+#define SGKeyAITranslator @"spotifyglass.lyrics.ai"
+#define SGKeyAIPrompt @"spotifyglass.lyrics.prompt"
+
+// Who made a translation: an AI provider's id with its model, or one of the two on the iPhone. A translation
+// saved before sources were kept has neither, and reads as unknown.
+#define SGTranslatedOnDevice @"translate"
+#define SGTranslatedByAppleIntelligence @"intelligence"
+@interface SGTranslationSource : NSObject
+@property (nonatomic, copy, readonly) NSString *by, *model;
+@property (nonatomic, readonly) NSDate *made; // nil: not known
++ (instancetype)by:(NSString *)by model:(NSString *)model made:(NSDate *)made;
+@property (nonatomic, readonly) NSString *name; // "Gemini (gemini-flash-latest)", "Translate on iPhone", "Unknown"
+@property (nonatomic, readonly) BOOL deletable; // made by an AI provider, or by no one known
+@end
+
+// The chosen provider has its key, a model and, for an OpenAI-compatible one, a usable server URL.
+BOOL SGAITranslatorReady(void);
+// The menu item's words: "Gemini", "Anthropic", or an OpenAI-compatible server's model; and who gets the lyrics.
+NSString *SGAITranslatorName(void);
+NSString *SGAITranslatorRecipient(void);
+// The provider and model a translation asked now is made by.
+SGTranslationSource *SGAITranslatorSource(void);
+
// One translation per line, in order, or nil and a message to show. Main queue. The same song in the
-// same language, model and prompt is asked once a launch.
-void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
- void (^done)(NSArray<NSString *> *translations, NSString *error));
+// same language, provider, model and prompt is asked once a launch.
+void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
+ void (^done)(NSArray<NSString *> *translations, NSString *error));
+// Forgets the song's answers kept for the launch, so it is asked again; a nil track forgets every song's.
+void SGLyricsForgetAITranslation(NSString *trackID, NSString *languageTag);
// "“Title” by Artist" for a track the player or the local files know, for a translator's instructions; else nil.
NSString *SGLyricsSongName(NSString *trackID);
@@ -26,19 +53,15 @@ NSString *SGLyricsSongName(NSString *trackID);
// The language a translation is asked in: the Lyrics page's, else the phone's own.
NSString *SGLyricsGeminiLanguage(void);
-// Gemini's reply read: one translation per line when it has exactly `count`, else nil and in `problem`
-// why not (the key, the limit, a filter, a recitation stop, a line count that does not match).
-NSArray<NSString *> *SGGeminiTranslationsIn(id root, NSInteger status, NSError *error, NSUInteger count, NSString **problem);
-
-// The Lyrics page's row: shows whether a key is set, and sets or removes it.
-SGModRow *SGGeminiKeyRow(void);
+// The request a provider is sent, plain being the one without the optional fields some models turn down.
+// nil for an unknown provider or a server URL that is not usable.
+NSURLRequest *SGAITranslationRequest(NSString *provider, NSString *model, NSString *prompt, NSString *key, BOOL plain);
+// A provider's reply read: one translation per line when it has exactly `count`, else nil and in `problem`
+// why not (the key, the limit, a filter, a refusal, a length stop, a line count that does not match).
+NSArray<NSString *> *SGAITranslationsIn(NSString *provider, id root, NSInteger status, NSError *error, NSUInteger count, NSString **problem);
-// The model Gemini translates with and the prompt it gets, read at each translation. Unset: gemini-flash-latest
-// and Vitrine's own prompt.
-#define SGKeyGeminiModel @"spotifyglass.lyrics.gemini.model"
-#define SGKeyGeminiPrompt @"spotifyglass.lyrics.gemini.prompt"
-SGModRow *SGGeminiModelRow(void);
-SGModRow *SGGeminiPromptRow(void);
+// The Lyrics page's rows: the provider, its key (and server), its model, and the prompt.
+NSArray<SGModRow *> *SGAITranslatorRows(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
@@ -53,10 +76,16 @@ SGModRow *SGGeminiPromptRow(void);
done:(void (^)(NSArray<NSString *> *lines, NSString *error))done;
@end
-// SavedTranslations.m: a song's translations kept on disk by track and language, matched to lines by their text.
-// The saved ones are the truth for translations made here: syncing fills the lines with no translation from them,
-// and takes a made translation off a line that has none saved (after Delete). Main thread.
-void SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines);
-void SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines);
+// SavedTranslations.m: a song's translations kept on disk by track and language, matched to lines by their text,
+// with who made them and when. The saved ones are the truth for translations made here: syncing fills the lines
+// with no translation from them, and takes a made translation off a line that has none saved (after Delete).
+// Syncing and saving give the saved file's source, nil when there is none. Main thread.
+SGTranslationSource *SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines);
+SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines, SGTranslationSource *source);
+// Deletes the song's saved translation and the launch's answers for it, then posts SGLyricsTranslationsDidChangeNotification.
+void SGLyricsDeleteSavedTranslation(NSString *track, NSString *language);
+// A saved file read: its lines (text to translation) and its source, or nil. A file from before sources were
+// kept is the lines alone.
+NSDictionary<NSString *, NSString *> *SGSavedTranslationLines(id json, SGTranslationSource **source);
// The Lyrics page's row: how many songs are kept, and a tap to delete them.
SGModRow *SGSavedTranslationsRow(void);
diff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m
index 5fae2188..9c7f9990 100644
--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m
+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m
@@ -9,26 +9,216 @@
#import "Headers/SPTPlayer.h"
#import "LyricsTranslation.h"
-// gemini-flash-latest follows each Flash release; Google gives two weeks' notice of a breaking change.
-static NSString *const kDefaultModel = @"gemini-flash-latest";
-// The default, then cheaper ones, which is why a model is picked: Google's ids, and the names shown for them.
-static NSArray<NSString *> *models(void) { return @[kDefaultModel, @"gemini-3.6-flash", @"gemini-3.5-flash-lite"]; }
-static NSArray<NSString *> *modelNames(void) { return @[@"Flash (latest)", @"3.6 Flash", @"3.5 Flash-Lite"]; }
static NSString *const kDefaultPrompt =
- @"Translate the lines of this song into {language}. Answer with a JSON array of exactly {count} strings, one "
- @"per input line and in the same order. Translate the meaning naturally, keep each line short like a "
- @"lyric, and keep an empty line empty. A line already in {language} stays as it is.";
-static NSString *const kService = @"Vitrine.Gemini", *const kAccount = @"api-key";
+ @"Translate the lines of this song into {language}: exactly {count} translations, one per input line and in "
+ @"the same order. Translate the meaning naturally, keep each line short like a lyric, and keep an empty line "
+ @"empty. A line already in {language} stays as it is.";
+static NSString *const kOpenAIDefaultURL = @"https://api.openai.com/v1";
+static NSString *const kOpenAIURLKey = @"spotifyglass.lyrics.openai.url";
+
+#pragma mark - the providers
+
+// One entry per provider: adding one is a row here, its request and its reply's reader.
+typedef struct {
+ // Literals only, which live as long as the app.
+ __unsafe_unretained NSString *tag, *name, *company, *service, *keyNote, *format;
+ // Presets, nil-ended, the first being the default; none: the user names the model.
+ __unsafe_unretained NSString *models[4], *modelNames[4];
+ BOOL modelInURL; // the id goes into the URL's path, so only the characters of an id are let through
+ // Words of a 400 that send the plain request instead: the optional fields a model may not know.
+ __unsafe_unretained NSString *plainWhen[4];
+ NSMutableURLRequest *(*request)(NSString *model, NSString *prompt, NSString *key, BOOL plain);
+ // The answer's text, or nil and in `stopped` why the model stopped short.
+ NSString *(*answer)(NSDictionary *reply, NSString *speaker, NSString **stopped);
+} SGAIProvider;
+
+static NSString *filtered(NSString *speaker) { return [NSString stringWithFormat:@"%@'s filters blocked this song's lyrics.", speaker]; }
+static NSString *tooLong(NSString *speaker) { return [NSString stringWithFormat:@"The song is too long for one answer from %@.", speaker]; }
+static NSString *declined(NSString *speaker) { return [NSString stringWithFormat:@"%@ declined to translate the song.", speaker]; }
+
+static id dig(id root, NSArray *path) {
+ for (id step in path) {
+ if ([step isKindOfClass:NSNumber.class]) root = [root isKindOfClass:NSArray.class] && [root count] > [step unsignedIntegerValue] ? root[[step unsignedIntegerValue]] : nil;
+ else root = [root isKindOfClass:NSDictionary.class] ? root[step] : nil;
+ }
+ return root;
+}
-#pragma mark - the key
+static NSString *string(id value) {
+ return [value isKindOfClass:NSString.class] ? value : nil;
+}
+
+static NSMutableURLRequest *post(NSString *url, NSDictionary *body) {
+ NSURL *endpoint = url ? [NSURL URLWithString:url] : nil;
+ if (!endpoint) return nil;
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:endpoint];
+ request.HTTPMethod = @"POST";
+ request.timeoutInterval = 60;
+ [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
+ request.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:0 error:nil];
+ return request;
+}
-static NSDictionary *keyQuery(void) {
+// What OpenAI's strict schema and Anthropic's ask for: an object at the top, the lines under "lines".
+static NSDictionary *linesSchema(void) {
+ return @{@"type": @"object", @"properties": @{@"lines": @{@"type": @"array", @"items": @{@"type": @"string"}}},
+ @"required": @[@"lines"], @"additionalProperties": @NO};
+}
+
+// Gemini: generateContent, the key in x-goog-api-key, a bare array forced by responseSchema.
+static NSMutableURLRequest *geminiRequest(NSString *model, NSString *prompt, NSString *key, BOOL plain) {
+ // Lyrics are often explicit, and translating them is what the user asked for, so every filter that can
+ // be lowered is. Recitation cannot be switched off, and is named when it stops an answer.
+ NSMutableArray *safety = [NSMutableArray array];
+ for (NSString *category in @[@"HARM_CATEGORY_HARASSMENT", @"HARM_CATEGORY_HATE_SPEECH",
+ @"HARM_CATEGORY_SEXUALLY_EXPLICIT", @"HARM_CATEGORY_DANGEROUS_CONTENT"]) {
+ [safety addObject:@{@"category": category, @"threshold": @"BLOCK_NONE"}];
+ }
+ NSMutableDictionary *config = [@{@"responseMimeType": @"application/json",
+ @"responseSchema": @{@"type": @"ARRAY", @"items": @{@"type": @"STRING"}}} mutableCopy];
+ // Gemini 3 thinks at length by default, which a whole song's translation does not need and which made it
+ // slow enough to time out. Plain: a model behind gemini-flash-latest that does not know the field.
+ if (!plain) config[@"thinkingConfig"] = @{@"thinkingLevel": @"low"};
+ NSMutableURLRequest *request = post([NSString stringWithFormat:@"https://generativelanguage.googleapis.com/v1beta/models/%@:generateContent", model],
+ @{@"contents": @[@{@"parts": @[@{@"text": prompt}]}], @"safetySettings": safety, @"generationConfig": config});
+ [request setValue:key forHTTPHeaderField:@"x-goog-api-key"];
+ return request;
+}
+
+// Why Gemini stopped short, as finishReason or promptFeedback.blockReason name it.
+static NSString *geminiStop(NSString *reason) {
+ if ([reason isEqualToString:@"RECITATION"]) return @"Gemini stopped because its answer repeated published lyrics.";
+ if ([@[@"SAFETY", @"PROHIBITED_CONTENT", @"BLOCKLIST", @"SPII"] containsObject:reason]) return filtered(@"Gemini");
+ if ([reason isEqualToString:@"MAX_TOKENS"]) return tooLong(@"Gemini");
+ return [NSString stringWithFormat:@"Gemini stopped before translating the song (%@).", reason];
+}
+
+static NSString *geminiAnswer(NSDictionary *reply, NSString *speaker, NSString **stopped) {
+ NSString *blocked = string(dig(reply, @[@"promptFeedback", @"blockReason"]));
+ NSString *finished = string(dig(reply, @[@"candidates", @0, @"finishReason"]));
+ if (blocked) *stopped = geminiStop(blocked);
+ else if (finished && ![finished isEqualToString:@"STOP"]) *stopped = geminiStop(finished);
+ return *stopped ? nil : string(dig(reply, @[@"candidates", @0, @"content", @"parts", @0, @"text"]));
+}
+
+// A server URL as typed or restored: http or https with a host, nothing that could carry a secret (a user,
+// a password, a query) into an exported settings file, and without /chat/completions if it was pasted whole.
+static NSString *serverIn(NSString *text) {
+ NSString *trimmed = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
+ NSURLComponents *url = trimmed.length ? [NSURLComponents componentsWithString:trimmed] : nil;
+ NSString *scheme = url.scheme.lowercaseString;
+ if (!url.host.length || !([scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"])
+ || url.user || url.password || url.query || url.fragment) return nil;
+ NSString *path = url.path;
+ if ([path hasSuffix:@"/"]) path = [path substringToIndex:path.length - 1];
+ if ([path hasSuffix:@"/chat/completions"]) path = [path substringToIndex:path.length - 17];
+ url.path = path;
+ return url.string;
+}
+
+// Unset: OpenAI's own. Set to something unusable: none, so a key meant for another server never goes to OpenAI.
+static NSString *openAIServer(void) {
+ NSString *stored = [NSUserDefaults.standardUserDefaults stringForKey:kOpenAIURLKey];
+ return stored.length ? serverIn(stored) : kOpenAIDefaultURL;
+}
+
+// OpenAI-compatible: chat completions with a bearer key, the lines forced into {"lines": [...]} by a strict
+// schema. Plain: no schema and no reasoning effort, for servers and models that take neither.
+static NSMutableURLRequest *openAIRequest(NSString *model, NSString *prompt, NSString *key, BOOL plain) {
+ NSString *server = openAIServer();
+ NSMutableDictionary *body = [@{@"model": model, @"messages": @[@{@"role": @"user", @"content": prompt}]} mutableCopy];
+ if (!plain) {
+ body[@"response_format"] = @{@"type": @"json_schema",
+ @"json_schema": @{@"name": @"translation", @"strict": @YES, @"schema": linesSchema()}};
+ body[@"reasoning_effort"] = @"low";
+ }
+ NSMutableURLRequest *request = post(server ? [server stringByAppendingString:@"/chat/completions"] : nil, body);
+ [request setValue:[@"Bearer " stringByAppendingString:key] forHTTPHeaderField:@"Authorization"];
+ return request;
+}
+
+static NSString *openAIAnswer(NSDictionary *reply, NSString *speaker, NSString **stopped) {
+ NSString *finished = string(dig(reply, @[@"choices", @0, @"finish_reason"]));
+ if (string(dig(reply, @[@"choices", @0, @"message", @"refusal"])).length) *stopped = declined(speaker);
+ else if ([finished isEqualToString:@"length"]) *stopped = tooLong(speaker);
+ else if ([finished isEqualToString:@"content_filter"]) *stopped = filtered(speaker);
+ return *stopped ? nil : string(dig(reply, @[@"choices", @0, @"message", @"content"]));
+}
+
+// Anthropic: the Messages API, the lines forced by output_config.format, thinking kept short by a low effort.
+// max_tokens is required; output is billed as made, so a high cap costs nothing. Plain: without output_config,
+// for a model that knows neither field.
+static NSMutableURLRequest *anthropicRequest(NSString *model, NSString *prompt, NSString *key, BOOL plain) {
+ NSMutableDictionary *body = [@{@"model": model, @"max_tokens": @16000,
+ @"messages": @[@{@"role": @"user", @"content": prompt}]} mutableCopy];
+ if (!plain) body[@"output_config"] = @{@"effort": @"low", @"format": @{@"type": @"json_schema", @"schema": linesSchema()}};
+ NSMutableURLRequest *request = post(@"https://api.anthropic.com/v1/messages", body);
+ [request setValue:key forHTTPHeaderField:@"x-api-key"];
+ [request setValue:@"2026-10-21" forHTTPHeaderField:@"anthropic-version"];
+ return request;
+}
+
+static NSString *anthropicAnswer(NSDictionary *reply, NSString *speaker, NSString **stopped) {
+ NSString *finished = string(reply[@"stop_reason"]);
+ if ([finished isEqualToString:@"refusal"]) *stopped = declined(speaker);
+ else if ([finished isEqualToString:@"max_tokens"]) *stopped = tooLong(speaker);
+ if (*stopped) return nil;
+ NSMutableString *text = [NSMutableString string];
+ id blocks = reply[@"content"];
+ for (id block in [blocks isKindOfClass:NSArray.class] ? blocks : @[]) {
+ if ([string(dig(block, @[@"type"])) isEqualToString:@"text"]) [text appendString:string(dig(block, @[@"text"])) ?: @""];
+ }
+ return text.length ? text : nil;
+}
+
+static const SGAIProvider kProviders[] = {
+ {@"gemini", @"Gemini", @"Google", @"Vitrine.Gemini",
+ @"Translate with Gemini sends the song's lyrics to Google, on your own key from Google AI Studio. The key stays on this iPhone.",
+ @"Answer with a JSON array of the {count} translations as strings.",
+ // gemini-flash-latest follows each Flash release; Google gives two weeks' notice of a breaking change.
+ {@"gemini-flash-latest", @"gemini-3.6-flash", @"gemini-3.5-flash-lite"}, {@"Flash (latest)", @"3.6 Flash", @"3.5 Flash-Lite"},
+ YES, {@"thinking"}, geminiRequest, geminiAnswer},
+ {@"openai", @"OpenAI-compatible", nil, @"Vitrine.OpenAI",
+ @"Sends the song's lyrics to the server below: OpenAI's own unless you name another, such as OpenRouter, or an "
+ @"Ollama on your network (http works for local addresses). The key stays on this iPhone; for a server without "
+ @"keys, type anything.",
+ @"Answer with a JSON object whose \"lines\" array holds the {count} translations as strings.",
+ {nil}, {nil}, NO, {@"response_format", @"json_schema", @"reasoning"}, openAIRequest, openAIAnswer},
+ {@"anthropic", @"Anthropic", @"Anthropic", @"Vitrine.Anthropic",
+ @"Translate with Anthropic sends the song's lyrics to Anthropic, on your own key from the Claude Console. The key stays on this iPhone.",
+ @"Answer with a JSON object whose \"lines\" array holds the {count} translations as strings.",
+ // The cheapest current model first: the reason a model is picked at all is what translating costs.
+ {@"claude-haiku-5-5", @"claude-sonnet-5-5", @"claude-opus-5-5"}, {@"Haiku 5.5", @"Sonnet 5.5", @"Opus 5.5"},
+ NO, {@"output_config", @"effort", @"json_schema"}, anthropicRequest, anthropicAnswer},
+};
+static const NSUInteger kProviderCount = sizeof(kProviders) / sizeof(kProviders[0]);
+
+static const SGAIProvider *providerFor(NSString *tag) {
+ for (NSUInteger i = 0; i < kProviderCount; i++) if ([kProviders[i].tag isEqualToString:tag]) return &kProviders[i];
+ return NULL;
+}
+
+// The chosen one; unset or unknown (a restored backup): Gemini, the first.
+static const SGAIProvider *chosen(void) {
+ return providerFor([NSUserDefaults.standardUserDefaults stringForKey:SGKeyAITranslator]) ?: &kProviders[0];
+}
+
+static BOOL isOpenAI(const SGAIProvider *p) { return [p->tag isEqualToString:@"openai"]; }
+
+// Who the messages name: the provider, or for an OpenAI-compatible one its server's host.
+static NSString *speaker(const SGAIProvider *p) {
+ return isOpenAI(p) ? ([NSURL URLWithString:openAIServer() ?: @""].host ?: @"The server") : p->name;
+}
+
+#pragma mark - the keys
+
+static NSDictionary *keyQuery(const SGAIProvider *p) {
return @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
- (__bridge id)kSecAttrService: kService, (__bridge id)kSecAttrAccount: kAccount};
+ (__bridge id)kSecAttrService: p->service, (__bridge id)kSecAttrAccount: @"api-key"};
}
-static NSString *storedKey(void) {
- NSMutableDictionary *query = [keyQuery() mutableCopy];
+static NSString *storedKey(const SGAIProvider *p) {
+ NSMutableDictionary *query = [keyQuery(p) mutableCopy];
query[(__bridge id)kSecReturnData] = @YES;
query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
CFTypeRef data = NULL;
@@ -37,18 +227,14 @@ static NSString *storedKey(void) {
return key.length ? key : nil;
}
-static void storeKey(NSString *key) {
- SecItemDelete((__bridge CFDictionaryRef)keyQuery());
+static void storeKey(const SGAIProvider *p, NSString *key) {
+ SecItemDelete((__bridge CFDictionaryRef)keyQuery(p));
if (!key.length) return;
- NSMutableDictionary *item = [keyQuery() mutableCopy];
+ NSMutableDictionary *item = [keyQuery(p) mutableCopy];
item[(__bridge id)kSecValueData] = [key dataUsingEncoding:NSUTF8StringEncoding];
item[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
- if (status != errSecSuccess) SGLog(@"gemini: the key could not be kept (%d)", (int)status);
-}
-
-BOOL SGGeminiKeySet(void) {
- return storedKey() != nil;
+ if (status != errSecSuccess) SGLog(@"ai: the %@ key could not be kept (%d)", p->tag, (int)status);
}
#pragma mark - the model and the prompt
@@ -58,25 +244,31 @@ static NSString *storedString(NSString *key) {
return value.length ? value : nil;
}
-// A model id as Google writes them, or nil: it goes into the request's URL, and a restored backup can bring
-// any text under its key.
-static NSString *modelIDIn(NSString *text) {
- static NSCharacterSet *other;
+static NSString *modelKey(const SGAIProvider *p) {
+ return [NSString stringWithFormat:@"spotifyglass.lyrics.%@.model", p->tag];
+}
+
+// A model id as the provider writes them, or nil: Gemini's goes into the request's URL, and a restored backup
+// can bring any text under its key. Ids in the body may have / and : (OpenRouter's, Ollama's).
+static NSString *modelIDIn(NSString *text, const SGAIProvider *p) {
+ static NSCharacterSet *strict, *loose;
static dispatch_once_t once;
dispatch_once(&once, ^{
- other = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_"].invertedSet;
+ NSString *idChars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_";
+ strict = [NSCharacterSet characterSetWithCharactersInString:idChars].invertedSet;
+ loose = [NSCharacterSet characterSetWithCharactersInString:[idChars stringByAppendingString:@"/:@"]].invertedSet;
});
NSString *modelID = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
- if ([modelID hasPrefix:@"models/"]) modelID = [modelID substringFromIndex:7];
- return modelID.length && [modelID rangeOfCharacterFromSet:other].location == NSNotFound ? modelID : nil;
+ if (p->modelInURL && [modelID hasPrefix:@"models/"]) modelID = [modelID substringFromIndex:7];
+ return modelID.length && modelID.length <= 200 && [modelID rangeOfCharacterFromSet:p->modelInURL ? strict : loose].location == NSNotFound ? modelID : nil;
}
-static NSString *model(void) {
- return modelIDIn(storedString(SGKeyGeminiModel)) ?: kDefaultModel;
+static NSString *model(const SGAIProvider *p) {
+ return modelIDIn(storedString(modelKey(p)), p) ?: p->models[0];
}
static NSString *promptTemplate(void) {
- return storedString(SGKeyGeminiPrompt) ?: kDefaultPrompt;
+ return storedString(SGKeyAIPrompt) ?: kDefaultPrompt;
}
// The first 8 hex digits of the template's SHA-256, for the log: which prompt went, never what the lyrics were.
@@ -87,6 +279,50 @@ static NSString *fingerprint(NSString *text) {
return [NSString stringWithFormat:@"%02x%02x%02x%02x", digest[0], digest[1], digest[2], digest[3]];
}
+BOOL SGAITranslatorReady(void) {
+ const SGAIProvider *p = chosen();
+ return storedKey(p) && model(p) && (!isOpenAI(p) || openAIServer());
+}
+
+NSString *SGAITranslatorName(void) {
+ const SGAIProvider *p = chosen();
+ return isOpenAI(p) ? model(p) ?: p->name : p->name;
+}
+
+NSString *SGAITranslatorRecipient(void) {
+ const SGAIProvider *p = chosen();
+ return p->company ?: speaker(p);
+}
+
+SGTranslationSource *SGAITranslatorSource(void) {
+ const SGAIProvider *p = chosen();
+ return [SGTranslationSource by:p->tag model:model(p) made:nil];
+}
+
+@implementation SGTranslationSource
+
++ (instancetype)by:(NSString *)by model:(NSString *)model made:(NSDate *)made {
+ SGTranslationSource *source = [self new];
+ source->_by = [by copy];
+ source->_model = [model copy];
+ source->_made = made;
+ return source;
+}
+
+- (NSString *)name {
+ const SGAIProvider *p = providerFor(_by);
+ if (p) return _model.length ? [NSString stringWithFormat:@"%@ (%@)", p->name, _model] : p->name;
+ if ([_by isEqualToString:SGTranslatedOnDevice]) return @"Translate on iPhone";
+ if ([_by isEqualToString:SGTranslatedByAppleIntelligence]) return @"Apple Intelligence";
+ return @"Unknown";
+}
+
+// Asking the iPhone again costs nothing, and its translation is the same.
+- (BOOL)deletable {
+ return ![_by isEqualToString:SGTranslatedOnDevice] && ![_by isEqualToString:SGTranslatedByAppleIntelligence];
+}
+@end
+
#pragma mark - asking
NSString *SGLyricsSongName(NSString *trackID) {
@@ -94,85 +330,92 @@ NSString *SGLyricsSongName(NSString *trackID) {
SPTPlayerTrack *track = trackID && !local ? SGKaraokeTrackFor(trackID) : nil;
NSString *title = local ? local[@"title"] : track.trackTitle, *artist = local ? local[@"artist"] : track.artistName;
if (![title isKindOfClass:NSString.class] || !title.length) return nil;
- return [artist isKindOfClass:NSString.class] && artist.length ? [NSString stringWithFormat:@"\u201C%@\u201D by %@", title, artist]
- : [NSString stringWithFormat:@"\u201C%@\u201D", title];
+ return [artist isKindOfClass:NSString.class] && artist.length ? [NSString stringWithFormat:@"“%@” by %@", title, artist]
+ : [NSString stringWithFormat:@"“%@”", title];
}
NSString *SGLyricsGeminiLanguage(void) {
return SGLyricsTranslationLanguage() ?: NSLocale.preferredLanguages.firstObject ?: @"en";
}
-// Why Gemini stopped short, as finishReason or promptFeedback.blockReason name it.
-static NSString *blockedBecause(NSString *reason) {
- if ([reason isEqualToString:@"RECITATION"]) return @"Gemini stopped because its answer repeated published lyrics.";
- if ([@[@"SAFETY", @"PROHIBITED_CONTENT", @"BLOCKLIST", @"SPII"] containsObject:reason]) return @"Gemini's filters blocked this song's lyrics.";
- if ([reason isEqualToString:@"MAX_TOKENS"]) return @"The song is too long for one answer from Gemini.";
- return [NSString stringWithFormat:@"Gemini stopped before translating the song (%@).", reason];
+NSURLRequest *SGAITranslationRequest(NSString *provider, NSString *modelID, NSString *prompt, NSString *key, BOOL plain) {
+ const SGAIProvider *p = providerFor(provider);
+ return p && modelID && key ? p->request(modelID, prompt, key, plain) : nil;
}
-NSArray<NSString *> *SGGeminiTranslationsIn(id root, NSInteger status, NSError *error, NSUInteger count, NSString **problem) {
+// The lines out of an answer: a bare array or {"lines": [...]}, whichever the request forced or the prompt asked
+// for, and inside a Markdown fence or a sentence when a model without a schema added one.
+static id linesIn(NSString *text) {
+ if (!text) return nil;
+ id parsed = [NSJSONSerialization JSONObjectWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
+ if (!parsed) {
+ NSRange open = [text rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"[{"]];
+ NSRange close = [text rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"]}"] options:NSBackwardsSearch];
+ if (open.location != NSNotFound && close.location != NSNotFound && close.location > open.location) {
+ NSString *inner = [text substringWithRange:NSMakeRange(open.location, close.location - open.location + 1)];
+ parsed = [NSJSONSerialization JSONObjectWithData:[inner dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
+ }
+ }
+ if ([parsed isKindOfClass:NSDictionary.class]) parsed = parsed[@"lines"];
+ return [parsed isKindOfClass:NSArray.class] ? parsed : nil;
+}
+
+NSArray<NSString *> *SGAITranslationsIn(NSString *provider, id root, NSInteger status, NSError *error, NSUInteger count, NSString **problem) {
+ const SGAIProvider *p = providerFor(provider) ?: &kProviders[0];
+ NSString *who = speaker(p);
NSDictionary *reply = [root isKindOfClass:NSDictionary.class] ? root : nil;
- id candidates = reply[@"candidates"];
- id first = [candidates isKindOfClass:NSArray.class] ? [candidates firstObject] : nil;
- id parts = [first isKindOfClass:NSDictionary.class] && [first[@"content"] isKindOfClass:NSDictionary.class] ? first[@"content"][@"parts"] : nil;
- id text = [parts isKindOfClass:NSArray.class] && [[parts firstObject] isKindOfClass:NSDictionary.class] ? [parts firstObject][@"text"] : nil;
- id parsed = [text isKindOfClass:NSString.class] ? [NSJSONSerialization JSONObjectWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] : nil;
- if ([parsed isKindOfClass:NSArray.class] && [parsed count] == count) {
+ NSString *stopped = nil;
+ NSArray *lines = status == 200 ? linesIn(p->answer(reply, who, &stopped)) : nil;
+ if (lines.count == count) {
NSMutableArray<NSString *> *clean = [NSMutableArray arrayWithCapacity:count];
- for (id line in parsed) [clean addObject:[line isKindOfClass:NSString.class] ? line : @""];
+ for (id line in lines) [clean addObject:[line isKindOfClass:NSString.class] ? line : @""];
return clean;
}
- id feedback = reply[@"promptFeedback"];
- id blocked = [feedback isKindOfClass:NSDictionary.class] ? feedback[@"blockReason"] : nil;
- id finished = [first isKindOfClass:NSDictionary.class] ? first[@"finishReason"] : nil;
- id failed = [reply[@"error"] isKindOfClass:NSDictionary.class] ? reply[@"error"][@"message"] : nil;
- NSString *googleSays = [failed isKindOfClass:NSString.class] ? failed : nil;
+ // {"error": {"message": ...}} from all three; a bare string from some compatible servers.
+ NSString *says = string(dig(reply, @[@"error", @"message"])) ?: string(reply[@"error"]);
if (error) {
- *problem = @"Gemini could not be reached.";
- } else if (status == 401 || status == 403 || (status == 400 && [googleSays localizedCaseInsensitiveContainsString:@"API key"])) {
- *problem = @"Gemini turned the key down. Check it on the Lyrics page.";
- } else if (status == 400) {
- *problem = googleSays.length ? [NSString stringWithFormat:@"Gemini did not take the request: %@", googleSays]
- : @"Gemini did not take the request (400).";
+ *problem = [NSString stringWithFormat:@"%@ could not be reached.", who];
+ } else if (status == 401 || status == 403 || (status == 400 && [says localizedCaseInsensitiveContainsString:@"API key"])) {
+ *problem = [NSString stringWithFormat:@"%@ turned the key down. Check it on the Lyrics page.", who];
+ } else if (status == 400 || status == 404) {
+ *problem = says.length ? [NSString stringWithFormat:@"%@ did not take the request: %@", who, says]
+ : [NSString stringWithFormat:@"%@ did not take the request (%ld).", who, (long)status];
} else if (status == 429) {
- *problem = @"Gemini's limit for this key is reached for now.";
- } else if (status == 503 || status == 500) {
- *problem = @"Gemini is busy right now. Try again in a minute.";
+ *problem = [NSString stringWithFormat:@"%@'s limit for this key is reached for now.", who];
+ } else if (status >= 500) {
+ *problem = [NSString stringWithFormat:@"%@ is busy right now. Try again in a minute.", who];
} else if (status != 200) {
- *problem = [NSString stringWithFormat:@"Gemini did not translate the song (%ld).", (long)status];
- } else if ([blocked isKindOfClass:NSString.class]) {
- *problem = blockedBecause(blocked);
- } else if ([finished isKindOfClass:NSString.class] && ![finished isEqualToString:@"STOP"]) {
- *problem = blockedBecause(finished);
- } else if ([parsed isKindOfClass:NSArray.class]) {
- *problem = [NSString stringWithFormat:@"Gemini answered %lu lines for the song's %lu. Try again.",
- (unsigned long)[parsed count], (unsigned long)count];
+ *problem = [NSString stringWithFormat:@"%@ did not translate the song (%ld).", who, (long)status];
+ } else if (stopped) {
+ *problem = stopped;
+ } else if (lines) {
+ *problem = [NSString stringWithFormat:@"%@ answered %lu lines for the song's %lu. Try again.", who,
+ (unsigned long)lines.count, (unsigned long)count];
} else {
- *problem = @"Gemini's answer could not be read. Try again.";
+ *problem = [NSString stringWithFormat:@"%@'s answer could not be read. Try again.", who];
}
return nil;
}
-// Google's advice for a busy model or a full minute's quota (408, 429, 5xx): ask again after about 1, 2 and 4 s,
-// spread a little so phones do not all come back at once. A key turned down or a request that timed out is not
-// asked again.
-// plain is the same request without the thinking level, sent once if Gemini turns that field down: a model behind
-// gemini-flash-latest that does not know it still translates.
-static void sendToGemini(NSURLRequest *request, NSURLRequest *plain, NSUInteger attempt,
- void (^finished)(NSData *data, NSInteger status, NSError *error)) {
+// The providers' advice for a busy model or a full minute's quota (408, 429, 5xx): ask again after about 1, 2
+// and 4 s, spread a little so phones do not all come back at once. A key turned down or a request that timed
+// out is not asked again. plain is the same request without the optional fields, sent once if a 400 names one.
+static void send(const SGAIProvider *p, NSURLRequest *request, NSURLRequest *plain, NSUInteger attempt,
+ void (^finished)(NSData *data, NSInteger status, NSError *error)) {
[[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
NSString *reply = status == 400 && data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : nil;
- if (plain && [reply localizedCaseInsensitiveContainsString:@"thinking"]) {
- SGLog(@"gemini: the thinking level was turned down, asking without it");
- sendToGemini(plain, nil, attempt, finished);
+ for (NSUInteger i = 0; plain && reply && i < 4 && p->plainWhen[i]; i++) {
+ if (![reply localizedCaseInsensitiveContainsString:p->plainWhen[i]]) continue;
+ SGLog(@"ai: %@ turned down %@, asking without the optional fields", p->tag, p->plainWhen[i]);
+ send(p, plain, nil, attempt, finished);
return;
}
if (attempt < 3 && !error && (status == 408 || status == 429 || status >= 500)) {
double delay = (double)(1 << attempt) * (0.75 + arc4random_uniform(500) / 1000.0);
- SGLog(@"gemini: %ld, asking again in %.1f s", (long)status, delay);
+ SGLog(@"ai: %ld, asking again in %.1f s", (long)status, delay);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
- sendToGemini(request, plain, attempt + 1, finished);
+ send(p, request, plain, attempt + 1, finished);
});
return;
}
@@ -180,19 +423,30 @@ static void sendToGemini(NSURLRequest *request, NSURLRequest *plain, NSUInteger
}] resume];
}
-static NSMutableDictionary<NSString *, NSArray<NSString *> *> *sg_done; // per launch, by track and language
+// Per launch, by "track|language|" and then the provider, server, model and prompt: a translation asked again
+// after any of them changed is a new one.
+static NSMutableDictionary<NSString *, NSArray<NSString *> *> *sg_done;
+
+void SGLyricsForgetAITranslation(NSString *trackID, NSString *languageTag) {
+ if (!trackID) {
+ [sg_done removeAllObjects];
+ return;
+ }
+ NSString *song = [NSString stringWithFormat:@"%@|%@|", trackID, languageTag];
+ for (NSString *memo in sg_done.allKeys) if ([memo hasPrefix:song]) [sg_done removeObjectForKey:memo];
+}
-void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
- void (^done)(NSArray<NSString *> *translations, NSString *error)) {
- NSString *key = storedKey();
- if (!key) {
- done(nil, @"Add a Gemini API key on the Lyrics page first.");
+void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
+ void (^done)(NSArray<NSString *> *translations, NSString *error)) {
+ const SGAIProvider *p = chosen();
+ NSString *key = storedKey(p), *modelID = model(p), *template = promptTemplate();
+ if (!key || !modelID) {
+ done(nil, [NSString stringWithFormat:@"Add a %@ API key%@ on the Lyrics page first.", p->name, modelID ? @"" : @" and a model"]);
return;
}
if (!sg_done) sg_done = [NSMutableDictionary dictionary];
- // By model and prompt too: a translation asked again after either changed is a new one.
- NSString *modelID = model(), *template = promptTemplate();
- NSString *memo = [NSString stringWithFormat:@"%@|%@|%@|%@", trackID, languageTag, modelID, template];
+ NSString *memo = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@", trackID, languageTag, p->tag,
+ isOpenAI(p) ? openAIServer() : @"", modelID, template];
if (trackID && sg_done[memo].count == lines.count) {
done(sg_done[memo], nil);
return;
@@ -202,46 +456,24 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *li
// By the whole tag, so the script stays: zh-Hant is "Chinese, Traditional" where its language alone is "Chinese".
NSString *language = [[NSLocale localeWithLocaleIdentifier:@"en"] localizedStringForLocaleIdentifier:languageTag] ?: languageTag;
NSData *input = [NSJSONSerialization dataWithJSONObject:texts options:0 error:nil];
- // Filled in by replacing, never as a format: the template is the user's own text.
- NSString *instructions = [[template stringByReplacingOccurrencesOfString:@"{language}" withString:language]
- stringByReplacingOccurrencesOfString:@"{count}" withString:@(texts.count).stringValue];
+ // Filled in by replacing, never as a format: the template is the user's own text. The provider's own
+ // sentence on the answer's shape follows it, so an edited prompt cannot ask for the wrong one.
+ NSString *instructions = [NSString stringWithFormat:@"%@ %@", template, p->format];
+ instructions = [[instructions stringByReplacingOccurrencesOfString:@"{language}" withString:language]
+ stringByReplacingOccurrencesOfString:@"{count}" withString:@(texts.count).stringValue];
NSString *prompt = [NSString stringWithFormat:@"%@\n\n%@", instructions, [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding]];
- // Lyrics are often explicit, and translating them is what the user asked for, so every filter that can
- // be lowered is. Recitation cannot be switched off, and is named when it stops an answer.
- NSMutableArray *safety = [NSMutableArray array];
- for (NSString *category in @[@"HARM_CATEGORY_HARASSMENT", @"HARM_CATEGORY_HATE_SPEECH",
- @"HARM_CATEGORY_SEXUALLY_EXPLICIT", @"HARM_CATEGORY_DANGEROUS_CONTENT"]) {
- [safety addObject:@{@"category": category, @"threshold": @"BLOCK_NONE"}];
+ NSURLRequest *request = p->request(modelID, prompt, key, NO), *plain = p->request(modelID, prompt, key, YES);
+ if (!request) {
+ done(nil, @"The OpenAI-compatible server's URL is not usable. Check it on the Lyrics page.");
+ return;
}
- NSDictionary *body = @{
- @"contents": @[@{@"parts": @[@{@"text": prompt}]}],
- @"safetySettings": safety,
- @"generationConfig": @{
- @"responseMimeType": @"application/json",
- @"responseSchema": @{@"type": @"ARRAY", @"items": @{@"type": @"STRING"}},
- // Gemini 3 thinks at length by default, which a whole song's translation does not need and which
- // made it slow enough to time out.
- @"thinkingConfig": @{@"thinkingLevel": @"low"},
- },
- };
- NSString *endpoint = [NSString stringWithFormat:@"https://generativelanguage.googleapis.com/v1beta/models/%@:generateContent", modelID];
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:endpoint]];
- request.HTTPMethod = @"POST";
- request.timeoutInterval = 60;
- [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
- [request setValue:key forHTTPHeaderField:@"x-goog-api-key"];
- request.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:0 error:nil];
- NSMutableURLRequest *plain = [request mutableCopy];
- NSMutableDictionary *plainBody = [body mutableCopy], *plainConfig = [body[@"generationConfig"] mutableCopy];
- [plainConfig removeObjectForKey:@"thinkingConfig"];
- plainBody[@"generationConfig"] = plainConfig;
- plain.HTTPBody = [NSJSONSerialization dataWithJSONObject:plainBody options:0 error:nil];
- SGLog(@"gemini: asking %@, prompt %@%@", modelID, fingerprint(template), storedString(SGKeyGeminiPrompt) ? @" (edited)" : @"");
- sendToGemini(request, plain, 0, ^(NSData *data, NSInteger status, NSError *error) {
+ SGLog(@"ai: asking %@ %@ at %@, prompt %@%@", p->tag, modelID, request.URL.host, fingerprint(template),
+ storedString(SGKeyAIPrompt) ? @" (edited)" : @"");
+ send(p, request, plain, 0, ^(NSData *data, NSInteger status, NSError *error) {
id root = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
NSString *problem = nil;
- NSArray *translations = SGGeminiTranslationsIn(root, status, error, texts.count, &problem);
- SGLog(@"gemini: %@ lines into %@: %@", @(texts.count), languageTag, translations ? @"translated" : problem);
+ NSArray *translations = SGAITranslationsIn(p->tag, root, status, error, texts.count, &problem);
+ SGLog(@"ai: %@ %@ lines into %@: %@", p->tag, @(texts.count), languageTag, translations ? @"translated" : problem);
dispatch_async(dispatch_get_main_queue(), ^{
if (translations && trackID) sg_done[memo] = translations;
done(translations, problem);
@@ -249,79 +481,97 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *li
});
}
-#pragma mark - the row
+#pragma mark - the rows
+
+NSNotificationName const SGLyricsTranslationsDidChangeNotification = @"spotifyglass.lyricsTranslationsDidChange";
+
+SGModRow *SGTranslateEverySongRow(void) {
+ SGModRow *row = SGOptionRow(@"Translate any song", @"The lyrics' translate menu for songs that already read as your language",
+ SGKeyLyricsTranslateEverySong);
+ row.changed = ^(BOOL on) {
+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];
+ };
+ return row;
+}
+
+static void configure(UITextField *field, NSString *placeholder) {
+ field.placeholder = placeholder;
+ field.autocorrectionType = UITextAutocorrectionTypeNo;
+ field.autocapitalizationType = UITextAutocapitalizationTypeNone;
+}
+// The key, and for an OpenAI-compatible provider its server above it. Says what leaves the phone, not only
+// where the key stays: each song translated goes to the provider whole.
static void askForKey(void) {
- // Says what leaves the phone, not only where the key stays: each song translated goes to Google whole.
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Gemini API key"
- message:@"Translate with Gemini sends the song's lyrics to Google, on your own key from Google AI Studio. The key stays on this iPhone."
- preferredStyle:UIAlertControllerStyleAlert];
- // An empty field would store nothing and take the key away, which only Remove is for: Save waits for text.
+ const SGAIProvider *p = chosen();
+ BOOL server = isOpenAI(p), stored = storedKey(p) != nil;
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@ API key", p->name]
+ message:p->keyNote preferredStyle:UIAlertControllerStyleAlert];
+ alert.overrideUserInterfaceStyle = UIUserInterfaceStyleDark; // over the dark settings, whatever the system's
__weak UIAlertController *weakAlert = alert;
+ UITextField *(^keyField)(void) = ^UITextField *{ return weakAlert.textFields.lastObject; };
UIAlertAction *save = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
- // A key copied with the quotes around it, as from a code sample, is turned down by Google as it stands.
+ if (server) {
+ NSString *url = serverIn(weakAlert.textFields.firstObject.text);
+ if (url && ![url isEqualToString:kOpenAIDefaultURL]) [NSUserDefaults.standardUserDefaults setObject:url forKey:kOpenAIURLKey];
+ else [NSUserDefaults.standardUserDefaults removeObjectForKey:kOpenAIURLKey];
+ }
+ // A key copied with the quotes around it, as from a code sample, is turned down as it stands.
NSMutableCharacterSet *around = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[around addCharactersInString:@"\"'“”‘’"];
- NSString *key = [weakAlert.textFields.firstObject.text stringByTrimmingCharactersInSet:around];
- if (key.length) storeKey(key);
+ NSString *key = [keyField().text stringByTrimmingCharactersInSet:around];
+ if (key.length) storeKey(p, key); // empty keeps the one stored: Remove is what takes it away
}];
- save.enabled = NO;
__weak UIAlertAction *weakSave = save;
+ void (^check)(void) = ^{
+ BOOL typed = [keyField().text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length > 0;
+ NSString *url = weakAlert.textFields.firstObject.text;
+ BOOL serverOK = !server || !url.length || serverIn(url);
+ weakSave.enabled = (typed || (server && stored)) && serverOK;
+ };
+ if (server) {
+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
+ configure(field, kOpenAIDefaultURL);
+ field.text = storedString(kOpenAIURLKey);
+ field.keyboardType = UIKeyboardTypeURL;
+ field.textContentType = UITextContentTypeURL;
+ [field addAction:[UIAction actionWithHandler:^(UIAction *action) { check(); }] forControlEvents:UIControlEventEditingChanged];
+ }];
+ }
[alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
- field.placeholder = @"API key";
- field.secureTextEntry = YES;
- field.autocorrectionType = UITextAutocorrectionTypeNo;
- field.autocapitalizationType = UITextAutocapitalizationTypeNone;
- __weak UITextField *weakField = field; // the field keeps its actions, and the alert both
- [field addAction:[UIAction actionWithHandler:^(UIAction *action) {
- weakSave.enabled = [weakField.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length > 0;
- }] forControlEvents:UIControlEventEditingChanged];
+ configure(field, stored ? @"API key (unchanged)" : @"API key");
+ // Not a secure field: iOS offers to save what one held in Passwords, which syncs it through iCloud.
+ [field addAction:[UIAction actionWithHandler:^(UIAction *action) { check(); }] forControlEvents:UIControlEventEditingChanged];
}];
[alert addAction:save];
- if (SGGeminiKeySet()) {
+ check();
+ if (stored) {
[alert addAction:[UIAlertAction actionWithTitle:@"Remove" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
- storeKey(nil);
+ storeKey(p, nil);
}]];
}
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
[SGTopController() presentViewController:alert animated:YES completion:nil];
}
-NSNotificationName const SGLyricsTranslationsDidChangeNotification = @"spotifyglass.lyricsTranslationsDidChange";
-
-SGModRow *SGTranslateEverySongRow(void) {
- SGModRow *row = SGOptionRow(@"Translate any song", @"The lyrics' translate menu for songs that already read as your language",
- SGKeyLyricsTranslateEverySong);
- row.changed = ^(BOOL on) {
- [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];
- };
- return row;
-}
-
-SGModRow *SGGeminiKeyRow(void) {
- return SGStatActionRow(@"Gemini API key", @"Translate any song from the lyrics' corner menu",
- ^NSString *{ return SGGeminiKeySet() ? @"Set" : @"Off"; }, ^{ askForKey(); });
-}
-
-#pragma mark - the model and prompt rows
-
static void askForModel(void) {
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Gemini model"
- message:@"A model id from Google AI Studio, such as gemini-3.5-flash-lite." preferredStyle:UIAlertControllerStyleAlert];
+ const SGAIProvider *p = chosen();
+ NSString *example = p->models[1] ?: p->models[0] ?: @"gpt-6-astra, or a model your server lists";
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@ model", p->name]
+ message:[NSString stringWithFormat:@"A model id, such as %@.", example] preferredStyle:UIAlertControllerStyleAlert];
+ alert.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
__weak UIAlertController *weakAlert = alert;
UIAlertAction *save = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
- NSString *modelID = modelIDIn(weakAlert.textFields.firstObject.text);
- if (modelID) [NSUserDefaults.standardUserDefaults setObject:modelID forKey:SGKeyGeminiModel];
+ NSString *modelID = modelIDIn(weakAlert.textFields.firstObject.text, p);
+ if (modelID) [NSUserDefaults.standardUserDefaults setObject:modelID forKey:modelKey(p)];
}];
save.enabled = NO;
__weak UIAlertAction *weakSave = save;
[alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
- field.placeholder = kDefaultModel;
- field.text = storedString(SGKeyGeminiModel);
- field.autocorrectionType = UITextAutocorrectionTypeNo;
- field.autocapitalizationType = UITextAutocapitalizationTypeNone;
+ configure(field, p->models[0] ?: @"Model id");
+ field.text = storedString(modelKey(p));
__weak UITextField *weakField = field;
- [field addAction:[UIAction actionWithHandler:^(UIAction *action) { weakSave.enabled = modelIDIn(weakField.text) != nil; }]
+ [field addAction:[UIAction actionWithHandler:^(UIAction *action) { weakSave.enabled = modelIDIn(weakField.text, p) != nil; }]
forControlEvents:UIControlEventEditingChanged];
}];
[alert addAction:save];
@@ -329,19 +579,11 @@ static void askForModel(void) {
[SGTopController() presentViewController:alert animated:YES completion:nil];
}
-SGModRow *SGGeminiModelRow(void) {
- NSArray<NSString *> *names = [modelNames() arrayByAddingObject:@"Other…"];
- return SGMenuRow(@"Gemini model", names, ^NSString *{
- NSUInteger index = [models() indexOfObject:model()];
- return index == NSNotFound ? model() : modelNames()[index];
- }, ^(NSInteger index) {
- if (index < (NSInteger)models().count) {
- if (index == 0) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyGeminiModel];
- else [NSUserDefaults.standardUserDefaults setObject:models()[(NSUInteger)index] forKey:SGKeyGeminiModel];
- } else {
- askForModel();
- }
- });
+static NSArray<NSString *> *modelMenu(const SGAIProvider *p) {
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
+ for (NSUInteger i = 0; i < 4 && p->modelNames[i]; i++) [names addObject:p->modelNames[i]];
+ [names addObject:@"Other…"];
+ return names;
}
// The prompt in a sheet: the checkmark stores it, Default puts Vitrine's back in the field. Stored equal to the
@@ -368,7 +610,8 @@ SGModRow *SGGeminiModelRow(void) {
_text.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_text];
UILabel *note = [UILabel new];
- note.text = @"{language} and {count} are filled in for each song, and its lines follow the prompt as a JSON array.";
+ note.text = @"For every AI translator. {language} and {count} are filled in for each song; the translator is then "
+ @"told the shape of its answer, and the song's lines follow as a JSON array.";
note.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
note.adjustsFontForContentSizeCategory = YES;
note.textColor = UIColor.secondaryLabelColor;
@@ -403,19 +646,47 @@ SGModRow *SGGeminiModelRow(void) {
- (void)save {
NSString *prompt = [_text.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
- if (!prompt.length || [prompt isEqualToString:kDefaultPrompt]) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyGeminiPrompt];
- else [NSUserDefaults.standardUserDefaults setObject:prompt forKey:SGKeyGeminiPrompt];
- SGLog(@"gemini: prompt %@", storedString(SGKeyGeminiPrompt) ? [@"edited, " stringByAppendingString:fingerprint(prompt)] : @"default");
+ if (!prompt.length || [prompt isEqualToString:kDefaultPrompt]) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyAIPrompt];
+ else [NSUserDefaults.standardUserDefaults setObject:prompt forKey:SGKeyAIPrompt];
+ SGLog(@"ai: prompt %@", storedString(SGKeyAIPrompt) ? [@"edited, " stringByAppendingString:fingerprint(prompt)] : @"default");
[self close];
}
@end
-SGModRow *SGGeminiPromptRow(void) {
- return SGStatActionRow(@"Translation prompt", @"What Gemini is told to do with a song's lines",
- ^NSString *{ return storedString(SGKeyGeminiPrompt) ? @"Edited" : @"Default"; }, ^{
+NSArray<SGModRow *> *SGAITranslatorRows(void) {
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
+ for (NSUInteger i = 0; i < kProviderCount; i++) [names addObject:kProviders[i].name];
+ // A pick in a menu row reloads the page's rows; the model row's menu is the chosen provider's presets.
+ SGModRow *models = SGMenuRow(@"Model", modelMenu(chosen()), ^NSString *{
+ const SGAIProvider *p = chosen();
+ NSString *current = model(p);
+ for (NSUInteger i = 0; i < 4 && p->models[i]; i++) if ([p->models[i] isEqualToString:current]) return p->modelNames[i];
+ return current ?: @"Not set";
+ }, nil);
+ __weak SGModRow *weakModels = models;
+ models.chosen = ^(NSInteger index) {
+ const SGAIProvider *p = chosen();
+ if (index == 0 && p->models[0]) [NSUserDefaults.standardUserDefaults removeObjectForKey:modelKey(p)];
+ else if (index < 4 && p->models[index]) [NSUserDefaults.standardUserDefaults setObject:p->models[index] forKey:modelKey(p)];
+ else askForModel();
+ };
+ SGModRow *provider = SGMenuRow(@"AI translator", names, ^NSString *{ return chosen()->name; }, ^(NSInteger index) {
+ if (index == 0) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyAITranslator];
+ else [NSUserDefaults.standardUserDefaults setObject:kProviders[index].tag forKey:SGKeyAITranslator];
+ weakModels.menu = modelMenu(chosen());
+ SGLog(@"ai: translator %@", chosen()->tag);
+ });
+ SGModRow *key = SGStatActionRow(@"API key", @"Translate any song from the lyrics' corner menu", ^NSString *{
+ const SGAIProvider *p = chosen();
+ if (!storedKey(p)) return @"Off";
+ return isOpenAI(p) ? [NSURL URLWithString:openAIServer() ?: @""].host ?: @"Server not usable" : @"Set";
+ }, ^{ askForKey(); });
+ SGModRow *prompt = SGStatActionRow(@"Translation prompt", @"What the AI translator is told to do with a song's lines",
+ ^NSString *{ return storedString(SGKeyAIPrompt) ? @"Edited" : @"Default"; }, ^{
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[SGPromptEditor new]];
nav.modalPresentationStyle = UIModalPresentationPageSheet;
SGPresentDark(nav);
[SGTopController() presentViewController:nav animated:YES completion:nil];
});
+ return @[provider, key, models, prompt];
}
diff --git a/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m b/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m
index 373474ca..31cf5e3f 100644
--- a/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m
+++ b/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m
@@ -1,5 +1,6 @@
// Translations kept on disk, whichever way they were made: one small JSON file a song and language in
-// Caches/Vitrine/Translations, each line's text to its translation, so a song comes back translated after
+// Caches/Vitrine/Translations, each line's text to its translation under "lines" with who made it ("by",
+// "model") and when ("made", seconds since 1970), so a song comes back translated after
// a relaunch and lyrics from another source still find their lines. The newest kKept files stay; iOS may
// clear Caches when it runs low, which costs a translation again.
#import "Core/SGCore.h"
@@ -26,11 +27,24 @@ static NSArray<NSURL *> *files(void) {
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil] ?: @[];
}
-void SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) {
- if (!track.length || !language.length || !lines.count) return;
+NSDictionary<NSString *, NSString *> *SGSavedTranslationLines(id json, SGTranslationSource **source) {
+ if (![json isKindOfClass:NSDictionary.class]) return nil;
+ id lines = json[@"lines"];
+ if (![lines isKindOfClass:NSDictionary.class]) {
+ *source = [SGTranslationSource by:nil model:nil made:nil]; // saved before sources were kept
+ return json;
+ }
+ id by = json[@"by"], model = json[@"model"], made = json[@"made"];
+ *source = [SGTranslationSource by:[by isKindOfClass:NSString.class] ? by : nil model:[model isKindOfClass:NSString.class] ? model : nil
+ made:[made isKindOfClass:NSNumber.class] ? [NSDate dateWithTimeIntervalSince1970:[made doubleValue]] : nil];
+ return lines;
+}
+
+SGTranslationSource *SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) {
+ if (!track.length || !language.length || !lines.count) return nil;
NSData *data = [NSData dataWithContentsOfURL:fileFor(track, language)];
- id saved = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
- if (![saved isKindOfClass:NSDictionary.class]) saved = nil;
+ SGTranslationSource *source = nil;
+ NSDictionary *saved = SGSavedTranslationLines(data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil, &source);
for (SGKaraokeLine *line in lines) {
id translation = saved[SGKaraokeLineText(line) ?: @""];
BOOL has = [translation isKindOfClass:NSString.class] && [translation length];
@@ -42,22 +56,32 @@ void SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<S
line.translationMade = YES;
}
}
+ return saved ? source : nil;
}
-void SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) {
- if (!track.length || !language.length) return;
+// One at a time, in the order asked: a song is saved after every batch, and an older write must not land last.
+static dispatch_queue_t writes(void) {
+ static dispatch_queue_t queue;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ queue = dispatch_queue_create("vitrine.translations", DISPATCH_QUEUE_SERIAL); });
+ return queue;
+}
+
+SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines, SGTranslationSource *source) {
+ if (!track.length || !language.length) return nil;
NSMutableDictionary<NSString *, NSString *> *saved = [NSMutableDictionary dictionary];
for (SGKaraokeLine *line in lines) {
NSString *text = SGKaraokeLineText(line);
if (text.length && line.translation.length) saved[text] = line.translation;
}
- if (!saved.count) return;
- NSData *data = [NSJSONSerialization dataWithJSONObject:saved options:0 error:nil];
- // One at a time, in the order asked: a song is saved after every batch, and an older write must not land last.
- static dispatch_queue_t writes;
- static dispatch_once_t once;
- dispatch_once(&once, ^{ writes = dispatch_queue_create("vitrine.translations", DISPATCH_QUEUE_SERIAL); });
- dispatch_async(writes, ^{
+ if (!saved.count) return nil;
+ // The source of the last translation asked: a song finished by a second translator names the second.
+ NSDate *now = [NSDate date];
+ NSMutableDictionary *file = [@{@"lines": saved, @"made": @(floor(now.timeIntervalSince1970))} mutableCopy];
+ if (source.by) file[@"by"] = source.by;
+ if (source.model) file[@"model"] = source.model;
+ NSData *data = [NSJSONSerialization dataWithJSONObject:file options:0 error:nil];
+ dispatch_async(writes(), ^{
[NSFileManager.defaultManager createDirectoryAtURL:folder() withIntermediateDirectories:YES attributes:nil error:nil];
[data writeToURL:fileFor(track, language) atomically:YES];
NSArray<NSURL *> *all = files();
@@ -70,6 +94,20 @@ void SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKara
}];
for (NSUInteger i = 0; i < all.count - kKept; i++) [NSFileManager.defaultManager removeItemAtURL:oldestFirst[i] error:nil];
});
+ return [SGTranslationSource by:source.by model:source.model made:now];
+}
+
+void SGLyricsDeleteSavedTranslation(NSString *track, NSString *language) {
+ if (!track.length || !language.length) return;
+ SGLyricsForgetAITranslation(track, language);
+ // After any write still queued, so it cannot bring the file back.
+ dispatch_async(writes(), ^{
+ [NSFileManager.defaultManager removeItemAtURL:fileFor(track, language) error:nil];
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGLog(@"translation: %@ in %@ deleted", track, language);
+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];
+ });
+ });
}
static NSString *summary(void) {
@@ -86,13 +124,14 @@ static NSString *summary(void) {
}
SGModRow *SGSavedTranslationsRow(void) {
- return SGStatActionRow(@"Saved translations", @"Songs translated on this iPhone or by Gemini come back translated",
+ return SGStatActionRow(@"Saved translations", @"Songs translated on this iPhone or by an AI translator come back translated",
^NSString *{ return summary(); }, ^{
if (!files().count) return;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Delete saved translations?"
message:@"Songs translated before are translated again the next time you ask." preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
[NSFileManager.defaultManager removeItemAtURL:folder() error:nil];
+ SGLyricsForgetAITranslation(nil, nil);
SGLog(@"translation: saved translations deleted");
[NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];
}]];