Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(metric): keep every sentence in BLEU and ROUGE scores (#4746)

钱晓缺db1b0e1e519c
diff --git a/internal/application/service/metric/common.go b/internal/application/service/metric/common.go
index 8f48a74aa..6c5086930 100644
--- a/internal/application/service/metric/common.go
+++ b/internal/application/service/metric/common.go
@@ -37,36 +37,15 @@ func max(a, b int) int {
}
func splitSentences(text string) []string {
- // 编译正则表达式(匹配中文句号或英文句号)
- re := regexp.MustCompile(`([。.])`)
-
- // 分割文本并保留分隔符用于定位
- split := re.Split(text, -1)
-
+ parts := strings.FieldsFunc(text, func(r rune) bool {
+ return r == '。' || r == '.'
+ })
var sentences []string
- current := strings.Builder{}
-
- for i, s := range split {
- // 交替获取文本段和分隔符(奇数为分隔符)
- if i%2 == 0 {
- current.WriteString(s)
- } else {
- // 当遇到分隔符时,完成当前句子
- if current.Len() > 0 {
- sentence := strings.TrimSpace(current.String())
- if sentence != "" {
- sentences = append(sentences, sentence)
- }
- current.Reset()
- }
+ for _, part := range parts {
+ if sentence := strings.TrimSpace(part); sentence != "" {
+ sentences = append(sentences, sentence)
}
}
-
- // 处理最后一个无分隔符的文本段
- if remaining := strings.TrimSpace(current.String()); remaining != "" {
- sentences = append(sentences, remaining)
- }
-
return sentences
}
diff --git a/internal/application/service/metric/common_test.go b/internal/application/service/metric/common_test.go
new file mode 100644
index 000000000..488fcf4fb
--- /dev/null
+++ b/internal/application/service/metric/common_test.go
@@ -0,0 +1,42 @@
+package metric
+
+import (
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSplitSentences(t *testing.T) {
+ for _, tc := range []struct {
+ text string
+ want []string
+ }{
+ {"", nil},
+ {" \n\t ", nil},
+ {"One. Two. Three. Four", []string{"One", "Two", "Three", "Four"}},
+ {"第一句。第二句。第三句。", []string{"第一句", "第二句", "第三句"}},
+ {" One。 Two. Third 。", []string{"One", "Two", "Third"}},
+ {".。One..。Two。", []string{"One", "Two"}},
+ {" single sentence ", []string{"single sentence"}},
+ } {
+ t.Run(tc.text, func(t *testing.T) {
+ require.Equal(t, tc.want, splitSentences(tc.text))
+ })
+ }
+}
+
+func TestTextMetricsIncludeEverySentence(t *testing.T) {
+ input := &types.MetricInput{GeneratedTexts: "alpha.gamma", GeneratedGT: "alpha.beta"}
+ for _, tc := range []struct {
+ name string
+ score float64
+ }{
+ {"BLEU-1", NewBLEUMetric(false, BLEU1Gram).Compute(input)},
+ {"ROUGE-1 precision", NewRougeMetric(false, "rouge-1", "p").Compute(input)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ require.InDelta(t, 0.5, tc.score, 1e-9)
+ })
+ }
+}