helen573 commited on
Commit
9c6f93b
·
verified ·
1 Parent(s): 0ef19a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -29
app.py CHANGED
@@ -2,11 +2,6 @@ import os
2
  import gradio as gr
3
  from datetime import datetime
4
  from notion_client import Client
5
-
6
- # Initialize Notion Client
7
- notion = Client(auth=os.getenv('NOTION_API_KEY'))
8
- NOTION_DB_ID = os.getenv('NOTION_DB_ID')
9
-
10
  try:
11
  from groq import Groq
12
  except ImportError:
@@ -16,34 +11,103 @@ except ImportError:
16
  # Initialize Groq client
17
  client = Groq(api_key=os.getenv('groq_key'))
18
 
 
 
 
 
19
  def log_to_notion(name, user_input, bot_response):
20
- """Log conversation to Notion database."""
21
  try:
22
  notion.pages.create(
23
  parent={"database_id": NOTION_DB_ID},
24
  properties={
25
  "Name": {"title": [{"text": {"content": name}}]},
26
- "Timestamp": {"date": {"start": datetime.now().isoformat() }},
27
  "User Input": {"rich_text": [{"text": {"content": user_input}}]},
28
- "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]},
29
  }
30
  )
31
  except Exception as e:
32
- print(f"Failed to log to Notion: {e}")
33
 
34
- def chat_response(message, chat_history):
35
- """Generate response for chatbot."""
 
36
  messages = [
37
- {"role": "system", "content": "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n說明數學上的可能用法時,先用中文講一遍再用 B1程度的英文複述一遍\n"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  ]
 
 
 
 
 
 
 
 
 
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  for msg in chat_history:
41
  messages.append({"role": "user", "content": msg[0]})
42
  if msg[1]:
43
  messages.append({"role": "assistant", "content": msg[1]})
44
-
45
  messages.append({"role": "user", "content": message})
46
-
47
  completion = client.chat.completions.create(
48
  model="llama-3.3-70b-versatile",
49
  messages=messages,
@@ -51,20 +115,21 @@ def chat_response(message, chat_history):
51
  max_tokens=1024,
52
  stream=False
53
  )
54
-
55
  return completion.choices[0].message.content
56
 
57
- def respond(message, history, name):
58
- """Process chatbot response, update history, and log to Notion."""
59
  response = chat_response(message, history)
60
- history.append((message, response))
61
-
62
  # Log to Notion
63
- log_to_notion(name, message, response)
64
-
 
 
65
  return "", history
66
 
67
- # Custom CSS for mathematical theme
68
  custom_css = """
69
  #component-0 {
70
  background-image: linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)),
@@ -100,24 +165,55 @@ custom_css = """
100
  # Create Gradio interface
101
  with gr.Blocks(css=custom_css) as demo:
102
  gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
103
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  with gr.Tab("💬 數學對話系統"):
105
  name_input = gr.Textbox(
106
- label="Your Name | 請輸入您的名字",
107
- placeholder="Enter your name here...",
108
  lines=1,
109
  elem_classes=["input-box"]
110
  )
111
- chatbot = gr.Chatbot([], elem_id="chatbot", bubble_full_width=False, avatar_images=("👨‍🎓", "👨‍🏫"))
 
 
 
 
 
 
 
112
  msg = gr.Textbox(
113
  label="發送訊息 | Send Message",
114
  placeholder="請輸入您的問題... | Enter your question...",
115
  show_label=False,
116
  elem_classes=["input-box"]
117
  )
118
- clear = gr.ClearButton([msg, chatbot], value="🗑️ 清除對話 | Clear Chat")
119
-
120
- msg.submit(respond, [msg, chatbot, name_input], [msg, chatbot])
 
121
 
122
  if __name__ == "__main__":
123
  demo.launch()
 
2
  import gradio as gr
3
  from datetime import datetime
4
  from notion_client import Client
 
 
 
 
 
5
  try:
6
  from groq import Groq
7
  except ImportError:
 
11
  # Initialize Groq client
12
  client = Groq(api_key=os.getenv('groq_key'))
13
 
14
+ # Initialize Notion client
15
+ notion = Client(auth=os.getenv('NOTION_API_KEY'))
16
+ NOTION_DB_ID = os.getenv('NOTION_DB_ID')
17
+
18
  def log_to_notion(name, user_input, bot_response):
19
+ """Log conversation to Notion database"""
20
  try:
21
  notion.pages.create(
22
  parent={"database_id": NOTION_DB_ID},
23
  properties={
24
  "Name": {"title": [{"text": {"content": name}}]},
25
+ "Timestamp": {"date": {"start": datetime.utcnow().isoformat()}},
26
  "User Input": {"rich_text": [{"text": {"content": user_input}}]},
27
+ "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]}
28
  }
29
  )
30
  except Exception as e:
31
+ print(f"Error logging to Notion: {e}")
32
 
33
+ def translate_to_english(word):
34
+ """Generate math-related English translation with bilingual explanation"""
35
+ # [Previous implementation remains the same]
36
  messages = [
37
+ {
38
+ "role": "system",
39
+ "content": """你是一個數學翻譯專家。請按照以下格式提供翻譯:
40
+
41
+ 1. 英文翻譯:[列出數學相關的英文翻譯]
42
+ 2. 中文解釋:[用中文詳細解釋這個詞在數學上的意義]
43
+ 3. English Explanation:[用英文重述上述中文解釋的內容]
44
+ 4. 數學使用場景:[說明在哪些數學情境會使用到這個詞]
45
+ 5. Mathematical Context:[用英文重述使用場景]
46
+
47
+ 如果該詞彙沒有數學相關的意思,請說明。"""
48
+ },
49
+ {
50
+ "role": "user",
51
+ "content": f"請提供中文詞彙 '{word}' 在數學上的英文翻譯和詳細解釋。"
52
+ }
53
  ]
54
+
55
+ completion = client.chat.completions.create(
56
+ model="llama-3.3-70b-versatile",
57
+ messages=messages,
58
+ temperature=0.7,
59
+ max_tokens=400,
60
+ stream=False
61
+ )
62
+
63
+ return completion.choices[0].message.content
64
 
65
+ def generate_example(word):
66
+ """Generate math-related example sentence for Chinese word"""
67
+ # [Previous implementation remains the same]
68
+ messages = [
69
+ {
70
+ "role": "system",
71
+ "content": """你是一個數學教師。請按照以下格式提供例句:
72
+
73
+ 1. 英文例句:[寫出一個數學相關的英文例句]
74
+ 2. 中文翻譯:[該例句的中文翻譯]
75
+ 3. 句子解釋:[用中文解釋這個例句中的數學概念]
76
+ 4. Sentence Explanation:[用英文重述上述解釋]"""
77
+ },
78
+ {
79
+ "role": "user",
80
+ "content": f"請用中文詞彙 '{word}' 的英文翻譯造一個數學相關的例句。"
81
+ }
82
+ ]
83
+
84
+ completion = client.chat.completions.create(
85
+ model="llama-3.3-70b-versatile",
86
+ messages=messages,
87
+ temperature=0.7,
88
+ max_tokens=400,
89
+ stream=False
90
+ )
91
+
92
+ return completion.choices[0].message.content
93
+
94
+ def chat_response(message, chat_history):
95
+ """Generate response for chatbot"""
96
+ # [Previous implementation remains the same]
97
+ messages = [
98
+ {
99
+ "role": "system",
100
+ "content": "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍\n"
101
+ }
102
+ ]
103
+
104
  for msg in chat_history:
105
  messages.append({"role": "user", "content": msg[0]})
106
  if msg[1]:
107
  messages.append({"role": "assistant", "content": msg[1]})
108
+
109
  messages.append({"role": "user", "content": message})
110
+
111
  completion = client.chat.completions.create(
112
  model="llama-3.3-70b-versatile",
113
  messages=messages,
 
115
  max_tokens=1024,
116
  stream=False
117
  )
118
+
119
  return completion.choices[0].message.content
120
 
121
+ def respond(message, name, history):
122
+ """Process chatbot response and update history"""
123
  response = chat_response(message, history)
124
+
 
125
  # Log to Notion
126
+ if name.strip(): # Only log if name is provided
127
+ log_to_notion(name, message, response)
128
+
129
+ history.append((message, response))
130
  return "", history
131
 
132
+ # [Previous CSS implementation remains the same]
133
  custom_css = """
134
  #component-0 {
135
  background-image: linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)),
 
165
  # Create Gradio interface
166
  with gr.Blocks(css=custom_css) as demo:
167
  gr.Markdown("# 雙語數學詞彙學習系統 | Bilingual Mathematics Learning System", elem_classes=["title"])
168
+
169
+ with gr.Tab("📚 單字英譯系統"):
170
+ with gr.Row():
171
+ word_input = gr.Textbox(
172
+ label="請輸入中文詞彙 | Enter Chinese Term",
173
+ placeholder="輸入中文詞彙(例如:向量、函數、極限)...",
174
+ lines=1,
175
+ elem_classes=["input-box"]
176
+ )
177
+
178
+ with gr.Row():
179
+ translate_btn = gr.Button("🔄 英譯 | Translate", variant="primary")
180
+ example_btn = gr.Button("📝 例句 | Example")
181
+
182
+ output_text = gr.Textbox(
183
+ label="翻譯結果 | Translation Result",
184
+ lines=10,
185
+ placeholder="翻譯結果將在這裡顯示... | Translation results will be displayed here...",
186
+ elem_classes=["output-box"]
187
+ )
188
+
189
+ translate_btn.click(translate_to_english, inputs=word_input, outputs=output_text)
190
+ example_btn.click(generate_example, inputs=word_input, outputs=output_text)
191
+
192
  with gr.Tab("💬 數學對話系統"):
193
  name_input = gr.Textbox(
194
+ label="姓名 | Name",
195
+ placeholder="請輸入您的姓名... | Please enter your name...",
196
  lines=1,
197
  elem_classes=["input-box"]
198
  )
199
+
200
+ chatbot = gr.Chatbot(
201
+ [],
202
+ elem_id="chatbot",
203
+ bubble_full_width=False,
204
+ avatar_images=("👨‍🎓", "👨‍🏫")
205
+ )
206
+
207
  msg = gr.Textbox(
208
  label="發送訊息 | Send Message",
209
  placeholder="請輸入您的問題... | Enter your question...",
210
  show_label=False,
211
  elem_classes=["input-box"]
212
  )
213
+
214
+ clear = gr.ClearButton([msg, chatbot, name_input], value="🗑️ 清除對話 | Clear Chat")
215
+
216
+ msg.submit(respond, [msg, name_input, chatbot], [msg, chatbot])
217
 
218
  if __name__ == "__main__":
219
  demo.launch()