""" Audio metadata (ID3 / Vorbis / EXIF) utilities for reading and writing tags. Uses mutagen for format-agnostic read/write. """ from pathlib import Path from typing import Optional, List, Dict, Tuple import re def _read_cover_art(source_path: str): """ Read cover art from an audio file. Returns (data_bytes, mime_type) or (None, None) if not found. """ try: ext = Path(source_path).suffix.lower() if ext == '.mp3': from mutagen.id3 import ID3, ID3NoHeaderError try: tags = ID3(source_path) apic_keys = [k for k in tags.keys() if k.startswith('APIC')] if apic_keys: apic = tags[apic_keys[0]] return apic.data, apic.mime except ID3NoHeaderError: pass elif ext == '.flac': from mutagen.flac import FLAC audio = FLAC(source_path) if audio.pictures: pic = audio.pictures[0] return pic.data, pic.mime elif ext == '.wav': from mutagen.wave import WAVE try: audio = WAVE(source_path) if audio.tags: apic_keys = [k for k in audio.tags.keys() if k.startswith('APIC')] if apic_keys: apic = audio.tags[apic_keys[0]] return apic.data, apic.mime except Exception: pass except Exception: pass return None, None def copy_metadata(source_path: str, dest_path: str, stem_label: Optional[str] = None, copy_lyrics: bool = True) -> None: """ Copy all common tags (title, artist, album, track, date, genre, cover art, lyrics) from source_path to dest_path. Optionally appends stem_label to the title. Silently ignores unsupported formats — metadata is cosmetic, never fatal. """ try: import mutagen src = mutagen.File(source_path, easy=True) if src is None: return title = src.get("title", [""])[0] if src.get("title") else "" artist = src.get("artist", [""])[0] if src.get("artist") else "" album = src.get("album", [""])[0] if src.get("album") else "" tracknumber = src.get("tracknumber", [""])[0] if src.get("tracknumber") else "" date = src.get("date", [""])[0] if src.get("date") else "" genre = src.get("genre", [""])[0] if src.get("genre") else "" if stem_label and title: title = f"{title} ({stem_label})" elif stem_label: title = stem_label cover_data, cover_mime = _read_cover_art(source_path) # Read lyrics from source lyrics = "" if copy_lyrics: lyrics = _read_lyrics_from_file(source_path) ext = Path(dest_path).suffix.lower() if ext == ".mp3": _write_mp3_tags(dest_path, title, artist, album, tracknumber, date, genre, cover_data, cover_mime, lyrics) elif ext == ".flac": _write_flac_tags(dest_path, title, artist, album, tracknumber, date, genre, cover_data, cover_mime, lyrics) elif ext == ".wav": _write_wav_tags(dest_path, title, artist, album, tracknumber, date, genre, cover_data, cover_mime) except Exception: pass # Never fail over metadata — it's cosmetic def _read_lyrics_from_file(path: str) -> str: """Read lyrics from a file using the same logic as read_metadata.""" try: ext = Path(path).suffix.lower() if ext == '.mp3': return _read_mp3_lyrics(path) elif ext in ('.flac', '.ogg', '.opus'): return _read_vorbis_lyrics(path) except Exception: pass return '' def _write_mp3_tags(path, title, artist, album, tracknumber, date, genre, cover_data=None, cover_mime=None, lyrics=None): from mutagen.id3 import ID3, ID3NoHeaderError, TIT2, TPE1, TALB, TRCK, TDRC, TCON, APIC, USLT try: tags = ID3(path) except ID3NoHeaderError: tags = ID3() if title: tags["TIT2"] = TIT2(encoding=3, text=title) if artist: tags["TPE1"] = TPE1(encoding=3, text=artist) if album: tags["TALB"] = TALB(encoding=3, text=album) if tracknumber: tags["TRCK"] = TRCK(encoding=3, text=tracknumber) if date: tags["TDRC"] = TDRC(encoding=3, text=date) if genre: tags["TCON"] = TCON(encoding=3, text=genre) if lyrics: tags["USLT::'eng'"] = USLT(encoding=3, lang='eng', desc='', text=lyrics) if cover_data: tags["APIC:"] = APIC( encoding=3, mime=cover_mime or "image/jpeg", type=3, desc="Cover", data=cover_data, ) tags.save(path) def _write_flac_tags(path, title, artist, album, tracknumber, date, genre, cover_data=None, cover_mime=None, lyrics=None): from mutagen.flac import FLAC, Picture audio = FLAC(path) if title: audio["title"] = title if artist: audio["artist"] = artist if album: audio["album"] = album if tracknumber: audio["tracknumber"] = tracknumber if date: audio["date"] = date if genre: audio["genre"] = genre if lyrics: audio["lyrics"] = lyrics if cover_data: pic = Picture() pic.type = 3 # front cover pic.mime = cover_mime or "image/jpeg" pic.desc = "Cover" pic.data = cover_data audio.clear_pictures() audio.add_picture(pic) audio.save() def _write_wav_tags(path, title, artist, album, tracknumber, date, genre, cover_data=None, cover_mime=None): from mutagen.wave import WAVE from mutagen.id3 import TIT2, TPE1, TALB, TRCK, TDRC, TCON, APIC try: audio = WAVE(path) if audio.tags is None: audio.add_tags() if title: audio.tags["TIT2"] = TIT2(encoding=3, text=title) if artist: audio.tags["TPE1"] = TPE1(encoding=3, text=artist) if album: audio.tags["TALB"] = TALB(encoding=3, text=album) if tracknumber: audio.tags["TRCK"] = TRCK(encoding=3, text=tracknumber) if date: audio.tags["TDRC"] = TDRC(encoding=3, text=date) if genre: audio.tags["TCON"] = TCON(encoding=3, text=genre) if cover_data: audio.tags["APIC:"] = APIC( encoding=3, mime=cover_mime or "image/jpeg", type=3, desc="Cover", data=cover_data, ) audio.save() except Exception: pass # --------------------------------------------------------------------------- # Metadata reading # --------------------------------------------------------------------------- def read_metadata(source_path: str) -> dict: """ Read basic metadata from an audio file. Returns dict with 'artist', 'title', 'album', 'lyrics' keys (all str). Lyrics are read in order of priority: 1. Synced lyrics tags (SYLT for MP3, syncedlyrics for FLAC/OGG) 2. Unsynced lyrics tags (USLT for MP3, lyrics/unsyncedlyrics for FLAC/OGG) 3. External .lrc file with same base name Silently returns empty strings on failure or unsupported format. """ result = {'artist': '', 'title': '', 'album': '', 'lyrics': ''} try: import mutagen src = mutagen.File(source_path, easy=True) if src is None: return result result['artist'] = (src.get('artist') or [''])[0] result['title'] = (src.get('title') or [''])[0] result['album'] = (src.get('album') or [''])[0] ext = Path(source_path).suffix.lower() lyrics = '' # Try to read lyrics from tags first if ext == '.mp3': lyrics = _read_mp3_lyrics(source_path) elif ext in ('.flac', '.ogg', '.opus'): lyrics = _read_vorbis_lyrics(source_path) # If no lyrics in tags, try external LRC file if not lyrics: lyrics = read_lrc_file(source_path) result['lyrics'] = lyrics except Exception: pass return result def _read_mp3_lyrics(path: str) -> str: """Read lyrics from ID3 tags: SYLT (synced) → USLT (unsynced) → TXXX:LYRICS. Also checks $-prefixed variants used by some tagging software. """ try: from mutagen.id3 import ID3, ID3NoHeaderError try: tags = ID3(path) except ID3NoHeaderError: return '' # Synced lyrics: SYLT contains list of (text, time_ms) tuples sylt_keys = [k for k in tags.keys() if k.startswith('SYLT')] if sylt_keys: return '\n'.join(t for t, _ in tags[sylt_keys[0]].text) # Unsynced lyrics uslt_keys = [k for k in tags.keys() if k.startswith('USLT')] if uslt_keys: return tags[uslt_keys[0]].text # TXXX:LYRICS fallback (also check $-prefixed variants) for txxx_key in ('TXXX:LYRICS', 'TXXX:$LYRICS', 'TXXX:SYNCEDLYRICS', 'TXXX:$SYNCEDLYRICS', 'TXXX:UNSYNCEDLYRICS', 'TXXX:$UNSYNCEDLYRICS'): if txxx_key in tags: text = tags[txxx_key].text if text: return text[0] if isinstance(text, list) else str(text) except Exception: pass return '' def _read_vorbis_lyrics(path: str) -> str: """Read lyrics from FLAC/OGG Vorbis comment tags. Checks SYNCEDLYRICS, LYRICS, and UNSYNCEDLYRICS (case-insensitive). Also checks variants with $ prefix (e.g., $LYRICS) used by some tagging software. Returns the first non-empty value found, or empty string if all are empty. """ try: import mutagen f = mutagen.File(path) if f is None: return '' # Build case-insensitive lookup: upper() -> original key key_map = {k.upper(): k for k in f.keys()} # Check in priority order: SYNCEDLYRICS -> LYRICS -> UNSYNCEDLYRICS # Also check $-prefixed variants as fallback for key in ('SYNCEDLYRICS', '$SYNCEDLYRICS', 'LYRICS', '$LYRICS', 'UNSYNCEDLYRICS', '$UNSYNCEDLYRICS'): if key in key_map: val = f.get(key_map[key]) if val: return val[0] except Exception: pass return '' # --------------------------------------------------------------------------- # LRC file utilities # --------------------------------------------------------------------------- LRC_LINE_REGEX = re.compile( r'^(\[\s*(\d+):(\d{1,2})(?:\.(\d{1,3}))?\s*\])' # timestamp [mm:ss.xx] r'\s*(.*?)$', # lyrics text re.MULTILINE ) ELRC_WORD_REGEX = re.compile( r'(<\s*(\d+):(\d{1,2})(?:\.(\d{1,3}))?\s*>)' # word timestamp r'\s*([^<\n]+)', # word text re.MULTILINE ) def read_lrc_file(audio_path: str) -> str: """ Read lyrics from an external .lrc file with the same base name as the audio file. Returns the raw LRC content or empty string if not found. """ audio_path = Path(audio_path) lrc_path = audio_path.with_suffix('.lrc') if not lrc_path.exists(): # Try case-insensitive search (covers both .lrc and .LRC on Linux) for pattern in ('*.lrc', '*.LRC'): for f in audio_path.parent.glob(pattern): if f.stem.lower() == audio_path.stem.lower(): lrc_path = f break if lrc_path.exists(): break if lrc_path.exists(): try: return lrc_path.read_text(encoding='utf-8', errors='ignore') except Exception: pass return '' def parse_lrc(lrc_content: str) -> List[Tuple[float, str]]: """ Parse LRC content into list of (timestamp_seconds, line_text) tuples. Args: lrc_content: Raw LRC file content Returns: List of (timestamp, line) tuples sorted by timestamp """ lines = [] for match in LRC_LINE_REGEX.finditer(lrc_content): minutes = int(match.group(2)) seconds = int(match.group(3)) millis = match.group(4) text = match.group(5).strip() if millis: # Handle different millisecond precisions millis = int(millis.ljust(3, '0')[:3]) else: millis = 0 timestamp = minutes * 60 + seconds + millis / 1000.0 if text: lines.append((timestamp, text)) # Sort by timestamp and remove duplicates lines.sort(key=lambda x: x[0]) # Remove duplicate timestamps (keep first occurrence) seen = set() unique_lines = [] for ts, text in lines: if ts not in seen: seen.add(ts) unique_lines.append((ts, text)) return unique_lines def parse_elrc(elrc_content: str) -> List[Tuple[float, str, List[Tuple[float, str]]]]: """ Parse Enhanced LRC (ELRC) content with word-level timestamps. Args: elrc_content: Raw ELRC file content Returns: List of (line_timestamp, line_text, [(word_timestamp, word), ...]) tuples """ lines = [] for match in LRC_LINE_REGEX.finditer(elrc_content): minutes = int(match.group(2)) seconds = int(match.group(3)) millis = match.group(4) full_line = match.group(5) if millis: millis = int(millis.ljust(3, '0')[:3]) else: millis = 0 line_timestamp = minutes * 60 + seconds + millis / 1000.0 # Parse word-level timestamps within this line words = [] for word_match in ELRC_WORD_REGEX.finditer(full_line): w_minutes = int(word_match.group(2)) w_seconds = int(word_match.group(3)) w_millis = word_match.group(4) w_text = word_match.group(5).strip() if w_millis: w_millis = int(w_millis.ljust(3, '0')[:3]) else: w_millis = 0 word_timestamp = w_minutes * 60 + w_seconds + w_millis / 1000.0 if w_text: words.append((word_timestamp, w_text)) # Clean line text (remove word timestamps) line_text = ELRC_WORD_REGEX.sub(r'\5', full_line).strip() if line_text or words: lines.append((line_timestamp, line_text, words)) lines.sort(key=lambda x: x[0]) return lines def format_lrc(lines: List[Tuple[float, str]], include_empty: bool = False) -> str: """ Format lines back into LRC format. Args: lines: List of (timestamp_seconds, line_text) tuples include_empty: Whether to include empty lines Returns: LRC formatted string """ result = [] for timestamp, text in lines: if not text and not include_empty: continue minutes = int(timestamp // 60) seconds = int(timestamp % 60) millis = int((timestamp % 1) * 100) result.append(f"[{minutes:02d}:{seconds:02d}.{millis:02d}]{text}") return '\n'.join(result) def format_elrc(lines: List[Tuple[float, str, List[Tuple[float, str]]]]) -> str: """ Format lines with word-level timestamps into ELRC format. Args: lines: List of (line_timestamp, line_text, [(word_timestamp, word), ...]) tuples Returns: ELRC formatted string """ result = [] for line_ts, line_text, words in lines: minutes = int(line_ts // 60) seconds = int(line_ts % 60) millis = int((line_ts % 1) * 100) if words: # Build line with word timestamps word_parts = [] for word_ts, word in words: w_min = int(word_ts // 60) w_sec = int(word_ts % 60) w_mil = int((word_ts % 1) * 100) word_parts.append(f"<{w_min:02d}:{w_sec:02d}.{w_mil:02d}>{word}") line_content = ' '.join(word_parts) else: line_content = line_text result.append(f"[{minutes:02d}:{seconds:02d}.{millis:02d}]{line_content}") return '\n'.join(result) def lyrics_to_plaintext(lyrics: str) -> str: """ Convert LRC/ELRC content to plain text (remove all timestamps). Args: lyrics: LRC formatted content Returns: Plain text lyrics """ # Remove line timestamps [mm:ss.xx] text = re.sub(r'\[\s*\d+:\d{2}(?:\.\d{1,3})?\s*\]', '', lyrics) # Remove word timestamps text = re.sub(r'<\s*\d+:\d{2}(?:\.\d{1,3})?\s*>', '', text) # Clean up whitespace lines = [line.strip() for line in text.split('\n') if line.strip()] return '\n'.join(lines) def is_lrc_synced(lyrics: str) -> bool: """ Check if lyrics content contains LRC timestamps (synced lyrics). Args: lyrics: Lyrics content to check Returns: True if content contains LRC timestamps """ return bool(LRC_LINE_REGEX.search(lyrics)) def extract_lyrics_from_file(file_path: str) -> Dict[str, str]: """ Extract lyrics from an audio file or LRC file. Args: file_path: Path to audio file or LRC file Returns: Dict with 'source', 'raw', 'synced', 'plain' keys - source: 'tag', 'lrc_file', or 'none' - raw: Original lyrics content with timestamps if present - synced: True if lyrics are timestamped - plain: Plain text version without timestamps """ path = Path(file_path) result = {'source': 'none', 'raw': '', 'synced': False, 'plain': ''} # If it's an LRC file, read it directly if path.suffix.lower() == '.lrc': try: content = path.read_text(encoding='utf-8', errors='ignore') result['source'] = 'lrc_file' result['raw'] = content result['synced'] = is_lrc_synced(content) result['plain'] = lyrics_to_plaintext(content) except Exception: pass return result # Otherwise, try to read from audio file metadata metadata = read_metadata(file_path) lyrics = metadata.get('lyrics', '') if lyrics: result['source'] = 'tag' result['raw'] = lyrics result['synced'] = is_lrc_synced(lyrics) result['plain'] = lyrics_to_plaintext(lyrics) else: # Try external LRC file as last resort lrc_content = read_lrc_file(file_path) if lrc_content: result['source'] = 'lrc_file' result['raw'] = lrc_content result['synced'] = is_lrc_synced(lrc_content) result['plain'] = lyrics_to_plaintext(lrc_content) return result