fix : canonical mime type mapping from formats to remove inconsistency #4627 (#4628)

* fix : canonical mime type mapping from formats to remove inconsistency

* Apply ruff format to _get_mime_type

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
This commit is contained in:
Aman Gupta 2026-07-26 23:45:08 +05:30 committed by GitHub
commit e4a87f2afe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 11 deletions

View file

@ -335,18 +335,21 @@ class Audio:
def _get_mime_type(self) -> str:
"""Get MIME type from format or guess from file extension."""
mapping = {
"wav": "audio/wav",
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
"m4a": "audio/mp4",
"flac": "audio/flac",
}
if self._format:
return f"audio/{self._format.lower()}"
return mapping.get(self._format.lower(), f"audio/{self._format.lower()}")
if self.path:
suffix = self.path.suffix.lower()
return {
".wav": "audio/wav",
".mp3": "audio/mpeg",
".ogg": "audio/ogg",
".m4a": "audio/mp4",
".flac": "audio/flac",
}.get(suffix, "application/octet-stream")
return mapping.get(
self.path.suffix.lower().lstrip("."), "application/octet-stream"
)
return "audio/wav" # default for raw binary data
def to_audio_content(

View file

@ -282,10 +282,25 @@ class TestAudio:
assert audio.data == b"test"
assert audio._mime_type == "audio/wav" # Default for raw data
def test_mime_type_from_format(self):
"""Test MIME type normalization from audio format."""
expected = {
"wav": "audio/wav",
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
"m4a": "audio/mp4",
"flac": "audio/flac",
}
for fmt, mime in expected.items():
audio = Audio(data=b"test", format=fmt)
assert audio._mime_type == mime
def test_audio_initialization_with_format(self):
"""Test audio initialization with a specific format."""
audio = Audio(data=b"test", format="mp3")
assert audio._mime_type == "audio/mp3"
assert audio._mime_type == "audio/mpeg"
def test_missing_data_and_path_raises_error(self):
"""Test that error is raised when neither path nor data is provided."""
@ -335,7 +350,7 @@ class TestAudio:
content = audio.to_audio_content()
assert content.type == "audio"
assert content.mime_type == "audio/mp3"
assert content.mime_type == "audio/mpeg"
assert content.data == base64.b64encode(test_data).decode()
def test_to_audio_content_error(self, monkeypatch):