Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import openai | |
| import PyPDF2 | |
| import os | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| # **更新後的主題選項** | |
| topics = ["教育哲學", "教育社會學", "教育心理學", "課程與教學", "教學原理", "班級經營", "教育測驗與評量", "青少年問題與輔導"] | |
| difficulties = ["簡單", "中等", "困難"] | |
| # 學習者錯誤統計(歷史紀錄) | |
| user_errors = {} | |
| # **開發者預設教材 PDF 檔案** | |
| DEFAULT_PDF_PATH = "教材.pdf" | |
| # 解析 PDF 並擷取文本(使用開發者預設的教材) | |
| def extract_text_from_pdf(): | |
| with open(DEFAULT_PDF_PATH, "rb") as pdf_file: # 修正此處為 "rb" | |
| reader = PyPDF2.PdfReader(pdf_file) | |
| text = "" | |
| for page in reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| pdf_text = extract_text_from_pdf() # 讀取教材 | |
| # AI 生成問題函數(基於預設教材) | |
| def generate_question(topic, difficulty): | |
| prompt = f"請根據以下教育學教材內容,設計一個屬於'{topic}'主題、'{difficulty}'難度的考題:\n{pdf_text}" | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4", | |
| messages=[{"role": "system", "content": "你是一位教育專家,請根據教材內容提供符合主題的問題。"}, | |
| {"role": "user", "content": prompt}] | |
| ) | |
| return response['choices'][0]['message']['content'] | |
| # AI 判斷對錯並提供講解 | |
| def analyze_answer(user_input, topic): | |
| global user_errors | |
| # 使用 AI 來分析回答 | |
| prompt = f"學生回答:'{user_input}'\n\n請分析學生的回答是否正確,並提供詳細講解與建議。" | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4", | |
| messages=[{"role": "system", "content": "你是一位教育專家,請評估學生的回答,並提供詳細講解。"}, | |
| {"role": "user", "content": prompt}] | |
| ) | |
| feedback = response['choices'][0]['message']['content'] | |
| # 記錄錯誤主題(長期紀錄) | |
| if "❌" in feedback: | |
| user_errors[topic] = user_errors.get(topic, 0) + 1 | |
| return feedback | |
| # 顯示弱點歷史紀錄 | |
| def get_weaknesses(): | |
| if not user_errors: | |
| return "🎯 目前沒有明顯弱點,繼續保持!" | |
| sorted_weaknesses = sorted(user_errors.items(), key=lambda x: x[1], reverse=True) | |
| history_text = "\n".join([f"{k}: {v} 次錯誤" for k, v in sorted_weaknesses]) | |
| return f"📌 **你的弱點領域**:\n{history_text}" | |
| # 設定 Gradio 介面 | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 教師檢定智慧陪讀家教 🚀") | |
| topic_input = gr.Dropdown(choices=topics, label="選擇複習主題") | |
| difficulty_input = gr.Dropdown(choices=difficulties, label="選擇難度等級") | |
| question_output = gr.Textbox(label="AI 生成的問題") | |
| ask_btn = gr.Button("生成問題") | |
| ask_btn.click(generate_question, inputs=[topic_input, difficulty_input], outputs=question_output) | |
| user_answer = gr.Textbox(label="你的回答") | |
| analysis_result = gr.Textbox(label="AI 分析與講解") | |
| analyze_btn = gr.Button("分析回答") | |
| analyze_btn.click(analyze_answer, inputs=[user_answer, topic_input], outputs=analysis_result) | |
| # 新增弱點歷史紀錄功能 | |
| weaknesses_output = gr.Textbox(label="弱點歷史紀錄") | |
| weakness_btn = gr.Button("查看過去錯誤主題") | |
| weakness_btn.click(get_weaknesses, outputs=weaknesses_output) | |
| demo.launch() | |