-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
370 lines (326 loc) · 9.41 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"annoyindex"
"encoding/json"
"flag"
"fmt"
"log"
"math"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/huichen/sego"
"github.com/huichen/wordvector_be/util"
"github.com/syndtr/goleveldb/leveldb"
)
const (
vecDim = 200
kSearch = 10000
defaultNumReturnKeywords = 10
maxNumReturnKeywords = 100
)
var (
port = flag.String("port", ":3721", "http 服务端口")
httpPathPrefix = flag.String("http_path_prefix", "", "")
dict = flag.String("dict", "", "sego 词典,从 github.com/huichen/sego/data/dictionary.txt 下载")
dbIndexToKeyword *leveldb.DB
dbKeywordToIndex *leveldb.DB
annoyIndex annoyindex.AnnoyIndex
segmenter sego.Segmenter
)
func main() {
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
if *dict != "" {
segmenter.LoadDictionary(*dict)
}
var err error
dbIndexToKeyword, err = leveldb.OpenFile("data/tencent_embedding_index_to_keyword.db", nil)
if err != nil {
log.Panic(err)
}
defer dbIndexToKeyword.Close()
dbKeywordToIndex, err = leveldb.OpenFile("data/tencent_embedding_keyword_to_index.db", nil)
if err != nil {
log.Panic(err)
}
defer dbKeywordToIndex.Close()
annoyIndex = annoyindex.NewAnnoyIndexAngular(vecDim)
annoyIndex.Load("data/tencent_embedding.ann")
http.HandleFunc(fmt.Sprintf("%s/get.similar.keywords/", *httpPathPrefix), getSimilarKeyword)
http.HandleFunc(fmt.Sprintf("%s/get.similar.keywords.from.vector/", *httpPathPrefix), getSimilarKeywordFromVector)
http.HandleFunc(fmt.Sprintf("%s/get.word.vector/", *httpPathPrefix), getWordVector)
http.HandleFunc(fmt.Sprintf("%s/get.similarity.score/", *httpPathPrefix), getSimilarityScore)
go func() {
if err := http.ListenAndServe(*port, nil); err != nil {
panic(err)
}
}()
errc := make(chan error, 2)
go func() {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT)
errc <- fmt.Errorf("%s", <-c)
}()
log.Println("terminated ", <-errc)
}
/*
从一个或者多个关键词找相似词
HTTP 请求参数
/get.similar.keywords/?keyword=xxx&num=yyy
支持多个 keyword 参数(词向量之和),num不指定的话默认10个,比如
/get.similar.keywords/?keyword=xxx&keyword=yyy&keyword=zzz
特殊用法:当 keyword 只有一个且是词向量表中没有的短语时,并且 --dict 参数载入了一个
词典,则将改 keyword 分词之后求多个分词的词向量之和的相似词
*/
type SimilarKeywordResponse struct {
Keywords []Keyword `json:"keywords"`
}
type Keyword struct {
Word string `json:"word"`
Similarity float32 `json:"similarity"`
}
func getSimilarKeyword(w http.ResponseWriter, r *http.Request) {
key, ok := r.URL.Query()["keyword"]
if !ok || len(key) == 0 {
http.Error(w, "必须输入 keyword", http.StatusInternalServerError)
return
}
num, ok := r.URL.Query()["num"]
var numKeywords int
if !ok || len(num) != 1 {
numKeywords = defaultNumReturnKeywords
} else {
var err error
numKeywords, err = strconv.Atoi(num[0])
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if numKeywords <= 0 {
numKeywords = defaultNumReturnKeywords
} else if numKeywords > maxNumReturnKeywords {
numKeywords = maxNumReturnKeywords
}
wordVec := make([]float32, vecDim)
_, err := dbKeywordToIndex.Get([]byte(key[0]), nil)
if err != nil {
if len(key) == 1 && *dict != "" {
// 只有一个关键词,且不出现在向量词表的特殊情况
segments := segmenter.Segment([]byte(key[0]))
key = sego.SegmentsToSlice(segments, false)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
validKeywords := 0
for _, k := range key {
id, err := dbKeywordToIndex.Get([]byte(k), nil)
if err != nil {
continue
}
validKeywords++
index := util.Uint32frombytes(id)
var wv []float32
annoyIndex.GetItem(int(index), &wv)
for i, v := range wv {
wordVec[i] = wordVec[i] + v
}
}
if validKeywords == 0 {
http.Error(w, "没有找到匹配关键词", http.StatusInternalServerError)
return
}
var result []int
annoyIndex.GetNnsByVector(wordVec, numKeywords, kSearch, &result)
var sim SimilarKeywordResponse
for _, k := range result {
keyword, err := dbIndexToKeyword.Get(util.Uint32bytes(uint32(k)), nil)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
similarityScore := getCosineSimilarityByVector(wordVec, k)
sim.Keywords = append(sim.Keywords, Keyword{
Word: string(keyword),
Similarity: similarityScore,
})
}
data, err := json.Marshal(sim)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(data)
}
/*
从一个或者多个关键词找相似词
HTTP POST 请求参数
/get.similar.keywords.from.vector/
body 是 SimilarKeywordFromVectorRequest 结构体的 json
*/
type SimilarKeywordFromVectorRequest struct {
NumKeywords int `json:"numKeywords"`
Vector []float32 `json:"vector"`
}
func getSimilarKeywordFromVector(w http.ResponseWriter, r *http.Request) {
var req SimilarKeywordFromVectorRequest
if r.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
wordVec := req.Vector
if len(wordVec) != vecDim {
http.Error(w, "vector 维度不匹配", http.StatusInternalServerError)
return
}
numKeywords := req.NumKeywords
if numKeywords <= 0 {
numKeywords = defaultNumReturnKeywords
} else if numKeywords > maxNumReturnKeywords {
numKeywords = maxNumReturnKeywords
}
var result []int
annoyIndex.GetNnsByVector(wordVec, numKeywords, kSearch, &result)
var sim SimilarKeywordResponse
for _, k := range result {
keyword, err := dbIndexToKeyword.Get(util.Uint32bytes(uint32(k)), nil)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
similarityScore := getCosineSimilarityByVector(wordVec, k)
sim.Keywords = append(sim.Keywords, Keyword{
Word: string(keyword),
Similarity: similarityScore,
})
}
data, err := json.Marshal(sim)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(data)
}
/*
返回一个或者多个关键词的词向量
HTTP 请求参数
/get.word.vector/?keyword=xxx
支持多个 keyword 参数(词向量之和),比如
/get.similar.keywords/?keyword=xxx&keyword=yyy&keyword=zzz
*/
type WordVectorResponse struct {
Vector []float32 `json:"vector"`
}
func getWordVector(w http.ResponseWriter, r *http.Request) {
key, ok := r.URL.Query()["keyword"]
if !ok || len(key) == 0 {
http.Error(w, "必须输入 keyword", http.StatusInternalServerError)
return
}
wordVec := make([]float32, vecDim)
for _, k := range key {
id, err := dbKeywordToIndex.Get([]byte(k), nil)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
index := util.Uint32frombytes(id)
var wv []float32
annoyIndex.GetItem(int(index), &wv)
for i, v := range wv {
wordVec[i] = wordVec[i] + v
}
}
var resp WordVectorResponse
resp.Vector = wordVec
data, err := json.Marshal(resp)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
/*
计算两个词的相似度
HTTP 请求参数
/get.similarity.score/?keyword1=xxx&keyword2=yyy
*/
type SimilarityScoreResponse struct {
Score float32 `json:"score"`
}
func getSimilarityScore(w http.ResponseWriter, r *http.Request) {
key1, ok := r.URL.Query()["keyword1"]
if !ok || len(key1) != 1 {
http.Error(w, "必须输入 keyword", http.StatusInternalServerError)
return
}
id1, err := dbKeywordToIndex.Get([]byte(key1[0]), nil)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
index1 := util.Uint32frombytes(id1)
key2, ok := r.URL.Query()["keyword2"]
if !ok || len(key2) != 1 {
http.Error(w, "必须输入 keyword", http.StatusInternalServerError)
return
}
id2, err := dbKeywordToIndex.Get([]byte(key2[0]), nil)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
index2 := util.Uint32frombytes(id2)
var resp SimilarityScoreResponse
resp.Score = getCosineSimilarity(int(index1), int(index2))
data, err := json.Marshal(resp)
if err != nil {
log.Printf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(data)
}
func getCosineSimilarity(i, j int) float32 {
var vec []float32
annoyIndex.GetItem(i, &vec)
return getCosineSimilarityByVector(vec, j)
}
func getCosineSimilarityByVector(vec []float32, j int) float32 {
var vec2 []float32
annoyIndex.GetItem(j, &vec2)
var a, b, c float32
for id, v := range vec {
a = a + v*vec2[id]
b = b + v*v
c = c + vec2[id]*vec2[id]
}
return a / float32(math.Sqrt(float64(b))*math.Sqrt(float64(c)))
}