騰訊云對象存儲數據萬象(Cloud Infinite,CI)為用戶提供圖片、視頻、語音、文本等文件的內容安全智能審核服務,幫助用戶有效識別涉黃、違法違規和廣告審核,規避運營風險。本文以音頻審核為例給出go語言示例代碼與相應結果。
一、預備條件
- 獲取API密鑰,不可泄漏
https://console.cloud.tencent.com/cam/capi - 將SecretId與SecretKey寫到環境變量
二、實現代碼
package mainimport ("context""fmt""net/http""net/url""os""path/filepath""github.com/gin-gonic/gin"cos "github.com/tencentyun/cos-go-sdk-v5"
)var cosClient *cos.Clientfunc initCOSClient() error {secretID := os.Getenv("SecretId")secretKey := os.Getenv("SecretKey")if secretID == "" || secretKey == "" {return fmt.Errorf("SecretId and SecretKey environment variables are required")}bu, _ := url.Parse("https://radio-1259203851.cos.ap-shanghai.myqcloud.com")cu, _ := url.Parse("https://radio-1259203851.ci.ap-shanghai.myqcloud.com")b := &cos.BaseURL{BucketURL: bu, CIURL: cu}cosClient = cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: secretID,SecretKey: secretKey,},})return nil
}func main() {if err := initCOSClient(); err != nil {fmt.Printf("Failed to initialize COS client: %v\n", err)fmt.Println("Please set the following environment variables:")fmt.Println("export SecretId=YOUR_SECRET_ID")fmt.Println("export SecretKey=YOUR_SECRET_KEY")os.Exit(1)}r := gin.Default()// 文件上傳接口r.POST("/upload", func(c *gin.Context) {file, err := c.FormFile("file")if err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}// 保存上傳的文件到臨時目錄tempDir := "temp"if err := os.MkdirAll(tempDir, 0755); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}tempFilePath := filepath.Join(tempDir, file.Filename)if err := c.SaveUploadedFile(file, tempFilePath); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}// 上傳文件到COScosKey := "audios/" + file.Filename_, err = cosClient.Object.PutFromFile(context.Background(), cosKey, tempFilePath, nil)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(),"message": "Failed to upload file to COS",})return}// 提交審核任務opt := &cos.PutAudioAuditingJobOptions{InputObject: cosKey,Conf: &cos.AudioAuditingJobConf{},}res, _, err := cosClient.CI.PutAudioAuditingJob(context.Background(), opt)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(),"message": "Failed to submit audio auditing job",})return}// 清理臨時文件os.Remove(tempFilePath)// 返回任務IDc.JSON(http.StatusOK, gin.H{"job_id": res.JobsDetail.JobId,"cos_key": cosKey,})})// 查詢審核結果接口r.GET("/result/:job_id", func(c *gin.Context) {jobID := c.Param("job_id")// 查詢審核結果res, _, err := cosClient.CI.GetAudioAuditingJob(context.Background(), jobID)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(),"message": "Failed to get audio auditing result",})return}c.JSON(http.StatusOK, res)})// 啟動服務器r.Run(":8080")
}
三、調用方法
- 上傳文件
使用postman,調用以下接口:
http://localhost:8080/upload
- 查詢任務
查詢任務的結果說明可參考:查詢音頻審核任務結果,需要重點關注的是result,該字段表示本次判定的審核結果,可以根據該結果,進行后續的操作。有效值:0(審核正常),1 (判定為違規敏感文件),2(疑似敏感,建議人工復核)。