PyObjC CoreML Framework

12.1 · active · verified Sun Apr 12

PyObjC-framework-CoreML provides Python wrappers for Apple's CoreML framework on macOS, enabling Python applications to interact with Core ML models. It is part of the larger PyObjC project, which creates a bridge between Python and Objective-C, and is actively maintained with releases often aligned with macOS updates. The current version is 12.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import the `CoreML` framework and attempt to load an `MLModel` using PyObjC. It highlights the typical PyObjC pattern for handling Objective-C methods that return errors by reference. A functional example would require an actual `.mlmodel` file.

import CoreML
import Foundation # Often needed for NSURL, NSBundle etc.
import os

# --- This example demonstrates attempting to load a CoreML model ---
# In a real scenario, 'your_model.mlmodel' would be a path to an actual Core ML model file.
# For demonstration, we'll try a dummy path or look for a model in the app bundle.
# Replace with the actual path to your .mlmodel file or ensure it's in your app bundle.

# Option 1: Direct path (replace with actual path)
model_path = os.environ.get('COREML_MODEL_PATH', '/tmp/your_model.mlmodel')

# Option 2: Attempt to find in the main bundle (common for macOS apps)
# mainBundle = Foundation.NSBundle.mainBundle()
# model_path_from_bundle = mainBundle.pathForResource_ofType_("YourModelName", "mlmodel")
# if model_path_from_bundle:
#     model_path = model_path_from_bundle

print(f"Attempting to load CoreML model from: {model_path}")

try:
    # CoreML methods often follow Objective-C conventions, e.g., 'methodName_error_'
    # for methods that take an NSError** parameter in Objective-C.
    # The PyObjC bridge translates this into a tuple (result, error_object).
    model, error = CoreML.MLModel.modelWithContentsOfURL_error_( 
        Foundation.NSURL.fileURLWithPath_(model_path), None
    )
    
    if error:
        print(f"Error loading model: {error.localizedDescription()}")
    elif model:
        print(f"Successfully loaded CoreML model: {model}")
        print(f"Model description: {model.modelDescription()}")
        # You can now interact with the model, e.g., for predictions:
        # input_features = CoreML.MLFeatureProvider.alloc().init()
        # prediction, pred_error = model.predictionFromFeatures_error_(input_features, None)
        # if not pred_error: print(f"Prediction: {prediction}")
    else:
        print("Failed to load model without explicit error or model object.")

except Exception as e:
    print(f"An unexpected Python exception occurred: {e}")

print(f"\nAccessing MLModel class directly: {CoreML.MLModel}")

view raw JSON →