precise

package module
v0.0.0-...-426f2d8 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2023 License: ISC Imports: 8 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

Precise-Lite for Go

This is a Go port of the MycroftAI Precise engine, using tflite and onnxruntime (based on the OpenVoiceOS fork).

I needed this for my Discord bot Astra - which I'm currently training a model for. Help us out here and submit a few voice clips!

What is working?

Everything should work, though I'm not sure if my port is off in any way. I'm not an AI/Machine Learning expert, I just read the code!

Supported Backends

Currently, I've tested it with tflite and onnxruntime (cpu and gpu) - onnxruntime works and would be fine on CPU, but on GPUs it is slower than CPU due to the simplicity of the model.

Example

See runner_test.go - this contains an example usage of both tflite and onnxruntime - though onnxruntime is slower, it was more of a test.

Docker

The Dockerfiles contain a pre-built Go image with all dependencies required to use this library. If you want to use it yourself, you can use a FROM statement for ghcr.io/tystuyfzand/precise-go public image, use it to build, and then copy the tflite runtime. These images are based off Ubuntu 22.04 (due to simplicity and unifying the GPU and non-GPU, but debian exists too)

The following tags are available, and all include Tensorflow 2.11.0 and ONNX 1.12.0

  • latest, ubuntu-jammy (Ubuntu 22.04)
  • debian (Debian 11)
  • latest-gpu, ubuntu-jammy-gpu (Ubuntu 22.04, CUDA 11.8.0, CUDNN 8)

To use this in Docker, tensorflow doesn't exactly have a precompiled lite version that I've found. The easiest way is to use the base docker image ghcr.io/tystuyfzand/precise-go (which contains the latest version of Go as of this) and use it to build your application with a multi-stage build. Then, add the tensorflow lite libraries.

Example:

FROM ghcr.io/tystuyfzand/precise-go:latest AS builder

ADD . /app
WORKDIR /app

RUN go build -o main

FROM ubuntu:jammy

COPY --from=builder /app/main /main
COPY --from=builder /usr/lib/libtensorflowlite.so /usr/lib/libtensorflowlite_c.so /usr/lib/

CMD ["/main"]

There is also support for onnxruntime (using go build -tags onnx) - but it's not necessary.

Note: GPU/CUDA support exists, but is actually SLOWER than CPU support due to how simple the model is. When using this, you're required to use single stage builds OR use the same base CUDA image.

Contributions, Bug Reports, etc.

All of these are welcome! If I made an error in the logic or there's something wrong, please let me know!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultThreshold = ThresholdOptions{
	MinZ:       -4.0,
	MaxZ:       4.0,
	Center:     0.5,
	Resolution: 200,
}

DefaultThreshold is the default set of options for the decoder.

View Source
var (
	ErrModelClosed = errors.New("model closed")
)
View Source
var (
	ErrUnexpectedType = errors.New("unexpected tensor type")
)

Functions

func LinSpace

func LinSpace(start, stop float32, num int) (res *tensor.Dense)

LinSpace returns evenly spaced numbers over a specified closed interval.

Types

type ActivationFunc

type ActivationFunc func()

type ExitFunc

type ExitFunc func(err error)

type Listener

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

func NewListener

func NewListener(model Model, p Params) (*Listener, error)

func (*Listener) Close

func (p *Listener) Close() error

func (*Listener) Update

func (p *Listener) Update(audio []int16) (float32, error)

type Model

type Model interface {
	Predict(inputData tensor.Tensor) (float32, error)
	Close() error
}

func NewTFLiteModel

func NewTFLiteModel(modelPath string) (Model, error)

NewTFLiteModel creates a new tensorflow lite model

type MuStd

type MuStd [][]float32

MuStd represents threshold configs with easy to use functions.

func (MuStd) Calculate

func (m MuStd) Calculate(value float32) []float32

Calculate applies the value to the configuration

func (MuStd) Max

func (m MuStd) Max(maxZ float32) float32

Max calculates the maximum with maxZ, then sorts and returns the highest value

func (MuStd) Min

func (m MuStd) Min(minZ float32) float32

Min calculates the minimum with minZ, then sorts and returns the lowest value

type Option

type Option func(*Runner)

func WithActivationFunc

func WithActivationFunc(f ActivationFunc) Option

WithActivationFunc sets the func called when activated

func WithDetectorOpts

func WithDetectorOpts(opts ...TriggerOption) Option

WithDetectorOpts sets detector options

func WithExitFunc

func WithExitFunc(f ExitFunc) Option

WithPredictionFunc sets the func called after prediction

func WithPredictionFunc

func WithPredictionFunc(f PredictionFunc) Option

WithPredictionFunc sets the func called after prediction

type Params

type Params struct {
	WindowT         float32 `json:"window_t" default:"0.1"`
	HopT            float32 `json:"hop_t" default:"0.05"`
	BufferT         float32 `json:"buffer_t" default:"1.5"`
	SampleRate      int     `json:"sample_rate" default:"16000"`
	SampleDepth     int     `json:"sample_depth" default:"2"`
	NMFCC           int     `json:"n_mfcc" default:"13"`
	NFilt           int     `json:"n_filt" default:"20"`
	NFft            int     `json:"n_fft" default:"512"`
	UseDelta        bool    `json:"use_delta" default:"false"`
	ThresholdConfig MuStd   `json:"threshold_config" default:"[[6,4]]"`
	ThresholdCenter float32 `json:"threshold_center" default:"0.2"`
}

Params is the Precise model parameter list. This can be loaded from JSON, however for tflite models these are hardcoded. Defaults are set for these elsewhere via NewParams, not using the tags, but they are there for reference

func NewParams

func NewParams() Params

func (Params) BufferSamples

func (p Params) BufferSamples() int

func (Params) HopSamples

func (p Params) HopSamples() int

func (Params) NFeatures

func (p Params) NFeatures() int

func (Params) WindowSamples

func (p Params) WindowSamples() int

type PredictionFunc

type PredictionFunc func(prob float32)

type Runner

type Runner struct {
	OnPrediction PredictionFunc
	OnActivation ActivationFunc
	OnExit       ExitFunc
	// contains filtered or unexported fields
}

func NewRunner

func NewRunner(listener *Listener, chunkSize int, opts ...Option) *Runner

NewRunner creates a new network runner

func (*Runner) Close

func (r *Runner) Close() error

Close stops the neural network runner

func (*Runner) Queue

func (r *Runner) Queue(samples []int16)

Queue passes in samples directly to the channel

func (*Runner) ReadFrom

func (r *Runner) ReadFrom(reader io.Reader) (int64, error)

ReadFrom allows the Runner to simply read from a reader

func (*Runner) Start

func (r *Runner) Start()

Start will start the runner and the goroutine

func (*Runner) Stop

func (r *Runner) Stop()

Stop will stop the runner without closing it.

func (*Runner) Write

func (r *Runner) Write(b []byte) (int, error)

Write allows a Runner to act as an io.Writer

type TFLiteModel

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

TFLiteModel represents a tensorflow lite model

func (*TFLiteModel) Close

func (m *TFLiteModel) Close() error

Close cleans up the model after use

func (*TFLiteModel) Predict

func (m *TFLiteModel) Predict(inputData tensor.Tensor) (float32, error)

Predict sends the input data into the input tensor, then invokes the model

type ThresholdDecoder

type ThresholdDecoder struct {
	MinOut   int
	MaxOut   int
	OutRange int
	// contains filtered or unexported fields
}

ThresholdDecoder decodes raw neural network output

func NewThresholdDecoder

func NewThresholdDecoder(muStds MuStd, options ThresholdOptions) *ThresholdDecoder

NewThresholdDecoder creates a new ThresholdDecoder with calculated distributions.

func (*ThresholdDecoder) Decode

func (t *ThresholdDecoder) Decode(rawOutput float32) float32

Decode takes raw neural network output and normalizes it using probability distribution

type ThresholdOptions

type ThresholdOptions struct {
	MinZ       float32
	MaxZ       float32
	Center     float32
	Resolution int
}

type TriggerDetector

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

func NewTriggerDetector

func NewTriggerDetector(chunkSize int, opts ...TriggerOption) *TriggerDetector

NewTriggerDetector creates a new TriggerDetector

func (*TriggerDetector) Update

func (t *TriggerDetector) Update(prob float32) bool

Update adds the current probability to the detection history

type TriggerOption

type TriggerOption func(*TriggerDetector)

func WithSensitivity

func WithSensitivity(sensitivity float32) TriggerOption

WithSensitivity sets the detector sensitivity

func WithTriggerLevel

func WithTriggerLevel(triggerLevel int) TriggerOption

WithTriggerLevel sets the number of triggers required to return a valid trigger

Jump to

Keyboard shortcuts

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