ContentSecurityObject.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # @Author : Rocky
  2. # @File : ContentSecurityObject.py
  3. # @Time : 2023/8/18 11:02
  4. from alibabacloud_green20220302.client import Client as Green20220302Client
  5. from alibabacloud_tea_openapi import models as open_api_models
  6. from alibabacloud_green20220302 import models as green_20220302_models
  7. from alibabacloud_tea_util import models as util_models
  8. from Ansjer.config import ALI_ACCESS_KEY_ID, ALI_ACCESS_KEY_SECRET
  9. ILLEGAL_LABEL_LIST = ['political_content', 'profanity', 'contraband', 'sexual_content', 'violence', 'negative_content',
  10. 'religion', 'cyberbullying']
  11. class ContentSecurity:
  12. """
  13. 阿里云内容安全服务类
  14. """
  15. def __init__(self):
  16. pass
  17. @staticmethod
  18. def create_client() -> Green20220302Client:
  19. """
  20. 使用AK&SK初始化账号Client
  21. @return: Client
  22. @throws Exception
  23. """
  24. config = open_api_models.Config(
  25. # 必填,您的 AccessKey ID,
  26. access_key_id=ALI_ACCESS_KEY_ID,
  27. # 必填,您的 AccessKey Secret,
  28. access_key_secret=ALI_ACCESS_KEY_SECRET
  29. )
  30. # Endpoint 请参考 https://api.aliyun.com/product/Green
  31. config.endpoint = f'green-cip.cn-shanghai.aliyuncs.com'
  32. return Green20220302Client(config)
  33. def text_review(self, service, service_parameters):
  34. """
  35. @param service: 审核服务类型
  36. @param service_parameters: 审核服务参数集
  37. @return: bool, True: 审核通过, False: 审核不通过
  38. """
  39. client = self.create_client()
  40. text_moderation_request = green_20220302_models.TextModerationRequest(service, service_parameters)
  41. runtime = util_models.RuntimeOptions()
  42. res = client.text_moderation_with_options(text_moderation_request, runtime)
  43. print(res)
  44. if res.status_code != 200:
  45. return False
  46. labels = res.body.data.labels
  47. labels_list = labels.split(',')
  48. for label in labels_list:
  49. if label in ILLEGAL_LABEL_LIST:
  50. return False
  51. return True