alibabacloud-bailian-speech-demo/s/speech-r/translate_speech_from_microphone_for_r/python master !1 ?11 ❯ python quick_ssl_bypass_test.py
⚠️ 警告: 此测试禁用了SSL验证!
🎯 目的: 验证API密钥是否有效
✅ API密钥: sk-8119136...
📡 连接中...
🎉 连接成功! (SSL验证已禁用)
❌ 错误: Cannot connect to host dashscope.aliyuncs.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
🚨 异常: TranslationRecognizerRealtime has stopped.
!/usr/bin/env python3
-- coding: utf-8 --
"""
API密钥诊断工具
用于检查DashScope API密钥的有效性和权限
"""
import os
import sys
import dashscope
from dashscope.audio.asr import *
import requests
import json
def check_api_key_format():
"""检查API密钥格式"""
api_key = os.environ.get('DASHSCOPE_API_KEY', '')
print("=== API密钥格式检查 ===")
if not api_key:
print("❌ 未设置DASHSCOPE_API_KEY环境变量")
return False
if api_key == '<your-dashscope-api-key>':
print("❌ API密钥未设置(仍为默认值)")
return False
if not api_key.startswith('sk-'):
print("❌ API密钥格式不正确(应以'sk-'开头)")
return False
if len(api_key) < 20:
print("❌ API密钥长度过短")
return False
print(f"✅ API密钥格式正确: {api_key[:10]}...")
return True
def test_basic_api_access():
"""测试基本API访问"""
print("\n=== 基本API访问测试 ===")
try:
# 设置API密钥
dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')
# 尝试调用一个简单的API来测试连接
from dashscope import Generation
response = Generation.call(
model='qwen-turbo',
prompt='Hello',
max_tokens=10
)
if response.status_code == 200:
print("✅ 基本API访问正常")
return True
else:
print(f"❌ API访问失败: {response.status_code}")
print(f"错误信息: {response.message}")
return False
except Exception as e:
print(f"❌ API访问异常: {str(e)}")
return False
def test_audio_service_access():
"""测试音频服务访问权限"""
print("\n=== 音频服务权限测试 ===")
try:
# 创建一个简单的回调类用于测试
class TestCallback(TranslationRecognizerCallback):
def __init__(self):
self.success = False
self.error_msg = ""
def on_open(self):
print("✅ 音频服务连接成功")
self.success = True
def on_error(self, message):
self.error_msg = f"错误: {message.message}"
print(f"❌ 音频服务错误: {message.message}")
def on_event(self, request_id, transcription_result, translation_result, usage):
pass
def on_complete(self):
pass
def on_close(self):
pass
callback = TestCallback()
# 尝试创建翻译识别器
translator = TranslationRecognizerRealtime(
model='gummy-realtime-v1',
format='pcm',
sample_rate=16000,
transcription_enabled=False,
translation_enabled=True,
translation_target_languages=['en'],
callback=callback,
)
# 尝试启动服务
translator.start()
# 等待一下看是否有错误
import time
time.sleep(2)
translator.stop()
if callback.success:
print("✅ 音频翻译服务权限正常")
return True
else:
print(f"❌ 音频翻译服务权限问题: {callback.error_msg}")
return False
except Exception as e:
print(f"❌ 音频服务测试异常: {str(e)}")
return False
def check_account_status():
"""检查账户状态"""
print("\n=== 账户状态建议 ===")
print("如果API密钥格式正确但仍无法访问,请检查:")
print("1. 🌐 登录阿里云控制台: https://dashscope.console.aliyun.com/")
print("2. 💰 检查账户余额是否充足")
print("3. 🔧 确认是否已开通'通义千问'服务")
print("4. 🎙️ 确认是否已开通'语音合成与识别'服务")
print("5. 🔑 尝试重新生成API密钥")
print("6. 📍 检查服务区域设置(推荐使用'华东1(杭州)')")
print("7. 📋 查看控制台中的服务使用限制")
def provide_solutions():
"""提供解决方案"""
print("\n=== 解决方案建议 ===")
print("1. 重新获取API密钥:")
print(" - 访问: https://dashscope.console.aliyun.com/api-key")
print(" - 删除现有密钥,重新创建")
print(" - 确保账户已实名认证")
print("\n2. 开通必要服务:")
print(" - DashScope通义千问: https://dashscope.console.aliyun.com/")
print(" - 语音技术服务: https://nls-portal.console.aliyun.com/")
print("\n3. 检查计费和配额:")
print(" - 确保账户有足够余额")
print(" - 检查API调用限制")
print("\n4. 如果是新账户:")
print(" - 可能需要等待服务开通(通常几分钟)")
print(" - 确保完成实名认证")
def main():
"""主函数"""
print("DashScope API 诊断工具")
print("=" * 50)
# 检查API密钥格式
format_ok = check_api_key_format()
if not format_ok:
print("\n请先正确设置API密钥:")
print("export DASHSCOPE_API_KEY='你的实际API密钥'")
return
# 测试基本API访问
basic_ok = test_basic_api_access()
# 测试音频服务
audio_ok = test_audio_service_access()
# 提供建议
check_account_status()
if not basic_ok or not audio_ok:
provide_solutions()
print("\n" + "=" * 50)
if basic_ok and audio_ok:
print("🎉 所有测试通过!您的API密钥应该可以正常使用。")
else:
print("⚠️ 存在权限问题,请按照上述建议进行排查。")
if name == 'main':
main()