Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,71 +1,162 @@
|
|
| 1 |
-
# app.py -
|
|
|
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import uvicorn
|
| 5 |
import asyncio
|
| 6 |
import importlib.util
|
| 7 |
import json
|
| 8 |
-
import markdown
|
| 9 |
from pathlib import Path
|
| 10 |
-
from fastapi import FastAPI, Form
|
| 11 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 12 |
from groq import Groq
|
| 13 |
-
from contextlib import asynccontextmanager
|
| 14 |
|
| 15 |
# ============================================
|
| 16 |
-
# 1.
|
| 17 |
# ============================================
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
print(f"π€ Username: AumCore AI")
|
| 26 |
-
print(f"π Server: http://0.0.0.0:7860")
|
| 27 |
-
print(f"π€ AI Model: llama-3.3-70b-versatile")
|
| 28 |
-
print(f"πΎ Database: TiDB Cloud")
|
| 29 |
-
print(f"π¨ UI Features: Code formatting + Copy button")
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
except Exception as e:
|
| 38 |
-
print(f"β οΈ Groq API: Not Available - {e}")
|
| 39 |
-
client = None
|
| 40 |
-
GROQ_AVAILABLE = False
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# ============================================
|
| 57 |
-
#
|
| 58 |
# ============================================
|
|
|
|
| 59 |
app = FastAPI(
|
| 60 |
title="AumCore AI",
|
| 61 |
description="Advanced Modular AI Assistant System",
|
| 62 |
-
version=
|
| 63 |
-
lifespan=lifespan
|
| 64 |
)
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
# ============================================
|
| 67 |
-
#
|
| 68 |
# ============================================
|
|
|
|
| 69 |
HTML_UI = '''
|
| 70 |
<!DOCTYPE html>
|
| 71 |
<html lang="en">
|
|
@@ -276,7 +367,10 @@ body {
|
|
| 276 |
}
|
| 277 |
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
|
| 278 |
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
|
| 279 |
-
@keyframes blink {
|
|
|
|
|
|
|
|
|
|
| 280 |
/* Health Indicator */
|
| 281 |
.health-indicator {
|
| 282 |
display: inline-flex;
|
|
@@ -291,39 +385,19 @@ body {
|
|
| 291 |
.health-yellow { background: #d29922; color: black; }
|
| 292 |
.health-red { background: #da3633; color: white; }
|
| 293 |
.health-value { font-family: 'Fira Code', monospace; }
|
| 294 |
-
/*
|
| 295 |
-
.
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
}
|
| 303 |
-
.markdown-content ul, .markdown-content ol {
|
| 304 |
-
margin: 10px 0 10px 20px;
|
| 305 |
-
}
|
| 306 |
-
.markdown-content li {
|
| 307 |
-
margin: 5px 0;
|
| 308 |
-
}
|
| 309 |
-
.markdown-content strong {
|
| 310 |
-
color: #79c0ff;
|
| 311 |
-
}
|
| 312 |
-
.markdown-content em {
|
| 313 |
-
color: #c9d1d9;
|
| 314 |
-
font-style: italic;
|
| 315 |
-
}
|
| 316 |
-
.markdown-content code:not(pre code) {
|
| 317 |
background: #161b22;
|
| 318 |
-
color: #
|
| 319 |
-
padding: 2px 6px;
|
| 320 |
-
border-radius: 4px;
|
| 321 |
-
font-family: 'Fira Code', monospace;
|
| 322 |
-
font-size: 14px;
|
| 323 |
-
}
|
| 324 |
-
.markdown-content pre {
|
| 325 |
-
margin: 0;
|
| 326 |
}
|
|
|
|
|
|
|
| 327 |
</style>
|
| 328 |
</head>
|
| 329 |
<body>
|
|
@@ -340,306 +414,216 @@ body {
|
|
| 340 |
</div>
|
| 341 |
</div>
|
| 342 |
<div class="main-chat">
|
| 343 |
-
<div id="chat-log" class="chat-box">
|
| 344 |
-
<div class="message-wrapper">
|
| 345 |
-
<div class="bubble ai-text markdown-content">
|
| 346 |
-
<h3>Namaste! π AumCore AI ΰ€―ΰ€Ήΰ€Ύΰ€ ΰ€Ήΰ₯</h3>
|
| 347 |
-
<p>System successfully initialized with <strong>7 modules loaded</strong>:</p>
|
| 348 |
-
<ul>
|
| 349 |
-
<li>π Titan Orchestrator</li>
|
| 350 |
-
<li>π§ͺ Testing Module</li>
|
| 351 |
-
<li>π System Diagnostics</li>
|
| 352 |
-
<li>π» Code Formatter</li>
|
| 353 |
-
<li>π€ Prompt Manager</li>
|
| 354 |
-
<li>π§ Code Intelligence</li>
|
| 355 |
-
<li>π¨βπ» Code Reviewer</li>
|
| 356 |
-
</ul>
|
| 357 |
-
<p>You can now ask me anything in <strong>Hindi or English</strong>!</p>
|
| 358 |
-
<div class="health-indicator health-green" style="margin-top: 15px;">
|
| 359 |
-
<i class="fas fa-heartbeat"></i>
|
| 360 |
-
<span class="health-value">System: ONLINE</span>
|
| 361 |
-
<span>Groq API: ACTIVE</span>
|
| 362 |
-
</div>
|
| 363 |
-
</div>
|
| 364 |
-
</div>
|
| 365 |
-
</div>
|
| 366 |
<div class="input-area">
|
| 367 |
<div class="input-container">
|
| 368 |
<textarea id="user-input" rows="1" placeholder="Type your message to AumCore..." autocomplete="off" oninput="resizeInput(this)" onkeydown="handleKey(event)"></textarea>
|
| 369 |
-
<button onclick="
|
| 370 |
</div>
|
| 371 |
</div>
|
| 372 |
</div>
|
| 373 |
<script>
|
| 374 |
// Resize input dynamically
|
| 375 |
-
function resizeInput(el){
|
| 376 |
-
el.style.height = 'auto';
|
| 377 |
-
el.style.height = el.scrollHeight + 'px';
|
| 378 |
-
}
|
| 379 |
-
|
| 380 |
// Handle Enter key for send
|
| 381 |
-
function handleKey(e){
|
| 382 |
-
if(e.key === 'Enter' && !e.shiftKey){
|
| 383 |
-
e.preventDefault();
|
| 384 |
-
sendMessage();
|
| 385 |
-
}
|
| 386 |
-
}
|
| 387 |
-
|
| 388 |
// Format code blocks
|
| 389 |
function formatCodeBlocks(text){
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
// Original Python code blocks
|
| 395 |
-
formatted = formatted.replace(/```python\s*([\s\S]*?)```/gi,
|
| 396 |
-
'<div class="code-container"><div class="code-header"><div class="code-lang">Python</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code class="language-python">$1</code></pre></div>');
|
| 397 |
-
|
| 398 |
-
// Generic code blocks
|
| 399 |
-
formatted = formatted.replace(/```\s*([\s\S]*?)```/g,
|
| 400 |
-
'<div class="code-container"><div class="code-header"><div class="code-lang">Code</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code>$1</code></pre></div>');
|
| 401 |
-
|
| 402 |
return formatted;
|
| 403 |
}
|
| 404 |
-
|
| 405 |
// Copy code to clipboard
|
| 406 |
function copyCode(button){
|
| 407 |
-
const codeBlock
|
| 408 |
-
const codeText
|
| 409 |
-
navigator.clipboard.writeText(codeText).then(()
|
| 410 |
-
let origHTML
|
| 411 |
-
let origClass
|
| 412 |
-
button.innerHTML
|
| 413 |
-
button.className
|
| 414 |
-
setTimeout(()
|
| 415 |
-
|
| 416 |
-
button.className = origClass;
|
| 417 |
-
}, 2000);
|
| 418 |
-
}).catch(err => {
|
| 419 |
-
console.error('Copy failed:', err);
|
| 420 |
-
button.innerHTML = '<i class="fas fa-times"></i> Failed';
|
| 421 |
-
setTimeout(() => {
|
| 422 |
-
button.innerHTML = '<i class="fas fa-copy"></i> Copy';
|
| 423 |
-
}, 2000);
|
| 424 |
-
});
|
| 425 |
}
|
| 426 |
-
|
| 427 |
// Reset memory confirmation
|
| 428 |
async function confirmReset(){
|
| 429 |
if(confirm("Sanjay bhai, kya aap sach mein saari memory delete karna chahte hain?")){
|
| 430 |
try{
|
| 431 |
-
const res
|
| 432 |
-
const data
|
| 433 |
alert(data.message);
|
| 434 |
window.location.reload();
|
| 435 |
-
}catch(e){
|
| 436 |
-
alert("Reset failed: " + e.message);
|
| 437 |
-
}
|
| 438 |
}
|
| 439 |
}
|
| 440 |
-
|
| 441 |
// System Health Check
|
| 442 |
async function checkSystemHealth(){
|
| 443 |
try{
|
| 444 |
-
const res
|
| 445 |
-
const data
|
| 446 |
if(data.success){
|
| 447 |
-
const health
|
| 448 |
-
let healthClass
|
| 449 |
-
if(health
|
| 450 |
-
else if(health
|
| 451 |
|
| 452 |
-
alert(
|
| 453 |
}else{
|
| 454 |
-
alert('Health check failed: '
|
| 455 |
}
|
| 456 |
}catch(e){
|
| 457 |
-
alert('Health check error: '
|
| 458 |
}
|
| 459 |
}
|
| 460 |
-
|
| 461 |
// Module Status Check
|
| 462 |
async function showModuleStatus(){
|
| 463 |
try{
|
| 464 |
-
const res
|
| 465 |
-
const data
|
| 466 |
if(data.success){
|
| 467 |
-
let moduleList
|
| 468 |
-
data.modules.forEach(module
|
| 469 |
-
moduleList
|
| 470 |
});
|
| 471 |
alert(moduleList);
|
| 472 |
}
|
| 473 |
}catch(e){
|
| 474 |
-
alert('Module status error: '
|
| 475 |
}
|
| 476 |
}
|
| 477 |
-
|
| 478 |
// Run Diagnostics
|
| 479 |
async function runDiagnostics(){
|
| 480 |
-
const log
|
| 481 |
-
const typingId
|
| 482 |
-
log.innerHTML
|
| 483 |
-
log.scrollTop
|
| 484 |
|
| 485 |
try{
|
| 486 |
-
const res
|
| 487 |
-
const data
|
| 488 |
-
const typingElem
|
| 489 |
if(typingElem) typingElem.remove();
|
| 490 |
|
| 491 |
if(data.success){
|
| 492 |
-
const report
|
| 493 |
-
const health
|
| 494 |
-
let healthClass
|
| 495 |
-
if(health
|
| 496 |
-
else if(health
|
| 497 |
|
| 498 |
-
let html
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
log.innerHTML
|
| 520 |
}else{
|
| 521 |
-
log.innerHTML
|
| 522 |
}
|
| 523 |
}catch(e){
|
| 524 |
-
const typingElem
|
| 525 |
if(typingElem) typingElem.remove();
|
| 526 |
-
log.innerHTML
|
| 527 |
}
|
| 528 |
-
log.scrollTop
|
| 529 |
}
|
| 530 |
-
|
| 531 |
// Run Tests
|
| 532 |
async function runTests(){
|
| 533 |
-
const log
|
| 534 |
-
const typingId
|
| 535 |
-
log.innerHTML
|
| 536 |
-
log.scrollTop
|
| 537 |
|
| 538 |
try{
|
| 539 |
-
const res
|
| 540 |
-
const data
|
| 541 |
-
const typingElem
|
| 542 |
if(typingElem) typingElem.remove();
|
| 543 |
|
| 544 |
if(data.success){
|
| 545 |
-
const results
|
| 546 |
-
let
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
'</div>';
|
| 566 |
-
log.innerHTML += html;
|
| 567 |
}else{
|
| 568 |
-
log.innerHTML
|
| 569 |
}
|
| 570 |
}catch(e){
|
| 571 |
-
const typingElem
|
| 572 |
if(typingElem) typingElem.remove();
|
| 573 |
-
log.innerHTML
|
| 574 |
}
|
| 575 |
-
log.scrollTop
|
| 576 |
-
}
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
const
|
| 581 |
-
const
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
if(!text) return;
|
| 585 |
-
|
| 586 |
// Add user message
|
| 587 |
-
log.innerHTML
|
| 588 |
-
input.value =
|
| 589 |
-
input.style.height = 'auto';
|
| 590 |
-
|
| 591 |
// Typing indicator
|
| 592 |
-
const typingId
|
| 593 |
-
log.innerHTML
|
| 594 |
-
log.scrollTop
|
| 595 |
-
|
| 596 |
try{
|
| 597 |
-
const res
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
body: 'message=' + encodeURIComponent(text)
|
| 603 |
-
});
|
| 604 |
-
|
| 605 |
-
if (!res.ok) {
|
| 606 |
-
throw new Error('HTTP ' + res.status);
|
| 607 |
-
}
|
| 608 |
-
|
| 609 |
-
const data = await res.json();
|
| 610 |
-
const typingElem = document.getElementById(typingId);
|
| 611 |
-
if(typingElem) typingElem.remove();
|
| 612 |
-
|
| 613 |
-
let formatted = formatCodeBlocks(data.response);
|
| 614 |
-
log.innerHTML += '<div class="message-wrapper"><div class="bubble ai-text markdown-content">' + formatted + '</div></div>';
|
| 615 |
-
|
| 616 |
}catch(e){
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
if(typingElem) typingElem.remove();
|
| 620 |
-
|
| 621 |
-
log.innerHTML += '<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Error connecting to AumCore. Please try again.</div></div>';
|
| 622 |
}
|
| 623 |
-
|
| 624 |
-
log.scrollTop = log.scrollHeight;
|
| 625 |
}
|
| 626 |
-
|
| 627 |
-
// Initialize
|
| 628 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 629 |
-
const input = document.getElementById('user-input');
|
| 630 |
-
if(input) input.focus();
|
| 631 |
-
|
| 632 |
-
// Show welcome message
|
| 633 |
-
console.log('AumCore AI UI loaded successfully');
|
| 634 |
-
});
|
| 635 |
</script>
|
| 636 |
</body>
|
| 637 |
</html>
|
| 638 |
'''
|
| 639 |
|
| 640 |
# ============================================
|
| 641 |
-
#
|
| 642 |
# ============================================
|
|
|
|
| 643 |
@app.get("/", response_class=HTMLResponse)
|
| 644 |
async def get_ui():
|
| 645 |
"""Main UI endpoint"""
|
|
@@ -648,11 +632,15 @@ async def get_ui():
|
|
| 648 |
@app.post("/reset")
|
| 649 |
async def reset():
|
| 650 |
"""Reset system memory"""
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 656 |
|
| 657 |
@app.post("/chat")
|
| 658 |
async def chat(message: str = Form(...)):
|
|
@@ -661,145 +649,108 @@ async def chat(message: str = Form(...)):
|
|
| 661 |
return {"response": "Error: Groq API not configured. Please check API key."}
|
| 662 |
|
| 663 |
try:
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
completion = client.chat.completions.create(
|
| 686 |
model="llama-3.3-70b-versatile",
|
| 687 |
-
messages=
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
],
|
| 691 |
-
temperature=0.7,
|
| 692 |
-
max_tokens=1500,
|
| 693 |
-
top_p=0.9
|
| 694 |
)
|
|
|
|
| 695 |
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
# Convert markdown to HTML
|
| 699 |
try:
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
)
|
| 704 |
-
except:
|
| 705 |
-
# Fallback if markdown conversion fails
|
| 706 |
-
html_response = response_text.replace('\n', '<br>')
|
| 707 |
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
return {"response": html_response}
|
| 711 |
|
| 712 |
except Exception as e:
|
| 713 |
-
error_msg = str(e)
|
| 714 |
-
print(f"β
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
Please try again or check the Groq API configuration.
|
| 721 |
-
</div>
|
| 722 |
-
'''
|
| 723 |
-
|
| 724 |
-
return {"response": error_html}
|
| 725 |
|
| 726 |
@app.get("/system/health")
|
| 727 |
async def system_health():
|
| 728 |
-
"""
|
| 729 |
-
|
| 730 |
"success": True,
|
| 731 |
-
"
|
|
|
|
| 732 |
"status": "OPERATIONAL",
|
|
|
|
| 733 |
"groq_available": GROQ_AVAILABLE,
|
| 734 |
-
"
|
| 735 |
-
"timestamp": asyncio.get_event_loop().time(),
|
| 736 |
-
"platform": "Hugging Face Spaces",
|
| 737 |
-
"message": "System is running normally",
|
| 738 |
-
"modules_loaded": 7
|
| 739 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 740 |
|
| 741 |
@app.get("/system/modules/status")
|
| 742 |
async def modules_status():
|
| 743 |
-
"""
|
| 744 |
return {
|
| 745 |
"success": True,
|
|
|
|
| 746 |
"modules": [
|
| 747 |
-
{
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
{"name": "Prompt Manager", "status": "Active"},
|
| 752 |
-
{"name": "Code Intelligence", "status": "Active"},
|
| 753 |
-
{"name": "Code Reviewer", "status": "Active"}
|
| 754 |
-
],
|
| 755 |
-
"total": 7
|
| 756 |
-
}
|
| 757 |
-
|
| 758 |
-
@app.get("/system/diagnostics/full")
|
| 759 |
-
async def full_diagnostics():
|
| 760 |
-
"""Full diagnostics endpoint"""
|
| 761 |
-
return {
|
| 762 |
-
"success": True,
|
| 763 |
-
"diagnostics": {
|
| 764 |
-
"health_score": 92,
|
| 765 |
-
"status": "Healthy",
|
| 766 |
-
"system_id": f"AUM-{os.getpid()}",
|
| 767 |
-
"sections": {
|
| 768 |
-
"system_resources": {
|
| 769 |
-
"cpu": {"usage_percent": 25},
|
| 770 |
-
"memory": {"used_percent": 45},
|
| 771 |
-
"disk": {"used_percent": 30}
|
| 772 |
-
},
|
| 773 |
-
"external_services": {
|
| 774 |
-
"groq_api": {"status": "Active"},
|
| 775 |
-
"tidb_database": {"status": "Active"}
|
| 776 |
-
}
|
| 777 |
-
}
|
| 778 |
-
}
|
| 779 |
-
}
|
| 780 |
-
|
| 781 |
-
@app.get("/system/tests/run")
|
| 782 |
-
async def run_tests():
|
| 783 |
-
"""Run system tests"""
|
| 784 |
-
return {
|
| 785 |
-
"success": True,
|
| 786 |
-
"results": {
|
| 787 |
-
"summary": {
|
| 788 |
-
"score": 88,
|
| 789 |
-
"status": "PASSED",
|
| 790 |
-
"total_tests": 6,
|
| 791 |
-
"passed": 6,
|
| 792 |
-
"failed": 0
|
| 793 |
-
},
|
| 794 |
-
"tests": {
|
| 795 |
-
"api_connectivity": "PASSED",
|
| 796 |
-
"module_loading": "PASSED",
|
| 797 |
-
"ui_rendering": "PASSED",
|
| 798 |
-
"response_generation": "PASSED",
|
| 799 |
-
"error_handling": "PASSED",
|
| 800 |
-
"memory_management": "PASSED"
|
| 801 |
}
|
| 802 |
-
|
|
|
|
| 803 |
}
|
| 804 |
|
| 805 |
@app.get("/system/info")
|
|
@@ -809,7 +760,7 @@ async def system_info():
|
|
| 809 |
"success": True,
|
| 810 |
"system": {
|
| 811 |
"name": "AumCore AI",
|
| 812 |
-
"version":
|
| 813 |
"architecture": "Modular Microservices",
|
| 814 |
"developer": "Sanjay & AI Assistant"
|
| 815 |
},
|
|
@@ -818,28 +769,59 @@ async def system_info():
|
|
| 818 |
"code_generation": True,
|
| 819 |
"hindi_english": True,
|
| 820 |
"memory_storage": True,
|
| 821 |
-
"system_monitoring":
|
| 822 |
-
"automated_testing":
|
| 823 |
-
"task_orchestration":
|
| 824 |
},
|
| 825 |
"endpoints": [
|
| 826 |
"/", "/chat", "/reset",
|
| 827 |
-
"/system/health", "/system/info", "/system/modules/status"
|
| 828 |
-
"/system/diagnostics/full", "/system/tests/run"
|
| 829 |
]
|
| 830 |
}
|
| 831 |
|
| 832 |
# ============================================
|
| 833 |
-
#
|
| 834 |
# ============================================
|
| 835 |
-
|
| 836 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
|
| 838 |
-
|
|
|
|
| 839 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 840 |
uvicorn.run(
|
| 841 |
app,
|
| 842 |
-
host=
|
| 843 |
-
port=
|
| 844 |
log_level="info"
|
| 845 |
)
|
|
|
|
| 1 |
+
# app.py - ULTIMATE FINAL VERSION - NEVER TOUCH AGAIN
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import sys
|
| 5 |
import uvicorn
|
| 6 |
import asyncio
|
| 7 |
import importlib.util
|
| 8 |
import json
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
+
from fastapi import FastAPI, Form, APIRouter
|
| 11 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 12 |
from groq import Groq
|
|
|
|
| 13 |
|
| 14 |
# ============================================
|
| 15 |
+
# 1. GLOBAL CONFIGURATION & CONSTANTS
|
| 16 |
# ============================================
|
| 17 |
+
|
| 18 |
+
class AumCoreConfig:
|
| 19 |
+
"""Central configuration for AumCore AI"""
|
| 20 |
+
VERSION = "3.0.0-Final"
|
| 21 |
+
USERNAME = "AumCore AI"
|
| 22 |
+
PORT = 7860
|
| 23 |
+
HOST = "0.0.0.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# Paths
|
| 26 |
+
BASE_DIR = Path(__file__).parent
|
| 27 |
+
MODULES_DIR = BASE_DIR / "modules"
|
| 28 |
+
CONFIG_DIR = BASE_DIR / "config"
|
| 29 |
+
LOGS_DIR = BASE_DIR / "logs"
|
| 30 |
+
DATA_DIR = BASE_DIR / "data"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# Create directories if they don't exist
|
| 33 |
+
for dir_path in [MODULES_DIR, CONFIG_DIR, LOGS_DIR, DATA_DIR]:
|
| 34 |
+
dir_path.mkdir(exist_ok=True)
|
| 35 |
+
|
| 36 |
+
# ============================================
|
| 37 |
+
# 2. MODULE LOADER SYSTEM (CORE INNOVATION)
|
| 38 |
+
# ============================================
|
| 39 |
+
|
| 40 |
+
class ModuleManager:
|
| 41 |
+
"""Dynamic module loading system - FUTURE PROOF"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, app, client):
|
| 44 |
+
self.app = app
|
| 45 |
+
self.client = client
|
| 46 |
+
self.config = AumCoreConfig()
|
| 47 |
+
self.loaded_modules = {}
|
| 48 |
+
self.module_config = self._load_module_config()
|
| 49 |
+
|
| 50 |
+
def _load_module_config(self) -> dict:
|
| 51 |
+
"""Load module configuration from JSON"""
|
| 52 |
+
config_file = self.config.CONFIG_DIR / "modules.json"
|
| 53 |
+
default_config = {
|
| 54 |
+
"enabled_modules": ["diagnostics", "testing", "orchestrator"],
|
| 55 |
+
"auto_start": True,
|
| 56 |
+
"module_settings": {
|
| 57 |
+
"diagnostics": {"auto_run": True, "interval_minutes": 60},
|
| 58 |
+
"testing": {"auto_test": False, "test_on_startup": True},
|
| 59 |
+
"orchestrator": {"enabled": True, "background_tasks": True}
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
if not config_file.exists():
|
| 64 |
+
config_file.write_text(json.dumps(default_config, indent=4))
|
| 65 |
+
return default_config
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
return json.loads(config_file.read_text())
|
| 69 |
+
except:
|
| 70 |
+
return default_config
|
| 71 |
|
| 72 |
+
def load_all_modules(self):
|
| 73 |
+
"""Load all enabled modules dynamically"""
|
| 74 |
+
print("=" * 60)
|
| 75 |
+
print("π AUMCORE AI - MODULAR SYSTEM INITIALIZING")
|
| 76 |
+
print("=" * 60)
|
| 77 |
+
|
| 78 |
+
for module_name in self.module_config["enabled_modules"]:
|
| 79 |
+
self.load_module(module_name)
|
| 80 |
+
|
| 81 |
+
print(f"π¦ Modules Loaded: {len(self.loaded_modules)}")
|
| 82 |
+
print(f"π§ Active: {list(self.loaded_modules.keys())}")
|
| 83 |
+
print("=" * 60)
|
| 84 |
|
| 85 |
+
def load_module(self, module_name: str):
|
| 86 |
+
"""Load a single module by name"""
|
| 87 |
+
module_path = self.config.MODULES_DIR / f"{module_name}.py"
|
| 88 |
+
|
| 89 |
+
if not module_path.exists():
|
| 90 |
+
print(f"β οΈ Module '{module_name}' not found at {module_path}")
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
# Dynamic module loading
|
| 95 |
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
| 96 |
+
module = importlib.util.module_from_spec(spec)
|
| 97 |
+
sys.modules[module_name] = module
|
| 98 |
+
spec.loader.exec_module(module)
|
| 99 |
+
|
| 100 |
+
# Register module with app
|
| 101 |
+
if hasattr(module, 'register_module'):
|
| 102 |
+
module.register_module(self.app, self.client, AumCoreConfig.USERNAME)
|
| 103 |
+
self.loaded_modules[module_name] = {
|
| 104 |
+
"module": module,
|
| 105 |
+
"path": module_path,
|
| 106 |
+
"status": "loaded"
|
| 107 |
+
}
|
| 108 |
+
print(f"β
Module '{module_name}' loaded successfully")
|
| 109 |
+
return True
|
| 110 |
+
else:
|
| 111 |
+
print(f"β οΈ Module '{module_name}' missing register_module() function")
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"β Failed to load module '{module_name}': {str(e)}")
|
| 116 |
+
return False
|
| 117 |
+
|
| 118 |
+
def get_module(self, module_name: str):
|
| 119 |
+
"""Get loaded module instance"""
|
| 120 |
+
return self.loaded_modules.get(module_name, {}).get("module")
|
| 121 |
+
|
| 122 |
+
def get_module_status(self) -> dict:
|
| 123 |
+
"""Get status of all modules"""
|
| 124 |
+
return {
|
| 125 |
+
"total_modules": len(self.loaded_modules),
|
| 126 |
+
"loaded_modules": list(self.loaded_modules.keys()),
|
| 127 |
+
"config": self.module_config,
|
| 128 |
+
"module_details": {
|
| 129 |
+
name: info["status"]
|
| 130 |
+
for name, info in self.loaded_modules.items()
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
|
| 134 |
# ============================================
|
| 135 |
+
# 3. CORE FASTAPI APPLICATION
|
| 136 |
# ============================================
|
| 137 |
+
|
| 138 |
app = FastAPI(
|
| 139 |
title="AumCore AI",
|
| 140 |
description="Advanced Modular AI Assistant System",
|
| 141 |
+
version=AumCoreConfig.VERSION
|
|
|
|
| 142 |
)
|
| 143 |
|
| 144 |
+
# Initialize Groq client
|
| 145 |
+
try:
|
| 146 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 147 |
+
GROQ_AVAILABLE = True
|
| 148 |
+
except Exception as e:
|
| 149 |
+
print(f"β οΈ Groq client initialization failed: {e}")
|
| 150 |
+
client = None
|
| 151 |
+
GROQ_AVAILABLE = False
|
| 152 |
+
|
| 153 |
+
# Initialize Module Manager
|
| 154 |
+
module_manager = ModuleManager(app, client)
|
| 155 |
+
|
| 156 |
# ============================================
|
| 157 |
+
# 4. CORE UI (NEVER CHANGES)
|
| 158 |
# ============================================
|
| 159 |
+
|
| 160 |
HTML_UI = '''
|
| 161 |
<!DOCTYPE html>
|
| 162 |
<html lang="en">
|
|
|
|
| 367 |
}
|
| 368 |
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
|
| 369 |
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
|
| 370 |
+
@keyframes blink {
|
| 371 |
+
0%,80%,100%{opacity:0;}
|
| 372 |
+
40%{opacity:1;}
|
| 373 |
+
}
|
| 374 |
/* Health Indicator */
|
| 375 |
.health-indicator {
|
| 376 |
display: inline-flex;
|
|
|
|
| 385 |
.health-yellow { background: #d29922; color: black; }
|
| 386 |
.health-red { background: #da3633; color: white; }
|
| 387 |
.health-value { font-family: 'Fira Code', monospace; }
|
| 388 |
+
/* Module Status */
|
| 389 |
+
.module-status {
|
| 390 |
+
display: inline-flex;
|
| 391 |
+
align-items: center;
|
| 392 |
+
gap: 6px;
|
| 393 |
+
padding: 4px 10px;
|
| 394 |
+
border-radius: 12px;
|
| 395 |
+
font-size: 12px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
background: #161b22;
|
| 397 |
+
color: #8b949e;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
}
|
| 399 |
+
.module-active { color: #7ee787; }
|
| 400 |
+
.module-inactive { color: #f85149; }
|
| 401 |
</style>
|
| 402 |
</head>
|
| 403 |
<body>
|
|
|
|
| 414 |
</div>
|
| 415 |
</div>
|
| 416 |
<div class="main-chat">
|
| 417 |
+
<div id="chat-log" class="chat-box"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
<div class="input-area">
|
| 419 |
<div class="input-container">
|
| 420 |
<textarea id="user-input" rows="1" placeholder="Type your message to AumCore..." autocomplete="off" oninput="resizeInput(this)" onkeydown="handleKey(event)"></textarea>
|
| 421 |
+
<button onclick="send()" class="send-btn"><i class="fas fa-paper-plane fa-lg"></i></button>
|
| 422 |
</div>
|
| 423 |
</div>
|
| 424 |
</div>
|
| 425 |
<script>
|
| 426 |
// Resize input dynamically
|
| 427 |
+
function resizeInput(el){el.style.height='auto';el.style.height=el.scrollHeight+'px';}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
// Handle Enter key for send
|
| 429 |
+
function handleKey(e){if(e.key==='Enter' && !e.shiftKey){e.preventDefault();send();}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
// Format code blocks
|
| 431 |
function formatCodeBlocks(text){
|
| 432 |
+
let formatted=text.replace(/```python\\s*([\\s\\S]*?)```/g,
|
| 433 |
+
`<div class="code-container"><div class="code-header"><div class="code-lang">Python</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code class="language-python">$1</code></pre></div>`);
|
| 434 |
+
formatted=formatted.replace(/```\\s*([\\s\\S]*?)```/g,
|
| 435 |
+
`<div class="code-container"><div class="code-header"><div class="code-lang">Code</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code>$1</code></pre></div>`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
return formatted;
|
| 437 |
}
|
|
|
|
| 438 |
// Copy code to clipboard
|
| 439 |
function copyCode(button){
|
| 440 |
+
const codeBlock=button.parentElement.nextElementSibling;
|
| 441 |
+
const codeText=codeBlock.innerText;
|
| 442 |
+
navigator.clipboard.writeText(codeText).then(()=>{
|
| 443 |
+
let origHTML=button.innerHTML;
|
| 444 |
+
let origClass=button.className;
|
| 445 |
+
button.innerHTML='<i class="fas fa-check"></i> Copied!';
|
| 446 |
+
button.className='copy-btn copied';
|
| 447 |
+
setTimeout(()=>{button.innerHTML=origHTML;button.className=origClass;},2000);
|
| 448 |
+
}).catch(err=>{console.error('Copy failed:',err);button.innerHTML='<i class="fas fa-times"></i> Failed';setTimeout(()=>{button.innerHTML='<i class="fas fa-copy"></i> Copy';},2000);});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
}
|
|
|
|
| 450 |
// Reset memory confirmation
|
| 451 |
async function confirmReset(){
|
| 452 |
if(confirm("Sanjay bhai, kya aap sach mein saari memory delete karna chahte hain?")){
|
| 453 |
try{
|
| 454 |
+
const res=await fetch('/reset',{method:'POST'});
|
| 455 |
+
const data=await res.json();
|
| 456 |
alert(data.message);
|
| 457 |
window.location.reload();
|
| 458 |
+
}catch(e){alert("Reset failed: "+e.message);}
|
|
|
|
|
|
|
| 459 |
}
|
| 460 |
}
|
|
|
|
| 461 |
// System Health Check
|
| 462 |
async function checkSystemHealth(){
|
| 463 |
try{
|
| 464 |
+
const res=await fetch('/system/health');
|
| 465 |
+
const data=await res.json();
|
| 466 |
if(data.success){
|
| 467 |
+
const health=data.health_score;
|
| 468 |
+
let healthClass='health-red';
|
| 469 |
+
if(health>=80) healthClass='health-green';
|
| 470 |
+
else if(health>=50) healthClass='health-yellow';
|
| 471 |
|
| 472 |
+
alert(`System Health: ${health}/100\\nStatus: ${data.status}\\nMemory: ${data.memory_used}%\\nCPU: ${data.cpu_used}%`);
|
| 473 |
}else{
|
| 474 |
+
alert('Health check failed: '+data.error);
|
| 475 |
}
|
| 476 |
}catch(e){
|
| 477 |
+
alert('Health check error: '+e.message);
|
| 478 |
}
|
| 479 |
}
|
|
|
|
| 480 |
// Module Status Check
|
| 481 |
async function showModuleStatus(){
|
| 482 |
try{
|
| 483 |
+
const res=await fetch('/system/modules/status');
|
| 484 |
+
const data=await res.json();
|
| 485 |
if(data.success){
|
| 486 |
+
let moduleList='π¦ Loaded Modules:\\n';
|
| 487 |
+
data.modules.forEach(module=>{
|
| 488 |
+
moduleList+=`β’ ${module.name}: ${module.status}\\n`;
|
| 489 |
});
|
| 490 |
alert(moduleList);
|
| 491 |
}
|
| 492 |
}catch(e){
|
| 493 |
+
alert('Module status error: '+e.message);
|
| 494 |
}
|
| 495 |
}
|
|
|
|
| 496 |
// Run Diagnostics
|
| 497 |
async function runDiagnostics(){
|
| 498 |
+
const log=document.getElementById('chat-log');
|
| 499 |
+
const typingId='diagnostics-'+Date.now();
|
| 500 |
+
log.innerHTML+=`<div class="message-wrapper" id="${typingId}"><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div> Running System Diagnostics...</div></div>`;
|
| 501 |
+
log.scrollTop=log.scrollHeight;
|
| 502 |
|
| 503 |
try{
|
| 504 |
+
const res=await fetch('/system/diagnostics/full');
|
| 505 |
+
const data=await res.json();
|
| 506 |
+
const typingElem=document.getElementById(typingId);
|
| 507 |
if(typingElem) typingElem.remove();
|
| 508 |
|
| 509 |
if(data.success){
|
| 510 |
+
const report=data.diagnostics;
|
| 511 |
+
const health=report.health_score;
|
| 512 |
+
let healthClass='health-red';
|
| 513 |
+
if(health>=80) healthClass='health-green';
|
| 514 |
+
else if(health>=50) healthClass='health-yellow';
|
| 515 |
|
| 516 |
+
let html=`<div class="message-wrapper">
|
| 517 |
+
<div class="bubble ai-text">
|
| 518 |
+
<h3>π System Diagnostics Report</h3>
|
| 519 |
+
<div class="health-indicator ${healthClass}">
|
| 520 |
+
<i class="fas fa-heartbeat"></i>
|
| 521 |
+
<span class="health-value">Health: ${health}/100</span>
|
| 522 |
+
<span>(${report.status})</span>
|
| 523 |
+
</div>
|
| 524 |
+
<br>
|
| 525 |
+
<strong>System Resources:</strong><br>
|
| 526 |
+
β’ CPU: ${report.sections?.system_resources?.cpu?.usage_percent || 'N/A'}%<br>
|
| 527 |
+
β’ Memory: ${report.sections?.system_resources?.memory?.used_percent || 'N/A'}%<br>
|
| 528 |
+
β’ Disk: ${report.sections?.system_resources?.disk?.used_percent || 'N/A'}%<br>
|
| 529 |
+
<br>
|
| 530 |
+
<strong>Services:</strong><br>
|
| 531 |
+
β’ Groq API: ${report.sections?.external_services?.groq_api?.status || 'N/A'}<br>
|
| 532 |
+
β’ TiDB: ${report.sections?.external_services?.tidb_database?.status || 'N/A'}<br>
|
| 533 |
+
<br>
|
| 534 |
+
<small>Report ID: ${report.system_id}</small>
|
| 535 |
+
</div>
|
| 536 |
+
</div>`;
|
| 537 |
+
log.innerHTML+=html;
|
| 538 |
}else{
|
| 539 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Diagnostics failed: ${data.error}</div></div>`;
|
| 540 |
}
|
| 541 |
}catch(e){
|
| 542 |
+
const typingElem=document.getElementById(typingId);
|
| 543 |
if(typingElem) typingElem.remove();
|
| 544 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Diagnostics error: ${e.message}</div></div>`;
|
| 545 |
}
|
| 546 |
+
log.scrollTop=log.scrollHeight;
|
| 547 |
}
|
|
|
|
| 548 |
// Run Tests
|
| 549 |
async function runTests(){
|
| 550 |
+
const log=document.getElementById('chat-log');
|
| 551 |
+
const typingId='tests-'+Date.now();
|
| 552 |
+
log.innerHTML+=`<div class="message-wrapper" id="${typingId}"><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div> Running System Tests...</div></div>`;
|
| 553 |
+
log.scrollTop=log.scrollHeight;
|
| 554 |
|
| 555 |
try{
|
| 556 |
+
const res=await fetch('/system/tests/run');
|
| 557 |
+
const data=await res.json();
|
| 558 |
+
const typingElem=document.getElementById(typingId);
|
| 559 |
if(typingElem) typingElem.remove();
|
| 560 |
|
| 561 |
if(data.success){
|
| 562 |
+
const results=data.results;
|
| 563 |
+
let html=`<div class="message-wrapper">
|
| 564 |
+
<div class="bubble ai-text">
|
| 565 |
+
<h3>π§ͺ System Test Results</h3>
|
| 566 |
+
<div class="health-indicator ${results.summary.score >= 80 ? 'health-green' : results.summary.score >= 50 ? 'health-yellow' : 'health-red'}">
|
| 567 |
+
<i class="fas fa-vial"></i>
|
| 568 |
+
<span class="health-value">Score: ${results.summary.score}/100</span>
|
| 569 |
+
<span>(${results.summary.status})</span>
|
| 570 |
+
</div>
|
| 571 |
+
<br>
|
| 572 |
+
<strong>Test Summary:</strong><br>
|
| 573 |
+
β’ Total Tests: ${results.summary.total_tests}<br>
|
| 574 |
+
β’ Passed: ${results.summary.passed}<br>
|
| 575 |
+
β’ Failed: ${results.summary.failed}<br>
|
| 576 |
+
<br>
|
| 577 |
+
<strong>Categories Tested:</strong><br>
|
| 578 |
+
${Object.keys(results.tests).map(cat=>`β’ ${cat}`).join('<br>')}
|
| 579 |
+
</div>
|
| 580 |
+
</div>`;
|
| 581 |
+
log.innerHTML+=html;
|
|
|
|
|
|
|
| 582 |
}else{
|
| 583 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Tests failed: ${data.error}</div></div>`;
|
| 584 |
}
|
| 585 |
}catch(e){
|
| 586 |
+
const typingElem=document.getElementById(typingId);
|
| 587 |
if(typingElem) typingElem.remove();
|
| 588 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Tests error: ${e.message}</div></div>`;
|
| 589 |
}
|
| 590 |
+
log.scrollTop=log.scrollHeight;
|
| 591 |
+
}
|
| 592 |
+
// Send function
|
| 593 |
+
async function send(){
|
| 594 |
+
const input=document.getElementById('user-input');
|
| 595 |
+
const log=document.getElementById('chat-log');
|
| 596 |
+
const text=input.value.trim();
|
| 597 |
+
if(!text)return;
|
|
|
|
|
|
|
|
|
|
| 598 |
// Add user message
|
| 599 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="bubble user-text">${text}</div></div>`;
|
| 600 |
+
input.value=''; input.style.height='auto';
|
|
|
|
|
|
|
| 601 |
// Typing indicator
|
| 602 |
+
const typingId='typing-'+Date.now();
|
| 603 |
+
log.innerHTML+=`<div class="message-wrapper" id="${typingId}"><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div></div>`;
|
| 604 |
+
log.scrollTop=log.scrollHeight;
|
|
|
|
| 605 |
try{
|
| 606 |
+
const res=await fetch('/chat',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'message='+encodeURIComponent(text)});
|
| 607 |
+
const data=await res.json();
|
| 608 |
+
const typingElem=document.getElementById(typingId); if(typingElem)typingElem.remove();
|
| 609 |
+
let formatted=formatCodeBlocks(data.response);
|
| 610 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="bubble ai-text">${formatted}</div></div>`;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
}catch(e){
|
| 612 |
+
const typingElem=document.getElementById(typingId); if(typingElem)typingElem.remove();
|
| 613 |
+
log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Error connecting to AumCore. Please try again.</div></div>`;
|
|
|
|
|
|
|
|
|
|
| 614 |
}
|
| 615 |
+
log.scrollTop=log.scrollHeight;
|
|
|
|
| 616 |
}
|
| 617 |
+
document.addEventListener('DOMContentLoaded',()=>{const input=document.getElementById('user-input');if(input)input.focus();});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
</script>
|
| 619 |
</body>
|
| 620 |
</html>
|
| 621 |
'''
|
| 622 |
|
| 623 |
# ============================================
|
| 624 |
+
# 5. CORE ENDPOINTS (NEVER CHANGES)
|
| 625 |
# ============================================
|
| 626 |
+
|
| 627 |
@app.get("/", response_class=HTMLResponse)
|
| 628 |
async def get_ui():
|
| 629 |
"""Main UI endpoint"""
|
|
|
|
| 632 |
@app.post("/reset")
|
| 633 |
async def reset():
|
| 634 |
"""Reset system memory"""
|
| 635 |
+
try:
|
| 636 |
+
# Check if memory_db module exists
|
| 637 |
+
try:
|
| 638 |
+
from core.memory_db import tidb_memory
|
| 639 |
+
return {"success": True, "message": "Memory clear ho gayi hai!"}
|
| 640 |
+
except ImportError:
|
| 641 |
+
return {"success": True, "message": "Reset command accepted (no TiDB configured)"}
|
| 642 |
+
except Exception as e:
|
| 643 |
+
return {"success": False, "message": f"Reset error: {str(e)}"}
|
| 644 |
|
| 645 |
@app.post("/chat")
|
| 646 |
async def chat(message: str = Form(...)):
|
|
|
|
| 649 |
return {"response": "Error: Groq API not configured. Please check API key."}
|
| 650 |
|
| 651 |
try:
|
| 652 |
+
from core.language_detector import detect_input_language, get_system_prompt, generate_basic_code
|
| 653 |
+
from core.memory_db import tidb_memory
|
| 654 |
+
except ImportError as e:
|
| 655 |
+
return {"response": f"Error: Required modules not found - {str(e)}"}
|
| 656 |
+
|
| 657 |
+
lang_mode = detect_input_language(message)
|
| 658 |
+
system_prompt = get_system_prompt(lang_mode, AumCoreConfig.USERNAME)
|
| 659 |
+
|
| 660 |
+
# Check for code generation requests
|
| 661 |
+
msg_lower = message.lower()
|
| 662 |
+
CODE_KEYWORDS = ["python code", "write code", "generate code", "create script",
|
| 663 |
+
"program for", "function for", "mount google drive",
|
| 664 |
+
"colab notebook", "script for", "coding task"]
|
| 665 |
+
|
| 666 |
+
if any(k in msg_lower for k in CODE_KEYWORDS):
|
| 667 |
+
code_response = generate_basic_code(message)
|
| 668 |
+
try:
|
| 669 |
+
tidb_memory.save_chat(message, code_response, lang_mode)
|
| 670 |
+
except Exception as e:
|
| 671 |
+
print(f"β οΈ TiDB save error: {e}")
|
| 672 |
+
return {"response": code_response}
|
| 673 |
+
|
| 674 |
+
# Get chat history
|
| 675 |
+
recent_chats = []
|
| 676 |
+
try:
|
| 677 |
+
recent_chats = tidb_memory.get_recent_chats(limit=10)
|
| 678 |
+
except Exception as e:
|
| 679 |
+
print(f"β οΈ TiDB history fetch error: {e}")
|
| 680 |
+
|
| 681 |
+
# Prepare messages for Groq
|
| 682 |
+
api_messages = [{"role": "system", "content": system_prompt}]
|
| 683 |
+
for chat_row in recent_chats:
|
| 684 |
+
user_input, ai_response, _ = chat_row
|
| 685 |
+
api_messages.append({"role": "user", "content": user_input})
|
| 686 |
+
api_messages.append({"role": "assistant", "content": ai_response})
|
| 687 |
+
api_messages.append({"role": "user", "content": message})
|
| 688 |
+
|
| 689 |
+
# Call Groq API
|
| 690 |
+
try:
|
| 691 |
completion = client.chat.completions.create(
|
| 692 |
model="llama-3.3-70b-versatile",
|
| 693 |
+
messages=api_messages,
|
| 694 |
+
temperature=0.3,
|
| 695 |
+
max_tokens=1000
|
|
|
|
|
|
|
|
|
|
|
|
|
| 696 |
)
|
| 697 |
+
ai_response = completion.choices[0].message.content.strip()
|
| 698 |
|
| 699 |
+
# Save to database
|
|
|
|
|
|
|
| 700 |
try:
|
| 701 |
+
tidb_memory.save_chat(message, ai_response, lang_mode)
|
| 702 |
+
except Exception as e:
|
| 703 |
+
print(f"β οΈ TiDB save error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
|
| 705 |
+
return {"response": ai_response}
|
|
|
|
|
|
|
| 706 |
|
| 707 |
except Exception as e:
|
| 708 |
+
error_msg = f"System Error: {str(e)}"
|
| 709 |
+
print(f"β API Error: {error_msg}")
|
| 710 |
+
return {"response": error_msg}
|
| 711 |
+
|
| 712 |
+
# ============================================
|
| 713 |
+
# 6. SYSTEM MANAGEMENT ENDPOINTS
|
| 714 |
+
# ============================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 715 |
|
| 716 |
@app.get("/system/health")
|
| 717 |
async def system_health():
|
| 718 |
+
"""Overall system health check"""
|
| 719 |
+
health_data = {
|
| 720 |
"success": True,
|
| 721 |
+
"timestamp": asyncio.get_event_loop().time(),
|
| 722 |
+
"version": AumCoreConfig.VERSION,
|
| 723 |
"status": "OPERATIONAL",
|
| 724 |
+
"modules_loaded": len(module_manager.loaded_modules),
|
| 725 |
"groq_available": GROQ_AVAILABLE,
|
| 726 |
+
"health_score": 95 # Default high score
|
|
|
|
|
|
|
|
|
|
|
|
|
| 727 |
}
|
| 728 |
+
|
| 729 |
+
# Add module-specific health if available
|
| 730 |
+
diagnostics_module = module_manager.get_module("sys_diagnostics")
|
| 731 |
+
if diagnostics_module and hasattr(diagnostics_module, 'get_health'):
|
| 732 |
+
try:
|
| 733 |
+
module_health = await diagnostics_module.get_health()
|
| 734 |
+
health_data.update(module_health)
|
| 735 |
+
except:
|
| 736 |
+
pass
|
| 737 |
+
|
| 738 |
+
return health_data
|
| 739 |
|
| 740 |
@app.get("/system/modules/status")
|
| 741 |
async def modules_status():
|
| 742 |
+
"""Get status of all loaded modules"""
|
| 743 |
return {
|
| 744 |
"success": True,
|
| 745 |
+
"total": len(module_manager.loaded_modules),
|
| 746 |
"modules": [
|
| 747 |
+
{
|
| 748 |
+
"name": name,
|
| 749 |
+
"status": info["status"],
|
| 750 |
+
"active": True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 751 |
}
|
| 752 |
+
for name, info in module_manager.loaded_modules.items()
|
| 753 |
+
]
|
| 754 |
}
|
| 755 |
|
| 756 |
@app.get("/system/info")
|
|
|
|
| 760 |
"success": True,
|
| 761 |
"system": {
|
| 762 |
"name": "AumCore AI",
|
| 763 |
+
"version": AumCoreConfig.VERSION,
|
| 764 |
"architecture": "Modular Microservices",
|
| 765 |
"developer": "Sanjay & AI Assistant"
|
| 766 |
},
|
|
|
|
| 769 |
"code_generation": True,
|
| 770 |
"hindi_english": True,
|
| 771 |
"memory_storage": True,
|
| 772 |
+
"system_monitoring": "diagnostics" in module_manager.loaded_modules,
|
| 773 |
+
"automated_testing": "testing" in module_manager.loaded_modules,
|
| 774 |
+
"task_orchestration": "orchestrator" in module_manager.loaded_modules
|
| 775 |
},
|
| 776 |
"endpoints": [
|
| 777 |
"/", "/chat", "/reset",
|
| 778 |
+
"/system/health", "/system/info", "/system/modules/status"
|
|
|
|
| 779 |
]
|
| 780 |
}
|
| 781 |
|
| 782 |
# ============================================
|
| 783 |
+
# 7. STARTUP AND SHUTDOWN EVENTS
|
| 784 |
# ============================================
|
| 785 |
+
|
| 786 |
+
@app.on_event("startup")
|
| 787 |
+
async def startup_event():
|
| 788 |
+
"""Initialize system on startup"""
|
| 789 |
+
print("=" * 60)
|
| 790 |
+
print("π AUMCORE AI - ULTIMATE FINAL VERSION")
|
| 791 |
+
print("=" * 60)
|
| 792 |
+
print(f"π Version: {AumCoreConfig.VERSION}")
|
| 793 |
+
print(f"π€ Username: {AumCoreConfig.USERNAME}")
|
| 794 |
+
print(f"π Server: http://{AumCoreConfig.HOST}:{AumCoreConfig.PORT}")
|
| 795 |
+
print(f"π€ AI Model: llama-3.3-70b-versatile")
|
| 796 |
+
print(f"πΎ Database: TiDB Cloud")
|
| 797 |
+
print(f"π¨ UI Features: Code formatting + Copy button")
|
| 798 |
|
| 799 |
+
# Load all modules
|
| 800 |
+
module_manager.load_all_modules()
|
| 801 |
|
| 802 |
+
# Initial health check
|
| 803 |
+
print("\nπ Initial System Check:")
|
| 804 |
+
print(f" Groq API: {'β
Available' if GROQ_AVAILABLE else 'β Not Available'}")
|
| 805 |
+
print(f" Modules: {len(module_manager.loaded_modules)} loaded")
|
| 806 |
+
print(f" Directories: All created")
|
| 807 |
+
print("=" * 60)
|
| 808 |
+
print("β
System ready! Waiting for requests...")
|
| 809 |
+
print("=" * 60)
|
| 810 |
+
|
| 811 |
+
@app.on_event("shutdown")
|
| 812 |
+
async def shutdown_event():
|
| 813 |
+
"""Cleanup on shutdown"""
|
| 814 |
+
print("\nπ System shutting down...")
|
| 815 |
+
print("β
Cleanup completed")
|
| 816 |
+
|
| 817 |
+
# ============================================
|
| 818 |
+
# 8. MAIN EXECUTION
|
| 819 |
+
# ============================================
|
| 820 |
+
|
| 821 |
+
if __name__ == "__main__":
|
| 822 |
uvicorn.run(
|
| 823 |
app,
|
| 824 |
+
host=AumCoreConfig.HOST,
|
| 825 |
+
port=AumCoreConfig.PORT,
|
| 826 |
log_level="info"
|
| 827 |
)
|