| 1 | import { Injectable } from '@nestjs/common'; |
| 2 | import { ConfigService } from '@nestjs/config'; |
| 3 | import * as tencentcloud from 'tencentcloud-sdk-nodejs-tms'; |
| 4 | import { Client } from 'tencentcloud-sdk-nodejs-tms/tencentcloud/services/tms/v20201229/tms_client'; |
| 5 | const TmsClient = tencentcloud.tms.v20201229.Client; |
| 6 | |
| 7 | export enum TmsLabels { |
| 8 | Normal = 'Normal', |
| 9 | Porn = 'Porn', |
| 10 | Abuse = 'Abuse', |
| 11 | Ad = 'Ad', |
| 12 | Error = 'Error', |
| 13 | } |
| 14 | |
| 15 | @Injectable() |
| 16 | export class TmsService { |
| 17 | private client: Client; |
| 18 | constructor(private configService: ConfigService) { |
| 19 | const options: { secretId: string; secretKey: string } = |
| 20 | this.configService.get('TMS_CONFIG'); |
| 21 | |
| 22 | const clientConfig = { |
| 23 | credential: options, |
| 24 | |
| 25 | region: 'ap-beijing', |
| 26 | profile: { |
| 27 | httpProfile: { |
| 28 | endpoint: 'tms.tencentcloudapi.com', |
| 29 | }, |
| 30 | }, |
| 31 | }; |
| 32 | |
| 33 | this.client = new TmsClient(clientConfig); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * 内容安全验证 |
| 38 | * @param content 文本内容 |
| 39 | * **Normal**:正常,**Porn**:色情,**Abuse**:谩骂,**Ad**:广告;以及其他令人反感、不安全或不适宜的内容类型 **Error** |
| 40 | */ |
| 41 | public async textModeration(content: string): Promise<TmsLabels> { |
| 42 | try { |
| 43 | const base64 = Buffer.from(content).toString('base64'); |
| 44 | const result = await this.client.TextModeration({ |
| 45 | Content: base64, |
| 46 | }); |
| 47 | |
| 48 | return result.Label as TmsLabels; |
| 49 | } catch (error: any) { |
| 50 | console.log('==== textModeration ====', error); |
| 51 | return TmsLabels.Error; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 |