ctranslate2ffi

package module
v0.0.0-...-b3faa04 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: Apache-2.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

CTranslate2 Go Bindings

Go bindings for CTranslate2 using libffi (no CGo required).

Features

  • Whisper: Speech recognition and transcription
  • Translator: Sequence-to-sequence translation
  • Generator: Language model text generation

Requirements

Runtime
  • The CTranslate2 shared library (libctranslate2.so, libctranslate2.dylib, or ctranslate2.dll)
  • libffi runtime:
    • Linux: apt install libffi8 or dnf install libffi
    • macOS: Bundled with the system
    • Windows: Bundled with the ffi package

Installation

go get github.com/ardanlabs/ctranslate2ffi

Usage

Load the Library

Before using any functions, load the CTranslate2 shared library:

package main

import "github.com/ardanlabs/ctranslate2ffi"

func main() {
    // Provide the directory containing libctranslate2.so/dylib/dll
    if err := ctranslate2ffi.Load("/usr/local/lib"); err != nil {
        panic(err)
    }
    
    // Check version
    fmt.Println("CTranslate2 version:", ctranslate2.Version())
}
Whisper (Speech Recognition)
// Load a Whisper model
config := ctranslate2.DefaultModelConfig()
config.Device = ctranslate2.DeviceCPU
config.ComputeType = ctranslate2.ComputeFloat32

whisper, err := ctranslate2.NewWhisper("/path/to/whisper-model", config)
if err != nil {
    panic(err)
}
defer whisper.Close()

// Check model properties
fmt.Println("Multilingual:", whisper.IsMultilingual())
fmt.Println("Num mels:", whisper.NumMels())

// Create audio features (mel spectrogram)
// Shape should be [batch_size, n_mels, time_frames]
features, err := ctranslate2.NewStorageViewFloat(melData, []int64{1, 80, 3000}, ctranslate2.DeviceCPU)
if err != nil {
    panic(err)
}
defer features.Close()

// Transcribe
opts := ctranslate2.DefaultWhisperOptions()
result, err := whisper.Generate(features, []string{"<|startoftranscript|>", "<|en|>"}, opts)
if err != nil {
    panic(err)
}
Translator
// Load a translation model
translator, err := ctranslate2.NewTranslator("/path/to/model", config)
if err != nil {
    panic(err)
}
defer translator.Close()

// Translate tokenized input
opts := ctranslate2.DefaultTranslationOptions()
result, err := translator.Translate([]string{"Hello", "world"}, opts)
if err != nil {
    panic(err)
}
Generator (Language Model)
// Load a language model
generator, err := ctranslate2.NewGenerator("/path/to/model", config)
if err != nil {
    panic(err)
}
defer generator.Close()

// Generate text
opts := ctranslate2.DefaultGenerationOptions()
opts.MaxLength = 100
result, err := generator.Generate([]string{"Once", "upon", "a", "time"}, opts)
if err != nil {
    panic(err)
}

Building CTranslate2 with C API

The C API wrapper must be compiled with CTranslate2:

  1. Copy ctranslate2_c.h to CTranslate2/include/
  2. Copy ctranslate2_c.cc to CTranslate2/src/
  3. Add the source file to CMakeLists.txt
  4. Build CTranslate2:
cd CTranslate2
mkdir build && cd build
cmake -DBUILD_SHARED_LIBS=ON ..
make -j$(nproc)

API Reference

Types
  • Device - CPU or CUDA
  • ComputeType - Computation precision (float32, int8, float16, etc.)
  • ModelConfig - Model loading configuration
  • WhisperOptions - Whisper generation options
  • TranslationOptions - Translation options
  • GenerationOptions - Text generation options
Functions
  • Load(path string) - Load the CTranslate2 shared library
  • Version() - Get library version
  • CUDAAvailable() - Check if CUDA is available
  • CUDADeviceCount() - Get number of CUDA devices
Error Handling
  • GetLastError() - Get the last error message
  • ClearError() - Clear the error state

License

Apache 2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FFITypeCt2floatarray = ffi.NewType(
	&ffi.TypePointer,
	&ffi.TypeUint64,
)
View Source
var FFITypeCt2generationresult = ffi.NewType(
	&ffi.TypePointer,
	&ffi.TypePointer,
	&ffi.TypeUint64,
	&ffi.TypePointer,
	&ffi.TypeUint64,
)
View Source
var FFITypeCt2stringarray = ffi.NewType(
	&ffi.TypePointer,
	&ffi.TypeUint64,
)
View Source
var FFITypeCt2translationresult = ffi.NewType(
	&ffi.TypePointer,
	&ffi.TypePointer,
	&ffi.TypeUint64,
	&ffi.TypePointer,
	&ffi.TypeUint64,
)

Functions

func CUDAAvailable

func CUDAAvailable() bool

CUDAAvailable returns whether CUDA is available.

func CUDADeviceCount

func CUDADeviceCount() int

CUDADeviceCount returns the number of CUDA devices.

func ClearError

func ClearError()

ClearError clears the last error.

func Ct2ClearError

func Ct2ClearError()

func Ct2CudaAvailable

func Ct2CudaAvailable() bool

func Ct2CudaDeviceCount

func Ct2CudaDeviceCount() int32

func Ct2FloatsFree

func Ct2FloatsFree(arr *Ct2floatarray)

func Ct2GenerationResultFree

func Ct2GenerationResultFree(result *Ct2generationresult)

func Ct2GeneratorFree

func Ct2GeneratorFree(generator Ct2generator)

func Ct2GeneratorGenerate

func Ct2GeneratorGenerate(generator Ct2generator, prompt uintptr, promptLength uint64, options Ct2generationoptions, resultOut *Ct2generationresult) int32

func Ct2GeneratorGenerateBatch

func Ct2GeneratorGenerateBatch(generator Ct2generator, prompts string, promptLengths uintptr, numPrompts uint64, options Ct2generationoptions, results *Ct2generationresult) int32

func Ct2GetLastError

func Ct2GetLastError() string

func Ct2StorageFree

func Ct2StorageFree(storage Ct2storageview)

func Ct2StorageGetShape

func Ct2StorageGetShape(storage Ct2storageview, shape uintptr, ndims uintptr) int32

func Ct2StorageSize

func Ct2StorageSize(storage Ct2storageview) int64

func Ct2StorageToFloat

func Ct2StorageToFloat(storage Ct2storageview, buffer uintptr) int32

func Ct2StringsFree

func Ct2StringsFree(arr *Ct2stringarray)

func Ct2TranslationResultFree

func Ct2TranslationResultFree(result *Ct2translationresult)

func Ct2TranslatorFree

func Ct2TranslatorFree(translator Ct2translator)

func Ct2TranslatorTranslate

func Ct2TranslatorTranslate(translator Ct2translator, source uintptr, sourceLength uint64, options Ct2translationoptions, resultOut *Ct2translationresult) int32

func Ct2TranslatorTranslateBatch

func Ct2TranslatorTranslateBatch(translator Ct2translator, sources string, sourceLengths uintptr, numSources uint64, options Ct2translationoptions, results *Ct2translationresult) int32

func Ct2Version

func Ct2Version() string

func Ct2WhisperDetectLanguage

func Ct2WhisperDetectLanguage(whisper Ct2whisper, features Ct2storageview, languages *Ct2stringarray, probabilities *Ct2floatarray) int32

func Ct2WhisperFree

func Ct2WhisperFree(whisper Ct2whisper)

func Ct2WhisperGenerate

func Ct2WhisperGenerate(whisper Ct2whisper, features Ct2storageview, prompts uintptr, numPrompts uint64, options Ct2whisperoptions, resultOut *Ct2whisperresult) int32

func Ct2WhisperIsMultilingual

func Ct2WhisperIsMultilingual(whisper Ct2whisper) bool

func Ct2WhisperNMels

func Ct2WhisperNMels(whisper Ct2whisper) uint64

func Ct2WhisperNumLanguages

func Ct2WhisperNumLanguages(whisper Ct2whisper) uint64

func Ct2WhisperResultFree

func Ct2WhisperResultFree(result *Ct2whisperresult)

func GetLastError

func GetLastError() string

GetLastError returns the last error message.

func Load

func Load(path string) error

func Version

func Version() string

Version returns the library version.

Types

type ComputeType

type ComputeType int

ComputeType represents the compute precision.

const (
	ComputeDefault     ComputeType = 0
	ComputeAuto        ComputeType = 1
	ComputeFloat32     ComputeType = 2
	ComputeInt8        ComputeType = 3
	ComputeInt8Float32 ComputeType = 4
	ComputeInt8Float16 ComputeType = 5
	ComputeInt16       ComputeType = 7
	ComputeFloat16     ComputeType = 8
	ComputeBFloat16    ComputeType = 9
)

type Ct2computetype

type Ct2computetype int32
const (
	Ct2ComputeDefault      Ct2computetype = 0
	Ct2ComputeAuto         Ct2computetype = 1
	Ct2ComputeFloat32      Ct2computetype = 2
	Ct2ComputeInt8         Ct2computetype = 3
	Ct2ComputeInt8Float32  Ct2computetype = 4
	Ct2ComputeInt8Float16  Ct2computetype = 5
	Ct2ComputeInt8Bfloat16 Ct2computetype = 6
	Ct2ComputeInt16        Ct2computetype = 7
	Ct2ComputeFloat16      Ct2computetype = 8
	Ct2ComputeBfloat16     Ct2computetype = 9
)

type Ct2device

type Ct2device int32
const (
	Ct2DeviceCpu  Ct2device = 0
	Ct2DeviceCuda Ct2device = 1
)

type Ct2floatarray

type Ct2floatarray struct {
	Values uintptr
	Count  uint64
}

type Ct2generationoptions

type Ct2generationoptions struct {
	BeamSize              uint64
	Patience              float32
	LengthPenalty         float32
	RepetitionPenalty     float32
	NoRepeatNgramSize     uint64
	DisableUnk            bool
	MaxLength             uint64
	MinLength             uint64
	SamplingTopk          uint64
	SamplingTopp          float32
	SamplingTemperature   float32
	NumHypotheses         uint64
	ReturnScores          bool
	IncludePromptInResult bool
}

func Ct2GenerationOptionsDefault

func Ct2GenerationOptionsDefault() Ct2generationoptions

type Ct2generationresult

type Ct2generationresult struct {
	Sequences       string
	SequenceLengths uintptr
	NumSequences    uint64
	Scores          uintptr
	NumScores       uint64
}

type Ct2generator

type Ct2generator uintptr

func Ct2GeneratorCreate

func Ct2GeneratorCreate(modelPath string, config Ct2modelconfig) Ct2generator

type Ct2modelconfig

type Ct2modelconfig struct {
	Device      Ct2device
	ComputeType Ct2computetype
	DeviceIndex int32
	NumThreads  uint64
	NumReplicas uint64
}

func Ct2ModelConfigDefault

func Ct2ModelConfigDefault() Ct2modelconfig

type Ct2storageview

type Ct2storageview uintptr

func Ct2StorageCreateFloat

func Ct2StorageCreateFloat(data uintptr, shape uintptr, ndims uint64, device Ct2device) Ct2storageview

func Ct2WhisperEncode

func Ct2WhisperEncode(whisper Ct2whisper, features Ct2storageview, toCpu bool) Ct2storageview

type Ct2stringarray

type Ct2stringarray struct {
	Strings string
	Count   uint64
}

type Ct2translationoptions

type Ct2translationoptions struct {
	BeamSize            uint64
	Patience            float32
	LengthPenalty       float32
	CoveragePenalty     float32
	RepetitionPenalty   float32
	NoRepeatNgramSize   uint64
	DisableUnk          bool
	MaxInputLength      uint64
	MaxDecodingLength   uint64
	MinDecodingLength   uint64
	SamplingTopk        uint64
	SamplingTopp        float32
	SamplingTemperature float32
	UseVmap             bool
	NumHypotheses       uint64
	ReturnScores        bool
	ReturnAttention     bool
	ReplaceUnknowns     bool
}

func Ct2TranslationOptionsDefault

func Ct2TranslationOptionsDefault() Ct2translationoptions

type Ct2translationresult

type Ct2translationresult struct {
	Hypotheses        string
	HypothesesLengths uintptr
	NumHypotheses     uint64
	Scores            uintptr
	NumScores         uint64
}

type Ct2translator

type Ct2translator uintptr

func Ct2TranslatorCreate

func Ct2TranslatorCreate(modelPath string, config Ct2modelconfig) Ct2translator

type Ct2whisper

type Ct2whisper uintptr

func Ct2WhisperCreate

func Ct2WhisperCreate(modelPath string, config Ct2modelconfig) Ct2whisper

type Ct2whisperoptions

type Ct2whisperoptions struct {
	BeamSize                 uint64
	Patience                 float32
	LengthPenalty            float32
	RepetitionPenalty        float32
	NoRepeatNgramSize        uint64
	MaxLength                uint64
	SamplingTopk             uint64
	SamplingTemperature      float32
	NumHypotheses            uint64
	ReturnScores             bool
	ReturnNoSpeechProb       bool
	MaxInitialTimestampIndex uint64
	SuppressBlank            bool
}

func Ct2WhisperOptionsDefault

func Ct2WhisperOptionsDefault() Ct2whisperoptions

type Ct2whisperresult

type Ct2whisperresult struct {
	Sequences    string
	NumSequences uint64
	Scores       uintptr
	NumScores    uint64
	NoSpeechProb float32
}

type Device

type Device int

Device represents the compute device.

const (
	DeviceCPU  Device = 0
	DeviceCUDA Device = 1
)

type GenerationOptions

type GenerationOptions struct {
	BeamSize              int
	Patience              float32
	LengthPenalty         float32
	RepetitionPenalty     float32
	NoRepeatNgramSize     int
	DisableUnk            bool
	MaxLength             int
	MinLength             int
	SamplingTopK          int
	SamplingTopP          float32
	SamplingTemp          float32
	NumHypotheses         int
	ReturnScores          bool
	IncludePromptInResult bool
}

GenerationOptions holds options for text generation.

func DefaultGenerationOptions

func DefaultGenerationOptions() GenerationOptions

DefaultGenerationOptions returns sensible defaults.

type GenerationResult

type GenerationResult struct {
	Sequences [][]string
	Scores    []float32
}

GenerationResult holds the result of text generation.

type Generator

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

Generator wraps a CTranslate2 generator (language model).

func NewGenerator

func NewGenerator(modelPath string, config ModelConfig) (*Generator, error)

NewGenerator loads a generator model from the given path.

func (*Generator) Close

func (g *Generator) Close()

Close releases the model resources.

func (*Generator) Generate

func (g *Generator) Generate(prompt []string, opts GenerationOptions) (*GenerationResult, error)

Generate generates text continuation from a prompt.

type ModelConfig

type ModelConfig struct {
	Device      Device
	ComputeType ComputeType
	DeviceIndex int
	NumThreads  int
	NumReplicas int
}

ModelConfig holds configuration for loading models.

func DefaultModelConfig

func DefaultModelConfig() ModelConfig

DefaultModelConfig returns sensible default configuration.

type StorageView

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

StorageView wraps a CTranslate2 storage view (tensor).

func NewStorageViewFloat

func NewStorageViewFloat(data []float32, shape []int64, device Device) (*StorageView, error)

NewStorageViewFloat creates a storage view from float data.

func (*StorageView) Close

func (s *StorageView) Close()

Close releases the storage view.

func (*StorageView) Shape

func (s *StorageView) Shape() ([]int64, error)

Shape returns the shape of the storage view.

func (*StorageView) Size

func (s *StorageView) Size() int64

Size returns the total number of elements.

func (*StorageView) ToFloat

func (s *StorageView) ToFloat() ([]float32, error)

ToFloat copies the data to a float slice.

type TranslationOptions

type TranslationOptions struct {
	BeamSize          int
	Patience          float32
	LengthPenalty     float32
	CoveragePenalty   float32
	RepetitionPenalty float32
	NoRepeatNgramSize int
	DisableUnk        bool
	MaxInputLength    int
	MaxDecodingLength int
	MinDecodingLength int
	SamplingTopK      int
	SamplingTopP      float32
	SamplingTemp      float32
	UseVMap           bool
	NumHypotheses     int
	ReturnScores      bool
	ReturnAttention   bool
	ReplaceUnknowns   bool
}

TranslationOptions holds options for translation.

func DefaultTranslationOptions

func DefaultTranslationOptions() TranslationOptions

DefaultTranslationOptions returns sensible defaults.

type TranslationResult

type TranslationResult struct {
	Hypotheses [][]string
	Scores     []float32
}

TranslationResult holds the result of translation.

type Translator

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

Translator wraps a CTranslate2 translator model.

func NewTranslator

func NewTranslator(modelPath string, config ModelConfig) (*Translator, error)

NewTranslator loads a translator model from the given path.

func (*Translator) Close

func (t *Translator) Close()

Close releases the model resources.

func (*Translator) Translate

func (t *Translator) Translate(tokens []string, opts TranslationOptions) (*TranslationResult, error)

Translate translates a single sequence of tokens.

type Whisper

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

Whisper wraps a CTranslate2 Whisper model.

func NewWhisper

func NewWhisper(modelPath string, config ModelConfig) (*Whisper, error)

NewWhisper loads a Whisper model from the given path.

func (*Whisper) Close

func (w *Whisper) Close()

Close releases the model resources.

func (*Whisper) Generate

func (w *Whisper) Generate(features *StorageView, prompts []string, opts WhisperOptions) (*WhisperResult, error)

Generate transcribes audio features.

func (*Whisper) IsMultilingual

func (w *Whisper) IsMultilingual() bool

IsMultilingual returns whether the model supports multiple languages.

func (*Whisper) NumLanguages

func (w *Whisper) NumLanguages() int

NumLanguages returns the number of supported languages.

func (*Whisper) NumMels

func (w *Whisper) NumMels() int

NumMels returns the number of mel filterbanks expected by the model.

type WhisperOptions

type WhisperOptions struct {
	BeamSize                 int
	Patience                 float32
	LengthPenalty            float32
	RepetitionPenalty        float32
	NoRepeatNgramSize        int
	MaxLength                int
	SamplingTopK             int
	SamplingTemperature      float32
	NumHypotheses            int
	ReturnScores             bool
	ReturnNoSpeechProb       bool
	MaxInitialTimestampIndex int
	SuppressBlank            bool
}

WhisperOptions holds generation options for Whisper.

func DefaultWhisperOptions

func DefaultWhisperOptions() WhisperOptions

DefaultWhisperOptions returns sensible default options.

type WhisperResult

type WhisperResult struct {
	Sequences    []string
	Scores       []float32
	NoSpeechProb float32
}

WhisperResult holds the result of Whisper transcription.

Directories

Path Synopsis
Example: Transcribe an MP3 file using CTranslate2 Whisper bindings
Example: Transcribe an MP3 file using CTranslate2 Whisper bindings

Jump to

Keyboard shortcuts

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