Download index.html from BLOCKED01/test123: direct link, hf CLI and curl.
- Browser
- Download file 49.6 kB
-
https://huggingface.co/spaces/BLOCKED01/test123/resolve/main/index.html
- Command line
-
hf download hf://spaces/BLOCKED01/test123/index.html
-
curl -L -o index.html https://huggingface.co/spaces/BLOCKED01/test123/resolve/main/index.html
49.6 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAG AI Document Explainer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style>
.chat-container {
height: calc(100vh - 200px);
}
.admin-panel {
display: none;
}
.document-list {
max-height: 400px;
overflow-y: auto;
}
.fade-in {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.markdown-content {
white-space: pre-wrap;
font-family: 'Courier New', monospace;
}
.typing-indicator {
display: inline-block;
}
.typing-indicator span {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #4b5563;
margin-right: 3px;
animation: bounce 1.4s infinite ease-in-out both;
}
.typing-indicator span:nth-child(1) {
animation-delay: -0.32s;
}
.typing-indicator span:nth-child(2) {
animation-delay: -0.16s;
}
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
.saving-indicator {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
.error-message {
background-color: #fee2e2;
border-left: 4px solid #ef4444;
padding: 1rem;
margin-bottom: 1rem;
border-radius: 0.375rem;
}
.retry-button {
background-color: #ef4444;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.875rem;
margin-top: 0.5rem;
display: inline-block;
cursor: pointer;
}
.retry-button:hover {
background-color: #dc2626;
}
</style>
</head>
<body class="bg-gray-100">
<!-- Navigation -->
<nav class="bg-blue-600 text-white p-4 shadow-md">
<div class="container mx-auto flex justify-between items-center">
<div class="flex items-center space-x-2">
<i class="fas fa-robot text-2xl"></i>
<h1 class="text-xl font-bold">RAG Document Explainer</h1>
</div>
<button id="adminBtn" class="bg-white text-blue-600 px-4 py-2 rounded-md font-medium hover:bg-blue-50 transition">
Admin Panel
</button>
</div>
</nav>
<!-- Main Chat Interface -->
<div id="chatInterface" class="container mx-auto p-4 max-w-6xl">
<div class="bg-white rounded-lg shadow-md p-6">
<h2 class="text-2xl font-bold text-gray-800 mb-6">Ask about any document</h2>
<!-- Topic Selection -->
<div class="mb-6">
<label for="topicSelect" class="block text-sm font-medium text-gray-700 mb-2">Select a topic</label>
<div class="flex space-x-2">
<select id="topicSelect" class="flex-grow p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<option value="">Loading topics...</option>
</select>
<button id="refreshTopics" class="bg-gray-200 hover:bg-gray-300 p-3 rounded-md">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
<!-- Chat Container -->
<div class="bg-gray-50 rounded-lg border border-gray-200 p-4 chat-container mb-4">
<div id="chatMessages" class="space-y-4 overflow-y-auto h-full p-2">
<div class="text-center text-gray-500 py-10">
<i class="fas fa-comments text-4xl mb-2"></i>
<p>Select a topic and start asking questions about the documents</p>
</div>
</div>
</div>
<!-- Input Area -->
<div class="flex space-x-2">
<input id="userInput" type="text" placeholder="Type your question here..."
class="flex-grow p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" disabled>
<button id="sendBtn" class="bg-blue-600 text-white p-3 rounded-md hover:bg-blue-700 transition disabled:opacity-50" disabled>
<i class="fas fa-paper-plane"></i>
</button>
</div>
</div>
</div>
<!-- Admin Panel -->
<div id="adminPanel" class="admin-panel container mx-auto p-4 max-w-6xl">
<div class="bg-white rounded-lg shadow-md p-6">
<div class="flex justify-between items-center mb-6">
<h2 class="text-2xl font-bold text-gray-800">Admin Panel</h2>
<button id="backToChat" class="bg-blue-600 text-white px-4 py-2 rounded-md font-medium hover:bg-blue-700 transition">
Back to Chat
</button>
</div>
<!-- Login Form (Initially shown) -->
<div id="loginForm" class="bg-gray-50 p-6 rounded-lg mb-6">
<h3 class="text-xl font-semibold text-gray-800 mb-4">Admin Login</h3>
<div class="space-y-4">
<div>
<label for="adminUsername" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
<input id="adminUsername" type="text" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
</div>
<div>
<label for="adminPassword" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
<input id="adminPassword" type="password" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
</div>
<button id="loginBtn" class="w-full bg-blue-600 text-white p-3 rounded-md hover:bg-blue-700 transition">
Login
</button>
</div>
</div>
<!-- Admin Content (Initially hidden) -->
<div id="adminContent" class="hidden">
<!-- Saving Indicator -->
<div id="savingIndicator" class="saving-indicator hidden">
<div class="bg-blue-500 text-white px-4 py-2 rounded-md shadow-lg flex items-center">
<i class="fas fa-circle-notch fa-spin mr-2"></i>
<span>Saving changes...</span>
</div>
</div>
<!-- Auto-save status -->
<div id="autoSaveStatus" class="bg-blue-50 text-blue-800 px-4 py-2 rounded-md mb-4 flex items-center">
<i class="fas fa-info-circle mr-2"></i>
<span>Changes are saved automatically when you exit the admin panel.</span>
</div>
<!-- Topic Management -->
<div class="mb-8">
<h3 class="text-xl font-semibold text-gray-800 mb-4">Topic Management</h3>
<div class="flex space-x-2 mb-4">
<input id="newTopicName" type="text" placeholder="New topic name"
class="flex-grow p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<button id="addTopicBtn" class="bg-green-600 text-white p-3 rounded-md hover:bg-green-700 transition">
Add Topic
</button>
</div>
<div class="bg-gray-50 p-4 rounded-lg">
<h4 class="font-medium text-gray-700 mb-2">Existing Topics</h4>
<div id="topicList" class="space-y-2">
<!-- Topics will be loaded here -->
</div>
</div>
</div>
<!-- Document Management -->
<div>
<h3 class="text-xl font-semibold text-gray-800 mb-4">Document Management</h3>
<div class="bg-gray-50 p-4 rounded-lg mb-4">
<h4 class="font-medium text-gray-700 mb-2">Add New Document</h4>
<div class="space-y-4">
<div>
<label for="docTopicSelect" class="block text-sm font-medium text-gray-700 mb-1">Topic</label>
<select id="docTopicSelect" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<option value="">Select a topic</option>
</select>
</div>
<div>
<label for="docTitle" class="block text-sm font-medium text-gray-700 mb-1">Document Title</label>
<input id="docTitle" type="text" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" placeholder="Document title">
</div>
<div>
<label for="docContent" class="block text-sm font-medium text-gray-700 mb-1">Content</label>
<textarea id="docContent" rows="5" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" placeholder="Paste document content here"></textarea>
</div>
<button id="addDocBtn" class="bg-green-600 text-white p-3 rounded-md hover:bg-green-700 transition">
Add Document
</button>
</div>
</div>
<div class="bg-gray-50 p-4 rounded-lg">
<h4 class="font-medium text-gray-700 mb-2">Existing Documents</h4>
<div class="mb-2 flex justify-between">
<div class="flex items-center space-x-2">
<label for="filterTopic" class="text-sm text-gray-700">Filter by topic:</label>
<select id="filterTopic" class="p-2 border border-gray-300 rounded-md">
<option value="">All topics</option>
</select>
</div>
<div class="relative">
<input id="searchDocs" type="text" placeholder="Search documents..." class="p-2 pl-8 border border-gray-300 rounded-md">
<i class="fas fa-search absolute left-2 top-3 text-gray-400"></i>
</div>
</div>
<div id="documentList" class="document-list space-y-2">
<!-- Documents will be loaded here -->
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Document Edit Modal -->
<div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-screen overflow-y-auto">
<div class="p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-xl font-semibold">Edit Document</h3>
<button id="closeModal" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times"></i>
</button>
</div>
<div class="space-y-4">
<div>
<label for="editDocTitle" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
<input id="editDocTitle" type="text" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
</div>
<div>
<label for="editDocTopic" class="block text-sm font-medium text-gray-700 mb-1">Topic</label>
<select id="editDocTopic" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<option value="">Select a topic</option>
</select>
</div>
<div>
<label for="editDocContent" class="block text-sm font-medium text-gray-700 mb-1">Content</label>
<textarea id="editDocContent" rows="10" class="w-full p-3 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
</div>
<div class="flex justify-end space-x-2 pt-4">
<button id="deleteDocBtn" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 transition">
Delete
</button>
<button id="saveDocBtn" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition">
Save Changes
</button>
</div>
</div>
</div>
</div>
</div>
<script>
// API Configuration
const OPENAI_API_KEY = "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";
const API_BASE_URL = "https://api.openai.com/v1/chat/completions";
// State management
let currentTopic = null;
let isAdminLoggedIn = false;
let documents = [];
let topics = [];
let currentEditingDocId = null;
let hasUnsavedChanges = false;
let lastFailedRequest = null;
// DOM Elements
const chatInterface = document.getElementById('chatInterface');
const adminPanel = document.getElementById('adminPanel');
const adminBtn = document.getElementById('adminBtn');
const backToChat = document.getElementById('backToChat');
const loginForm = document.getElementById('loginForm');
const adminContent = document.getElementById('adminContent');
const adminUsername = document.getElementById('adminUsername');
const adminPassword = document.getElementById('adminPassword');
const loginBtn = document.getElementById('loginBtn');
const topicSelect = document.getElementById('topicSelect');
const refreshTopics = document.getElementById('refreshTopics');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const chatMessages = document.getElementById('chatMessages');
const newTopicName = document.getElementById('newTopicName');
const addTopicBtn = document.getElementById('addTopicBtn');
const topicList = document.getElementById('topicList');
const docTopicSelect = document.getElementById('docTopicSelect');
const docTitle = document.getElementById('docTitle');
const docContent = document.getElementById('docContent');
const addDocBtn = document.getElementById('addDocBtn');
const filterTopic = document.getElementById('filterTopic');
const searchDocs = document.getElementById('searchDocs');
const documentList = document.getElementById('documentList');
const editModal = document.getElementById('editModal');
const closeModal = document.getElementById('closeModal');
const editDocTitle = document.getElementById('editDocTitle');
const editDocTopic = document.getElementById('editDocTopic');
const editDocContent = document.getElementById('editDocContent');
const deleteDocBtn = document.getElementById('deleteDocBtn');
const saveDocBtn = document.getElementById('saveDocBtn');
const savingIndicator = document.getElementById('savingIndicator');
const autoSaveStatus = document.getElementById('autoSaveStatus');
// Event Listeners
adminBtn.addEventListener('click', showAdminPanel);
backToChat.addEventListener('click', () => {
if (hasUnsavedChanges) {
saveChanges().then(() => showChatInterface());
} else {
showChatInterface();
}
});
loginBtn.addEventListener('click', handleLogin);
refreshTopics.addEventListener('click', loadTopics);
topicSelect.addEventListener('change', handleTopicChange);
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
addTopicBtn.addEventListener('click', addNewTopic);
addDocBtn.addEventListener('click', addNewDocument);
filterTopic.addEventListener('change', filterDocuments);
searchDocs.addEventListener('input', filterDocuments);
closeModal.addEventListener('click', () => editModal.classList.add('hidden'));
saveDocBtn.addEventListener('click', saveDocumentChanges);
deleteDocBtn.addEventListener('click', deleteDocument);
// Form elements that trigger changes
const adminFormElements = [newTopicName, docTopicSelect, docTitle, docContent, editDocTitle, editDocTopic, editDocContent];
adminFormElements.forEach(element => {
element.addEventListener('change', () => {
hasUnsavedChanges = true;
});
element.addEventListener('input', () => {
hasUnsavedChanges = true;
});
});
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
loadTopics();
loadDocuments();
});
// Functions
function showAdminPanel() {
chatInterface.style.display = 'none';
adminPanel.style.display = 'block';
if (!isAdminLoggedIn) {
loginForm.style.display = 'block';
adminContent.style.display = 'none';
} else {
loginForm.style.display = 'none';
adminContent.style.display = 'block';
loadAdminTopics();
loadAdminDocuments();
}
}
function showChatInterface() {
chatInterface.style.display = 'block';
adminPanel.style.display = 'none';
}
function handleLogin() {
const username = adminUsername.value.trim();
const password = adminPassword.value.trim();
if (username === 'Admin' && password === 'Admin123') {
isAdminLoggedIn = true;
loginForm.style.display = 'none';
adminContent.style.display = 'block';
loadAdminTopics();
loadAdminDocuments();
// Show success message
const loginMessage = document.createElement('div');
loginMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
loginMessage.innerHTML = '<strong>Success!</strong> You are now logged in as admin.';
adminContent.insertBefore(loginMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
loginMessage.classList.remove('fade-in');
loginMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => loginMessage.remove(), 300);
}, 3000);
} else {
alert('Invalid credentials. Please try again.');
}
}
async function loadTopics() {
try {
// Simulate API call to get topics
// In a real app, this would be an actual API call
const mockTopics = [
{ id: '1', name: 'Technology' },
{ id: '2', name: 'Science' },
{ id: '3', name: 'Business' },
{ id: '4', name: 'Health' }
];
topics = mockTopics;
// Populate topic dropdown
topicSelect.innerHTML = '<option value="">Select a topic</option>';
mockTopics.forEach(topic => {
const option = document.createElement('option');
option.value = topic.id;
option.textContent = topic.name;
topicSelect.appendChild(option);
});
// Enable input if topics are loaded
userInput.disabled = false;
sendBtn.disabled = false;
} catch (error) {
console.error('Error loading topics:', error);
topicSelect.innerHTML = '<option value="">Error loading topics</option>';
}
}
async function loadAdminTopics() {
// Populate topic dropdowns in admin panel
docTopicSelect.innerHTML = '<option value="">Select a topic</option>';
filterTopic.innerHTML = '<option value="">All topics</option>';
editDocTopic.innerHTML = '<option value="">Select a topic</option>';
topics.forEach(topic => {
const option1 = document.createElement('option');
option1.value = topic.id;
option1.textContent = topic.name;
docTopicSelect.appendChild(option1.cloneNode(true));
const option2 = document.createElement('option');
option2.value = topic.id;
option2.textContent = topic.name;
filterTopic.appendChild(option2.cloneNode(true));
const option3 = document.createElement('option');
option3.value = topic.id;
option3.textContent = topic.name;
editDocTopic.appendChild(option3.cloneNode(true));
});
// Populate topic list for management
topicList.innerHTML = '';
topics.forEach(topic => {
const topicItem = document.createElement('div');
topicItem.className = 'flex justify-between items-center bg-white p-3 rounded border border-gray-200';
topicItem.innerHTML = `
<span>${topic.name}</span>
<button class="text-red-600 hover:text-red-800 delete-topic" data-id="${topic.id}">
<i class="fas fa-trash"></i>
</button>
`;
topicList.appendChild(topicItem);
});
// Add event listeners to delete buttons
document.querySelectorAll('.delete-topic').forEach(btn => {
btn.addEventListener('click', (e) => {
const topicId = e.currentTarget.getAttribute('data-id');
deleteTopic(topicId);
});
});
}
async function loadDocuments() {
try {
// Simulate API call to get documents
// In a real app, this would be an actual API call
const mockDocuments = [
{ id: '1', title: 'Introduction to AI', topicId: '1', content: 'Artificial Intelligence (AI) refers to the simulation of human intelligence in machines...' },
{ id: '2', title: 'Machine Learning Basics', topicId: '1', content: 'Machine learning is a subset of AI that focuses on building systems that learn from data...' },
{ id: '3', title: 'Quantum Computing', topicId: '2', content: 'Quantum computing leverages quantum-mechanical phenomena to perform calculations...' },
{ id: '4', title: 'Startup Funding', topicId: '3', content: 'Startup funding typically progresses through several stages: seed, Series A, B, C, etc...' },
{ id: '5', title: 'Nutrition Guidelines', topicId: '4', content: 'A balanced diet should include a variety of fruits, vegetables, whole grains, and lean proteins...' }
];
documents = mockDocuments;
} catch (error) {
console.error('Error loading documents:', error);
}
}
async function loadAdminDocuments() {
documentList.innerHTML = '';
documents.forEach(doc => {
const topic = topics.find(t => t.id === doc.topicId) || { name: 'Unknown' };
const docItem = document.createElement('div');
docItem.className = 'bg-white p-3 rounded border border-gray-200';
docItem.innerHTML = `
<div class="flex justify-between items-start mb-2">
<h4 class="font-medium">${doc.title}</h4>
<div class="flex space-x-2">
<button class="text-blue-600 hover:text-blue-800 edit-doc" data-id="${doc.id}">
<i class="fas fa-edit"></i>
</button>
<button class="text-red-600 hover:text-red-800 delete-doc" data-id="${doc.id}">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<div class="text-sm text-gray-600 mb-2">Topic: ${topic.name}</div>
<div class="text-sm text-gray-500 truncate">${doc.content.substring(0, 100)}...</div>
`;
documentList.appendChild(docItem);
});
// Add event listeners to edit and delete buttons
document.querySelectorAll('.edit-doc').forEach(btn => {
btn.addEventListener('click', (e) => {
const docId = e.currentTarget.getAttribute('data-id');
openEditModal(docId);
});
});
document.querySelectorAll('.delete-doc').forEach(btn => {
btn.addEventListener('click', (e) => {
const docId = e.currentTarget.getAttribute('data-id');
if (confirm('Are you sure you want to delete this document?')) {
deleteDocument(docId);
}
});
});
}
function handleTopicChange() {
currentTopic = topicSelect.value;
if (currentTopic) {
// Clear chat and show welcome message for the topic
chatMessages.innerHTML = '';
const topicName = topicSelect.options[topicSelect.selectedIndex].text;
const welcomeMessage = `
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div class="font-semibold text-blue-800">Welcome to the ${topicName} topic!</div>
<div class="text-sm text-blue-600 mt-1">You can now ask questions about ${topicName.toLowerCase()} documents.</div>
</div>
`;
chatMessages.innerHTML = welcomeMessage;
}
}
async function sendMessage() {
const question = userInput.value.trim();
if (!question || !currentTopic) return;
// Add user message to chat
addMessageToChat('user', question);
userInput.value = '';
// Show typing indicator
const typingIndicator = document.createElement('div');
typingIndicator.className = 'bg-gray-100 border border-gray-200 rounded-lg p-4 text-gray-700';
typingIndicator.innerHTML = `
<div class="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
`;
chatMessages.appendChild(typingIndicator);
chatMessages.scrollTop = chatMessages.scrollHeight;
try {
// Get relevant documents for the current topic
const relevantDocs = documents.filter(doc => doc.topicId === currentTopic);
if (relevantDocs.length === 0) {
typingIndicator.remove();
addMessageToChat('assistant', 'There are no documents available for this topic. Please try another topic or ask the admin to add documents.');
return;
}
// Prepare context for the AI
const context = relevantDocs.map(doc => `Document: ${doc.title}\n${doc.content}`).join('\n\n');
// Call OpenAI API
const response = await axios.post(API_BASE_URL, {
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: `You are a helpful assistant that answers questions based on the provided documents.
Use the following documents to answer the user's question. If you don't know the answer,
say that you don't know. Be concise and accurate in your responses.
Documents:
${context}`
},
{
role: "user",
content: question
}
],
temperature: 0.7,
max_tokens: 500
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
}
});
// Remove typing indicator
typingIndicator.remove();
// Add AI response to chat
const answer = response.data.choices[0].message.content;
addMessageToChat('assistant', answer);
} catch (error) {
console.error('Error getting AI response:', error);
// Remove typing indicator
typingIndicator.remove();
// Store the failed request for retry
lastFailedRequest = {
question,
currentTopic
};
// Show error message with retry option
let errorMessage = 'Sorry, I encountered an error while processing your request.';
if (error.response) {
if (error.response.status === 401) {
errorMessage = 'Error: Invalid API key. Please check your OpenAI API key configuration.';
} else if (error.response.status === 429) {
errorMessage = 'Error: Rate limit exceeded. Please wait a moment and try again.';
} else if (error.response.data?.error?.message) {
errorMessage = `Error: ${error.response.data.error.message}`;
}
}
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message fade-in';
errorDiv.innerHTML = `
<p>${errorMessage}</p>
<div class="retry-button" onclick="retryLastRequest()">
<i class="fas fa-redo mr-1"></i> Retry
</div>
`;
chatMessages.appendChild(errorDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
}
function retryLastRequest() {
if (lastFailedRequest) {
currentTopic = lastFailedRequest.currentTopic;
userInput.value = lastFailedRequest.question;
sendMessage();
}
}
function addMessageToChat(role, content) {
const messageDiv = document.createElement('div');
messageDiv.className = `fade-in ${role === 'user' ? 'text-right' : 'text-left'}`;
if (role === 'user') {
messageDiv.innerHTML = `
<div class="inline-block bg-blue-600 text-white rounded-lg p-3 max-w-xs md:max-w-md lg:max-w-lg">
${content}
</div>
`;
} else {
// Format AI response with markdown-like formatting
const formattedContent = content
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // Bold
.replace(/\*(.*?)\*/g, '<em>$1</em>') // Italic
.replace(/`(.*?)`/g, '<code class="bg-gray-200 px-1 rounded">$1</code>') // Inline code
.replace(/```([\s\S]*?)```/g, '<pre class="bg-gray-100 p-2 rounded overflow-x-auto"><code>$1</code></pre>'); // Code blocks
messageDiv.innerHTML = `
<div class="inline-block bg-gray-200 text-gray-800 rounded-lg p-3 max-w-xs md:max-w-md lg:max-w-lg">
${formattedContent}
</div>
`;
}
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function addNewTopic() {
const topicName = newTopicName.value.trim();
if (!topicName) return;
// Simulate adding a new topic (in a real app, this would be an API call)
const newTopic = {
id: Date.now().toString(),
name: topicName
};
topics.push(newTopic);
newTopicName.value = '';
hasUnsavedChanges = true;
// Reload topics in admin panel
loadAdminTopics();
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> Topic "${topicName}" has been added.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
}
function deleteTopic(topicId) {
if (!confirm('Are you sure you want to delete this topic? All associated documents will also be deleted.')) {
return;
}
// Simulate deleting a topic (in a real app, this would be an API call)
const topicIndex = topics.findIndex(t => t.id === topicId);
if (topicIndex !== -1) {
const deletedTopic = topics.splice(topicIndex, 1)[0];
// Also remove documents associated with this topic
documents = documents.filter(doc => doc.topicId !== topicId);
hasUnsavedChanges = true;
// Reload topics and documents in admin panel
loadAdminTopics();
loadAdminDocuments();
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> Topic "${deletedTopic.name}" has been deleted.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
}
}
function addNewDocument() {
const title = docTitle.value.trim();
const content = docContent.value.trim();
const topicId = docTopicSelect.value;
if (!title || !content || !topicId) {
alert('Please fill in all fields');
return;
}
// Simulate adding a new document (in a real app, this would be an API call)
const newDoc = {
id: Date.now().toString(),
title,
topicId,
content
};
documents.push(newDoc);
docTitle.value = '';
docContent.value = '';
docTopicSelect.value = '';
hasUnsavedChanges = true;
// Reload documents in admin panel
loadAdminDocuments();
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> Document "${title}" has been added.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
}
function filterDocuments() {
const topicFilter = filterTopic.value;
const searchQuery = searchDocs.value.toLowerCase();
documentList.innerHTML = '';
documents
.filter(doc => {
// Filter by topic if selected
if (topicFilter && doc.topicId !== topicFilter) return false;
// Filter by search query
if (searchQuery) {
const titleMatch = doc.title.toLowerCase().includes(searchQuery);
const contentMatch = doc.content.toLowerCase().includes(searchQuery);
return titleMatch || contentMatch;
}
return true;
})
.forEach(doc => {
const topic = topics.find(t => t.id === doc.topicId) || { name: 'Unknown' };
const docItem = document.createElement('div');
docItem.className = 'bg-white p-3 rounded border border-gray-200';
docItem.innerHTML = `
<div class="flex justify-between items-start mb-2">
<h4 class="font-medium">${doc.title}</h4>
<div class="flex space-x-2">
<button class="text-blue-600 hover:text-blue-800 edit-doc" data-id="${doc.id}">
<i class="fas fa-edit"></i>
</button>
<button class="text-red-600 hover:text-red-800 delete-doc" data-id="${doc.id}">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<div class="text-sm text-gray-600 mb-2">Topic: ${topic.name}</div>
<div class="text-sm text-gray-500 truncate">${doc.content.substring(0, 100)}...</div>
`;
documentList.appendChild(docItem);
});
// Add event listeners to edit and delete buttons
document.querySelectorAll('.edit-doc').forEach(btn => {
btn.addEventListener('click', (e) => {
const docId = e.currentTarget.getAttribute('data-id');
openEditModal(docId);
});
});
document.querySelectorAll('.delete-doc').forEach(btn => {
btn.addEventListener('click', (e) => {
const docId = e.currentTarget.getAttribute('data-id');
if (confirm('Are you sure you want to delete this document?')) {
deleteDocument(docId);
}
});
});
}
function openEditModal(docId) {
const doc = documents.find(d => d.id === docId);
if (!doc) return;
currentEditingDocId = docId;
editDocTitle.value = doc.title;
editDocContent.value = doc.content;
// Set the topic in the dropdown
editDocTopic.value = doc.topicId;
editModal.classList.remove('hidden');
}
function saveDocumentChanges() {
const docId = currentEditingDocId;
const docIndex = documents.findIndex(d => d.id === docId);
if (docIndex === -1) return;
const title = editDocTitle.value.trim();
const content = editDocContent.value.trim();
const topicId = editDocTopic.value;
if (!title || !content || !topicId) {
alert('Please fill in all fields');
return;
}
// Update the document
documents[docIndex] = {
...documents[docIndex],
title,
content,
topicId
};
hasUnsavedChanges = true;
// Close the modal
editModal.classList.add('hidden');
// Reload documents in admin panel
loadAdminDocuments();
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> Document "${title}" has been updated.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
}
function deleteDocument(docId) {
const docIndex = documents.findIndex(d => d.id === docId);
if (docIndex === -1) return;
const deletedDoc = documents.splice(docIndex, 1)[0];
hasUnsavedChanges = true;
// If we're in the edit modal for this doc, close it
if (currentEditingDocId === docId) {
editModal.classList.add('hidden');
currentEditingDocId = null;
}
// Reload documents in admin panel
loadAdminDocuments();
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> Document "${deletedDoc.title}" has been deleted.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
}
async function saveChanges() {
if (!hasUnsavedChanges) return;
savingIndicator.classList.remove('hidden');
// Simulate saving changes to a backend
// In a real app, this would be actual API calls to save topics and documents
try {
await new Promise(resolve => setTimeout(resolve, 1500));
hasUnsavedChanges = false;
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4 fade-in';
successMessage.innerHTML = `<strong>Success!</strong> All changes have been saved.`;
adminContent.insertBefore(successMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.classList.remove('fade-in');
successMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => successMessage.remove(), 300);
}, 3000);
} catch (error) {
console.error('Error saving changes:', error);
// Show error message
const errorMessage = document.createElement('div');
errorMessage.className = 'bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4 fade-in';
errorMessage.innerHTML = `<strong>Error!</strong> Failed to save changes. Please try again.`;
adminContent.insertBefore(errorMessage, adminContent.firstChild);
// Remove message after 3 seconds
setTimeout(() => {
errorMessage.classList.remove('fade-in');
errorMessage.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => errorMessage.remove(), 300);
}, 3000);
} finally {
savingIndicator.classList.add('hidden');
}
}
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=BLOCKED01/test123" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAG AI Document Explainer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style>
.chat-container {
height: calc(100vh - 200px);
}
.admin-panel {
display: none;
}
.document-list {
max-height: 400px;
overflow-y: auto;
}
.fade-in {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.markdown-content {
white-space: pre-wrap;
font-family: 'Courier New', monospace;
}
.typing-indicator {
display: inline-block;
}
.typing-indicator span {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #4b5563;
margin-right: 3px;
animation: bounce 1.4s infinite ease-in-out both;
}
.typing-indicator span:nth-child(1) {
animation-delay: -0.32s;
}
.typing-indicator span:nth-child(2) {
animation-delay: -0.16s;
}
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
.saving-indicator {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
.error-message {
background-color: #fee2e2;
border-left: 4px solid #ef4444;
padding: 1rem;
margin-bottom: 1rem;
border-radius: 0.375rem;
}
.retry-button {
background-color: #ef4444;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.875rem;
margin-top: 0.5rem;
display: inline-block;
cursor: pointer;
}
.retry-button:hover {
background-color: #dc2626;
}
</style>
</head>
<body class="bg-gray-100">
<!-- Navigation -->
<nav class="bg-blue-600 text-white p-4 shadow-md">
<div class="container mx-auto flex justify-between items-center">
<div class="flex items-center space-x-2">
<i class="fas fa-robot text-2xl"></i>
<h1 class="text-xl font-bold">RAG Document Explainer</h1>
</div>
<button id="adminBtn" class="bg-white text-blue-600 px-4 py-2 rounded-md font-medium hover:bg-blue-50 transition">
Admin Panel
</button>
</div>
</nav>
<!-- Main Chat Interface -->
<div id="chatInterface" class="container mx-auto p-4 max-w-6xl">
<div class="bg-white rounded-lg shadow-md p-6">
<h2 class="text-2xl font-bold text-gray-800 mb-6">Ask about any document</h2>