Spaces:
Running
Running
File size: 28,826 Bytes
cca4a24 |
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>๐ค AI-Powered Document Search & RAG Chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.1);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 { font-size: 2.5em; margin-bottom: 10px; }
.header p { font-size: 1.2em; opacity: 0.9; }
.status {
background: #f8f9fa;
padding: 15px 30px;
border-bottom: 1px solid #e9ecef;
font-weight: 600;
color: #495057;
}
.tabs {
display: flex;
background: #f8f9fa;
border-bottom: 1px solid #e9ecef;
}
.tab {
flex: 1;
padding: 15px 20px;
background: none;
border: none;
cursor: pointer;
font-weight: 600;
font-size: 14px;
transition: all 0.3s;
border-bottom: 3px solid transparent;
}
.tab:hover { background: #e9ecef; }
.tab.active { background: white; border-bottom-color: #667eea; color: #667eea; }
.tab-content {
display: none;
padding: 30px;
}
.tab-content.active { display: block; }
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: #495057;
}
input, textarea, select {
width: 100%;
padding: 12px;
border: 2px solid #e9ecef;
border-radius: 8px;
font-size: 16px;
transition: border-color 0.3s;
}
input:focus, textarea:focus, select:focus {
outline: none;
border-color: #667eea;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s;
}
button:hover { transform: translateY(-2px); }
.btn-secondary {
background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
}
.result {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 20px;
margin-top: 15px;
white-space: pre-wrap;
max-height: 400px;
overflow-y: auto;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.alert {
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
}
.alert-info {
background: #d1ecf1;
border: 1px solid #b8daff;
color: #0c5460;
}
.alert-success {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.slider-container {
display: flex;
align-items: center;
gap: 15px;
}
.slider {
flex: 1;
}
.slider-value {
min-width: 40px;
text-align: center;
font-weight: 600;
color: #667eea;
}
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #f3f3f3;
border-top: 2px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>๐ค AI-Powered Document Search & RAG Chat</h1>
<p>Complete RAG system with semantic search and intelligent responses</p>
</div>
<div class="status" id="status">
๐ Documents: 3 | ๐ค AI Models: Not loaded
</div>
<div class="tabs">
<button class="tab active" onclick="showTab('init')">๐ Initialize AI</button>
<button class="tab" onclick="showTab('chat')">๐ค AI Chat (RAG)</button>
<button class="tab" onclick="showTab('search')">๐ Semantic Search</button>
<button class="tab" onclick="showTab('add')">๐ Add Documents</button>
<button class="tab" onclick="showTab('test')">๐งช System Test</button>
</div>
<!-- Initialize AI Tab -->
<div id="init" class="tab-content active">
<div class="alert alert-info">
<strong>๐ Start here!</strong> Initialize the AI system for semantic search and intelligent chat.
</div>
<div class="alert alert-success">
<strong>โก Features:</strong><br>
โข ๐ฎ <strong>Semantic Search:</strong> AI-powered similarity matching<br>
โข ๐ง <strong>Smart Chat:</strong> Context-aware responses with document retrieval<br>
โข ๐ <strong>RAG Pipeline:</strong> Retrieval-Augmented Generation for accurate answers
</div>
<button onclick="initializeModels()" style="font-size: 18px; padding: 15px 30px;">
๐ Initialize AI Models
</button>
<div id="initStatus" class="result" style="display: none;"></div>
</div>
<!-- AI Chat Tab -->
<div id="chat" class="tab-content">
<div class="alert alert-info">
<strong>๐ค Ask questions!</strong> The AI searches through documents and provides intelligent answers.
</div>
<div class="alert alert-success">
<strong>๐ก Try asking:</strong><br>
โข "What is artificial intelligence?"<br>
โข "How does space exploration work?"<br>
โข "What are renewable energy sources?"
</div>
<div class="grid">
<div>
<label for="chatQuestion">Your Question</label>
<textarea id="chatQuestion" rows="3" placeholder="Ask anything about the documents..."></textarea>
</div>
<div>
<label for="maxContext">Context Documents</label>
<div class="slider-container">
<input type="range" id="maxContext" class="slider" min="1" max="5" value="3" oninput="updateSliderValue('maxContext')">
<span id="maxContextValue" class="slider-value">3</span>
</div>
</div>
</div>
<button onclick="chatWithRAG()">๐ค Ask AI</button>
<div id="chatResponse" class="result" style="display: none;"></div>
</div>
<!-- Semantic Search Tab -->
<div id="search" class="tab-content">
<div class="alert alert-info">
<strong>๐ฎ Semantic search!</strong> Find documents by meaning, not just keywords.
</div>
<div class="grid">
<div>
<label for="searchQuery">Search Query</label>
<input type="text" id="searchQuery" placeholder="Try: 'machine learning', 'Mars missions', 'solar power'">
</div>
<div>
<label for="maxResults">Max Results</label>
<div class="slider-container">
<input type="range" id="maxResults" class="slider" min="1" max="10" value="5" oninput="updateSliderValue('maxResults')">
<span id="maxResultsValue" class="slider-value">5</span>
</div>
</div>
</div>
<div style="display: flex; gap: 10px;">
<button onclick="searchDocumentsSemantic()">๐ฎ Semantic Search</button>
<button class="btn-secondary" onclick="searchDocumentsKeyword()">๐ค Keyword Search</button>
</div>
<div id="searchResults" class="result" style="display: none;"></div>
</div>
<!-- Add Documents Tab -->
<div id="add" class="tab-content">
<div class="alert alert-info">
<strong>๐ Expand your knowledge base!</strong> Add your own documents to search and chat with.
</div>
<div class="form-group">
<label for="docTitle">Document Title (optional)</label>
<input type="text" id="docTitle" placeholder="Enter document title...">
</div>
<div class="form-group">
<label for="docContent">Document Content</label>
<textarea id="docContent" rows="8" placeholder="Paste your document text here..."></textarea>
</div>
<button onclick="addDocument()">๐ Add Document</button>
<div class="grid">
<div id="addStatus" class="result" style="display: none;"></div>
<div id="docPreview" class="result" style="display: none;"></div>
</div>
</div>
<!-- System Test Tab -->
<div id="test" class="tab-content">
<div class="alert alert-info">
<strong>๐งช Test the system</strong> to verify everything is working correctly.
</div>
<button onclick="testSystem()">๐งช Run System Test</button>
<div id="testOutput" class="result" style="display: none;"></div>
</div>
</div>
<script>
// Document storage and AI state
let documents = [
{
id: 0,
title: "Artificial Intelligence Overview",
content: "Artificial Intelligence (AI) is a branch of computer science that aims to create intelligent machines that work and react like humans. Some activities computers with AI are designed for include speech recognition, learning, planning, and problem-solving. AI is used in healthcare, finance, transportation, and entertainment. Machine learning enables computers to learn from experience without explicit programming. Deep learning uses neural networks to understand complex patterns.",
embedding: null
},
{
id: 1,
title: "Space Exploration",
content: "Space exploration is the ongoing discovery and exploration of celestial structures in outer space through evolving space technology. Physical exploration is conducted by unmanned robotic probes and human spaceflight. Space exploration has been used for geopolitical rivalries like the Cold War. The early era was driven by a Space Race between the Soviet Union and United States. Modern exploration includes Mars missions, the International Space Station, and satellite programs.",
embedding: null
},
{
id: 2,
title: "Renewable Energy",
content: "Renewable energy comes from naturally replenished resources on a human timescale. It includes sunlight, wind, rain, tides, waves, and geothermal heat. Renewable energy contrasts with fossil fuels that are used faster than replenished. Most renewable sources are sustainable. Solar energy is abundant and promising. Wind energy and hydroelectric power are major contributors to renewable generation worldwide.",
embedding: null
}
];
let modelsInitialized = false;
// Simple embedding generation based on word frequency
function generateEmbedding(text) {
const words = text.toLowerCase().split(/\s+/);
const embedding = new Array(10).fill(0);
// Word to dimension mapping
const wordDims = {
'ai': 0, 'artificial': 0, 'intelligence': 0, 'machine': 0, 'learning': 0,
'space': 1, 'exploration': 1, 'mars': 1, 'satellite': 1, 'rocket': 1,
'energy': 2, 'renewable': 2, 'solar': 2, 'wind': 2, 'power': 2,
'computer': 3, 'technology': 3, 'science': 3, 'data': 3,
'human': 4, 'people': 4, 'society': 4, 'world': 4,
'system': 5, 'network': 5, 'process': 5, 'method': 5,
'research': 6, 'study': 6, 'analysis': 6, 'development': 6,
'future': 7, 'modern': 7, 'new': 7, 'advanced': 7,
'problem': 8, 'solution': 8, 'application': 8, 'use': 8,
'important': 9, 'major': 9, 'significant': 9, 'key': 9
};
// Count word frequencies
words.forEach(word => {
if (wordDims.hasOwnProperty(word)) {
embedding[wordDims[word]]++;
}
});
// Normalize vector
const magnitude = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0));
if (magnitude > 0) {
return embedding.map(val => val / magnitude);
}
return embedding;
}
// Calculate cosine similarity
function cosineSimilarity(a, b) {
const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
const magnitudeB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
if (magnitudeA === 0 || magnitudeB === 0) return 0;
return dotProduct / (magnitudeA * magnitudeB);
}
// UI Functions
function showTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab').forEach(button => {
button.classList.remove('active');
});
// Show selected tab
document.getElementById(tabName).classList.add('active');
event.target.classList.add('active');
}
function updateSliderValue(sliderId) {
const slider = document.getElementById(sliderId);
const valueSpan = document.getElementById(sliderId + 'Value');
valueSpan.textContent = slider.value;
}
function updateStatus() {
const status = document.getElementById('status');
status.textContent = `๐ Documents: ${documents.length} | ๐ค AI Models: ${modelsInitialized ? 'Loaded' : 'Not loaded'}`;
}
// AI Functions
function initializeModels() {
const statusDiv = document.getElementById('initStatus');
statusDiv.style.display = 'block';
statusDiv.innerHTML = '<div class="loading"></div> Initializing AI models...';
setTimeout(() => {
modelsInitialized = true;
// Generate embeddings for all documents
documents.forEach(doc => {
doc.embedding = generateEmbedding(doc.content);
});
statusDiv.innerHTML = `โ
AI Models initialized successfully!
๐ฎ Embeddings generated for all documents
๐ง Ready for semantic search and RAG chat!
๐ System Status:
โข Documents processed: ${documents.length}
โข Embedding dimensions: 10
โข Similarity algorithm: Cosine similarity
โข Ready for advanced queries!`;
updateStatus();
}, 2000);
}
function searchDocumentsSemantic() {
const query = document.getElementById('searchQuery').value;
const maxResults = parseInt(document.getElementById('maxResults').value);
const resultsDiv = document.getElementById('searchResults');
if (!query.trim()) {
resultsDiv.style.display = 'block';
resultsDiv.textContent = 'โ Please enter a search query';
return;
}
if (!modelsInitialized) {
resultsDiv.style.display = 'block';
resultsDiv.textContent = 'โ Please initialize AI models first!';
return;
}
resultsDiv.style.display = 'block';
resultsDiv.innerHTML = '<div class="loading"></div> Searching...';
setTimeout(() => {
const queryEmbedding = generateEmbedding(query);
const results = [];
documents.forEach(doc => {
if (doc.embedding) {
const similarity = cosineSimilarity(queryEmbedding, doc.embedding);
results.push({ doc, similarity });
}
});
results.sort((a, b) => b.similarity - a.similarity);
if (results.length === 0) {
resultsDiv.textContent = `โ No documents found for '${query}'`;
return;
}
let output = `๐ Semantic search results for '${query}':\n\n`;
results.slice(0, maxResults).forEach((result, i) => {
const doc = result.doc;
const similarity = result.similarity;
const excerpt = doc.content.length > 200 ? doc.content.substring(0, 200) + '...' : doc.content;
output += `**Result ${i + 1}** (similarity: ${similarity.toFixed(3)})\n๐ Title: ${doc.title}\n๐ Content: ${excerpt}\n\n`;
});
resultsDiv.textContent = output;
}, 500);
}
function searchDocumentsKeyword() {
const query = document.getElementById('searchQuery').value;
const maxResults = parseInt(document.getElementById('maxResults').value);
const resultsDiv = document.getElementById('searchResults');
if (!query.trim()) {
resultsDiv.style.display = 'block';
resultsDiv.textContent = 'โ Please enter a search query';
return;
}
resultsDiv.style.display = 'block';
resultsDiv.innerHTML = '<div class="loading"></div> Searching...';
setTimeout(() => {
const results = [];
const queryWords = query.toLowerCase().split(/\s+/);
documents.forEach(doc => {
const contentLower = doc.content.toLowerCase();
const titleLower = doc.title.toLowerCase();
let matches = 0;
queryWords.forEach(word => {
matches += (contentLower.match(new RegExp(word, 'g')) || []).length;
matches += (titleLower.match(new RegExp(word, 'g')) || []).length * 2; // Title matches weighted more
});
if (matches > 0) {
results.push({ doc, score: matches });
}
});
results.sort((a, b) => b.score - a.score);
if (results.length === 0) {
resultsDiv.textContent = `โ No documents found containing '${query}'`;
return;
}
let output = `๐ Keyword search results for '${query}':\n\n`;
results.slice(0, maxResults).forEach((result, i) => {
const doc = result.doc;
const excerpt = doc.content.length > 200 ? doc.content.substring(0, 200) + '...' : doc.content;
output += `**Result ${i + 1}**\n๐ Title: ${doc.title}\n๐ Content: ${excerpt}\n\n`;
});
resultsDiv.textContent = output;
}, 500);
}
function chatWithRAG() {
const question = document.getElementById('chatQuestion').value;
const maxContext = parseInt(document.getElementById('maxContext').value);
const responseDiv = document.getElementById('chatResponse');
if (!question.trim()) {
responseDiv.style.display = 'block';
responseDiv.textContent = 'โ Please enter a question';
return;
}
if (!modelsInitialized) {
responseDiv.style.display = 'block';
responseDiv.textContent = 'โ AI models not loaded yet. Please initialize them first!';
return;
}
responseDiv.style.display = 'block';
responseDiv.innerHTML = '<div class="loading"></div> Generating response...';
setTimeout(() => {
// Use semantic search to find relevant documents
const queryEmbedding = generateEmbedding(question);
const relevantDocs = [];
documents.forEach(doc => {
if (doc.embedding) {
const similarity = cosineSimilarity(queryEmbedding, doc.embedding);
if (similarity > 0.1) { // Threshold for relevance
relevantDocs.push({ doc, similarity });
}
}
});
relevantDocs.sort((a, b) => b.similarity - a.similarity);
relevantDocs.splice(maxContext); // Limit to maxContext documents
if (relevantDocs.length === 0) {
responseDiv.textContent = 'โ No relevant context found. Try asking about AI, space exploration, or renewable energy.';
return;
}
// Generate response based on context
const contextTexts = relevantDocs.map(item => item.doc.content.substring(0, 400));
const context = contextTexts.join(' ');
// Simple response generation based on question type
const questionLower = question.toLowerCase();
let response = '';
if (questionLower.includes('what') || questionLower.includes('define')) {
response = `๐ค Based on the documents, here's what I found:\n\n${context.substring(0, 500)}...`;
} else if (questionLower.includes('how') || questionLower.includes('process') || questionLower.includes('work')) {
response = `๐ค Here's how it works according to the documents:\n\n${context.substring(0, 500)}...`;
} else if (questionLower.includes('why') || questionLower.includes('reason')) {
response = `๐ค The reasons include:\n\n${context.substring(0, 500)}...`;
} else {
response = `๐ค Based on the relevant documents:\n\n${context.substring(0, 500)}...`;
}
response += `\n\n๐ Sources: ${relevantDocs.length} documents | Best similarity: ${relevantDocs[0].similarity.toFixed(3)}`;
responseDiv.textContent = response;
}, 1500);
}
function addDocument() {
const title = document.getElementById('docTitle').value || `User Document ${documents.length - 2}`;
const content = document.getElementById('docContent').value;
const statusDiv = document.getElementById('addStatus');
const previewDiv = document.getElementById('docPreview');
if (!content.trim()) {
statusDiv.style.display = 'block';
statusDiv.textContent = 'โ Please enter document content';
previewDiv.style.display = 'none';
return;
}
const docId = documents.length;
const document = {
id: docId,
title: title,
content: content.trim(),
embedding: modelsInitialized ? generateEmbedding(content) : null
};
documents.push(document);
const preview = content.length > 300 ? content.substring(0, 300) + '...' : content;
const status = `โ
Document added successfully!
๐ Title: ${title}
๐ Size: ${content.length.toLocaleString()} characters
๐ Total documents: ${documents.length}${modelsInitialized ? '\n๐ฎ Embedding generated automatically' : ''}`;
statusDiv.style.display = 'block';
statusDiv.textContent = status;
previewDiv.style.display = 'block';
previewDiv.textContent = `๐ Preview:\n${preview}`;
// Clear form
document.getElementById('docTitle').value = '';
document.getElementById('docContent').value = '';
updateStatus();
}
function testSystem() {
const outputDiv = document.getElementById('testOutput');
outputDiv.style.display = 'block';
outputDiv.innerHTML = '<div class="loading"></div> Running system tests...';
setTimeout(() => {
if (documents.length === 0) {
outputDiv.textContent = 'โ No documents found!';
return;
}
// Perform a test search
const testQuery = 'AI';
const queryEmbedding = generateEmbedding(testQuery);
let testResults = [];
if (modelsInitialized) {
documents.forEach(doc => {
if (doc.embedding) {
const similarity = cosineSimilarity(queryEmbedding, doc.embedding);
if (similarity > 0) {
testResults.push({ doc, similarity });
}
}
});
testResults.sort((a, b) => b.similarity - a.similarity);
}
let output = `โ
System test successful! ${documents.length} documents loaded.\n\n`;
if (modelsInitialized) {
output += `๐ฎ AI Models: โ
Loaded\n๐งฎ Embeddings: โ
Generated\n๐ Test search for "AI": ${testResults.length} results\n\n`;
if (testResults.length > 0) {
const topResult = testResults[0];
output += `๐ Top result: "${topResult.doc.title}" (similarity: ${topResult.similarity.toFixed(3)})\n`;
output += `๐ Content: ${topResult.doc.content.substring(0, 150)}...`;
}
} else {
output += `โ ๏ธ AI Models: Not initialized\n๐ก Click "Initialize AI Models" to enable semantic search and RAG chat`;
}
outputDiv.textContent = output;
}, 1000);
}
// Initialize UI
updateStatus();
</script>
</body>
</html>
|