forked from otiai10/gosseract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
111 lines (102 loc) · 2.12 KB
/
client.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
package gosseract
import "fmt"
import "image"
import "os"
import "image/png"
// Client is an client to use gosseract functions
type Client struct {
tesseract tesseractCmd
source path
digest path
Error error
}
type path struct {
value string
}
func (p *path) Ready() bool {
return (p.value != "")
}
func (p *path) Get() string {
return p.value
}
// NewClient provide reference to new Client
func NewClient() (c *Client, e error) {
tess, e := getTesseractCmd()
if e != nil {
return
}
c = &Client{tesseract: tess}
return
}
// Src accepts path to target source file
func (c *Client) Src(srcPath string) *Client {
c.source = path{srcPath}
return c
}
// Digest accepts path to target digest file
func (c *Client) Digest(digestPath string) *Client {
c.digest = path{digestPath}
return c
}
// Image accepts image object of target
func (c *Client) Image(img image.Image) *Client {
imageFilePath, e := generateTmpFile()
if e != nil {
c.Error = e
return c
}
f, e := os.Create(imageFilePath)
// TODO: DRY
if e != nil {
c.Error = e
return c
}
defer f.Close()
png.Encode(f, img)
// TODO: delete created file after
c.source = path{f.Name()}
return c
}
// Out executes tesseract and gives results
func (c *Client) Out() (out string, e error) {
if e = c.ready(); e != nil {
return
}
// TODO: validation to call execute
out, e = c.execute()
return
}
// Must executes tesseract directly by parameter map
func (c *Client) Must(params map[string]string) (out string, e error) {
if e = c.accept(params); e != nil {
return
}
return c.Out()
}
func (c *Client) accept(params map[string]string) (e error) {
var ok bool
var src string
if src, ok = params["src"]; !ok {
return fmt.Errorf("Missing parameter `src`.")
}
c.source = path{src}
if digest, ok := params["digest"]; ok {
c.digest = path{digest}
}
return
}
func (c *Client) ready() (e error) {
if !c.source.Ready() {
return fmt.Errorf("Source is not set")
}
return
}
func (c *Client) execute() (res string, e error) {
args := []string{
c.source.Get(),
}
if c.digest.Ready() {
args = append(args, c.digest.Get())
}
return c.tesseract.Execute(args)
}