-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathocr.go
69 lines (59 loc) · 1.39 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
package utils
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime/multipart"
"net/http"
)
const (
ocrAPI = "https://api.ocr.space/parse/image"
ocrAPIKey = "5a64d478-9c89-43d8-88e3-c65de9999580"
)
var errNoResult = errors.New("no ocr result")
// OCR reads image from reader r and converts it into string.
func OCR(r io.Reader) (string, error) {
return OCRWithClient(r, http.DefaultClient)
}
// OCRWithClient reads image from reader r and converts it into string
// with custom http.Client.
func OCRWithClient(r io.Reader, client *http.Client) (string, error) {
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, _ := w.CreateFormFile("file", "pic.jpg")
if _, err := io.Copy(part, r); err != nil {
return "", err
}
params := map[string]string{
"scale": "true",
}
for k, v := range params {
w.WriteField(k, v)
}
w.Close()
req, _ := http.NewRequest("POST", ocrAPI, &body)
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("apikey", ocrAPIKey)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var res struct {
ParsedResults []struct {
ParsedText string
}
}
if err := json.Unmarshal(b, &res); err != nil {
return "", err
}
if len(res.ParsedResults) == 0 {
return "", errNoResult
}
return res.ParsedResults[0].ParsedText, nil
}