Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat(lyrics): batch translate albums and playlists from the ellipsis menu (#145)
anna0a11c1097c9b
diff --git a/harness/lyrics-translation/build.sh b/harness/lyrics-translation/build.shindex a7b6d512..c66b119c 100755--- a/harness/lyrics-translation/build.sh+++ b/harness/lyrics-translation/build.sh@@ -9,5 +9,5 @@ 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" "$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"+ -framework UIKit -framework CoreGraphics -framework Security -framework NaturalLanguage -framework Foundation -o "$HERE/build/check""$HERE/build/check"diff --git a/harness/lyrics-translation/check.m b/harness/lyrics-translation/check.mindex a71a0a56..16227b76 100644--- a/harness/lyrics-translation/check.m+++ b/harness/lyrics-translation/check.m@@ -21,6 +21,10 @@ 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) {}+BOOL SGFlag(NSString *key, BOOL fallback) {+ id v = [NSUserDefaults.standardUserDefaults objectForKey:key];+ return v ? [v boolValue] : fallback;+}#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)diff --git a/harness/system-menu/main.m b/harness/system-menu/main.mindex b5b4a157..c11e257c 100644--- a/harness/system-menu/main.m+++ b/harness/system-menu/main.m@@ -20,6 +20,7 @@// The album footer is exercised by harness/album-queue and the Spotify simulator test. These// player-menu fixtures do not provide an album page or the shared album footer.void SGAlbumQueueInstall(UIViewController *menu) {}+void SGBatchTranslationInstall(UIViewController *menu) {}void SGRPlayerMenuWatch(UIView *button);// touch.m: a finger's touches, through UIKit's own recognizers.diff --git a/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.x b/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.xindex db084f19..46baa4a9 100644--- a/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.x+++ b/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.x@@ -7,7 +7,7 @@static const UIControlEvents kActivationEvents = UIControlEventTouchUpInside | UIControlEventPrimaryActionTriggered;static BOOL isMenuButton(UIControl *control) {- return [control.accessibilityIdentifier hasPrefix:SGAlbumQueueButtonPrefix];+ return [control.accessibilityIdentifier hasPrefix:@"Components.UI.ContextMenuButton"];}%hook UIControl@@ -34,6 +34,6 @@ static BOOL isMenuButton(UIControl *control) {%end%ctor {- if (!SGNativeUI() || !SGHidden(SGKeyFakePremium)) return;+ if (!SGNativeUI()) return;%init;}diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.xindex 3da506ac..ce7f5cb2 100644--- a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x@@ -27,6 +27,7 @@#import "Redesigned/Kit/SGRKit.h"#import "Shared/Player/SpeedPitch.h"#import "Shared/AlbumQueue/AlbumQueue.h"+#import "Shared/LyricsTranslation/BatchTranslation.h"#import "ContextMenu.h"// After a pick of Spotify's, how long its sheet has to start going, or to push a page of its own (which shows@@ -679,12 +680,20 @@ static void raiseHost(UIWindow *window) {}];}+- (UIMenuElement *)elementFor:(SGRSheetRow *)row {+ if ([row.control isKindOfClass:UIButton.class]) {+ UIButton *button = (UIButton *)row.control;+ if (button.menu && button.showsMenuAsPrimaryAction) return button.menu;+ }+ return [self actionFor:row];+}+- (NSArray<UIMenuElement *> *)rowElements {NSMutableArray<UIMenuElement *> *groups = [NSMutableArray array];for (NSArray<SGRSheetRow *> *group in _groups) {NSMutableArray<UIMenuElement *> *actions = [NSMutableArray array];for (SGRSheetRow *row in group) {- if (!row.quick) [actions addObject:[self actionFor:row]];+ if (!row.quick) [actions addObject:[self elementFor:row]];}if (actions.count) [groups addObject:inlineGroup(actions)];}@@ -847,6 +856,7 @@ static NSString *storedKey(NSString *kind) {UITableView *table = tableIn(self.sheet.viewIfLoaded, 0);if (!table || rowCount(table) == 0) return NO;SGAlbumQueueInstall(self.sheet);+ SGBatchTranslationInstall(self.sheet);CFTimeInterval started = CACurrentMediaTime();[table layoutIfNeeded];_table = table;diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.mindex d3424308..4e8495f1 100644--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m@@ -422,7 +422,7 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {}- (void)sgr_tap {- if ([self.source.accessibilityIdentifier hasPrefix:SGAlbumQueueButtonPrefix]) SGAlbumQueueMarkSource(self.source);+ if ([self.source.accessibilityIdentifier hasPrefix:@"Components.UI.ContextMenuButton"]) SGAlbumQueueMarkSource(self.source);SGRActivate(self.source);// The word is watched where Spotify writes it, but a button that rebuilds its content on the state it// just took writes the new word into a label the watch has never seen. So a tap, and only a tap, asks@@ -476,6 +476,7 @@ SGRMirrorButton *SGRPinnedMoreRecentButton(void) {sg_morePage = button.superview;sg_moreButton = button;sg_moreTappedAt = CACurrentMediaTime();+ SGAlbumQueueMarkSource(button.superview);}@enddiff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.mindex 721b4fb7..e333e91b 100644--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m@@ -1842,72 +1842,6 @@ static NSArray<NSString *> *textsOf(NSArray<SGKaraokeLine *> *lines) {return texts;}-// Letters outside the target's script, read from the characters: past Latin for a Latin-script language, Latin for-// any other. A short Korean line or one mixed with English, which the recognizer is not sure of, still counts.-static NSUInteger otherScriptLetters(NSString *text, BOOL latinTarget) {- __block NSUInteger count = 0;- [text enumerateSubstringsInRange:NSMakeRange(0, text.length) options:NSStringEnumerationByComposedCharacterSequences- usingBlock:^(NSString *character, NSRange range, NSRange enclosing, BOOL *stop) {- UTF32Char c = 0;- if (![character getBytes:&c maxLength:sizeof(c) usedLength:NULL encoding:NSUTF32LittleEndianStringEncoding options:0- range:NSMakeRange(0, character.length) remainingRange:NULL]) return;- if (![NSCharacterSet.letterCharacterSet longCharacterIsMember:c]) return;- BOOL latin = c < 0x250 || (c >= 0x1E00 && c < 0x1F00);- if (latin != latinTarget) count++;- }];- return count;-}--// Words spelled the way Korean is in Latin letters, with "eo" or "eu" (neol, geureon, eotteoke). Spicy Lyrics'-// community syncs give some K-pop this way. Of twenty English songs checked, no line had two such words.-static NSUInteger romanizedKoreanWords(NSString *text) {- NSUInteger count = 0;- for (NSString *word in [text componentsSeparatedByCharactersInSet:NSCharacterSet.letterCharacterSet.invertedSet]) {- if ([word containsString:@"eo"] || [word containsString:@"eu"]) count++;- }- return count;-}--// Whether a song is in a language other than `language`, line by line: one distinct line in five that the recognizer-// is at least 80% sure is another language, or two lines in another script (Hangul, kana, Han among English, for-// K-pop with only a verse in Korean). A line with two letters of another script counts however unsure the-// recognizer is: NewJeans' "New Jeans" has six such lines, all short or mixed with English. So does a line of Korean-// in Latin letters (romanizedKoreanWords). A chorus sung eight-// times weighs as one line. The whole song's guess is not asked: short lines sway it (it reads Havana, all "ooh-// na-na", as Dutch), and an unsure line counts neither way. A song with no line it is sure of counts as foreign,-// too little to tell.-static BOOL inAnotherLanguage(NSArray<SGKaraokeLine *> *lines, NSString *language) {- NSString *(^code)(NSString *) = ^NSString *(NSString *tag) {- return [tag componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-_"]].firstObject.lowercaseString;- };- NSString *target = code(language);- NSString *targetScript = [NSOrthography defaultOrthographyForLanguage:language].dominantScript;- NSUInteger distinct = 0, sure = 0, foreign = 0, otherScript = 0;- NSMutableSet<NSString *> *seen = [NSMutableSet set];- NLLanguageRecognizer *recognizer = [NLLanguageRecognizer new];- for (SGKaraokeLine *line in lines) {- NSString *text = hasWords(line) ? SGKaraokeLineText(line).lowercaseString : nil;- if (!text.length || [seen containsObject:text]) continue;- [seen addObject:text];- distinct++;- BOOL lettersOther = otherScriptLetters(text, [targetScript isEqualToString:@"Latn"]) >= 2;- if (lettersOther) otherScript++;- [recognizer reset];- [recognizer processString:text];- NSDictionary<NLLanguage, NSNumber *> *guess = [recognizer languageHypothesesWithMaximum:1];- NLLanguage found = guess.allKeys.firstObject;- BOOL confident = found && guess[found].doubleValue >= 0.8, inTarget = confident && [code(found) isEqualToString:target];- // A line sure to be in the target language does not count as romanized Korean, so French "peu" and "heure" stay.- if (!lettersOther && !inTarget && romanizedKoreanWords(text) >= 2) otherScript++;- if (!confident) continue;- sure++;- if (inTarget) continue;- foreign++;- if (!lettersOther && ![[NSOrthography defaultOrthographyForLanguage:found].dominantScript isEqualToString:targetScript]) otherScript++;- }- return !sure || foreign * 5 >= MAX(distinct, 5) || otherScript >= 2;-}-// Whether a line with words is still without a translation.static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {for (SGKaraokeLine *line in lines) if (!line.translation.length && hasWords(line)) return YES;@@ -1926,7 +1860,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {_plain = SGKaraokeLinesTiming(_lines) == SGKaraokeTimingNone;_savedLanguage = SGLyricsTranslationTarget();_saved = _sample ? nil : SGLyricsSyncSavedTranslation(_track, _savedLanguage, _lines);- _foreign = inAnotherLanguage(_lines, _savedLanguage);+ _foreign = SGKaraokeInAnotherLanguage(_lines, _savedLanguage);NSInteger sungTo = 0; // the top of the song counts as where the singing before the first line endsfor (NSUInteger i = 0; i < count; i++) {SGKaraokeLine *line = _lines[i];diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumPage.swift b/tweak/Sources/Shared/AlbumQueue/AlbumPage.swiftindex 17d153b7..0ba3767b 100644--- a/tweak/Sources/Shared/AlbumQueue/AlbumPage.swift+++ b/tweak/Sources/Shared/AlbumQueue/AlbumPage.swift@@ -14,3 +14,31 @@ public final class SGAlbumQueuePage: NSObject {return url.absoluteString}}++@objc(SGEntityPage)+public final class SGEntityPage: NSObject {+ @objc public static func entityURI(_ controller: AnyObject) -> String? {+ if let album = SGAlbumQueuePage.albumURI(controller) { return album }+ return playlistURI(controller)+ }++ @objc public static func playlistURI(_ controller: AnyObject) -> String? {+ func search(_ val: Any, depth: Int) -> String? {+ if depth > 4 { return nil }+ let mirror = Mirror(reflecting: val)+ for child in mirror.children {+ if let str = child.value as? String, str.hasPrefix("spotify:playlist:") {+ return str+ }+ if let url = child.value as? URL, url.absoluteString.hasPrefix("spotify:playlist:") {+ return url.absoluteString+ }+ if let res = search(child.value, depth: depth + 1) {+ return res+ }+ }+ return nil+ }+ return search(controller, depth: 0)+ }+}diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueue.h b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.hindex 4f63bf3c..d2254e37 100644--- a/tweak/Sources/Shared/AlbumQueue/AlbumQueue.h+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.h@@ -1,6 +1,16 @@#import <Foundation/Foundation.h>+#import <UIKit/UIKit.h>@class UIView, UIViewController;BOOL SGAlbumQueueIsAlbumURI(NSString *uri);+BOOL SGIsPlaylistURI(NSString *uri);+BOOL SGIsValidEntityURI(NSString *uri);+NSString *SGSanitizeEntityURI(NSString *raw);++// The confirmation notice shown under the Dynamic Island.+@interface SGAlbumQueueNotice : UIView++ (void)showIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol;++ (void)showIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol persistent:(BOOL)persistent;+@end// Spotify's ⋯ buttons. An album header's identifier ends in the album's id.#define SGAlbumQueueButtonPrefix @"Components.UI.ContextMenuButton-"diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.m b/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.mindex f4af5952..51738ff3 100644--- a/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.m+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.m@@ -33,4 +33,43 @@ NSArray<NSString *> *SGAlbumQueueTrackURIs(id context, NSString *uri, NSString *return tracks;}-BOOL SGAlbumQueueIsAlbumURI(NSString *uri) { return validURI(uri, @"spotify:album:"); }+NSString *SGSanitizeEntityURI(NSString *raw) {+ if (![raw isKindOfClass:NSString.class] || raw.length == 0) return nil;+ NSString *clean = raw;+ if ([clean hasPrefix:@"https://open.spotify.com/playlist/"]) {+ clean = [@"spotify:playlist:" stringByAppendingString:[clean substringFromIndex:@"https://open.spotify.com/playlist/".length]];+ } else if ([clean hasPrefix:@"https://open.spotify.com/album/"]) {+ clean = [@"spotify:album:" stringByAppendingString:[clean substringFromIndex:@"https://open.spotify.com/album/".length]];+ }+ for (NSString *prefix in @[@"spotify:playlist:", @"spotify:album:"]) {+ if ([clean hasPrefix:prefix]) {+ NSString *sub = [clean substringFromIndex:prefix.length];+ NSRange q = [sub rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"?:/#"]];+ if (q.location != NSNotFound) sub = [sub substringToIndex:q.location];+ if (sub.length == 22) {+ BOOL validChars = YES;+ for (NSUInteger i = 0; i < sub.length; i++) {+ unichar c = [sub characterAtIndex:i];+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {+ validChars = NO;+ break;+ }+ }+ if (validChars) return [prefix stringByAppendingString:sub];+ }+ }+ }+ return nil;+}++BOOL SGAlbumQueueIsAlbumURI(NSString *uri) {+ NSString *clean = SGSanitizeEntityURI(uri);+ return clean && [clean hasPrefix:@"spotify:album:"];+}+BOOL SGIsPlaylistURI(NSString *uri) {+ NSString *clean = SGSanitizeEntityURI(uri);+ return clean && [clean hasPrefix:@"spotify:playlist:"];+}+BOOL SGIsValidEntityURI(NSString *uri) {+ return SGSanitizeEntityURI(uri) != nil;+}diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.x b/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.xindex 149f7035..815af034 100644--- a/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.x+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.x@@ -1,5 +1,6 @@#import "Core/SGCore.h"#import "Shared/AdBlock/AdBlock.h"+#import "Shared/LyricsTranslation/BatchTranslation.h"#import "AlbumQueue.h"@interface SGAlbumQueuePage : NSObject@@ -43,6 +44,7 @@ static NSString *SGAlbumQueueURIForView(UIView *view) {void SGAlbumQueueMarkSource(UIView *view) {sg_pending = SGAlbumQueueURIForView(view);sg_markedAt = CACurrentMediaTime();+ SGBatchTranslationMarkSource(view);}static UITableView *tableIn(UIView *view, NSUInteger depth) {@@ -78,55 +80,199 @@ static BOOL hasNativeQueueRow(UITableView *table) {return NO;}+static UIWindow *activeWindow(UIWindow *window) {+ if (window && window.windowScene && !window.hidden) return window;+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {+ if (scene.activationState != UISceneActivationStateForegroundActive && scene.activationState != UISceneActivationStateForegroundInactive) continue;+ if (![scene isKindOfClass:UIWindowScene.class]) continue;+ for (UIWindow *w in ((UIWindowScene *)scene).windows) {+ if (!w.hidden && w.windowLevel == UIWindowLevelNormal) return w;+ }+ }+ return window;+}++@interface NSObject (SGSymbolEffects)++ (id)effect;++ (id)optionsWithRepeating;+- (id)optionsWithSpeed:(double)speed;++ (id)replaceDownUpTransition;+- (void)addSymbolEffect:(id)effect options:(id)options animated:(BOOL)animated;+- (void)removeAllSymbolEffects;+- (void)setSymbolImage:(UIImage *)image withContentTransition:(id)transition;+@end++static UIFont *footnoteTabularFont(void) {+ UIFont *base = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];+ return [UIFont monospacedDigitSystemFontOfSize:base.pointSize weight:UIFontWeightRegular];+}++#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wunguarded-availability-new"+#pragma clang diagnostic ignored "-Wdeprecated-declarations"+static void applySymbolToIcon(UIImageView *icon, NSString *symbol, NSString *previousSymbol, BOOL persistent, BOOL previousPersistent) {+ UIImage *img = [UIImage systemImageNamed:symbol];+ BOOL symbolChanged = !previousSymbol || ![previousSymbol isEqualToString:symbol];+ BOOL persistentChanged = persistent != previousPersistent;+ if (@available(iOS 17.0, *)) {+ Class transitionCls = NSClassFromString(@"NSSymbolReplaceContentTransition");+ if (previousSymbol && symbolChanged &&+ [transitionCls respondsToSelector:@selector(replaceDownUpTransition)] &&+ [icon respondsToSelector:@selector(setSymbolImage:withContentTransition:)]) {+ if ([icon respondsToSelector:@selector(removeAllSymbolEffects)]) [icon removeAllSymbolEffects];+ [icon setSymbolImage:img withContentTransition:[transitionCls replaceDownUpTransition]];+ } else if (symbolChanged) {+ icon.image = img;+ }+ if ([icon respondsToSelector:@selector(removeAllSymbolEffects)]) {+ if (persistent) {+ if (symbolChanged || persistentChanged) {+ Class pulseCls = NSClassFromString(@"NSSymbolPulseEffect");+ Class optsCls = NSClassFromString(@"NSSymbolEffectOptions");+ if ([pulseCls respondsToSelector:@selector(effect)] &&+ [optsCls respondsToSelector:@selector(optionsWithRepeating)] &&+ [icon respondsToSelector:@selector(addSymbolEffect:options:animated:)]) {+ id opts = [optsCls optionsWithRepeating];+ if ([opts respondsToSelector:@selector(optionsWithSpeed:)]) {+ opts = [opts optionsWithSpeed:0.2];+ }+ [icon addSymbolEffect:[pulseCls effect] options:opts animated:YES];+ }+ }+ } else if (persistentChanged || symbolChanged) {+ [icon removeAllSymbolEffects];+ }+ }+ } else if (symbolChanged) {+ icon.image = img;+ }+}+#pragma clang diagnostic pop+// The outcome as a glass capsule under the Dynamic Island, the way the system confirms an action.// It materializes on a critically damped spring, leaves the way it came, and a tap or an upward// swipe sends it off early. VoiceOver hears the same words.-@interface SGAlbumQueueNotice : UIView-@end@implementation SGAlbumQueueNotice {UIVisualEffectView *_glass;+ UIImageView *_icon;+ UILabel *_top;+ UILabel *_bottom;+ NSString *_symbol;CGFloat _restY;BOOL _leaving;+ BOOL _persistent;+ uint64_t _generation;}static __weak SGAlbumQueueNotice *sg_notice;+ (void)showIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol {+ [self showIn:window title:title detail:detail symbol:symbol persistent:NO];+}+++ (void)showIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol persistent:(BOOL)persistent {+ window = activeWindow(window);if (!window) return;++ SGAlbumQueueNotice *existing = sg_notice;+ if (existing && !existing->_leaving && existing.superview) {+ [existing updateTitle:title detail:detail symbol:symbol persistent:persistent];+ return;+ }+[sg_notice leave:0];SGAlbumQueueNotice *notice = [[self alloc] initWithFrame:CGRectZero];notice.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;- [notice buildIn:window title:title detail:detail symbol:symbol];+ [notice buildIn:window title:title detail:detail symbol:symbol persistent:persistent];sg_notice = notice;UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, notice.accessibilityLabel);- // Long enough to read: a confirmation is glanced at, a problem is read.- NSTimeInterval stay = detail ? 2.5 : 4;- __weak SGAlbumQueueNotice *weakNotice = notice;- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [weakNotice leave:0]; });++ if (!persistent) {+ uint64_t gen = notice->_generation;+ NSTimeInterval stay = detail ? 2.5 : 4;+ __weak SGAlbumQueueNotice *weakNotice = notice;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGAlbumQueueNotice *strongNotice = weakNotice;+ if (strongNotice && strongNotice->_generation == gen) [strongNotice leave:0];+ });+ }}-- (void)buildIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol {- UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:symbol]];- icon.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleBody scale:UIImageSymbolScaleMedium];- icon.tintColor = UIColor.labelColor;- icon.contentMode = UIViewContentModeCenter;- UILabel *top = [UILabel new];- top.text = title;+- (void)updateTitle:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol persistent:(BOOL)persistent {+ _generation++;+ BOOL titleChanged = ![_top.text isEqualToString:title];+ BOOL previousPersistent = _persistent;+ _persistent = persistent;+ _top.text = title;+ _bottom.text = detail;+ _bottom.font = footnoteTabularFont();+ applySymbolToIcon(_icon, symbol, _symbol, persistent, previousPersistent);+ _symbol = [symbol copy];+ self.accessibilityLabel = detail ? [NSString stringWithFormat:@"%@, %@", title, detail] : title;+ if (titleChanged || !persistent) {+ UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, self.accessibilityLabel);+ }++ UIWindow *window = self.window ?: activeWindow(nil);+ if (window) {+ CGFloat maxWidth = MIN(window.bounds.size.width - 32, 380), iconSide = 28, pad = 18, gap = 10;+ CGFloat textMax = maxWidth - pad * 2 - iconSide - gap;+ CGSize topSize = [_top sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)];+ CGSize bottomSize = detail ? [_bottom sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)] : CGSizeZero;+ CGFloat textWidth = MIN(textMax, MAX(topSize.width, bottomSize.width));+ CGFloat textHeight = topSize.height + bottomSize.height;+ CGFloat height = MAX(50, textHeight + 24), width = pad * 2 + iconSide + gap + textWidth;+ _restY = window.safeAreaInsets.top + 6;+ CGRect targetFrame = CGRectMake((window.bounds.size.width - width) / 2, _restY, width, height);++ [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState animations:^{+ self.frame = targetFrame;+ self->_glass.frame = self.bounds;+ SGShapeGlass(self->_glass, 22, textHeight < 40);+ self->_icon.frame = CGRectMake(pad, (height - iconSide) / 2, iconSide, iconSide);+ CGFloat y = (height - textHeight) / 2;+ self->_top.frame = CGRectMake(pad + iconSide + gap, y, textWidth, topSize.height);+ self->_bottom.frame = CGRectMake(pad + iconSide + gap, y + topSize.height, textWidth, bottomSize.height);+ } completion:nil];+ }++ if (!persistent) {+ uint64_t gen = _generation;+ NSTimeInterval stay = detail ? 2.5 : 4;+ __weak SGAlbumQueueNotice *weakNotice = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGAlbumQueueNotice *strongNotice = weakNotice;+ if (strongNotice && strongNotice->_generation == gen) [strongNotice leave:0];+ });+ }+}++- (void)buildIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol persistent:(BOOL)persistent {+ _persistent = persistent;+ _generation++;+ _symbol = [symbol copy];+ _icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:symbol]];+ _icon.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleBody scale:UIImageSymbolScaleMedium];+ _icon.tintColor = UIColor.labelColor;+ _icon.contentMode = UIViewContentModeCenter;+ applySymbolToIcon(_icon, symbol, nil, persistent, NO);+ _top = [UILabel new];+ _top.text = title;UIFont *subheadline = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];- top.font = [UIFont systemFontOfSize:subheadline.pointSize weight:UIFontWeightSemibold];- top.textColor = UIColor.labelColor;- top.numberOfLines = 0;- top.textAlignment = detail ? NSTextAlignmentNatural : NSTextAlignmentCenter;- UILabel *bottom = [UILabel new];- bottom.text = detail;- bottom.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];+ _top.font = [UIFont systemFontOfSize:subheadline.pointSize weight:UIFontWeightSemibold];+ _top.textColor = UIColor.labelColor;+ _top.numberOfLines = 0;+ _top.textAlignment = detail ? NSTextAlignmentNatural : NSTextAlignmentCenter;+ _bottom = [UILabel new];+ _bottom.text = detail;+ _bottom.font = footnoteTabularFont();// secondaryLabelColor reads under 3:1 on the tinted glass; this reads about 5.7:1.- bottom.textColor = [UIColor colorWithWhite:1 alpha:0.78];+ _bottom.textColor = [UIColor colorWithWhite:1 alpha:0.78];// Hugs its words, up to a width that keeps a line short enough to read at a glance.CGFloat maxWidth = MIN(window.bounds.size.width - 32, 380), iconSide = 28, pad = 18, gap = 10;CGFloat textMax = maxWidth - pad * 2 - iconSide - gap;- CGSize topSize = [top sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)];- CGSize bottomSize = detail ? [bottom sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)] : CGSizeZero;+ CGSize topSize = [_top sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)];+ CGSize bottomSize = detail ? [_bottom sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)] : CGSizeZero;CGFloat textWidth = MIN(textMax, MAX(topSize.width, bottomSize.width));CGFloat textHeight = topSize.height + bottomSize.height;CGFloat height = MAX(50, textHeight + 24), width = pad * 2 + iconSide + gap + textWidth;@@ -139,11 +285,11 @@ static __weak SGAlbumQueueNotice *sg_notice;_glass.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;[self addSubview:_glass];SGShapeGlass(_glass, 22, textHeight < 40);- icon.frame = CGRectMake(pad, (height - iconSide) / 2, iconSide, iconSide);+ _icon.frame = CGRectMake(pad, (height - iconSide) / 2, iconSide, iconSide);CGFloat y = (height - textHeight) / 2;- top.frame = CGRectMake(pad + iconSide + gap, y, textWidth, topSize.height);- bottom.frame = CGRectMake(pad + iconSide + gap, y + topSize.height, textWidth, bottomSize.height);- for (UIView *v in @[icon, top, bottom]) [_glass.contentView addSubview:v];+ _top.frame = CGRectMake(pad + iconSide + gap, y, textWidth, topSize.height);+ _bottom.frame = CGRectMake(pad + iconSide + gap, y + topSize.height, textWidth, bottomSize.height);+ for (UIView *v in @[_icon, _top, _bottom]) [_glass.contentView addSubview:v];self.isAccessibilityElement = YES;self.accessibilityLabel = detail ? [NSString stringWithFormat:@"%@, %@", title, detail] : title;@@ -190,6 +336,7 @@ static __weak SGAlbumQueueNotice *sg_notice;- (void)leave:(CGFloat)velocity {if (_leaving) return;_leaving = YES;+ _generation++;BOOL still = UIAccessibilityIsReduceMotionEnabled();CGFloat distance = self.frame.origin.y + self.bounds.size.height;CGFloat spring = distance > 0 && velocity < 0 ? -velocity / distance : 0;@@ -279,7 +426,6 @@ void SGAlbumQueueInstall(UIViewController *menu) {}if (native.boolValue) return;SGAlbumQueueRow *row = objc_getAssociatedObject(menu, &kRowKey);- if (table.tableFooterView && table.tableFooterView != row && table.tableFooterView.bounds.size.height > 0) return;if (!row) {row = [[SGAlbumQueueRow alloc] initWithFrame:CGRectZero];row.menu = menu;@@ -288,17 +434,48 @@ void SGAlbumQueueInstall(UIViewController *menu) {}row.uri = uri;CGFloat height = MAX(56, [UIFont preferredFontForTextStyle:UIFontTextStyleBody].lineHeight + 24);- CGSize size = CGSizeMake(table.bounds.size.width, height);- // The table moves its footer to the end of the content, so only the size says whether it changed.- if (table.tableFooterView != row || !CGSizeEqualToSize(row.bounds.size, size)) {- // Outside the sheet's rise, or the row slides down over Spotify's rows from the table's top.+ CGFloat width = table.bounds.size.width;+ UIView *existing = table.tableFooterView;+ if (existing == row) {+ if (!CGSizeEqualToSize(row.bounds.size, CGSizeMake(width, height))) {+ [UIView performWithoutAnimation:^{+ row.frame = CGRectMake(0, 0, width, height);+ table.tableFooterView = row;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];+ }+ return;+ }+ if (existing && ![existing isKindOfClass:UIControl.class] && [existing.subviews containsObject:row]) return;+ if (existing && existing.bounds.size.height > 0) {+ NSArray<UIView *> *existingRows = [existing isKindOfClass:UIControl.class] ? @[existing] : [existing.subviews copy];+ UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, existing.bounds.size.height + height)];+ container.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ CGFloat y = 0;+ row.frame = CGRectMake(0, y, width, height);+ y += height;+ [container addSubview:row];+ for (UIView *sub in existingRows) {+ if (sub == row) continue;+ sub.frame = CGRectMake(0, y, width, sub.bounds.size.height);+ y += sub.bounds.size.height;+ [container addSubview:sub];+ }+ container.frame = CGRectMake(0, 0, width, y);[UIView performWithoutAnimation:^{- row.frame = (CGRect){CGPointZero, size};- table.tableFooterView = row;+ table.tableFooterView = container;[table invalidateIntrinsicContentSize];[table layoutIfNeeded];}];+ return;}+ [UIView performWithoutAnimation:^{+ row.frame = CGRectMake(0, 0, width, height);+ table.tableFooterView = row;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];}%hook _TtC24ContextMenu_InternalImpl25ContextMenuViewControllerdiff --git a/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.h b/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.hnew file mode 100644index 00000000..b37c042c--- /dev/null+++ b/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.h@@ -0,0 +1,22 @@+// Batch translation of albums and playlists from the ellipsis menu.+#import <UIKit/UIKit.h>++@class UIViewController;++typedef NS_ENUM(NSInteger, SGBatchTranslationEngine) {+ SGBatchTranslationEngineAI,+ SGBatchTranslationEngineOnDevice,+ SGBatchTranslationEngineAppleIntelligence+};++// Starts batch translation for the given album or playlist URI.+void SGBatchTranslateURI(NSString *uri, SGBatchTranslationEngine engine, UIWindow *window);++// Installs the batch translation row into the context menu sheet's table footer.+void SGBatchTranslationInstall(UIViewController *menu);++// Records the source button/view that was tapped to open the menu.+void SGBatchTranslationMarkSource(UIView *view);++// Whether a batch translation is currently running.+BOOL SGBatchTranslationIsRunning(void);diff --git a/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.x b/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.xnew file mode 100644index 00000000..78beb008--- /dev/null+++ b/tweak/Sources/Shared/LyricsTranslation/BatchTranslation.x@@ -0,0 +1,736 @@+#import <dlfcn.h>+#import <objc/message.h>+#import "Core/SGCore.h"+#import "Shared/Lyrics/Lyrics.h"+#import "Shared/LyricsSources/LyricsSources.h"+#import "Shared/AlbumQueue/AlbumQueue.h"+#import "Settings/SGPageStyle.h"+#import "LyricsTranslation.h"+#import "BatchTranslation.h"++@interface SGEntityPage : NSObject++ (NSString *)entityURI:(id)controller;++ (NSString *)playlistURI:(id)controller;+@end++@interface SGBatchCandidateSong : NSObject+@property (nonatomic, copy) NSString *trackID;+@property (nonatomic, copy) NSString *trackURI;+@property (nonatomic, strong) NSArray<SGKaraokeLine *> *lines;+@property (nonatomic, strong) NSArray<NSString *> *texts;+@end+@implementation SGBatchCandidateSong+@end++static char kURIKey, kRowKey, kSeenKey;+static NSString *sg_pendingURI;+static CFTimeInterval sg_markedAt;+static BOOL sg_translating;++static UIWindow *normalAppWindow(UIWindow *preferred) {+ if (preferred && !preferred.hidden && preferred.windowLevel == UIWindowLevelNormal &&+ ![NSStringFromClass(preferred.class) isEqualToString:@"SGRSheetWindow"]) {+ return preferred;+ }+ for (UIWindow *w in preferred.windowScene.windows) {+ if (!w.hidden && w.windowLevel == UIWindowLevelNormal &&+ ![NSStringFromClass(w.class) isEqualToString:@"SGRSheetWindow"]) {+ return w;+ }+ }+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {+ if (scene.activationState != UISceneActivationStateForegroundActive &&+ scene.activationState != UISceneActivationStateForegroundInactive) continue;+ if (![scene isKindOfClass:UIWindowScene.class]) continue;+ for (UIWindow *w in ((UIWindowScene *)scene).windows) {+ if (!w.hidden && w.windowLevel == UIWindowLevelNormal &&+ ![NSStringFromClass(w.class) isEqualToString:@"SGRSheetWindow"]) {+ return w;+ }+ }+ }+ return preferred;+}++static NSString *SGExtractEntityURI(id object) {+ if (!object || [object isKindOfClass:UIView.class]) return nil;+ Class entityPage = NSClassFromString(@"SGEntityPage");+ if (entityPage && [entityPage respondsToSelector:@selector(entityURI:)]) {+ NSString *str = [entityPage performSelector:@selector(entityURI:) withObject:object];+ NSString *clean = SGSanitizeEntityURI(str);+ if (clean) return clean;+ }+ for (NSString *name in @[@"pageURI", @"playlistURI", @"playlistURL", @"entityURI", @"uri"]) {+ SEL sel = NSSelectorFromString(name);+ if ([object respondsToSelector:sel]) {+ id val = ((id (*)(id, SEL))objc_msgSend)(object, sel);+ NSString *str = [val isKindOfClass:NSURL.class] ? ((NSURL *)val).absoluteString : ([val isKindOfClass:NSString.class] ? (NSString *)val : nil);+ NSString *clean = SGSanitizeEntityURI(str);+ if (clean) return clean;+ }+ }+ return nil;+}++static NSString *SGResolveEntityURIForView(UIView *view) {+ for (UIResponder *r = view; r; r = r.nextResponder) {+ if (![r isKindOfClass:UIViewController.class]) continue;+ UIViewController *vc = (UIViewController *)r;+ NSString *uri = SGExtractEntityURI(vc);+ if (uri) return uri;+ if (vc.parentViewController) {+ uri = SGExtractEntityURI(vc.parentViewController);+ if (uri) return uri;+ }+ }+ return nil;+}++void SGBatchTranslationMarkSource(UIView *view) {+ NSString *resolved = SGResolveEntityURIForView(view);+ if (!SGIsValidEntityURI(resolved)) {+ sg_pendingURI = nil;+ return;+ }+ NSString *entityID = [resolved componentsSeparatedByString:@":"].lastObject;+ NSString *expectedIdent = entityID.length ? [SGAlbumQueueButtonPrefix stringByAppendingString:entityID] : nil;+ BOOL isEntitySource = ![view isKindOfClass:UIControl.class];+ if (!isEntitySource && expectedIdent && [view.accessibilityIdentifier isEqualToString:expectedIdent]) {+ isEntitySource = YES;+ }+ if (!isEntitySource) {+ BOOL inCell = NO, inHeader = NO;+ for (UIView *v = view; v; v = v.superview) {+ if ([v isKindOfClass:UITableViewCell.class] || [v isKindOfClass:UICollectionViewCell.class]) {+ inCell = YES;+ break;+ }+ if ([v.accessibilityIdentifier isEqualToString:@"CreativeWorkPlatform.Header"] ||+ [v.accessibilityIdentifier isEqualToString:@"PL.Header"]) {+ inHeader = YES;+ break;+ }+ }+ if (inHeader && !inCell) isEntitySource = YES;+ }+ if (isEntitySource) {+ sg_pendingURI = resolved;+ sg_markedAt = CACurrentMediaTime();+ } else {+ sg_pendingURI = nil;+ }+}++BOOL SGBatchTranslationIsRunning(void) {+ return sg_translating;+}++static NSArray<NSString *> *textsOfLines(NSArray<SGKaraokeLine *> *lines) {+ NSMutableArray *texts = [NSMutableArray arrayWithCapacity:lines.count];+ for (SGKaraokeLine *line in lines) {+ NSString *text = SGKaraokeLineText(line);+ [texts addObject:text ?: @""];+ }+ return texts;+}++#pragma mark - Track resolution++static void resolveTracks(NSString *uri, void (^completion)(NSArray<NSString *> *trackIDs, NSString *error)) {+ SGSpclientHeaders(^(NSDictionary<NSString *, NSString *> *headers) {+ if (!headers) {+ completion(nil, @"Spotify is not ready");+ return;+ }+ NSMutableArray<NSString *> *collected = [NSMutableArray array];+ NSMutableSet<NSString *> *seen = [NSMutableSet set];+ __block void (^fetchPage)(NSString *);+ fetchPage = ^(NSString *address) {+ NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:address]];+ req.timeoutInterval = 15;+ req.allHTTPHeaderFields = headers;+ [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];+ [[NSURLSession.sharedSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *err) {+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ id json = (status == 200 && data.length) ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;+ if (![json isKindOfClass:NSDictionary.class]) {+ fetchPage = nil;+ dispatch_async(dispatch_get_main_queue(), ^{+ completion(nil, @"Could not load songs");+ });+ return;+ }+ id pages = json[@"pages"];+ NSString *nextURL = nil;+ if ([pages isKindOfClass:NSArray.class]) {+ for (id page in pages) {+ if (![page isKindOfClass:NSDictionary.class]) continue;+ id next = page[@"next_page_url"];+ if ([next isKindOfClass:NSString.class] && [next length]) nextURL = next;+ id tracks = page[@"tracks"];+ if (![tracks isKindOfClass:NSArray.class]) continue;+ for (id entry in tracks) {+ if (![entry isKindOfClass:NSDictionary.class]) continue;+ NSString *tURI = entry[@"uri"];+ if ([tURI hasPrefix:@"spotify:track:"]) {+ NSString *tID = [tURI substringFromIndex:@"spotify:track:".length];+ if (tID.length == 22 && ![seen containsObject:tID]) {+ [seen addObject:tID];+ [collected addObject:tID];+ }+ }+ }+ }+ }+ if (nextURL) {+ fetchPage(nextURL);+ } else {+ fetchPage = nil;+ dispatch_async(dispatch_get_main_queue(), ^{+ completion(collected, nil);+ });+ }+ }] resume];+ };+ fetchPage([@"https://spclient.wg.spotify.com/context-resolve/v1/" stringByAppendingString:uri]);+ });+}++#pragma mark - Lyrics fetching for candidates++static void fetchSpotifyColorLyrics(NSString *trackID, NSDictionary<NSString *, NSString *> *headers,+ void (^completion)(NSArray<SGKaraokeLine *> *lines)) {+ if (!headers) {+ completion(nil);+ return;+ }+ NSString *address = [NSString stringWithFormat:@"https://spclient.wg.spotify.com/color-lyrics/v2/track/%@?format=json&vocalRemoval=false&market=from_token", trackID];+ NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:address]];+ req.allHTTPHeaderFields = headers;+ [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];+ [NSURLProtocol setProperty:@YES forKey:SGLyricsOwnRequestKey inRequest:req];+ [[NSURLSession.sharedSession dataTaskWithRequest:req completionHandler:^(NSData *body, NSURLResponse *response, NSError *error) {+ completion(SGKaraokeLinesFromBody(body));+ }] resume];+}++static void fetchLyricsForTrack(NSString *trackID, NSDictionary<NSString *, NSString *> *headers,+ void (^completion)(NSArray<SGKaraokeLine *> *lines)) {+ NSArray *cached = SGKaraokeLinesForTrack(trackID);+ if (cached.count) {+ completion(cached);+ return;+ }+ if (SGLyricsEnabled()) {+ SGLyricsFetch(trackID, ^(SGLyricsResult *result) {+ NSArray<SGKaraokeLine *> *providerLines = result.karaokeLines;+ if (providerLines.count && SGKaraokeLinesTiming(providerLines) != SGKaraokeTimingNone) {+ SGKaraokeKeepLines(trackID, providerLines);+ if (result.provider) SGLyricsSetCredit(trackID, result.provider);+ completion(providerLines);+ return;+ }+ fetchSpotifyColorLyrics(trackID, headers, ^(NSArray<SGKaraokeLine *> *spotifyLines) {+ if (spotifyLines.count && SGKaraokeLinesTiming(spotifyLines) != SGKaraokeTimingNone) {+ SGKaraokeKeepLines(trackID, spotifyLines);+ completion(spotifyLines);+ } else if (providerLines.count) {+ SGKaraokeKeepLines(trackID, providerLines);+ if (result.provider) SGLyricsSetCredit(trackID, result.provider);+ completion(providerLines);+ } else if (spotifyLines.count) {+ SGKaraokeKeepLines(trackID, spotifyLines);+ completion(spotifyLines);+ } else {+ completion(nil);+ }+ });+ });+ return;+ }+ fetchSpotifyColorLyrics(trackID, headers, ^(NSArray<SGKaraokeLine *> *spotifyLines) {+ if (spotifyLines.count) SGKaraokeKeepLines(trackID, spotifyLines);+ completion(spotifyLines);+ });+}++static void filterCandidateSongs(NSArray<NSString *> *trackIDs, NSString *targetLang,+ void (^completion)(NSArray<SGBatchCandidateSong *> *candidates, NSUInteger savedCount, NSUInteger sameLangCount)) {+ BOOL skipSaved = SGLyricsBatchSkipSaved();+ BOOL translateAny = SGHidden(SGKeyLyricsTranslateEverySong);+ SGSpclientHeaders(^(NSDictionary<NSString *, NSString *> *headers) {+ NSMutableArray<SGBatchCandidateSong *> *candidates = [NSMutableArray array];+ __block NSUInteger savedCount = 0;+ __block NSUInteger sameLangCount = 0;+ dispatch_group_t group = dispatch_group_create();+ for (NSString *trackID in trackIDs) {+ if (skipSaved && SGLyricsHasSavedTranslation(trackID, targetLang)) {+ savedCount++;+ continue;+ }+ dispatch_group_enter(group);+ fetchLyricsForTrack(trackID, headers, ^(NSArray<SGKaraokeLine *> *lines) {+ if (lines.count) {+ BOOL hasActualWords = NO;+ for (SGKaraokeLine *l in lines) {+ NSString *t = SGKaraokeLineText(l);+ if (t.length && ![t isEqualToString:@"♪"]) { hasActualWords = YES; break; }+ }+ if (hasActualWords) {+ if (translateAny || SGKaraokeInAnotherLanguage(lines, targetLang)) {+ SGBatchCandidateSong *song = [SGBatchCandidateSong new];+ song.trackID = trackID;+ song.trackURI = [@"spotify:track:" stringByAppendingString:trackID];+ song.lines = lines;+ song.texts = textsOfLines(lines);+ @synchronized (candidates) {+ [candidates addObject:song];+ }+ } else {+ @synchronized (candidates) {+ sameLangCount++;+ }+ }+ }+ }+ dispatch_group_leave(group);+ });+ }+ dispatch_group_notify(group, dispatch_get_main_queue(), ^{+ completion(candidates, savedCount, sameLangCount);+ });+ });+}++#pragma mark - Batch translation execution++void SGBatchTranslateURI(NSString *uri, SGBatchTranslationEngine engine, UIWindow *window) {+ window = normalAppWindow(window);+ if (sg_translating) {+ [SGAlbumQueueNotice showIn:window title:@"Already Translating" detail:@"Wait for this batch" symbol:@"exclamationmark.circle" persistent:NO];+ return;+ }+ sg_translating = YES;+ BOOL isAlbum = SGAlbumQueueIsAlbumURI(uri);+ NSString *entityName = isAlbum ? @"Album" : @"Playlist";+ NSString *targetLang = SGLyricsTranslationTarget();++ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"Translating %@", entityName] detail:@"Resolving songs…" symbol:@"translate" persistent:YES];++ resolveTracks(uri, ^(NSArray<NSString *> *trackIDs, NSString *resolveError) {+ if (resolveError || !trackIDs.count) {+ sg_translating = NO;+ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"Could Not Load %@", entityName] detail:resolveError ?: @"No songs found" symbol:@"exclamationmark.circle" persistent:NO];+ return;+ }+ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"Translating %@", entityName] detail:@"Checking lyrics…" symbol:@"translate" persistent:YES];+ filterCandidateSongs(trackIDs, targetLang, ^(NSArray<SGBatchCandidateSong *> *candidates, NSUInteger savedCount, NSUInteger sameLangCount) {+ if (!candidates.count) {+ sg_translating = NO;+ if (savedCount > 0 && sameLangCount == 0) {+ NSString *detail = savedCount == 1 ? @"1 song saved" : [NSString stringWithFormat:@"%lu songs saved", (unsigned long)savedCount];+ [SGAlbumQueueNotice showIn:window title:@"Already Translated" detail:detail symbol:@"checkmark.circle" persistent:NO];+ } else if (sameLangCount > 0 && savedCount == 0) {+ [SGAlbumQueueNotice showIn:window title:@"Already in Your Language" detail:nil symbol:@"checkmark.circle" persistent:NO];+ } else if (savedCount > 0) {+ [SGAlbumQueueNotice showIn:window title:@"Already Translated" detail:nil symbol:@"checkmark.circle" persistent:NO];+ } else {+ [SGAlbumQueueNotice showIn:window title:@"No Lyrics Found" detail:nil symbol:@"exclamationmark.circle" persistent:NO];+ }+ return;+ }+ NSUInteger total = candidates.count;+ __block NSUInteger completed = 0;++ if (engine == SGBatchTranslationEngineAI) {+ NSUInteger batchSize = SGLyricsBatchSize();+ if (batchSize == 0) batchSize = total;++ NSMutableArray<NSArray<SGBatchCandidateSong *> *> *chunks = [NSMutableArray array];+ for (NSUInteger i = 0; i < total; i += batchSize) {+ NSUInteger len = MIN(batchSize, total - i);+ [chunks addObject:[candidates subarrayWithRange:NSMakeRange(i, len)]];+ }++ NSMutableSet<NSString *> *savedTrackIDs = [NSMutableSet set];+ SGTranslationSource *source = SGAITranslatorSource();+ NSString *providerName = SGAITranslatorName() ?: @"AI";+ NSString *translatingTitle = [NSString stringWithFormat:@"Translating %@", entityName];++ void (^saveSongTranslation)(SGBatchCandidateSong *, NSArray<NSString *> *) = ^(SGBatchCandidateSong *song, NSArray<NSString *> *trans) {+ if (!song || trans.count != song.lines.count || [savedTrackIDs containsObject:song.trackID]) return;+ for (NSUInteger idx = 0; idx < song.lines.count; idx++) {+ SGKaraokeLine *line = song.lines[idx];+ NSString *t = trans[idx];+ if (t.length) {+ line.translation = t;+ line.translationMade = YES;+ }+ }+ SGLyricsSaveTranslation(song.trackID, targetLang, song.lines, source);+ [savedTrackIDs addObject:song.trackID];+ completed++;+ };++ __block void (^processChunk)(NSUInteger);+ processChunk = ^(NSUInteger chunkIndex) {+ if (chunkIndex >= chunks.count) {+ processChunk = nil;+ sg_translating = NO;+ NSString *detail = completed == 1 ? @"1 song saved" : [NSString stringWithFormat:@"%lu songs saved", (unsigned long)completed];+ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"%@ Translated", entityName] detail:detail symbol:@"checkmark.circle" persistent:NO];+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];+ return;+ }+ NSArray<SGBatchCandidateSong *> *chunk = chunks[chunkIndex];+ NSMutableDictionary<NSString *, NSArray<NSString *> *> *songsMap = [NSMutableDictionary dictionary];+ NSMutableDictionary<NSString *, SGBatchCandidateSong *> *lookup = [NSMutableDictionary dictionary];+ for (SGBatchCandidateSong *song in chunk) {+ songsMap[song.trackURI] = song.texts;+ lookup[song.trackURI] = song;+ lookup[song.trackID] = song;+ }+ NSString *askDetail = completed > 0+ ? [NSString stringWithFormat:@"%lu of %lu songs…", (unsigned long)completed, (unsigned long)total]+ : [NSString stringWithFormat:@"Asking %@…", providerName];+ [SGAlbumQueueNotice showIn:window title:translatingTitle detail:askDetail symbol:@"sparkles" persistent:YES];++ SGLyricsTranslateBatchWithAI(songsMap, targetLang, ^(NSString *phase) {+ if (!sg_translating) return;+ if ([phase isEqualToString:@"Thinking…"]) {+ NSString *thinkDetail = completed > 0+ ? [NSString stringWithFormat:@"Thinking • %lu/%lu…", (unsigned long)completed, (unsigned long)total]+ : @"Thinking…";+ [SGAlbumQueueNotice showIn:window title:translatingTitle detail:thinkDetail symbol:@"sparkles" persistent:YES];+ } else if ([phase isEqualToString:@"Writing"]) {+ NSString *writeDetail = [NSString stringWithFormat:@"%lu of %lu songs…", (unsigned long)MIN(completed + 1, total), (unsigned long)total];+ [SGAlbumQueueNotice showIn:window title:translatingTitle detail:writeDetail symbol:@"sparkles" persistent:YES];+ }+ }, ^(NSString *trackKey, NSArray<NSString *> *lines) {+ if (!sg_translating) return;+ SGBatchCandidateSong *song = lookup[trackKey];+ if (!song) {+ for (SGBatchCandidateSong *c in chunk) {+ if ([c.trackURI caseInsensitiveCompare:trackKey] == NSOrderedSame ||+ [c.trackID caseInsensitiveCompare:trackKey] == NSOrderedSame) {+ song = c;+ break;+ }+ }+ }+ if (song && lines.count == song.lines.count && ![savedTrackIDs containsObject:song.trackID]) {+ saveSongTranslation(song, lines);+ NSString *progressDetail = [NSString stringWithFormat:@"%lu of %lu songs…", (unsigned long)MIN(completed + 1, total), (unsigned long)total];+ [SGAlbumQueueNotice showIn:window title:translatingTitle detail:progressDetail symbol:@"sparkles" persistent:YES];+ }+ }, ^(NSDictionary<NSString *, NSArray<NSString *> *> *results, NSString *error) {+ if (results.count) {+ for (SGBatchCandidateSong *song in chunk) {+ NSArray<NSString *> *trans = results[song.trackURI] ?: results[song.trackID];+ if (trans.count == song.lines.count) {+ saveSongTranslation(song, trans);+ }+ }+ }+ if (error || !results.count) {+ processChunk = nil;+ sg_translating = NO;+ NSString *title = completed > 0+ ? [NSString stringWithFormat:@"Translated %lu of %lu", (unsigned long)completed, (unsigned long)total]+ : @"Translation Failed";+ NSString *detail = error ?: @"Could not read reply";+ [SGAlbumQueueNotice showIn:window title:title detail:detail symbol:@"exclamationmark.circle" persistent:NO];+ if (completed > 0) {+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];+ }+ return;+ }+ processChunk(chunkIndex + 1);+ });+ };+ processChunk(0);+ } else {+ BOOL isAI = (engine == SGBatchTranslationEngineAppleIntelligence);+ NSString *symbol = isAI ? @"apple.intelligence" : @"translate";+ NSString *by = isAI ? SGTranslatedByAppleIntelligence : SGTranslatedOnDevice;+ __block NSString *lastError = nil;+ __block void (^translateNext)(NSUInteger);+ translateNext = ^(NSUInteger idx) {+ if (idx >= total) {+ translateNext = nil;+ sg_translating = NO;+ if (completed == total) {+ NSString *detail = completed == 1 ? @"1 song saved" : [NSString stringWithFormat:@"%lu songs saved", (unsigned long)completed];+ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"%@ Translated", entityName] detail:detail symbol:@"checkmark.circle" persistent:NO];+ } else if (completed > 0) {+ NSString *title = [NSString stringWithFormat:@"Translated %lu of %lu", (unsigned long)completed, (unsigned long)total];+ NSString *detail = lastError ?: [NSString stringWithFormat:@"%lu songs saved", (unsigned long)completed];+ [SGAlbumQueueNotice showIn:window title:title detail:detail symbol:@"exclamationmark.circle" persistent:NO];+ } else {+ [SGAlbumQueueNotice showIn:window title:@"Translation Failed" detail:lastError ?: @"Could not translate songs" symbol:@"exclamationmark.circle" persistent:NO];+ }+ if (completed > 0) {+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];+ }+ return;+ }+ SGBatchCandidateSong *song = candidates[idx];+ [SGAlbumQueueNotice showIn:window title:[NSString stringWithFormat:@"Translating %@", entityName] detail:[NSString stringWithFormat:@"%lu of %lu songs…", (unsigned long)(idx + 1), (unsigned long)total] symbol:symbol persistent:YES];+ void (^onDone)(NSArray<NSString *> *, NSString *) = ^(NSArray<NSString *> *translations, NSString *err) {+ if (!err && translations.count == song.lines.count) {+ for (NSUInteger lIdx = 0; lIdx < song.lines.count; lIdx++) {+ NSString *t = translations[lIdx];+ if (t.length) {+ song.lines[lIdx].translation = t;+ song.lines[lIdx].translationMade = YES;+ }+ }+ SGLyricsSaveTranslation(song.trackID, targetLang, song.lines, [SGTranslationSource by:by model:nil made:nil]);+ completed++;+ } else if (err.length) {+ lastError = err;+ if ([err hasPrefix:@"Download "] ||+ [err containsString:@"needs iOS 26"] ||+ [err containsString:@"does not work in this language"]) {+ translateNext = nil;+ sg_translating = NO;+ NSString *title = completed > 0+ ? [NSString stringWithFormat:@"Translated %lu of %lu", (unsigned long)completed, (unsigned long)total]+ : @"Translation Failed";+ [SGAlbumQueueNotice showIn:window title:title detail:err symbol:@"exclamationmark.circle" persistent:NO];+ if (completed > 0) {+ [NSNotificationCenter.defaultCenter postNotificationName:SGLyricsTranslationsDidChangeNotification object:nil];+ }+ return;+ }+ }+ translateNext(idx + 1);+ };+ if (isAI) {+ [SGOnDeviceTranslation translateWithAppleIntelligence:song.texts to:targetLang song:SGLyricsSongName(song.trackID) progress:^(NSArray<NSString *> *soFar) {} done:onDone];+ } else {+ [SGOnDeviceTranslation translate:song.texts to:targetLang from:window done:onDone];+ }+ };+ translateNext(0);+ }+ });+ });+}++#pragma mark - Menu & Row UI++@interface SGBatchTranslateRow : UIButton+@property (nonatomic, copy) NSString *uri;+@property (nonatomic, weak) UIViewController *menuController;+@end++@implementation SGBatchTranslateRow {+ UILabel *_title;+ UIImageView *_icon;+ UIImageView *_chevron;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ _title = [UILabel new];+ _title.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ _title.adjustsFontForContentSizeCategory = YES;+ _title.textColor = UIColor.whiteColor;++ _icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"translate"]];+ _icon.tintColor = [UIColor colorWithWhite:1 alpha:0.65];+ _icon.contentMode = UIViewContentModeScaleAspectFit;++ _chevron = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"chevron.right"]];+ _chevron.tintColor = [UIColor colorWithWhite:1 alpha:0.35];+ _chevron.contentMode = UIViewContentModeScaleAspectFit;++ for (UIView *v in @[_title, _icon, _chevron]) {+ v.userInteractionEnabled = NO;+ [self addSubview:v];+ }+ self.isAccessibilityElement = YES;+ self.showsMenuAsPrimaryAction = YES;+ return self;+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat h = self.bounds.size.height, w = self.bounds.size.width;+ _icon.frame = CGRectMake(16, (h - 24) / 2, 24, 24);+ _chevron.frame = CGRectMake(MAX(0, w - 32), (h - 16) / 2, 16, 16);+ _title.frame = CGRectMake(56, 0, MAX(0, w - 96), h);+}++- (void)setHighlighted:(BOOL)highlighted {+ [super setHighlighted:highlighted];+ self.backgroundColor = [UIColor colorWithWhite:1 alpha:highlighted ? 0.08 : 0];+}++- (void)configureForURI:(NSString *)uri menuController:(UIViewController *)menu {+ _uri = [uri copy];+ _menuController = menu;+ BOOL isAlbum = SGAlbumQueueIsAlbumURI(uri);+ NSString *rowTitle = isAlbum ? @"Translate Album" : @"Translate Playlist";+ _title.text = rowTitle;+ self.accessibilityLabel = rowTitle;+ self.accessibilityIdentifier = @"spotifyglass.batchTranslate";++ UIWindow *window = normalAppWindow(menu.viewIfLoaded.window);++ NSString *targetLang = SGLyricsTranslationTarget();+ BOOL onDevice = SGFlag(SGKeyLyricsTranslateOnDevice, YES) && SGOnDeviceTranslation.translationAvailable;+ BOOL intelligence = SGFlag(SGKeyLyricsAppleIntelligence, YES) && [SGOnDeviceTranslation appleIntelligenceAvailable:targetLang];+ BOOL ai = SGAITranslatorReady();++ NSMutableArray<UIMenuElement *> *items = [NSMutableArray array];+ __weak UIViewController *weakMenu = menu;+ UIWindow *strongWindow = window;++ if (onDevice) {+ UIAction *action = [UIAction actionWithTitle:@"Translate on iPhone" image:[UIImage systemImageNamed:@"translate"] identifier:nil handler:^(UIAction *a) {+ [weakMenu dismissViewControllerAnimated:YES completion:nil];+ SGBatchTranslateURI(uri, SGBatchTranslationEngineOnDevice, strongWindow);+ }];+ action.subtitle = @"Apple's Translate, on this iPhone";+ [items addObject:action];+ }+ if (intelligence) {+ UIAction *action = [UIAction actionWithTitle:@"Translate with Apple Intelligence" image:[UIImage systemImageNamed:@"apple.intelligence"] identifier:nil handler:^(UIAction *a) {+ [weakMenu dismissViewControllerAnimated:YES completion:nil];+ SGBatchTranslateURI(uri, SGBatchTranslationEngineAppleIntelligence, strongWindow);+ }];+ action.subtitle = @"On this iPhone";+ [items addObject:action];+ }+ if (ai) {+ NSString *title = [@"Translate with " stringByAppendingString:SGAITranslatorName()];+ NSString *subtitle = [@"Sends the lyrics to " stringByAppendingString:SGAITranslatorRecipient()];+ UIAction *action = [UIAction actionWithTitle:title image:[UIImage systemImageNamed:@"sparkles"] identifier:nil handler:^(UIAction *a) {+ [weakMenu dismissViewControllerAnimated:YES completion:nil];+ SGBatchTranslateURI(uri, SGBatchTranslationEngineAI, strongWindow);+ }];+ action.subtitle = subtitle;+ [items addObject:action];+ }+ if (!onDevice && !intelligence && !ai) {+ UIAction *action = [UIAction actionWithTitle:@"No Translator Configured" image:[UIImage systemImageNamed:@"exclamationmark.circle"] identifier:nil handler:^(UIAction *a) {}];+ action.attributes = UIMenuElementAttributesDisabled;+ action.subtitle = @"Add an API key in Mod Settings > Lyrics";+ [items addObject:action];+ }+ self.menu = [UIMenu menuWithTitle:rowTitle image:[UIImage systemImageNamed:@"translate"] identifier:nil options:0 children:items];+ self.enabled = YES;+}+@end++static UITableView *tableInView(UIView *view, NSUInteger depth) {+ if ([view isKindOfClass:UITableView.class]) return (UITableView *)view;+ if (depth > 6) return nil;+ for (UIView *child in view.subviews) {+ UITableView *table = tableInView(child, depth + 1);+ if (table) return table;+ }+ return nil;+}++void SGBatchTranslationInstall(UIViewController *menu) {+ NSString *uri = objc_getAssociatedObject(menu, &kURIKey);+ if (!uri && !objc_getAssociatedObject(menu, &kSeenKey)) {+ objc_setAssociatedObject(menu, &kSeenKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ if (CACurrentMediaTime() - sg_markedAt <= 1.5 && SGIsValidEntityURI(sg_pendingURI)) {+ uri = SGSanitizeEntityURI(sg_pendingURI);+ }+ sg_pendingURI = nil;+ if (!uri) {+ typedef UIView *(*RecentPageFn)(void);+ RecentPageFn recentPage = (RecentPageFn)dlsym(RTLD_DEFAULT, "SGRPinnedMoreRecentPage");+ UIView *page = recentPage ? recentPage() : nil;+ if (page) uri = SGResolveEntityURIForView(page);+ }+ if (SGIsValidEntityURI(uri)) {+ uri = SGSanitizeEntityURI(uri);+ objc_setAssociatedObject(menu, &kURIKey, uri, OBJC_ASSOCIATION_COPY_NONATOMIC);+ }+ }+ if (!SGIsValidEntityURI(uri)) return;++ UITableView *table = tableInView(menu.viewIfLoaded, 0);+ if (!table) return;++ SGBatchTranslateRow *row = objc_getAssociatedObject(menu, &kRowKey);+ if (!row) {+ row = [[SGBatchTranslateRow alloc] initWithFrame:CGRectZero];+ objc_setAssociatedObject(menu, &kRowKey, row, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ [row configureForURI:uri menuController:menu];++ CGFloat rowHeight = MAX(56, [UIFont preferredFontForTextStyle:UIFontTextStyleBody].lineHeight + 24);+ CGFloat width = table.bounds.size.width;+ if (width <= 0) width = menu.viewIfLoaded.bounds.size.width;+ if (width <= 0) width = UIScreen.mainScreen.bounds.size.width;++ UIView *existingFooter = table.tableFooterView;+ if (existingFooter == row) {+ if (!CGSizeEqualToSize(row.bounds.size, CGSizeMake(width, rowHeight))) {+ [UIView performWithoutAnimation:^{+ row.frame = CGRectMake(0, 0, width, rowHeight);+ table.tableFooterView = row;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];+ }+ return;+ }++ if (existingFooter && ![existingFooter isKindOfClass:UIControl.class] && [existingFooter.subviews containsObject:row]) {+ return;+ }+ if (existingFooter && existingFooter.bounds.size.height > 0) {+ NSArray<UIView *> *existingRows = [existingFooter isKindOfClass:UIControl.class] ? @[existingFooter] : [existingFooter.subviews copy];+ UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, existingFooter.bounds.size.height + rowHeight)];+ container.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ CGFloat y = 0;+ for (UIView *sub in existingRows) {+ if (sub == row) continue;+ sub.frame = CGRectMake(0, y, width, sub.bounds.size.height);+ y += sub.bounds.size.height;+ [container addSubview:sub];+ }+ row.frame = CGRectMake(0, y, width, rowHeight);+ y += rowHeight;+ [container addSubview:row];+ container.frame = CGRectMake(0, 0, width, y);+ [UIView performWithoutAnimation:^{+ table.tableFooterView = container;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];+ return;+ }++ [UIView performWithoutAnimation:^{+ row.frame = CGRectMake(0, 0, width, rowHeight);+ table.tableFooterView = row;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];+}++%hook _TtC24ContextMenu_InternalImpl25ContextMenuViewController+- (void)viewWillAppear:(BOOL)animated {+ SGBatchTranslationInstall((UIViewController *)self);+ %orig;+}+- (void)viewDidLayoutSubviews {+ %orig;+ SGBatchTranslationInstall((UIViewController *)self);+}+%end++%ctor {+ %init;+ SGRequireClasses(@[@"_TtC24ContextMenu_InternalImpl25ContextMenuViewController"]);+}diff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.hindex 0371457c..10712430 100644--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h@@ -27,6 +27,13 @@ NSArray<SGModRow *> *SGOnDeviceTranslatorRows(void);// Gemini's thinking level (unset: low) and the request timeout in seconds for every provider (unset: 120).#define SGKeyAIThinking @"spotifyglass.lyrics.gemini.thinking"#define SGKeyAITimeout @"spotifyglass.lyrics.ai.timeout"+#define SGKeyLyricsBatchPrompt @"spotifyglass.lyrics.batch.prompt"+#define SGKeyLyricsBatchSize @"spotifyglass.lyrics.batch.size"+#define SGKeyLyricsBatchSkipSaved @"spotifyglass.lyrics.batch.skip_saved"++NSString *SGLyricsBatchPromptTemplate(void);+NSUInteger SGLyricsBatchSize(void);+BOOL SGLyricsBatchSkipSaved(void);// 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.@@ -54,6 +61,12 @@ SGTranslationSource *SGAITranslatorSource(void);// 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));+// Multiple songs translated in one prompt, keyed by track URI (or ID). Streams live phase ("Thinking…",+// "Writing") and per-song completions as each song's array closes in the SSE stream. Main queue.+void SGLyricsTranslateBatchWithAI(NSDictionary<NSString *, NSArray<NSString *> *> *songs, NSString *languageTag,+ void (^onPhase)(NSString *phase),+ void (^onSong)(NSString *trackKey, NSArray<NSString *> *lines),+ void (^done)(NSDictionary<NSString *, NSArray<NSString *> *> *results, 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);@@ -95,6 +108,9 @@ NSArray<SGModRow *> *SGAITranslatorRows(void);// Syncing gives the saved file's source, nil when none of its lines shows; saving gives the new one. Main thread.SGTranslationSource *SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines);SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines, SGTranslationSource *source);+BOOL SGLyricsHasSavedTranslation(NSString *track, NSString *language);+// Whether a song's lines read as another language than `language`.+BOOL SGKaraokeInAnotherLanguage(NSArray<SGKaraokeLine *> *lines, NSString *language);// 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 werediff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.mindex a0619e0b..c7a9c5db 100644--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.m@@ -1,4 +1,5 @@#import <CommonCrypto/CommonDigest.h>+#import <NaturalLanguage/NaturalLanguage.h>#import <Security/Security.h>#import "Core/SGCore.h"#import "Settings/SGModPage.h"@@ -13,6 +14,10 @@ static NSString *const kDefaultPrompt =@"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 kDefaultBatchPrompt =+ @"Translate the lyrics of these {count} songs into {language}. Translate the meaning naturally as sung, "+ @"keep each line short like a lyric, and keep empty lines empty. Lines already in {language} stay as they are. "+ @"Return a JSON object with the exact same track IDs as keys, mapping each to an array of translated lines in the exact same order.";static NSString *const kOpenAIDefaultURL = @"https://api.openai.com/v1";// The OpenAI-compatible server is kept beside its key, never in the settings: a settings file from someone// else could otherwise point a key stored here at their own server.@@ -116,7 +121,23 @@ static NSString *geminiAnswer(NSDictionary *reply, NSString *speaker, NSString *NSString *finished = string(dig(reply, @[@"candidates", @0, @"finishReason"]));if (blocked) *stopped = geminiStop(blocked, speaker);else if (finished && ![finished isEqualToString:@"STOP"]) *stopped = geminiStop(finished, speaker);- return *stopped ? nil : string(dig(reply, @[@"candidates", @0, @"content", @"parts", @0, @"text"]));+ if (*stopped) return nil;+ NSArray *parts = dig(reply, @[@"candidates", @0, @"content", @"parts"]);+ if (![parts isKindOfClass:NSArray.class]) return nil;+ for (id part in parts) {+ if ([part isKindOfClass:NSDictionary.class]) {+ NSNumber *thought = part[@"thought"];+ if (thought && [thought boolValue]) continue;+ NSString *t = string(part[@"text"]);+ if (t.length) return t;+ }+ }+ for (NSInteger i = (NSInteger)parts.count - 1; i >= 0; i--) {+ id part = parts[i];+ NSString *t = string(part[@"text"]);+ if (t.length) return t;+ }+ return nil;}// A server URL as typed or stored: http or https with a host, no user, password or query (which could carry a@@ -300,6 +321,82 @@ static NSString *promptTemplate(void) {return storedString(SGKeyAIPrompt) ?: kDefaultPrompt;}+NSString *SGLyricsBatchPromptTemplate(void) {+ return storedString(SGKeyLyricsBatchPrompt) ?: kDefaultBatchPrompt;+}++NSUInteger SGLyricsBatchSize(void) {+ NSNumber *val = [NSUserDefaults.standardUserDefaults objectForKey:SGKeyLyricsBatchSize];+ if (!val) return 20;+ NSInteger n = val.integerValue;+ if (n == 0) return 0;+ if (n == 10 || n == 20 || n == 30 || n == 40 || n == 50) return (NSUInteger)n;+ return 20;+}++BOOL SGLyricsBatchSkipSaved(void) {+ return SGFlag(SGKeyLyricsBatchSkipSaved, YES);+}++static BOOL hasWords(SGKaraokeLine *line) {+ NSString *text = SGKaraokeLineText(line);+ return text.length > 0 && ![text isEqualToString:@"♪"];+}++static NSUInteger otherScriptLetters(NSString *text, BOOL latinTarget) {+ __block NSUInteger count = 0;+ [text enumerateSubstringsInRange:NSMakeRange(0, text.length) options:NSStringEnumerationByComposedCharacterSequences+ usingBlock:^(NSString *character, NSRange range, NSRange enclosing, BOOL *stop) {+ UTF32Char c = 0;+ if (![character getBytes:&c maxLength:sizeof(c) usedLength:NULL encoding:NSUTF32LittleEndianStringEncoding options:0+ range:NSMakeRange(0, character.length) remainingRange:NULL]) return;+ if (![NSCharacterSet.letterCharacterSet longCharacterIsMember:c]) return;+ BOOL latin = c < 0x250 || (c >= 0x1E00 && c < 0x1F00);+ if (latin != latinTarget) count++;+ }];+ return count;+}++static NSUInteger romanizedKoreanWords(NSString *text) {+ NSUInteger count = 0;+ for (NSString *word in [text componentsSeparatedByCharactersInSet:NSCharacterSet.letterCharacterSet.invertedSet]) {+ if ([word containsString:@"eo"] || [word containsString:@"eu"]) count++;+ }+ return count;+}++BOOL SGKaraokeInAnotherLanguage(NSArray<SGKaraokeLine *> *lines, NSString *language) {+ if (!lines.count || !language.length) return NO;+ NSString *(^code)(NSString *) = ^NSString *(NSString *tag) {+ return [tag componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-_"]].firstObject.lowercaseString;+ };+ NSString *target = code(language);+ NSString *targetScript = [NSOrthography defaultOrthographyForLanguage:language].dominantScript;+ NSUInteger distinct = 0, sure = 0, foreign = 0, otherScript = 0;+ NSMutableSet<NSString *> *seen = [NSMutableSet set];+ NLLanguageRecognizer *recognizer = [NLLanguageRecognizer new];+ for (SGKaraokeLine *line in lines) {+ NSString *text = hasWords(line) ? SGKaraokeLineText(line).lowercaseString : nil;+ if (!text.length || [seen containsObject:text]) continue;+ [seen addObject:text];+ distinct++;+ BOOL lettersOther = otherScriptLetters(text, [targetScript isEqualToString:@"Latn"]) >= 2;+ if (lettersOther) otherScript++;+ [recognizer reset];+ [recognizer processString:text];+ NSDictionary<NLLanguage, NSNumber *> *guess = [recognizer languageHypothesesWithMaximum:1];+ NLLanguage found = guess.allKeys.firstObject;+ BOOL confident = found && guess[found].doubleValue >= 0.8, inTarget = confident && [code(found) isEqualToString:target];+ if (!lettersOther && !inTarget && romanizedKoreanWords(text) >= 2) otherScript++;+ if (!confident) continue;+ sure++;+ if (inTarget) continue;+ foreign++;+ if (!lettersOther && ![[NSOrthography defaultOrthographyForLanguage:found].dominantScript isEqualToString:targetScript]) otherScript++;+ }+ return !sure || foreign * 5 >= MAX(distinct, 5) || otherScript >= 2;+}+// The first 8 hex digits of the template's SHA-256, for the log: which prompt went, never what the lyrics were.static NSString *fingerprint(NSString *text) {NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];@@ -472,7 +569,7 @@ void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines,const SGAIProvider *p = chosen();NSString *key = storedSecret(p, kKeyAccount), *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"]);+ done(nil, [NSString stringWithFormat:@"Add a %@ API key%@ in Mod Settings > Lyrics first.", p->name, modelID ? @"" : @" and choose a model"]);return;}if (!sg_done) sg_done = [NSMutableDictionary dictionary];@@ -496,7 +593,7 @@ void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines,NSString *prompt = [NSString stringWithFormat:@"%@\n\n%@", instructions, [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding]];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.");+ done(nil, @"The server URL is invalid. Check it in Mod Settings > Lyrics.");return;}SGLog(@"ai: asking %@ %@ at %@, prompt %@%@", p->tag, modelID, request.URL.host, fingerprint(template),@@ -513,6 +610,485 @@ void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines,});}+static NSDictionary *batchMapIn(NSString *text) {+ if (!text.length) return nil;+ id parsed = [NSJSONSerialization JSONObjectWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];+ if (!parsed) {+ for (NSString *bracket in @[@"{", @"["]) {+ NSString *closeBracket = [bracket isEqualToString:@"{"] ? @"}" : @"]";+ NSRange open = [text rangeOfString:bracket], close = [text rangeOfString:closeBracket 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) break;+ }+ }+ }+ if ([parsed isKindOfClass:NSDictionary.class]) {+ for (NSString *key in @[@"songs", @"tracks", @"translations", @"results", @"data"]) {+ if ([parsed[key] isKindOfClass:NSDictionary.class]) return parsed[key];+ }+ return parsed;+ }+ if ([parsed isKindOfClass:NSArray.class]) {+ NSMutableDictionary *mapped = [NSMutableDictionary dictionary];+ for (NSUInteger i = 0; i < [parsed count]; i++) {+ id item = parsed[i];+ if ([item isKindOfClass:NSDictionary.class]) {+ NSString *tID = item[@"track"] ?: item[@"id"] ?: item[@"track_id"] ?: item[@"uri"] ?: @(i).stringValue;+ id lines = item[@"lines"] ?: item[@"translations"] ?: item[@"translation"];+ if (lines) mapped[tID] = lines;+ else mapped[@(i).stringValue] = item;+ } else if ([item isKindOfClass:NSArray.class]) {+ mapped[@(i).stringValue] = item;+ }+ }+ return mapped;+ }+ return nil;+}++static NSURLRequest *batchRequest(const SGAIProvider *p, NSString *modelID, NSString *prompt, NSString *key, BOOL plain, BOOL stream) {+ if ([p->tag isEqualToString:@"gemini"]) {+ 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"} mutableCopy];+ if (!plain) config[@"thinkingConfig"] = @{@"thinkingLevel": geminiThinkingLevel()};+ NSString *action = stream ? @"streamGenerateContent?alt=sse" : @"generateContent";+ NSMutableURLRequest *req = post([NSString stringWithFormat:@"https://generativelanguage.googleapis.com/v1beta/models/%@:%@", modelID, action],+ @{@"contents": @[@{@"parts": @[@{@"text": prompt}]}], @"safetySettings": safety, @"generationConfig": config});+ [req setValue:key forHTTPHeaderField:@"x-goog-api-key"];+ return req;+ }+ if ([p->tag isEqualToString:@"openai"]) {+ NSString *server = openAIServer();+ NSMutableDictionary *body = [@{@"model": modelID, @"messages": @[@{@"role": @"user", @"content": prompt}]} mutableCopy];+ if (stream) body[@"stream"] = @YES;+ if (!plain) {+ body[@"response_format"] = @{@"type": @"json_object"};+ body[@"reasoning_effort"] = @"low";+ }+ NSMutableURLRequest *req = post(server ? [server stringByAppendingString:@"/chat/completions"] : nil, body);+ [req setValue:[@"Bearer " stringByAppendingString:key] forHTTPHeaderField:@"Authorization"];+ return req;+ }+ if ([p->tag isEqualToString:@"anthropic"]) {+ NSMutableDictionary *body = [@{@"model": modelID, @"max_tokens": @16000,+ @"messages": @[@{@"role": @"user", @"content": prompt}]} mutableCopy];+ if (stream) body[@"stream"] = @YES;+ if (!plain) body[@"output_config"] = @{@"effort": @"low"};+ NSMutableURLRequest *req = post(@"https://api.anthropic.com/v1/messages", body);+ [req setValue:key forHTTPHeaderField:@"x-api-key"];+ [req setValue:@"2026-10-21" forHTTPHeaderField:@"anthropic-version"];+ return req;+ }+ return p->request(modelID, prompt, key, plain);+}++// Scans the accumulated JSON stream for any song keys whose `[...]` array has fully closed,+// and emits each completed song once via `onSong`.+static void scanCompletedSongsInStream(NSString *accumulated,+ NSDictionary<NSString *, NSArray<NSString *> *> *songs,+ NSMutableSet<NSString *> *emitted,+ NSMutableDictionary<NSString *, NSArray<NSString *> *> *streamedResults,+ void (^onSong)(NSString *trackKey, NSArray<NSString *> *lines)) {+ if (!accumulated.length) return;+ NSUInteger len = accumulated.length;+ for (NSString *trackKey in songs) {+ if ([emitted containsObject:trackKey]) continue;+ NSString *bareID = [trackKey hasPrefix:@"spotify:track:"] ? [trackKey substringFromIndex:@"spotify:track:".length] : trackKey;+ NSString *uriID = [@"spotify:track:" stringByAppendingString:bareID];++ NSRange keyRange = [accumulated rangeOfString:[NSString stringWithFormat:@"\"%@\"", trackKey]];+ if (keyRange.location == NSNotFound) {+ keyRange = [accumulated rangeOfString:[NSString stringWithFormat:@"\"%@\"", bareID]];+ }+ if (keyRange.location == NSNotFound) {+ keyRange = [accumulated rangeOfString:[NSString stringWithFormat:@"\"%@\"", uriID]];+ }+ if (keyRange.location == NSNotFound) continue;++ NSUInteger pos = NSMaxRange(keyRange);+ // Find opening '[' after ':' (skipping optional wrapper object like {"lines": [)+ NSUInteger arrayStart = NSNotFound;+ BOOL passedColon = NO;+ while (pos < len) {+ unichar c = [accumulated characterAtIndex:pos];+ if (c == ':') {+ passedColon = YES;+ } else if (passedColon) {+ if (c == '[') { arrayStart = pos; break; }+ if (c == ',' || c == ']') break;+ }+ pos++;+ }+ if (arrayStart == NSNotFound) continue;++ // Scan string-aware brackets to find matching ']'+ NSInteger depth = 0;+ BOOL inString = NO;+ BOOL escaped = NO;+ NSUInteger arrayEnd = NSNotFound;+ for (NSUInteger i = arrayStart; i < len; i++) {+ unichar c = [accumulated characterAtIndex:i];+ if (escaped) {+ escaped = NO;+ continue;+ }+ if (c == '\\' && inString) {+ escaped = YES;+ continue;+ }+ if (c == '"') {+ inString = !inString;+ continue;+ }+ if (!inString) {+ if (c == '[') depth++;+ else if (c == ']') {+ depth--;+ if (depth == 0) {+ arrayEnd = i;+ break;+ }+ }+ }+ }+ if (arrayEnd != NSNotFound) {+ NSString *slice = [accumulated substringWithRange:NSMakeRange(arrayStart, arrayEnd - arrayStart + 1)];+ id parsed = [NSJSONSerialization JSONObjectWithData:[slice dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];+ if ([parsed isKindOfClass:NSArray.class]) {+ NSMutableArray<NSString *> *clean = [NSMutableArray arrayWithCapacity:[parsed count]];+ for (id l in parsed) [clean addObject:[l isKindOfClass:NSString.class] ? l : [l description]];+ [emitted addObject:trackKey];+ NSArray<NSString *> *expected = songs[trackKey];+ if (expected && clean.count == expected.count) {+ streamedResults[trackKey] = clean;+ streamedResults[bareID] = clean;+ if (onSong) {+ NSArray<NSString *> *copyLines = [clean copy];+ dispatch_async(dispatch_get_main_queue(), ^{+ onSong(trackKey, copyLines);+ });+ }+ }+ }+ }+ }+}++@interface SGAIBatchStreamDelegate : NSObject <NSURLSessionDataDelegate>+@property (nonatomic, assign) const SGAIProvider *provider;+@property (nonatomic, copy) NSDictionary<NSString *, NSArray<NSString *> *> *songs;+@property (nonatomic, copy) void (^onPhase)(NSString *phase);+@property (nonatomic, copy) void (^onSong)(NSString *trackKey, NSArray<NSString *> *lines);+@property (nonatomic, copy) void (^completion)(NSData *rawData, NSString *accumulatedText, NSDictionary<NSString *, NSArray<NSString *> *> *streamedResults, NSString *stopReason, NSInteger status, NSError *error);+@end++@implementation SGAIBatchStreamDelegate {+ NSMutableData *_rawBuffer;+ NSMutableData *_utf8Buffer;+ NSMutableString *_accumulatedText;+ NSMutableSet<NSString *> *_emittedSongs;+ NSMutableDictionary<NSString *, NSArray<NSString *> *> *_streamedResults;+ NSString *_stopReason;+ NSInteger _statusCode;+ BOOL _reportedThinking;+ BOOL _reportedWriting;+}++- (instancetype)init {+ if (!(self = [super init])) return nil;+ _rawBuffer = [NSMutableData data];+ _utf8Buffer = [NSMutableData data];+ _accumulatedText = [NSMutableString string];+ _emittedSongs = [NSMutableSet set];+ _streamedResults = [NSMutableDictionary dictionary];+ return self;+}++- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask+didReceiveResponse:(NSURLResponse *)response+ completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {+ if ([response isKindOfClass:NSHTTPURLResponse.class]) {+ _statusCode = ((NSHTTPURLResponse *)response).statusCode;+ }+ completionHandler(NSURLSessionResponseAllow);+}++- (void)processSSEEventLine:(NSString *)line {+ NSString *trimmed = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (![trimmed hasPrefix:@"data:"]) return;+ NSString *payload = [[trimmed substringFromIndex:5] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ if (!payload.length || [payload isEqualToString:@"[DONE]"]) return;++ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[payload dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];+ if (![json isKindOfClass:NSDictionary.class]) return;++ BOOL sawThought = NO;+ NSMutableString *deltaText = [NSMutableString string];+ NSString *tag = self.provider->tag;++ if ([tag isEqualToString:@"gemini"]) {+ NSString *blocked = string(dig(json, @[@"promptFeedback", @"blockReason"]));+ if (blocked.length) _stopReason = blocked;+ NSArray *candidates = json[@"candidates"];+ NSDictionary *first = [candidates isKindOfClass:NSArray.class] ? candidates.firstObject : nil;+ NSString *finish = [first isKindOfClass:NSDictionary.class] ? string(first[@"finishReason"]) : nil;+ if (finish.length && ![finish isEqualToString:@"STOP"]) _stopReason = finish;+ NSArray *parts = [first isKindOfClass:NSDictionary.class] ? first[@"content"][@"parts"] : nil;+ if ([parts isKindOfClass:NSArray.class]) {+ for (NSDictionary *part in parts) {+ if (![part isKindOfClass:NSDictionary.class]) continue;+ if ([part[@"thought"] respondsToSelector:@selector(boolValue)] && [part[@"thought"] boolValue]) {+ sawThought = YES;+ } else if ([part[@"text"] isKindOfClass:NSString.class]) {+ [deltaText appendString:part[@"text"]];+ }+ }+ }+ } else if ([tag isEqualToString:@"openai"]) {+ NSArray *choices = json[@"choices"];+ NSDictionary *first = [choices isKindOfClass:NSArray.class] ? choices.firstObject : nil;+ NSString *finish = [first isKindOfClass:NSDictionary.class] ? string(first[@"finish_reason"]) : nil;+ if (finish.length && ![finish isEqualToString:@"stop"]) _stopReason = finish;+ NSDictionary *delta = [first isKindOfClass:NSDictionary.class] ? first[@"delta"] : nil;+ if ([delta isKindOfClass:NSDictionary.class]) {+ if ([delta[@"reasoning_content"] isKindOfClass:NSString.class] || [delta[@"reasoning"] isKindOfClass:NSString.class]) {+ sawThought = YES;+ }+ if ([delta[@"content"] isKindOfClass:NSString.class]) {+ [deltaText appendString:delta[@"content"]];+ }+ }+ } else if ([tag isEqualToString:@"anthropic"]) {+ NSDictionary *delta = json[@"delta"];+ NSString *stop = ([delta isKindOfClass:NSDictionary.class] ? string(delta[@"stop_reason"]) : nil) ?: string(json[@"stop_reason"]);+ if (stop.length && ![stop isEqualToString:@"end_turn"]) _stopReason = stop;+ if ([delta isKindOfClass:NSDictionary.class]) {+ NSString *type = delta[@"type"];+ if ([type isEqualToString:@"thinking_delta"] || [delta[@"thinking"] isKindOfClass:NSString.class]) {+ sawThought = YES;+ } else if ([delta[@"text"] isKindOfClass:NSString.class]) {+ [deltaText appendString:delta[@"text"]];+ }+ }+ }++ if (sawThought && !_reportedThinking && !_reportedWriting) {+ _reportedThinking = YES;+ if (self.onPhase) {+ void (^phaseBlock)(NSString *) = self.onPhase;+ dispatch_async(dispatch_get_main_queue(), ^{+ phaseBlock(@"Thinking…");+ });+ }+ }+ if (deltaText.length > 0) {+ if (!_reportedWriting) {+ _reportedWriting = YES;+ if (self.onPhase) {+ void (^phaseBlock)(NSString *) = self.onPhase;+ dispatch_async(dispatch_get_main_queue(), ^{+ phaseBlock(@"Writing");+ });+ }+ }+ [_accumulatedText appendString:deltaText];+ scanCompletedSongsInStream(_accumulatedText, self.songs, _emittedSongs, _streamedResults, self.onSong);+ }+}++- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {+ [_rawBuffer appendData:data];+ if (_statusCode != 200) return;+ [_utf8Buffer appendData:data];++ const uint8_t *bytes = _utf8Buffer.bytes;+ NSUInteger length = _utf8Buffer.length;+ NSUInteger lineStart = 0;+ for (NSUInteger i = 0; i < length; i++) {+ if (bytes[i] == '\n') {+ NSData *lineData = [_utf8Buffer subdataWithRange:NSMakeRange(lineStart, i - lineStart)];+ NSString *lineStr = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];+ if (lineStr) [self processSSEEventLine:lineStr];+ lineStart = i + 1;+ }+ }+ if (lineStart > 0) {+ [_utf8Buffer replaceBytesInRange:NSMakeRange(0, lineStart) withBytes:NULL length:0];+ }+}++- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {+ if (_statusCode == 200 && _utf8Buffer.length > 0) {+ NSString *tail = [[NSString alloc] initWithData:_utf8Buffer encoding:NSUTF8StringEncoding];+ if (tail.length) [self processSSEEventLine:tail];+ [_utf8Buffer setLength:0];+ }+ if (self.completion) {+ self.completion(_rawBuffer, _accumulatedText, _streamedResults, _stopReason, _statusCode, error);+ }+}++@end++static void sendBatchStream(const SGAIProvider *p,+ NSURLRequest *request,+ NSURLRequest *plain,+ NSDictionary<NSString *, NSArray<NSString *> *> *songs,+ NSUInteger attempt,+ void (^onPhase)(NSString *phase),+ void (^onSong)(NSString *trackKey, NSArray<NSString *> *lines),+ void (^done)(NSData *rawData, NSString *accumulatedText, NSDictionary<NSString *, NSArray<NSString *> *> *streamedResults, NSString *stopReason, NSInteger status, NSError *error)) {+ SGAIBatchStreamDelegate *del = [SGAIBatchStreamDelegate new];+ del.provider = p;+ del.songs = songs;+ del.onPhase = onPhase;+ del.onSong = onSong;+ del.completion = ^(NSData *rawData, NSString *accumulatedText, NSDictionary<NSString *, NSArray<NSString *> *> *streamedResults, NSString *stopReason, NSInteger status, NSError *error) {+ NSString *reply = status == 400 && rawData ? [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding] : nil;+ for (NSUInteger i = 0; plain && reply && i < 4 && p->plainWhen[i]; i++) {+ if (![reply localizedCaseInsensitiveContainsString:p->plainWhen[i]]) continue;+ SGLog(@"ai batch: %@ turned down %@, asking without the optional fields", p->tag, p->plainWhen[i]);+ sendBatchStream(p, plain, nil, songs, attempt, onPhase, onSong, done);+ return;+ }+ BOOL transient = (error && error.code != NSURLErrorTimedOut && error.code != NSURLErrorCancelled) ||+ status == 408 || status == 429 || status >= 500;+ if (transient && attempt < 2 && streamedResults.count == 0) {+ int64_t delay = (1LL << attempt) * NSEC_PER_SEC + (int64_t)arc4random_uniform(250) * NSEC_PER_MSEC;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ sendBatchStream(p, request, plain, songs, attempt + 1, onPhase, onSong, done);+ });+ return;+ }+ done(rawData, accumulatedText, streamedResults, stopReason, status, error);+ };+ NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];+ config.timeoutIntervalForRequest = aiTimeout();+ config.timeoutIntervalForResource = MAX(aiTimeout() * (songs.count ?: 1), 600.0);+ NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:del delegateQueue:nil];+ [[session dataTaskWithRequest:request] resume];+ [session finishTasksAndInvalidate];+}++void SGLyricsTranslateBatchWithAI(NSDictionary<NSString *, NSArray<NSString *> *> *songs,+ NSString *languageTag,+ void (^onPhase)(NSString *phase),+ void (^onSong)(NSString *trackKey, NSArray<NSString *> *lines),+ void (^done)(NSDictionary<NSString *, NSArray<NSString *> *> *results, NSString *error)) {+ const SGAIProvider *p = chosen();+ NSString *key = storedSecret(p, kKeyAccount), *modelID = model(p), *template = SGLyricsBatchPromptTemplate();+ if (!key || !modelID) {+ done(nil, [NSString stringWithFormat:@"Set up %@ in Mod Settings", p->name]);+ return;+ }+ if (!songs.count) {+ done(@{}, nil);+ return;+ }+ NSString *language = [[NSLocale localeWithLocaleIdentifier:@"en"] localizedStringForLocaleIdentifier:languageTag] ?: languageTag;+ NSData *inputData = [NSJSONSerialization dataWithJSONObject:songs options:NSJSONWritingPrettyPrinted error:nil];+ NSString *inputJSON = inputData ? [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding] : @"{}";++ NSString *instructions = template;+ instructions = [[instructions stringByReplacingOccurrencesOfString:@"{language}" withString:language]+ stringByReplacingOccurrencesOfString:@"{count}" withString:@(songs.count).stringValue];+ NSString *prompt = [NSString stringWithFormat:@"%@\n\n%@", instructions, inputJSON];++ NSURLRequest *request = batchRequest(p, modelID, prompt, key, NO, YES);+ NSURLRequest *plain = batchRequest(p, modelID, prompt, key, YES, YES);+ if (!request) {+ done(nil, @"Invalid server URL");+ return;+ }+ SGLog(@"ai batch: asking %@ %@ (%lu songs, streaming) into %@, prompt %@", p->tag, modelID, (unsigned long)songs.count, languageTag, fingerprint(template));+ sendBatchStream(p, request, plain, songs, 0, onPhase, onSong, ^(NSData *data, NSString *accumulatedText, NSDictionary<NSString *, NSArray<NSString *> *> *streamedResults, NSString *streamStopped, NSInteger status, NSError *error) {+ NSString *who = speaker(p);+ NSString *stopped = streamStopped;+ NSDictionary *rawDict = nil;+ if (status == 200) {+ if (accumulatedText.length > 0) {+ rawDict = batchMapIn(accumulatedText);+ }+ if (!rawDict && data.length > 0) {+ id root = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (root) rawDict = batchMapIn(p->answer(root, who, &stopped));+ }+ }++ NSMutableDictionary<NSString *, NSArray<NSString *> *> *results = [NSMutableDictionary dictionaryWithDictionary:streamedResults ?: @{}];+ if (rawDict) {+ NSUInteger songIndex = 0;+ for (NSString *trackKey in songs) {+ NSString *bareID = [trackKey hasPrefix:@"spotify:track:"] ? [trackKey substringFromIndex:@"spotify:track:".length] : trackKey;+ NSString *uriID = [@"spotify:track:" stringByAppendingString:bareID];+ id rawLines = rawDict[trackKey] ?: rawDict[bareID] ?: rawDict[uriID];+ if (!rawLines) {+ for (NSString *k in rawDict) {+ if ([k caseInsensitiveCompare:trackKey] == NSOrderedSame ||+ [k caseInsensitiveCompare:bareID] == NSOrderedSame ||+ [k caseInsensitiveCompare:uriID] == NSOrderedSame) {+ rawLines = rawDict[k];+ break;+ }+ }+ }+ if (!rawLines) {+ rawLines = rawDict[@(songIndex).stringValue];+ }+ if ([rawLines isKindOfClass:NSDictionary.class]) {+ if ([rawLines[@"lines"] isKindOfClass:NSArray.class]) rawLines = rawLines[@"lines"];+ else if ([rawLines[@"translations"] isKindOfClass:NSArray.class]) rawLines = rawLines[@"translations"];+ }+ if ([rawLines isKindOfClass:NSArray.class]) {+ NSMutableArray<NSString *> *clean = [NSMutableArray array];+ for (id l in rawLines) [clean addObject:[l isKindOfClass:NSString.class] ? l : [l description]];+ NSArray<NSString *> *expected = songs[trackKey];+ if (expected && clean.count == expected.count) {+ results[trackKey] = clean;+ results[bareID] = clean;+ }+ }+ songIndex++;+ }+ }++ NSUInteger answered = results.count / 2;+ NSString *problem = nil;+ if (answered >= songs.count) {+ // All songs in the chunk completed.+ } else if (error) {+ problem = error.code == NSURLErrorTimedOut+ ? [NSString stringWithFormat:@"%@ timed out", who]+ : [NSString stringWithFormat:@"Could not reach %@", who];+ } else if (status == 401 || status == 403) {+ problem = [NSString stringWithFormat:@"%@ rejected API key", who];+ } else if (status == 429) {+ problem = [NSString stringWithFormat:@"%@ rate limit reached", who];+ } else if (status >= 500) {+ problem = [NSString stringWithFormat:@"%@ is busy, try again", who];+ } else if (status != 200) {+ problem = [NSString stringWithFormat:@"%@ error (%ld)", who, (long)status];+ } else if (stopped) {+ problem = [NSString stringWithFormat:@"%@ stopped early", who];+ } else if (!answered) {+ problem = @"Could not read reply";+ } else {+ problem = [NSString stringWithFormat:@"%@ translated %lu of %lu songs", who, (unsigned long)answered, (unsigned long)songs.count];+ }++ SGLog(@"ai batch: %@ answered %lu of %lu songs into %@: %@", p->tag, (unsigned long)answered, (unsigned long)songs.count, languageTag, problem ?: @"ok");+ dispatch_async(dispatch_get_main_queue(), ^{+ done(results.count ? results : nil, problem);+ });+ });+}+#pragma mark - the rowsNSNotificationName const SGLyricsTranslationsDidChangeNotification = @"spotifyglass.lyricsTranslationsDidChange";@@ -659,15 +1235,23 @@ static NSArray<NSString *> *modelMenu(const SGAIProvider *p) {// The prompt in a sheet: the checkmark stores it, Default puts Vitrine's back in the field. Stored equal to the// default, or empty, it is removed, so a later change to the default reaches it.@interface SGPromptEditor : UIViewController+- (instancetype)initWithBatch:(BOOL)batch;@end@implementation SGPromptEditor {UITextView *_text;+ BOOL _batch;+}++- (instancetype)initWithBatch:(BOOL)batch {+ if (!(self = [super init])) return nil;+ _batch = batch;+ return self;}- (void)viewDidLoad {[super viewDidLoad];- self.title = @"Translation prompt";+ self.title = _batch ? @"Batch prompt" : @"Translation prompt";self.view.backgroundColor = UIColor.systemGroupedBackgroundColor;_text = [UITextView new];_text.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];@@ -676,12 +1260,14 @@ static NSArray<NSString *> *modelMenu(const SGAIProvider *p) {_text.textContainerInset = UIEdgeInsetsMake(16, 16, 16, 16);_text.alwaysBounceVertical = YES;_text.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;- _text.text = promptTemplate();+ _text.text = _batch ? SGLyricsBatchPromptTemplate() : promptTemplate();_text.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:_text];UILabel *note = [UILabel new];- 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.text = _batch ? @"For multi-song batch translations. {language} and {count} are filled in for each batch; "+ @"the songs' lines follow as a JSON object mapping track IDs to arrays of lines."+ : @"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;@@ -711,14 +1297,16 @@ static NSArray<NSString *> *modelMenu(const SGAIProvider *p) {}- (void)reset {- _text.text = kDefaultPrompt;+ _text.text = _batch ? kDefaultBatchPrompt : kDefaultPrompt;}- (void)save {NSString *prompt = [_text.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];- 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");+ NSString *def = _batch ? kDefaultBatchPrompt : kDefaultPrompt;+ NSString *key = _batch ? SGKeyLyricsBatchPrompt : SGKeyAIPrompt;+ if (!prompt.length || [prompt isEqualToString:def]) [NSUserDefaults.standardUserDefaults removeObjectForKey:key];+ else [NSUserDefaults.standardUserDefaults setObject:prompt forKey:key];+ SGLog(@"ai: %@ prompt %@", _batch ? @"batch" : @"", storedString(key) ? [@"edited, " stringByAppendingString:fingerprint(prompt)] : @"default");[self close];}@end@@ -770,6 +1358,7 @@ NSArray<SGModRow *> *SGAITranslatorRows(void) {translatorChanged();});thinking.visible = ^{ return [chosen()->tag isEqualToString:@"gemini"]; };+NSArray<NSNumber *> *timeoutSeconds = @[@30, @60, @90, @(kDefaultAITimeout), @180, @240, @300];NSMutableArray<NSString *> *timeouts = [NSMutableArray array];for (NSNumber *seconds in timeoutSeconds) [timeouts addObject:[NSString stringWithFormat:@"%@ s", seconds]];@@ -780,5 +1369,24 @@ NSArray<SGModRow *> *SGAITranslatorRows(void) {if (seconds == kDefaultAITimeout) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyAITimeout];else [NSUserDefaults.standardUserDefaults setInteger:seconds forKey:SGKeyAITimeout];});- return @[provider, key, models, thinking, timeout, prompt];++ NSArray<NSNumber *> *batchSizes = @[@10, @20, @30, @40, @50, @0];+ NSArray<NSString *> *batchSizeOptions = @[@"10 songs", @"20 songs", @"30 songs", @"40 songs", @"50 songs", @"All at once"];+ SGModRow *batchSizeRow = SGMenuRow(@"Songs per batch", batchSizeOptions, ^NSString *{+ NSUInteger idx = [batchSizes indexOfObject:@(SGLyricsBatchSize())];+ return batchSizeOptions[idx != NSNotFound ? idx : 1];+ }, ^(NSInteger index) {+ NSUInteger size = batchSizes[index].unsignedIntegerValue;+ if (size == 20) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyLyricsBatchSize];+ else [NSUserDefaults.standardUserDefaults setInteger:size forKey:SGKeyLyricsBatchSize];+ });+ SGModRow *batchPromptRow = SGStatActionRow(@"Batch prompt", @"Prompt used when translating multiple songs at once",+ ^NSString *{ return storedString(SGKeyLyricsBatchPrompt) ? @"Edited" : @"Default"; }, ^{+ UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[SGPromptEditor alloc] initWithBatch:YES]];+ nav.modalPresentationStyle = UIModalPresentationPageSheet;+ SGPresentDark(nav);+ [SGTopController() presentViewController:nav animated:YES completion:nil];+ });+ SGModRow *skipSavedRow = SGSwitchRow(@"Skip saved translations", @"Skip songs that already have a saved translation", SGKeyLyricsBatchSkipSaved);+ return @[provider, key, models, thinking, timeout, prompt, batchSizeRow, batchPromptRow, skipSavedRow];}diff --git a/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m b/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.mindex 1d1144c1..5b5fa90b 100644--- a/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m+++ b/tweak/Sources/Shared/LyricsTranslation/SavedTranslations.m@@ -100,6 +100,11 @@ SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *languagereturn [SGTranslationSource by:source.by model:source.model made:now];}+BOOL SGLyricsHasSavedTranslation(NSString *track, NSString *language) {+ if (!track.length || !language.length) return NO;+ return [NSFileManager.defaultManager fileExistsAtPath:fileFor(track, language).path];+}+// After any write still queued, so it cannot bring a file back.static void deleteQueued(NSURL *url, NSString *what) {dispatch_async(writes(), ^{