-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathporcupine.go
72 lines (60 loc) · 1.48 KB
/
porcupine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package porcupine
// #include <stdlib.h>
// #include "include/pv_porcupine.h"
import "C"
import (
"crypto/sha1"
_ "embed"
"errors"
"fmt"
"os"
"path/filepath"
)
//go:embed model/porcupine_params.pv
var modelData []byte
var (
ErrOutOfMemory = errors.New("porcupine: out of memory")
ErrIOError = errors.New("porcupine: IO error")
ErrInvalidArgument = errors.New("porcupine: invalid argument")
ErrUnknownStatus = errors.New("unknown status code")
)
type Keyword struct {
Label string
FilePath string
Sensitivity float32
}
func checkStatus(status int) error {
switch status {
case C.PV_STATUS_SUCCESS:
return nil
case C.PV_STATUS_OUT_OF_MEMORY:
return ErrOutOfMemory
case C.PV_STATUS_INVALID_ARGUMENT:
return ErrInvalidArgument
case C.PV_STATUS_IO_ERROR:
return ErrIOError
default:
return ErrUnknownStatus
}
}
func temporaryModelFile() (string, error) {
return memoizeIntoFile(modelData, "porcupine_params.pv")
}
func memoizeIntoFile(source []byte, name string) (string, error) {
hasher := sha1.New()
hasher.Write(source)
hash := fmt.Sprintf("%x", hasher.Sum(nil))
temporaryFolder := filepath.Join(os.TempDir(), hash)
temporaryPath := filepath.Join(temporaryFolder, name)
err := os.Mkdir(temporaryFolder, 0755)
if err != nil && !os.IsExist(err) {
return "", err
}
if _, err = os.Stat(temporaryPath); os.IsNotExist(err) {
err = os.WriteFile(temporaryPath, source, 0600)
if err != nil {
return "", err
}
}
return temporaryPath, nil
}