This repository has been archived by the owner on Mar 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
nextword.go
337 lines (289 loc) · 6.81 KB
/
nextword.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
package main
import (
"bufio"
"errors"
"fmt"
"github.com/high-moctane/go-readerer"
"io"
"os"
"path/filepath"
"strings"
)
// ReadLineBufSize is buffer size for Nextword.ReadLine
var ReadLineBufSize = 10000 // 10000 is the fastest value (?)
// NextwordParams is a Nextword parameter.
type NextwordParams struct {
DataPath string
CandidateNum int // Number of candidates
Greedy bool // If true, Nextword suggests words from all n-gram data.
}
// Nextword suggests next English words.
type Nextword struct {
params *NextwordParams
readLineBufSize int
}
// NewNextword returns new Nextword. If params is not valid, err will be not nil.
func NewNextword(params *NextwordParams) (*Nextword, error) {
// nil check
if params == nil {
return nil, errors.New("invalid params")
}
// DataPath
fi, err := os.Stat(params.DataPath)
if err != nil {
return nil, errors.New(`"NEXTWORD_DATA_PATH" environment variable is not set`)
}
if !fi.IsDir() {
return nil, errors.New(`invalid "NEXTWORD_DATA_PATH"`)
}
// candidate-num
if params.CandidateNum <= 0 {
return nil, errors.New("candidate-num must be a positive integer")
}
return &Nextword{
params: params,
readLineBufSize: ReadLineBufSize,
}, nil
}
// Suggest suggests next English words from input. If input ends with " ",
// it returns all likely words. If not, it returns the words that begins the last
// word of input.
func (nw *Nextword) Suggest(input string) (candidates []string, err error) {
ngram, prefix := nw.parseInput(input)
// search n-gram
for i := 0; i < len(ngram); i++ {
var cand []string
cand, err = nw.searchNgram(ngram[i:])
if err != nil {
return
}
// merge
if prefix != "" {
cand = nw.filterCandidates(cand, prefix)
}
candidates = nw.mergeCandidates(candidates, cand)
// end condition
if len(candidates) > nw.params.CandidateNum {
candidates = candidates[:nw.params.CandidateNum]
}
if !nw.params.Greedy && len(candidates) > 0 {
return
}
}
// search 1-gram
cand, err := nw.searchOneGram(prefix)
if err != nil {
return
}
candidates = nw.mergeCandidates(candidates, cand)
if len(candidates) > nw.params.CandidateNum {
candidates = candidates[:nw.params.CandidateNum]
}
return
}
// parseInput returns last ngram and prefix in the input.
func (*Nextword) parseInput(input string) (ngram []string, prefix string) {
elems := strings.Split(input, " ")
// If elems does not end with " ", the word will be prefix.
if elems[len(elems)-1] != "" {
prefix = elems[len(elems)-1]
elems = elems[:len(elems)-1]
}
// collect up to last four words.
for i := len(elems) - 1; i >= 0; i-- {
if elems[i] == "" {
continue
}
ngram = append([]string{elems[i]}, ngram...)
if len(ngram) >= 4 {
break
}
}
return
}
// searchNgram search next English from ngram.
func (nw *Nextword) searchNgram(ngram []string) (candidates []string, err error) {
fname, ok := nw.ngramFileName(ngram)
if !ok {
return
}
// open
path := filepath.Join(nw.params.DataPath, fname)
if _, err = os.Stat(path); err != nil {
return nil, nil
}
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
fi, err := os.Stat(path)
if err != nil {
return
}
// search
query := strings.Join(ngram, " ") + "\t"
offset, err := nw.binarySearch(f, 0, fi.Size(), query)
if err != nil {
err = nw.removeEOF(err)
return
}
line, err := nw.readLine(f, offset)
if err != nil {
err = nw.removeEOF(err)
return
}
if !strings.HasPrefix(line, query) {
return
}
candidates = strings.Split(strings.Split(line, "\t")[1], " ")
return
}
// ngramFileName returns appropriate file name from ngram.
func (*Nextword) ngramFileName(ngram []string) (fname string, ok bool) {
initial := strings.ToLower(string([]rune(ngram[0])[0]))
if initial < "a" && "z" < initial {
return
}
fname = fmt.Sprintf("%dgram-%s.txt", len(ngram)+1, initial)
ok = true
return
}
// searchOneGram search English words that begins with prefix.
func (nw *Nextword) searchOneGram(prefix string) (candidates []string, err error) {
if prefix == "" {
return
}
// open
path := filepath.Join(nw.params.DataPath, "1gram.txt")
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
fi, err := os.Stat(path)
if err != nil {
return
}
// search offset
offset, err := nw.binarySearch(f, 0, fi.Size(), prefix)
if err != nil {
if err == io.EOF {
err = nil
}
return
}
// collect
r := readerer.FromReaderAt(f, offset)
sc := bufio.NewScanner(r)
for sc.Scan() {
line := sc.Text()
if !strings.HasPrefix(line, prefix) {
break
}
candidates = append(candidates, line)
}
if sc.Err() != nil {
err = sc.Err()
return
}
return
}
// binarySearch searches query from r between left to right.
func (nw *Nextword) binarySearch(r io.ReaderAt, left, right int64, query string) (offset int64, err error) {
for left <= right {
mid := left + (right-left)/2
if mid == 0 {
offset = 0
} else {
var str string
str, err = nw.readLine(r, mid)
if err != nil {
err = nw.removeEOF(err)
return
}
offset = mid + int64(len(str)) + 1 // "\n"
}
var line string
line, err = nw.readLine(r, offset)
if err != nil {
err = nw.removeEOF(err)
return
}
if query < line {
right = mid - 1
} else if query == line {
return
} else {
left = mid + 1
}
}
mid := left + (right-left)/2
if mid == 0 {
offset = 0
} else {
var str string
str, err = nw.readLine(r, mid)
if err != nil {
err = nw.removeEOF(err)
return
}
offset = mid + int64(len(str)) + 1 // "\n"
}
return
}
// readLine reads r from offset until "\n".
func (nw *Nextword) readLine(r io.ReaderAt, offset int64) (string, error) {
strBuilder := new(strings.Builder)
for {
buf := make([]byte, nw.readLineBufSize)
n, err := r.ReadAt(buf, offset)
if err == io.EOF && n == 0 {
return "", err
} else if err != nil && err != io.EOF {
strBuilder.Write(buf[:n])
return strBuilder.String(), err
}
strBuilder.Write(buf[:n])
// return when buf has "\n"
for i, b := range buf[:n] {
if b == '\n' {
return strBuilder.String()[:strBuilder.Len()-n+i], nil
}
}
offset += int64(n)
}
}
// removeEOF removes io.EOF from err.
func (*Nextword) removeEOF(err error) error {
if err == io.EOF {
return nil
}
return err
}
// mergeCandidates merges two candidates
func (*Nextword) mergeCandidates(a, b []string) []string {
ret := a[:]
m := map[string]bool{}
for _, str := range a {
m[str] = true
}
for _, str := range b {
if !m[str] {
m[str] = true
ret = append(ret, str)
}
}
return ret
}
// filterCandidates filters words which do not begin with prefix from cand.
func (*Nextword) filterCandidates(cand []string, prefix string) []string {
res := make([]string, 0, len(cand))
for _, str := range cand {
if !strings.HasPrefix(str, prefix) {
continue
}
res = append(res, str)
}
return res
}