Files
MyGolandRelease/tools/preheat/main.go
T
zerorigin f5bfbac6c3 feat: 标准库文档批量预热——补全/悬停翻译秒出
懒翻译要等 1-2 秒。真 gopls 实证 go/doc 从本地源码提取的文档与
gopls 补全/悬停正文规范化空白后完全一致,批量预热方案成立:
- internal/godoc: go/doc 提取器 + 36 个常用标准库清单 + NormKey
- app.PreheatDocs: 6 并发翻译,进度走输出面板,已缓存自动跳过;
  菜单手动触发 + 打开项目 8 秒后自动跑(每会话一次)
- tools/preheat: 命令行批量工具,直接写用户缓存文件
- 缓存 key 统一 NormKey,预热/懒翻译/旧缓存三方互命中
- 已实测灌入 10 包 394 条译文(272 秒),常用包全部秒出
2026-11-04 17:30:51 +08:00

177 lines
4.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 一次性工具:命令行批量预热标准库文档翻译,直接写入用户缓存文件
//(%APPDATA%/mygoland/translations.json),IDE 启动装载后补全/悬停秒出中文。
//
// 用法:
//
// go run ./tools/preheat -key <APIKey> [-base <BaseURL>] [-model <Model>] [-only fmt,strings]
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"mygoland/internal/ai"
"mygoland/internal/godoc"
)
func main() {
key := flag.String("key", "", "API Key")
base := flag.String("base", "https://open.bigmodel.cn/api/paas/v4", "OpenAI 兼容接口地址")
model := flag.String("model", "glm-4-flash", "模型名")
only := flag.String("only", "", "只翻这些包(逗号分隔),空为全部常用包")
workers := flag.Int("workers", 6, "并发数")
flag.Parse()
if *key == "" {
fmt.Fprintln(os.Stderr, "需要 -key")
os.Exit(2)
}
cfg := ai.Config{BaseURL: *base, APIKey: *key, Model: *model}
cache := loadCache()
fmt.Printf("现有缓存 %d 条\n", len(cache))
pkgs := godoc.CommonPkgs
if *only != "" {
pkgs = splitCSV(*only)
}
// 收集待翻任务。
type task struct{ text string }
var tasks []task
pending := map[string]bool{}
for _, p := range pkgs {
docs, err := godoc.Docs(p)
if err != nil {
fmt.Printf("跳过 %s: %v\n", p, err)
continue
}
n := 0
for _, d := range docs {
k := godoc.NormKey(d)
if _, ok := cache[k]; ok || pending[k] {
continue
}
pending[k] = true
tasks = append(tasks, task{d})
n++
}
fmt.Printf("%-16s %3d 条文档,待翻 %d\n", p, len(docs), n)
}
fmt.Printf("共 %d 条待翻,%d 并发开始...\n", len(tasks), *workers)
start := time.Now()
idx := make(chan int)
var wg sync.WaitGroup
var mu sync.Mutex
okCount, failCount := 0, 0
for i := 0; i < *workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range idx {
text := tasks[j].text
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
tr, err := ai.TranslateDoc(ctx, cfg, text)
cancel()
if err != nil || tr == "" {
mu.Lock()
failCount++
mu.Unlock()
fmt.Printf("✗ %d/%d %v: %v\n", j+1, len(tasks), head(text), err)
continue
}
mu.Lock()
cache[godoc.NormKey(text)] = tr
okCount++
done := okCount
mu.Unlock()
if done%25 == 0 {
fmt.Printf("… %d/%d(%.0f 秒)\n", done, len(tasks), time.Since(start).Seconds())
}
}
}()
}
for j := range tasks {
idx <- j
}
close(idx)
wg.Wait()
saveCache(cache)
fmt.Printf("完成:成功 %d,失败 %d,缓存共 %d 条,耗时 %.0f 秒 → %s\n",
okCount, failCount, len(cache), time.Since(start).Seconds(), cachePath())
}
func splitCSV(s string) []string {
var out []string
for _, x := range splitComma(s) {
if x != "" {
out = append(out, x)
}
}
return out
}
func splitComma(s string) []string {
var out []string
cur := ""
for _, r := range s {
if r == ',' || r == ',' {
out = append(out, cur)
cur = ""
continue
}
cur += string(r)
}
return append(out, cur)
}
func head(s string) string {
r := []rune(s)
if len(r) > 30 {
return string(r[:30]) + "…"
}
return s
}
func cachePath() string {
base, err := os.UserConfigDir()
if err != nil {
panic(err)
}
return filepath.Join(base, "mygoland", "translations.json")
}
func loadCache() map[string]string {
b, err := os.ReadFile(cachePath())
if err != nil {
return map[string]string{}
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
fmt.Printf("旧缓存解析失败(忽略): %v\n", err)
return map[string]string{}
}
// 统一规范化 key。
out := map[string]string{}
for k, v := range m {
if k != "" && v != "" {
out[godoc.NormKey(k)] = v
}
}
return out
}
func saveCache(m map[string]string) {
_ = os.MkdirAll(filepath.Dir(cachePath()), 0o755)
b, _ := json.MarshalIndent(m, "", " ")
if err := os.WriteFile(cachePath(), b, 0o644); err != nil {
fmt.Printf("写入缓存失败: %v\n", err)
}
}