helen573 commited on
Commit
299460f
·
verified ·
1 Parent(s): 4111634

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -59
app.py CHANGED
@@ -41,38 +41,37 @@ def log_to_notion(name, chinese_term="", user_input="", bot_response=""):
41
 
42
  def translate_to_english(name, word):
43
  """Generate math-related English translation with bilingual explanation"""
44
- translations = {
45
- "向量": {
46
- "english": "Vector",
47
- "chinese_explanation": "向量是一種具有大小與方向的數學實體",
48
- "english_explanation": "A vector is a mathematical entity characterized by magnitude and direction.",
49
- "math_context": "向量廣泛用於物理和工程學中力和位移表示。",
50
- "english_context": "Vectors are widely used in physics and engineering to represent forces and displacements."
51
- },
52
- "函數": {
53
- "english": "Function",
54
- "chinese_explanation": "函數描述變量之間的依賴關係。",
55
- "english_explanation": "A function describes the dependency relationship between variables.",
56
- "math_context": "函數是數學分析中的核心概念,常用於表示輸入與輸出之間的關係。",
57
- "english_context": "Functions are a core concept in mathematical analysis, often used to represent input-output relationships."
 
 
58
  },
59
- "極限": {
60
- "english": "Limit",
61
- "chinese_explanation": "極限用於描述函趨於某一特定值行為。",
62
- "english_explanation": "The limit describes the behavior of a function as it approaches a specific value.",
63
- "math_context": "極限是微積分中的基礎概念,用於定義導數和積分。",
64
- "english_context": "Limits are a foundational concept in calculus, used to define derivatives and integrals."
65
  }
66
- }
67
- if word in translations:
68
- t = translations[word]
69
- response = f"""1. 英文翻譯:{t['english']}
70
- 2. 中文解釋:{t['chinese_explanation']}
71
- 3. English Explanation: {t['english_explanation']}
72
- 4. 數學使用場景:{t['math_context']}
73
- 5. Mathematical Context: {t['english_context']}"""
74
- else:
75
- response = f"抱歉,未找到 '{word}' 的對應翻譯與解釋。請嘗試其他數學詞彙!"
76
 
77
  # Log to Notion
78
  log_to_notion(name=name, chinese_term=word, bot_response=response)
@@ -80,44 +79,112 @@ def translate_to_english(name, word):
80
 
81
  def generate_example(name, word):
82
  """Generate math-related example sentence for Chinese word"""
83
- examples = {
84
- "向量": {
85
- "example": "The vector \\( \\vec{v} = (3, 4) \\) represents a point in 2D space.",
86
- "translation": "向量 \\( \\vec{v} = (3, 4) \\) 表示二維空間中的一個點。",
87
- "explanation": "此例句中的向量表示從原點到座標 (3, 4) 的方向和距離。"
88
- },
89
- "函數": {
90
- "example": "The function \\( f(x) = x^2 \\) squares the input value.",
91
- "translation": "函數 \\( f(x) = x^2 \\) 將輸入值平方。",
92
- "explanation": "此例句中的描述了輸入值與輸出值之間的關係。"
 
 
93
  },
94
- "極限": {
95
- "example": "The limit of \\( f(x) = 1/x \\) as x approaches infinity is 0.",
96
- "translation": " x 趨於無窮大時,\\( f(x) = 1/x \\) 極限為 0。",
97
- "explanation": "此例句中的極限描述了函數在某一趨勢下的行為。"
98
  }
99
- }
100
- if word in examples:
101
- e = examples[word]
102
- response = f"""1. 英文例句:{e['example']}
103
- 2. 中文翻譯:{e['translation']}
104
- 3. 句子解釋:{e['explanation']}"""
105
- else:
106
- response = f"抱歉,未找到 '{word}' 的例句。請嘗試其他數學詞彙!"
 
 
107
 
108
  # Log to Notion
109
  log_to_notion(name=name, chinese_term=word, bot_response=response)
110
  return response
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  def respond(name, message, history):
113
  """Process chatbot response and update history"""
114
- response = f"You asked: {message}. Here's a sample response with math: \\( a^2 + b^2 = c^2 \\)."
115
  history.append((message, response))
116
  return "", history
117
 
118
- # Custom CSS remains the same as in your original code
119
  custom_css = """
120
- [Your existing CSS here]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  """
122
 
123
  # Create Gradio interface
@@ -140,13 +207,15 @@ with gr.Blocks(css=custom_css) as demo:
140
  lines=1,
141
  elem_classes=["input-box"]
142
  )
 
143
  with gr.Row():
144
  translate_btn = gr.Button("🔄 英譯 | Translate", variant="primary")
145
  example_btn = gr.Button("📝 例句 | Example")
146
-
147
  output_text = gr.Markdown(
148
  label="翻譯結果 | Translation Result",
149
- elem_classes=["output-box"]
 
150
  )
151
 
152
  translate_btn.click(translate_to_english, inputs=[name_input, word_input], outputs=output_text)
@@ -157,12 +226,19 @@ with gr.Blocks(css=custom_css) as demo:
157
  [],
158
  elem_id="chatbot",
159
  bubble_full_width=False,
160
- avatar_images=("👨‍🎓", "👨‍🏫")
 
161
  )
 
162
  msg = gr.Textbox(
163
  label="發送訊息 | Send Message",
164
  placeholder="請輸入您的問題... | Enter your question...",
165
  show_label=False,
166
  elem_classes=["input-box"]
167
  )
168
- clear = gr.ClearButton([msg, chatbot], value="
 
 
 
 
 
 
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": """你是一數學翻譯專家請按照以下格式提供翻譯,注意數學公式要用 LaTeX 格式包覆(使用 $$ 符號):
48
+
49
+ 1. 英文翻譯:[列出數相關英文翻譯]
50
+
51
+ 2. 中文解釋:[用中文詳細解釋這個詞在數學上的意義,需要時使用 LaTeX 數學式]
52
+
53
+ 3. English Explanation:[用英文重述上述中文解釋的內容,需要時使用 LaTeX 數學式]
54
+
55
+ 4. 數學使用場景:[說明在哪些數學情境會使用到這個詞,並舉例使用 LaTeX 數學式]
56
+
57
+ 5. Mathematical Context:[用英文重述使用場景,保留 LaTeX 數學式]
58
+
59
+ 如果該詞彙沒有數學相關的意思,請說明。"""
60
  },
61
+ {
62
+ "role": "user",
63
+ "content": f"請提供中文詞彙 '{word}' 在學上英文翻譯和詳細解釋。"
 
 
 
64
  }
65
+ ]
66
+
67
+ completion = client.chat.completions.create(
68
+ model="llama-3.3-70b-versatile",
69
+ messages=messages,
70
+ temperature=0.7,
71
+ max_tokens=400,
72
+ stream=False
73
+ )
74
+ response = completion.choices[0].message.content
75
 
76
  # Log to Notion
77
  log_to_notion(name=name, chinese_term=word, bot_response=response)
 
79
 
80
  def generate_example(name, word):
81
  """Generate math-related example sentence for Chinese word"""
82
+ messages = [
83
+ {
84
+ "role": "system",
85
+ "content": """你是一個數學教師。請按照以下格式提供例句,注意數學公式要用 LaTeX 格式包覆(使用 $$ 符號):
86
+
87
+ 1. 英文例句:[寫出一個數學相關的英文例句,包含 LaTeX 數學式]
88
+
89
+ 2. 中文翻譯:[該例句的中文翻譯,保留 LaTeX 數學式]
90
+
91
+ 3. 句子解釋:[用中文解釋這個例句中的數學概念,需要時使用 LaTeX 數學式]
92
+
93
+ 4. Sentence Explanation:[用英文重述上述解釋,需要時使用 LaTeX 數學式]"""
94
  },
95
+ {
96
+ "role": "user",
97
+ "content": f"請用中文詞彙 '{word}'英文翻譯造一個數學相關的例句。"
 
98
  }
99
+ ]
100
+
101
+ completion = client.chat.completions.create(
102
+ model="llama-3.3-70b-versatile",
103
+ messages=messages,
104
+ temperature=0.7,
105
+ max_tokens=400,
106
+ stream=False
107
+ )
108
+ response = completion.choices[0].message.content
109
 
110
  # Log to Notion
111
  log_to_notion(name=name, chinese_term=word, bot_response=response)
112
  return response
113
 
114
+ def chat_response(name, message, chat_history):
115
+ """Generate response for chatbot"""
116
+ messages = [
117
+ {
118
+ "role": "system",
119
+ "content": """你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。
120
+ 說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍。
121
+
122
+ 請注意:
123
+ 1. 所有數學公式都要用 LaTeX 格式書寫(使用 $$ 符號包覆)
124
+ 2. 示範解題時,每個步驟都要清楚標示,並搭配 LaTeX 數學式
125
+ 3. 回答要有條理,適時使用換行來分隔不同段落"""
126
+ }
127
+ ]
128
+
129
+ for msg in chat_history:
130
+ messages.append({"role": "user", "content": msg[0]})
131
+ if msg[1]:
132
+ messages.append({"role": "assistant", "content": msg[1]})
133
+
134
+ messages.append({"role": "user", "content": message})
135
+
136
+ completion = client.chat.completions.create(
137
+ model="llama-3.3-70b-versatile",
138
+ messages=messages,
139
+ temperature=1,
140
+ max_tokens=1024,
141
+ stream=False
142
+ )
143
+ response = completion.choices[0].message.content
144
+
145
+ # Log to Notion
146
+ log_to_notion(name=name, user_input=message, bot_response=response)
147
+ return response
148
+
149
  def respond(name, message, history):
150
  """Process chatbot response and update history"""
151
+ response = chat_response(name, message, history)
152
  history.append((message, response))
153
  return "", history
154
 
155
+ # Custom CSS for math rendering and layout
156
  custom_css = """
157
+ .math-container .katex {
158
+ font-size: 1.1em;
159
+ }
160
+ .input-box {
161
+ font-size: 1.1em;
162
+ }
163
+ .output-box {
164
+ font-size: 1.1em;
165
+ line-height: 1.5;
166
+ }
167
+ .title {
168
+ text-align: center;
169
+ font-size: 1.8em;
170
+ margin-bottom: 1em;
171
+ color: #2a4365;
172
+ }
173
+ #chatbot {
174
+ height: 600px;
175
+ overflow-y: auto;
176
+ }
177
+ .message {
178
+ padding: 1em;
179
+ margin: 0.5em;
180
+ border-radius: 8px;
181
+ }
182
+ .user-message {
183
+ background-color: #e2e8f0;
184
+ }
185
+ .bot-message {
186
+ background-color: #edf2f7;
187
+ }
188
  """
189
 
190
  # Create Gradio interface
 
207
  lines=1,
208
  elem_classes=["input-box"]
209
  )
210
+
211
  with gr.Row():
212
  translate_btn = gr.Button("🔄 英譯 | Translate", variant="primary")
213
  example_btn = gr.Button("📝 例句 | Example")
214
+
215
  output_text = gr.Markdown(
216
  label="翻譯結果 | Translation Result",
217
+ value="翻譯結果將在這裡顯示... | Translation results will be displayed here...",
218
+ elem_classes=["output-box", "math-container"]
219
  )
220
 
221
  translate_btn.click(translate_to_english, inputs=[name_input, word_input], outputs=output_text)
 
226
  [],
227
  elem_id="chatbot",
228
  bubble_full_width=False,
229
+ avatar_images=("👨‍🎓", "👨‍🏫"),
230
+ elem_classes=["math-container"]
231
  )
232
+
233
  msg = gr.Textbox(
234
  label="發送訊息 | Send Message",
235
  placeholder="請輸入您的問題... | Enter your question...",
236
  show_label=False,
237
  elem_classes=["input-box"]
238
  )
239
+
240
+ clear = gr.ClearButton([msg, chatbot], value="🗑️ 清除對話 | Clear Chat")
241
+ msg.submit(respond, [name_input, msg, chatbot], [msg, chatbot])
242
+
243
+ if __name__ == "__main__":
244
+ demo.launch()