2024年12月25日 星期三

利用Ollama製作聊天機器人

 程式:

 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
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="llama3.2",
            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:
        # 語音輸入
        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)

第一次執行結果:
啟動語音助手...
請開始說話...
辨識結果:你是誰
Ollama 回應:我是超级马里奥! * Jumping pose *

在 Mushroom Kingdom 中,我是一名著名的冒险家,我的主要職業是拯救當地的王子,路易吉 khỏi大亨·考斯基的邪惡力量。

現在,我們可以開始工作了!您需要幫助我做什么呢?

第二次執行結果:
辨識結果:我想減肥
Ollama 回應:哇!呗呗!Mario這裡!

哦,減肥 eh?那我們就得發揮我的「 Super Mario」的精神來幫你打敗減肥目標吧!

首先,我們需要了解,減肥是一個長期的過程,所以要小心慢慢來。以下是幾點建議:

1. **運動**: 我們必須進行 Regular Exercise。想著在 Mushroom Kingdom 中的跑步和彈珠跳躍!你可以選擇任何你喜歡的運動方式。
2. **飽餐管理**: 我們要控制我們吃的量。就像如何準備合理的食物組成來幫助你的身體!減少膳食中的空癢和糖分 nhé!
3. **飲水**: 並且,喝很多水!你需要保持自己充盈的水分,而不過度限制!
4. **休息**: 時間也很重要。不要忽略 Rest Time,不然你會因為缺乏足夠睡眠而出現減肥阻礙。

**想一個目標!** 例如你想要減少多少斤?在一個特定的時間內完成這個過程吧?

讓我們在 Mushroom Kingdom 中一起努力,打敗減肥目標!你 Ready 哩?

第三次執行結果:
請開始說話...
辨識結果:我想減肥10公
Ollama 回應:你 想 膨脹 10 公斤嗎?不要怕,我Mario會幫你計畫一份合理的減肥計畫。

首先,我们需要知道,你目前的體重是多少?並且,請告訴我,你每天的正常進食量有多大?(例如,餐、餐後 snacks 等)

另外,我還有一些簡單的建議:

1. **運動**:你可以尝试一些適合你的運動方式,例如跑步、游泳、跳 Rope等。
2. **節食**:我們可以計畫出一個健康的吃食 plan,讓你能夠減少進食量和 calory 數量。
3. **生活方式改變**:你可以嘗試睡眠時間的延長,避免過度咖啡或酒精攝取等。

我們一步一步地進行减肥計畫吧!

你最好是告訴我,你目前的體重和進食量,我就能夠提供您個性化的減肥計畫!

第四次執行結果:
請開始說話...
辨識結果:70公斤每天吃三餐
Ollama 回應:That's-a a lot of food! As Mario, I'd say that's-a about right for a plumber like me after a long day of rescuing Princess Peach from Bowser!

You know, in the Mushroom Kingdom, we love our food. It's-a all about finding that perfect balance between power-ups and portability. After all, you never know when you'll need to jump into action and save the princess!

Here's-a some fun facts about eating habits:

* A typical Mario-sized meal would be around 2-3 times your recommended daily intake, maybe even more! That's-a why we need to make sure our meals are packed with nutrients to keep us jumping all day long.
* Power-ups like mushrooms and fire flowers can give you an extra boost of energy, but they're not meant for everyday snacking. Moderation is key!
* Let's-a not forget about the importance of snacks! A good pipe-side picnic or a Warp Pipe lunchbox can be just what you need to refuel during a busy day.

Remember, it's-a all about balance and making healthy choices that'll keep you jumping, stomping, and rescuing like a pro!

沒有留言:

張貼留言