Exemplo n.º 1
0
    def get_results(self, task_id, ind):
        try:
            print("Getting result for %s" % self.temp_data["file_path"][ind])
            cred = credential.Credential(self._secret_id, self._secret_key)
            httpProfile = HttpProfile()
            httpProfile.endpoint = self._endpoint

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = asr_client.AsrClient(cred, "", clientProfile)

            req = models.DescribeTaskStatusRequest()
            params = {"TaskId": task_id}
            req.from_json_string(json.dumps(params))
            seconds = 0
            while True:
                time.sleep(1)
                seconds += 1
                resp = client.DescribeTaskStatus(req)
                result_json = json.loads(resp.to_json_string())
                result_status = result_json["Data"]["StatusStr"]
                if result_status in ["success", "failed"]:
                    break
                print(seconds)
            result_data = result_json["Data"]["ResultDetail"]
            result_data_str = json.dumps(result_data, ensure_ascii=False)
            self.temp_data["result_data"].append(result_data_str)

        except TencentCloudSDKException as err:
            print(err)
Exemplo n.º 2
0
def get(Taskid):
    try:
        cred = credential.Credential(config['tenxun_api']['secretId'],
                                     config['tenxun_api']['secretKey'])
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = asr_client.AsrClient(cred, "", clientProfile)

        req = models.DescribeTaskStatusRequest()
        params = {"TaskId": Taskid}
        req.from_json_string(json.dumps(params))

        resp = json.loads(client.DescribeTaskStatus(req).to_json_string())
        if (resp['Data']['StatusStr'] == "success"):
            if (resp['Data']['Result']):
                #print(resp['Data']['Result'])
                resp_e = resp['Data']['Result'].split(' ')[-1]

                return resp_e
            else:
                return "什么都没有听到呢"
        else:
            return get(Taskid)
    except TencentCloudSDKException as err:
        get(Taskid)
Exemplo n.º 3
0
    def getText(self, taskId):
        try:
            req = models.DescribeTaskStatusRequest()
            params = '{"TaskId":' + str(taskId) + '}'
            req.from_json_string(params)

            resp = self.client.DescribeTaskStatus(req)
            # print(resp.to_json_string())

            return resp.to_json_string()

        except TencentCloudSDKException as err:
            print(err)
Exemplo n.º 4
0
    def get_result(self, task_id):

        try:

            req_result = models.DescribeTaskStatusRequest()
            params_result = {"TaskId": task_id}
            req_result._deserialize(params_result)

            resp_result = self.client.DescribeTaskStatus(req_result)

            result = resp_result.to_json_string()
            final_result = json.loads(result)
            text = final_result['Data']['Result']

            return text

        except TencentCloudSDKException as err:
            print(err)
Exemplo n.º 5
0
async def tx_asr_result(task_id: str) -> str:
    """腾讯云 ASR"""

    config = manager.config
    id = config["asr"]["tx_id"]
    key = config["asr"]["tx_key"]

    while True:
        try:
            cred = credential.Credential(id, key)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "asr.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = asr_client.AsrClient(cred, "", clientProfile)

            req = models.DescribeTaskStatusRequest()
            req.from_json_string(dumps({"TaskId": task_id}))

            resp = client.DescribeTaskStatus(req)
            data = resp._serialize(allow_none=True)["Data"]
            status = data["StatusStr"]

            if status == "success":
                # detail = data["ResultDetail"]
                result = data["Result"]
                # duration = data["AudioDuration"]

                logger.info(f"tencent cloud sdk asr is done: {task_id} {result}")
                return result.strip()
            elif status == "failed":
                logger.error(f'task status failed: {data["ErrorMsg"]}')
            else:
                logger.warning(f"task status is {status}")
                continue

        except TencentCloudSDKException as err:
            print(err)

        break
def video_to_text(video_url, video_id):
    """
    input:
        video_url
        video_id

    output:
        results 
            format: [{time_start:xxx,time_end:xxx,text:xxx,vid:xxx},...]
    """
    from tencentcloud.common import credential
    from tencentcloud.common.profile.client_profile import ClientProfile
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.asr.v20190614 import asr_client, models
    import base64
    import io
    import time
    import sys
    if sys.version_info[0] == 3:
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

    # post the audio to tencent cloud platform
    try:
        # <Your SecretId><Your SecretKey> of tencent cloud
        cred = credential.Credential(
            "AKID1w0sUvY1A4nQyJC5O1PXP43qMimcZNCY", "LWSHzeGgrmQNBk4MOiqiRu40at7TYNJg")
        # set http request
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        client = asr_client.AsrClient(cred, "ap-beijing", clientProfile)

        # set params and create recognition task
        req = models.CreateRecTaskRequest()
        params = {"ChannelNum": 1, "ResTextFormat": 0, "SourceType": 0}
        req._deserialize(params)
        req.EngineModelType = "16k_en"
        req.Url = video_url
        resp = client.CreateRecTask(req)

        # set result query
        req = models.DescribeTaskStatusRequest()
        params = '{"TaskId":%s}' % resp.Data.TaskId
        req.from_json_string(params)

        # polling
        resp = client.DescribeTaskStatus(req)
        while resp.Data.Status != 2:
            print(111)
            if 'faild' in resp.Data.StatusStr:
                break
            print(222)
            print("video ID: " + str(video_id) + " is " +
                  resp.Data.StatusStr, flush=True)
            time.sleep(1)
            resp = client.DescribeTaskStatus(req)

        # process the result
        print("video ID: " + str(video_id) + " is " +
              resp.Data.StatusStr, flush=True)
        results = []
        lines = resp.Data.Result.split('\n')
        for line in lines:
            if len(line) < 1:
                continue
            time, text = line.split(']')[0][1:], line.split(']')[1][2:-1]
            result_dict = {}
            result_dict["time_start"], result_dict[
                "time_end"] = time.split(',')[0], time.split(',')[1]
            result_dict["text"] = text
            result_dict["vid"] = video_id
            results.append(result_dict)

        return results

    except TencentCloudSDKException as err:
        print(err)
Exemplo n.º 7
0
#根据TaskId编码进行结果的查询

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models
try:
    #此处<Your SecretId><Your SecretKey>需要替换成客户自己的账号信息
    cred = credential.Credential("Your SecretId", "Your SecretKey")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)

    req = models.DescribeTaskStatusRequest()
    params = '{"TaskId":737083613}'
    req.from_json_string(params)

    resp = client.DescribeTaskStatus(req)
    print(resp.to_json_string())

except TencentCloudSDKException as err:
    print(err)
'''
运行后的结果如下,能识别“梅赛德斯奔驰”语句
{"Data": {"Status": 2, "StatusStr": "success", "Result": "[0:0.000,0:1.540]  梅赛德斯奔驰。\n", "TaskId": 737083613, "ErrorMsg": "", "ResultDetail": null}, "RequestId": "4f87d14f-8b0f-4970-b517-eaf8c5df2e9d"}
'''