summaryrefslogtreecommitdiff
path: root/parse/bucket.go
blob: 3a4cd6a7586d6951e4e3c95502c7fd9146f77ffa (plain)
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
package parse

import (
	"io"
	"path/filepath"
	"os"
	"sort"
	"strconv"
)

type BucketSpec struct {
	Min float64
	Name string
}
type BucketSpecs []BucketSpec
func (b BucketSpecs) Len() int { return len(b) }
func (b BucketSpecs) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b BucketSpecs) Less(i, j int) bool { return b[i].Min < b[j].Min }

func bucketLine(l LineDetail, buckets BucketSpecs, dirname string) error {
	todir := ""
	for _, b := range buckets {
		if l.Avgconf >= b.Min {
			todir = b.Name
		}
	}

	if todir == "" {
		return nil
	}

	avgstr := strconv.FormatFloat(l.Avgconf, 'G', -1, 64)
	if len(avgstr) > 2 {
		avgstr = avgstr[2:]
	}

	base := filepath.Join(dirname, todir, filepath.Base(l.OcrName) + "_" + l.Name + "_" + avgstr)

	err := os.MkdirAll(filepath.Join(dirname, todir), 0700)
	if err != nil {
		return err
	}

	f, err := os.Create(base + ".png")
	if err != nil {
		return err
	}
	defer f.Close()

	err = l.Img.CopyLineTo(f)
	if err != nil {
		return err
	}

	f, err = os.Create(base + ".txt")
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.WriteString(f, l.Text)
	if err != nil {
		return err
	}

	return nil
}

// Copies line images and text into directories based on their
// confidence, as defined by the buckets struct
func BucketUp(lines LineDetails, buckets BucketSpecs, dirname string) error {
	sort.Sort(buckets)
	// TODO: record and print out summary of % in each bucket category (see how tools did it)
	for _, l := range lines {
		err := bucketLine(l, buckets, dirname)
		if err != nil {
			return err
		}
	}

	return nil
}