Updated on 2025-07-02 GMT+08:00

Text Moderation (V3)

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

    Change the value of text in TextDetectionDataReq in the sample code to the text to be detected. Then run 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
    # coding: utf-8
     
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkmoderation.v3.region.moderation_region import ModerationRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkmoderation.v3 import *
    import os
     
    if __name__ == "__main__":
        # Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
        # In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
        ak = os.getenv("HUAWEICLOUD_SDK_AK")
        sk = os.getenv("HUAWEICLOUD_SDK_SK")
     
        credentials = BasicCredentials(ak, sk) \
     
        client = ModerationClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(ModerationRegion.value_of("xxx"))\        
            .build()
        # Replace xxx with the service region, for example, ap-southeast-3.
        try:
            request = RunTextModerationRequest()
            databody = TextDetectionDataReq(
                text="test"
            )
            request.body = TextDetectionReq(
                data=databody,
                event_type="comment"
            )
            response = client.run_text_moderation(request)
            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.
    {"request_id": "d81702cfd3599e103030c3d52d6f955f", "result": {"suggestion": "pass", "label": "normal", "details": []}}