utils.go 5.3 KB
Newer Older
L
LKKlein 已提交
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
package ocr

import (
	"archive/tar"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/LKKlein/gocv"
	"gopkg.in/yaml.v3"
)

func getString(args map[string]interface{}, key string, dv string) string {
	if f, ok := args[key]; ok {
		return f.(string)
	}
	return dv
}

func getFloat64(args map[string]interface{}, key string, dv float64) float64 {
	if f, ok := args[key]; ok {
		return f.(float64)
	}
	return dv
}

func getInt(args map[string]interface{}, key string, dv int) int {
	if i, ok := args[key]; ok {
		return i.(int)
	}
	return dv
}

func getBool(args map[string]interface{}, key string, dv bool) bool {
	if b, ok := args[key]; ok {
		return b.(bool)
	}
	return dv
}

func ReadImage(image_path string) gocv.Mat {
	img := gocv.IMRead(image_path, gocv.IMReadColor)
	if img.Empty() {
		log.Printf("Could not read image %s\n", image_path)
		os.Exit(1)
	}
	return img
}

func clip(value, min, max int) int {
	if value <= min {
		return min
	} else if value >= max {
		return max
	}
	return value
}

func minf(data []float32) float32 {
	v := data[0]
	for _, val := range data {
		if val < v {
			v = val
		}
	}
	return v
}

func maxf(data []float32) float32 {
	v := data[0]
	for _, val := range data {
		if val > v {
			v = val
		}
	}
	return v
}

func mini(data []int) int {
	v := data[0]
	for _, val := range data {
		if val < v {
			v = val
		}
	}
	return v
}

func maxi(data []int) int {
	v := data[0]
	for _, val := range data {
		if val > v {
			v = val
		}
	}
	return v
}

func argmax(arr []float32) (int, float32) {
	max_value, index := arr[0], 0
	for i, item := range arr {
		if item > max_value {
			max_value = item
			index = i
		}
	}
	return index, max_value
}

func checkModelExists(modelPath string) bool {
	if isPathExist(modelPath+"/model") && isPathExist(modelPath+"/params") {
		return true
	}
	if strings.HasPrefix(modelPath, "http://") ||
		strings.HasPrefix(modelPath, "ftp://") || strings.HasPrefix(modelPath, "https://") {
		return true
	}
	return false
}

func downloadFile(filepath, url string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	log.Println("[download_file] from:", url, " to:", filepath)
	return err
}

func isPathExist(path string) bool {
	if _, err := os.Stat(path); err == nil {
		return true
	} else if os.IsNotExist(err) {
		return false
	}
	return false
}

func downloadModel(modelDir, modelPath string) (string, error) {
	if modelPath != "" && (strings.HasPrefix(modelPath, "http://") ||
		strings.HasPrefix(modelPath, "ftp://") || strings.HasPrefix(modelPath, "https://")) {
156 157 158 159
		if checkModelExists(modelDir) {
			return modelDir, nil
		}
		_, suffix := path.Split(modelPath)
L
LKKlein 已提交
160 161 162 163 164 165 166 167 168 169 170 171
		outPath := filepath.Join(modelDir, suffix)
		outDir := filepath.Dir(outPath)
		if !isPathExist(outDir) {
			os.MkdirAll(outDir, os.ModePerm)
		}

		if !isPathExist(outPath) {
			err := downloadFile(outPath, modelPath)
			if err != nil {
				return "", err
			}
		}
172 173 174 175 176

		if strings.HasSuffix(outPath, ".tar") && !checkModelExists(modelDir) {
			unTar(modelDir, outPath)
			os.Remove(outPath)
			return modelDir, nil
L
LKKlein 已提交
177
		}
178
		return modelDir, nil
L
LKKlein 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
	}
	return modelPath, nil
}

func unTar(dst, src string) (err error) {
	fr, err := os.Open(src)
	if err != nil {
		return err
	}
	defer fr.Close()

	tr := tar.NewReader(fr)
	for {
		hdr, err := tr.Next()

		switch {
		case err == io.EOF:
			return nil
		case err != nil:
			return err
		case hdr == nil:
			continue
		}

203 204 205 206 207 208
		var dstFileDir string
		if strings.Contains(hdr.Name, "model") {
			dstFileDir = filepath.Join(dst, "model")
		} else if strings.Contains(hdr.Name, "params") {
			dstFileDir = filepath.Join(dst, "params")
		}
L
LKKlein 已提交
209 210 211

		switch hdr.Typeflag {
		case tar.TypeDir:
212
			continue
L
LKKlein 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
		case tar.TypeReg:
			file, err := os.OpenFile(dstFileDir, os.O_CREATE|os.O_RDWR, os.FileMode(hdr.Mode))
			if err != nil {
				return err
			}
			_, err2 := io.Copy(file, tr)
			if err2 != nil {
				return err2
			}
			file.Close()
		}
	}

	return nil
}

229 230 231 232 233 234 235 236 237
func readLines2StringSlice(filepath string) []string {
	if strings.HasPrefix(filepath, "http://") || strings.HasPrefix(filepath, "https://") {
		home, _ := os.UserHomeDir()
		dir := home + "/.paddleocr/rec/"
		_, suffix := path.Split(filepath)
		f := dir + suffix
		if !isPathExist(f) {
			err := downloadFile(f, filepath)
			if err != nil {
L
LKKlein 已提交
238
				log.Println("download ppocr key file error! You can specify your local dict path by conf.yaml.")
239 240 241 242 243 244
				return nil
			}
		}
		filepath = f
	}
	content, err := ioutil.ReadFile(filepath)
L
LKKlein 已提交
245
	if err != nil {
246
		log.Println("read ppocr key file error!")
L
LKKlein 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
		return nil
	}
	lines := strings.Split(string(content), "\n")
	return lines
}

func ReadYaml(yamlPath string) (map[string]interface{}, error) {
	data, err := ioutil.ReadFile(yamlPath)
	if err != nil {
		return nil, err
	}
	var body interface{}
	if err := yaml.Unmarshal(data, &body); err != nil {
		return nil, err
	}

	body = convertYaml2Map(body)
	return body.(map[string]interface{}), nil
}

func convertYaml2Map(i interface{}) interface{} {
	switch x := i.(type) {
	case map[interface{}]interface{}:
		m2 := map[string]interface{}{}
		for k, v := range x {
			m2[k.(string)] = convertYaml2Map(v)
		}
		return m2
	case []interface{}:
		for i, v := range x {
			x[i] = convertYaml2Map(v)
		}
	}
	return i
}