Files
new-api/service/sensitive.go

86 lines
2.2 KiB
Go
Raw Normal View History

2024-03-20 17:07:42 +08:00
package service
import (
2024-05-23 23:59:55 +08:00
"errors"
2024-03-20 17:07:42 +08:00
"fmt"
2024-05-23 23:59:55 +08:00
"one-api/dto"
"one-api/setting"
2024-03-20 17:07:42 +08:00
"strings"
)
2024-05-23 23:59:55 +08:00
func CheckSensitiveMessages(messages []dto.Message) error {
for _, message := range messages {
if len(message.Content) > 0 {
if message.IsStringContent() {
stringContent := message.StringContent()
if ok, words := SensitiveWordContains(stringContent); ok {
return errors.New("sensitive words: " + strings.Join(words, ","))
}
}
} else {
arrayContent := message.ParseContent()
for _, m := range arrayContent {
if m.Type == "image_url" {
// TODO: check image url
} else {
if ok, words := SensitiveWordContains(m.Text); ok {
return errors.New("sensitive words: " + strings.Join(words, ","))
}
}
}
}
}
return nil
}
func CheckSensitiveText(text string) error {
if ok, words := SensitiveWordContains(text); ok {
return errors.New("sensitive words: " + strings.Join(words, ","))
}
return nil
}
func CheckSensitiveInput(input any) error {
switch v := input.(type) {
case string:
return CheckSensitiveText(v)
case []string:
text := ""
for _, s := range v {
text += s
}
return CheckSensitiveText(text)
}
return CheckSensitiveText(fmt.Sprintf("%v", input))
}
2024-03-20 17:07:42 +08:00
// SensitiveWordContains 是否包含敏感词,返回是否包含敏感词和敏感词列表
func SensitiveWordContains(text string) (bool, []string) {
if len(setting.SensitiveWords) == 0 {
2024-03-20 22:33:22 +08:00
return false, nil
}
checkText := strings.ToLower(text)
return AcSearch(checkText, setting.SensitiveWords, false)
2024-03-20 17:07:42 +08:00
}
// SensitiveWordReplace 敏感词替换,返回是否包含敏感词和替换后的文本
2024-03-20 19:00:51 +08:00
func SensitiveWordReplace(text string, returnImmediately bool) (bool, []string, string) {
if len(setting.SensitiveWords) == 0 {
2024-03-20 22:33:22 +08:00
return false, nil, text
}
2024-03-20 20:26:34 +08:00
checkText := strings.ToLower(text)
m := InitAc(setting.SensitiveWords)
2024-03-20 20:26:34 +08:00
hits := m.MultiPatternSearch([]rune(checkText), returnImmediately)
2024-03-20 17:07:42 +08:00
if len(hits) > 0 {
2024-03-20 19:00:51 +08:00
words := make([]string, 0)
2024-03-20 17:07:42 +08:00
for _, hit := range hits {
pos := hit.Pos
word := string(hit.Word)
2024-03-21 14:29:56 +08:00
text = text[:pos] + "**###**" + text[pos+len(word):]
2024-03-20 19:00:51 +08:00
words = append(words, word)
2024-03-20 17:07:42 +08:00
}
2024-03-20 19:00:51 +08:00
return true, words, text
2024-03-20 17:07:42 +08:00
}
2024-03-20 19:00:51 +08:00
return false, nil, text
2024-03-20 17:07:42 +08:00
}