/
aws.go
169 lines (151 loc) · 3.96 KB
/
aws.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
package ocr
import (
"encoding/json"
"fmt"
"path"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/textract"
)
type AWSClient struct {
CredentialsPath string
}
// Method required by ocr.Client
// Returns AWS document text detection Result
// Reference: https://docs.aws.amazon.com/textract/
func (c AWSClient) Run(image []byte) (*Result, error) {
const (
service = "AWS"
keyName = "credentials"
configName = "config"
maxSizeMB = 5
)
credentialsFile := path.Join(c.CredentialsPath, keyName)
configFile := path.Join(c.CredentialsPath, configName)
three := new(int)
*three = 3
config := aws.Config{
MaxRetries: three,
}
s, err := session.NewSessionWithOptions(
session.Options{
SharedConfigFiles: []string{credentialsFile, configFile},
SharedConfigState: session.SharedConfigEnable,
},
)
if err != nil {
return nil, fmt.Errorf("%s: configuration error: %v", service, err)
}
client := textract.New(s, &config)
doc := textract.Document{
Bytes: image,
}
ddti := textract.DetectDocumentTextInput{
Document: &doc,
}
start := time.Now()
result, err := client.DetectDocumentText(&ddti)
milli := int64(time.Since(start) / time.Millisecond)
if err != nil {
return nil, fmt.Errorf("%s: OCR request failed - %v", service, err)
}
version := *result.DetectDocumentTextModelVersion
blocks := result.Blocks
var lines []string
for _, block := range blocks {
if *block.BlockType == "LINE" {
lines = append(lines, *block.Text)
}
}
fullText := strings.Join(lines[:], "\n")
date := fmtTime(start.UTC())
encoded, err := json.Marshal(result)
return &Result{
Service: service,
Version: version,
FullText: fullText,
Duration: milli,
Date: date,
Raw: encoded,
}, err
}
func geometryToBox(g *textract.Geometry, wi, hi int) string {
b := g.BoundingBox
w, h := float64(wi), float64(hi)
return encodeRawBounds(int(*b.Left*w+.5), int(*b.Top*h+.5),
int(*b.Width*w+.5), int(*b.Height*h+.5))
}
func relsToIds(rels []*textract.Relationship) ([]*string, error) {
for _, rel := range rels {
// Invariant: len(r.Relationships) <= 2 because Type is {CHILD, VALUE}
switch *rel.Type {
case "CHILD":
return rel.Ids, nil
case "VALUE":
continue
default:
return nil, fmt.Errorf("Invalid format type: %v", *rel.Type)
}
}
return nil, nil // No error on empty
}
func (_ AWSClient) ResultToDetection(result *Result, width, height int) (*Detection, error) {
var response textract.DetectDocumentTextOutput
err := json.Unmarshal(result.Raw, &response)
if err != nil {
return nil, err
}
mpages := make([]textract.Block, 0)
blks := make(map[string]*textract.Block)
for _, b := range response.Blocks {
switch *b.BlockType {
case "PAGE":
mpages = append(mpages, *b)
case "LINE":
blks[*b.Id] = b
case "WORD":
blks[*b.Id] = b
default:
return nil, fmt.Errorf("Invalid BlockType: %v", *b.BlockType)
}
}
blocks := make([]Block, 0, len(mpages))
for _, r := range mpages {
ids, err := relsToIds(r.Relationships)
if err != nil {
return nil, err
}
if ids == nil {
continue
}
lines := make([]Line, 0, len(ids))
for _, id := range ids {
l, ok := blks[*id]
if !ok {
return nil, fmt.Errorf("Line %v not found", *id)
}
ids, err := relsToIds(l.Relationships)
if err != nil {
return nil, err
}
if ids == nil {
continue
}
words := make([]Word, 0, len(ids))
for _, id := range ids {
w, ok := blks[*id]
if !ok {
return nil, fmt.Errorf("Word %v not found", *id)
}
words = append(words, Word{geometryToBox(w.Geometry, width, height), *w.Text})
}
lines = append(lines, Line{geometryToBox(l.Geometry, width, height), words})
}
blocks = append(blocks, Block{geometryToBox(r.Geometry, width, height), lines})
}
algoID := sanitizeString(result.Service[:3] + "-" + result.Version)
millis := uint32(result.Duration)
return &Detection{algoID, result.Date, millis, blocks}, nil
}