helen573 commited on
Commit
bc59c65
·
verified ·
1 Parent(s): d259ebe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -224
app.py CHANGED
@@ -1,182 +1,66 @@
1
- import os
2
- import gradio as gr
3
- from datetime import datetime
4
 
5
- # Handle notion-client import
6
- try:
7
- from notion_client import Client
8
- except ImportError:
9
- os.system('pip install notion-client')
10
- from notion_client import Client
11
-
12
- # Handle groq import
13
- try:
14
- from groq import Groq
15
- except ImportError:
16
- os.system('pip install groq')
17
- from groq import Groq
18
-
19
- # Initialize Groq client
20
- client = Groq(api_key=os.getenv('groq_key'))
21
-
22
- # Initialize Notion client
23
- notion = Client(auth=os.getenv('NOTION_API_KEY'))
24
- NOTION_DB_ID = os.getenv('NOTION_DB_ID')
25
-
26
- def log_to_notion(name, chinese_term="", user_input="", bot_response=""):
27
- """Log interaction to Notion database"""
28
- try:
29
- notion.pages.create(
30
- parent={"database_id": NOTION_DB_ID},
31
- properties={
32
- "Name": {"title": [{"text": {"content": name}}]},
33
- "Timestamp": {"date": {"start": datetime.now().isoformat()}},
34
- "Chinese Term": {"rich_text": [{"text": {"content": chinese_term}}]},
35
- "User Input": {"rich_text": [{"text": {"content": user_input}}]},
36
- "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]}
37
- }
38
- )
39
- except Exception as e:
40
- print(f"Error logging to Notion: {e}")
41
-
42
- def translate_to_english(name, word):
43
- """Generate math-related English translation with bilingual explanation"""
44
- messages = [
45
- {
46
- "role": "system",
47
- "content": """你是一個數學翻譯專家。請用以下規則提供翻譯:
48
-
49
- 格式規範:
50
- 1. 文字和數學式必須在同一行,不得換行
51
- 2. 在需要換行處使用 <br> 標記
52
- 3. 所有數學式用 $$...$$ 包覆
53
-
54
- 示例格式:
55
- 對數是指若 $$b^y = x$$,則 $$y$$ 稱為 $$x$$ 以 $$b$$ 為底的對數,記為 $$\log_b x$$。<br>
56
- 換底公式為 $$\log_a x = \frac{\log_c x}{\log_c a}$$。
57
-
58
- 請按此格式提供:
59
- 1. 英文翻譯:[列出數學相關的英文翻譯]<br>
60
-
61
- 2. 中文解釋:[連貫的中文解釋,所有數學式與文字在同一行]<br>
62
-
63
- 3. English Explanation:[連貫的英文解釋,所有數學式與文字在同一行]<br>
64
-
65
- 4. 數學使用場景:[數學使用場景說明,公式與文字在同一行]<br>
66
-
67
- 5. Mathematical Context:[英文場景說明,公式與文字在同一行]"""
68
- },
69
- {
70
- "role": "user",
71
- "content": f"請提供中文詞彙 '{word}' 在數學上的英文翻譯和詳細解釋。"
72
- }
73
- ]
74
-
75
- completion = client.chat.completions.create(
76
- model="llama-3.3-70b-versatile",
77
- messages=messages,
78
- temperature=0.7,
79
- max_tokens=400,
80
- stream=False
81
- )
82
- response = completion.choices[0].message.content
83
-
84
- # Log to Notion
85
- log_to_notion(name=name, chinese_term=word, bot_response=response)
86
- return response
87
-
88
- def generate_example(name, word):
89
- """Generate math-related example sentence for Chinese word"""
90
- messages = [
91
- {
92
- "role": "system",
93
- "content": """你是一個數學教師。請用以下規則提供例句:
94
-
95
- 1. 英文例句:[寫出一個數學相關的英文例句]
96
- - 數學公式必須用 $$...$$ 包覆,並與文字在同一行
97
- - 例如:The solution of $$\log_2 x = 3$$ is $$x = 8$$<br>
98
-
99
- 2. 中文翻譯:[該例句的中文翻譯]
100
- - 保持相同的 LaTeX 數學式格式,確保與文字在同一行
101
- - 例如:方程式 $$\log_2 x = 3$$ 的解為 $$x = 8$$<br>
102
-
103
- 3. 句子解釋:[用中文解釋這個例句中的數學概念]
104
- - 所有數學符號和公式都需要用 LaTeX 格式,並與文字在同一行
105
- - 例如:因為 $$2^3 = 8$$,所以 $$\log_2 8 = 3$$<br>
106
-
107
- 4. Sentence Explanation:[用英文重述上述解釋]
108
- - 保持相同的 LaTeX 數學式格式,確保與文字在同一行"""
109
- },
110
- {
111
- "role": "user",
112
- "content": f"請用中文詞彙 '{word}' 的英文翻譯造一個數學相關的例句。"
113
- }
114
- ]
115
 
116
- completion = client.chat.completions.create(
117
- model="llama-3.3-70b-versatile",
118
- messages=messages,
119
- temperature=0.7,
120
- max_tokens=400,
121
- stream=False
122
  )
123
- response = completion.choices[0].message.content
124
-
125
- # Log to Notion
126
- log_to_notion(name=name, chinese_term=word, bot_response=response)
127
- return response
128
-
129
- def chat_response(name, message, chat_history):
130
- """Generate response for chatbot"""
131
- messages = [
132
- {
133
- "role": "system",
134
- "content": """你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。
135
-
136
- 格式要求:
137
- 1. 所有數學公式都要用 LaTeX 格式書寫(使用 $$...$$ 符號包覆)
138
- 2. 數學式必須與文字在同一行,中間使用 <br> 換行
139
- 3. 變數使用 $$x$$, $$y$$, $$a$$, $$b$$ 等格式
140
- 4. 運算符號使用 $$+$$, $$-$$, $$\times$$, $$\div$$ 等格式
141
- 5. 分數使用 $$\frac{分子}{分母}$$ 格式
142
- 6. 示範解題時,每個步驟的說明文字和數學式要在同一行
143
-
144
- 示例格式:
145
- 讓我們來看一道對數方程式:$$\log_2 x = 3$$<br>
146
- 解題步驟:<br>
147
- 1. 利用指數的定義:$$2^3 = x$$<br>
148
- 2. 計算得到:$$x = 8$$<br>
149
- 因此,方程式 $$\log_2 x = 3$$ 的解為 $$x = 8$$。"""
150
- }
151
- ]
152
-
153
- for msg in chat_history:
154
- messages.append({"role": "user", "content": msg[0]})
155
- if msg[1]:
156
- messages.append({"role": "assistant", "content": msg[1]})
157
 
158
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- completion = client.chat.completions.create(
161
- model="llama-3.3-70b-versatile",
162
- messages=messages,
163
- temperature=1,
164
- max_tokens=1024,
165
- stream=False
166
- )
167
- response = completion.choices[0].message.content
168
 
169
- # Log to Notion
170
- log_to_notion(name=name, user_input=message, bot_response=response)
171
- return response
 
 
 
172
 
173
- def respond(name, message, history):
174
- """Process chatbot response and update history"""
175
- response = chat_response(name, message, history)
176
- history.append((message, response))
177
- return "", history
178
 
179
- # Custom CSS for math rendering and layout
180
  custom_css = """
181
  .math-container .katex {
182
  font-size: 1.1em;
@@ -189,6 +73,11 @@ custom_css = """
189
  .output-box {
190
  font-size: 1.1em;
191
  line-height: 2;
 
 
 
 
 
192
  }
193
  .title {
194
  text-align: center;
@@ -225,58 +114,5 @@ custom_css = """
225
  }
226
  """
227
 
228
- # Create Gradio interface
229
- with gr.Blocks(css=custom_css) as demo:
230
- gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
231
-
232
- # Add name input at the top
233
- name_input = gr.Textbox(
234
- label="請輸入您的名字 | Enter Your Name",
235
- placeholder="請輸入您的名字... | Please enter your name...",
236
- lines=1,
237
- elem_classes=["input-box"]
238
- )
239
-
240
- with gr.Tab("📚 單字英譯系統"):
241
- with gr.Row():
242
- word_input = gr.Textbox(
243
- label="請輸入中文詞彙 | Enter Chinese Term",
244
- placeholder="輸入中文詞彙(例如:向量、函數、極限)...",
245
- lines=1,
246
- elem_classes=["input-box"]
247
- )
248
-
249
- with gr.Row():
250
- translate_btn = gr.Button("🔄 英譯 | Translate", variant="primary")
251
- example_btn = gr.Button("📝 例句 | Example")
252
-
253
- output_text = gr.Markdown(
254
- label="翻譯結果 | Translation Result",
255
- value="翻譯結果將在這裡顯示... | Translation results will be displayed here...",
256
- elem_classes=["output-box", "math-container", "contains-math", "gradio-markdown"]
257
- )
258
-
259
- translate_btn.click(translate_to_english, inputs=[name_input, word_input], outputs=output_text)
260
- example_btn.click(generate_example, inputs=[name_input, word_input], outputs=output_text)
261
-
262
- with gr.Tab("💬 數學對話系統"):
263
- chatbot = gr.Chatbot(
264
- [],
265
- elem_id="chatbot",
266
- bubble_full_width=False,
267
- avatar_images=("👨‍🎓", "👨‍🏫"),
268
- elem_classes=["math-container", "contains-math"]
269
- )
270
-
271
- msg = gr.Textbox(
272
- label="發送訊息 | Send Message",
273
- placeholder="請輸入您的問題... | Enter your question...",
274
- show_label=False,
275
- elem_classes=["input-box"]
276
- )
277
-
278
- clear = gr.ClearButton([msg, chatbot], value="🗑️ 清除對話 | Clear Chat")
279
- msg.submit(respond, [name_input, msg, chatbot], [msg, chatbot])
280
-
281
  if __name__ == "__main__":
282
  demo.launch()
 
1
+ # [Previous imports and function definitions remain the same...]
 
 
2
 
3
+ # Create Gradio interface
4
+ with gr.Blocks(css=custom_css) as demo:
5
+ gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Add name input at the top
8
+ name_input = gr.Textbox(
9
+ label="請輸入您的名字 | Enter Your Name",
10
+ placeholder="請輸入您的名字... | Please enter your name...",
11
+ lines=1,
12
+ elem_classes=["input-box"]
13
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ with gr.Tab("📚 單字英譯系統"):
16
+ with gr.Row():
17
+ word_input = gr.Textbox(
18
+ label="請輸入中文詞彙 | Enter Chinese Term",
19
+ placeholder="輸入中文詞彙(例如:向量、函數、極限)...",
20
+ lines=1,
21
+ elem_classes=["input-box"]
22
+ )
23
+
24
+ with gr.Row():
25
+ with gr.Column(scale=1):
26
+ translate_btn = gr.Button("🔄 英譯 | Translate", variant="primary", size="lg")
27
+ translate_output = gr.Markdown(
28
+ label="英譯結果 | Translation Result",
29
+ value="英譯結果將在這裡顯示... | Translation results will be displayed here...",
30
+ elem_classes=["output-box", "math-container", "contains-math", "gradio-markdown"]
31
+ )
32
+
33
+ with gr.Column(scale=1):
34
+ example_btn = gr.Button("📝 例句 | Example", size="lg")
35
+ example_output = gr.Markdown(
36
+ label="例句結果 | Example Result",
37
+ value="例句結果將在這裡顯示... | Example results will be displayed here...",
38
+ elem_classes=["output-box", "math-container", "contains-math", "gradio-markdown"]
39
+ )
40
+
41
+ translate_btn.click(translate_to_english, inputs=[name_input, word_input], outputs=translate_output)
42
+ example_btn.click(generate_example, inputs=[name_input, word_input], outputs=example_output)
43
 
44
+ with gr.Tab("💬 數學對話系統"):
45
+ chatbot = gr.Chatbot(
46
+ [],
47
+ elem_id="chatbot",
48
+ bubble_full_width=False,
49
+ avatar_images=("👨‍🎓", "👨‍🏫"),
50
+ elem_classes=["math-container", "contains-math"]
51
+ )
52
 
53
+ msg = gr.Textbox(
54
+ label="發送訊息 | Send Message",
55
+ placeholder="請輸入您的問題... | Enter your question...",
56
+ show_label=False,
57
+ elem_classes=["input-box"]
58
+ )
59
 
60
+ clear = gr.ClearButton([msg, chatbot], value="🗑️ 清除對話 | Clear Chat")
61
+ msg.submit(respond, [name_input, msg, chatbot], [msg, chatbot])
 
 
 
62
 
63
+ # Update custom CSS to style the new layout
64
  custom_css = """
65
  .math-container .katex {
66
  font-size: 1.1em;
 
73
  .output-box {
74
  font-size: 1.1em;
75
  line-height: 2;
76
+ min-height: 200px;
77
+ padding: 1em;
78
+ border: 1px solid #e2e8f0;
79
+ border-radius: 8px;
80
+ margin-top: 1em;
81
  }
82
  .title {
83
  text-align: center;
 
114
  }
115
  """
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  if __name__ == "__main__":
118
  demo.launch()