Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions python/src/magika/magika.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,30 @@ def get_model_content_types(self) -> List[ContentTypeLabel]:
model_content_types.update(self._model_config.target_labels_space)
return sorted(model_content_types)

def get_content_type_info(self, label: ContentTypeLabel) -> ContentTypeInfo:
"""Returns metadata for a given content type label.

This provides access to the content type knowledge base, exposing
structured metadata such as mime type, group, human-readable
description, common file extensions, and whether the type is
text-based.

Args:
label: The ContentTypeLabel to look up.

Returns:
The ContentTypeInfo for the given label.

Raises:
MagikaError: If the label is not present in the content type
knowledge base (e.g., ContentTypeLabel.UNDEFINED).
"""
if label not in self._cts_infos:
raise MagikaError(
f"Content type '{label}' is not in the content type knowledge base."
)
return self._cts_infos[label]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This is a great addition to the public API. I have a couple of suggestions for improvement:

  1. Use EAFP pattern: For better adherence to Python idioms, consider using a try...except block (EAFP - "it's easier to ask for forgiveness than permission") instead of checking for the key's presence before accessing it. This is generally more performant if the key is expected to be present most of the time.
  2. Fix docstring example: The example ContentTypeLabel.UNDEFINED in the Raises section of the docstring appears to be incorrect, as undefined is present in content_types_kb.min.json and thus will not raise an error. To avoid confusion, it's best to remove the example.

Here's a suggested implementation incorporating these points:

    def get_content_type_info(self, label: ContentTypeLabel) -> ContentTypeInfo:
        """Returns metadata for a given content type label.

        This provides access to the content type knowledge base, exposing
        structured metadata such as mime type, group, human-readable
        description, common file extensions, and whether the type is
        text-based.

        Args:
            label: The ContentTypeLabel to look up.

        Returns:
            The ContentTypeInfo for the given label.

        Raises:
            MagikaError: If the label is not present in the content type
                knowledge base.
        """
        try:
            return self._cts_infos[label]
        except KeyError:
            raise MagikaError(
                f"Content type '{label}' is not in the content type knowledge base."
            ) from None


@staticmethod
def _get_default_model_name() -> str:
"""Returns the default model name.
Expand Down
31 changes: 31 additions & 0 deletions python/tests/test_magika_python_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,37 @@ def test_get_model_and_output_content_types() -> None:
}.issubset(model_content_types_set)


def test_get_content_type_info() -> None:
"""Test Magika.get_content_type_info() — fixes #826.

Verifies that the public API correctly exposes ContentTypeInfo metadata
(mime_type, group, description, extensions, is_text) for every
ContentTypeLabel that is part of the content type knowledge base.
"""
m = Magika()

# Every output content type must be queryable and return valid metadata.
for label in m.get_output_content_types():
info = m.get_content_type_info(label)
assert isinstance(info, ContentTypeInfo)
assert info.label == label
assert isinstance(info.mime_type, str) and info.mime_type != ""
assert isinstance(info.group, str) and info.group != ""
assert isinstance(info.description, str) and info.description != ""
assert isinstance(info.extensions, list)
assert isinstance(info.is_text, bool)

# Spot-check a well-known content type's metadata.
pdf_info = m.get_content_type_info(ContentTypeLabel.PDF)
assert pdf_info.mime_type == "application/pdf"
assert pdf_info.group == "document"
assert pdf_info.is_text is False

# Text-based type should report is_text=True.
py_info = m.get_content_type_info(ContentTypeLabel.PYTHON)
assert py_info.is_text is True
Comment on lines +764 to +792
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This test covers the success paths well, but it's missing a check for the error condition. The get_content_type_info method is documented to raise a MagikaError for unknown labels. Please add a test case to verify this behavior.

def test_get_content_type_info() -> None:
    """Test Magika.get_content_type_info() — fixes #826.

    Verifies that the public API correctly exposes ContentTypeInfo metadata
    (mime_type, group, description, extensions, is_text) for every
    ContentTypeLabel that is part of the content type knowledge base.
    """
    from magika.types import MagikaError

    m = Magika()

    # Every output content type must be queryable and return valid metadata.
    for label in m.get_output_content_types():
        info = m.get_content_type_info(label)
        assert isinstance(info, ContentTypeInfo)
        assert info.label == label
        assert isinstance(info.mime_type, str) and info.mime_type != ""
        assert isinstance(info.group, str) and info.group != ""
        assert isinstance(info.description, str) and info.description != ""
        assert isinstance(info.extensions, list)
        assert isinstance(info.is_text, bool)

    # Spot-check a well-known content type's metadata.
    pdf_info = m.get_content_type_info(ContentTypeLabel.PDF)
    assert pdf_info.mime_type == "application/pdf"
    assert pdf_info.group == "document"
    assert pdf_info.is_text is False

    # Text-based type should report is_text=True.
    py_info = m.get_content_type_info(ContentTypeLabel.PYTHON)
    assert py_info.is_text is True

    # Verify that an unknown label raises MagikaError.
    with pytest.raises(MagikaError, match="is not in the content type knowledge base"):
        # Note: we use a string here because all ContentTypeLabel enum
        # members are expected to be in the KB.
        m.get_content_type_info("this_is_not_a_real_label")



def test_magika_imports():
imported_modules = utils.get_imported_objects_after_wildcard()

Expand Down