Clarifai gRPC API Client

12.3.0 · active · verified Tue Apr 14

The official Clarifai gRPC Python client provides an interface for interacting with the Clarifai API, offering powerful AI capabilities for computer vision and natural language processing. Currently at version 12.3.0, the library maintains a frequent release cadence, often aligning its major and minor versions with the backend API.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Clarifai gRPC client using a Personal Access Token (PAT) and make a prediction on an image URL. It retrieves the PAT and Application ID from environment variables, which is the recommended authentication method. Remember to replace 'YOUR_USER_ID' and 'YOUR_CLARIFAI_APP_ID' with your actual Clarifai credentials if not set as environment variables.

import os

from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2

# Your Clarifai PAT (Personal Access Token) and Application ID
CLARIFAI_PAT = os.environ.get('CLARIFAI_PAT', '')
CLARIFAI_APP_ID = os.environ.get('CLARIFAI_APP_ID', 'YOUR_CLARIFAI_APP_ID')

# Initialize the gRPC client
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)

metadata = (('authorization', 'Key ' + CLARIFAI_PAT),)
userDataObject = resources_pb2.UserAppIDSet(user_id='YOUR_USER_ID', app_id=CLARIFAI_APP_ID)

# Example: Predict concepts in an image URL
image_url = 'https://samples.clarifai.com/metro-north.jpg'

post_model_outputs_response = stub.PostModelOutputs(
    service_pb2.PostModelOutputsRequest(
        # You can use your own model ID or a public one like 'general-image-recognition'
        model_id='general-image-recognition',
        user_app_id=userDataObject,
        inputs=[
            resources_pb2.Input(
                data=resources_pb2.Data(
                    image=resources_pb2.Image(url=image_url)
                )
            )
        ]
    ),
    metadata=metadata
)

if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
    raise Exception(
        f"Post model outputs failed, status: {post_model_outputs_response.status.description}"
    )

# Print the results
print('Predicted concepts:')
for concept in post_model_outputs_response.outputs[0].data.concepts:
    print(f"{concept.name}: {concept.value:.4f}")

view raw JSON →