'text'
🚨 错误信息
Traceback (most recent call last):
File "c:\Users\a1\Desktop\test\音频模型TTS&STT\STT模型gpt-4o-transcribe.py", line 31, in <module>
print(q_voice_to_text(r"C:\Users\a1\Desktop\test\音频模型TTS&STT\luyin.mp3")) # 替换为实际的音频文件路径
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\a1\Desktop\test\音频模型TTS&STT\STT模型gpt-4o-transcribe.py", line 26, in q_voice_to_text
voice_text = data["text"] if data["text"] is not None else ""
~~~~^^^^^^^^
KeyError: 'text'
🤖 AI解决方案
报错分析报告
1. 错误翻译
原文:KeyError: 'text'
译文:键错误:'text'
2. 原因分析
根本原因:代码尝试从返回的字典数据中访问键为 'text' 的字段,但该键在字典中不存在。
具体分析:
q_voice_to_text 函数中第26行data 字典对象可能没有包含预期的 "text" 键3. 解决方案
python
def q_voice_to_text(audio_path):
client = OpenAI(api_key="your-api-key")
with open(audio_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model="whisper-1", # 或使用最新的模型
file=audio_file
)
# 直接访问转录文本,不通过字典键
voice_text = transcription.text if hasattr(transcription, 'text') else ""
return voice_text
检查API返回结构的调试版本:
python
def q_voice_to_text_debug(audio_path):
client = OpenAI(api_key="your-api-key")
with open(audio_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
# 调试:打印返回对象的结构
print(f"返回类型: {type(transcription)}")
print(f"对象属性: {dir(transcription)}")
# 尝试不同的属性访问方式
if hasattr(transcription, 'text'):
return transcription.text
elif hasattr(transcription, 'transcription'):
return transcription.transcription
else:
# 如果是字典结构,检查键
if isinstance(transcription, dict):
print(f"字典键: {transcription.keys()}")
return transcription.get('text', '')
# 转换为字符串获取信息
return str(transcription)
4. ️ 预防措施
最佳实践建议:
.get('key', default_value) 方法替代直接字典键访问,避免KeyError️ 推荐工具:
pdb 或 ipdb 进行交互式调试print(json.dumps(data, indent=2)) 查看完整API响应结构python
try:
voice_text = data.get("text", "")
except AttributeError:
# 如果data不是字典,尝试其他访问方式
voice_text = str(data)
except Exception as e:
print(f"转录过程出错: {e}")
voice_text = ""
提示:检查OpenAI API版本和返回的数据结构,不同版本的SDK可能有不同的返回对象格式。