File size: 8,530 Bytes
669b6be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef2939
669b6be
 
fef2939
 
669b6be
 
 
fef2939
669b6be
 
fef2939
669b6be
 
 
 
 
 
a0505b5
 
 
 
 
669b6be
 
 
a0505b5
 
669b6be
 
a0505b5
669b6be
 
a0505b5
669b6be
 
 
 
 
a0505b5
669b6be
 
 
a0505b5
669b6be
 
 
a0505b5
669b6be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

    // DOM Elements
    const messagesContainer = document.getElementById('messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const emptyChat = document.getElementById('empty-chat');
    const chatContainer = document.getElementById('chat-container');
    const sourcesContainer = document.getElementById('sources-container');
    const noSources = document.getElementById('no-sources');
    const scrapeBtn = document.getElementById('scrape-btn');
    const refreshBtn = document.getElementById('refresh-btn');

    // State
    let messages = [];
    let sources = [];

    // Initialize
    document.addEventListener('DOMContentLoaded', () => {
        // Enable/disable send button based on input
        messageInput.addEventListener('input', () => {
            sendButton.disabled = !messageInput.value.trim();
        });
        
        // Send message on button click
        sendButton.addEventListener('click', sendMessage);
        
        // Send message on Enter key
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        // Admin buttons
        scrapeBtn.addEventListener('click', triggerScrape);
        refreshBtn.addEventListener('click', triggerRefreshIndex);
    });

    // Format date
    function formatDate() {
        return new Date().toLocaleString();
    }

    // Create message element
    function createMessageElement(message) {
        const messageEl = document.createElement('div');
        messageEl.className = `message ${message.role}`;
    
        const bubble = document.createElement('div');
        bubble.className = 'bubble';
        bubble.innerHTML = marked.parse(message.content); // parse Markdown to HTML
    
        const meta = document.createElement('div');
        meta.className = 'meta';
        meta.textContent = formatDate();
    
        messageEl.appendChild(bubble);
        messageEl.appendChild(meta);
    
        return messageEl;
    }

    // Update sources panel
    function updateSources(sources) {
        sourcesContainer.innerHTML = '';
    
        // Filter sources with score > -8
        const filteredSources = sources.filter(source => source.score > -8);
    
        if (filteredSources.length === 0) {
            sourcesContainer.appendChild(noSources);
            return;
        }
    
        filteredSources.forEach(source => {
            const card = document.createElement('div');
            card.className = 'source-card';
    
            const title = document.createElement('h4');
            title.textContent = source.title;
    
            const link = document.createElement('a');
            link.className = 'link';
            link.href = source.url;
            link.target = '_blank';
            link.innerHTML = `View source <i class="fas fa-external-link-alt"></i>`;
    
            const score = document.createElement('div');
            score.className = 'score';
            score.textContent = `Relevance: ${source.score.toFixed(2)}`;
    
            card.appendChild(title);
            card.appendChild(link);
            card.appendChild(score);
    
            sourcesContainer.appendChild(card);
        });
    }

    // Send message
    async function sendMessage() {
        const content = messageInput.value.trim();
        if (!content) return;
        
        // Hide empty chat if visible
        if (emptyChat.style.display !== 'none') {
            emptyChat.style.display = 'none';
        }
        
        // Add user message
        const userMessage = { role: 'user', content };
        messages.push(userMessage);
        messagesContainer.appendChild(createMessageElement(userMessage));
        
        // Clear input
        messageInput.value = '';
        sendButton.disabled = true;
        
        // Show thinking message
        const thinkingEl = document.createElement('div');
        thinkingEl.className = 'message assistant';
        
        const thinkingBubble = document.createElement('div');
        thinkingBubble.className = 'bubble';
        thinkingBubble.textContent = 'Thinking...';
        
        thinkingEl.appendChild(thinkingBubble);
        messagesContainer.appendChild(thinkingEl);
        
        // Scroll to bottom
        chatContainer.scrollTop = chatContainer.scrollHeight;
        
        try {
            // Call API
            const response = await fetch('/api/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    query: content,
                    k: 5
                }),
            });
            
            if (!response.ok) {
                throw new Error('API request failed');
            }
            
            const data = await response.json();
            
            // Remove thinking message
            messagesContainer.removeChild(thinkingEl);
            
            // Add assistant message
            const assistantMessage = { role: 'assistant', content: data.response };
            messages.push(assistantMessage);
            messagesContainer.appendChild(createMessageElement(assistantMessage));
            
            // Update sources
            sources = data.sources;
            updateSources(sources);
            
            // Scroll to bottom
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
        } catch (error) {
            console.error('Error:', error);
            
            // Remove thinking message
            messagesContainer.removeChild(thinkingEl);
            
            // Add error message
            const errorMessage = { 
                role: 'assistant', 
                content: "I'm sorry, I encountered an error. Please try again later or contact UB International Student Services directly."
            };
            messages.push(errorMessage);
            messagesContainer.appendChild(createMessageElement(errorMessage));
            
            // Scroll to bottom
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }

    // Quick questions
    async function askQuickQuestion(question) {
        // Set the question in the input field
        messageInput.value = question;
        
        // Send the message
        await sendMessage();
    }

    // Admin functions
    async function triggerScrape() {
        scrapeBtn.disabled = true;
        scrapeBtn.textContent = 'Scraping...';
        
        try {
            const response = await fetch('/api/scrape', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    seed_url: 'https://www.buffalo.edu/international-student-services.html',
                    max_pages: 100
                }),
            });
            
            if (!response.ok) {
                throw new Error('API request failed');
            }
            
            const data = await response.json();
            alert(`${data.message}`);
            
        } catch (error) {
            console.error('Error:', error);
            alert('Error starting scraper. Please check console for details.');
            
        } finally {
            scrapeBtn.disabled = false;
            scrapeBtn.textContent = 'Scrape New Content';
        }
    }

    async function triggerRefreshIndex() {
        refreshBtn.disabled = true;
        refreshBtn.textContent = 'Refreshing...';
        
        try {
            const response = await fetch('/api/refresh-index', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            
            if (!response.ok) {
                throw new Error('API request failed');
            }
            
            const data = await response.json();
            alert(`${data.message}`);
            
        } catch (error) {
            console.error('Error:', error);
            alert('Error refreshing index. Please check console for details.');
            
        } finally {
            refreshBtn.disabled = false;
            refreshBtn.textContent = 'Refresh Index';
        }
    }