SwiftWhisper icon indicating copy to clipboard operation
SwiftWhisper copied to clipboard

crash when initializing with an invalid model

Open zaphoyd opened this issue 1 year ago • 4 comments

When Whisper.init(fromFileURL) is called with a file URL that is a file that exists, but not a valid model file, the error condition from the underlying whisper.cpp library is not handled.

Specifically: self.whisperContext = fileURL.relativePath.withCString { whisper_init_from_file($0) }

whisper_init_from_file will return nullptr in this case. The attempted assignment produces the following error which crashes the program using the library.

whisper_init_from_file_no_state: loading model from '.'
whisper_model_load: loading model
whisper_model_load: invalid model data (bad magic)
whisper_init_no_state: failed to load model
SwiftWhisper/Whisper.swift:16: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I'd like to add a check to this initializer so my program can catch and safely handle this case. In theory, my program could attempt to figure out if this was a valid model file, but this would involve re-implementing the detection code from whisper.cpp that I am trying to wrap. Letting that code that is already doing the error handling just pass the error through seems like a better arrangement.

Doing so would probably require changing the init signature to a throwing one or a fail-able one. I understand that this would involve a change in API here. Is there a way to handle this that would be likely to be accepted as a PR? Is there a more general plan for how to handle this sort of error case?

zaphoyd avatar Aug 29 '23 21:08 zaphoyd