-
Notifications
You must be signed in to change notification settings - Fork 224
/
ocr_http_handler.go
87 lines (66 loc) · 1.8 KB
/
ocr_http_handler.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
package ocrworker
import (
"encoding/json"
"fmt"
"net/http"
"github.com/couchbaselabs/logg"
)
type OcrHttpHandler struct {
RabbitConfig RabbitConfig
}
func NewOcrHttpHandler(r RabbitConfig) *OcrHttpHandler {
return &OcrHttpHandler{
RabbitConfig: r,
}
}
func (s *OcrHttpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
logg.LogTo("OCR_HTTP", "serveHttp called")
defer req.Body.Close()
ocrRequest := OcrRequest{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&ocrRequest)
if err != nil {
logg.LogError(err)
http.Error(w, "Unable to unmarshal json", 500)
return
}
ocrResult, err := HandleOcrRequest(ocrRequest, s.RabbitConfig)
if err != nil {
msg := "Unable to perform OCR decode. Error: %v"
errMsg := fmt.Sprintf(msg, err)
logg.LogError(fmt.Errorf(errMsg))
http.Error(w, errMsg, 500)
return
}
logg.LogTo("OCR_HTTP", "ocrResult: %v", ocrResult)
fmt.Fprintf(w, ocrResult.Text)
}
func HandleOcrRequest(ocrRequest OcrRequest, rabbitConfig RabbitConfig) (OcrResult, error) {
switch ocrRequest.InplaceDecode {
case true:
// inplace decode: short circuit rabbitmq, and just call
// ocr engine directly
ocrEngine := NewOcrEngine(ocrRequest.EngineType)
ocrResult, err := ocrEngine.ProcessRequest(ocrRequest)
if err != nil {
msg := "Error processing ocr request. Error: %v"
errMsg := fmt.Sprintf(msg, err)
logg.LogError(fmt.Errorf(errMsg))
return OcrResult{}, err
}
return ocrResult, nil
default:
// add a new job to rabbitmq and wait for worker to respond w/ result
ocrClient, err := NewOcrRpcClient(rabbitConfig)
if err != nil {
logg.LogError(err)
return OcrResult{}, err
}
ocrResult, err := ocrClient.DecodeImage(ocrRequest)
if err != nil {
logg.LogError(err)
return OcrResult{}, err
}
return ocrResult, nil
}
}