sensitive.go 1.9 KB

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