sensitive.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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) error {
  10. for _, message := range messages {
  11. if len(message.Content) > 0 {
  12. if message.IsStringContent() {
  13. stringContent := message.StringContent()
  14. if ok, words := SensitiveWordContains(stringContent); ok {
  15. return errors.New("sensitive words: " + strings.Join(words, ","))
  16. }
  17. }
  18. } else {
  19. arrayContent := message.ParseContent()
  20. for _, m := range arrayContent {
  21. if m.Type == "image_url" {
  22. // TODO: check image url
  23. } else {
  24. if ok, words := SensitiveWordContains(m.Text); ok {
  25. return errors.New("sensitive words: " + strings.Join(words, ","))
  26. }
  27. }
  28. }
  29. }
  30. }
  31. return nil
  32. }
  33. func CheckSensitiveText(text string) error {
  34. if ok, words := SensitiveWordContains(text); ok {
  35. return errors.New("sensitive words: " + strings.Join(words, ","))
  36. }
  37. return nil
  38. }
  39. func CheckSensitiveInput(input any) error {
  40. switch v := input.(type) {
  41. case string:
  42. return CheckSensitiveText(v)
  43. case []string:
  44. text := ""
  45. for _, s := range v {
  46. text += s
  47. }
  48. return CheckSensitiveText(text)
  49. }
  50. return CheckSensitiveText(fmt.Sprintf("%v", input))
  51. }
  52. // SensitiveWordContains 是否包含敏感词,返回是否包含敏感词和敏感词列表
  53. func SensitiveWordContains(text string) (bool, []string) {
  54. if len(setting.SensitiveWords) == 0 {
  55. return false, nil
  56. }
  57. checkText := strings.ToLower(text)
  58. return AcSearch(checkText, setting.SensitiveWords, false)
  59. }
  60. // SensitiveWordReplace 敏感词替换,返回是否包含敏感词和替换后的文本
  61. func SensitiveWordReplace(text string, returnImmediately bool) (bool, []string, string) {
  62. if len(setting.SensitiveWords) == 0 {
  63. return false, nil, text
  64. }
  65. checkText := strings.ToLower(text)
  66. m := InitAc(setting.SensitiveWords)
  67. hits := m.MultiPatternSearch([]rune(checkText), returnImmediately)
  68. if len(hits) > 0 {
  69. words := make([]string, 0)
  70. for _, hit := range hits {
  71. pos := hit.Pos
  72. word := string(hit.Word)
  73. text = text[:pos] + "**###**" + text[pos+len(word):]
  74. words = append(words, word)
  75. }
  76. return true, words, text
  77. }
  78. return false, nil, text
  79. }