Skip to content

FEAT: choose plugin based on extension and lazy-import plugins - #680

Merged
FirefoxMetzger merged 63 commits into
imageio:masterfrom
FirefoxMetzger:format-prediction
Nov 17, 2021
Merged

FirefoxMetzger merged 63 commits into
imageio:masterfrom
FirefoxMetzger:format-prediction

Conversation

@FirefoxMetzger

@FirefoxMetzger FirefoxMetzger commented Nov 5, 2021 •

Copy link
Copy Markdown
Contributor

Closes #641
Closes #677 (fix is implemented here)
Closes #665
Closes #334

Issues that may be closed or will become easy to close
#580

This PR is essentially a large refactor of the plugin manager that aligns imopen, the old FormatManager and the docs and forces them to remain in sync. It does so by adding (and changing) a few things:

  1. imageio.core now relies on imageio.config for global configuration (formerly used for docs only).
  2. It adds known_plugins and known_extensions in imageio.config to track extensions and plugins.
  3. imopen now looks up the request's extension in known_extensions and (upon success) tries relevant plugins first. (Smart searching of plugins by accounting for the file's extension. #641)
  4. imopen now checks known_plugins when checking all plugins (if extension-based handling doesn't work).
  5. imopen's state is no longer needed, so it is now a function (formerly it was a class).
  6. FormatManager now internally delegates all format lookups to imopen. (formerly, imopen called the format manager as a fallback when it couldn't find a plugin).
  7. FormatManager's add_format now adds a format to known_formats and it's sort method sorts known_formats.
  8. imopen will now lazy-import a plugin during the first time it selects that plugin to handle a request. (fixes 'import imageio' on M1 MacBook with Python 3.9 causes "MemoryError" - installed with conda/pip #665 because FreeImage will only be imported when actually used by the code)
  9. imopen will now display a friendly error message in cases a request could not be handled, but a user might be able to install a plugin to handle it. (Improve error message when reading an EXR file without plugin installed #334)
  10. FormatManager will now lazy-import a plugin during the first time it is asked to return a format of that plugin.
  11. It adds a check to FreeImage's _can_read to handle a bug in FreeImage related to PPM and PBM files (FreeImage identifies images written via PPM-FI as PBM-FI. #677)

Lazy-importing should also be a good first step towards factoring out some of the backends (including FreeImage), which would eventually address #580.


What is left for this PR:

  • Docstrings for the relevant functions.
  • Tests to hit the PR coverage target.

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

I noticed a "regression" introduced in this PR: If the user selected a specific format using the old FormatManager, it would be used immediately without doing any checks. In imopen, a LegacyPlugin (wrapping an old Format) will test can_read first and will fail if the format claims it can't read.

As a result, imageio-ffmpeg can no longer read from FileObjects or byte strings, because its plugin only checks the file extension, which is None in this case and gets rejected.

@almarklein This would need to be fixed by having ffmpeg check the header of the file (or what ever the equivalent thing is for that backend). Any thoughts on how to best go about this?

@almarklein

Copy link
Copy Markdown
Member

Any thoughts on how to best go about this?

Nope. I bet that there would be an awful lot of headers that ffmpeg could parse, but I don't think we can give ffmpeg a few bytes and ask it to let us know if it looks familiar :) I guess this is the way it is?

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

but I don't think we can give ffmpeg a few bytes and ask it to let us know if it looks familiar :) I guess this is the way it is?

Theoretically, there is ffprobe that might give us that information in a relatively efficient way. I don't know how easy/hard it would be to feed in a file object though (I also don't really know how we do that in ffmpeg itself :D).

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

Status update: Currently the tests are breaking (again), because we give DICOM special treatment and allow it to read folders. I ran into this situation multiple times while writing this PR, and I remember dealing with this in previous PRs.

@almarklein Can we formalize folder support for Requests (introduce a URI_FOLDER or something) and factor out this code-path, or explicitly deny it with a clean error message?

Currently, Request.get_file() breaks with a PermissionDeniedError somewhere deep inside the library, if the request points to a folder. None of our docs suggest that it is possible to use directories as URIs and, with the exception of DICOM, all plugins break when they encounter a folder. I would consider this a bug and - in fact - our official example suggests that this is impossible.

At the same time, we have supported folder access for DICOM for several years now, and simply dropping it seems like a bad idea.

@almarklein

Copy link
Copy Markdown
Member

Interesting. This is indeed an edge case. In the old version, we seemed to have worked around it. Do you know why we do run into it now? Maybe that gives a hint on how to best solve this.

Introduce a URI_FOLDER or something

That may seem the most clean solution, but I don't oversee how this will affect the rest of the code. If we can make this work without needing changes in all other plugins then maybe this is a way forward.

Alternatively, we may need to force reading a dicomdir by providing the path to an arbitrary file in that directory. This is also not pretty though...

Do you think we can keep DICOM working as-is if the plugin is explicitly selected? That might help.

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

Do you know why we do run into it now? Maybe that gives a hint on how to best solve this.

We ran into this before but simply patched it in the function that encountered it instead of dealing with it formerly. For example:

# Prepare
try:
f = self.get_file()
except IOError:
if os.path.isdir(self.filename): # A directory, e.g. for DICOM
self._firstbytes = bytes()
return
raise

In this particular case, we are encountering it because I made tifffile's _can_read more sophisticated. I now check the file header in addition to the extension to decide if the file is a TIFF. tifffile gets checked before DICOM (the unit test didn't enforce the DICOM plugin), and that then breaks the test.

That may seem the most clean solution, but I don't oversee how this will affect the rest of the code. If we can make this work without needing changes in all other plugins then maybe this is a way forward.

I'm not sure if this is possible to change incrementally; my hunch is that it isn't. However, at the moment, we even struggle to detect if the request points to a file vs. a folder, so even if we would be willing to add changes to all plugins in one go, we would first have to establish how this info is shared with plugins.

Do you think we can keep DICOM working as-is if the plugin is explicitly selected? That might help.

Yes, that's what I implemented in 4923c7d. If the request is called with an explicit plugin=value then it will work fine. Otherwise, an error will be raised when the URI points to a dictionary.

This is, however, me adding a quick-fix to solve breaking CI, so we might still want to formalize this behavior to avoid doing more quick-fix patches (and remove the ones we have already).

@almarklein

Copy link
Copy Markdown
Member

This is, however, me adding a quick-fix to solve breaking CI, so we might still want to formalize this behavior to avoid doing more quick-fix patches (and remove the ones we have already).

Given the circumstances I think that fix is actually not that hacky. Formalizing support for folders just because of this one plugin, without any further advantages, is also not great. What I mean to say: I don't there is a "pure" way to deal with this, and the current solution is clear for the user and confines the odd feature of being able to read a directory to a specific plugin.

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

Given the circumstances I think that fix is actually not that hacky. Formalizing support for folders just because of this one plugin, without any further advantages, is also not great. What I mean to say: I don't there is a "pure" way to deal with this, and the current solution is clear for the user and confines the odd feature of being able to read a directory to a specific plugin.

Yep. Given my perspective (maintainer level background knowledge of what ImageIO does and does not do), I agree here. Explicit support for folders adds much more problems than it solves. It can be like this for now, but I will dare to make a prophecy and say that we will bump into this issue again further down the road x).

When I said we might still want to formalize this behavior I mainly meant that we should have an agreed-upon standard on what we expect to happen here. If it is "we don't do folders, except for legacy reasons (DICOM)" that solves it for me. Though, in this case, I would like to see if we can check if that ability is still needed, or if we can deprecate it in v3 and make things consistent. (This way, Request can raise when it encounters a folder and it would make for cleaner code.)

On the other hand the question "how to read a folder of images with ImageIO?" is one of the more popular questions that I encounter when I am digging for problems with the library to find features we might wish to add. Our example on reading folders does address this, however, so I don't see it as a high-priority issue for now :)


Unless you have any unresolved points @almarklein I think the above should resolve/conclude all open points.

There is still the ffmpeg "regression"/bug of rejecting byte streams because ffmpeg's can_read isn't sophisticated enough. This, however, requires a bigger change (#680 (comment)) potentially involving changes to imageio-ffmpeg, so I would do this in a dedicated PR. If you agree @almarklein , I am happy to accept this temporary regression here and solve it down the line once we pick up the general slack around ffmpeg (missing formats, stream support, potential replacement with pyAV, ...)

@almarklein

Copy link
Copy Markdown
Member

I will dare to make a prophecy and say that we will bump into this issue again further down the road x).

I won't be surprised either :)

There is still the ffmpeg "regression"/bug of rejecting byte streams because ffmpeg's can_read isn't sophisticated enough.

Could you please remind me how this will affect users?

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

Could you please remind me how this will affect users?

Sure. On current master, iio.mimread(b"...", format="ffmpeg") will happily load the video, assuming that b"..." is indeed a byte string containing a valid video. This is because using format=... with the old FormatManager will skip the can_read check.

In this PR iio.mimread(b"...", format="ffmpeg") will raise a ValueError (I think that's the legacy exception type here), because imopen will handle the call itself instead of delegating to FormatManager. imopen will use a LegacyPlugin that wraps the v2 ffmpeg format/plugin and that provides compatibility. In v3 the ability to handle a request is tested during plugin initialization (Plugin.__init__ may fail with a InitializationError), and LegacyPlugin does this by calling the wrapped plugin's can_read/can_write functions. This causes problems for ffmpeg, because its can_read decides purely based on the file extension and hence returns False for b"..." (extension is None).

I currently see no trivial way around this, and the correct way to resolve it is to make ffmpeg._can_read more sophisticated and/or port the ffmpeg plugin into a V3 plugin. The latter is already on the TODO list, so I was thinking to clean all that up in one go.

@almarklein almarklein mentioned this pull request Nov 17, 2021
@almarklein

Copy link
Copy Markdown
Member

Ok, seems like very much an edge case to me, and we can probably live with that regression temporarily.

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

@almarklein Okay looks like we agree on all the open points. Anything else to add or should we merge once the tests pass?

(They currently beak because of a merge conflict with master. We introduced tifffile as a test dependency and I need to track down why that did not update for the CI runners.)

@huangxin168

Copy link
Copy Markdown

I failed to use Nuitka to pack imageio with 'pyav' plugin,
I saw pyinstaller sulution in imageio doc, is it possible for Nuitka?

@FirefoxMetzger

Copy link
Copy Markdown
Contributor Author

@huangxin168 I have never used Nuitka myself. That said, based on my brief google search it will discover files to include by scanning the source for import statements. This doesn't work for dynamic imports, however, and the docs suggest to use --include-plugin-directory to manually include a folder. I suspect that you can use that option to include ImageIO and all its plugins (which are dynamically imported) to make this work.

Since Nuitka also acts as a compiler, another point to investigate is how it interacts with C extensions. This is because pyav is a cython project, which means that some of its modules are actually compiled C-code, which may or may not cause problems depending on how smart Nuitka is.

@huangxin168

Copy link
Copy Markdown

@FirefoxMetzger I tried --include-plugin-directory, unfortunately the same. Thank you for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

4 participants