summaryrefslogtreecommitdiff
path: root/pkg/prob/prob.go
blob: 67baa034cead4abccacf21945c29320af6c908b4 (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
// Copyright 2019 Nick White.
// Use of this source code is governed by the GPLv3
// license that can be found in the LICENSE file.

// prob processes .prob files generated by ocropus
package prob

import (
	"io/ioutil"
	"path/filepath"
	"strconv"
	"strings"

	"rescribe.xyz/utils/pkg/line"
)

func getLineAvg(f string) (float64, error) {
	totalconf := float64(0)
	num := 0

	prob, err := ioutil.ReadFile(f)
	if err != nil {
		return 0, err
	}

	for _, l := range strings.Split(string(prob), "\n") {
		fields := strings.Fields(l)

		if len(fields) == 2 {
			conf, err := strconv.ParseFloat(fields[1], 64)
			if err != nil {
				continue
			}
			totalconf += conf
			num += 1
		}
	}
	if num <= 0 {
		return 0, nil
	}
	avg := totalconf / float64(num)
	return avg, nil
}

// GetLineDetails parses a .prob and corresponding .txt file
func GetLineDetails(probfn string) (line.Details, error) {
	var l line.Detail
	lines := make(line.Details, 0)

	avg, err := getLineAvg(probfn)
	if err != nil {
		return lines, err
	}

	filebase := strings.Replace(probfn, ".prob", "", 1)

	txt, err := ioutil.ReadFile(filebase + ".txt")
	if err != nil {
		return lines, err
	}

	l.Name = filepath.Base(filebase)
	l.Avgconf = avg
	l.Text = string(txt)
	l.OcrName = filepath.Base(filepath.Dir(filebase))

	var imgfn line.ImgPath
	imgfn.Path = filebase + ".bin.png"
	l.Img = imgfn

	lines = append(lines, l)

	return lines, nil
}