SC999 commited on
Commit
37ed40f
1 Parent(s): d5da84b

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +49 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #app.py
2
+ import time
3
+ import gradio as gr
4
+ import google.generativeai as genai
5
+ import os
6
+
7
+ # 從 Hugging Face secrets 中讀取 API 金鑰(如果需要)
8
+ api_key = os.getenv('GOOGLE_API_KEY')
9
+ if not api_key:
10
+ raise ValueError("請設置 'GOOGLE_API_KEY' 環境變數")
11
+
12
+ # 設定 API 金鑰
13
+ genai.configure(api_key=api_key)
14
+
15
+ # 初始化模型
16
+ try:
17
+ model = genai.GenerativeModel('gemini-1.5-pro')
18
+ chat = model.start_chat(history=[])
19
+ print("模型載入成功。")
20
+ except Exception as e:
21
+ raise ValueError(f"無法載入模型:{e}")
22
+
23
+ # 將 Gradio 的歷史紀錄轉換為 Gemini 格式
24
+ def transform_history(history):
25
+ new_history = []
26
+ for chat in history:
27
+ new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
28
+ new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
29
+ return new_history
30
+
31
+ # 回應生成函數
32
+ def response(message, history):
33
+ global chat
34
+ # 將 Gradio 的歷史紀錄轉換為 Gemini 的格式
35
+ chat.history = transform_history(history)
36
+
37
+ # 發送訊息到 Gemini API
38
+ response = chat.send_message(message)
39
+ response.resolve()
40
+
41
+ # 逐字回傳生成的文字,實現打字機效果
42
+ for i in range(len(response.text)):
43
+ time.sleep(0.05) # 每個字符間隔 0.05 秒
44
+ yield response.text[: i+1]
45
+
46
+ # 建立 Gradio 聊天界面
47
+ gr.ChatInterface(response,
48
+ title='Gemini Chat',
49
+ textbox=gr.Textbox(placeholder="Question to Gemini")).launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio
2
+ google-generativeai