aboutsummaryrefslogtreecommitdiff
path: root/cmd/importer/importer.go
blob: 18a7a7bcde0a0d70d582ae258a3e98c28b89a1a0 (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
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
package importer

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"math"
	"os"
	"strings"

	"github.com/urfave/cli/v2"

	"git.gabrielgio.me/dict/db"
)

var ImportCommand = &cli.Command{
	Name:  "import",
	Usage: "convert dict.cc dictionary into a queryable sqlite format.",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "output",
			Value: "main.dict",
			Usage: "Dictionary database location",
		},
		&cli.StringFlag{
			Name:  "input",
			Value: "dict.txt",
			Usage: "Dict.cc txt dictionary file",
		},
	},
	Action: func(cCtx *cli.Context) error {
		input := cCtx.String("input")
		output := cCtx.String("output")
		return Import(context.Background(), input, output)
	},
}

func Import(ctx context.Context, txtInput, sqliteOutput string) error {
	db, err := db.Open(":memory:")
	if err != nil {
		return err
	}
	err = db.Migrate(ctx)
	if err != nil {
		return err
	}

	file, err := os.Open(txtInput)
	if err != nil {
		return err
	}
	defer file.Close()

	count := 0
	total, err := lineCounter(file)
	if err != nil {
		return err
	}

	_, err = file.Seek(0, 0)
	if err != nil {
		return err
	}

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		if strings.HasPrefix(scanner.Text(), "#") || scanner.Text() == "" {
			continue
		}

		var (
			p    = strings.SplitN(scanner.Text(), "\t", 2)
			word = p[0]
			line = strings.ReplaceAll(p[1], "\t", " ")
		)

		if err := db.InsertLine(ctx, word, line); err != nil {
			return err
		}
		count++

		if (count % 1234) == 0 {
			fmt.Print("\033[G\033[K") // move the cursor left and clear the line
			per := math.Ceil((float64(count) / float64(total)) * 100.0)
			fmt.Printf("%d/%d (%.0f%%)", count, total, per)
		}
	}

	fmt.Printf("Consolidating")
	err = db.Consolidade(ctx)
	if err != nil {
		return err
	}

	err = db.Backup(ctx, sqliteOutput)
	if err != nil {
		return err
	}
	return nil
}

func lineCounter(r io.Reader) (int, error) {
	var count int
	const lineBreak = '\n'

	buf := make([]byte, bufio.MaxScanTokenSize)

	for {
		bufferSize, err := r.Read(buf)
		if err != nil && err != io.EOF {
			return 0, err
		}

		var buffPosition int
		for {
			i := bytes.IndexByte(buf[buffPosition:], lineBreak)
			if i == -1 || bufferSize == buffPosition {
				break
			}
			buffPosition += i + 1
			count++
		}
		if err == io.EOF {
			break
		}
	}

	return count, nil
}