Skip to content

Add support for image/webp to mimetypes package #2002

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions python/cog/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import mimetypes

from pydantic import BaseModel

from .mimetypes_ext import install_mime_extensions
from .predictor import BasePredictor
from .server.worker import emit_metric
from .types import (
Expand All @@ -11,6 +14,8 @@
Secret,
)

install_mime_extensions(mimetypes)

try:
from ._version import __version__
except ImportError:
Expand Down
16 changes: 16 additions & 0 deletions python/cog/mimetypes_ext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import Protocol


class IMimeTypes(Protocol):
def add_type(self, type: str, ext: str, strict: bool = True) -> None: ...


def install_mime_extensions(mimetypes: IMimeTypes) -> None:
"""
Older versions of Python are missing the MIME types for more recent file formats
this function adds the missing MIME types to the mimetypes module.
"""

# This could also be done by loading a mime.types file from disk using
# mimetypes.read_mime_types().
mimetypes.add_type("image/webp", ".webp")
17 changes: 17 additions & 0 deletions python/tests/test_mimetypes_ext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from mimetypes import MimeTypes
from cog.mimetypes_ext import install_mime_extensions


def test_webp_ext_support():
# Assert on empty database.
mt = MimeTypes(filenames=tuple())
assert mt.guess_type("image.webp") == (None, None)
install_mime_extensions(mt)
assert mt.guess_type("image.webp") == ("image/webp", None)

# Assert global override
import cog

import mimetypes

assert mimetypes.guess_type("image.webp") == ("image/webp", None)
Loading