Skip to content

[Feature Request] Magika Dependency Optional #1234

Open

Description

Would it be possible to make the Magika dependency optional (i.e., pulled in as an extra)? I'm trying to use MarkItDown in the browser via Pyodide and Magika's dependency on ONNX is causing trouble.

My understanding is that Magika is used to determine the stream type, I guess in cases where the application doesn't provide it (or maybe provides incorrect information by accident?). In my case, I'd be happy to trade away that flexibility in exchange for dropping the Magika / ONNX dependency.

I tested with a forked repo where I removed self._magika.identify_stream(file_stream) from _get_stream_info_guesses() and I was able to convert PDFs in the browser.

Activity

  1. josh-levinson-scratchpad commented on May 15, 2025

    @josh-levinson-scratchpad

    👍 We're trying to use this in an AWS lambda and the >100MB runtime dependency makes this more challenging than it needs to be. Being able to specify a file type based on extension, mime type, or something lighter weight like file would be nice.

  2. RKeelan commented on May 26, 2025

    @RKeelan
    Author

    I forked the repo and removed the magika dependency, and it seems to work okay

  3. Soulter commented on May 31, 2025

    @Soulter
    Contributor

    I also think this feature is necessary.

  4. coneill-relay commented on Jun 23, 2025

    @coneill-relay

    It would be nice to have the ability to slim down this package. Im also trying to use this in a lambda and have resorted to just building an image and deploying to lambda which allows me 10Gb of space. The ability to guess types is useful but seems overkill if you are using this to process known filetypes

  5. aswinbharadwaj commented on Jul 23, 2025

    @aswinbharadwaj

    It would help to make the file detection dependency optional in order to bring down the size of the pkg.
    Also, if every file type was offered as an optional install that would help bring down the size.
    My use case was just to process HTML, and didn't need the entire pkg to do that.

  6. htxryan commented on Jul 31, 2025

    @htxryan

    This would be fantastic! We need to support as many hosting environments as possible, and this required dependency makes it difficult.

  7. Soulter commented on Jul 31, 2025

    @Soulter
    Contributor

    Hi, I created a fork of markitdown weeks ago, which has removed magika, guys can use https://github.com/Soulter/markitdown as a temporary solution until authors fix this issue.

    pip install markitdown-no-magika
    # or select some of the following feature:
    # pptx = ["python-pptx"]
    # docx = ["mammoth", "lxml"]
    # xlsx = ["pandas", "openpyxl"]
    # xls = ["pandas", "xlrd"]
    # pdf = ["pdfminer.six"]
    # outlook = ["olefile"]
    # audio-transcription = ["pydub", "SpeechRecognition"]
    # youtube-transcription = ["youtube-transcript-api"]
    # az-doc-intel = ["azure-ai-documentintelligence", "azure-identity"]
    # 
    # example: 
    # pip install markitdown-no-magika[pptx, docx, xlsx, pdf]
  8. typefox09 commented on Sep 11, 2025

    @typefox09

    Plus one on this, can't use it in an AWS lambda, 140mb for Magika is ridiculous

  9. ClaraLeigh commented on Sep 12, 2025

    @ClaraLeigh

    FYI for anyone interested (ie Bobby R (@typefox09) ) the no markitdown-no-magika repo Soulter (@Soulter) made does work on lambda, at least in a POC test I did for a future project. However I suspect a slightly clearner PR would be better to make it work with the main repo.

    Small reminder, to import using that package, it would be: from markitdown_no_magika import MarkItDown

  10. wafriq commented on Oct 28, 2025

    @wafriq

    User of Digital Ocean Functions here which require a zipped environment to be max 48 MB.

    magika comes both with a large (~30 MB if I recall correctly) binary blob for its model and it's also pulling in https://pypi.org/project/onnxruntime/ which itself is another heavy dependency.

    To remove these 2 dependencies, I run this post-processing after pyp install markitdown:

    pip install markitdown
    pip uninstall -y magika onnxruntime
    

    and then replacing magika with a shim:

    cp magika.py virtualenv/lib/python3.11/site-packages/
    

    Here's the magika.py shim file:

    """Magika shim which always fails stream identification"""
    
    class Magika:
        def __init__(self, *args, **kwargs):
            pass
    
        def identify_stream(self, stream):
            return MagikaResult()
    
    
    class MagikaResult:
        def __init__(self):
            self.status = "failed"
    
    
    __version__ = "0.6.1"
    __all__ = ['Magika']
    

    Now you will always need to explicitly pass either file_extension=".html" (deprecated according to the docs) or stream_info=StreamInfo(mimetype="application/html") to .convert() to prevent the converter detection from failing.

    The entire zipped environment is now only ~20 MB and the Digital Ocean Function executes as expected. (I also removed click and a few other dependencies that seem unnecessary for my use case)

    I found above approach better than forking the markitdown repo as other users did.

  11. basnijholt commented on Jan 14, 2026

    @basnijholt
    Contributor

    Modified cross posting from https://github.com/microsoft/onnxruntime/issues/26309#issuecomment-3743333977:

    I maintain a CLI tool (agent-cli) where onnxruntime is an optional dependency for specific features (RAG/memory), and wanted to share the downstream impact this is causing.

    When a user runs uv tool install agent-cli[memory] and uv selects Python 3.14 (which it does by default if 3.14 is installed), the installation either fails entirely if onnxruntime is in the dependency tree, or falls back to an older version of my package that didn't have the transitive onnxruntime dependency. Neither is great.

    I ended up adding python_version < '3.14' markers (basnijholt/agent-cli#198):

    [project.optional-dependencies]
    memory = [
        "onnxruntime>=1.17.0; python_version < '3.14'",
        # ...
    ]

    This lets users on 3.14 install my package (with memory/RAG features unavailable), but the annoying part is that when onnxruntime does add 3.14 support, I'll need to release a new version to remove this constraint - it won't just work for existing users.

    Making magika and optional dependency in markitdown would solve this issue and remove a huge transitive dependency.

  12. mehfuzh commented on Mar 14, 2026

    @mehfuzh

    I am trying to distribute a local LLM-driven TUI. I use markItDown to process PDF, docx, etc, to convert to markdown (modern assembly for LLMs) before building the dataset and fine-tuning.

    I've noticed that binary is extremely large. If I want to go pyintaller route to easily distribute it. One of dependencies that is contributing to it is magika it is using AI model to detect file types, which I don't need as I can just do it using simple semantic mime-types

    I am going to use this for now

    pip install markitdown-no-magika
    

    However, it would be great to have a version without magika for using it just as a document processor, where I know the file types

  13. MrLeit commented on Oct 28, 2026

    @MrLeit

    In case anyone else comes across this and doesn't want to use a random outdated library like markitdown-no-magika, here is a patch which should exclude the dep and stub it. When the MR for this feature lands you can simply drop patch.

    Exclude the package.

    exclude-dependencies = [
        "magika",
    ]
    

    Monkey patch the module to have a custom Magika impl with a bit of documentation and guards in case the underlying source changes.

    """markitdown library tweaks: a stand-in for magika, which markitdown imports but the chat does not need.
    
    magika, with the onnxruntime model behind it, sniffs a file's type from its bytes. markitdown imports it
    at the top of its main module and loads its model in `MarkItDown()`, about 50 MB held for the life of the
    process. Every file the chat converts arrives with its extension, which markitdown keeps as its guess
    when magika identifies nothing, so magika is excluded from the lock (`exclude-dependencies` in the root
    pyproject.toml) and the stub below answers in its place. The stub is registered when this module is
    imported, which has to happen before markitdown is.
    
    Making magika optional is requested in https://github.com/microsoft/markitdown/issues/1234 and
    implemented, unmerged, in https://github.com/microsoft/markitdown/pull/1355. Once markitdown no longer
    needs magika, delete this module and the exclusion.
    """
    
    import importlib.util
    import inspect
    import sys
    from types import ModuleType, SimpleNamespace
    from typing import BinaryIO
    
    # The markitdown code the stub answers: magika constructed in MarkItDown.__init__, and asked to
    # identify a stream in _get_stream_info_guesses, whose result is used only when its status is "ok".
    _EXPECTED_SOURCE = {
        "__init__": ("magika.Magika()",),
        "_get_stream_info_guesses": ("self._magika.identify_stream(", 'result.status == "ok"'),
    }
    
    
    class _Magika:
        """magika.Magika as markitdown calls it, identifying nothing."""
    
        def identify_stream(self, stream: BinaryIO) -> SimpleNamespace:
            # Not raising: markitdown calls this inside try/finally, with no except.
            return SimpleNamespace(status="failed")
    
    
    _STUBBED = importlib.util.find_spec("magika") is None
    if _STUBBED:
        _magika = ModuleType("magika")
        _magika.Magika = _Magika  # type: ignore[attr-defined]
        sys.modules["magika"] = _magika
    
    
    def check_magika_stub() -> None:
        """Fail when markitdown no longer calls magika the way the stub answers. A changed call could
        reach what the stub lacks, and a release that drops magika no longer needs the stub at all."""
        if not _STUBBED:
            return
        from markitdown import MarkItDown
    
        missing = [
            f"{method}: {snippet}"
            for method, snippets in _EXPECTED_SOURCE.items()
            for snippet in snippets
            if snippet not in inspect.getsource(getattr(MarkItDown, method))
        ]
        if missing:
            raise RuntimeError(
                f"markitdown no longer uses magika as the stub in {__name__} expects ({'; '.join(missing)}). "
                "Revisit the stub, or remove it with the magika exclusion if magika is optional upstream "
                "(https://github.com/microsoft/markitdown/issues/1234)."
            )
    
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions