File size: 4,956 Bytes
57b8366
 
 
 
 
 
8eb449d
57b8366
 
 
 
 
8eb449d
57b8366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eb449d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b8366
8eb449d
 
 
 
57b8366
 
 
 
 
 
 
 
 
 
 
8eb449d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# core/callbacks.py
import io
import contextlib
import traceback
from datetime import datetime
import pytz
import difflib  # ✨ 1. 導入 difflib 函式庫

from core.visits import get_current_visit_count
from core.notifications import send_line_notification_in_background
from config.data import KNOWLEDGE_BASE

# (execute_user_code 函式維持不變,此處省略以節省篇幅)
def execute_user_code(code_string, source_lab):
    """Executes user-provided code in a restricted environment and sends a notification."""
    string_io = io.StringIO()
    status = "✅ 成功"
    error_info = ""
    fig = None
    
    try:
        with contextlib.redirect_stdout(string_io):
            local_scope = {}
            # Pre-import necessary libraries for the user's code
            exec("import matplotlib.pyplot as plt; import numpy as np; import cartopy.crs as ccrs; import cartopy.feature as cfeature; from matplotlib.ticker import FixedFormatter", local_scope)
            exec(code_string, local_scope)
        
        console_output = string_io.getvalue()
        fig = local_scope.get('fig')
        
        if fig is None:
            status = "⚠️ 警告"
            error_info = "程式碼執行完畢,但未找到 'fig' 物件。"
            return None, f"{error_info}\nPrint 輸出:\n{console_output}"
        
        success_message = f"✅ 程式碼執行成功!\n\n--- Console Output ---\n{console_output}"
        return fig, success_message

    except Exception:
        status = "❌ 失敗"
        error_info = traceback.format_exc()
        final_message = f"❌ 程式碼執行失敗!\n\n--- Error Traceback ---\n{error_info}"
        return None, final_message
        
    finally:
        # This block will always run, regardless of success or failure
        tz = pytz.timezone('Asia/Taipei')
        current_time = datetime.now(tz).strftime('%H:%M:%S')
        visit_count = get_current_visit_count()
        
        notification_text = (
            f"🔬 程式碼實驗室互動!\n\n"
            f"時間: {current_time}\n"
            f"實驗室: {source_lab}\n"
            f"執行狀態: {status}\n"
            f"總載入數: {visit_count}"
        )
        if status == "❌ 失敗":
            # Add specific error type to notification for quick debugging
            error_type = error_info.strip().split('\n')[-1]
            notification_text += f"\n錯誤類型: {error_type}"
            
        send_line_notification_in_background(notification_text)


# --- ✨ 2. 加入新的模糊比對函式 ---
def find_best_match(user_input, knowledge_base, threshold=0.6):
    """

    Finds the best matching answer from the knowledge base using fuzzy string matching.

    """
    best_score = 0
    best_answer = "這個問題很有趣,不過我的知識庫目前還沒有收錄相關的答案。您可以試著問我關於**課程評分、Anaconda安裝、Colab與Codespaces的差別**等問題!"
    best_match_keyword = None

    # Iterate through all keywords in the knowledge base
    for category, entries in knowledge_base.items():
        for entry in entries:
            for keyword in entry['keywords']:
                # Calculate similarity score
                score = difflib.SequenceMatcher(None, user_input.lower(), keyword.lower()).ratio()
                if score > best_score:
                    best_score = score
                    best_match_keyword = keyword
                    best_answer = entry['answer']

    # If the best score is above the threshold, return the answer directly.
    if best_score >= threshold:
        return best_answer
    # If the score is too low, but we found a potential match, ask for confirmation.
    elif best_match_keyword:
        return f"這個問題我不是很確定,您是指 **「{best_match_keyword}」** 嗎?\n\n我目前找到的相關資料如下:\n\n{best_answer}"
    # If the knowledge base was empty or no match was found at all.
    else:
        return best_answer


def ai_chatbot_with_kb(message, history):
    """

    Handles chatbot interaction by calling the fuzzy matching function and sends a notification.

    """
    # Notification logic (remains the same)
    tz = pytz.timezone('Asia/Taipei')
    current_time = datetime.now(tz).strftime('%H:%M:%S')
    visit_count = get_current_visit_count()
    notification_text = (
        f"🤖 AI 助教被提問!\n\n"
        f"時間: {current_time}\n"
        f"使用者問題:\n「{message}」\n\n"
        f"總載入數: {visit_count}"
    )
    send_line_notification_in_background(notification_text)

    # --- ✨ 3. 使用新的模糊比對函式取代舊的搜尋邏輯 ---
    # The old exact-match logic is now replaced by a single call to our new function.
    return find_best_match(message.strip(), KNOWLEDGE_BASE)