sensitive.go 2.3 KB

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