Skip to content

modosaic.services.extension

modosaic.services.extension

ExtensionService

Helpers for image extensions and filesystem-safe path fragments.

infer_extension_from_bytes staticmethod

infer_extension_from_bytes(data)

Infer a known image extension from encoded bytes.

Parameters:

Name Type Description Default
data bytes

Encoded image bytes.

required

Returns:

Type Description
str | None

.png, .jpg, or None when the signature is unknown.

Source code in modosaic/services/extension.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
@staticmethod
def infer_extension_from_bytes(data: bytes) -> str | None:
    """Infer a known image extension from encoded bytes.

    Args:
        data: Encoded image bytes.

    Returns:
        `.png`, `.jpg`, or `None` when the signature is unknown.
    """
    if data.startswith(PNG_BYTES):
        return PNG_EXTENSION
    if data.startswith(JPG_BYTES):
        return JPG_EXTENSION
    return None

normalize_extension staticmethod

normalize_extension(extension, fallback='.bin')

Normalize a file extension.

Parameters:

Name Type Description Default
extension str | None

Optional extension with or without a leading dot.

required
fallback str

Extension returned when extension is empty.

'.bin'

Returns:

Type Description
str

Extension with a leading dot.

Source code in modosaic/services/extension.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@staticmethod
def normalize_extension(extension: str | None, fallback: str = ".bin") -> str:
    """Normalize a file extension.

    Args:
        extension: Optional extension with or without a leading dot.
        fallback: Extension returned when `extension` is empty.

    Returns:
        Extension with a leading dot.
    """
    if not extension:
        return fallback
    return extension if extension.startswith(".") else f".{extension}"

sanitize_fragment staticmethod

sanitize_fragment(value)

Convert arbitrary text into a safe filename fragment.

Parameters:

Name Type Description Default
value str

Text to sanitize.

required

Returns:

Type Description
str

A non-empty fragment containing alphanumeric characters, dots,

str

dashes, and underscores only.

Source code in modosaic/services/extension.py
23
24
25
26
27
28
29
30
31
32
33
34
35
@staticmethod
def sanitize_fragment(value: str) -> str:
    """Convert arbitrary text into a safe filename fragment.

    Args:
        value: Text to sanitize.

    Returns:
        A non-empty fragment containing alphanumeric characters, dots,
        dashes, and underscores only.
    """
    safe = "".join(ch if ch.isalnum() or ch in {"-", "_", "."} else "_" for ch in value)
    return safe.strip("._") or "sample"