ChingCL commited on
Commit
42c82db
·
verified ·
1 Parent(s): 8cae9e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -106
app.py CHANGED
@@ -1,117 +1,68 @@
 
1
  import gradio as gr
2
 
3
- # 創建 Gradio 介面
4
- def create_interface():
5
- with gr.Blocks() as demo:
6
- gr.HTML("""
7
- <!DOCTYPE html>
8
- <html>
9
- <head>
10
- <title>成語對對碰</title>
11
- <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
12
- <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
13
- <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
14
- </head>
15
- <body>
16
- <div id="root"></div>
17
- <script type="text/babel">
18
- // React 組件
19
- const idiomDatabase = [
20
- { mainIdiom: '急如星火', synonyms: ['迫在眉睫', '刻不容緩'], meaning: '形容事情非常緊急' },
21
- { mainIdiom: '一葉知秋', synonyms: ['見微知著', '月暈而風'], meaning: '從小徵兆可以預見未來的發展' },
22
- { mainIdiom: '一丘之貉', synonyms: ['沆瀣一氣', '狐群狗黨'], meaning: '形容品性相同的壞人' },
23
- { mainIdiom: '一蹴可幾', synonyms: ['一步登天', '唾手可得'], meaning: '一下子就能達到目的' },
24
- { mainIdiom: '一暴十寒', synonyms: ['兩天打魚,三天曬網', '虎頭蛇尾'], meaning: '形容學習或做事不能持之以恆' },
25
- { mainIdiom: '環堵蕭然', synonyms: ['一貧如洗', '家徒四壁'], meaning: '形容生活很貧困' },
26
- { mainIdiom: '一字千金', synonyms: ['字字珠璣', '文不加點'], meaning: '形容文章寫得好,文字珍貴' },
27
- { mainIdiom: '一擲千金', synonyms: ['揮金如土', '揮霍無度'], meaning: '形容揮霍錢財' },
28
- { mainIdiom: '生靈塗炭', synonyms: ['民不聊生', '民生凋敝'], meaning: '形容人民生活困苦' },
29
- { mainIdiom: '瓜熟蒂落', synonyms: ['水到渠成', '順理成章'], meaning: '形容事情自然成功' }
30
- ];
31
 
32
- function ChineseIdiomGame() {
33
- const [questionIndex, setQuestionIndex] = React.useState(0);
34
- const [score, setScore] = React.useState(0);
35
- const [selectedAnswers, setSelectedAnswers] = React.useState([]);
36
 
37
- const currentQuestion = idiomDatabase[questionIndex];
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- const handleSelect = (answer) => {
40
- if (selectedAnswers.includes(answer)) return;
41
- if (currentQuestion.synonyms.includes(answer)) {
42
- const newSelected = [...selectedAnswers, answer];
43
- setSelectedAnswers(newSelected);
44
- if (newSelected.length === 2) {
45
- const newScore = score + 10;
46
- setScore(newScore);
47
- setTimeout(() => {
48
- setQuestionIndex((questionIndex + 1) % idiomDatabase.length);
49
- setSelectedAnswers([]);
50
- }, 1000);
51
- }
52
- }
53
- };
54
 
55
- const options = [
56
- ...currentQuestion.synonyms,
57
- '望穿秋水',
58
- '守株待兔',
59
- '揮金如土',
60
- '一暴十寒'
61
- ].sort(() => Math.random() - 0.5);
62
 
63
- return (
64
- <div style={{ padding: '20px' }}>
65
- <h1 style={{ textAlign: 'center', marginBottom: '20px' }}>成語對對碰</h1>
66
- <div style={{
67
- backgroundColor: '#f0f0f0',
68
- padding: '20px',
69
- borderRadius: '8px',
70
- marginBottom: '20px'
71
- }}>
72
- <h2 style={{ textAlign: 'center' }}>{currentQuestion.mainIdiom}</h2>
73
- <p style={{ textAlign: 'center' }}>{currentQuestion.meaning}</p>
74
- </div>
75
- <div style={{
76
- display: 'grid',
77
- gridTemplateColumns: 'repeat(2, 1fr)',
78
- gap: '10px'
79
- }}>
80
- {options.map((option, index) => (
81
- <button
82
- key={index}
83
- onClick={() => handleSelect(option)}
84
- style={{
85
- padding: '10px',
86
- backgroundColor: selectedAnswers.includes(option) ? '#4CAF50' : 'white',
87
- color: selectedAnswers.includes(option) ? 'white' : 'black',
88
- border: '1px solid #ddd',
89
- borderRadius: '4px'
90
- }}
91
- >
92
- {option}
93
- </button>
94
- ))}
95
- </div>
96
- <div style={{
97
- marginTop: '20px',
98
- textAlign: 'center'
99
- }}>
100
- 分數: {score}
101
- </div>
102
- </div>
103
- );
104
- }
105
 
106
- ReactDOM.render(<ChineseIdiomGame />, document.getElementById('root'));
107
- </script>
108
- </body>
109
- </html>
110
- """)
111
-
112
  return demo
113
 
114
- # 啟動 Gradio 介面
115
  if __name__ == "__main__":
116
- demo = create_interface()
117
- demo.launch()
 
1
+ import os
2
  import gradio as gr
3
 
4
+ # 確保 groq 已安裝
5
+ try:
6
+ from groq import Groq
7
+ except ImportError:
8
+ os.system('pip install groq')
9
+ from groq import Groq
10
+
11
+ # 初始化 Groq 客戶端
12
+ client = Groq()
13
+
14
+ # 獲取 API 密鑰
15
+ api_key = os.getenv('groq_key')
16
+ if not api_key:
17
+ raise ValueError("API key 'groq_key' 未設定於環境變數中!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ client.api_key = api_key
 
 
 
20
 
21
+ def chat_with_groq(user_message):
22
+ """與 Groq 模型進行互動"""
23
+ try:
24
+ completion = client.chat.completions.create(
25
+ model="llama-3.1-70b-versatile",
26
+ messages=[
27
+ {"role": "system", "content": "你是一個國中國文老師,會出成語遊戲讓學生玩"},
28
+ {"role": "user", "content": user_message}
29
+ ],
30
+ temperature=1,
31
+ max_tokens=1024,
32
+ top_p=1,
33
+ stream=False
34
+ )
35
 
36
+ response = ""
37
+ for chunk in completion:
38
+ response += chunk.choices[0].delta.content or ""
39
+ return response
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ except Exception as e:
42
+ return f"發生錯誤:{e}"
 
 
 
 
 
43
 
44
+ # 定義 Gradio 介面
45
+ def gradio_chatbot():
46
+ chatbot = gr.Chatbot()
47
+
48
+ def respond(message, history):
49
+ response = chat_with_groq(message)
50
+ history.append((message, response))
51
+ return history, history
52
+
53
+ with gr.Blocks() as demo:
54
+ with gr.Row():
55
+ gr.Markdown("### 成語遊戲 Chatbot")
56
+ with gr.Row():
57
+ chatbot = gr.Chatbot()
58
+ with gr.Row():
59
+ user_input = gr.Textbox(placeholder="輸入你的訊息...")
60
+ submit_button = gr.Button("送出")
61
+ submit_button.click(respond, [user_input, chatbot], [chatbot, chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
 
 
 
 
 
63
  return demo
64
 
65
+ # 啟動應用程式
66
  if __name__ == "__main__":
67
+ app = gradio_chatbot()
68
+ app.launch()