Updated on 2023-07-17 GMT+08:00

Text Moderation (V2)

  1. This section describes how to use the Text Moderation SDK by AK/SK authentication.

    Replace the AK/SK in the sample code with the actual AK/SK. Set the value of text in TextDetectionItemsReq in the code to configure the text to be detected, and execute the code.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkmoderation.v2.region.moderation_region import ModerationRegion
    from huaweicloudsdkmoderation.v2 import ModerationClient,RunTextModerationRequest,TextDetectionItemsReq,TextDetectionReq
    
    if __name__ == "__main__":
           //Enter your AK/SK.
        ak = "<YOUR AK>"
        sk = "<YOUR SK>"
    
        credentials = BasicCredentials(ak, sk)
    
        client = ModerationClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(ModerationRegion.value_of("xxx")) \   //Replace xxx with the region where the service is located.
            .build()
    
        try:
            request = RunTextModerationRequest()
            listTextDetectionItemsReqItemsbody = [
                TextDetectionItemsReq(
                    text="text",  //Enter the text to be detected.
                    type="content"
                )
            ]
            listTextDetectionReqCategoriesbody = [
                "porn",
                "abuse",
                "contraband",
                "flood"
            ]
            request.body = TextDetectionReq(
                items=listTextDetectionItemsReqItemsbody,
                categories=listTextDetectionReqCategoriesbody
            )
            response = client.run_text_moderation(request)
            print(response.status_code)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  2. If 200 is displayed on the console, the code is successfully executed. The text moderation result is displayed on the console.
    200
    {"result": {"suggestion": "block", "detail": {"contraband": ["potassium arsenite"], "porn": ["nude chat"]}}}}