python 获取视频文案

做自媒体的用户,很多人都需要去获取视频的文案。就是将视频里面的说话内容转变成文字,目前很多小程序里面都提供了这个功能。

下面我从python开发的角度教大家如何获取文字

1.首先需要获取用户分享的视频地址

如何获取到视频地址可以参考这篇文章,CSDN

2.拿着视频地址将视频进行下载,将视频转换成音频

视频转音频主要用到了ffmpeg这个包,装好了这个包后直接使用命令行执行

import os
import subprocess
import time

video_input = "/data/video_input/"
video_output = "/data/video_output/"

local_file_name = 'video_' + str(time.time()) + '.mp4'
local_url = video_input + local_file_name

input_file = local_url
file_name_without_ext, ext = os.path.splitext(local_file_name)
new_file_name = file_name_without_ext + '.mp3'
output_file = video_output + new_file_name

command = "ffmpeg -i {input_file} -vn -acodec libmp3lame {output_file}".format(input_file=input_file,                                                                           output_file=output_file)

process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

3.调用语音转文字的接口,将音频转换为文字

语音转文字,这里我推荐使用腾讯的语音转文字

安装对应的包

pip install tencentcloud-sdk-python-asr 

具体文档可参考:登录 - 腾讯云

分2步,

3.1首先需要将音频进行上传

import json
import re
import shutil
import random
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 requests

def upload_file(file_name):
    """
    上传文件
    :param file_name:
    :return:
    """
    upload_result = {
        'succ': 'F',
        'message': '',
        'task_id': 0
    }
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
        # 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
        # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        cred = credential.Credential(SecretId, SecretKey)
        # 实例化一个http选项,可选的,没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        # 实例化一个client选项,可选的,没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = asr_client.AsrClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.CreateRecTaskRequest()
        params = {
            "EngineModelType": "8k_zh",
            "ChannelNum": 1,
            "ResTextFormat": 0,
            "SourceType": 0,
            "Url": "https://你的域名/mp3/{file}".format(file=file_name)
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个CreateRecTaskResponse的实例,与请求对象对应
        resp = client.CreateRecTask(req)
        # 输出json格式的字符串回包
        print(resp.to_json_string())
        task_result = json.loads(resp.to_json_string())

        upload_result['succ'] = 'T'
        upload_result['message'] = '上传成功'
        upload_result['task_id'] = task_result['Data']['TaskId']

    except TencentCloudSDKException as err:
        # print(err)
        upload_result['message'] = err

    return upload_result

3.2 上传后,然后使用一个任务获取任务的状态

import json
import re
import shutil
import random
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 requests

def get_result(taskId):
    """
    根据taskid 获取数据
    :param taskId: int
    :return:
    """
    task_result = {
        'succ': 'T',
        'status': 0,
        'content': ''
    }
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
        # 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
        # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        cred = credential.Credential(SecretId, SecretKey)
        # 实例化一个http选项,可选的,没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        # 实例化一个client选项,可选的,没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = asr_client.AsrClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.DescribeTaskStatusRequest()
        params = {
            "TaskId": taskId
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个DescribeTaskStatusResponse的实例,与请求对象对应
        resp = client.DescribeTaskStatus(req)
        # 输出json格式的字符串回包
        textResult = json.loads(resp.to_json_string())

        task_result['status'] = textResult['Data']['Status']
        task_result['content'] = textResult['Data']['Result']
        # if textResult['Data']['Status'] == 2:
        #     print(replace_brackets(textResult['Data']['Result']))
        # else:
        #     print(textResult)

    except TencentCloudSDKException as err:
        print(err)
        task_result['succ'] = 'F'
        task_result['content'] = '获取状态失败'

    return task_result

这样就获取到了整个的文案内容了。

最后大家可以试试我的小程序,获取视频文案,

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值