iamSammi commited on
Commit
d914fc2
·
verified ·
1 Parent(s): 921be27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -69
app.py CHANGED
@@ -4,96 +4,114 @@ import PyPDF2
4
  import os
5
  from datetime import datetime
6
 
7
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
8
 
9
- # **更新後的主題選項**
10
  topics = ["教育哲學", "教育社會學", "教育心理學", "課程與教學", "教學原理", "班級經營", "教育測驗與評量", "青少年問題與輔導"]
11
  difficulties = ["簡單", "中等", "困難"]
12
 
13
- # 學習者錯誤統計(歷史紀錄)
14
  user_errors = {}
15
  error_history = {}
16
 
17
- # **開發者預設教材 PDF 檔案**
18
  DEFAULT_PDF_PATH = "教材.pdf"
19
 
20
- # 解析 PDF 並擷取文本(使用開發者預設的教材)
21
  def extract_text_from_pdf():
22
- with open(DEFAULT_PDF_PATH, "rb") as pdf_file:
23
- reader = PyPDF2.PdfReader(pdf_file)
24
- text = ""
25
- for page in reader.pages:
26
- text += page.extract_text() + "\n"
27
- return text
 
 
 
 
 
 
28
 
29
- pdf_text = extract_text_from_pdf() # 讀取教材
30
-
31
- # AI 生成問題函數(基於預設教材)
32
  def generate_question(topic, difficulty):
33
- prompt = f"請根據以下教育學教材內容,設計一個屬於'{topic}'主題、'{difficulty}'難度的考題:\n{pdf_text}"
34
-
35
- response = openai.ChatCompletion.create(
36
- model="gpt-4",
37
- messages=[{"role": "system", "content": "你是一位教育專家,請根據教材內容提供符合主題的問題。"},
38
- {"role": "user", "content": prompt}]
39
- )
40
- return response['choices'][0]['message']['content']
41
-
42
- # AI 根據 PDF 教材分析回答,並記錄錯題與日期
 
 
 
 
 
43
  def analyze_answer(user_input, topic):
44
  global user_errors, error_history
 
 
 
 
45
 
46
- # 取得當前日期
47
  current_date = datetime.today().strftime("%Y-%m-%d")
48
-
49
- # 使用 AI 來分析回答(比對 PDF 教材)
50
- prompt = f"請根據以下教材內容,檢查學生的回答是否正確,並提供正確答案與詳細講解:\n{pdf_text}\n\n學生回答:'{user_input}'"
51
-
52
- response = openai.ChatCompletion.create(
53
- model="gpt-4",
54
- messages=[{"role": "system", "content": "你是一位教育專家,請根據教材內容分析學生的回答,並提供正確答案與講解。"},
55
- {"role": "user", "content": prompt}]
56
- )
57
-
58
- feedback = response['choices'][0]['message']['content']
59
-
60
- # 記錄錯題與日期
61
- if "❌" in feedback:
 
62
  user_errors[topic] = user_errors.get(topic, 0) + 1
63
- if current_date not in error_history:
64
- error_history[current_date] = []
65
- error_history[current_date].append({"題目": topic, "回答": user_input, "AI 分析": feedback})
66
-
 
67
  return feedback
68
 
69
- # 查詢特定日期的錯題歷史
70
- def get_errors_by_date(date):
71
- if date in error_history:
72
- errors = error_history[date]
73
- return "\n".join([f"🔹 題目: {e['題目']}\n📝 回答: {e['回答']}\n📖 AI 分析: {e['AI 分析']}" for e in errors])
74
- return "❌ 該日期沒有錯題紀錄"
 
 
 
75
 
76
- # 設定 Gradio 介面
77
  with gr.Blocks() as demo:
78
- gr.Markdown("# 教師檢定智慧陪讀家教 🚀")
79
-
80
- topic_input = gr.Dropdown(choices=topics, label="選擇複習主題")
81
- difficulty_input = gr.Dropdown(choices=difficulties, label="選擇難度等級")
82
- question_output = gr.Textbox(label="AI 生成的問題")
83
-
84
- ask_btn = gr.Button("生成問題")
85
- ask_btn.click(generate_question, inputs=[topic_input, difficulty_input], outputs=question_output)
86
-
87
- user_answer = gr.Textbox(label="你的回答")
88
- analysis_result = gr.Textbox(label="AI 分析與講解")
89
-
90
- analyze_btn = gr.Button("分析回答")
91
- analyze_btn.click(analyze_answer, inputs=[user_answer, topic_input], outputs=analysis_result)
92
-
93
- # 新增「錯題日期選擇」功能
 
 
 
 
94
  date_input = gr.Textbox(label="輸入日期(YYYY-MM-DD)")
95
- error_history_output = gr.Textbox(label="當日錯題紀錄")
96
- search_errors_btn = gr.Button("查看該日期錯題")
97
- search_errors_btn.click(get_errors_by_date, inputs=date_input, outputs=error_history_output)
 
 
98
 
99
  demo.launch()
 
4
  import os
5
  from datetime import datetime
6
 
7
+ # openai 0.28:API 金鑰設定
8
+ openai.api_key = os.getenv("OPENAI_API_KEY")
9
 
 
10
  topics = ["教育哲學", "教育社會學", "教育心理學", "課程與教學", "教學原理", "班級經營", "教育測驗與評量", "青少年問題與輔導"]
11
  difficulties = ["簡單", "中等", "困難"]
12
 
 
13
  user_errors = {}
14
  error_history = {}
15
 
 
16
  DEFAULT_PDF_PATH = "教材.pdf"
17
 
 
18
  def extract_text_from_pdf():
19
+ if not os.path.exists(DEFAULT_PDF_PATH):
20
+ print(f"[錯誤] 教材未找到:{DEFAULT_PDF_PATH}")
21
+ return ""
22
+ try:
23
+ with open(DEFAULT_PDF_PATH, "rb") as f:
24
+ reader = PyPDF2.PdfReader(f)
25
+ return "\n".join([page.extract_text() or "" for page in reader.pages])
26
+ except Exception as e:
27
+ print(f"[錯誤] PDF 載入失敗:{e}")
28
+ return ""
29
+
30
+ pdf_text = extract_text_from_pdf()
31
 
 
 
 
32
  def generate_question(topic, difficulty):
33
+ if not pdf_text.strip():
34
+ return "⚠️ 無法載入教材內容,請確認 PDF 是否存在。"
35
+ prompt = f"請根據以下教育學教材內容,設計一個屬於「{topic}」主題、「{difficulty}」難度的考題:\n\n{pdf_text}"
36
+ try:
37
+ response = openai.ChatCompletion.create(
38
+ model="gpt-4o-mini-2024-07-18",
39
+ messages=[
40
+ {"role": "system", "content": "你是一位教育專家,請根據教材內容設計問題。"},
41
+ {"role": "user", "content": prompt}
42
+ ]
43
+ )
44
+ return response["choices"][0]["message"]["content"]
45
+ except Exception as e:
46
+ return f"⚠️ 發生錯誤:{e}"
47
+
48
  def analyze_answer(user_input, topic):
49
  global user_errors, error_history
50
+ if not user_input.strip():
51
+ return "⚠️ 請輸入回答。"
52
+ if not pdf_text.strip():
53
+ return "⚠️ 教材內容未載入,請確認 PDF。"
54
 
 
55
  current_date = datetime.today().strftime("%Y-%m-%d")
56
+ prompt = f"請根據以下教材內容,檢查學生的回答是否正確,並提供正確答案與講解:\n{pdf_text}\n\n學生回答:'{user_input}'"
57
+
58
+ try:
59
+ response = openai.ChatCompletion.create(
60
+ model="gpt-4o-mini-2024-07-18",
61
+ messages=[
62
+ {"role": "system", "content": "你是一位教育專家,請根據教材內容分析學生回答。"},
63
+ {"role": "user", "content": prompt}
64
+ ]
65
+ )
66
+ feedback = response["choices"][0]["message"]["content"]
67
+ except Exception as e:
68
+ return f"⚠️ 發生錯誤:{e}"
69
+
70
+ if "❌" in feedback or "錯" in feedback:
71
  user_errors[topic] = user_errors.get(topic, 0) + 1
72
+ error_history.setdefault(current_date, []).append({
73
+ "題目": topic,
74
+ "回答": user_input,
75
+ "AI 分析": feedback
76
+ })
77
  return feedback
78
 
79
+ def get_errors_by_date_safe(date_str):
80
+ try:
81
+ datetime.strptime(date_str, "%Y-%m-%d")
82
+ except ValueError:
83
+ return "⚠️ 日期格式錯誤,請使用 YYYY-MM-DD。"
84
+ errors = error_history.get(date_str)
85
+ if not errors:
86
+ return "✅ 該日無錯題紀錄。"
87
+ return "\n\n".join([f"🔹 題目: {e['題目']}\n📝 回答: {e['回答']}\n📖 AI 分析: {e['AI 分析']}" for e in errors])
88
 
 
89
  with gr.Blocks() as demo:
90
+ gr.Markdown("# 👨‍🏫 教師檢定智慧陪讀家教 🚀")
91
+
92
+ with gr.Row():
93
+ topic_input = gr.Dropdown(choices=topics, label="選擇複習主題")
94
+ difficulty_input = gr.Dropdown(choices=difficulties, label="選擇難度等級")
95
+ ask_btn = gr.Button("🎯 生成問題")
96
+ question_output = gr.Textbox(label="AI 生成的問題", lines=4)
97
+ ask_btn.click(fn=lambda t, d: generate_question(t, d),
98
+ inputs=[topic_input, difficulty_input],
99
+ outputs=question_output)
100
+
101
+ user_answer = gr.Textbox(label="你的回答", lines=3)
102
+ analyze_btn = gr.Button("📊 分析回答")
103
+ analysis_result = gr.Textbox(label="AI 分析與講解", lines=5)
104
+ analyze_btn.click(fn=lambda ans, topic: analyze_answer(ans, topic),
105
+ inputs=[user_answer, topic_input],
106
+ outputs=analysis_result)
107
+
108
+ gr.Markdown("---")
109
+ gr.Markdown("📅 查詢錯題紀錄")
110
  date_input = gr.Textbox(label="輸入日期(YYYY-MM-DD)")
111
+ search_errors_btn = gr.Button("🔍 查看該日期錯題")
112
+ error_history_output = gr.Textbox(label="錯題紀錄", lines=5)
113
+ search_errors_btn.click(fn=get_errors_by_date_safe,
114
+ inputs=date_input,
115
+ outputs=error_history_output)
116
 
117
  demo.launch()