File size: 2,130 Bytes
952b474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82525ae
 
 
 
 
 
 
 
952b474
 
 
 
 
 
 
 
 
 
 
82525ae
 
 
 
 
 
952b474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82525ae
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
import time
import gradio as gr
import google.generativeai as genai
import os

# 從 Hugging Face secrets 中讀取 API 金鑰(如果需要)
api_key = os.getenv('GOOGLE_API_KEY')
if not api_key:
    raise ValueError("請設置 'GOOGLE_API_KEY' 環境變數")

# 設定 API 金鑰
genai.configure(api_key=api_key)

# 初始化模型
try:
    model = genai.GenerativeModel('gemini-1.5-pro')
    chat = model.start_chat(history=[])
    print("模型載入成功。")
except Exception as e:
    raise ValueError(f"無法載入模型:{e}")

# 定義與酒類、調酒、酒吧相關的關鍵詞
keywords = ["alcohol", "cocktail", "beer", "wine", "whiskey", "vodka", "rum", "bartender", "bar", "drink", "liquor", "spirits"]

# 檢查訊息是否與酒類、調酒、酒吧相關
def is_relevant_question(message):
    message_lower = message.lower()  # 將訊息轉為小寫以便檢查
    return any(keyword in message_lower for keyword in keywords)

# 將 Gradio 的歷史紀錄轉換為 Gemini 格式
def transform_history(history):
    new_history = []
    for chat in history:
        new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
        new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
    return new_history

# 回應生成函數
def response(message, history):
    global chat
    
    # 檢查訊息是否與酒類、調酒、酒吧相關
    if not is_relevant_question(message):
        yield "I'm sorry, I can only answer questions related to alcohol, cocktails, and bars."
        return
    
    # 將 Gradio 的歷史紀錄轉換為 Gemini 的格式
    chat.history = transform_history(history)
    
    # 發送訊息到 Gemini API
    response = chat.send_message(message)
    response.resolve()

    # 逐字回傳生成的文字,實現打字機效果
    for i in range(len(response.text)):
        time.sleep(0.05)  # 每個字符間隔 0.05 秒
        yield response.text[: i+1]

# 建立 Gradio 聊天界面
gr.ChatInterface(response,
                 title='Gemini Chat',
                 textbox=gr.Textbox(placeholder="Question to Gemini")).launch(share=True)