main.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # 智能音箱电脑模拟版 - 主程序
  2. import os
  3. import sys
  4. from config import Config
  5. from recorder import record_until_silence
  6. from asr import transcribe
  7. from llm import chat
  8. from tts_client import synthesize_and_download
  9. from player import play
  10. def main():
  11. print('=' * 60)
  12. print('🎙️ 智能音箱电脑模拟版')
  13. print('=' * 60)
  14. # 验证配置
  15. try:
  16. Config.validate()
  17. except ValueError as e:
  18. print(f'\n❌ 配置错误:\n{e}')
  19. print('\n请先复制 .env.example 为 .env 并填入 API Key')
  20. sys.exit(1)
  21. print(f'\n✅ 配置 OK')
  22. print(f' ASR: {Config.ASR_PROVIDER}')
  23. print(f' LLM: {Config.LLM_PROVIDER} / {Config.LLM_MODEL}')
  24. print(f' TTS: {Config.TTS_BASE_URL} (voice: {Config.TTS_VOICE_NAME})')
  25. print('\n操作说明:')
  26. print(' 1. 按回车开始录音')
  27. print(' 2. 说完后自动停止')
  28. print(' 3. 系统识别 → LLM 回复 → TTS 播放')
  29. print(' 4. 输入 q 退出')
  30. print()
  31. history = []
  32. while True:
  33. user_input = input('\n[按回车录音 / 输入 q 退出] > ').strip()
  34. if user_input.lower() == 'q':
  35. print('👋 再见!')
  36. break
  37. try:
  38. # 1. 录音
  39. print('\n[1/4] 录音...')
  40. audio_data = record_until_silence(
  41. max_seconds=Config.MAX_RECORD_SECONDS,
  42. silence_threshold=Config.SILENCE_THRESHOLD,
  43. silence_duration_ms=Config.SILENCE_DURATION_MS,
  44. )
  45. if not audio_data:
  46. print('⚠️ 没录到声音,重试')
  47. continue
  48. # 2. ASR
  49. print('\n[2/4] 语音识别...')
  50. user_text = transcribe(audio_data)
  51. if not user_text:
  52. print('⚠️ 没识别到文字,重试')
  53. continue
  54. # 3. LLM
  55. print('\n[3/4] LLM 对话...')
  56. reply_text = chat(user_text, history)
  57. # 4. TTS(调你的 API)⭐
  58. print('\n[4/4] TTS 合成 + 播放...')
  59. audio_path = synthesize_and_download(reply_text)
  60. play(audio_path)
  61. # 清理临时文件
  62. try:
  63. os.unlink(audio_path)
  64. except OSError:
  65. pass
  66. # 保存历史
  67. history.append({'role': 'user', 'content': user_text})
  68. history.append({'role': 'assistant', 'content': reply_text})
  69. # 只保留最近 5 轮
  70. if len(history) > 10:
  71. history = history[-10:]
  72. except KeyboardInterrupt:
  73. print('\n\n⏸️ 中断')
  74. continue
  75. except Exception as e:
  76. print(f'\n❌ 出错了: {e}')
  77. import traceback
  78. traceback.print_exc()
  79. continue
  80. if __name__ == '__main__':
  81. main()