Files
new-api/service/sensitive.go

95 lines
2.3 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"
)
func CheckSensitiveMessages(messages []dto.Message) ([]string, error) {
if len(messages) == 0 {
return nil, nil
}
2024-05-23 23:59:55 +08:00
for _, message := range messages {
arrayContent := message.ParseContent()
for _, m := range arrayContent {
if m.Type == "image_url" {
// TODO: check image url
continue
}
// 检查 text 是否为空
if m.Text == "" {
continue
}
if ok, words := SensitiveWordContains(m.Text); ok {
return words, errors.New("sensitive words detected")
2024-05-23 23:59:55 +08:00
}
}
}
return nil, nil
2024-05-23 23:59:55 +08:00
}
func CheckSensitiveText(text string) ([]string, error) {
2024-05-23 23:59:55 +08:00
if ok, words := SensitiveWordContains(text); ok {
return words, errors.New("sensitive words detected")
2024-05-23 23:59:55 +08:00
}
return nil, nil
2024-05-23 23:59:55 +08:00
}
func CheckSensitiveInput(input any) ([]string, error) {
2024-05-23 23:59:55 +08:00
switch v := input.(type) {
case string:
return CheckSensitiveText(v)
case []string:
var builder strings.Builder
2024-05-23 23:59:55 +08:00
for _, s := range v {
builder.WriteString(s)
2024-05-23 23:59:55 +08:00
}
return CheckSensitiveText(builder.String())
2024-05-23 23:59:55 +08:00
}
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
}
if len(text) == 0 {
return false, nil
}
checkText := strings.ToLower(text)
return AcSearch(checkText, setting.SensitiveWords, true)
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 {
words := make([]string, 0, len(hits))
var builder strings.Builder
builder.Grow(len(text))
lastPos := 0
2024-03-20 17:07:42 +08:00
for _, hit := range hits {
pos := hit.Pos
word := string(hit.Word)
builder.WriteString(text[lastPos:pos])
builder.WriteString("**###**")
lastPos = pos + len(word)
2024-03-20 19:00:51 +08:00
words = append(words, word)
2024-03-20 17:07:42 +08:00
}
builder.WriteString(text[lastPos:])
return true, words, builder.String()
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
}