forked from sajari/docconv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_ocr.go
46 lines (37 loc) · 969 Bytes
/
image_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
// +build ocr
package docconv
import (
"fmt"
"io"
"sync"
"github.com/otiai10/gosseract/v2"
)
var langs = struct {
sync.RWMutex
lang string
}{lang: "eng"}
// ConvertImage converts images to text.
// Requires gosseract.
func ConvertImage(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
meta := make(map[string]string)
out := make(chan string, 1)
// TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns?
go func(file *LocalFile) {
langs.RLock()
body := gosseract.Must(gosseract.Params{Src: file.Name(), Languages: langs.lang})
langs.RUnlock()
out <- string(body)
}(f)
return <-out, meta, nil
}
// SetImageLanguages sets the languages parameter passed to gosseract.
func SetImageLanguages(l string) {
langs.Lock()
langs.lang = l
langs.Unlock()
}