glair

package module
v0.0.1-beta.5 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 4 Imported by: 0

README

GLAIR

GLAIR Vision Go SDK

License

Requirement

  • Go 1.18 or later with Go modules.

Installation

You can import the SDK in your Go files with import:

import (
    "github.com/glair-ai/glair-vision-go"
    "github.com/glair-ai/glair-vision-go/client"
)

After that, you can run go commands and let the Go toolchain resolve and fetch the SDK module automatically.

Alternatively, you can also run go get to explicitly resolve and fetch the SDK module:

go get -u github.com/glair-ai/glair-vision-go

Usage

The package needs to be configured with your credentials, see here for more detailed instructions

package main

import (
    "github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

func main() {
    config := glair.NewConfig("<username>", "<password>", "<api_key>")

    client := client.New(config)
}

The configuration object will be initialized with the following values:

Option Default Description
BaseUrl https://api.vision.glair.ai Base URL for GLAIR Vision API
ApiVersion v1 GLAIR Vision API version to be used
Client Default Go HTTP client HTTP Client to be used when sending request to GLAIR Vision API
Logger LeveledLogger with LevelNone Logger instace to be used to log errors, information, or debugging messages

You can change the above values using the provided With<Option> method of the configuration object, for example:

package main

import (
    "github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

func main() {
    config := glair.NewConfig("<username>", "<password>", "<api_key>")
    // set the base url to `http://localhost:3000` 
    config = config.WithBaseURL("http://localhost:3000")

    client := client.New(config)
}

Afterwards, you can use the provided functions to access GLAIR Vision API.

Documentation

For comprehensive list of available API provided by GLAIR Vision Go SDK, check out the API Documentation. You can also see the runnable examples in the examples folder. For details on all the functionality in this library, see the Go documentation.

Below are a few simple usage examples:

Perform OCR on KTP

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

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

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	file, _ := os.Open("path/to/image.jpg")

	result, err := client.Ocr.KTP(ctx, glair.OCRInput{
		Image: file,
	})

	if err != nil {
		log.Fatalln(err.Error())
	}

  	fmt.Println(result.Read.Nama)
}

Perform OCR on Receipt by providing path to the image file

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

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

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	result, err := client.Ocr.Receipt(ctx, glair.OCRInput{
		Image: "path/to/image.jpg",
	})

	if err != nil {
		log.Fatalln(err.Error())
	}

  	fmt.Println(result.Read.Nama)
}

Perform OCR on KTP with timeout

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

func main() {
	baseContext := context.Background()
	contextWithTimeout, cancel := context.WithTimeout(baseContext, 100*time.Millisecond)
	defer cancel()

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	file, _ := os.Open("../images/ktp.jpeg")

	result, err := client.Ocr.KTP(contextWithTimeout, glair.OCRInput{
		Image: file,
	})

	if err != nil {
		if glairErr, ok := err.(*glair.Error); ok {
			switch glairErr.Code {
			case glair.ErrorCodeTimeout:
				log.Printf("Request timed out")
			default:
				log.Printf("Error: %v\n", glairErr.Code)
			}
		} else {
			log.Printf("Unexpected Error: %v\n", err)
		}

		os.Exit(1)
	}

	beautified, _ := json.MarshalIndent(result, "", "  ")

	fmt.Println(string(beautified))
}

Using custom HTTP client to intercept HTTP requests

package client

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/glair-ai/glair-vision-go"
)

// MyClient is a HTTP client that adds `x-powered-by`
// header to a normal HTTP request.
//
// It wraps the default HTTP client
type MyClient struct {
	client *http.Client
}

func (c *MyClient) Do(req *http.Request) (*http.Response, error) {
	req.Header.Set("X-Powered-By", "GLAIR")

	res, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}

	return res, nil
}

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

	config := glair.NewConfig("", "", "").WithClient(&MyClient{client: http.DefaultClient})
	client := New(config)

	file, _ := os.Open("../images/ktp.jpeg")

	result, err := client.Ocr.KTP(ctx, glair.OCRInput{
		Image: file,
	})

	if err != nil {
		log.Fatalln(err.Error())
	}

	beautified, _ := json.MarshalIndent(result, "", "  ")

	fmt.Println(string(beautified))
}

Perform face verification using GLAIR Vision Face Verification API

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

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

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	image, _ := os.Open("path/to/image.jpg")

	result, err := client.FaceBio.FaceMatching(ctx, glair.FaceMatchingInput{
		StoredImage:   image,
		CapturedImage: image,
	})

	if err != nil {
		log.Fatalln(err.Error())
	}

	beautified, _ := json.MarshalIndent(result, "", "  ")

	fmt.Println(string(beautified))
}

Perform KTP data verification using GLAIR Identity Verification API

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

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

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	result, err := client.Identity.BasicVerification(ctx, glair.BasicVerificationInput{
		Nik:    "",
		Name:   glair.String(""),
		Gender: glair.String(""),
		DateOfBirth: ""
	})

	if err != nil {
		log.Fatalln(err.Error())
	}

	beautified, _ := json.MarshalIndent(result, "", "  ")

	fmt.Println(string(beautified))
}

Error Handling

Whenever an error occurs, GLAIR Vision Go SDK will wrap the error into a glair.Error object that contains the following properties

Property Type Description
Code ErrorCode Unique identifier that distinguish errors
Message string Human-readable error message. Contains basic information of error cause
Err error The original error object returned by the SDK
Response Response GLAIR Vision API response body. Only available if the request has been successfully sent the GLAIR Vision API

It's recommended to assert the error to glair.Error whenever an error is returned, for example:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

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

	config := glair.NewConfig("", "", "")
	client := client.New(config)

	file, _ := os.Open("path/to/image.jpg")

	result, err := client.Ocr.KTP(ctx, glair.OCRInput{
		Image: file,
	})

	if err != nil {
    		// is a glair.Error, assert the error code
	  	if glairErr, ok := err.(*glair.Error); ok {
      		switch glairErr.Code {
        		case glair.ErrorCodeFileError:
          			fmt.Println("Cannot read input file correctly")
        		case glair.ErrorCodeNetworkError:
          			fmt.Println("There are problems while connecting to GLAIR Vision API")
        		default:
          			fmt.Printf("GLAIR SDK returns error code: %d", glairErr.Code)
      			}
    		} else {
      			fmt.Printf("Unexpected error occured: %w", err)
    		}
	}
}

Error Code

To make debugging errors easier, GLAIR Vision Go SDK provides error code to all glair.Error objects. Below are the list of error codes that are returned by GLAIR Vision Go SDK

Error Code Reason
ErrorCodeFileError The SDK encounters an error when processing the image file. It's possible that the file doesn't exist, the SDK cannot access the file from the given path, or the file is corrupted. This code also returned when incorrect representation of file is provided.
ErrorCodeNetworkError The SDK fails to complete the HTTP request with the given HTTP client
ErrorCodeTimeout The network request sent by the SDK has timed out. This error is fixable by increasing the request timeout duration or by completely removing the timeout from the context
ErrorCodeForbidden The SDK attempts to access an API endpoint with insufficient credentials. Please contact us if you think that this is a mistake
ErrorCodeAPIError GLAIR Vision API returns a non-OK response. Please inspect the Response object for more detailed explanation if this code is returned
ErrorCodeInvalidResponse GLAIR Vision API returns an unexpected response. Please contact us if you receive this error code

Response

When error with code ErrorCodeAPIError is returned, GLAIR Vision SDK with return additional context of the failure encapsulated in the Response object. The Response object has the following properties.

Property Description
Code HTTP Status code returned by GLAIR Vision API
Body Raw response body returned by GLAIR Vision API

Logging

By default, GLAIR Vision Go SDK does not log anything regardless of severity. However, you can enable logging implementing the Logger interface from the main package and add it to the configuration object with WithLogger method.

package main

import (
	"fmt"

	"github.com/glair-ai/glair-vision-go"
	"github.com/glair-ai/glair-vision-go/client"
)

type MyLogger struct {}

func (l MyLogger) Debugf(format string, val ...interface{}) {
	// do not log debug messages
}

func (l MyLogger) Infof(format string, val ...interface{}) {
	fmt.Printf("[GLAIR - Information] " + format, val)
}

func (l MyLogger) Warnf(format string, val ...interface{}) {
	fmt.Printf("[GLAIR - Warning] " + format, val)
}

func (l MyLogger) Errorf(format string, val ...interface{}) {
	fmt.Printf("[GLAIR - Debug] " + format, val)
}

func main() {
	config := glair.NewConfig("<username>", "<password>", "<api_key>").
		WithLogger(MyLogger{})
}

The Logger interface has the following signature

type Logger interface {
	Debugf(format string, val ...interface{})
	Infof(format string, val ...interface{})
	Warnf(format string, val ...interface{})
	Errorf(format string, val ...interface{})
}

Alternatively, the SDK provides convenient LeveledLogger struct that implements the Logger interface.

type LeveledLogger struct {
	Level LogLevel
}

LeveledLogger accepts Level property that determines what messages should be logged. Below is the list of available Level for LeveledLogger

Level Value Description
LevelNone 0 Do not log anything
LevelError 1 Log all error messages and output them to stderr
LevelWarn 2 Log all warning messages and output them to stdout
LevelInfo 3 Log all informational messages and output them to stdout
LevelDebug 4 Log all debugging messages and output them to stdout

All Level property also logs any messages below their Level. For example, LeveledLogger with LevelInfo will log informational, warnings, and error messages.

License

This project is licensed under the MIT License

Documentation

Overview

Package glair provides common objects that can be used across all GLAIR Vision Go SDK packages

This package serves as the entrypoint to interact with the GLAIR Vision SDK

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Int

func Int(num int) *int

Int is an utility function to convert integers to its pointer variants

Useful for filling out optional fields

func String

func String(str string) *string

String is an utility function to convert strings to its pointer variants

Useful for filling out optional fields

Types

type ActiveLivenessInput

type ActiveLivenessInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Image represents the input image that will be processed by GLAIR
	// Vision Face Matching API.
	//
	// Image must be provided as a string that represents a path to the
	// image or an object that implements *os.Image
	Image interface{}
	// GestureCode represents gesture idenfification code that will
	// be used to determine which gesture should be used to detect
	// liveness from the image.
	//
	// Please refer to https://docs.glair.ai/vision/active-liveness
	// for the list of all supported gesture codes
	GestureCode string
}

ActiveLivenessInput stores parameters for active liveness requests

type BPKBInput

type BPKBInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Image represents the input image that will be processed by GLAIR
	// Vision OCR API.
	//
	// Image must be provided as a string that represents a path to the
	// image or an object that implements *os.Image
	Image interface{}
	// Page represents specific page number to be read from the BPKB
	// image file. If this argument is omitted, the API will read
	// all pages.
	//
	// Page is optional
	Page *int
}

BPKBInput stores parameters for BPKB requests

type BasicVerificationInput

type BasicVerificationInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Nik represents single identification number of the
	// person to be verified
	Nik string
	// Name represents the name of the person to be verified
	//
	// Name is optional
	Name *string
	// DateOfBirth represents date of birth of the person to
	// be verified
	//
	// DateOfBirth must be provided as a time.Time instance
	// or as a string in dd-mm-yyyy format
	//
	// DateOfBirth is optional
	DateOfBirth interface{}
	// NoKk represents family registration number of the person
	//
	// NoKk is optional
	NoKk *string
	// MotherMaidenName represents identity holder's mother
	// maiden name
	//
	// MotherMaidenName is optional
	MotherMaidenName *string
	// PlaceOfBirth represents place of birth of the identity holder
	// in their KTP
	//
	// PlaceOfBirth is optional
	PlaceOfBirth *string
	// Address represents address of the identity holder
	// in their KTP
	//
	// Address is optional
	Address *string
	// Gender represents gender of the identity holder
	// in their KTP
	//
	// Gender is optional
	Gender *string
	// MaritalStatus represents marital status of the identity holder
	// in their KTP
	//
	// MaritalStatus is optional
	MaritalStatus *string
	// JobType represents job of the identity holder
	// in their KTP
	//
	// JobType is optional
	JobType *string
	// Province represents the province of residence of the identity holder
	// in their KTP
	//
	// Province is optional
	Province *string
	// City represents the city of residence of the identity holder
	// in their KTP
	//
	// City is optional
	City *string
	// District represents the district of residence of the identity holder
	// in their KTP
	//
	// District is optional
	District *string
	// Subdistrict represents the subdistrict of residence of the identity holder
	// in their KTP
	//
	// Subdistrict is optional
	Subdistrict *string
	// Rt represents the RT of residence of the identity holder
	// in their KTP
	//
	// Rt is optional
	Rt *string
	// Rw represents the RW of residence of the identity holder
	// in their KTP
	//
	// Rw is optional
	Rw *string
}

BasicVerificationInput stores parameters for basic identity verification request

type Config

type Config struct {
	// Username represents username to be used for basic authentication
	// with GLAIR Vision API
	Username string
	// Password represents password to be used for basic authentication
	// with GLAIR Vision API
	Password string
	// API key represents API key to be used for authentication
	// with GLAIR Vision API
	ApiKey string

	// BaseUrl represents base URL path for GLAIR Vision API
	// endpoints. Defaults to "https://api.vision.glair.ai"
	BaseUrl string
	// ApiVersion represents GLAIR Vision API version to
	// be called. Defaults to "v1"
	ApiVersion string

	// Client represents the HTTP client that is used
	// to call the HTTP endpoints of GLAIR Vision API.
	// Defaults to the default HTTP client of Go
	Client HTTPClient

	// Logger represents the logger to be used by
	// GLAIR Vision Go SDK to log necessary informations.
	// Defaults to no log
	Logger Logger
}

Config provides configuration for a client instance, including credentials and API configuration such as base URL and API version.

func NewConfig

func NewConfig(username string, password string, apiKey string) *Config

NewConfig creates a new configuration object with default values for base URL and API Version.

func (*Config) GetEndpointURL

func (c *Config) GetEndpointURL(
	service string,
	endpoint string,
) string

GetEndpointURL creates service URL with base URL and API version

func (*Config) WithBaseURL

func (c *Config) WithBaseURL(url string) *Config

WithBaseURL sets base API URL for the configuration object

func (*Config) WithClient

func (c *Config) WithClient(client HTTPClient) *Config

WithClient sets HTTP client for the configuration object that will be used for calling GLAIR Vision API endpoints

func (*Config) WithCredentials

func (c *Config) WithCredentials(
	username string,
	password string,
	apiKey string,
) *Config

WithCredentials sets user credentials for the configuration object

func (*Config) WithLogger

func (c *Config) WithLogger(logger Logger) *Config

WithLogger sets the logger to be used by client instances

func (*Config) WithVersion

func (c *Config) WithVersion(version string) *Config

WithVersion sets API version for the configuration object

type Error

type Error struct {
	// Code represents unique code to quickly distinguish errors from
	// GLAIR Vision SDK
	Code ErrorCode
	// Message represents human-readable error object related
	// to the error
	Message string
	// Err is the original error object that is returned by the SDK
	Err error

	// Response represents response returned by GLAIR Vision API
	// if response is available
	Response Response
}

Error is an extended error object used by GLAIR Vision SDK

Whenever error is returned, it is recommended to assert the error to this type

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string

ErrorCode is unique code to quickly distinguish errors from GLAIR Vision SDK

const (
	// ErrorCodeFileError is returned when the SDK fails
	// to read or parse the given input file
	ErrorCodeFileError ErrorCode = "FILE_ERROR"
	// ErrorCodeNetworkError is returned when the SDK is unable to
	// complete the HTTP request to GLAIR Vision API with the given
	// HTTP client
	ErrorCodeNetworkError ErrorCode = "NETWORK_ERROR"
	// ErrorCodeTimeout is returned when the HTTP request sent
	// by the SDK has timed out
	//
	// To solve this problem, you can increase the timeout
	// value from the context or remove the timeout entirely
	ErrorCodeTimeout ErrorCode = "TIMEOUT"
	// ErrorCodeForbidden is returned when the provided credentials
	// have insufficient access rights to the requested endpoint
	//
	// If you think this is a mistake, please contact us
	ErrorCodeForbidden ErrorCode = "FORBIDDEN"
	// ErrorCodeAPIError is returned when GLAIR Vision API
	// returns a non-OK response. In this case, please
	// check the Body property for more details on the error
	ErrorCodeAPIError ErrorCode = "API_ERROR"
	// ErrorCodeInvalidResponse is returned when GLAIR Vision API
	// returns an unexpected response
	//
	// Generally, this error is impossible to be returned.
	// If you encounter this error, please contact us
	ErrorCodeInvalidResponse ErrorCode = "INVALID_RESPONSE"
)

type FaceMatchingInput

type FaceMatchingInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// StoredImage represents the stored image that will be used
	// as a base for face matching
	//
	// StoredImage must be provided as a string that represents a path to the
	// image or an object that implements *os.File
	StoredImage interface{}
	// CapturedImage represents the captured image that will be compared
	// to the stored image.
	//
	// CapturedImage must be provided as a string that represents a path to the
	// image or an object that implements *os.File
	CapturedImage interface{}
}

OCRInput stores parameters for Face Matching request

type FaceVerificationInput

type FaceVerificationInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Nik represents single identification number of the
	// person to be verified
	Nik string
	// FaceImage represents the input image that will be used
	// to verify the identity of the identity card
	//
	// FaceImage must be provided as a string that represents a path to the
	// image or an object that implements *os.File
	FaceImage interface{}
	// Name represents the name of the person to be verified
	Name string
	// DateOfBirth represents date of birth of the person to
	// be verified
	//
	// DateOfBirth must be provided as a string with dd-mm-yyyy
	// format or as an instance of *time.Time
	DateOfBirth interface{}
}

FaceVerificationInput stores parameters for identity verification request with face

type HTTPClient

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

HTTPClient is an interface that users can implement to customize HTTP calls behavior when interacting with GLAIR Vision API

type LeveledLogger

type LeveledLogger struct {
	Level LogLevel
}

LeveledLogger represents logger instance that will be used by GLAIR Vision Go SDK

func (*LeveledLogger) Debugf

func (l *LeveledLogger) Debugf(format string, val ...interface{})

func (*LeveledLogger) Errorf

func (l *LeveledLogger) Errorf(format string, val ...interface{})

func (*LeveledLogger) Infof

func (l *LeveledLogger) Infof(format string, val ...interface{})

func (*LeveledLogger) Warnf

func (l *LeveledLogger) Warnf(format string, val ...interface{})

type LogLevel

type LogLevel int

LogLevel represents logging level of GLAIR Vision SDK

const (
	// LevelNone sets the logger to disables logging entirely
	LevelNone LogLevel = 0
	// LevelError sets the logger to show only error messages
	LevelError LogLevel = 1
	// LevelWarn sets the logger to show warning and error messages
	LevelWarn LogLevel = 2
	// LevelInfo sets the logger to show information, warning, and error messages
	LevelInfo LogLevel = 3
	// LevelDebug sets the logger to display any messages, including debugging statements
	LevelDebug LogLevel = 4
)

type Logger

type Logger interface {
	// Debugf prints debug message with the provided format to stdout
	Debugf(format string, val ...interface{})
	// Infof prints informational message with the provided format to stdout
	Infof(format string, val ...interface{})
	// Warnf prints warning message with the provided format to stdout
	Warnf(format string, val ...interface{})
	// Errorf prints error message with the provided format to stderr
	Errorf(format string, val ...interface{})
}

Logger represents base contract for logging functionalities

type OCRInput

type OCRInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Image represents the input image that will be processed by GLAIR
	// Vision OCR API.
	//
	// Image must be provided as a string that represents a path to the
	// image or an object that implements *os.Image
	Image interface{}
}

OCRInput stores parameters for OCR requests

type PassiveLivenessInput

type PassiveLivenessInput struct {
	// RequestID represents request identifier for debugging purposes
	RequestID string
	// Image represents the input image that will be processed by GLAIR
	// Vision Face Matching API.
	//
	// Image must be provided as a string that represents a path to the
	// image or an object that implements *os.Image
	Image interface{}
}

PassiveLivenessInput stores parameters for passive liveness requests

type Response

type Response struct {
	Status int                    `json:"status,omitempty"`
	Body   map[string]interface{} `json:"body"`
}

Response represents the response returned by GLAIR Vision API if request returned an error

type Session

type Session struct {
	Status     string `json:"status"`
	SuccessURL string `json:"success_url"`
	CancelURL  string `json:"cancel_url"`
	URL        string `json:"url"`
}

Session stores session data from any GLAIR Vision session requests

type SessionsInput

type SessionsInput struct {
	// SuccessURL represents redirection URL
	// when the session is concluded successfully
	//
	// SuccessURL is required
	SuccessURL string
	// CancelURL represents redirection URL
	// when user presses the back button during
	// the session or the session encountered an
	// error when processing the request
	//
	// CancelURL is optional
	CancelURL *string
}

SessionsInput stores sessions request input

Directories

Path Synopsis
Package client provides API client that can be used to interact with GLAIR Vision products
Package client provides API client that can be used to interact with GLAIR Vision products
examples
Package face is a collection of functions and objects that interacts with GLAIR Vision Face Biometrics API and its results
Package face is a collection of functions and objects that interacts with GLAIR Vision Face Biometrics API and its results
Package identity is a collection of functions and objects that interacts with GLAIR Vision identity verification API and its results
Package identity is a collection of functions and objects that interacts with GLAIR Vision identity verification API and its results
Package ocr is a collection of functions and objects that interacts with GLAIR Vision OCR products and its results
Package ocr is a collection of functions and objects that interacts with GLAIR Vision OCR products and its results

Jump to

Keyboard shortcuts

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