AumCoreAI commited on
Commit
424673d
Β·
verified Β·
1 Parent(s): 8ebe336

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +388 -236
app.py CHANGED
@@ -1,63 +1,164 @@
1
- # app.py - FULL VERBOSE 450+ LINES VERSION
2
  import os
 
3
  import uvicorn
4
  import asyncio
5
- from fastapi import FastAPI, Form
 
 
 
6
  from fastapi.responses import HTMLResponse, JSONResponse
7
  from groq import Groq
8
 
9
- # --- CORE INITIALIZATION ---
10
- app = FastAPI()
11
- client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
12
-
13
- # Configuration
14
- USERNAME = "AumCore AI"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # Import System Orchestrator with Diagnostics
17
- try:
18
- from system_orchestrator import AumCoreMaster, get_system_diagnostics
19
- SYSTEM_ORCHESTRATOR_ENABLED = True
20
- ORCHESTRATOR_WITH_DIAGNOSTICS = True
21
- orchestrator = None
22
 
23
- # Initialize orchestrator in background
24
- async def init_orchestrator():
25
- global orchestrator
26
- orchestrator = AumCoreMaster()
27
- print("πŸš€ System Orchestrator initialized")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # Run initial diagnostics
30
  try:
31
- from system_orchestrator import get_system_diagnostics
32
- diag_result = await get_system_diagnostics()
33
- if diag_result.get("success"):
34
- health = diag_result["diagnostics"].get("health_score", 0)
35
- print(f"πŸ“Š Initial Diagnostics: Health Score {health}/100")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  else:
37
- print(f"⚠️ Diagnostics failed: {diag_result.get('error')}")
 
 
38
  except Exception as e:
39
- print(f"⚠️ Initial diagnostics error: {e}")
 
40
 
41
- @app.on_event("startup")
42
- async def startup_event():
43
- if SYSTEM_ORCHESTRATOR_ENABLED:
44
- task = asyncio.create_task(init_orchestrator())
45
- print("⏳ Orchestrator initialization started...")
46
-
47
- except ImportError as e:
48
- print(f"⚠️ System Orchestrator not available: {e}")
49
- SYSTEM_ORCHESTRATOR_ENABLED = False
50
- ORCHESTRATOR_WITH_DIAGNOSTICS = False
51
- orchestrator = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # HTML UI - VERBOSE, 450+ lines
 
 
54
  HTML_UI = '''
55
  <!DOCTYPE html>
56
  <html lang="en">
57
  <head>
58
  <meta charset="UTF-8">
59
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
60
- <title>AumCore AI - Final Build</title>
61
  <script src="https://cdn.tailwindcss.com"></script>
62
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
63
  <style>
@@ -263,7 +364,7 @@ body {
263
  .typing-dot:nth-child(3) { animation-delay: 0.4s; }
264
  @keyframes blink { 0%,80%,100%{opacity:0;} 40%{opacity:1;} }
265
 
266
- /* Diagnostics Health Indicator */
267
  .health-indicator {
268
  display: inline-flex;
269
  align-items: center;
@@ -277,16 +378,32 @@ body {
277
  .health-yellow { background: #d29922; color: black; }
278
  .health-red { background: #da3633; color: white; }
279
  .health-value { font-family: 'Fira Code', monospace; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  </style>
281
  </head>
282
  <body>
283
  <div class="sidebar">
284
  <button class="nav-item new-chat-btn" onclick="window.location.reload()"><i class="fas fa-plus"></i> New Chat</button>
285
  <div class="nav-item" onclick="checkSystemHealth()"><i class="fas fa-heartbeat"></i> System Health</div>
 
286
  <div class="nav-item"><i class="fas fa-history"></i> History</div>
287
  <div class="mt-auto">
288
  <div class="nav-item reset-btn" onclick="confirmReset()"><i class="fas fa-trash-alt"></i> Reset Memory</div>
289
  <div class="nav-item" onclick="runDiagnostics()"><i class="fas fa-stethoscope"></i> Run Diagnostics</div>
 
290
  <div class="nav-item"><i class="fas fa-cog"></i> Settings</div>
291
  </div>
292
  </div>
@@ -338,7 +455,7 @@ async function confirmReset(){
338
  // System Health Check
339
  async function checkSystemHealth(){
340
  try{
341
- const res=await fetch('/system/diagnostics/summary');
342
  const data=await res.json();
343
  if(data.success){
344
  const health=data.health_score;
@@ -354,7 +471,23 @@ async function checkSystemHealth(){
354
  alert('Health check error: '+e.message);
355
  }
356
  }
357
- // Run Full Diagnostics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  async function runDiagnostics(){
359
  const log=document.getElementById('chat-log');
360
  const typingId='diagnostics-'+Date.now();
@@ -392,10 +525,6 @@ async function runDiagnostics(){
392
  β€’ Groq API: ${report.sections?.external_services?.groq_api?.status || 'N/A'}<br>
393
  β€’ TiDB: ${report.sections?.external_services?.tidb_database?.status || 'N/A'}<br>
394
  <br>
395
- <strong>Logs:</strong><br>
396
- β€’ Recent Errors: ${report.sections?.logs_analysis?.error_count || 0}<br>
397
- β€’ Log Size: ${report.sections?.logs_analysis?.log_file_size_mb || 0} MB<br>
398
- <br>
399
  <small>Report ID: ${report.system_id}</small>
400
  </div>
401
  </div>`;
@@ -410,6 +539,50 @@ async function runDiagnostics(){
410
  }
411
  log.scrollTop=log.scrollHeight;
412
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  // Send function
414
  async function send(){
415
  const input=document.getElementById('user-input');
@@ -441,225 +614,204 @@ document.addEventListener('DOMContentLoaded',()=>{const input=document.getElemen
441
  </html>
442
  '''
443
 
444
- # --- BACKEND ---
 
 
445
  @app.get("/", response_class=HTMLResponse)
446
  async def get_ui():
 
447
  return HTML_UI
448
 
449
  @app.post("/reset")
450
  async def reset():
 
451
  try:
452
- from memory_db import tidb_memory
453
- # Use orchestrator if available for system-wide reset
454
- if SYSTEM_ORCHESTRATOR_ENABLED and orchestrator:
455
- print("πŸ”„ Using System Orchestrator for enhanced reset...")
456
- # Could trigger orchestrator's state management here
457
- return {"message": "Memory clear ho gayi hai!"}
458
  except Exception as e:
459
- return {"message": f"Reset completed with note: {str(e)}"}
460
 
461
  @app.post("/chat")
462
  async def chat(message: str = Form(...)):
463
- from language_detector import detect_input_language, get_system_prompt, generate_basic_code
464
- from memory_db import tidb_memory
465
-
466
- # Use orchestrator for heavy processing if available
467
- if SYSTEM_ORCHESTRATOR_ENABLED and orchestrator:
468
- print(f"πŸ€– Orchestrator available for processing: {message[:50]}...")
469
- # Example: Could offload certain tasks to orchestrator's task processor
470
- # For now, just log that it's available
 
471
 
472
  lang_mode = detect_input_language(message)
473
- system_prompt = get_system_prompt(lang_mode, USERNAME)
474
-
 
475
  msg_lower = message.lower()
 
 
 
476
 
477
- # πŸš€ STRICT CODING ROUTER - AI coding expert mode
478
- # Only specific coding requests go to generate_basic_code()
479
- # LLM ko free-style coding nahi karne dena
480
- STRICT_CODE_KEYWORDS = ["python code","write code","generate code","create script","program for","function for","mount google drive","colab notebook","script for","coding task"]
481
- if any(k in msg_lower for k in STRICT_CODE_KEYWORDS):
482
  code_response = generate_basic_code(message)
483
- try: tidb_memory.save_chat(message, code_response, lang_mode)
484
- except Exception as e: print(f"⚠️ TiDB save error (code): {e}")
 
 
485
  return {"response": code_response}
486
-
487
- recent_chats=[]
488
- try: recent_chats=tidb_memory.get_recent_chats(limit=10)
489
- except Exception as e: print(f"⚠️ TiDB history fetch error: {e}")
490
-
491
- api_messages=[{"role":"system","content":system_prompt}]
 
 
 
 
492
  for chat_row in recent_chats:
493
- user_input, ai_response, _=chat_row
494
- api_messages.append({"role":"user","content":user_input})
495
- api_messages.append({"role":"assistant","content":ai_response})
496
- api_messages.append({"role":"user","content":message})
497
-
 
498
  try:
499
- completion=client.chat.completions.create(model="llama-3.3-70b-versatile",messages=api_messages,temperature=0.3,max_tokens=1000)
500
- ai_response=completion.choices[0].message.content.strip()
501
- try: tidb_memory.save_chat(message, ai_response, lang_mode)
502
- except Exception as e: print(f"⚠️ TiDB save error: {e}")
 
 
 
 
 
 
 
 
 
 
503
  return {"response": ai_response}
 
504
  except Exception as e:
505
- error_msg=f"System Error: {str(e)}"
506
  print(f"❌ API Error: {error_msg}")
507
  return {"response": error_msg}
508
 
509
- # --- SYSTEM ORCHESTRATOR INTEGRATION ENDPOINTS ---
510
- @app.get("/system/status")
511
- async def system_status():
512
- """Check system orchestrator status"""
513
- if SYSTEM_ORCHESTRATOR_ENABLED:
514
- return {
515
- "status": "active" if orchestrator else "initializing",
516
- "enabled": True,
517
- "version": "2.0.1-Stable",
518
- "message": "AumCore System Orchestrator integrated"
519
- }
520
- return {"status": "disabled", "message": "System Orchestrator not available"}
521
-
522
- @app.post("/system/task")
523
- async def process_system_task():
524
- """Endpoint for orchestrator-based task processing"""
525
- if not SYSTEM_ORCHESTRATOR_ENABLED or not orchestrator:
526
- return {"error": "System Orchestrator not available"}
527
 
528
- try:
529
- # Example: Trigger a system task through orchestrator
530
- print("πŸ”„ Processing system task via orchestrator...")
531
- return {"status": "task_queued", "message": "System task processing initiated"}
532
- except Exception as e:
533
- return {"error": f"Task processing failed: {str(e)}"}
534
-
535
- # --- LEVEL 2: SYSTEM DIAGNOSTICS ENDPOINTS ---
536
- @app.get("/system/diagnostics/summary")
537
- async def diagnostics_summary():
538
- """Get system health summary"""
539
- if not SYSTEM_ORCHESTRATOR_ENABLED or not ORCHESTRATOR_WITH_DIAGNOSTICS:
540
- return JSONResponse(
541
- status_code=503,
542
- content={
543
- "success": False,
544
- "error": "Diagnostics not available",
545
- "message": "System orchestrator with diagnostics not enabled"
546
- }
547
- )
548
 
549
- try:
550
- from system_orchestrator import get_system_diagnostics
551
- result = await get_system_diagnostics()
552
-
553
- if result.get("success"):
554
- diag = result["diagnostics"]
555
- return {
556
- "success": True,
557
- "health_score": diag.get("health_score", 0),
558
- "status": diag.get("status", "UNKNOWN"),
559
- "timestamp": diag.get("timestamp"),
560
- "cpu_used": diag.get("sections", {}).get("system_resources", {}).get("cpu", {}).get("usage_percent", 0),
561
- "memory_used": diag.get("sections", {}).get("system_resources", {}).get("memory", {}).get("used_percent", 0),
562
- "disk_used": diag.get("sections", {}).get("system_resources", {}).get("disk", {}).get("used_percent", 0),
563
- "groq_status": diag.get("sections", {}).get("external_services", {}).get("groq_api", {}).get("status", "UNKNOWN"),
564
- "error_count": diag.get("sections", {}).get("logs_analysis", {}).get("error_count", 0),
565
- "system_id": diag.get("system_id", "N/A")
566
- }
567
- else:
568
- return JSONResponse(
569
- status_code=500,
570
- content={
571
- "success": False,
572
- "error": result.get("error", "Unknown diagnostics error"),
573
- "timestamp": result.get("timestamp")
574
- }
575
- )
576
- except Exception as e:
577
- return JSONResponse(
578
- status_code=500,
579
- content={
580
- "success": False,
581
- "error": f"Diagnostics failed: {str(e)}",
582
- "timestamp": datetime.now().isoformat()
583
- }
584
- )
585
 
586
- @app.get("/system/diagnostics/full")
587
- async def diagnostics_full():
588
- """Get complete system diagnostics report"""
589
- if not SYSTEM_ORCHESTRATOR_ENABLED or not ORCHESTRATOR_WITH_DIAGNOSTICS:
590
- return JSONResponse(
591
- status_code=503,
592
- content={
593
- "success": False,
594
- "error": "Diagnostics not available",
595
- "message": "System orchestrator with diagnostics not enabled"
 
596
  }
597
- )
598
-
599
- try:
600
- from system_orchestrator import get_system_diagnostics
601
- result = await get_system_diagnostics()
602
- return result
603
- except Exception as e:
604
- return JSONResponse(
605
- status_code=500,
606
- content={
607
- "success": False,
608
- "error": f"Diagnostics failed: {str(e)}",
609
- "timestamp": datetime.now().isoformat()
610
- }
611
- )
612
 
613
- @app.get("/system/diagnostics/history")
614
- async def diagnostics_history():
615
- """Get diagnostics history (last 10 reports)"""
616
- if not SYSTEM_ORCHESTRATOR_ENABLED or not ORCHESTRATOR_WITH_DIAGNOSTICS:
617
- return JSONResponse(
618
- status_code=503,
619
- content={
620
- "success": False,
621
- "error": "Diagnostics not available"
622
- }
623
- )
624
-
625
- try:
626
- import json
627
- if os.path.exists("data/system_state.json"):
628
- with open("data/system_state.json", "r") as f:
629
- data = json.load(f)
630
- history = data.get("diagnostics_history", [])
631
- return {
632
- "success": True,
633
- "count": len(history),
634
- "history": history,
635
- "latest": history[-1] if history else None
636
- }
637
- return {
638
- "success": True,
639
- "count": 0,
640
- "history": [],
641
- "message": "No diagnostics history found"
642
- }
643
- except Exception as e:
644
- return JSONResponse(
645
- status_code=500,
646
- content={
647
- "success": False,
648
- "error": f"Failed to get history: {str(e)}"
649
- }
650
- )
651
 
652
- if __name__ == "__main__":
653
- print("="*60)
654
- print("πŸš€ AUMCORE AI - FINAL BUILD STARTING")
655
- print("="*60)
656
- print(f"πŸ“ Username: {USERNAME}")
657
- print(f"🌐 Server: http://0.0.0.0:7860")
 
 
 
 
 
 
658
  print(f"πŸ€– AI Model: llama-3.3-70b-versatile")
659
  print(f"πŸ’Ύ Database: TiDB Cloud")
660
  print(f"🎨 UI Features: Code formatting + Copy button")
661
- print(f"πŸ”„ System Orchestrator: {'ENABLED' if SYSTEM_ORCHESTRATOR_ENABLED else 'DISABLED'}")
662
- print(f"πŸ“Š Diagnostics Engine: {'ENABLED' if ORCHESTRATOR_WITH_DIAGNOSTICS else 'DISABLED'}")
663
- print(f"πŸ” New Endpoints: /system/diagnostics/summary, /system/diagnostics/full, /system/diagnostics/history")
664
- print("="*60)
665
- uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - ULTIMATE FINAL VERSION - NEVER TOUCH AGAIN
2
  import os
3
+ import sys
4
  import uvicorn
5
  import asyncio
6
+ import importlib.util
7
+ import json
8
+ from pathlib import Path
9
+ from fastapi import FastAPI, Form, APIRouter
10
  from fastapi.responses import HTMLResponse, JSONResponse
11
  from groq import Groq
12
 
13
+ # ============================================
14
+ # 1. GLOBAL CONFIGURATION & CONSTANTS
15
+ # ============================================
16
+ class AumCoreConfig:
17
+ """Central configuration for AumCore AI"""
18
+ VERSION = "3.0.0-Final"
19
+ USERNAME = "AumCore AI"
20
+ PORT = 7860
21
+ HOST = "0.0.0.0"
22
+
23
+ # Paths
24
+ BASE_DIR = Path(__file__).parent
25
+ MODULES_DIR = BASE_DIR / "modules"
26
+ CONFIG_DIR = BASE_DIR / "config"
27
+ LOGS_DIR = BASE_DIR / "logs"
28
+ DATA_DIR = BASE_DIR / "data"
29
+
30
+ # Create directories if they don't exist
31
+ for dir_path in [MODULES_DIR, CONFIG_DIR, LOGS_DIR, DATA_DIR]:
32
+ dir_path.mkdir(exist_ok=True)
33
 
34
+ # ============================================
35
+ # 2. MODULE LOADER SYSTEM (CORE INNOVATION)
36
+ # ============================================
37
+ class ModuleManager:
38
+ """Dynamic module loading system - FUTURE PROOF"""
 
39
 
40
+ def __init__(self, app, client):
41
+ self.app = app
42
+ self.client = client
43
+ self.config = AumCoreConfig()
44
+ self.loaded_modules = {}
45
+ self.module_config = self._load_module_config()
46
+
47
+ def _load_module_config(self) -> dict:
48
+ """Load module configuration from JSON"""
49
+ config_file = self.config.CONFIG_DIR / "modules.json"
50
+ default_config = {
51
+ "enabled_modules": ["diagnostics", "testing", "orchestrator"],
52
+ "auto_start": True,
53
+ "module_settings": {
54
+ "diagnostics": {"auto_run": True, "interval_minutes": 60},
55
+ "testing": {"auto_test": False, "test_on_startup": True},
56
+ "orchestrator": {"enabled": True, "background_tasks": True}
57
+ }
58
+ }
59
+
60
+ if not config_file.exists():
61
+ config_file.write_text(json.dumps(default_config, indent=4))
62
+ return default_config
63
 
 
64
  try:
65
+ return json.loads(config_file.read_text())
66
+ except:
67
+ return default_config
68
+
69
+ def load_all_modules(self):
70
+ """Load all enabled modules dynamically"""
71
+ print("=" * 60)
72
+ print("πŸš€ AUMCORE AI - MODULAR SYSTEM INITIALIZING")
73
+ print("=" * 60)
74
+
75
+ for module_name in self.module_config["enabled_modules"]:
76
+ self.load_module(module_name)
77
+
78
+ print(f"πŸ“¦ Modules Loaded: {len(self.loaded_modules)}")
79
+ print(f"πŸ”§ Active: {list(self.loaded_modules.keys())}")
80
+ print("=" * 60)
81
+
82
+ def load_module(self, module_name: str):
83
+ """Load a single module by name"""
84
+ module_path = self.config.MODULES_DIR / f"{module_name}.py"
85
+
86
+ if not module_path.exists():
87
+ print(f"⚠️ Module '{module_name}' not found at {module_path}")
88
+ return False
89
+
90
+ try:
91
+ # Dynamic module loading
92
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
93
+ module = importlib.util.module_from_spec(spec)
94
+ sys.modules[module_name] = module
95
+ spec.loader.exec_module(module)
96
+
97
+ # Register module with app
98
+ if hasattr(module, 'register_module'):
99
+ module.register_module(self.app, self.client, AumCoreConfig.USERNAME)
100
+ self.loaded_modules[module_name] = {
101
+ "module": module,
102
+ "path": module_path,
103
+ "status": "loaded"
104
+ }
105
+ print(f"βœ… Module '{module_name}' loaded successfully")
106
+ return True
107
  else:
108
+ print(f"⚠️ Module '{module_name}' missing register_module() function")
109
+ return False
110
+
111
  except Exception as e:
112
+ print(f"❌ Failed to load module '{module_name}': {str(e)}")
113
+ return False
114
 
115
+ def get_module(self, module_name: str):
116
+ """Get loaded module instance"""
117
+ return self.loaded_modules.get(module_name, {}).get("module")
118
+
119
+ def get_module_status(self) -> dict:
120
+ """Get status of all modules"""
121
+ return {
122
+ "total_modules": len(self.loaded_modules),
123
+ "loaded_modules": list(self.loaded_modules.keys()),
124
+ "config": self.module_config,
125
+ "module_details": {
126
+ name: info["status"]
127
+ for name, info in self.loaded_modules.items()
128
+ }
129
+ }
130
+
131
+ # ============================================
132
+ # 3. CORE FASTAPI APPLICATION
133
+ # ============================================
134
+ app = FastAPI(
135
+ title="AumCore AI",
136
+ description="Advanced Modular AI Assistant System",
137
+ version=AumCoreConfig.VERSION
138
+ )
139
+
140
+ # Initialize Groq client
141
+ try:
142
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
143
+ GROQ_AVAILABLE = True
144
+ except Exception as e:
145
+ print(f"⚠️ Groq client initialization failed: {e}")
146
+ client = None
147
+ GROQ_AVAILABLE = False
148
+
149
+ # Initialize Module Manager
150
+ module_manager = ModuleManager(app, client)
151
 
152
+ # ============================================
153
+ # 4. CORE UI (NEVER CHANGES)
154
+ # ============================================
155
  HTML_UI = '''
156
  <!DOCTYPE html>
157
  <html lang="en">
158
  <head>
159
  <meta charset="UTF-8">
160
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
161
+ <title>AumCore AI - Ultimate Version</title>
162
  <script src="https://cdn.tailwindcss.com"></script>
163
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
164
  <style>
 
364
  .typing-dot:nth-child(3) { animation-delay: 0.4s; }
365
  @keyframes blink { 0%,80%,100%{opacity:0;} 40%{opacity:1;} }
366
 
367
+ /* Health Indicator */
368
  .health-indicator {
369
  display: inline-flex;
370
  align-items: center;
 
378
  .health-yellow { background: #d29922; color: black; }
379
  .health-red { background: #da3633; color: white; }
380
  .health-value { font-family: 'Fira Code', monospace; }
381
+
382
+ /* Module Status */
383
+ .module-status {
384
+ display: inline-flex;
385
+ align-items: center;
386
+ gap: 6px;
387
+ padding: 4px 10px;
388
+ border-radius: 12px;
389
+ font-size: 12px;
390
+ background: #161b22;
391
+ color: #8b949e;
392
+ }
393
+ .module-active { color: #7ee787; }
394
+ .module-inactive { color: #f85149; }
395
  </style>
396
  </head>
397
  <body>
398
  <div class="sidebar">
399
  <button class="nav-item new-chat-btn" onclick="window.location.reload()"><i class="fas fa-plus"></i> New Chat</button>
400
  <div class="nav-item" onclick="checkSystemHealth()"><i class="fas fa-heartbeat"></i> System Health</div>
401
+ <div class="nav-item" onclick="showModuleStatus()"><i class="fas fa-cube"></i> Module Status</div>
402
  <div class="nav-item"><i class="fas fa-history"></i> History</div>
403
  <div class="mt-auto">
404
  <div class="nav-item reset-btn" onclick="confirmReset()"><i class="fas fa-trash-alt"></i> Reset Memory</div>
405
  <div class="nav-item" onclick="runDiagnostics()"><i class="fas fa-stethoscope"></i> Run Diagnostics</div>
406
+ <div class="nav-item" onclick="runTests()"><i class="fas fa-vial"></i> Run Tests</div>
407
  <div class="nav-item"><i class="fas fa-cog"></i> Settings</div>
408
  </div>
409
  </div>
 
455
  // System Health Check
456
  async function checkSystemHealth(){
457
  try{
458
+ const res=await fetch('/system/health');
459
  const data=await res.json();
460
  if(data.success){
461
  const health=data.health_score;
 
471
  alert('Health check error: '+e.message);
472
  }
473
  }
474
+ // Module Status Check
475
+ async function showModuleStatus(){
476
+ try{
477
+ const res=await fetch('/system/modules/status');
478
+ const data=await res.json();
479
+ if(data.success){
480
+ let moduleList='πŸ“¦ Loaded Modules:\\n';
481
+ data.modules.forEach(module=>{
482
+ moduleList+=`β€’ ${module.name}: ${module.status}\\n`;
483
+ });
484
+ alert(moduleList);
485
+ }
486
+ }catch(e){
487
+ alert('Module status error: '+e.message);
488
+ }
489
+ }
490
+ // Run Diagnostics
491
  async function runDiagnostics(){
492
  const log=document.getElementById('chat-log');
493
  const typingId='diagnostics-'+Date.now();
 
525
  β€’ Groq API: ${report.sections?.external_services?.groq_api?.status || 'N/A'}<br>
526
  β€’ TiDB: ${report.sections?.external_services?.tidb_database?.status || 'N/A'}<br>
527
  <br>
 
 
 
 
528
  <small>Report ID: ${report.system_id}</small>
529
  </div>
530
  </div>`;
 
539
  }
540
  log.scrollTop=log.scrollHeight;
541
  }
542
+ // Run Tests
543
+ async function runTests(){
544
+ const log=document.getElementById('chat-log');
545
+ const typingId='tests-'+Date.now();
546
+ 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>`;
547
+ log.scrollTop=log.scrollHeight;
548
+
549
+ try{
550
+ const res=await fetch('/system/tests/run');
551
+ const data=await res.json();
552
+ const typingElem=document.getElementById(typingId);
553
+ if(typingElem) typingElem.remove();
554
+
555
+ if(data.success){
556
+ const results=data.results;
557
+ let html=`<div class="message-wrapper">
558
+ <div class="bubble ai-text">
559
+ <h3>πŸ§ͺ System Test Results</h3>
560
+ <div class="health-indicator ${results.summary.score >= 80 ? 'health-green' : results.summary.score >= 50 ? 'health-yellow' : 'health-red'}">
561
+ <i class="fas fa-vial"></i>
562
+ <span class="health-value">Score: ${results.summary.score}/100</span>
563
+ <span>(${results.summary.status})</span>
564
+ </div>
565
+ <br>
566
+ <strong>Test Summary:</strong><br>
567
+ β€’ Total Tests: ${results.summary.total_tests}<br>
568
+ β€’ Passed: ${results.summary.passed}<br>
569
+ β€’ Failed: ${results.summary.failed}<br>
570
+ <br>
571
+ <strong>Categories Tested:</strong><br>
572
+ ${Object.keys(results.tests).map(cat=>`β€’ ${cat}`).join('<br>')}
573
+ </div>
574
+ </div>`;
575
+ log.innerHTML+=html;
576
+ }else{
577
+ log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Tests failed: ${data.error}</div></div>`;
578
+ }
579
+ }catch(e){
580
+ const typingElem=document.getElementById(typingId);
581
+ if(typingElem) typingElem.remove();
582
+ log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Tests error: ${e.message}</div></div>`;
583
+ }
584
+ log.scrollTop=log.scrollHeight;
585
+ }
586
  // Send function
587
  async function send(){
588
  const input=document.getElementById('user-input');
 
614
  </html>
615
  '''
616
 
617
+ # ============================================
618
+ # 5. CORE ENDPOINTS (NEVER CHANGES)
619
+ # ============================================
620
  @app.get("/", response_class=HTMLResponse)
621
  async def get_ui():
622
+ """Main UI endpoint"""
623
  return HTML_UI
624
 
625
  @app.post("/reset")
626
  async def reset():
627
+ """Reset system memory"""
628
  try:
629
+ # Check if memory_db module exists
630
+ try:
631
+ from memory_db import tidb_memory
632
+ return {"success": True, "message": "Memory clear ho gayi hai!"}
633
+ except ImportError:
634
+ return {"success": True, "message": "Reset command accepted (no TiDB configured)"}
635
  except Exception as e:
636
+ return {"success": False, "message": f"Reset error: {str(e)}"}
637
 
638
  @app.post("/chat")
639
  async def chat(message: str = Form(...)):
640
+ """Main chat endpoint"""
641
+ if not GROQ_AVAILABLE:
642
+ return {"response": "Error: Groq API not configured. Please check API key."}
643
+
644
+ try:
645
+ from language_detector import detect_input_language, get_system_prompt, generate_basic_code
646
+ from memory_db import tidb_memory
647
+ except ImportError as e:
648
+ return {"response": f"Error: Required modules not found - {str(e)}"}
649
 
650
  lang_mode = detect_input_language(message)
651
+ system_prompt = get_system_prompt(lang_mode, AumCoreConfig.USERNAME)
652
+
653
+ # Check for code generation requests
654
  msg_lower = message.lower()
655
+ CODE_KEYWORDS = ["python code", "write code", "generate code", "create script",
656
+ "program for", "function for", "mount google drive",
657
+ "colab notebook", "script for", "coding task"]
658
 
659
+ if any(k in msg_lower for k in CODE_KEYWORDS):
 
 
 
 
660
  code_response = generate_basic_code(message)
661
+ try:
662
+ tidb_memory.save_chat(message, code_response, lang_mode)
663
+ except Exception as e:
664
+ print(f"⚠️ TiDB save error: {e}")
665
  return {"response": code_response}
666
+
667
+ # Get chat history
668
+ recent_chats = []
669
+ try:
670
+ recent_chats = tidb_memory.get_recent_chats(limit=10)
671
+ except Exception as e:
672
+ print(f"⚠️ TiDB history fetch error: {e}")
673
+
674
+ # Prepare messages for Groq
675
+ api_messages = [{"role": "system", "content": system_prompt}]
676
  for chat_row in recent_chats:
677
+ user_input, ai_response, _ = chat_row
678
+ api_messages.append({"role": "user", "content": user_input})
679
+ api_messages.append({"role": "assistant", "content": ai_response})
680
+ api_messages.append({"role": "user", "content": message})
681
+
682
+ # Call Groq API
683
  try:
684
+ completion = client.chat.completions.create(
685
+ model="llama-3.3-70b-versatile",
686
+ messages=api_messages,
687
+ temperature=0.3,
688
+ max_tokens=1000
689
+ )
690
+ ai_response = completion.choices[0].message.content.strip()
691
+
692
+ # Save to database
693
+ try:
694
+ tidb_memory.save_chat(message, ai_response, lang_mode)
695
+ except Exception as e:
696
+ print(f"⚠️ TiDB save error: {e}")
697
+
698
  return {"response": ai_response}
699
+
700
  except Exception as e:
701
+ error_msg = f"System Error: {str(e)}"
702
  print(f"❌ API Error: {error_msg}")
703
  return {"response": error_msg}
704
 
705
+ # ============================================
706
+ # 6. SYSTEM MANAGEMENT ENDPOINTS
707
+ # ============================================
708
+ @app.get("/system/health")
709
+ async def system_health():
710
+ """Overall system health check"""
711
+ health_data = {
712
+ "success": True,
713
+ "timestamp": asyncio.get_event_loop().time(),
714
+ "version": AumCoreConfig.VERSION,
715
+ "status": "OPERATIONAL",
716
+ "modules_loaded": len(module_manager.loaded_modules),
717
+ "groq_available": GROQ_AVAILABLE,
718
+ "health_score": 95 # Default high score
719
+ }
 
 
 
720
 
721
+ # Add module-specific health if available
722
+ diagnostics_module = module_manager.get_module("diagnostics")
723
+ if diagnostics_module and hasattr(diagnostics_module, 'get_health'):
724
+ try:
725
+ module_health = await diagnostics_module.get_health()
726
+ health_data.update(module_health)
727
+ except:
728
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
729
 
730
+ return health_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731
 
732
+ @app.get("/system/modules/status")
733
+ async def modules_status():
734
+ """Get status of all loaded modules"""
735
+ return {
736
+ "success": True,
737
+ "total": len(module_manager.loaded_modules),
738
+ "modules": [
739
+ {
740
+ "name": name,
741
+ "status": info["status"],
742
+ "active": True
743
  }
744
+ for name, info in module_manager.loaded_modules.items()
745
+ ]
746
+ }
 
 
 
 
 
 
 
 
 
 
 
 
747
 
748
+ @app.get("/system/info")
749
+ async def system_info():
750
+ """Get complete system information"""
751
+ return {
752
+ "success": True,
753
+ "system": {
754
+ "name": "AumCore AI",
755
+ "version": AumCoreConfig.VERSION,
756
+ "architecture": "Modular Microservices",
757
+ "developer": "Sanjay & AI Assistant"
758
+ },
759
+ "capabilities": {
760
+ "ai_chat": True,
761
+ "code_generation": True,
762
+ "hindi_english": True,
763
+ "memory_storage": True,
764
+ "system_monitoring": "diagnostics" in module_manager.loaded_modules,
765
+ "automated_testing": "testing" in module_manager.loaded_modules,
766
+ "task_orchestration": "orchestrator" in module_manager.loaded_modules
767
+ },
768
+ "endpoints": [
769
+ "/", "/chat", "/reset",
770
+ "/system/health", "/system/info", "/system/modules/status"
771
+ ]
772
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
773
 
774
+ # ============================================
775
+ # 7. STARTUP AND SHUTDOWN EVENTS
776
+ # ============================================
777
+ @app.on_event("startup")
778
+ async def startup_event():
779
+ """Initialize system on startup"""
780
+ print("=" * 60)
781
+ print("πŸš€ AUMCORE AI - ULTIMATE FINAL VERSION")
782
+ print("=" * 60)
783
+ print(f"πŸ“ Version: {AumCoreConfig.VERSION}")
784
+ print(f"πŸ‘€ Username: {AumCoreConfig.USERNAME}")
785
+ print(f"🌐 Server: http://{AumCoreConfig.HOST}:{AumCoreConfig.PORT}")
786
  print(f"πŸ€– AI Model: llama-3.3-70b-versatile")
787
  print(f"πŸ’Ύ Database: TiDB Cloud")
788
  print(f"🎨 UI Features: Code formatting + Copy button")
789
+
790
+ # Load all modules
791
+ module_manager.load_all_modules()
792
+
793
+ # Initial health check
794
+ print("\nπŸ” Initial System Check:")
795
+ print(f" Groq API: {'βœ… Available' if GROQ_AVAILABLE else '❌ Not Available'}")
796
+ print(f" Modules: {len(module_manager.loaded_modules)} loaded")
797
+ print(f" Directories: All created")
798
+ print("=" * 60)
799
+ print("βœ… System ready! Waiting for requests...")
800
+ print("=" * 60)
801
+
802
+ @app.on_event("shutdown")
803
+ async def shutdown_event():
804
+ """Cleanup on shutdown"""
805
+ print("\nπŸ›‘ System shutting down...")
806
+ print("βœ… Cleanup completed")
807
+
808
+ # ============================================
809
+ # 8. MAIN EXECUTION
810
+ # ============================================
811
+ if __name__ == "__main__":
812
+ uvicorn.run(
813
+ app,
814
+ host=AumCoreConfig.HOST,
815
+ port=AumCoreConfig.PORT,
816
+ log_level="info"
817
+ )