Spaces:
Running
Running
File size: 2,973 Bytes
8787f9d | 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 | const chatContent = document.getElementById('chat-content');
const questionInput = document.getElementById('question');
const sendButton = document.getElementById('send-btn');
const fileInput = document.getElementById('file-input');
// Initialize Markdown-it with syntax highlighting
const md = markdownit({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre><code class="hljs">' + hljs.highlight(str, { language: lang }).value + '</code></pre>';
} catch (__) {}
}
return '<pre><code>' + md.utils.escapeHtml(str) + '</code></pre>';
},
});
// Function to add messages to the chat
const addMessage = (text, type, isMarkdown = false) => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
const messageContent = document.createElement('p');
messageContent.innerHTML = isMarkdown ? md.render(text) : text;
messageDiv.appendChild(messageContent);
chatContent.appendChild(messageDiv);
chatContent.scrollTop = chatContent.scrollHeight;
};
// Handle Send Button Click for Chat Messages
sendButton.addEventListener('click', async () => {
const question = questionInput.value.trim();
if (!question) return;
// Add user's message to the chat
addMessage(question, 'user');
// Clear the input field
questionInput.value = '';
// Send the question to the backend
try {
const response = await fetch('http://127.0.0.1:8080/qa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question }),
});
const data = await response.json();
// Add bot's response to the chat
if (data.answer) {
addMessage(data.answer, 'bot', true); // Render bot's response as Markdown
} else if (data.error) {
addMessage(`Error: ${data.error}`, 'bot');
}
} catch (error) {
addMessage(`Error: ${error.message}`, 'bot');
}
});
// Handle File Upload
fileInput.addEventListener('change', async (event) => {
const files = event.target.files;
if (files.length > 0) {
const formData = new FormData();
Array.from(files).forEach((file) => {
formData.append('file', file);
});
// Send the file to the backend
try {
const response = await fetch('http://127.0.0.1:8080/upload', {
method: 'POST',
body: formData,
});
const data = await response.json();
// Add a confirmation message to the chat
if (data.message) {
addMessage(data.message, 'bot');
} else if (data.error) {
addMessage(`Error: ${data.error}`, 'bot');
}
} catch (error) {
addMessage(`Error: ${error.message}`, 'bot');
}
}
});
|