AumCoreAI commited on
Commit
82e3567
Β·
verified Β·
1 Parent(s): 3d0d89c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -5
app.py CHANGED
@@ -1,8 +1,9 @@
1
  # app.py - FULL VERBOSE 450+ LINES VERSION
2
  import os
3
  import uvicorn
 
4
  from fastapi import FastAPI, Form
5
- from fastapi.responses import HTMLResponse
6
  from groq import Groq
7
 
8
  # --- CORE INITIALIZATION ---
@@ -12,10 +13,11 @@ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
12
  # Configuration
13
  USERNAME = "AumCore AI"
14
 
15
- # Import System Orchestrator
16
  try:
17
- from system_orchestrator import AumCoreMaster
18
  SYSTEM_ORCHESTRATOR_ENABLED = True
 
19
  orchestrator = None
20
 
21
  # Initialize orchestrator in background
@@ -23,18 +25,29 @@ try:
23
  global orchestrator
24
  orchestrator = AumCoreMaster()
25
  print("πŸš€ System Orchestrator initialized")
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  @app.on_event("startup")
28
  async def startup_event():
29
- import asyncio
30
  if SYSTEM_ORCHESTRATOR_ENABLED:
31
  task = asyncio.create_task(init_orchestrator())
32
- # Don't wait for completion to avoid blocking startup
33
  print("⏳ Orchestrator initialization started...")
34
 
35
  except ImportError as e:
36
  print(f"⚠️ System Orchestrator not available: {e}")
37
  SYSTEM_ORCHESTRATOR_ENABLED = False
 
38
  orchestrator = None
39
 
40
  # HTML UI - VERBOSE, 450+ lines
@@ -249,14 +262,31 @@ body {
249
  .typing-dot:nth-child(2) { animation-delay: 0.2s; }
250
  .typing-dot:nth-child(3) { animation-delay: 0.4s; }
251
  @keyframes blink { 0%,80%,100%{opacity:0;} 40%{opacity:1;} }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  </style>
253
  </head>
254
  <body>
255
  <div class="sidebar">
256
  <button class="nav-item new-chat-btn" onclick="window.location.reload()"><i class="fas fa-plus"></i> New Chat</button>
 
257
  <div class="nav-item"><i class="fas fa-history"></i> History</div>
258
  <div class="mt-auto">
259
  <div class="nav-item reset-btn" onclick="confirmReset()"><i class="fas fa-trash-alt"></i> Reset Memory</div>
 
260
  <div class="nav-item"><i class="fas fa-cog"></i> Settings</div>
261
  </div>
262
  </div>
@@ -305,6 +335,81 @@ async function confirmReset(){
305
  }catch(e){alert("Reset failed: "+e.message);}
306
  }
307
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  // Send function
309
  async function send(){
310
  const input=document.getElementById('user-input');
@@ -427,6 +532,123 @@ async def process_system_task():
427
  except Exception as e:
428
  return {"error": f"Task processing failed: {str(e)}"}
429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  if __name__ == "__main__":
431
  print("="*60)
432
  print("πŸš€ AUMCORE AI - FINAL BUILD STARTING")
@@ -437,5 +659,7 @@ if __name__ == "__main__":
437
  print(f"πŸ’Ύ Database: TiDB Cloud")
438
  print(f"🎨 UI Features: Code formatting + Copy button")
439
  print(f"πŸ”„ System Orchestrator: {'ENABLED' if SYSTEM_ORCHESTRATOR_ENABLED else 'DISABLED'}")
 
 
440
  print("="*60)
441
  uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
 
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 ---
 
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
 
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
 
262
  .typing-dot:nth-child(2) { animation-delay: 0.2s; }
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;
270
+ gap: 8px;
271
+ padding: 6px 12px;
272
+ border-radius: 20px;
273
+ font-size: 14px;
274
+ font-weight: 600;
275
+ }
276
+ .health-green { background: #238636; color: white; }
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>
 
335
  }catch(e){alert("Reset failed: "+e.message);}
336
  }
337
  }
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;
345
+ let healthClass='health-red';
346
+ if(health>=80) healthClass='health-green';
347
+ else if(health>=50) healthClass='health-yellow';
348
+
349
+ alert(`System Health: ${health}/100\\nStatus: ${data.status}\\nMemory: ${data.memory_used}%\\nCPU: ${data.cpu_used}%`);
350
+ }else{
351
+ alert('Health check failed: '+data.error);
352
+ }
353
+ }catch(e){
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();
361
+ 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>`;
362
+ log.scrollTop=log.scrollHeight;
363
+
364
+ try{
365
+ const res=await fetch('/system/diagnostics/full');
366
+ const data=await res.json();
367
+ const typingElem=document.getElementById(typingId);
368
+ if(typingElem) typingElem.remove();
369
+
370
+ if(data.success){
371
+ const report=data.diagnostics;
372
+ const health=report.health_score;
373
+ let healthClass='health-red';
374
+ if(health>=80) healthClass='health-green';
375
+ else if(health>=50) healthClass='health-yellow';
376
+
377
+ let html=`<div class="message-wrapper">
378
+ <div class="bubble ai-text">
379
+ <h3>πŸ“Š System Diagnostics Report</h3>
380
+ <div class="health-indicator ${healthClass}">
381
+ <i class="fas fa-heartbeat"></i>
382
+ <span class="health-value">Health: ${health}/100</span>
383
+ <span>(${report.status})</span>
384
+ </div>
385
+ <br>
386
+ <strong>System Resources:</strong><br>
387
+ β€’ CPU: ${report.sections?.system_resources?.cpu?.usage_percent || 'N/A'}%<br>
388
+ β€’ Memory: ${report.sections?.system_resources?.memory?.used_percent || 'N/A'}%<br>
389
+ β€’ Disk: ${report.sections?.system_resources?.disk?.used_percent || 'N/A'}%<br>
390
+ <br>
391
+ <strong>Services:</strong><br>
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>`;
402
+ log.innerHTML+=html;
403
+ }else{
404
+ log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Diagnostics failed: ${data.error}</div></div>`;
405
+ }
406
+ }catch(e){
407
+ const typingElem=document.getElementById(typingId);
408
+ if(typingElem) typingElem.remove();
409
+ log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Diagnostics error: ${e.message}</div></div>`;
410
+ }
411
+ log.scrollTop=log.scrollHeight;
412
+ }
413
  // Send function
414
  async function send(){
415
  const input=document.getElementById('user-input');
 
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")
 
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")