mp3-cover-adder 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ """
2
+ mp3-cover-adder: Python library to embed MP3 album art and edit ID3 tags.
3
+
4
+ This library provides a simple, offline API for reading and writing
5
+ ID3 metadata and album art in MP3 files.
6
+ """
7
+
8
+ from mp3_cover_adder.core import (
9
+ MP3CoverAdder,
10
+ read_mp3_metadata,
11
+ set_mp3_cover,
12
+ remove_mp3_cover,
13
+ set_mp3_metadata,
14
+ write_mp3,
15
+ )
16
+
17
+ __version__ = "0.1.0"
18
+ __all__ = [
19
+ "MP3CoverAdder",
20
+ "read_mp3_metadata",
21
+ "set_mp3_cover",
22
+ "remove_mp3_cover",
23
+ "set_mp3_metadata",
24
+ "write_mp3",
25
+ ]
@@ -0,0 +1,334 @@
1
+ """Core functionality for MP3 cover art and metadata manipulation."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional, Union, Dict, Any
5
+ from io import BytesIO
6
+ import shutil
7
+ import tempfile
8
+ import os
9
+
10
+ from mutagen.mp3 import MP3
11
+ from mutagen.id3 import ID3, APIC, TIT2, TPE1, TALB, PictureType
12
+
13
+
14
+ class MP3CoverAdder:
15
+ """
16
+ Main class for manipulating MP3 files with cover art and ID3 metadata.
17
+
18
+ Example:
19
+ >>> mp3 = MP3CoverAdder("song.mp3")
20
+ >>> mp3.set_cover("cover.jpg")
21
+ >>> mp3.set_metadata(title="My Song", artist="Artist Name")
22
+ >>> mp3.write("output.mp3")
23
+ """
24
+
25
+ def __init__(self, file_path: Union[str, Path, bytes, BytesIO]):
26
+ """
27
+ Initialize MP3CoverAdder with an MP3 file.
28
+
29
+ Args:
30
+ file_path: Path to MP3 file, bytes, or BytesIO object
31
+ """
32
+ self._original_data = None
33
+ self._is_fileobj = False
34
+
35
+ if isinstance(file_path, bytes):
36
+ self._original_data = file_path
37
+ file_path = BytesIO(file_path)
38
+ self._is_fileobj = True
39
+ elif isinstance(file_path, BytesIO):
40
+ self._original_data = file_path.getvalue()
41
+ self._is_fileobj = True
42
+
43
+ self.audio = MP3(file_path)
44
+ if self.audio.tags is None:
45
+ self.audio.add_tags()
46
+
47
+ self._file_path = file_path
48
+
49
+ def get_metadata(self) -> Dict[str, Optional[str]]:
50
+ """
51
+ Read current ID3 metadata from the MP3 file.
52
+
53
+ Returns:
54
+ Dictionary containing title, artist, and album
55
+ """
56
+ tags = self.audio.tags
57
+ return {
58
+ "title": str(tags.get("TIT2", "")) if tags.get("TIT2") else None,
59
+ "artist": str(tags.get("TPE1", "")) if tags.get("TPE1") else None,
60
+ "album": str(tags.get("TALB", "")) if tags.get("TALB") else None,
61
+ }
62
+
63
+ def get_cover(self) -> Optional[bytes]:
64
+ """
65
+ Extract the album art from the MP3 file.
66
+
67
+ Returns:
68
+ Cover image as bytes, or None if no cover exists
69
+ """
70
+ tags = self.audio.tags
71
+ if tags is None:
72
+ return None
73
+
74
+ for key in tags.keys():
75
+ if key.startswith("APIC:"):
76
+ return tags[key].data
77
+
78
+ return None
79
+
80
+ def set_cover(
81
+ self,
82
+ image_source: Union[str, Path, bytes],
83
+ mime_type: Optional[str] = None,
84
+ description: str = "Cover",
85
+ ) -> None:
86
+ """
87
+ Set or replace the album art in the MP3 file.
88
+
89
+ Args:
90
+ image_source: Path to image file or image bytes (JPEG/PNG)
91
+ mime_type: MIME type (e.g., "image/jpeg"). Auto-detected if not provided.
92
+ description: Description for the cover art (default: "Cover")
93
+ """
94
+ if isinstance(image_source, (str, Path)):
95
+ with open(image_source, "rb") as f:
96
+ image_data = f.read()
97
+
98
+ if mime_type is None:
99
+ ext = Path(image_source).suffix.lower()
100
+ mime_type = {
101
+ ".jpg": "image/jpeg",
102
+ ".jpeg": "image/jpeg",
103
+ ".png": "image/png",
104
+ ".gif": "image/gif",
105
+ ".bmp": "image/bmp",
106
+ }.get(ext, "image/jpeg")
107
+ else:
108
+ image_data = image_source
109
+ if mime_type is None:
110
+ if image_data.startswith(b"\xff\xd8"):
111
+ mime_type = "image/jpeg"
112
+ elif image_data.startswith(b"\x89PNG"):
113
+ mime_type = "image/png"
114
+ elif image_data.startswith(b"GIF"):
115
+ mime_type = "image/gif"
116
+ else:
117
+ mime_type = "image/jpeg"
118
+
119
+ self.audio.tags.delall("APIC")
120
+ self.audio.tags.add(
121
+ APIC(
122
+ encoding=3,
123
+ mime=mime_type,
124
+ type=PictureType.COVER_FRONT,
125
+ desc=description,
126
+ data=image_data,
127
+ )
128
+ )
129
+
130
+ def remove_cover(self) -> None:
131
+ """Remove all album art from the MP3 file."""
132
+ self.audio.tags.delall("APIC")
133
+
134
+ def set_metadata(
135
+ self,
136
+ title: Optional[str] = None,
137
+ artist: Optional[str] = None,
138
+ album: Optional[str] = None,
139
+ ) -> None:
140
+ """
141
+ Set ID3 metadata fields.
142
+
143
+ Args:
144
+ title: Song title
145
+ artist: Artist name
146
+ album: Album name
147
+ """
148
+ if title is not None:
149
+ self.audio.tags.delall("TIT2")
150
+ self.audio.tags.add(TIT2(encoding=3, text=title))
151
+
152
+ if artist is not None:
153
+ self.audio.tags.delall("TPE1")
154
+ self.audio.tags.add(TPE1(encoding=3, text=artist))
155
+
156
+ if album is not None:
157
+ self.audio.tags.delall("TALB")
158
+ self.audio.tags.add(TALB(encoding=3, text=album))
159
+
160
+ def write(self, output_path: Optional[Union[str, Path]] = None) -> None:
161
+ """
162
+ Write changes to the MP3 file.
163
+
164
+ Args:
165
+ output_path: Path for output file. If None, modifies the original file.
166
+ """
167
+ if output_path is None:
168
+ self.audio.save()
169
+ else:
170
+ output_path = Path(output_path)
171
+ output_path.parent.mkdir(parents=True, exist_ok=True)
172
+
173
+ if isinstance(self._file_path, (str, Path)):
174
+ shutil.copy2(self._file_path, output_path)
175
+ elif self._original_data is not None:
176
+ output_path.write_bytes(self._original_data)
177
+
178
+ new_mp3 = MP3(output_path)
179
+ if new_mp3.tags is None:
180
+ new_mp3.add_tags()
181
+
182
+ new_mp3.tags.clear()
183
+ for key, value in self.audio.tags.items():
184
+ new_mp3.tags[key] = value
185
+
186
+ new_mp3.save()
187
+
188
+ def to_bytes(self) -> bytes:
189
+ """
190
+ Get the modified MP3 as bytes without writing to disk.
191
+
192
+ Returns:
193
+ MP3 file content as bytes
194
+ """
195
+ with tempfile.NamedTemporaryFile(mode='wb', suffix='.mp3', delete=False) as tmp:
196
+ tmp_path = tmp.name
197
+
198
+ try:
199
+ self.write(tmp_path)
200
+ with open(tmp_path, 'rb') as f:
201
+ return f.read()
202
+ finally:
203
+ if os.path.exists(tmp_path):
204
+ os.unlink(tmp_path)
205
+
206
+
207
+ def read_mp3_metadata(file_path: Union[str, Path, bytes, BytesIO]) -> Dict[str, Any]:
208
+ """
209
+ Read ID3 metadata and cover art from an MP3 file (convenience function).
210
+
211
+ Args:
212
+ file_path: Path to MP3 file, bytes, or BytesIO object
213
+
214
+ Returns:
215
+ Dictionary with 'title', 'artist', 'album', and 'has_cover' keys
216
+ """
217
+ mp3 = MP3CoverAdder(file_path)
218
+ metadata = mp3.get_metadata()
219
+ metadata["has_cover"] = mp3.get_cover() is not None
220
+ return metadata
221
+
222
+
223
+ def set_mp3_cover(
224
+ input_path: Union[str, Path, bytes, BytesIO],
225
+ image_source: Union[str, Path, bytes],
226
+ output_path: Optional[Union[str, Path]] = None,
227
+ mime_type: Optional[str] = None,
228
+ ) -> Optional[bytes]:
229
+ """
230
+ Set cover art on an MP3 file (convenience function).
231
+
232
+ Args:
233
+ input_path: Path to input MP3 file, bytes, or BytesIO
234
+ image_source: Path to image file or image bytes
235
+ output_path: Path for output file. If None, returns bytes instead.
236
+ mime_type: MIME type (auto-detected if not provided)
237
+
238
+ Returns:
239
+ MP3 bytes if output_path is None, otherwise None
240
+ """
241
+ mp3 = MP3CoverAdder(input_path)
242
+ mp3.set_cover(image_source, mime_type=mime_type)
243
+
244
+ if output_path is None:
245
+ return mp3.to_bytes()
246
+ else:
247
+ mp3.write(output_path)
248
+ return None
249
+
250
+
251
+ def remove_mp3_cover(
252
+ input_path: Union[str, Path, bytes, BytesIO],
253
+ output_path: Optional[Union[str, Path]] = None,
254
+ ) -> Optional[bytes]:
255
+ """
256
+ Remove cover art from an MP3 file (convenience function).
257
+
258
+ Args:
259
+ input_path: Path to input MP3 file, bytes, or BytesIO
260
+ output_path: Path for output file. If None, returns bytes instead.
261
+
262
+ Returns:
263
+ MP3 bytes if output_path is None, otherwise None
264
+ """
265
+ mp3 = MP3CoverAdder(input_path)
266
+ mp3.remove_cover()
267
+
268
+ if output_path is None:
269
+ return mp3.to_bytes()
270
+ else:
271
+ mp3.write(output_path)
272
+ return None
273
+
274
+
275
+ def set_mp3_metadata(
276
+ input_path: Union[str, Path, bytes, BytesIO],
277
+ output_path: Optional[Union[str, Path]] = None,
278
+ title: Optional[str] = None,
279
+ artist: Optional[str] = None,
280
+ album: Optional[str] = None,
281
+ ) -> Optional[bytes]:
282
+ """
283
+ Set ID3 metadata on an MP3 file (convenience function).
284
+
285
+ Args:
286
+ input_path: Path to input MP3 file, bytes, or BytesIO
287
+ output_path: Path for output file. If None, returns bytes instead.
288
+ title: Song title
289
+ artist: Artist name
290
+ album: Album name
291
+
292
+ Returns:
293
+ MP3 bytes if output_path is None, otherwise None
294
+ """
295
+ mp3 = MP3CoverAdder(input_path)
296
+ mp3.set_metadata(title=title, artist=artist, album=album)
297
+
298
+ if output_path is None:
299
+ return mp3.to_bytes()
300
+ else:
301
+ mp3.write(output_path)
302
+ return None
303
+
304
+
305
+ def write_mp3(
306
+ input_path: Union[str, Path, bytes, BytesIO],
307
+ output_path: Union[str, Path],
308
+ image_source: Optional[Union[str, Path, bytes]] = None,
309
+ title: Optional[str] = None,
310
+ artist: Optional[str] = None,
311
+ album: Optional[str] = None,
312
+ mime_type: Optional[str] = None,
313
+ ) -> None:
314
+ """
315
+ Write an MP3 file with optional cover art and metadata (convenience function).
316
+
317
+ Args:
318
+ input_path: Path to input MP3 file, bytes, or BytesIO
319
+ output_path: Path for output file
320
+ image_source: Optional path to image file or image bytes
321
+ title: Optional song title
322
+ artist: Optional artist name
323
+ album: Optional album name
324
+ mime_type: Optional MIME type for image (auto-detected if not provided)
325
+ """
326
+ mp3 = MP3CoverAdder(input_path)
327
+
328
+ if image_source is not None:
329
+ mp3.set_cover(image_source, mime_type=mime_type)
330
+
331
+ if title is not None or artist is not None or album is not None:
332
+ mp3.set_metadata(title=title, artist=artist, album=album)
333
+
334
+ mp3.write(output_path)
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.5
2
+ Name: mp3-cover-adder
3
+ Version: 0.1.0
4
+ Summary: Python library to embed MP3 album art and edit ID3 tags
5
+ Project-URL: Homepage, https://github.com/sherotree/mp3-cover-adder-py
6
+ Project-URL: Repository, https://github.com/sherotree/mp3-cover-adder-py
7
+ Project-URL: Web Tool, https://www.uwarp.design/mp3-cover-adder
8
+ Author-email: Sherotree <sherotree@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: album-art,audio,cover-art,id3,metadata,mp3
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Multimedia :: Sound/Audio
22
+ Requires-Python: >=3.8
23
+ Requires-Dist: mutagen>=1.45.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: black>=23.0.0; extra == 'dev'
26
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
31
+ Requires-Dist: pytest>=7.0.0; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # mp3-cover-adder
35
+
36
+ [**Add Cover to MP3**](https://www.uwarp.design/mp3-cover-adder) — free browser tool for embedding album art and editing ID3 tags (the reference UI for this library).
37
+
38
+ Offline Python library for embedding album art and editing ID3 metadata in MP3 files.
39
+
40
+ Package: **`mp3-cover-adder`** on PyPI (`0.1.0`).
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install mp3-cover-adder
46
+ ```
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ from mp3_cover_adder import MP3CoverAdder
52
+
53
+ # Read and modify an MP3 file
54
+ mp3 = MP3CoverAdder("song.mp3")
55
+ mp3.set_cover("cover.jpg")
56
+ mp3.set_metadata(title="My Song", artist="Artist Name", album="Album Title")
57
+ mp3.write("output.mp3")
58
+
59
+ # Or work with bytes in memory
60
+ result_bytes = mp3.to_bytes()
61
+ ```
62
+
63
+ ## API
64
+
65
+ ### Class API
66
+
67
+ | Method | Description |
68
+ | --- | --- |
69
+ | `MP3CoverAdder(file_path)` | Load MP3 from path, bytes, or BytesIO |
70
+ | `.get_metadata()` | Returns `dict` with title, artist, album |
71
+ | `.get_cover()` | Returns cover image as `bytes` or `None` |
72
+ | `.set_cover(image, mime_type=None)` | Set/replace cover from path or bytes (JPEG/PNG) |
73
+ | `.remove_cover()` | Remove all album art |
74
+ | `.set_metadata(title=None, artist=None, album=None)` | Update ID3 text fields |
75
+ | `.write(output_path=None)` | Save to file (or modify in-place if path is `None`) |
76
+ | `.to_bytes()` | Get modified MP3 as bytes without writing |
77
+
78
+ ### Convenience functions
79
+
80
+ | Function | Role |
81
+ | --- | --- |
82
+ | `read_mp3_metadata(file)` | Read metadata + check for cover art |
83
+ | `set_mp3_cover(input, image, output=None)` | Add cover (returns bytes if `output` is `None`) |
84
+ | `remove_mp3_cover(input, output=None)` | Remove cover (returns bytes if `output` is `None`) |
85
+ | `set_mp3_metadata(input, output=None, ...)` | Update metadata (returns bytes if `output` is `None`) |
86
+ | `write_mp3(input, output, image=None, ...)` | One-shot: write MP3 with optional cover + metadata |
87
+
88
+ ## Examples
89
+
90
+ ### Read metadata and cover
91
+
92
+ ```python
93
+ from mp3_cover_adder import read_mp3_metadata, MP3CoverAdder
94
+
95
+ # Quick check
96
+ info = read_mp3_metadata("song.mp3")
97
+ print(info) # {'title': '...', 'artist': '...', 'album': '...', 'has_cover': True}
98
+
99
+ # Extract cover
100
+ mp3 = MP3CoverAdder("song.mp3")
101
+ cover_bytes = mp3.get_cover()
102
+ if cover_bytes:
103
+ with open("extracted_cover.jpg", "wb") as f:
104
+ f.write(cover_bytes)
105
+ ```
106
+
107
+ ### Add or replace cover art
108
+
109
+ ```python
110
+ from mp3_cover_adder import set_mp3_cover
111
+
112
+ # From file path (MIME type auto-detected from extension)
113
+ set_mp3_cover("input.mp3", "cover.jpg", output_path="output.mp3")
114
+
115
+ # From bytes in memory (MIME type auto-detected from magic bytes)
116
+ with open("cover.png", "rb") as f:
117
+ cover_data = f.read()
118
+
119
+ result = set_mp3_cover("input.mp3", cover_data) # returns bytes
120
+ with open("output.mp3", "wb") as f:
121
+ f.write(result)
122
+ ```
123
+
124
+ ### Update metadata only
125
+
126
+ ```python
127
+ from mp3_cover_adder import MP3CoverAdder
128
+
129
+ mp3 = MP3CoverAdder("song.mp3")
130
+ mp3.set_metadata(
131
+ title="Updated Title",
132
+ artist="New Artist",
133
+ album="New Album"
134
+ )
135
+ mp3.write() # modify in-place
136
+ ```
137
+
138
+ ### Remove album art
139
+
140
+ ```python
141
+ from mp3_cover_adder import remove_mp3_cover
142
+
143
+ remove_mp3_cover("input.mp3", output_path="output_no_cover.mp3")
144
+ ```
145
+
146
+ ### All-in-one convenience
147
+
148
+ ```python
149
+ from mp3_cover_adder import write_mp3
150
+
151
+ write_mp3(
152
+ input_path="input.mp3",
153
+ output_path="output.mp3",
154
+ image_source="cover.jpg",
155
+ title="Song Title",
156
+ artist="Artist Name",
157
+ album="Album Name"
158
+ )
159
+ ```
160
+
161
+ ## Tests
162
+
163
+ ```bash
164
+ pytest
165
+ # or with coverage
166
+ pytest --cov=mp3_cover_adder
167
+ ```
168
+
169
+ ## Development
170
+
171
+ ```bash
172
+ # Install dev dependencies
173
+ pip install -e ".[dev]"
174
+
175
+ # Run tests
176
+ pytest
177
+
178
+ # Format code
179
+ black src/ tests/
180
+
181
+ # Lint
182
+ ruff check src/ tests/
183
+ ```
184
+
185
+ ## License
186
+
187
+ MIT. See [LICENSE](./LICENSE).
@@ -0,0 +1,6 @@
1
+ mp3_cover_adder/__init__.py,sha256=cJbRZXch8hblYyhhkLQ3wv_RKc6iaS56fI4B7dbaJdU,519
2
+ mp3_cover_adder/core.py,sha256=7cVv3Bqi4H_3-I7rIpaW8BoIlBu5s1wlezkk3LEWjIs,10242
3
+ mp3_cover_adder-0.1.0.dist-info/METADATA,sha256=1WT9xLa9vPxqF0JCaGHzzv5JDESKTIPJUf97za9Pmok,5070
4
+ mp3_cover_adder-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ mp3_cover_adder-0.1.0.dist-info/licenses/LICENSE,sha256=AmdkZ4b6KoWeSKU8gIrC4XlCHx617Quw79zI2FhbFmY,1066
6
+ mp3_cover_adder-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sherotree
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.