helen573 commited on
Commit
1025cee
·
verified ·
1 Parent(s): 24e9376

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -107
app.py CHANGED
@@ -2,32 +2,33 @@ import os
2
  import gradio as gr
3
  from datetime import datetime
4
 
 
5
  try:
6
  from notion_client import Client
7
  except ImportError:
8
  os.system('pip install notion-client')
9
  from notion_client import Client
10
 
 
11
  try:
12
  from groq import Groq
13
  except ImportError:
14
  os.system('pip install groq')
15
  from groq import Groq
16
 
 
17
  client = Groq(api_key=os.getenv('groq_key'))
 
 
18
  notion = Client(auth=os.getenv('NOTION_API_KEY'))
19
  NOTION_DB_ID = os.getenv('NOTION_DB_ID')
20
 
 
21
  custom_css = """
22
  .math-container .katex {
23
  font-size: 1.1em;
24
- display: inline !important;
25
- white-space: nowrap !important;
26
- }
27
- .math-container p {
28
  display: inline-block !important;
29
- width: 100% !important;
30
- white-space: normal !important;
31
  }
32
  .input-box {
33
  font-size: 1.1em;
@@ -40,7 +41,6 @@ custom_css = """
40
  border: 1px solid #e2e8f0;
41
  border-radius: 8px;
42
  margin-top: 1em;
43
- white-space: normal !important;
44
  }
45
  .title {
46
  text-align: center;
@@ -78,6 +78,7 @@ custom_css = """
78
  """
79
 
80
  def log_to_notion(name, chinese_term="", user_input="", bot_response=""):
 
81
  try:
82
  notion.pages.create(
83
  parent={"database_id": NOTION_DB_ID},
@@ -92,62 +93,32 @@ def log_to_notion(name, chinese_term="", user_input="", bot_response=""):
92
  except Exception as e:
93
  print(f"Error logging to Notion: {e}")
94
 
95
- def format_math_response(response):
96
- """Format response to ensure proper LaTeX formatting"""
97
- # Replace incorrect LaTeX formatting with correct one
98
- response = response.replace(r'$\log_b(x)', r'$$\log_b(x)$$')
99
- response = response.replace(r'$\log_', r'$$\log_')
100
- response = response.replace('log_', '\\log_')
101
- response = response.replace('$x', '$$x$$')
102
- response = response.replace('$b$', '$$b$$')
103
- response = response.replace('$1', '$$1$$')
104
- response = response.replace('$(', '$$(')
105
- response = response.replace(')$', ')$$')
106
-
107
- # Clean up any remaining single dollar signs
108
- parts = response.split('$')
109
- formatted_parts = []
110
- for i, part in enumerate(parts):
111
- if i % 2 == 1: # Inside math expression
112
- formatted_parts.append(f'$${part}$$')
113
- else: # Outside math expression
114
- formatted_parts.append(part)
115
- response = ''.join(formatted_parts)
116
-
117
- # Fix common spacing issues
118
- response = response.replace('$$$$', '$$')
119
- response = response.replace(' ', ' ')
120
-
121
- # Format line breaks
122
- lines = [line.strip() for line in response.split('\n') if line.strip()]
123
- return '<br>'.join(lines)
124
-
125
  def translate_to_english(name, word):
 
126
  messages = [
127
  {
128
  "role": "system",
129
  "content": """你是一個數學翻譯專家。請用以下規則提供翻譯:
130
 
131
- 1. 數學式格式規範:
132
- - 所有數學式都必須使用 $$...$$
133
- - 對數表示:$$\\log_b(x)$$
134
- - 變數:$$x$$, $$y$$, $$a$$, $$b$$
135
- - 數字:$$1$$, $$2$$, $$3$$
136
- - 不要使用單個 $ 符號
137
- - 所有數學符號都要用 LaTeX 格式
138
-
139
- 2. 對數的特別注意事項:
140
- - 正確格式:$$\\log_b(x)$$
141
- - 底數是 b 時:$$\\log_b$$
142
- - 底數是 2 時:$$\\log_2$$
143
- - 底數是 e 時:$$\\ln$$
144
-
145
- 3. 回應格式(每項使用 <br> 分隔):
146
- 1. 英文翻譯:[包含完整的數學符號]<br>
147
- 2. 中文解釋:[包含完整的數學符號]<br>
148
- 3. English Explanation:[包含完整的數學符號]<br>
149
- 4. 數學使用場景:[包含完整的數學符號]<br>
150
- 5. Mathematical Context:[包含完整的數學符號]<br>"""
151
  },
152
  {
153
  "role": "user",
@@ -163,35 +134,32 @@ def translate_to_english(name, word):
163
  stream=False
164
  )
165
  response = completion.choices[0].message.content
166
- formatted_response = format_math_response(response)
167
- log_to_notion(name=name, chinese_term=word, bot_response=formatted_response)
168
- return formatted_response
 
169
 
170
  def generate_example(name, word):
 
171
  messages = [
172
  {
173
  "role": "system",
174
  "content": """你是一個數學教師。請用以下規則提供例句:
175
 
176
- 1. 數學式格式規範:
177
- - 所有數學式都必須使用 $$...$$
178
- - 對數表示:$$\\log_b(x)$$
179
- - 變數:$$x$$, $$y$$, $$a$$, $$b$$
180
- - 數字:$$1$$, $$2$$, $$3$$
181
- - 不要使用單個 $ 符號
182
- - 所有數學符號都要用 LaTeX 格式
183
-
184
- 2. 對數的特別注意事項:
185
- - 正確格式:$$\\log_b(x)$$
186
- - 底數是 b 時:$$\\log_b$$
187
- - 底數是 2 時:$$\\log_2$$
188
- - 底數是 e 時:$$\\ln$$
189
-
190
- 3. 回應格式(每項使用 <br> 分隔):
191
- 1. 英文例句:[包含完整的數學符號]<br>
192
- 2. 中文翻譯:[包含完整的數學符號]<br>
193
- 3. 句子解釋:[包含完整的數學符號]<br>
194
- 4. Sentence Explanation:[包含完整的數學符號]<br>"""
195
  },
196
  {
197
  "role": "user",
@@ -207,34 +175,32 @@ def generate_example(name, word):
207
  stream=False
208
  )
209
  response = completion.choices[0].message.content
210
- formatted_response = format_math_response(response)
211
- log_to_notion(name=name, chinese_term=word, bot_response=formatted_response)
212
- return formatted_response
 
213
 
214
  def chat_response(name, message, chat_history):
 
215
  messages = [
216
  {
217
  "role": "system",
218
- "content": """你是一個高中數學老師,使用英文回應。請確保:
219
-
220
- 1. 數學式格式規範:
221
- - 所有數學式都必須使用 $$...$$
222
- - 對數表示:$$\\log_b(x)$$
223
- - 變數:$$x$$, $$y$$, $$a$$, $$b$$
224
- - 數字:$$1$$, $$2$$, $$3$$
225
- - 不要使用單個 $ 符號
226
- - 所有數學符號都要用 LaTeX 格式
227
-
228
- 2. 對數的特別注意事項:
229
- - 正確格式:$$\\log_b(x)$$
230
- - 底數是 b 時:$$\\log_b$$
231
- - 底數是 2 時:$$\\log_2$$
232
- - 底數是 e 時:$$\\ln$$
233
-
234
- 3. 格式要求:
235
- - 用 <br> 分隔不同段落
236
- - 數學式必須與文字在同一行
237
- - 每個步驟的說明文字和數學式都要在同一行"""
238
  }
239
  ]
240
 
@@ -253,18 +219,22 @@ def chat_response(name, message, chat_history):
253
  stream=False
254
  )
255
  response = completion.choices[0].message.content
256
- formatted_response = format_math_response(response)
257
- log_to_notion(name=name, user_input=message, bot_response=formatted_response)
258
- return formatted_response
 
259
 
260
  def respond(name, message, history):
 
261
  response = chat_response(name, message, history)
262
  history.append((message, response))
263
  return "", history
264
 
 
265
  with gr.Blocks(css=custom_css) as demo:
266
  gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
267
-
 
268
  name_input = gr.Textbox(
269
  label="請輸入您的名字 | Enter Your Name",
270
  placeholder="請輸入您的名字... | Please enter your name...",
@@ -321,4 +291,4 @@ with gr.Blocks(css=custom_css) as demo:
321
  msg.submit(respond, [name_input, msg, chatbot], [msg, chatbot])
322
 
323
  if __name__ == "__main__":
324
- demo.launch()
 
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
+ # Define custom CSS first
27
  custom_css = """
28
  .math-container .katex {
29
  font-size: 1.1em;
 
 
 
 
30
  display: inline-block !important;
31
+ white-space: nowrap !important;
 
32
  }
33
  .input-box {
34
  font-size: 1.1em;
 
41
  border: 1px solid #e2e8f0;
42
  border-radius: 8px;
43
  margin-top: 1em;
 
44
  }
45
  .title {
46
  text-align: center;
 
78
  """
79
 
80
  def log_to_notion(name, chinese_term="", user_input="", bot_response=""):
81
+ """Log interaction to Notion database"""
82
  try:
83
  notion.pages.create(
84
  parent={"database_id": NOTION_DB_ID},
 
93
  except Exception as e:
94
  print(f"Error logging to Notion: {e}")
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  def translate_to_english(name, word):
97
+ """Generate math-related English translation with bilingual explanation"""
98
  messages = [
99
  {
100
  "role": "system",
101
  "content": """你是一個數學翻譯專家。請用以下規則提供翻譯:
102
 
103
+ 格式規範:
104
+ 1. 文字和數學式必須在同一行,不得換行
105
+ 2. 在需要換行處使用 <br> 標記
106
+ 3. 所有數學式用 $$...$$ 包覆
107
+
108
+ 示例格式:
109
+ 對數是指若 $$b^y = x$$,則 $$y$$ 稱為 $$x$$ 以 $$b$$ 為底的對數,記為 $$\log_b x$$。<br>
110
+ 換底公式為 $$\log_a x = \frac{\log_c x}{\log_c a}$$。
111
+
112
+ 請按此格式提供:
113
+ 1. 英文翻譯:[列出數學相關的英文翻譯]<br>
114
+
115
+ 2. 中文解釋:[連貫的中文解釋,所有數學式與文字在同一行]<br>
116
+
117
+ 3. English Explanation:[連貫的英文解釋,所有數學式與文字在同一行]<br>
118
+
119
+ 4. 數學使用場景:[數學使用場景說明,公式與文字在同一行]<br>
120
+
121
+ 5. Mathematical Context:[英文場景說明,公式與文字在同一行]"""
 
122
  },
123
  {
124
  "role": "user",
 
134
  stream=False
135
  )
136
  response = completion.choices[0].message.content
137
+
138
+ # Log to Notion
139
+ log_to_notion(name=name, chinese_term=word, bot_response=response)
140
+ return response
141
 
142
  def generate_example(name, word):
143
+ """Generate math-related example sentence for Chinese word"""
144
  messages = [
145
  {
146
  "role": "system",
147
  "content": """你是一個數學教師。請用以下規則提供例句:
148
 
149
+ 1. 英文例句:[寫出一個數學相關的英文例句]
150
+ - 數學公式必須用 $$...$$ 包覆,並與文字在同一行
151
+ - 例如:The solution of $$\log_2 x = 3$$ is $$x = 8$$<br>
152
+
153
+ 2. 中文翻譯:[該例句的中文翻譯]
154
+ - 保持相同的 LaTeX 數學式格式,確保與文字在同一行
155
+ - 例如:方程式 $$\log_2 x = 3$$ 的解為 $$x = 8$$<br>
156
+
157
+ 3. 句子解釋:[用中文解釋這個例句中的數學概念]
158
+ - 所有數學符號和公式都需要用 LaTeX 格式,並與文字在同一行
159
+ - 例如:因為 $$2^3 = 8$$,所以 $$\log_2 8 = 3$$<br>
160
+
161
+ 4. Sentence Explanation:[用英文重述上述解釋]
162
+ - 保持相同的 LaTeX 數學式格式,確保與文字在同一行"""
 
 
 
 
 
163
  },
164
  {
165
  "role": "user",
 
175
  stream=False
176
  )
177
  response = completion.choices[0].message.content
178
+
179
+ # Log to Notion
180
+ log_to_notion(name=name, chinese_term=word, bot_response=response)
181
+ return response
182
 
183
  def chat_response(name, message, chat_history):
184
+ """Generate response for chatbot"""
185
  messages = [
186
  {
187
  "role": "system",
188
+ "content": """你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。
189
+
190
+ 格式要求:
191
+ 1. 所有數學公式都要用 LaTeX 格式書寫(使用 $$...$$ 符號包覆)
192
+ 2. 數學式必須與文字在同一行,中間使用 <br> 換行
193
+ 3. 變數使用 $$x$$, $$y$$, $$a$$, $$b$$ 等格式
194
+ 4. 運算符號使用 $$+$$, $$-$$, $$\times$$, $$\div$$ 等格式
195
+ 5. 分數使用 $$\frac{分子}{分母}$$ 格式
196
+ 6. 示範解題時,每個步驟的說明文字和數學式要在同一行
197
+
198
+ 示例格式:
199
+ 讓我們來看一道對數方程式:$$\log_2 x = 3$$<br>
200
+ 解題步驟:<br>
201
+ 1. 利用指數的定義:$$2^3 = x$$<br>
202
+ 2. 計算得到:$$x = 8$$<br>
203
+ 因此,方程式 $$\log_2 x = 3$$ 的解為 $$x = 8$$。"""
 
 
 
 
204
  }
205
  ]
206
 
 
219
  stream=False
220
  )
221
  response = completion.choices[0].message.content
222
+
223
+ # Log to Notion
224
+ log_to_notion(name=name, user_input=message, bot_response=response)
225
+ return response
226
 
227
  def respond(name, message, history):
228
+ """Process chatbot response and update history"""
229
  response = chat_response(name, message, history)
230
  history.append((message, response))
231
  return "", history
232
 
233
+ # Create Gradio interface
234
  with gr.Blocks(css=custom_css) as demo:
235
  gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
236
+
237
+ # Add name input at the top
238
  name_input = gr.Textbox(
239
  label="請輸入您的名字 | Enter Your Name",
240
  placeholder="請輸入您的名字... | Please enter your name...",
 
291
  msg.submit(respond, [name_input, msg, chatbot], [msg, chatbot])
292
 
293
  if __name__ == "__main__":
294
+ demo.launch()