Coverage for downtify/cover_art.py: 65%

124 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Extract embedded cover art from audio files.""" 

2 

3from __future__ import annotations 

4 

5import base64 

6import mimetypes 

7import os 

8from pathlib import Path 

9 

10from mutagen import File as MutagenFile 

11from mutagen.flac import FLAC, Picture 

12from mutagen.id3 import ID3 

13from mutagen.mp4 import MP4 

14from mutagen.oggopus import OggOpus 

15from mutagen.oggvorbis import OggVorbis 

16 

17 

18def _embedded_cover_from_id3(path: Path) -> tuple[bytes | None, str | None]: 

19 try: 

20 tag = ID3(str(path)) 

21 for frame in tag.getall('APIC'): 

22 if frame.data: 

23 return frame.data, frame.mime or 'image/jpeg' 

24 except Exception: 

25 pass 

26 return None, None 

27 

28 

29def _embedded_cover_from_flac(path: Path) -> tuple[bytes | None, str | None]: 

30 try: 

31 f = FLAC(str(path)) 

32 if f.pictures: 

33 pic = f.pictures[0] 

34 return pic.data, pic.mime or 'image/jpeg' 

35 except Exception: 

36 pass 

37 return None, None 

38 

39 

40def _embedded_cover_from_mp4(path: Path) -> tuple[bytes | None, str | None]: 

41 try: 

42 m = MP4(str(path)) 

43 covr = m.tags.get('covr') if m.tags else None 

44 if not covr: 

45 return None, None 

46 pic = covr[0] 

47 fmt = getattr(pic, 'imageformat', None) 

48 mime = 'image/png' if fmt == 14 else 'image/jpeg' 

49 return bytes(pic), mime 

50 except Exception: 

51 return None, None 

52 

53 

54def _embedded_cover_from_ogg(path: Path) -> tuple[bytes | None, str | None]: 

55 try: 

56 ogg = ( 

57 OggOpus(str(path)) 

58 if path.suffix.lower() == '.opus' 

59 else OggVorbis(str(path)) 

60 ) 

61 blocks = ogg.get('metadata_block_picture') or [] 

62 for raw in blocks: 

63 try: 

64 pic = Picture(base64.b64decode(raw)) 

65 if pic.data: 

66 return pic.data, pic.mime or 'image/jpeg' 

67 except Exception: 

68 continue 

69 except Exception: 

70 pass 

71 return None, None 

72 

73 

74def _embedded_cover_from_mutagen( 

75 path: Path, 

76) -> tuple[bytes | None, str | None]: 

77 try: 

78 f = MutagenFile(str(path)) 

79 if f is not None and getattr(f, 'pictures', None): 

80 pic = f.pictures[0] 

81 return pic.data, pic.mime or 'image/jpeg' 

82 except Exception: 

83 pass 

84 return None, None 

85 

86 

87def extract_embedded_cover(path: Path) -> tuple[bytes | None, str | None]: 

88 """Return ``(image_bytes, mime)`` for the embedded cover, or ``(None, None)``.""" 

89 

90 suffix = path.suffix.lower() 

91 data, mime = _embedded_cover_from_id3(path) 

92 if data: 

93 return data, mime 

94 if suffix == '.flac': 

95 data, mime = _embedded_cover_from_flac(path) 

96 if data: 

97 return data, mime 

98 if suffix in {'.m4a', '.mp4', '.aac'}: 

99 data, mime = _embedded_cover_from_mp4(path) 

100 if data: 

101 return data, mime 

102 if suffix in {'.ogg', '.opus'}: 

103 data, mime = _embedded_cover_from_ogg(path) 

104 if data: 

105 return data, mime 

106 return _embedded_cover_from_mutagen(path) 

107 

108 

109_FOLDER_COVER_STEMS = frozenset({ 

110 'cover', 

111 'folder', 

112 'front', 

113 'album', 

114 'artwork', 

115 'albumart', 

116}) 

117 

118 

119def _mime_for_image(path: Path) -> str: 

120 guessed, _ = mimetypes.guess_type(str(path)) 

121 return guessed or 'image/jpeg' 

122 

123 

124def extract_folder_cover(path: Path) -> tuple[bytes | None, str | None]: 

125 """Return cover image bytes from common filenames next to *path*.""" 

126 

127 parent = path.parent 

128 if not parent.is_dir(): 

129 return None, None 

130 candidates: list[Path] = [] 

131 try: 

132 with os.scandir(parent) as entries: 

133 for entry in entries: 

134 suffix = Path(entry.name).suffix.lower() 

135 if suffix not in {'.jpg', '.jpeg', '.png', '.webp'}: 

136 continue 

137 stem = Path(entry.name).stem.casefold() 

138 if stem not in _FOLDER_COVER_STEMS: 

139 continue 

140 if not entry.is_file(follow_symlinks=True): 

141 continue 

142 candidates.append(Path(entry.path)) 

143 except OSError: 

144 return None, None 

145 for entry in sorted(candidates, key=lambda item: item.name.casefold()): 

146 try: 

147 data = entry.read_bytes() 

148 except OSError: 

149 continue 

150 if data: 

151 return data, _mime_for_image(entry) 

152 return None, None 

153 

154 

155def extract_cover_art(path: Path) -> tuple[bytes | None, str | None]: 

156 """Embedded tags first, then ``cover.jpg`` / ``folder.jpg`` in the same folder.""" 

157 

158 data, mime = extract_embedded_cover(path) 

159 if data: 

160 return data, mime 

161 return extract_folder_cover(path) 

162 

163 

164def file_has_cover_art(path: Path) -> bool: 

165 """True when embedded or folder art exists (used by ``/list``).""" 

166 

167 if not path.is_file(): 

168 return False 

169 if extract_folder_cover(path)[0]: 

170 return True 

171 return extract_embedded_cover(path)[0] is not None