2025年6月3日 星期二

加入try..except來修復聊天機器人逾時的錯誤

補充執行本土大型語言模型的指令

模型:llama3-taide-lx-8b-chat-alpha1

前一篇文章:利用Ollama結合本土的大型語言模型製作聊天機器人

逾時未輸入語音的錯誤:

Traceback (most recent call last):

  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python313/ollama4.py", line 51, in <module>

    user_input = recognize_speech()

  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python313/ollama4.py", line 17, in recognize_speech

    audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)

  File "C:\Users\cheng-min\AppData\Local\Programs\Python\Python313\Lib\site-packages\speech_recognition\__init__.py", line 460, in listen

    for a in result:

  File "C:\Users\cheng-min\AppData\Local\Programs\Python\Python313\Lib\site-packages\speech_recognition\__init__.py", line 490, in _listen

    raise WaitTimeoutError("listening timed out while waiting for phrase to start")

speech_recognition.exceptions.WaitTimeoutError: listening timed out while waiting for phrase to start

修改程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import speech_recognition as sr
import pyttsx3
import requests
import ollama

# 初始化文字轉語音引擎
engine = pyttsx3.init()
engine.setProperty('rate', 150)  # 語速調整
engine.setProperty('volume', 0.9)  # 音量調整

# 語音轉文字
def recognize_speech():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("請開始說話...")
        try:
            audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
            text = recognizer.recognize_google(audio, language="zh-TW")
            print(f"辨識結果:{text}")
            return text
        except sr.UnknownValueError:
            print("無法辨識語音,請再試一次。")
            return None
        except sr.RequestError as e:
            print(f"語音服務出現錯誤:{e}")
            return None

# 發送請求到 Ollama API
def get_ollama_response(prompt):
    try:
        # 替換為適用的 ollama.generate 調用方法
        response = ollama.generate(
            model="cwchang/llama3-taide-lx-8b-chat-alpha1:latest",
            prompt=prompt
        )
        return response["response"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 文字轉語音
def speak_text(text):
    engine.say(text)
    engine.runAndWait()

# 主程序
if __name__ == "__main__":
    print("啟動語音助手(結束請說退出)...")
    while True:
        try:
            # 語音輸入
            user_input = recognize_speech()
            if user_input:
                # 停止程序的關鍵字
                if "結束" in user_input or "退出" in user_input:
                    print("結束程序。")
                    speak_text("感謝使用,再見!")
                    break
                # 發送給 Ollama 並取得回應
                response = get_ollama_response(user_input)
                print(f"Ollama 回應:{response}")

                # 語音輸出
                speak_text(response)
        except sr.WaitTimeoutError:
             print("未偵測到語音輸入,請再試一次。")

執行結果:
啟動語音助手(結束請說退出)...
請開始說話...
辨識結果:給我一則30個字的童話
Ollama 回應:從前有一座神秘島嶼,住著一群善良的小妖怪,他們幫助旅行者找到心之所向,但代價是他們必須完成一個任務:在月光下散播歡樂與笑聲。於是,小妖怪們在島上舉辦了最歡樂的派對,吸引了眾多旅人參加,在月光下共舞、共享喜悅,成為永恆的傳說。
請開始說話...
辨識結果:結束
結束程序。

沒有留言:

張貼留言