• python音频转文字调用baidu


    python音频转文字调用的是百度智能云的接口,因业务需求会涉及比较多数字,所以这里做了数字的处理,可根据自己的需求修改。

    1. from flask import Flask, request, jsonify
    2. import requests
    3. from flask_limiter import Limiter
    4. app = Flask(__name__)
    5. limiter = Limiter(app) # 初始化限流扩展
    6. API_KEY = "" #百度智能云上获取
    7. SECRET_KEY = ""
    8. import re
    9. from cn2an import an2cn, transform
    10. def replace_chinese_numbers(text):
    11. # 使用正则表达式匹配句子中的中文数字
    12. chinese_numbers = re.findall(r'[零一二三四五六七八九十百千万]+', text)
    13. # 遍历匹配到的中文数字,逐一替换为阿拉伯数字
    14. for chinese_number in chinese_numbers:
    15. arabic_number = transform(chinese_number, 'cn2an')
    16. text = text.replace(chinese_number, arabic_number)
    17. return text
    18. @app.route('/transcribe', methods=['POST'])
    19. @limiter.limit("5 per second") # 设置限流规则为最多同时 5 个请求
    20. def transcribe_audio():
    21. audio_data = request.data
    22. access_token = get_access_token()
    23. if not access_token:
    24. return jsonify({"error": "Error getting access token"}), 500
    25. url = "https://vop.baidu.com/server_api"
    26. headers = {
    27. 'Content-Type': 'audio/pcm; rate=16000', # 设置正确的 Content-Type
    28. 'Accept': 'application/json',
    29. }
    30. params = {
    31. "cuid": "your_unique_id", # 替换为你的用户唯一标识,随便写
    32. "token": access_token,
    33. }
    34. response = requests.post(url, headers=headers, params=params, data=audio_data)
    35. if response.status_code == 200:
    36. try:
    37. result = response.json()
    38. if "result" in result:
    39. transcript = result["result"][0]
    40. cleaned_transcript = replace_chinese_numbers(transcript)
    41. print(cleaned_transcript)
    42. return jsonify({"transcript": cleaned_transcript})
    43. else:
    44. return jsonify({"error": "No transcription found in the response"}), 500
    45. except UserWarning as warning:
    46. # 如果出现 UserWarning 异常,返回未处理的 transcript
    47. warnings.warn(str(warning))
    48. return jsonify({"transcript": transcript})
    49. else:
    50. return jsonify({"error": "Error in transcription request"}), 500
    51. def get_access_token():
    52. url = "https://aip.baidubce.com/oauth/2.0/token"
    53. params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    54. response = requests.post(url, params=params)
    55. if response.status_code == 200:
    56. access_token = response.json().get("access_token")
    57. return access_token
    58. else:
    59. print("Error getting access token:", response.text)
    60. return None
    61. if __name__ == '__main__':
    62. app.run(host='0.0.0.0', port=16258)

  • 相关阅读:
    excel文件导入dbeaver中文乱码
    ICV报告: ADAS SoC市场规模将在2024年迎来较大突破
    定位与轨迹-百度鹰眼轨迹开放平台-学习笔记
    【1 操作系统概述】
    获取苏宁易购商品信息操作详情
    Promise
    java基础15
    windows- 怎么查看本地网卡速度
    字符串压缩(一)之ZSTD
    java中子类重写继承的方法的规则是什么?
  • 原文地址:https://blog.csdn.net/weixin_44740756/article/details/132687182