cloudinaryanalysis

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 9, 2025 License: MIT Imports: 12 Imported by: 0

README

Cloudinary Analysis Go SDK

Summary

Analyze API (Beta): Use the Analyze API to analyze any external asset and return details based on the type of analysis requested.

Currently supports the following analysis options:

Notes:

  • The Analyze API is currently in development and is available as a Public Beta, which means we value your feedback, so please feel free to share any thoughts with us.
  • The analysis options require an active subscription to the relevant add-on. Learn more about registering for add-ons.

The API supports both Basic Authentication using your Cloudinary API Key and API Secret (which can be found on the Dashboard page of your Cloudinary Console) or OAuth2 (Contact support for more information regarding OAuth).

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/cloudinary/analysis-go/cloudinaryanalysis

SDK Example Usage

Example
package main

import (
	"context"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.AnalyzeAIVisionGeneralResponse != nil {
		// handle response
	}
}

Server Selection

Server Variables

The default server https://api.cloudinary.com/v2/analysis/{cloud_name} contains variables and is set to https://api.cloudinary.com/v2/analysis/CLOUD_NAME by default. To override default values, the following options are available when initializing the SDK client instance:

  • WithCloudName(cloudName string)
Override Server URL Per-Client

The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:

package main

import (
	"context"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithServerURL("https://api.cloudinary.com/v2/analysis/CLOUD_NAME"),
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.AnalyzeAIVisionGeneralResponse != nil {
		// handle response
	}
}

Authentication

Per-Client Security Schemes

This SDK supports the following security schemes globally:

Name Type Scheme
CloudinaryAuth http Custom HTTP
OAuth2 oauth2 OAuth2 token

You can set the security parameters through the WithSecurity option when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:

package main

import (
	"context"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.AnalyzeAIVisionGeneralResponse != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
Analyze
Tasks

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:

package main

import (
	"context"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/retry"
	"log"
	"models/operations"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	}, operations.WithRetries(
		retry.Config{
			Strategy: "backoff",
			Backoff: &retry.BackoffStrategy{
				InitialInterval: 1,
				MaxInterval:     50,
				Exponent:        1.1,
				MaxElapsedTime:  100,
			},
			RetryConnectionErrors: false,
		}))
	if err != nil {
		log.Fatal(err)
	}
	if res.AnalyzeAIVisionGeneralResponse != nil {
		// handle response
	}
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:

package main

import (
	"context"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/retry"
	"log"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.AnalyzeAIVisionGeneralResponse != nil {
		// handle response
	}
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.

By Default, an API error will return apierrors.APIError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.

For example, the AiVisionGeneral function may return the following errors:

Error Type Status Code Content Type
apierrors.ErrorResponse 400, 401, 403, 404 application/json
apierrors.RateLimitedResponse 429 application/json
apierrors.ErrorResponse 500 application/json
apierrors.APIError 4XX, 5XX */*
Example
package main

import (
	"context"
	"errors"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/apierrors"
	"github.com/cloudinary/analysis-go/cloudinaryanalysis/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := cloudinaryanalysis.New(
		cloudinaryanalysis.WithSecurity(components.Security{
			CloudinaryAuth: &components.SchemeCloudinaryAuth{
				APIKey:    "CLOUDINARY_API_KEY",
				APISecret: "CLOUDINARY_API_SECRET",
			},
		}),
	)

	res, err := s.Analyze.AiVisionGeneral(ctx, components.AnalyzeAIVisionGeneralRequest{
		Source: components.CreateSourceURI(
			components.URI{
				URI: "https://res.cloudinary.com/demo/image/upload/sample.jpg",
			},
		),
		Prompts: []string{
			"Describe this image in detail",
			"Does this image contain an insect?",
		},
	})
	if err != nil {

		var e *apierrors.ErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.RateLimitedResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.ErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.APIError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"
	"github.com/myorg/your-go-sdk"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = sdk.New(sdk.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerList = []string{
	"https://api.cloudinary.com/v2/analysis/{cloud_name}",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Analyze

type Analyze struct {
	// contains filtered or unexported fields
}

Analyze - Use the Analyze API to analyze any external asset and return details based on the type of analysis requested.

func (*Analyze) AiVisionGeneral

AiVisionGeneral - Analyze - AI Vision General The General mode serves a wide array of applications by providing detailed answers to diverse questions about an image. Users can inquire about any aspect of an image, such as identifying objects, understanding scenes, or interpreting text within the image.

func (*Analyze) AiVisionModeration

AiVisionModeration - Analyze - AI Vision Moderation The Moderation mode accepts multiple questions about an image, to which the response provides concise answers of "yes," "no," or "unknown." This functionality allows for a nuanced evaluation of whether the image adheres to specific content policies, creative specs, or aesthetic criteria.

func (*Analyze) AiVisionTagging

AiVisionTagging - Analyze - AI Vision Tagging The Tagging mode accepts a list of tag names along with their corresponding descriptions. If the image matches the description, which may encompass various elements, it will be appropriately tagged. This approach enables customers to align with their own brand taxonomy, offering a dynamic, flexible, and open method for image classification.

func (*Analyze) Captioning

Captioning - Analyze - Captioning Provides a caption for an image.

func (*Analyze) CldFashion

CldFashion - Analyze - Cld-Fashion Analyze an image using the [Cld-Fashion](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. Cloudinary's fashion model is specifically dedicated to items of clothing. The response includes attributes of the clothing identified, for example whether the garment contains pockets, its material and the fastenings used.

func (*Analyze) CldText

CldText - Analyze - Cld-Text Analyze an image using the [Cld-Text](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. Cloudinary's text model tells you if your image includes text, and where it's located. Used with image tagging, you can then search for images that contain blocks of text. Used with object-aware cropping, you can choose to keep only the text part, or specify a crop that avoids the text.

func (*Analyze) Coco

Coco - Analyze - Coco Analyze an image using the [Coco](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. The [Common Objects in Context](https://cocodataset.org/) model contains just 80 common objects.

func (*Analyze) GoogleLogoDetection

GoogleLogoDetection - Analyze - Google Logo Detection Detects popular product logos within an image.

func (*Analyze) GoogleTagging

GoogleTagging - Analyze - Google Tagging Provides tags for an image using Google's tagging service.

func (*Analyze) HumanAnatomy

HumanAnatomy - Analyze - Human Anatomy Analyze an image using the [Human Anatomy](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. Cloudinary's human anatomy model identifies parts of the human body in an image. It works best when the majority of a human body is detected in the image.

func (*Analyze) ImageQuality

ImageQuality - Analyze - Image Quality Analysis Analyze an image using the [Image Quality Analysis](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#image_quality_analysis) model.

func (*Analyze) Lvis

Lvis - Analyze - Lvis Analyze an image using the [Lvis](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. The [Large Vocabulary Instance Segmentation](https://www.lvisdataset.org/) model contains thousands of general objects.

func (*Analyze) ShopClassifier

ShopClassifier - Analyze - Shop Classifier Analyze an image using the [Shop Classifier](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. Cloudinary's shop classifier model detects if the image is a product image taken in a studio, or if it's a natural image.

func (*Analyze) Unidet

Unidet - Analyze - Unidet Analyze an image using the [Unidet](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#ai_based_image_captioning) content-aware detection model. The [UniDet](https://github.com/xingyizhou/UniDet) model is a unified model, combining a number of object models, including [Objects365](https://www.objects365.org/overview.html), which focuses on diverse objects in the wild.

func (*Analyze) WatermarkDetection

WatermarkDetection - Analyze - Watermark Detection Analyze an image using the [Watermark Detection](https://cloudinary.com/documentation/cloudinary_ai_content_analysis_addon#watermark_detection) detection model.

type CloudinaryAnalysis

type CloudinaryAnalysis struct {
	// Use the Analyze API to analyze any external asset and return details based on the type of analysis requested.
	Analyze *Analyze
	// Query the status of analysis tasks.
	Tasks *Tasks
	// contains filtered or unexported fields
}

CloudinaryAnalysis - Analyze API (Beta): Use the Analyze API to analyze any external asset and return details based on the type of analysis requested.

Currently supports the following analysis options:

func New

func New(opts ...SDKOption) *CloudinaryAnalysis

New creates a new instance of the SDK with the provided options

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for suplying the SDK with a custom HTTP client

type SDKOption

type SDKOption func(*CloudinaryAnalysis)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithCloudName

func WithCloudName(cloudName string) SDKOption

WithCloudName allows setting the cloud_name variable for url substitution

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(security components.Security) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServerIndex

func WithServerIndex(serverIndex int) SDKOption

WithServerIndex allows the overriding of the default server by index

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

type Tasks

type Tasks struct {
	// contains filtered or unexported fields
}

Tasks - Query the status of analysis tasks.

func (*Tasks) GetStatus

GetStatus - Get analysis task status Get the status of an analysis task.

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL