This repository has been archived by the owner on Feb 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
ocr.go
420 lines (327 loc) · 8.77 KB
/
ocr.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*
Copyright (c) 2016, Maxim Konakov
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package main
import (
"bytes"
"container/heap"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"unicode"
)
var cmd *cmdLineOptions
func main() {
var err error
// command line parameters
if cmd, err = parseCmdLine(); err != nil {
die(err.Error())
}
// read filters
lineFilter, textFilter, err := makeFilters()
if err != nil {
die(err.Error())
}
// OCR
var text bytes.Buffer
if err = extractText(&text, lineFilter); err != nil {
die(err.Error())
}
// apply full-text filter
if len(cmd.output) == 0 {
_, err = os.Stdout.Write(textFilter(text.Bytes()))
} else {
var out *os.File
if out, err = os.OpenFile(cmd.output, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666); err == nil {
defer func() {
if err == nil {
err = out.Close()
} else {
out.Close()
}
}()
_, err = out.Write(textFilter(text.Bytes()))
}
}
if err != nil {
die(err.Error())
}
}
func extractText(text *bytes.Buffer, filter func([]byte) []byte) (err error) {
// temporary directory
var dir string
dir, err = ioutil.TempDir("", "ocr-")
if err != nil {
return
}
dir = filepath.FromSlash(dir + "/") // make sure we have trailing slash
defer os.RemoveAll(dir)
// signal processing
signals := make(chan os.Signal, 5)
go func() {
<-signals
os.RemoveAll(dir)
die("Interrupted")
}()
signal.Notify(signals, os.Interrupt, os.Kill)
// extract images from input file
if err = extractImages(dir); err != nil {
return
}
// OCR
return ocr(dir, text, filter)
}
// image extractor
func extractImages(dir string) error {
switch ext := filepath.Ext(cmd.input); ext {
case ".pdf":
return pdfExtractImages(dir)
case ".djvu":
return djvuExtractImages(dir)
default:
return errors.New("Unknown file type: " + cmd.input)
}
}
// 'pdfimages' driver
func pdfExtractImages(dir string) error {
if err := checkPdfImageExtractor(); err != nil {
return err
}
args := []string{"-tiff", "-f", strconv.Itoa(int(cmd.first))}
if cmd.last >= cmd.first {
args = append(args, "-l", strconv.Itoa(int(cmd.last)))
}
args = append(args, cmd.input, dir)
var msg bytes.Buffer
command := exec.Command("pdfimages", args...)
command.Stderr = &msg
err := command.Run()
if err == nil {
return nil
}
if _, ok := err.(*exec.ExitError); ok && msg.Len() > 0 {
s := msg.String()
if strings.HasPrefix(s, "pdfimages") { // got 'usage' string instead of an error message
s = "Program 'pdfimages' exited with an error; parameters: " + strings.Join(args, " ")
} else {
s = strings.TrimSpace(s)
}
err = errors.New(s)
}
return err
}
func checkPdfImageExtractor() error {
var help bytes.Buffer
command := exec.Command("pdfimages", "--help")
command.Stderr = &help
if err := command.Run(); err != nil {
return err
}
re := regexp.MustCompile(`^\s+-tiff\s+`)
for s, _ := help.ReadBytes('\n'); len(s) > 0; s, _ = help.ReadBytes('\n') {
if re.Match(s) {
return nil
}
}
return errors.New("Installed version of 'pdfimages' does not support '-tiff' option")
}
// 'ddjvu' driver
func djvuExtractImages(dir string) error {
args := []string{"-format=tiff", "-mode=black", "-eachpage"} // -scale=600 (dpi) ?
if cmd.first <= cmd.last {
args = append(args, fmt.Sprintf("-page=%d-%d", cmd.first, cmd.last))
} else if cmd.first > 1 {
args = append(args, fmt.Sprintf("-page=%d-100000", cmd.first))
}
args = append(args, cmd.input, dir+"%05d.tif")
var msg bytes.Buffer
command := exec.Command("ddjvu", args...)
command.Stderr = &msg
err := command.Run()
if err == nil {
return nil
}
if _, ok := err.(*exec.ExitError); ok {
prefix := regexp.MustCompile(`^ddjvu:\s+(?:\[[^\]]*\]\s*)?`)
s, _ := msg.ReadBytes('\n')
s = bytes.TrimSpace(prefix.ReplaceAllLiteral(s, []byte{}))
err = errors.New(string(s))
}
return err
}
// request/response data structures for parallel ocr
type ocrRequest struct {
no uint
image string
}
func (req *ocrRequest) process() (text []byte, err error) {
text, err = exec.Command("tesseract", req.image, "-", "-l", cmd.language).Output()
if err != nil {
msg := fmt.Sprintf("(page %d) ", req.no+cmd.first)
if e, ok := err.(*exec.ExitError); ok {
if n := bytes.IndexByte(e.Stderr, '\n'); n >= 0 { // get first line only
e.Stderr = e.Stderr[:n]
}
msg += string(bytes.TrimSpace(e.Stderr))
} else {
msg += err.Error()
}
err = errors.New(msg)
}
return
}
type ocrResult struct {
req ocrRequest
err error
text []byte
}
func processOCRRequest(req *ocrRequest) (r *ocrResult) {
r = &ocrResult{req: *req}
r.text, r.err = req.process()
return
}
// heap of ocrResult structures for restoring the original page order
type resultHeap []*ocrResult
func (h resultHeap) Len() int { return len(h) }
func (h resultHeap) Less(i, j int) bool { return h[i].req.no < h[j].req.no }
func (h resultHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *resultHeap) Push(x interface{}) { *h = append(*h, x.(*ocrResult)) }
func (h *resultHeap) Pop() interface{} {
n := len(*h) - 1
val := (*h)[n]
*h = (*h)[:n]
return val
}
// OCR driver
func ocr(dir string, text *bytes.Buffer, filter func([]byte) []byte) error {
// list all image files
files, err := filepath.Glob(dir + "*.tif")
if err != nil {
return err
}
if len(files) == 0 {
return errors.New("No images found in file " + cmd.input)
}
if len(files) > 1 {
sort.Strings(files)
}
// channels
n := runtime.NumCPU()
results := make(chan *ocrResult, n)
requests := make(chan *ocrRequest, len(files))
var wg sync.WaitGroup
// workers
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for req := range requests {
results <- processOCRRequest(req)
}
}()
}
go func() {
wg.Wait()
close(results)
}()
// fill in request channel
for i, file := range files {
requests <- &ocrRequest{uint(i), file}
}
close(requests)
// read results
var h resultHeap
i := uint(0)
heap.Init(&h)
for r := range results {
heap.Push(&h, r)
for ; len(h) > 0 && h[0].req.no == i; i++ {
r = heap.Pop(&h).(*ocrResult)
if r.err != nil {
return r.err
}
// process the result
reader := bytes.NewBuffer(r.text)
for s, _ := reader.ReadBytes('\n'); len(s) > 0; s, _ = reader.ReadBytes('\n') {
if _, err := text.Write(filter(bytes.TrimRightFunc(s, unicode.IsSpace))); err != nil {
return err
}
if err := text.WriteByte('\n'); err != nil {
return err
}
}
}
}
if h.Len() > 0 {
panic(fmt.Sprintf("Heap still has %d elements", h.Len()))
}
return nil
}
// little helpers
func die(msg string) {
fmt.Fprintln(os.Stderr, "ERROR:", msg)
os.Exit(1)
}
// fiter function maker
func makeFilters() (lineFilter, textFilter func([]byte) []byte, err error) {
rules := new(ruleList)
for _, name := range cmd.filters {
var file *os.File
if file, err = os.Open(name); err != nil {
return
}
defer file.Close()
if err = rules.add(file, name); err != nil {
return
}
}
lineFilter = seqFilter(rules.lineRules)
textFilter = seqFilter(rules.textRules)
return
}
func seqFilter(rules []func([]byte) []byte) func([]byte) []byte {
if len(rules) == 0 {
return func(s []byte) []byte { return s }
}
return func(s []byte) []byte {
if len(s) > 0 {
for _, f := range rules {
if s = f(s); len(s) == 0 {
break
}
}
}
return s
}
}