Skip to content

Add support for CoreML model generation #1676

Open
@cgrindel

Description

@cgrindel

Original Slack thread

I’m working on adding a local package that’s currently using SPM into Bazel. The package contains some CoreML models that SPM has special handling for to generate Swift interfaces for automatically. I looked into using swift_apple_core_ml_library from rules_apple to generate the needed files, but that creates a separate Swift library for each model and I’d like to keep the current structure where the models are within the main package and don’t require a dedicated import statement for each generated Swift file.
To that end I’ve written this, which I get the impression probably isn’t great practice, but I was curious how discouraged it is and if there’s a better approach.

    # Handle any CoreML models by including them as data and generating new Swift source files
    coreml_models = native.glob(["{}/**/*.mlmodel".format(path)])
    for model in coreml_models:
        # Get model filename without extension
        name = paths.replace_extension(paths.basename(model), "")
        # 'coreml generate` outputs to <model_name>.swift
        output_src = ":{}.swift".format(name)

        native.genrule(
            name = name,
            srcs = [model],
            outs = [output_src],
            cmd = "xcrun coremlc generate --public-access --language Swift $(locations {}) $(@D)".format(model)
        )

        srcs.append(output_src)
        data.append(model)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions