sensitive.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package service
  2. import (
  3. "errors"
  4. "strings"
  5. "github.com/QuantumNous/new-api/dto"
  6. "github.com/QuantumNous/new-api/setting"
  7. )
  8. func CheckSensitiveMessages(messages []dto.Message) ([]string, error) {
  9. if len(messages) == 0 {
  10. return nil, nil
  11. }
  12. for _, message := range messages {
  13. arrayContent := message.ParseContent()
  14. for _, m := range arrayContent {
  15. if m.Type == "image_url" {
  16. // TODO: check image url
  17. continue
  18. }
  19. // 检查 text 是否为空
  20. if m.Text == "" {
  21. continue
  22. }
  23. if ok, words := SensitiveWordContains(m.Text); ok {
  24. return words, errors.New("sensitive words detected")
  25. }
  26. }
  27. }
  28. return nil, nil
  29. }
  30. func CheckSensitiveText(text string) (bool, []string) {
  31. return SensitiveWordContains(text)
  32. }
  33. // SensitiveWordContains 是否包含敏感词,返回是否包含敏感词和敏感词列表
  34. func SensitiveWordContains(text string) (bool, []string) {
  35. if len(setting.SensitiveWords) == 0 {
  36. return false, nil
  37. }
  38. if len(text) == 0 {
  39. return false, nil
  40. }
  41. checkText := strings.ToLower(text)
  42. return AcSearch(checkText, setting.SensitiveWords, true)
  43. }
  44. // SensitiveWordReplace 敏感词替换,返回是否包含敏感词和替换后的文本
  45. func SensitiveWordReplace(text string, returnImmediately bool) (bool, []string, string) {
  46. if len(setting.SensitiveWords) == 0 {
  47. return false, nil, text
  48. }
  49. checkText := strings.ToLower(text)
  50. m := getOrBuildAC(setting.SensitiveWords)
  51. hits := m.MultiPatternSearch([]rune(checkText), returnImmediately)
  52. if len(hits) > 0 {
  53. words := make([]string, 0, len(hits))
  54. var builder strings.Builder
  55. builder.Grow(len(text))
  56. lastPos := 0
  57. for _, hit := range hits {
  58. pos := hit.Pos
  59. word := string(hit.Word)
  60. builder.WriteString(text[lastPos:pos])
  61. builder.WriteString("**###**")
  62. lastPos = pos + len(word)
  63. words = append(words, word)
  64. }
  65. builder.WriteString(text[lastPos:])
  66. return true, words, builder.String()
  67. }
  68. return false, nil, text
  69. }