Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ kd 专注于简洁、高效、丝滑的查询功能,不会发展成集成式

- `kd --update`命令一键更新版本

- 英文标识符(驼峰、下划线)可拆词翻译,如`kd getUserByID`按`get user by id`查询(需开启配置`split_camelcase_and_snakecase`)

> 更多功能正在开发中 👽

## 🚀 安装和升级
Expand Down Expand Up @@ -203,6 +205,7 @@ GLOBAL OPTIONS:

说明:

- 开启`split_camelcase_and_snakecase`后,英文标识符式输入会自动拆词后翻译:驼峰如`getUserByID`拆为`get user by id`,下划线如`hello_world`拆为`hello world`。普通查询会先整串查询、未找到再拆分回退;`-t`长句会对句中出现的标识符同样拆分
- JSON模式直接输出数据库中raw data,key为简写,暂不打算优化为易读形式
- 查询进度仅用于交互式终端,并在正式结果输出前自动清除。现代终端显示完整动画,能力不明确或较旧的终端会降级为ASCII提示;JSON、管道和重定向输出不会混入动态状态

Expand All @@ -227,6 +230,10 @@ english_only = false
# 精简输出,去除英语解释和例句(可使用 --no-brief 参数临时关闭)
brief = false

# 查询英文标识符时先按驼峰/下划线拆词再翻译,如 helloWorld -> hello world;
# 偏编程场景,默认关闭,避免影响普通查询意图
split_camelcase_and_snakecase = false

# 音频缓存目录大小上限(MiB),默认2048(2 GiB);设为0时朗读后不保留音频
audio_cache_max_size_mb = 2048

Expand Down
4 changes: 4 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ type Config struct {
FreqAlert bool `toml:"freq_alert" default:"false"`
Brief bool `toml:"brief" default:"false"`
AudioCacheMaxSizeMB uint64 `toml:"audio_cache_max_size_mb" default:"2048"`

// SplitCamelcaseAndSnakecase 查询英文标识符时先按驼峰/下划线拆词再翻译(偏编程场景)。
SplitCamelcaseAndSnakecase bool `toml:"split_camelcase_and_snakecase" default:"false"`

// MaxCached uint `default:"10000" toml:"max_cached"`

Logging LoggerConfig `toml:"logging"`
Expand Down
20 changes: 14 additions & 6 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ func TestGenerateDefaultConfig(t *testing.T) {
}
if !strings.Contains(got, `theme = "temp"`) ||
!strings.Contains(got, "audio_cache_max_size_mb = 2048") ||
!strings.Contains(got, "split_camelcase_and_snakecase = false") ||
!strings.Contains(got, "[logging]") {
t.Fatalf("generated config is missing expected settings:\n%s", got)
}
Expand Down Expand Up @@ -141,6 +142,9 @@ func TestMissingConfigUsesDefaults(t *testing.T) {
if Cfg.AudioCacheMaxSizeMB != 2048 {
t.Fatalf("AudioCacheMaxSizeMB = %d, want 2048", Cfg.AudioCacheMaxSizeMB)
}
if Cfg.SplitCamelcaseAndSnakecase {
t.Fatal("SplitCamelcaseAndSnakecase default = true, want false")
}
}

func TestGeneratedConfigRoundTrip(t *testing.T) {
Expand All @@ -152,12 +156,13 @@ func TestGeneratedConfigRoundTrip(t *testing.T) {
})

Cfg = Config{
Paging: true,
PagerCommand: "less -RF",
EnglishOnly: true,
Theme: "wudao",
Brief: true,
AudioCacheMaxSizeMB: 0,
Paging: true,
PagerCommand: "less -RF",
EnglishOnly: true,
Theme: "wudao",
Brief: true,
AudioCacheMaxSizeMB: 0,
SplitCamelcaseAndSnakecase: true,
Logging: LoggerConfig{
Enable: true,
Level: "info",
Expand All @@ -181,6 +186,9 @@ func TestGeneratedConfigRoundTrip(t *testing.T) {
if Cfg.Theme != "wudao" || !Cfg.Paging || Cfg.PagerCommand != "less -RF" || !Cfg.EnglishOnly || !Cfg.Brief {
t.Fatalf("round-tripped config = %+v", Cfg)
}
if !Cfg.SplitCamelcaseAndSnakecase {
t.Fatal("round-tripped SplitCamelcaseAndSnakecase = false, want true")
}
if !Cfg.Logging.Enable || Cfg.Logging.Level != "info" || !Cfg.Logging.Stderr {
t.Fatalf("round-tripped logging config = %+v", Cfg.Logging)
}
Expand Down
49 changes: 49 additions & 0 deletions internal/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"regexp"
"strings"

"github.com/Karmenzind/kd/config"
"github.com/Karmenzind/kd/internal/cache"
"github.com/Karmenzind/kd/internal/core"
"github.com/Karmenzind/kd/internal/daemon"
Expand Down Expand Up @@ -35,10 +36,58 @@ func Query(query string, noCache bool, longText bool) (r *model.Result, err erro
return QueryWithProgress(query, noCache, longText, ui.NopProgress())
}

// QueryWithProgress 负责标识符式查询的回退编排(由配置项
// split_camelcase_and_snakecase 控制,默认关闭):
// - 短词(kd helloWorld / kd hello_world):先按整体查询,未找到再拆词拼成
// 词组,走长文本机器翻译通道。
// - 长文本(kd -t):先对整段中的标识符 token 拆词重写后再翻译,重写无结果
// 时退回原文重试。
//
// 拆分细节见 pkg/str 的 SplitIdentifier / RewriteIdentifiers。
func QueryWithProgress(query string, noCache bool, longText bool, progress ui.Progress) (r *model.Result, err error) {
if progress == nil {
progress = ui.NopProgress()
}

raw := str.Simplify(query)
splitIdentifier := config.Cfg.SplitCamelcaseAndSnakecase
lookup := raw
if longText && splitIdentifier {
lookup = str.RewriteIdentifiers(raw)
}

if r, err = querySingle(lookup, noCache, longText, progress); err != nil || r.Found || r.Prompt != "" {
return r, err
}

if !splitIdentifier {
return r, err
}

if longText {
if lookup != raw {
if fr, ferr := querySingle(raw, noCache, true, progress); ferr == nil && fr.Found {
return fr, nil
}
}
return r, err
}

phrase, ok := str.IdentifierPhrase(raw)
if !ok {
return r, err
}
fr, ferr := querySingle(phrase, noCache, true, progress)
if ferr != nil || !fr.Found {
return r, err
}
// 复用主查询的计数通道:长文本结果不会启动 CounterIncr,
// 若直接返回会在 freq_alert 开启时永久阻塞在 <-r.History。
fr.History = r.History
return fr, nil
}

func querySingle(query string, noCache bool, longText bool, progress ui.Progress) (r *model.Result, err error) {
// TODO (k): <2024-01-02> regexp
query = normalizeQuery(query, longText)

Expand Down
80 changes: 80 additions & 0 deletions pkg/str/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,86 @@ func Simplify(s string) string {
return strings.TrimSpace(s)
}

// identifierTokenPat 匹配标识符式的 token(字母或下划线开头,后续为字母/数字/下划线)。
var identifierTokenPat = regexp.MustCompile(`[A-Za-z_][A-Za-z0-9_]*`)

// SplitIdentifier 把标识符式字符串拆成组成词,支持 camelCase/PascalCase 与下划线:
//
// helloWorld -> [hello World]
// HTTPServer -> [HTTP Server]
// getHTTPResponse -> [get HTTP Response]
// getUserByID -> [get User By ID]
// hello_world -> [hello world]
// _private -> [private]
// user2FA -> [user2 FA]
//
// 不含任何边界的字符串会原样返回为单元素切片;空串、纯下划线会返回空切片。
func SplitIdentifier(s string) []string {
segments := make([]string, 0, 2)
for _, chunk := range strings.Split(s, "_") {
if chunk == "" {
continue
}
segments = append(segments, splitCamelCase(chunk)...)
}
return segments
}

// splitCamelCase 在大小写边界处切分,数字不单独成段而是跟随前一段。
func splitCamelCase(s string) []string {
runes := []rune(s)
parts := make([]string, 0, 2)
start := 0
for i := 1; i < len(runes); i++ {
prev, cur := runes[i-1], runes[i]
if !isUpperASCII(cur) {
continue
}
switch {
case isLowerASCII(prev) || isDigitASCII(prev):
// helloWorld、user2FA
case isUpperASCII(prev) && i+1 < len(runes) && isLowerASCII(runes[i+1]):
// HTTPServer,把连续大写视为整体
default:
continue
}
parts = append(parts, string(runes[start:i]))
start = i
}
return append(parts, string(runes[start:]))
}

func isUpperASCII(r rune) bool { return r >= 'A' && r <= 'Z' }

func isLowerASCII(r rune) bool { return r >= 'a' && r <= 'z' }

func isDigitASCII(r rune) bool { return r >= '0' && r <= '9' }

// IdentifierPhrase 返回标识符拆词后以空格拼接的小写形式,ok 表示结果与原始输入不同。
// 普通单词、词组、纯全大写词不会触发(ok=false)。
func IdentifierPhrase(s string) (string, bool) {
segments := SplitIdentifier(s)
if len(segments) == 0 {
return "", false
}
phrase := strings.ToLower(strings.Join(segments, " "))
if phrase == strings.ToLower(s) {
return "", false
}
return phrase, true
}

// RewriteIdentifiers 把文本中每个标识符式 token 替换为空格分词后的小写形式,
// 其余内容保持不变。用于长文本翻译前的预处理。
func RewriteIdentifiers(text string) string {
return identifierTokenPat.ReplaceAllStringFunc(text, func(token string) string {
if phrase, ok := IdentifierPhrase(token); ok {
return phrase
}
return token
})
}

// SimplifyLines 按行拆分文本,逐行Simplify并丢弃空行。
// 用于处理缓存中残留的、未经清洗的HTML原始文本(含换行与大段缩进)。
func SimplifyLines(s string) []string {
Expand Down
96 changes: 95 additions & 1 deletion pkg/str/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package str

import "testing"
import (
"reflect"
"testing"
)

func TestSimplify(t *testing.T) {
tests := []struct {
Expand All @@ -25,6 +28,97 @@ func TestSimplify(t *testing.T) {
}
}

func TestSplitIdentifier(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{name: "plain lowercase", input: "hello", want: []string{"hello"}},
{name: "capitalized word", input: "Hello", want: []string{"Hello"}},
{name: "all caps word", input: "HTTP", want: []string{"HTTP"}},
{name: "camelCase", input: "helloWorld", want: []string{"hello", "World"}},
{name: "PascalCase", input: "HelloWorld", want: []string{"Hello", "World"}},
{name: "snake_case", input: "hello_world", want: []string{"hello", "world"}},
{name: "acronym prefix", input: "HTTPServer", want: []string{"HTTP", "Server"}},
{name: "acronym in middle", input: "getHTTPResponse", want: []string{"get", "HTTP", "Response"}},
{name: "single letters kept", input: "getUserByID", want: []string{"get", "User", "By", "ID"}},
{name: "leading underscore", input: "_private", want: []string{"private"}},
{name: "trailing underscores", input: "trailing__", want: []string{"trailing"}},
{name: "digit stays with previous", input: "user2FA", want: []string{"user2", "FA"}},
{name: "digit prefix", input: "v2Api", want: []string{"v2", "Api"}},
{name: "mixed snake and camel", input: "user_nameTag", want: []string{"user", "name", "Tag"}},
{name: "phrase untouched", input: "leave me alone", want: []string{"leave me alone"}},
{name: "only underscores", input: "___", want: []string{}},
{name: "empty", input: "", want: []string{}},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := SplitIdentifier(tt.input)
if len(got) == 0 && len(tt.want) == 0 {
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Fatalf("SplitIdentifier(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}

func TestIdentifierPhrase(t *testing.T) {
tests := []struct {
name string
input string
wantPhrase string
wantOK bool
}{
{name: "camelCase", input: "helloWorld", wantPhrase: "hello world", wantOK: true},
{name: "PascalCase", input: "HelloWorld", wantPhrase: "hello world", wantOK: true},
{name: "snake_case", input: "hello_world", wantPhrase: "hello world", wantOK: true},
{name: "leading underscore", input: "_private", wantPhrase: "private", wantOK: true},
{name: "acronym", input: "getHTTPResponse", wantPhrase: "get http response", wantOK: true},
{name: "plain word unchanged", input: "hello", wantOK: false},
{name: "capitalized word unchanged", input: "Hello", wantOK: false},
{name: "all caps unchanged", input: "HTTP", wantOK: false},
{name: "phrase unchanged", input: "leave me alone", wantOK: false},
{name: "empty", input: "", wantOK: false},
{name: "only underscores", input: "___", wantOK: false},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotPhrase, gotOK := IdentifierPhrase(tt.input)
if gotOK != tt.wantOK || gotPhrase != tt.wantPhrase {
t.Fatalf("IdentifierPhrase(%q) = (%q, %v), want (%q, %v)", tt.input, gotPhrase, gotOK, tt.wantPhrase, tt.wantOK)
}
})
}
}

func TestRewriteIdentifiers(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{name: "camel in sentence", input: "Call getUserByID now", want: "Call get user by id now"},
{name: "snake in sentence", input: "set user_name please", want: "set user name please"},
{name: "plain sentence untouched", input: "leave me alone", want: "leave me alone"},
{name: "punctuation kept", input: "use (helloWorld).", want: "use (hello world)."},
{name: "Chinese mixed", input: "调用 getUserByID 方法", want: "调用 get user by id 方法"},
{name: "all caps untouched", input: "HTTP server", want: "HTTP server"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := RewriteIdentifiers(tt.input); got != tt.want {
t.Fatalf("RewriteIdentifiers(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}

func TestSimplifyLines(t *testing.T) {
input := "n.\n\n 小羊;羔羊\n 小羊肉\t\n\n"
got := SimplifyLines(input)
Expand Down
Loading