@@ -733,6 +733,7 @@ def scrape(cls, html: str) -> str | None:
733
733
class Translator (RequestHandler ):
734
734
TRANSLATE_URL = "https://api.cognitive.microsofttranslator.com/translate"
735
735
LINE_PARTS_RE = re .compile (r"^(\[\d\d:\d\d.\d\d\]|) *(.*)$" )
736
+ remove_translations = partial (re .compile (r" / [^\n]+" ).sub , "" )
736
737
737
738
_log : beets .logging .Logger
738
739
api_key : str
@@ -802,21 +803,33 @@ def append_translations(self, lines: Iterable[str]) -> list[str]:
802
803
def translate (self , new_lyrics : str , old_lyrics : str ) -> str :
803
804
"""Translate the given lyrics to the target language.
804
805
806
+ Check old lyrics for existing translations and return them if their
807
+ original text matches the new lyrics. This is to avoid translating
808
+ the same lyrics multiple times.
809
+
805
810
If the lyrics are already in the target language or not in any of
806
811
of the source languages (if configured), they are returned as is.
807
812
808
813
The footer with the source URL is preserved, if present.
809
814
"""
815
+ if (
816
+ " / " in old_lyrics
817
+ and self .remove_translations (old_lyrics ) == new_lyrics
818
+ ):
819
+ self .info ("🔵 Translations already exist" )
820
+ return old_lyrics
821
+
810
822
lyrics_language = langdetect .detect (new_lyrics )
811
823
if lyrics_language != self .to_lang and (
812
824
not self .from_langs or lyrics_language in self .from_langs
813
825
):
814
826
lyrics , * url = new_lyrics .split ("\n \n Source: " )
815
827
with self .handle_request ():
816
828
translated_lines = self .append_translations (lyrics .splitlines ())
829
+ self .info ("🟢 Translated lyrics to {}" , self .to_lang .upper ())
817
830
return "\n \n Source: " .join (["\n " .join (translated_lines ), * url ])
818
831
819
- return lyrics
832
+ return new_lyrics
820
833
821
834
822
835
@dataclass
@@ -1052,12 +1065,7 @@ def add_item_lyrics(self, item: Item, write: bool) -> None:
1052
1065
if lyrics := self .find_lyrics (item ):
1053
1066
self .info ("🟢 Found lyrics: {0}" , item )
1054
1067
if translator := self .translator :
1055
- initial_lyrics = lyrics
1056
- if (lyrics := translator .translate (lyrics )) != initial_lyrics :
1057
- self .info (
1058
- "🟢 Added translation to {}" ,
1059
- self .config ["translate_to" ].get ().upper (),
1060
- )
1068
+ lyrics = translator .translate (lyrics , item .lyrics )
1061
1069
else :
1062
1070
self .info ("🔴 Lyrics not found: {}" , item )
1063
1071
lyrics = self .config ["fallback" ].get ()
0 commit comments