diff --git a/README.md b/README.md index 65d8a0b..e77d9e1 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,15 @@ dit run login.html # With probabilities dit run https://github.com/login --proba +# Download the pretrained model to the cache (~/.dit/model.json) +dit model pull + +# Show the cached model's path, size, and SHA-256 checksum +dit model status + +# Remove the cached model +dit model rm + # Download training data and model from Hugging Face dit data download diff --git a/dit.go b/dit.go index a9331d9..16fe3f7 100644 --- a/dit.go +++ b/dit.go @@ -16,12 +16,15 @@ package dit import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" "io" "log/slog" "net/http" "os" "path/filepath" + "strings" "time" "github.com/happyhackingspace/dit/captcha" @@ -30,11 +33,21 @@ import ( ) // downloadTimeout bounds the total time spent fetching the model. -const downloadTimeout = 1 * time.Minute +// The model is ~93MB, so allow for slow connections. +const downloadTimeout = 10 * time.Minute // ModelURL is the canonical download location for the pretrained model. const ModelURL = "https://huggingface.co/datasets/happyhackingspace/dit/resolve/main/model.json" +// ModelSHA256 is the pinned hex-encoded SHA-256 checksum of the model served +// at ModelURL. When non-empty, Download verifies the fetched file against it +// and fails on mismatch. +// +// TODO: pin the published checksum of model.json. While empty, verification +// is skipped: the computed checksum is logged with a warning instead so it +// can be copied here. +const ModelSHA256 = "" + // Classifier wraps the form and field type classification models. type Classifier struct { fc *classifier.FormFieldClassifier @@ -78,8 +91,8 @@ func New() (*Classifier, error) { return Load(path) } - dest := filepath.Join(ModelDir(), "model.json") - slog.Info("Model not found, downloading", "url", ModelURL, "dest", dest) + dest := DefaultModelPath() + slog.Info("Model not found, downloading", "url", ModelURL, "dest", dest, "size", "~93MB") if err := Download(dest); err != nil { return nil, fmt.Errorf("dit: %w", err) } @@ -87,45 +100,138 @@ func New() (*Classifier, error) { } // Download fetches the pretrained model from ModelURL and writes it to dest, -// creating parent directories as needed. A partial file is removed on error. +// creating parent directories as needed. Progress is reported to stderr. The +// file is written to a temporary path and renamed into place only after the +// download completes and, when ModelSHA256 is set, its checksum matches, so +// a partial or corrupt file is never left at dest. func Download(dest string) error { - if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { - return fmt.Errorf("create model dir: %w", err) + _, err := downloadModel(ModelURL, dest, ModelSHA256, os.Stderr) + return err +} + +// downloadModel fetches url into dest, streaming progress to progress and +// returning the hex-encoded SHA-256 checksum of the downloaded file. When +// pinnedSHA256 is non-empty the checksum must match or the download fails; +// when empty, the computed checksum is logged with a warning. +func downloadModel(url, dest, pinnedSHA256 string, progress io.Writer) (string, error) { + dir := filepath.Dir(dest) + if err := os.MkdirAll(dir, 0755); err != nil { + return "", fmt.Errorf("create model dir: %w", err) } ctx, cancel := context.WithTimeout(context.Background(), downloadTimeout) defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, ModelURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { - return fmt.Errorf("download model: %w", err) + return "", fmt.Errorf("download model: %w", err) } resp, err := http.DefaultClient.Do(req) if err != nil { - return fmt.Errorf("download model: %w", err) + return "", fmt.Errorf("download model: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - return fmt.Errorf("download model: HTTP %d", resp.StatusCode) + return "", fmt.Errorf("download model: HTTP %d", resp.StatusCode) } - f, err := os.Create(dest) + tmp, err := os.CreateTemp(dir, filepath.Base(dest)+".*.partial") if err != nil { - return fmt.Errorf("create model file: %w", err) + return "", fmt.Errorf("create model file: %w", err) } - written, err := io.Copy(f, resp.Body) + hash := sha256.New() + pw := newProgressWriter(progress, resp.ContentLength) + written, err := io.Copy(io.MultiWriter(tmp, hash, pw), resp.Body) + pw.finish() if err != nil { - _ = f.Close() - _ = os.Remove(dest) - return fmt.Errorf("download model: %w", err) + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + return "", fmt.Errorf("download model: %w", err) } - if err := f.Close(); err != nil { - return fmt.Errorf("close model file: %w", err) + if err := tmp.Close(); err != nil { + _ = os.Remove(tmp.Name()) + return "", fmt.Errorf("close model file: %w", err) } - slog.Info("Model downloaded", "size", fmt.Sprintf("%.1fMB", float64(written)/1024/1024)) - return nil + sum := hex.EncodeToString(hash.Sum(nil)) + switch { + case pinnedSHA256 == "": + slog.Warn("No pinned model checksum; skipping verification", "sha256", sum) + case !strings.EqualFold(sum, pinnedSHA256): + _ = os.Remove(tmp.Name()) + return "", fmt.Errorf("model checksum mismatch: got %s, want %s", sum, pinnedSHA256) + } + + if err := os.Rename(tmp.Name(), dest); err != nil { + _ = os.Remove(tmp.Name()) + return "", fmt.Errorf("move model file: %w", err) + } + + slog.Info("Model downloaded", "size", fmt.Sprintf("%.1fMB", float64(written)/1024/1024), "sha256", sum) + return sum, nil +} + +// progressWriter reports byte-count progress to an io.Writer as data passes +// through it. +type progressWriter struct { + w io.Writer + total int64 + written int64 + lastAt time.Time +} + +// progressInterval throttles progress updates. +const progressInterval = 200 * time.Millisecond + +func newProgressWriter(w io.Writer, total int64) *progressWriter { + return &progressWriter{w: w, total: total} +} + +// Write implements io.Writer and never fails. +func (p *progressWriter) Write(b []byte) (int, error) { + p.written += int64(len(b)) + if time.Since(p.lastAt) >= progressInterval { + p.report() + } + return len(b), nil +} + +func (p *progressWriter) report() { + if p.w == nil { + return + } + p.lastAt = time.Now() + mb := float64(p.written) / 1024 / 1024 + if p.total > 0 { + pct := float64(p.written) / float64(p.total) * 100 + _, _ = fmt.Fprintf(p.w, "\rDownloading model: %.1f/%.1f MB (%.0f%%)", mb, float64(p.total)/1024/1024, pct) + } else { + _, _ = fmt.Fprintf(p.w, "\rDownloading model: %.1f MB", mb) + } +} + +// finish prints the final progress line followed by a newline. +func (p *progressWriter) finish() { + if p.w == nil { + return + } + p.report() + _, _ = fmt.Fprintln(p.w) +} + +// FileSHA256 returns the hex-encoded SHA-256 checksum of the file at path. +func FileSHA256(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer func() { _ = f.Close() }() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil } // ModelDir returns the default model storage directory (~/.dit). @@ -137,6 +243,13 @@ func ModelDir() string { return filepath.Join(home, ".dit") } +// DefaultModelPath returns the default cached model location +// (~/.dit/model.json), the destination of implicit first-run downloads and +// of "dit model pull". +func DefaultModelPath() string { + return filepath.Join(ModelDir(), "model.json") +} + // FindModel searches for a model file by name. // Search order: current dir walk-up to module root, then ~/.dit/. func FindModel(name string) (string, error) { diff --git a/dit_model_test.go b/dit_model_test.go new file mode 100644 index 0000000..535b3a8 --- /dev/null +++ b/dit_model_test.go @@ -0,0 +1,240 @@ +package dit + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func sha256Hex(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func TestDownloadModelWritesFile(t *testing.T) { + content := []byte(`{"model":"test"}`) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(content) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "model.json") + sum, err := downloadModel(srv.URL, dest, "", nil) + if err != nil { + t.Fatalf("downloadModel: %v", err) + } + if want := sha256Hex(content); sum != want { + t.Errorf("checksum = %s, want %s", sum, want) + } + + got, err := os.ReadFile(dest) + if err != nil { + t.Fatalf("read downloaded file: %v", err) + } + if !bytes.Equal(got, content) { + t.Errorf("file content = %q, want %q", got, content) + } +} + +func TestDownloadModelCreatesParentDirs(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("data")) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "nested", "dir", "model.json") + if _, err := downloadModel(srv.URL, dest, "", nil); err != nil { + t.Fatalf("downloadModel: %v", err) + } + if _, err := os.Stat(dest); err != nil { + t.Errorf("downloaded file missing: %v", err) + } +} + +func TestDownloadModelPinnedChecksumMatch(t *testing.T) { + content := []byte("verified model data") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(content) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "model.json") + sum, err := downloadModel(srv.URL, dest, sha256Hex(content), nil) + if err != nil { + t.Fatalf("downloadModel with matching pin: %v", err) + } + if want := sha256Hex(content); sum != want { + t.Errorf("checksum = %s, want %s", sum, want) + } +} + +func TestDownloadModelPinnedChecksumCaseInsensitive(t *testing.T) { + content := []byte("verified model data") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(content) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "model.json") + if _, err := downloadModel(srv.URL, dest, strings.ToUpper(sha256Hex(content)), nil); err != nil { + t.Fatalf("downloadModel with uppercase pin: %v", err) + } +} + +func TestDownloadModelChecksumMismatch(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("tampered data")) + })) + defer srv.Close() + + dir := t.TempDir() + dest := filepath.Join(dir, "model.json") + wrongSum := strings.Repeat("ab", 32) + _, err := downloadModel(srv.URL, dest, wrongSum, nil) + if err == nil { + t.Fatal("expected checksum mismatch error, got nil") + } + if !strings.Contains(err.Error(), "checksum mismatch") { + t.Errorf("error = %v, want checksum mismatch", err) + } + if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) { + t.Errorf("expected no file at dest after mismatch, stat err = %v", statErr) + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read dir: %v", err) + } + if len(entries) != 0 { + t.Errorf("expected empty dir after mismatch, found %d entries", len(entries)) + } +} + +func TestDownloadModelHTTPError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not found", http.StatusNotFound) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "model.json") + _, err := downloadModel(srv.URL, dest, "", nil) + if err == nil { + t.Fatal("expected HTTP error, got nil") + } + if !strings.Contains(err.Error(), "HTTP 404") { + t.Errorf("error = %v, want HTTP 404", err) + } + if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) { + t.Errorf("expected no file at dest after HTTP error, stat err = %v", statErr) + } +} + +func TestDownloadModelDoesNotOverwriteOnFailure(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("bad data")) + })) + defer srv.Close() + + dest := filepath.Join(t.TempDir(), "model.json") + existing := []byte("existing good model") + if err := os.WriteFile(dest, existing, 0644); err != nil { + t.Fatalf("write existing: %v", err) + } + + wrongSum := strings.Repeat("cd", 32) + if _, err := downloadModel(srv.URL, dest, wrongSum, nil); err == nil { + t.Fatal("expected checksum mismatch error, got nil") + } + got, err := os.ReadFile(dest) + if err != nil { + t.Fatalf("read dest: %v", err) + } + if !bytes.Equal(got, existing) { + t.Errorf("existing file was overwritten on failed download") + } +} + +func TestDownloadModelProgress(t *testing.T) { + content := bytes.Repeat([]byte("x"), 4096) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(content))) + _, _ = w.Write(content) + })) + defer srv.Close() + + var progress bytes.Buffer + dest := filepath.Join(t.TempDir(), "model.json") + if _, err := downloadModel(srv.URL, dest, "", &progress); err != nil { + t.Fatalf("downloadModel: %v", err) + } + out := progress.String() + if !strings.Contains(out, "Downloading model:") { + t.Errorf("progress output missing header: %q", out) + } + if !strings.Contains(out, "(100%)") { + t.Errorf("progress output missing final percentage: %q", out) + } + if !strings.HasSuffix(out, "\n") { + t.Errorf("progress output should end with newline: %q", out) + } +} + +func TestProgressWriterUnknownTotal(t *testing.T) { + var buf bytes.Buffer + pw := newProgressWriter(&buf, -1) + if _, err := pw.Write(bytes.Repeat([]byte("y"), 2048)); err != nil { + t.Fatalf("Write: %v", err) + } + pw.finish() + out := buf.String() + if !strings.Contains(out, "Downloading model: 0.0 MB") { + t.Errorf("progress output = %q, want byte count without percentage", out) + } + if strings.Contains(out, "%") { + t.Errorf("progress output should not contain percentage when total unknown: %q", out) + } +} + +func TestProgressWriterNilWriter(t *testing.T) { + pw := newProgressWriter(nil, 100) + if _, err := pw.Write([]byte("data")); err != nil { + t.Fatalf("Write with nil writer: %v", err) + } + pw.finish() +} + +func TestFileSHA256(t *testing.T) { + content := []byte("checksum me") + path := filepath.Join(t.TempDir(), "file.txt") + if err := os.WriteFile(path, content, 0644); err != nil { + t.Fatalf("write file: %v", err) + } + + sum, err := FileSHA256(path) + if err != nil { + t.Fatalf("FileSHA256: %v", err) + } + if want := sha256Hex(content); sum != want { + t.Errorf("FileSHA256 = %s, want %s", sum, want) + } + + if _, err := FileSHA256(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Error("expected error for missing file, got nil") + } +} + +func TestDefaultModelPath(t *testing.T) { + path := DefaultModelPath() + if filepath.Base(path) != "model.json" { + t.Errorf("DefaultModelPath = %q, want model.json basename", path) + } + if filepath.Dir(path) != ModelDir() { + t.Errorf("DefaultModelPath dir = %q, want %q", filepath.Dir(path), ModelDir()) + } +} diff --git a/go.mod b/go.mod index f4f0bbf..f040291 100644 --- a/go.mod +++ b/go.mod @@ -2,14 +2,14 @@ module github.com/happyhackingspace/dit go 1.26.0 -toolchain go1.26.9 +toolchain go1.26.10 require ( github.com/PuerkitoBio/goquery v1.13.0 github.com/chromedp/chromedp v0.16.0 github.com/creativeprojects/go-selfupdate v1.6.0 github.com/spf13/cobra v1.10.2 - golang.org/x/net v0.59.0 + golang.org/x/net v0.62.0 ) require ( @@ -34,9 +34,9 @@ require ( github.com/spf13/pflag v1.0.9 // indirect github.com/ulikunitz/xz v0.5.15 // indirect gitlab.com/gitlab-org/api/client-go v1.46.0 // indirect - golang.org/x/crypto v0.57.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sys v0.49.0 // indirect golang.org/x/time v0.15.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 321555e..1b6a7f9 100644 --- a/go.sum +++ b/go.sum @@ -77,23 +77,23 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 501fdd8..39f79c2 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -53,6 +53,7 @@ func (c *CLI) setupCommands() { c.rootCmd.AddCommand(c.newEvaluateCommand()) c.rootCmd.AddCommand(c.newUpCommand()) c.rootCmd.AddCommand(c.newDataCommand()) + c.rootCmd.AddCommand(c.newModelCommand()) } // Run executes the CLI and returns any error. diff --git a/internal/cli/data.go b/internal/cli/data.go index acf6168..597d2c8 100644 --- a/internal/cli/data.go +++ b/internal/cli/data.go @@ -117,26 +117,9 @@ func dataDownload(dataFolder string) error { slog.Info("Training data extracted", "files", count, "folder", dataFolder) slog.Info("Downloading model", "url", dit.ModelURL) - modelResp, err := http.Get(dit.ModelURL) - if err != nil { - return fmt.Errorf("download model: %w", err) - } - defer func() { _ = modelResp.Body.Close() }() - if modelResp.StatusCode != http.StatusOK { - return fmt.Errorf("download model: HTTP %d", modelResp.StatusCode) - } - - mf, err := os.Create("model.json") - if err != nil { - return fmt.Errorf("create model.json: %w", err) - } - written, err := io.Copy(mf, modelResp.Body) - if err != nil { - _ = mf.Close() - return fmt.Errorf("write model.json: %w", err) + if err := dit.Download("model.json"); err != nil { + return err } - _ = mf.Close() - slog.Info("Model downloaded", "size", fmt.Sprintf("%.1fMB", float64(written)/1024/1024)) return nil } diff --git a/internal/cli/model.go b/internal/cli/model.go new file mode 100644 index 0000000..ba0282e --- /dev/null +++ b/internal/cli/model.go @@ -0,0 +1,103 @@ +package cli + +import ( + "fmt" + "io" + "log/slog" + "os" + + "github.com/happyhackingspace/dit" + "github.com/spf13/cobra" +) + +func (c *CLI) newModelCommand() *cobra.Command { + modelCmd := &cobra.Command{ + Use: "model", + Short: "Manage the pretrained model cache", + Run: func(cmd *cobra.Command, args []string) { + _ = cmd.Help() + }, + } + + var force bool + pullCmd := &cobra.Command{ + Use: "pull", + Short: "Download the pretrained model to the local cache", + Example: ` dit model pull + dit model pull --force`, + RunE: func(cmd *cobra.Command, args []string) error { + return modelPull(os.Stdout, dit.DefaultModelPath(), force) + }, + } + pullCmd.Flags().BoolVar(&force, "force", false, "Re-download even if the model is already cached") + + statusCmd := &cobra.Command{ + Use: "status", + Short: "Show the cached model's path, size, and SHA-256 checksum", + RunE: func(cmd *cobra.Command, args []string) error { + return modelStatus(os.Stdout, dit.DefaultModelPath()) + }, + } + + rmCmd := &cobra.Command{ + Use: "rm", + Short: "Remove the cached model", + RunE: func(cmd *cobra.Command, args []string) error { + return modelRm(os.Stdout, dit.DefaultModelPath()) + }, + } + + modelCmd.AddCommand(pullCmd, statusCmd, rmCmd) + return modelCmd +} + +// modelPull downloads the pretrained model to dest unless it is already +// present; force re-downloads unconditionally. +func modelPull(w io.Writer, dest string, force bool) error { + if !force { + if _, err := os.Stat(dest); err == nil { + if _, err := fmt.Fprintf(w, "Model already cached at %s (use --force to re-download)\n", dest); err != nil { + return err + } + return modelStatus(w, dest) + } + } + slog.Info("Downloading model", "url", dit.ModelURL, "dest", dest, "size", "~93MB") + if err := dit.Download(dest); err != nil { + return err + } + return modelStatus(w, dest) +} + +// modelStatus prints the model file's path, existence, size, and SHA-256 +// checksum. +func modelStatus(w io.Writer, path string) error { + info, err := os.Stat(path) + if os.IsNotExist(err) { + _, werr := fmt.Fprintf(w, "path: %s\nexists: false\n", path) + return werr + } + if err != nil { + return fmt.Errorf("stat model: %w", err) + } + sum, err := dit.FileSHA256(path) + if err != nil { + return fmt.Errorf("checksum model: %w", err) + } + _, err = fmt.Fprintf(w, "path: %s\nexists: true\nsize: %.1f MB (%d bytes)\nsha256: %s\n", + path, float64(info.Size())/1024/1024, info.Size(), sum) + return err +} + +// modelRm removes the cached model file if it exists. +func modelRm(w io.Writer, path string) error { + if _, err := os.Stat(path); os.IsNotExist(err) { + _, werr := fmt.Fprintf(w, "No cached model at %s\n", path) + return werr + } + if err := os.Remove(path); err != nil { + return fmt.Errorf("remove model: %w", err) + } + _, err := fmt.Fprintf(w, "Removed %s\n", path) + return err +} diff --git a/internal/cli/model_test.go b/internal/cli/model_test.go new file mode 100644 index 0000000..3108a40 --- /dev/null +++ b/internal/cli/model_test.go @@ -0,0 +1,107 @@ +package cli + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestModelStatusMissing(t *testing.T) { + path := filepath.Join(t.TempDir(), "model.json") + var buf bytes.Buffer + if err := modelStatus(&buf, path); err != nil { + t.Fatalf("modelStatus: %v", err) + } + out := buf.String() + if !strings.Contains(out, "path: "+path) { + t.Errorf("output missing path: %q", out) + } + if !strings.Contains(out, "exists: false") { + t.Errorf("output missing exists false: %q", out) + } + if strings.Contains(out, "sha256") { + t.Errorf("output should not contain checksum for missing file: %q", out) + } +} + +func TestModelStatusExisting(t *testing.T) { + content := []byte(`{"model":"test"}`) + path := filepath.Join(t.TempDir(), "model.json") + if err := os.WriteFile(path, content, 0644); err != nil { + t.Fatalf("write model: %v", err) + } + + var buf bytes.Buffer + if err := modelStatus(&buf, path); err != nil { + t.Fatalf("modelStatus: %v", err) + } + out := buf.String() + if !strings.Contains(out, "exists: true") { + t.Errorf("output missing exists true: %q", out) + } + if !strings.Contains(out, fmt.Sprintf("(%d bytes)", len(content))) { + t.Errorf("output missing byte size: %q", out) + } + sum := sha256.Sum256(content) + if !strings.Contains(out, "sha256: "+hex.EncodeToString(sum[:])) { + t.Errorf("output missing checksum: %q", out) + } +} + +func TestModelRm(t *testing.T) { + path := filepath.Join(t.TempDir(), "model.json") + if err := os.WriteFile(path, []byte("data"), 0644); err != nil { + t.Fatalf("write model: %v", err) + } + + var buf bytes.Buffer + if err := modelRm(&buf, path); err != nil { + t.Fatalf("modelRm: %v", err) + } + if !strings.Contains(buf.String(), "Removed "+path) { + t.Errorf("output = %q, want removal message", buf.String()) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("file still exists after rm, stat err = %v", err) + } +} + +func TestModelRmMissing(t *testing.T) { + path := filepath.Join(t.TempDir(), "model.json") + var buf bytes.Buffer + if err := modelRm(&buf, path); err != nil { + t.Fatalf("modelRm on missing file: %v", err) + } + if !strings.Contains(buf.String(), "No cached model at "+path) { + t.Errorf("output = %q, want no-model message", buf.String()) + } +} + +func TestModelPullAlreadyCached(t *testing.T) { + content := []byte("cached model") + path := filepath.Join(t.TempDir(), "model.json") + if err := os.WriteFile(path, content, 0644); err != nil { + t.Fatalf("write model: %v", err) + } + + var buf bytes.Buffer + if err := modelPull(&buf, path, false); err != nil { + t.Fatalf("modelPull: %v", err) + } + out := buf.String() + if !strings.Contains(out, "already cached") { + t.Errorf("output = %q, want already-cached message", out) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read model: %v", err) + } + if !bytes.Equal(got, content) { + t.Errorf("cached model modified by pull without --force") + } +} diff --git a/internal/cli/up.go b/internal/cli/up.go index 77e7252..819b984 100644 --- a/internal/cli/up.go +++ b/internal/cli/up.go @@ -3,11 +3,8 @@ package cli import ( "context" "fmt" - "io" "log/slog" - "net/http" "os" - "path/filepath" "github.com/creativeprojects/go-selfupdate" "github.com/happyhackingspace/dit" @@ -62,21 +59,13 @@ func (c *CLI) selfUpdate() error { fmt.Printf("Updated to %s\n", latest.Version()) // Also refresh cached model - modelDest := filepath.Join(dit.ModelDir(), "model.json") + modelDest := dit.DefaultModelPath() if _, err := os.Stat(modelDest); err == nil { slog.Info("Updating cached model") - modelResp, err := http.Get(dit.ModelURL) - if err == nil { - defer func() { _ = modelResp.Body.Close() }() - if modelResp.StatusCode == http.StatusOK { - if err := os.MkdirAll(filepath.Dir(modelDest), 0755); err == nil { - if f, err := os.Create(modelDest); err == nil { - _, _ = io.Copy(f, modelResp.Body) - _ = f.Close() - slog.Info("Model updated") - } - } - } + if err := dit.Download(modelDest); err != nil { + slog.Warn("Model update failed", "error", err) + } else { + slog.Info("Model updated") } }