|
@@ -27,6 +27,10 @@ clt = Client(config)
|
|
class Security:
|
|
class Security:
|
|
@classmethod
|
|
@classmethod
|
|
def security(cls, content):
|
|
def security(cls, content):
|
|
|
|
+ """
|
|
|
|
+ 内容安全审核方法
|
|
|
|
+ 返回: (是否安全, 结果字典/字符串)
|
|
|
|
+ """
|
|
serviceParameters = {
|
|
serviceParameters = {
|
|
'content': content
|
|
'content': content
|
|
}
|
|
}
|
|
@@ -37,28 +41,45 @@ class Security:
|
|
|
|
|
|
try:
|
|
try:
|
|
response = clt.text_moderation_plus(textModerationPlusRequest)
|
|
response = clt.text_moderation_plus(textModerationPlusRequest)
|
|
|
|
+
|
|
|
|
+ # HTTP请求成功
|
|
if response.status_code == 200:
|
|
if response.status_code == 200:
|
|
- # 将响应体转换为字典格式
|
|
|
|
- result_dict = response.body.to_map()
|
|
|
|
- logger.info('response success. result:{}'.format(result_dict))
|
|
|
|
-
|
|
|
|
- if result_dict['Code'] == 200:
|
|
|
|
- risk_level = result_dict['Data']['RiskLevel']
|
|
|
|
- if risk_level in ["high", "medium"]:
|
|
|
|
- return False, result_dict
|
|
|
|
- return True, result_dict
|
|
|
|
- else:
|
|
|
|
- logger.error('Business error. code:{}, message:{}'.format(
|
|
|
|
- result_dict['Code'], result_dict['Message']))
|
|
|
|
- return False, result_dict
|
|
|
|
|
|
+ try:
|
|
|
|
+ # 将响应体转换为字典格式
|
|
|
|
+ result_dict = response.body.to_map()
|
|
|
|
+ logger.info(f'审核成功. 结果:{result_dict}')
|
|
|
|
+
|
|
|
|
+ # 业务状态码检查
|
|
|
|
+ if result_dict.get('Code') == 200:
|
|
|
|
+ risk_level = result_dict.get('Data', {}).get('RiskLevel', '').lower()
|
|
|
|
+
|
|
|
|
+ # 风险等级判断
|
|
|
|
+ if risk_level in ["high", "medium"]:
|
|
|
|
+ return False, json.dumps(result_dict, ensure_ascii=False)
|
|
|
|
+ return True, json.dumps(result_dict, ensure_ascii=False)
|
|
|
|
+ else:
|
|
|
|
+ # 业务错误
|
|
|
|
+ error_msg = f"业务错误. 代码:{result_dict.get('Code')}, 消息:{result_dict.get('Message', '无')}"
|
|
|
|
+ logger.error(error_msg)
|
|
|
|
+ return False, error_msg
|
|
|
|
+
|
|
|
|
+ except Exception as parse_error:
|
|
|
|
+ # 响应解析错误
|
|
|
|
+ error_msg = f"响应解析错误: {str(parse_error)}"
|
|
|
|
+ logger.error(error_msg)
|
|
|
|
+ return False, error_msg
|
|
|
|
+
|
|
else:
|
|
else:
|
|
- error_msg = 'API request failed. status:{}'.format(response.status_code)
|
|
|
|
|
|
+ # HTTP请求失败
|
|
|
|
+ error_msg = f"API请求失败. 状态码:{response.status_code}, 响应:{str(response)}"
|
|
logger.error(error_msg)
|
|
logger.error(error_msg)
|
|
- return False, {'error': error_msg}
|
|
|
|
|
|
+ return False, error_msg
|
|
|
|
|
|
- except Exception as err:
|
|
|
|
- logger.error(f"Error in security check: {str(err)}")
|
|
|
|
- return False, {'error': str(err)}
|
|
|
|
|
|
+ except Exception as e:
|
|
|
|
+ # 全局异常处理
|
|
|
|
+ error_msg = f"内容审核异常: {str(e)}"
|
|
|
|
+ logger.exception(error_msg)
|
|
|
|
+ return False, error_msg
|
|
if __name__ == '__main__':
|
|
if __name__ == '__main__':
|
|
is_safe, result = Security.security("测试安全边界")
|
|
is_safe, result = Security.security("测试安全边界")
|
|
print(f"安全状态: {is_safe}")
|
|
print(f"安全状态: {is_safe}")
|