Downloading tflite models from server rather than using the models from assets folder in Swift

Viewed 278

I have seen tensorflow lite examples for iOS and they resides in the assets folder. We have some model on the server that I want to download and keep on document directory and use.

Here is how I download and save the model to the document directory.

class ModelFileManager {

  let folderRoute = "Models"

  func saveModel(with file: String, data: Data, extension fileExtension: String) {
      let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)

      if !FileManager.default.fileExists(atPath: documentsDirectory.path) {
          do {
              try FileManager.default.createDirectory(atPath: documentsDirectory.path, withIntermediateDirectories: true, attributes: nil)
          } catch {
              print(error)
          }
      }

      let fileURL = documentsDirectory.appendingPathComponent("\(file).\(fileExtension)", isDirectory: false)

      do {
          try data.write(to: fileURL)
          print("File save at \(fileURL.absoluteString)")
      } catch {
          print("File can't not be save at path \(fileURL.absoluteString), with error : \(error)");
      }
  }

  func fetchModel(for name: String) -> String {
      let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)
      let fileURL = documentsDirectory.appendingPathComponent("\(name)", isDirectory: false)
      return fileURL.absoluteString
  }
}

So when I give the path of the file to the Interpreter, it says

The model is not a valid Flatbuffer file
Failed to create the interpreter with error: Failed to load the given model.
1 Answers

I solved this by replacing the file:/// with empty string from absoluteString

func fetchModel(for name: String) -> String {
  let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)
  let fileURL = documentsDirectory.appendingPathComponent("\(name)", isDirectory: false)
  return fileURL.absoluteString.replacingOccurrences(of: "file:///", with: "")
}
Related