bar.go 2.1 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
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
package progress

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/jmorganca/ollama/format"
	"golang.org/x/term"
)

type Bar struct {
	message      string
	messageWidth int

	maxValue     int64
	initialValue int64
	currentValue int64

	started time.Time
	stopped time.Time
}

func NewBar(message string, maxValue, initialValue int64) *Bar {
	return &Bar{
		message:      message,
		messageWidth: -1,
		maxValue:     maxValue,
		initialValue: initialValue,
		currentValue: initialValue,
		started:      time.Now(),
	}
}

func (b *Bar) String() string {
	termWidth, _, err := term.GetSize(int(os.Stderr.Fd()))
	if err != nil {
		panic(err)
	}

	var pre, mid, suf strings.Builder

	if b.message != "" {
		message := strings.TrimSpace(b.message)
		if b.messageWidth > 0 && len(message) > b.messageWidth {
			message = message[:b.messageWidth]
		}

		fmt.Fprintf(&pre, "%s", message)
		if b.messageWidth-pre.Len() >= 0 {
			pre.WriteString(strings.Repeat(" ", b.messageWidth-pre.Len()))
		}

		pre.WriteString(" ")
	}

58
	fmt.Fprintf(&pre, "%.0f%% ", b.percent())
Michael Yang's avatar
Michael Yang committed
59
60
61
62
63
64
65

	fmt.Fprintf(&suf, "(%s/%s, %s/s, %s)",
		format.HumanBytes(b.currentValue),
		format.HumanBytes(b.maxValue),
		format.HumanBytes(int64(b.rate())),
		b.elapsed())

66
	mid.WriteString("▕")
Michael Yang's avatar
Michael Yang committed
67

68
	f := termWidth - pre.Len() - suf.Len() - 2
Michael Yang's avatar
Michael Yang committed
69
70
	n := int(float64(f) * b.percent() / 100)

71
72
	if n > 0 {
		mid.WriteString(strings.Repeat("█", n))
Michael Yang's avatar
Michael Yang committed
73
74
75
76
77
78
	}

	if f-n > 0 {
		mid.WriteString(strings.Repeat(" ", f-n))
	}

79
	mid.WriteString("▏")
Michael Yang's avatar
Michael Yang committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

	return pre.String() + mid.String() + suf.String()
}

func (b *Bar) Set(value int64) {
	if value >= b.maxValue {
		value = b.maxValue
		b.stopped = time.Now()
	}

	b.currentValue = value
}

func (b *Bar) percent() float64 {
	if b.maxValue > 0 {
		return float64(b.currentValue) / float64(b.maxValue) * 100
	}

	return 0
}

func (b *Bar) rate() float64 {
Michael Yang's avatar
Michael Yang committed
102
103
104
105
106
107
	elapsed := b.elapsed()
	if elapsed.Seconds() > 0 {
		return (float64(b.currentValue) - float64(b.initialValue)) / elapsed.Seconds()
	}

	return 0
Michael Yang's avatar
Michael Yang committed
108
109
110
111
112
113
114
115
116
117
}

func (b *Bar) elapsed() time.Duration {
	stopped := b.stopped
	if stopped.IsZero() {
		stopped = time.Now()
	}

	return stopped.Sub(b.started).Round(time.Second)
}