Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
pii: AstrLink Guard as a second local model (#3578)
yetone0db804999e51
diff --git a/internal/pii/astrlink.go b/internal/pii/astrlink.gonew file mode 100644index 000000000..edaeb4ba8--- /dev/null+++ b/internal/pii/astrlink.go@@ -0,0 +1,339 @@+package pii++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "sync"+ "sync/atomic"+ "time"++ "github.com/yetone/magpie/internal/appdir"+ "github.com/yetone/magpie/internal/pii/guard"+ "github.com/yetone/magpie/internal/redact"+)++// AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0) is the second+// local model: a 37 MB int8 token classifier for Chinese and English,+// run in magpie's own process by internal/pii/guard, on the CPU of every+// system, with nothing native to download. Its files are fetched from+// Hugging Face at the revision their sha256 were pinned at (the+// publisher's own listing), and are loaded on the first request that+// needs them and let go after idleAfter with none.++// guardRev is the repo's revision (v0.1.3) the files below were hashed at.+var guardRev = "7216b6a3b897ef903d4b1ba367ae6fb95b0fa5e4"++type pinned struct {+ path string // in the repo; saved under its base name+ size int64+ sha string+}++var guardFiles = []pinned{+ {"int8/model_int8.onnx", 330781, "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a"},+ {"int8/model_int8.onnx_data", 37124608, "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067"},+ {"int8/tokenizer.json", 1502881, "0cf3b235ef125658015a6c8026a5fe6f28088bf825101a990ec18a10200feef4"},+}++var guardBase = "https://huggingface.co/QuantumNous/astrlink-guard/resolve/"++func guardURL(f pinned) string { return guardBase + guardRev + "/" + f.path }++// guardRoot is where AstrLink Guard's files are kept, in magpie's cache+// beside Privacy Filter's folder: a folder per revision, and the found+// file (cache.go).+var guardRoot = func() string { return filepath.Join(appdir.Cache(), "astrlink-guard") }++func guardDir() string { return filepath.Join(guardRoot(), guardRev[:12]) }++func guardSize() int64 {+ var n int64+ for _, f := range guardFiles {+ n += f.size+ }+ return n+}++// guardInstalled says every file is on disk at its size.+func guardInstalled() bool {+ for _, f := range guardFiles {+ fi, err := os.Stat(filepath.Join(guardDir(), filepath.Base(f.path)))+ if err != nil || fi.Size() != f.size {+ return false+ }+ }+ return true+}++var gdl dlState++// guardInstall fetches the files not on disk yet, each checked against+// its sha256; done counts the bytes of all three.+func guardInstall(ctx context.Context) error {+ if err := os.MkdirAll(guardDir(), 0o755); err != nil {+ return err+ }+ var base int64+ for _, f := range guardFiles {+ path := filepath.Join(guardDir(), filepath.Base(f.path))+ if fi, err := os.Stat(path); err != nil || fi.Size() != f.size {+ var n atomic.Int64+ stop := make(chan struct{})+ go func() {+ t := time.NewTicker(200 * time.Millisecond)+ defer t.Stop()+ for {+ select {+ case <-stop:+ return+ case <-t.C:+ gdl.done.Store(base + n.Load())+ }+ }+ }()+ err := fetch(ctx, guardURL(f), path, f.size, f.sha, &n)+ close(stop)+ if err != nil {+ return fmt.Errorf("downloading %s: %w", filepath.Base(f.path), err)+ }+ }+ base += f.size+ gdl.done.Store(base)+ }+ removeOldGuard()+ return nil+}++// removeOldGuard deletes the folders of revisions pinned before.+func removeOldGuard() {+ es, _ := os.ReadDir(guardRoot())+ for _, e := range es {+ if e.IsDir() && e.Name() != filepath.Base(guardDir()) {+ os.RemoveAll(filepath.Join(guardRoot(), e.Name()))+ }+ }+}++// gsrv is AstrLink Guard, loaded, and why it failed; mu is never held+// while it loads or reads.+var gsrv struct {+ mu sync.Mutex+ m spanFinder+ gen int // counts the unloads+ loadMS int+ loading bool+ idle *time.Timer+ failed string+ lastErr error+ fails int+ retryAt time.Time+}++// spanFinder is the model, loaded (*guard.Model).+type spanFinder interface{ Find(text string) []guard.Span }++// guardLoad reads the model; a var for tests.+var guardLoad = func(dir string) (spanFinder, error) {+ m, err := guard.Load(dir)+ if err != nil {+ return nil, err+ }+ return m, nil+}++// guardTurn is held by the one request the model reads.+var guardTurn = make(chan struct{}, 1)++var guardBackend = &backend{+ turn: guardTurn,+ waiting: new(atomic.Int32),+ cache: newLRU(20000),+ disk: new(diskState),+ path: func() string { return filepath.Join(guardRoot(), "found-"+guardRev[:12]+".bin") },+ classify: guardClassify,+ heldBack: guardHeldBack,+}++// guardClassify is what the model finds in texts, loaded if it isn't.+// The caller holds the backend's turn.+func guardClassify(texts []string) ([][]redact.Found, error) {+ out, err := guardClassifyTurn(texts)+ gsrv.mu.Lock()+ gsrv.failed = ""+ switch {+ case err == nil:+ gsrv.lastErr, gsrv.fails, gsrv.retryAt = nil, 0, time.Time{}+ case err == ErrNotInstalled:+ // not a model that failed: tried again once it is downloaded+ gsrv.failed = err.Error()+ default:+ gsrv.failed, gsrv.lastErr = err.Error(), err+ gsrv.fails+++ gsrv.retryAt = time.Now().Add(retryAfter(gsrv.fails))+ }+ gsrv.mu.Unlock()+ return out, err+}++func guardClassifyTurn(texts []string) ([][]redact.Found, error) {+ gsrv.mu.Lock()+ m, gen := gsrv.m, gsrv.gen+ if m == nil {+ gsrv.loading = true+ }+ gsrv.mu.Unlock()+ if m == nil {+ if !guardInstalled() {+ gsrv.mu.Lock()+ gsrv.loading = false+ gsrv.mu.Unlock()+ return nil, ErrNotInstalled+ }+ t := time.Now()+ var err error+ m, err = guardLoad(guardDir())+ gsrv.mu.Lock()+ gsrv.loading = false+ if err == nil && gsrv.gen == gen {+ gsrv.m, gsrv.loadMS = m, int(time.Since(t)/time.Millisecond)+ }+ gsrv.mu.Unlock()+ if err != nil {+ return nil, fmt.Errorf("the local masking model didn't load: %w", err)+ }+ }+ out := make([][]redact.Found, len(texts))+ for i, t := range texts {+ for _, s := range m.Find(t) {+ out[i] = append(out[i], redact.Found{Start: s.Start, End: s.End, Label: guardLabel(s.Label)})+ }+ }+ gsrv.mu.Lock()+ if gsrv.gen == gen && gsrv.m != nil { // not stopped meanwhile+ if gsrv.idle != nil {+ gsrv.idle.Stop()+ }+ gsrv.idle = time.AfterFunc(idleAfter, guardIdle)+ }+ gsrv.mu.Unlock()+ return out, nil+}++// guardIdle lets the model go after idleAfter with no request, unless+// one is on it now (it sets the timer again when done).+func guardIdle() {+ select {+ case guardTurn <- struct{}{}:+ defer func() { <-guardTurn }()+ default:+ return+ }+ guardUnload()+}++func guardUnload() {+ gsrv.mu.Lock()+ if gsrv.idle != nil {+ gsrv.idle.Stop()+ gsrv.idle = nil+ }+ gsrv.m = nil+ gsrv.gen+++ gsrv.mu.Unlock()+}++// guardLabels names the model's labels as Privacy Filter does, which is+// what redact's Model reads: url, ip_address and private_date are left+// out there as they are for Privacy Filter (an address the rules don't+// mask is in a request for the vendor to read).+var guardLabels = map[string]string{+ "private_person": "private_person",+ "private_address": "private_address",+ "phone": "private_phone",+ "email": "private_email",+ "account": "account_number",+ "payment_card": "account_number",+ "common_secret": "secret",+ "url": "private_url",+ "ip_address": "ip_address",+ "private_date": "private_date",+}++func guardLabel(l string) string {+ if n, ok := guardLabels[l]; ok {+ return n+ }+ return l+}++func guardHeldBack() error {+ gsrv.mu.Lock()+ defer gsrv.mu.Unlock()+ if gsrv.lastErr == nil || !time.Now().Before(gsrv.retryAt) {+ return nil+ }+ return fmt.Errorf("%w; it is tried again in %s, and until then a request it hasn't read is held back at once. To send requests masked by the rules alone, turn the model off in Settings → Privacy",+ gsrv.lastErr, time.Until(gsrv.retryAt).Round(time.Second))+}++// guardModel is AstrLink Guard as a Model.+type guardModel struct{}++func (guardModel) ID() string { return AstrLinkGuard }++func (guardModel) Supported() bool { return true }++func (guardModel) Installed() bool { return guardInstalled() }++func (guardModel) Size() int64 { return guardSize() }++func (guardModel) Find(ctx context.Context, texts []string) ([][]redact.Found, error) {+ return guardBackend.find(ctx, texts)+}++func (guardModel) Now() Status {+ s := Status{Model: AstrLinkGuard, Supported: true, Installed: guardInstalled(), Size: guardSize()}+ gdl.fill(&s)+ gsrv.mu.Lock()+ if gsrv.m != nil {+ s.Running, s.Device, s.LoadMS = true, "CPU", gsrv.loadMS+ }+ s.Failed, s.Loading = gsrv.failed, gsrv.loading+ gsrv.mu.Unlock()+ s.Waiting = int(guardBackend.waiting.Load())+ return s+}++func (guardModel) Download(done func()) error { return gdl.run(guardSize(), guardInstall, done) }++func (guardModel) Cancel() { gdl.stop() }++func (guardModel) Warm() {+ if guardInstalled() {+ go func() {+ guardBackend.turn <- struct{}{}+ defer func() { <-guardBackend.turn }()+ guardClassify([]string{"warm"})+ }()+ }+}++// Stop lets the model go at once; a request reading it finishes with the+// model it has.+func (guardModel) Stop() {+ guardUnload()+ gsrv.mu.Lock()+ gsrv.lastErr, gsrv.fails, gsrv.retryAt = nil, 0, time.Time{}+ gsrv.mu.Unlock()+}++func (g guardModel) Remove() error {+ g.Cancel()+ g.Stop()+ gdl.mu.Lock()+ gdl.err = ""+ gdl.mu.Unlock()+ return os.RemoveAll(guardRoot())+}diff --git a/internal/pii/astrlink_test.go b/internal/pii/astrlink_test.gonew file mode 100644index 000000000..951e370da--- /dev/null+++ b/internal/pii/astrlink_test.go@@ -0,0 +1,326 @@+package pii++import (+ "context"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/pii/guard"+ "github.com/yetone/magpie/internal/redact"+)++// guardSandbox gives AstrLink Guard a folder of the test's own, and+// puts back what the test changed.+func guardSandbox(t *testing.T) string {+ t.Helper()+ d := t.TempDir()+ wasRoot, wasFiles, wasBase, wasLoad, wasIdle := guardRoot, guardFiles, guardBase, guardLoad, idleAfter+ wasDir := dir+ guardRoot = func() string { return filepath.Join(d, "astrlink-guard") }+ dir = func() string { return filepath.Join(d, "privacy-filter") }+ t.Cleanup(func() {+ guardModel{}.Cancel()+ guardModel{}.Stop()+ for deadline := time.Now().Add(30 * time.Second); (guardModel{}).Now().Downloading && time.Now().Before(deadline); {+ time.Sleep(10 * time.Millisecond)+ }+ guardBackend.disk.mu.Lock()+ if guardBackend.disk.timer != nil && guardBackend.disk.timer.Stop() {+ guardBackend.disk.saves.Done()+ }+ guardBackend.disk.timer, guardBackend.disk.loaded = nil, ""+ guardBackend.disk.mu.Unlock()+ guardBackend.disk.saves.Wait()+ guardBackend.cache.mu.Lock()+ guardBackend.cache.ll.Init()+ clear(guardBackend.cache.m)+ guardBackend.cache.mu.Unlock()+ gsrv.mu.Lock()+ gsrv.failed, gsrv.loadMS = "", 0+ gsrv.mu.Unlock()+ guardRoot, guardFiles, guardBase, guardLoad, idleAfter = wasRoot, wasFiles, wasBase, wasLoad, wasIdle+ dir = wasDir+ })+ return d+}++// fakeGuardFiles puts files of the pinned sizes where the model goes.+func fakeGuardFiles(t *testing.T) {+ t.Helper()+ guardFiles = []pinned{{"int8/model_int8.onnx", 3, "x"}, {"int8/model_int8.onnx_data", 5, "x"}, {"int8/tokenizer.json", 2, "x"}}+ os.MkdirAll(guardDir(), 0o755)+ for _, f := range guardFiles {+ if err := os.WriteFile(filepath.Join(guardDir(), filepath.Base(f.path)), make([]byte, f.size), 0o644); err != nil {+ t.Fatal(err)+ }+ }+}++// fakeFinder finds each word of its map in a text, by the model's own+// label, and counts the texts it read.+type fakeFinder struct {+ words map[string]string+ reads *atomic.Int32+}++func (f fakeFinder) Find(text string) []guard.Span {+ f.reads.Add(1)+ var out []guard.Span+ for w, l := range f.words {+ if i := strings.Index(text, w); i >= 0 {+ out = append(out, guard.Span{Start: i, End: i + len(w), Label: l, Score: 0.99})+ }+ }+ return out+}++func TestChoose(t *testing.T) {+ guardSandbox(t)+ for _, c := range []struct {+ name string+ on bool+ want string+ }{+ {"", false, AstrLinkGuard}, // a new user+ {"", true, PrivacyFilter}, // had Privacy Filter on before there was a choice+ {AstrLinkGuard, true, AstrLinkGuard}, // picked+ {PrivacyFilter, false, PrivacyFilter}, // picked+ {"something-else", false, AstrLinkGuard},+ } {+ if got := Choose(c.name, c.on); got != c.want {+ t.Errorf("Choose(%q, %v) = %q, want %q", c.name, c.on, got, c.want)+ }+ }+ // Privacy Filter downloaded and turned off: turning the model on+ // again uses it, rather than download another+ os.MkdirAll(dir(), 0o755)+ os.WriteFile(modelPath(), make([]byte, 1), 0o644)+ wasSize := modelSize+ modelSize = 1+ defer func() { modelSize = wasSize }()+ os.MkdirAll(serveDir(), 0o755)+ os.WriteFile(exe("pf-serve"), []byte("x"), 0o755)+ if got := Choose("", false); got != PrivacyFilter {+ t.Errorf("with Privacy Filter on disk, Choose = %q", got)+ }+}++func TestOfAndModels(t *testing.T) {+ if Of(PrivacyFilter).ID() != PrivacyFilter || Of(AstrLinkGuard).ID() != AstrLinkGuard {+ t.Fatal("Of names the wrong model")+ }+ ms := Models()+ if len(ms) != 2 || ms[0].ID() != PrivacyFilter || ms[1].ID() != AstrLinkGuard {+ t.Fatalf("Models = %v", ms)+ }+ if !Of(AstrLinkGuard).Supported() {+ t.Fatal("AstrLink Guard runs in Go everywhere")+ }+ if got := Of(AstrLinkGuard).Size(); got != 330781+37124608+1502881 {+ t.Fatalf("size = %d", got)+ }+}++// What AstrLink Guard finds reaches redact under Privacy Filter's labels,+// which are the ones redact's Model masks; a text read once is not read+// again.+func TestGuardFindsUnderRedactsLabels(t *testing.T) {+ guardSandbox(t)+ fakeGuardFiles(t)+ var reads, loads atomic.Int32+ guardLoad = func(string) (spanFinder, error) {+ loads.Add(1)+ return fakeFinder{map[string]string{"13800138000": "phone", "张三": "private_person", "sk-abc": "common_secret", "6222020200112233445": "payment_card", "https://a.example": "url"}, &reads}, nil+ }+ texts := []string{"张三的电话是13800138000", "key sk-abc", "卡号 6222020200112233445 https://a.example", "nothing"}+ got, err := Of(AstrLinkGuard).Find(context.Background(), texts)+ if err != nil {+ t.Fatal(err)+ }+ labels := func(fs []redact.Found) map[string]bool {+ m := map[string]bool{}+ for _, f := range fs {+ m[f.Label] = true+ }+ return m+ }+ if l := labels(got[0]); !l["private_phone"] || !l["private_person"] || len(l) != 2 {+ t.Errorf("text 0: %v", got[0])+ }+ if l := labels(got[1]); !l["secret"] || len(l) != 1 {+ t.Errorf("text 1: %v", got[1])+ }+ if l := labels(got[2]); !l["account_number"] || !l["private_url"] || len(l) != 2 {+ t.Errorf("text 2: %v", got[2])+ }+ if len(got[3]) != 0 {+ t.Errorf("text 3: %v", got[3])+ }+ if f := got[0][0]; texts[0][f.Start:f.End] != "张三" && texts[0][f.Start:f.End] != "13800138000" {+ t.Errorf("span %v is %q", f, texts[0][f.Start:f.End])+ }+ n := reads.Load()+ if _, err := Of(AstrLinkGuard).Find(context.Background(), texts); err != nil {+ t.Fatal(err)+ }+ if reads.Load() != n || loads.Load() != 1 {+ t.Fatalf("asked again: %d reads, %d loads", reads.Load()-n, loads.Load())+ }+ st := Of(AstrLinkGuard).Now()+ if st.Model != AstrLinkGuard || !st.Installed || !st.Running || st.Device != "CPU" {+ t.Fatalf("Now = %+v", st)+ }+ if pst := Of(PrivacyFilter).Now(); pst.Model != PrivacyFilter || pst.Running {+ t.Fatalf("Privacy Filter's Now = %+v", pst)+ }+}++// One whose files aren't on disk fails, rather than mask by the rules+// alone; one that didn't load is held back at once until it is tried+// again.+func TestGuardNotInstalledAndHeldBack(t *testing.T) {+ guardSandbox(t)+ if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"a"}); err != ErrNotInstalled {+ t.Fatalf("err = %v", err)+ }+ fakeGuardFiles(t)+ var loads atomic.Int32+ guardLoad = func(string) (spanFinder, error) {+ loads.Add(1)+ return nil, os.ErrInvalid+ }+ if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"b"}); err == nil {+ t.Fatal("a model that didn't load answered")+ }+ _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"c"})+ if err == nil || !strings.Contains(err.Error(), "tried again in") || loads.Load() != 1 {+ t.Fatalf("err = %v after %d loads", err, loads.Load())+ }+ if st := Of(AstrLinkGuard).Now(); st.Failed == "" {+ t.Fatalf("Now = %+v", st)+ }+ Of(AstrLinkGuard).Stop() // turned off and on: tried at once+ if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"d"}); err == nil || loads.Load() != 2 {+ t.Fatalf("err = %v after %d loads", err, loads.Load())+ }+}++// The model is let go after idleAfter with no request, and loaded again+// by the next.+func TestGuardLetGoWhenIdle(t *testing.T) {+ guardSandbox(t)+ fakeGuardFiles(t)+ idleAfter = 20 * time.Millisecond+ var reads, loads atomic.Int32+ guardLoad = func(string) (spanFinder, error) {+ loads.Add(1)+ return fakeFinder{nil, &reads}, nil+ }+ if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"one"}); err != nil {+ t.Fatal(err)+ }+ for deadline := time.Now().Add(10 * time.Second); Of(AstrLinkGuard).Now().Running; time.Sleep(5 * time.Millisecond) {+ if time.Now().After(deadline) {+ t.Fatal("still loaded")+ }+ }+ if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"two"}); err != nil || loads.Load() != 2 {+ t.Fatalf("err = %v, %d loads", err, loads.Load())+ }+}++// Download fetches each file, checked against its pin, from the+// publisher's address at the pinned revision; a file whose bytes don't+// match is not kept.+func TestGuardDownload(t *testing.T) {+ guardSandbox(t)+ body := map[string][]byte{"/r/aaaabbbbcccc1/int8/model_int8.onnx": []byte("graph"), "/r/aaaabbbbcccc1/int8/model_int8.onnx_data": []byte("weights!"), "/r/aaaabbbbcccc1/int8/tokenizer.json": []byte("{}")}+ f := &files{m: map[string][]byte{}}+ for k, v := range body {+ f.m[k] = v+ }+ s := httptest.NewServer(f)+ defer s.Close()+ wasRev := guardRev+ defer func() { guardRev = wasRev }()+ guardRev, guardBase = "aaaabbbbcccc1", s.URL+"/r/"+ guardFiles = nil+ for _, p := range []string{"int8/model_int8.onnx", "int8/model_int8.onnx_data", "int8/tokenizer.json"} {+ b := body["/r/aaaabbbbcccc1/"+p]+ guardFiles = append(guardFiles, pinned{p, int64(len(b)), sum(b)})+ }+ // a folder of a revision pinned before goes once this one is in+ os.MkdirAll(filepath.Join(guardRoot(), "old"), 0o755)+ wait := func() Status {+ t.Helper()+ done := make(chan struct{})+ if err := Of(AstrLinkGuard).Download(func() { close(done) }); err != nil {+ t.Fatal(err)+ }+ for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) {+ select {+ case <-done:+ return Of(AstrLinkGuard).Now()+ default:+ }+ st := Of(AstrLinkGuard).Now()+ if !st.Downloading && st.Error != "" {+ return st+ }+ if time.Now().After(deadline) {+ t.Fatalf("not done: %+v", st)+ }+ }+ }+ // the server's data file isn't the one pinned+ good := body["/r/aaaabbbbcccc1/int8/model_int8.onnx_data"]+ f.mu.Lock()+ f.m["/r/aaaabbbbcccc1/int8/model_int8.onnx_data"] = []byte("weights?")+ f.mu.Unlock()+ if st := wait(); !strings.Contains(st.Error, "checksum") || st.Installed {+ t.Fatalf("a file that doesn't match its pin: %+v", st)+ }+ f.mu.Lock()+ f.m["/r/aaaabbbbcccc1/int8/model_int8.onnx_data"] = good+ f.mu.Unlock()+ st := wait()+ if st.Error != "" || !st.Installed || st.Done != st.Total || st.Total != int64(len("graph")+len("weights!")+len("{}")) {+ t.Fatalf("Now = %+v", st)+ }+ if b, _ := os.ReadFile(filepath.Join(guardDir(), "model_int8.onnx_data")); string(b) != "weights!" {+ t.Fatalf("data = %q", b)+ }+ if _, err := os.Stat(filepath.Join(guardRoot(), "old")); err == nil {+ t.Fatal("the older revision's folder was left")+ }+ if err := Of(AstrLinkGuard).Remove(); err != nil || Of(AstrLinkGuard).Installed() {+ t.Fatalf("Remove: %v", err)+ }+}++// TestGuardFilesAreThePublishers checks each pinned file against the+// int8 lines of the publisher's own SHA256SUMS at guardRev (kept in+// testdata): its path in the repo and its sha256. A path the repo+// doesn't have is a 404 on every user's download.+func TestGuardFilesAreThePublishers(t *testing.T) {+ b, err := os.ReadFile(filepath.Join("testdata", "astrlink-SHA256SUMS"))+ if err != nil {+ t.Fatal(err)+ }+ sums := map[string]string{}+ for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") {+ if sha, path, ok := strings.Cut(l, " "); ok {+ sums[path] = sha+ }+ }+ for _, f := range guardFiles {+ if sums[f.path] != f.sha {+ t.Errorf("%s: pinned %s, the publisher lists %q", f.path, f.sha, sums[f.path])+ }+ }+}diff --git a/internal/pii/pii.go b/internal/pii/pii.goindex 6cfa14299..26a6f9aca 100644--- a/internal/pii/pii.go+++ b/internal/pii/pii.go@@ -21,6 +21,7 @@package piiimport (+ "context""errors""os""path/filepath"@@ -28,6 +29,7 @@ import ("time""github.com/yetone/magpie/internal/appdir"+ "github.com/yetone/magpie/internal/redact")// The model, at a revision of LocalAI's repo, so the file is always the@@ -112,9 +114,10 @@ var ErrNotInstalled = errors.New("the local masking model isn't downloaded; down// Status is what Settings → Privacy shows of the model.type Status struct {- Supported bool `json:"supported"`- Installed bool `json:"installed"`- Size int64 `json:"size"`+ Model string `json:"model"`+ Supported bool `json:"supported"`+ Installed bool `json:"installed"`+ Size int64 `json:"size"`// a download under way, or the last one's errorDownloading bool `json:"downloading,omitempty"`Done int64 `json:"done,omitempty"`@@ -137,7 +140,7 @@ type Status struct {// Now is the model's status.func Now() Status {- s := Status{Supported: Supported(), Installed: Installed(), Size: modelSize}+ s := Status{Model: PrivacyFilter, Supported: Supported(), Installed: Installed(), Size: modelSize}dl.fill(&s)srv.mu.Lock()if srv.h != nil {@@ -162,5 +165,77 @@ func Remove() error {return os.RemoveAll(dir())}+// The local models Settings → Privacy offers, by the id the settings keep+// (settings.RedactModelName).+const (+ PrivacyFilter = "privacy-filter"+ AstrLinkGuard = "astrlink-guard"+)++// Model is one local model.+type Model interface {+ ID() string+ Supported() bool+ Installed() bool+ // Size is how much turning it on downloads.+ Size() int64+ Find(ctx context.Context, texts []string) ([][]redact.Found, error)+ Now() Status+ // Download fetches it in the background and calls done once it is on+ // disk; Cancel stops that.+ Download(done func()) error+ Cancel()+ // Warm loads it in the background, where it is on disk.+ Warm()+ // Stop lets it go; Remove stops it and deletes it.+ Stop()+ Remove() error+}++// Models are the local models, Privacy Filter first.+func Models() []Model { return []Model{pfModel{}, guardModel{}} }++// Of is the model id names; AstrLink Guard's for an id there's none of.+func Of(id string) Model {+ if id == PrivacyFilter {+ return pfModel{}+ }+ return guardModel{}+}++// Choose is the model masking uses: the one the user picked (name);+// with none picked, Privacy Filter where it was turned on (on) or+// downloaded before there was a choice, so its user keeps the model they+// had and downloads nothing; else AstrLink Guard, a 38 MB download that+// runs on every CPU and, measured on code (docs/subsystems), masks far+// fewer ordinary values.+func Choose(name string, on bool) string {+ switch name {+ case PrivacyFilter, AstrLinkGuard:+ return name+ }+ if on || Installed() {+ return PrivacyFilter+ }+ return AstrLinkGuard+}++// pfModel is Privacy Filter as a Model.+type pfModel struct{}++func (pfModel) ID() string { return PrivacyFilter }+func (pfModel) Supported() bool { return Supported() }+func (pfModel) Installed() bool { return Installed() }+func (pfModel) Size() int64 { return Size() }+func (pfModel) Now() Status { return Now() }+func (pfModel) Download(done func()) error { return Download(done) }+func (pfModel) Cancel() { Cancel() }+func (pfModel) Warm() { Warm() }+func (pfModel) Stop() { Stop() }+func (pfModel) Remove() error { return Remove() }+func (pfModel) Find(ctx context.Context, texts []string) ([][]redact.Found, error) {+ return FindContext(ctx, texts)+}+// idleAfter is how long pf-serve runs with no request before it is ended.var idleAfter = 10 * time.Minutediff --git a/internal/pii/testdata/astrlink-SHA256SUMS b/internal/pii/testdata/astrlink-SHA256SUMSnew file mode 100644index 000000000..b9c1d94e3--- /dev/null+++ b/internal/pii/testdata/astrlink-SHA256SUMS@@ -0,0 +1,9 @@+9aedf1796c122cab7541844d2e1956abdce08001319236767efb00869b736de5 int8/CHECKSUMS.json+fce00fb8de579f06fb31e86bd50ddc3ab1c9a9163b19d38ba6b09313964d2210 int8/astrlink-model.json+2c20003590d642e273c03c4c7c82d9849fa75f64bf29a71ec0a0c9a20ba4a150 int8/config.json+880cf75052409cd63f6cb234086a3f77f2bc0523197ee417331555fd0609c191 int8/label_mapping.json+1a81b6cdcedbc8481b956109df303a84fbbef84cc2229bf3a26c80237dc1f120 int8/labels.json+0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a int8/model_int8.onnx+0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067 int8/model_int8.onnx_data+0cf3b235ef125658015a6c8026a5fe6f28088bf825101a990ec18a10200feef4 int8/tokenizer.json+3a7cf4d70bb7c0376f18cc6ad23c143853de5b4478084c414d5dbbd35ea5c589 int8/tokenizer_config.jsondiff --git a/internal/source/china_test.go b/internal/source/china_test.goindex b2feab8fa..734c31281 100644--- a/internal/source/china_test.go+++ b/internal/source/china_test.go@@ -34,9 +34,11 @@ func TestChinaFirst(t *testing.T) {"https://raw.githubusercontent.com/magpie-community/plugins/main/registry.json": "https://cdn.jsdelivr.net/gh/magpie-community/plugins@main/registry.json","https://huggingface.co/LocalAI-io/privacy-filter-GGUF/resolve/935d868/privacy-filter-q8.gguf": "https://hf-mirror.com/LocalAI-io/privacy-filter-GGUF/resolve/935d868/privacy-filter-q8.gguf",// no other model, and no page of Hugging Face's- "https://huggingface.co/someone/else/resolve/main/x.gguf": "",- "https://huggingface.co/LocalAI-io/privacy-filter-GGUF": "",- "https://huggingface.co/LocalAI-io/privacy-filter-GGUF/resolve/main/x?dl=1": "",+ "https://huggingface.co/someone/else/resolve/main/x.gguf": "",+ "https://huggingface.co/QuantumNous/astrlink-guard/resolve/7216b6a/int8/model_int8.onnx_data": "https://hf-mirror.com/QuantumNous/astrlink-guard/resolve/7216b6a/int8/model_int8.onnx_data",+ "https://huggingface.co/QuantumNous/other/resolve/7216b6a/x": "",+ "https://huggingface.co/LocalAI-io/privacy-filter-GGUF": "",+ "https://huggingface.co/LocalAI-io/privacy-filter-GGUF/resolve/main/x?dl=1": "",// npm's download counts are npmjs's own: npmmirror counts its own"https://api.npmjs.org/downloads/point/last-week/pkg": "",// nothing else of GitHub's: no proxy stands in for itdiff --git a/internal/source/source.go b/internal/source/source.goindex ba126271f..73ed64ffe 100644--- a/internal/source/source.go+++ b/internal/source/source.go@@ -40,7 +40,7 @@ var China = func() bool { return settings.Load().ChinaMirror }// "" when there is none. Only mirrors that serve the same bytes as the// official address: npmmirror for npm's registry and Bun's releases (whose// zips are checked against Bun's checksums all the same), jsDelivr for the-// community repo's plugin list, hf-mirror for the masking model. Never a proxy such as gh-proxy, which+// community repo's plugin list, hf-mirror for the masking models. Never a proxy such as gh-proxy, which// would hand magpie whatever it liked.func chinaFirst(raw string) string {u, err := url.Parse(raw)@@ -55,11 +55,13 @@ func chinaFirst(raw string) string {return bunMirror + "/" + rest}case "huggingface.co":- // the local masking model (internal/pii), at the revision its- // sha256 was pinned at: hf-mirror serves Hugging Face's files,- // and what it serves is checked against that pin- if strings.HasPrefix(u.EscapedPath(), "/LocalAI-io/privacy-filter-GGUF/resolve/") && u.RawQuery == "" {- return hfMirror + u.EscapedPath()+ // the local masking models (internal/pii), at the revision their+ // sha256 were pinned at: hf-mirror serves Hugging Face's files,+ // and what it serves is checked against those pins+ for _, repo := range []string{"/LocalAI-io/privacy-filter-GGUF/resolve/", "/QuantumNous/astrlink-guard/resolve/"} {+ if strings.HasPrefix(u.EscapedPath(), repo) && u.RawQuery == "" {+ return hfMirror + u.EscapedPath()+ }}case "raw.githubusercontent.com":// /magpie-community/plugins/<branch>/<path>