-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfasttext.go
103 lines (85 loc) · 2.24 KB
/
fasttext.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package fasttext
// #cgo CXXFLAGS: -I${SRCDIR}/fastText/src -I${SRCDIR} -std=c++14
// #cgo LDFLAGS: -lstdc++
// #include <stdio.h>
// #include <stdlib.h>
// #include "cbits.h"
import "C"
import (
"encoding/json"
"unsafe"
)
// A model object. Effectively a wrapper
// around the C fasttext handle
type Model struct {
path string
handle C.FastTextHandle
}
// Opens a model from a path and returns a model
// object
func Open(path string) *Model {
// fmt.Println("something")
// create a C string from the Go string
cpath := C.CString(path)
// you have to delete the converted string
// See https://github.com/golang/go/wiki/cgo
defer C.free(unsafe.Pointer(cpath))
return &Model{
path: path,
handle: C.NewHandle(cpath),
}
}
// Closes a model handle
func (handle *Model) Close() error {
if handle == nil {
return nil
}
C.DeleteHandle(handle.handle)
return nil
}
// Performs model prediction
func (handle *Model) Predict(query string) (Predictions, error) {
cquery := C.CString(query)
defer C.free(unsafe.Pointer(cquery))
// Call the Predict function defined in cbits.cpp
// passing in the model handle and the query string
r := C.Predict(handle.handle, cquery)
// the C code returns a c string which we need to
// convert to a go string
defer C.free(unsafe.Pointer(r))
js := C.GoString(r)
// unmarshal the json results into the predictions
// object. See https://blog.golang.org/json-and-go
predictions := []Prediction{}
err := json.Unmarshal([]byte(js), &predictions)
if err != nil {
return nil, err
}
return predictions, nil
}
func (handle *Model) Analogy(query string) (Analogs, error) {
cquery := C.CString(query)
defer C.free(unsafe.Pointer(cquery))
r := C.Analogy(handle.handle, cquery)
defer C.free(unsafe.Pointer(r))
js := C.GoString(r)
analogies := []Analog{}
err := json.Unmarshal([]byte(js), &analogies)
if err != nil {
return nil, err
}
return analogies, nil
}
func (handle *Model) Wordvec(query string) (Vectors, error) {
cquery := C.CString(query)
defer C.free(unsafe.Pointer(cquery))
r := C.Wordvec(handle.handle, cquery)
defer C.free(unsafe.Pointer(r))
js := C.GoString(r)
vectors := []Vector{}
err := json.Unmarshal([]byte(js), &vectors)
if err != nil {
return nil, err
}
return vectors, nil
}