-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecognizer.go
More file actions
192 lines (163 loc) · 3.8 KB
/
recognizer.go
File metadata and controls
192 lines (163 loc) · 3.8 KB
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
package rescript
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"golang.org/x/sync/errgroup"
"github.com/akeil/rmtool"
"github.com/akeil/rmtool/pkg/lines"
)
// The Recognizer organizes calls to the MyScript API to convert notbooks
// from handwriting to a recognize Result.
//
// The recognizer also manages caching to avoid repeated calls to the API
// if a page has not changed.
type Recognizer struct {
ms *MyScript
cacheDir string
cacheMx sync.RWMutex
}
// NewRecognizer creates a recognizer withthe given credentials for the
// MyScript API.
//
// If cacheDir is non-empty, it will be used to cache responses from the API.
// If it is empty, caching is disabled.
func NewRecognizer(appKey, hmacKey, cacheDir string) *Recognizer {
return &Recognizer{
ms: NewMyScript(appKey, hmacKey),
cacheDir: cacheDir,
}
}
// Recognize performs handwriting recognition on all pages of the given document.
// It resturns a map of page-IDs and recognition results.
func (r *Recognizer) Recognize(doc *rmtool.Document, l LanguageCode) (map[string]*Node, error) {
var resultsMx sync.Mutex
results := make(map[string]*Node)
var group errgroup.Group
for _, p := range doc.Pages() {
pageID := p
group.Go(func() error {
d, err := doc.Drawing(pageID)
if err != nil {
return err
}
res, err := r.recognizeDrawing(d, l)
if err != nil {
return err
}
resultsMx.Lock()
results[pageID] = toTokens(res)
resultsMx.Unlock()
return nil
})
}
err := group.Wait()
if err != nil {
return results, err
}
return results, nil
}
func (r *Recognizer) recognizeDrawing(d *lines.Drawing, l LanguageCode) (Result, error) {
groups := make([]StrokeGroup, len(d.Layers))
t := int64(0)
for i, l := range d.Layers {
g, tx := ConvertLayer(t, l)
t = tx
groups[i] = g
}
req := prepareRequest(l)
req.StrokeGroups = groups
k, err := cacheKey(req)
if err == nil {
cached, err := r.readCache(k)
if err == nil {
return cached, nil
}
}
res, err := r.ms.Batch(req)
if err != nil {
return res, err
}
if k != "" {
go r.writeCache(k, res)
}
return res, err
}
func (r *Recognizer) readCache(key string) (Result, error) {
var res Result
if r.cacheDir == "" {
return res, fmt.Errorf("cache dir not set")
}
r.cacheMx.RLock()
defer r.cacheMx.RUnlock()
p := filepath.Join(r.cacheDir, key+".cache.json")
f, err := os.Open(p)
if err != nil {
return res, err
}
defer f.Close()
err = json.NewDecoder(f).Decode(&res)
if err != nil {
return res, err
}
return res, nil
}
func (r *Recognizer) writeCache(key string, res Result) error {
if r.cacheDir == "" {
return fmt.Errorf("cache dir not set")
}
r.cacheMx.Lock()
defer r.cacheMx.Unlock()
err := os.MkdirAll(r.cacheDir, 0755)
if err != nil {
if !os.IsExist(err) {
return err
}
}
p := filepath.Join(r.cacheDir, key+".cache.json")
f, err := os.Create(p)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(res)
}
func prepareRequest(l LanguageCode) Request {
req := NewRequest()
req.Width = lines.MaxWidth
req.Height = lines.MaxHeight
guides := false // recommended to turn off in Offscreen usage
bbox := true
chars := false
words := true
req.Configuration = NewConfiguration(l, guides, bbox, chars, words)
return req
}
func cacheKey(req Request) (string, error) {
cs := sha1.New()
req.checksum(cs)
return hex.EncodeToString(cs.Sum(nil)), nil
}
func toTokens(r Result) *Node {
// this assumes the the MmyScript "words" are exactly the same concept
// as our "tokens".
// Seems to be the case, AFAIK
var head *Node
var tail *Node
var curr *Node
for _, w := range r.Words {
curr = NewNode(NewToken(w.Label))
if head != nil {
head.InsertAfter(curr)
head = curr
} else {
head = curr
tail = curr
}
}
return tail
}