-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_backend.py
More file actions
797 lines (690 loc) · 29.5 KB
/
Copy pathprocess_backend.py
File metadata and controls
797 lines (690 loc) · 29.5 KB
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
"""
AI-Driven Process Recommendation System — Version 1 (Rule-Based Engine)
Flask backend with psutil process monitoring and deterministic rule engine.
V2 Upgrade Path:
- Replace get_recommendation() body with ML model inference
- extract_features() is already built for feature extraction
- training_data list is populated on every label action
- POST /api/train endpoint is stubbed and ready
"""
from flask import Flask, jsonify, request, Response
from flask_cors import CORS
import psutil
import os
import time
import threading
# V2 addition
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
import numpy as np
import pickle, json
from datetime import datetime
app = Flask(__name__)
CORS(app)
# ─────────────────────────────────────────────
# In-memory state (V1 — no database)
# ─────────────────────────────────────────────
user_labels = {} # { "name_pid": "critical"|"normal"|"expendable" }
training_data = [] # V2: used to train Random Forest classifier
# V2 addition
model = None # RandomForestClassifier instance
label_encoder = None # LabelEncoder for recommendation classes
model_metadata = {} # accuracy, trained_at, sample_count, feature_importances
MODEL_FILE = "process_model.pkl"
METADATA_FILE = "model_metadata.json"
_is_training = False # prevents concurrent auto-train threads
# ─────────────────────────────────────────────
# Background cache for process data
# Prevents slow psutil calls from blocking API responses
# ─────────────────────────────────────────────
_cache = {
"processes": [],
"system_stats": {},
"last_update": 0,
}
_cache_lock = threading.Lock()
_model_lock = threading.Lock() # V2.1 addition
# ---------------------------------------------
# Category detection
# ---------------------------------------------
CATEGORY_KEYWORDS = {
"system": [
"systemd", "init", "kernel", "kthreadd", "sshd", "dbus", "udev",
"svchost", "csrss", "lsass", "services", "smss", "wininit",
"system", "winlogon", "dwm", "explorer", "taskhostw", "conhost",
"runtimebroker", "searchhost", "startmenuexperiencehost",
"shellexperiencehost", "sihost", "fontdrvhost", "ctfmon",
],
"browser": [
"chrome", "firefox", "brave", "edge", "safari", "msedge", "opera",
"chromium", "vivaldi",
],
"media": [
"vlc", "spotify", "mpv", "rhythmbox", "wmplayer", "groove",
"foobar2000", "audacity", "obs", "obs64",
],
"dev_tool": [
"code", "cursor", "pycharm", "idea", "vim", "nvim", "devenv",
"powershell", "cmd", "windowsterminal", "wt", "python", "node",
"git", "java", "dotnet", "msbuild", "vscode",
],
}
CAT_ENCODE = {"system": 0, "browser": 1, "media": 2, "dev_tool": 3, "other": 4}
LABEL_ENCODE = {"critical": 2, "normal": 1, "expendable": 0}
def detect_category(name):
"""Auto-detect process category from its name."""
if not name:
return "other"
name_lower = name.lower().replace(".exe", "").replace(".EXE", "")
for cat, keywords in CATEGORY_KEYWORDS.items():
for kw in keywords:
if kw in name_lower:
return cat
return "other"
# ---------------------------------------------
# V2 Compatibility — Feature Extraction
# ---------------------------------------------
def extract_features(proc):
# V2 addition
cat_map = {"system":0, "browser":1, "media":2, "dev_tool":3, "other":4}
label_map = {"critical":2, "normal":1, "expendable":0}
return [
min(float(proc.get("cpu_percent", 0)), 100.0),
min(float(proc.get("memory_percent", 0)), 100.0),
cat_map.get(proc.get("category", "other"), 4),
int(proc.get("num_threads", 1) or 1),
label_map.get(
user_labels.get(f"{proc.get('name')}_{proc.get('pid')}"),
1
)
]
# ─────────────────────────────────────────────
# Layer 3 — Rule Engine
# CRITICAL: This function is the ONLY thing that
# changes in V2. Signature and return shape are frozen.
# ─────────────────────────────────────────────
def get_recommendation(proc):
# V2 addition: ML model path
if model is not None:
try:
features = np.array([extract_features(proc)])
pred_encoded = model.predict(features)[0]
pred_proba = model.predict_proba(features)[0]
recommendation = label_encoder.inverse_transform([pred_encoded])[0]
confidence = round(float(max(pred_proba)), 3)
top2 = sorted(zip(label_encoder.classes_, pred_proba),
key=lambda x: x[1], reverse=True)[:2]
reason = (f"ML: {top2[0][0]} ({top2[0][1]*100:.0f}%) "
f"vs {top2[1][0]} ({top2[1][1]*100:.0f}%)")
return {"recommendation": recommendation,
"confidence": confidence, "reason": reason}
except Exception as e:
pass # fall through to rule engine if model fails
# V1 rule engine fallback (keep entire V1 logic here, unchanged)
cpu = proc.get("cpu_percent", 0) or 0
mem = proc.get("memory_percent", 0) or 0
cat = proc.get("category", "other")
name = proc.get("name", "")
pid = proc.get("pid", "")
# Resolve user label — check exact key first, then by name prefix
label_key = f"{name}_{pid}"
user_label = user_labels.get(label_key)
if not user_label:
for key, val in user_labels.items():
if key.startswith(f"{name}_"):
user_label = val
break
# Rule 1: User labeled as critical → prioritize
if user_label == "critical":
return {
"recommendation": "prioritize",
"confidence": 0.95,
"reason": "User labeled as critical",
}
# Rule 2: User labeled as expendable → terminate
if user_label == "expendable":
return {
"recommendation": "terminate",
"confidence": 0.90,
"reason": "User labeled as expendable",
}
# Rule 3: System process → prioritize (protected)
if cat == "system":
return {
"recommendation": "prioritize",
"confidence": 0.99,
"reason": "System process — protected",
}
# Rule 4: High resource usage → terminate
if cpu > 70 or mem > 30:
reasons = []
if cpu > 70:
reasons.append(f"High CPU usage ({cpu:.1f}%) exceeds threshold")
if mem > 30:
reasons.append(f"High memory usage ({mem:.1f}%) exceeds threshold")
return {
"recommendation": "terminate",
"confidence": 0.85,
"reason": "; ".join(reasons),
}
# Rule 5: Moderate resource usage → pause
if cpu > 40 or mem > 15:
reasons = []
if cpu > 40:
reasons.append(f"Moderate CPU usage ({cpu:.1f}%)")
if mem > 15:
reasons.append(f"Moderate memory usage ({mem:.1f}%)")
return {
"recommendation": "pause",
"confidence": 0.75,
"reason": "; ".join(reasons),
}
# Rule 6: Light elevated usage → monitor
if cpu > 20 or mem > 8:
reasons = []
if cpu > 20:
reasons.append(f"Elevated CPU usage ({cpu:.1f}%)")
if mem > 8:
reasons.append(f"Elevated memory usage ({mem:.1f}%)")
return {
"recommendation": "monitor",
"confidence": 0.70,
"reason": "; ".join(reasons),
}
# Rule 7: Default → monitor
return {
"recommendation": "monitor",
"confidence": 0.60,
"reason": "Normal resource usage — no action needed",
}
# ─────────────────────────────────────────────
# Layer 1 — Data Collection (background refresh)
# ─────────────────────────────────────────────
def get_cpu_temperature():
"""
Attempt to read CPU temperature via psutil sensors.
Returns a dict with value and source, or None if unavailable.
"""
try:
if not hasattr(psutil, "sensors_temperatures"):
return None
temps = psutil.sensors_temperatures()
if not temps:
return None
# Priority order of sensor keys to check
priority_keys = [
"coretemp", "k10temp", "cpu_thermal",
"acpitz", "zenpower", "it8720"
]
for key in priority_keys:
if key in temps:
entries = temps[key]
# Filter to entries with "Package", "Tdie", or index 0
package = [e for e in entries
if "package" in e.label.lower()
or "tdie" in e.label.lower()
or "cpu" in e.label.lower()]
entry = package[0] if package else entries[0]
return {
"value": round(entry.current, 1),
"high": round(entry.high, 1) if entry.high else None,
"critical": round(entry.critical, 1) if entry.critical else None,
"source": key
}
# Fallback: use first available sensor
for key, entries in temps.items():
if entries:
return {
"value": round(entries[0].current, 1),
"high": round(entries[0].high, 1) if entries[0].high else None,
"critical": round(entries[0].critical, 1) if entries[0].critical else None,
"source": key
}
except Exception as e:
print(f"[Temp] Could not read temperature: {e}")
return None
def get_process_memory_bytes(proc):
"""
Get actual memory usage in bytes for a process.
Returns RSS (Resident Set Size) — physical RAM actually used.
"""
try:
mem_info = proc.memory_info()
return mem_info.rss # bytes, physical RAM in use
except (psutil.NoSuchProcess, psutil.AccessDenied):
return 0
def _refresh_cache():
"""Background worker: refresh process and system data every 2 seconds."""
while True:
try:
# Collect process data
processes = []
for proc in psutil.process_iter(
["pid", "name", "cpu_percent", "memory_percent",
"status", "username", "num_threads"]
):
try:
info = proc.info
proc_dict = {
"pid": info["pid"],
"name": info["name"] or "Unknown",
"cpu_percent": round(info["cpu_percent"] or 0, 1),
"memory_percent": round(info["memory_percent"] or 0, 2),
"status": info["status"],
"username": info["username"] or "N/A",
"num_threads": info["num_threads"] or 0,
"category": detect_category(info["name"] or ""),
"memory_bytes": get_process_memory_bytes(proc),
}
# Apply rule engine
rec = get_recommendation(proc_dict)
proc_dict.update(rec)
# Attach user label if exists
label_key = f"{proc_dict['name']}_{proc_dict['pid']}"
proc_dict["user_label"] = user_labels.get(label_key)
if not proc_dict["user_label"]:
for key, val in user_labels.items():
if key.startswith(f"{proc_dict['name']}_"):
proc_dict["user_label"] = val
break
processes.append(proc_dict)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# Sort by composite score: 60% CPU + 40% Memory (descending)
processes.sort(
key=lambda p: p["cpu_percent"] * 0.6 + p["memory_percent"] * 0.4,
reverse=True,
)
# Collect system stats
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
cpu_per_core = psutil.cpu_percent(percpu=True)
stats = {
"cpu_total": psutil.cpu_percent(),
"cpu_per_core": cpu_per_core,
"cpu_cores": psutil.cpu_count(),
"memory_total_gb": round(mem.total / (1024 ** 3), 2),
"memory_used_gb": round(mem.used / (1024 ** 3), 2),
"memory_percent": mem.percent,
"swap_percent": swap.percent,
"cpu_temperature": get_cpu_temperature(),
}
# Update cache atomically
with _cache_lock:
_cache["processes"] = processes
_cache["system_stats"] = stats
_cache["last_update"] = time.time()
except Exception as e:
print(f"[Cache] Error refreshing: {e}")
time.sleep(2)
def _start_cache_thread():
"""Start the background cache refresh daemon."""
t = threading.Thread(target=_refresh_cache, daemon=True)
t.start()
# ─────────────────────────────────────────────
# Layer 1 — Data Collection Endpoints (serve from cache)
# ─────────────────────────────────────────────
@app.route("/api/processes")
def get_processes():
"""Serve cached process data (refreshed every 2 seconds in background)."""
with _cache_lock:
return jsonify(_cache["processes"])
@app.route("/api/system/stats")
def system_stats():
"""Serve cached system statistics."""
with _cache_lock:
return jsonify(_cache["system_stats"])
@app.route("/api/action", methods=["POST"])
def process_action():
"""Execute an action on a process and its entire process tree."""
data = request.json
pid = data.get("pid")
action = data.get("action")
try:
proc = psutil.Process(pid)
proc_name = proc.name()
# Gather the full process tree (children first, parent last)
try:
children = proc.children(recursive=True)
except (psutil.NoSuchProcess, psutil.AccessDenied):
children = []
if action == "kill":
# Kill children first (bottom-up), then parent
killed = 0
for child in children:
try:
child.terminate()
killed += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
proc.terminate()
killed += 1
# Give processes a moment then force-kill any survivors
_, alive = psutil.wait_procs([proc] + children, timeout=2)
for p in alive:
try:
p.kill() # SIGKILL / force kill
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return jsonify({
"ok": True,
"message": f"Terminated {proc_name} and {killed - 1} child process(es)"
})
elif action == "pause":
# Suspend all children first, then parent
paused = 0
for child in children:
try:
child.suspend()
paused += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
proc.suspend()
paused += 1
return jsonify({
"ok": True,
"message": f"Suspended {proc_name} and {paused - 1} child process(es)"
})
elif action == "resume":
# Resume parent first, then children
resumed = 0
proc.resume()
resumed += 1
for child in children:
try:
child.resume()
resumed += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return jsonify({
"ok": True,
"message": f"Resumed {proc_name} and {resumed - 1} child process(es)"
})
elif action == "prioritize":
# Boost parent and all children
priority = psutil.HIGH_PRIORITY_CLASS if os.name == "nt" else -5
boosted = 0
proc.nice(priority)
boosted += 1
for child in children:
try:
child.nice(priority)
boosted += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return jsonify({
"ok": True,
"message": f"Boosted {proc_name} and {boosted - 1} child process(es)"
})
else:
return jsonify({"ok": False, "message": f"Unknown action: {action}"})
except psutil.NoSuchProcess:
return jsonify({"ok": False, "message": "Process no longer exists"})
except psutil.AccessDenied:
return jsonify({"ok": False, "message": "Access denied — try running as administrator"})
except Exception as e:
return jsonify({"ok": False, "message": str(e)})
@app.route("/api/engine/status")
def engine_status():
# V2 addition
return jsonify({
"engine": "ml_random_forest" if model else "rule_based",
"version": "2.0",
"model_ready": model is not None,
"training_samples": len(training_data),
"labeled_processes": len(user_labels),
"metadata": model_metadata if model_metadata else None
})
# ─────────────────────────────────────────────
# Layer 2 — User Importance Input
# ─────────────────────────────────────────────
@app.route("/api/label", methods=["POST"])
def set_label():
"""
Store a user-assigned importance label for a process.
Also appends to training_data for V2 ML compatibility.
"""
data = request.json
pid = data.get("pid")
name = data.get("name")
label = data.get("label") # "critical" | "normal" | "expendable"
label_key = f"{name}_{pid}"
user_labels[label_key] = label
# V2 addition: Store features alongside label
training_data.append({
"features": extract_features({
"name": data["name"],
"pid": data["pid"],
"cpu_percent": data["cpu"],
"memory_percent": data["memory"],
"category": data["category"],
"num_threads": data["threads"]
}),
"recommendation": derive_recommendation_from_label(data["label"], data["cpu"])
})
# V2.1 addition: Automatic background training
# Guard: only spawn one auto-train thread at a time
if len(training_data) >= 5 and not _is_training:
threading.Thread(target=perform_training, daemon=True).start()
return jsonify({"ok": True, "label_count": len(user_labels)})
# V2.1 addition: Extracted training logic for reuse
def perform_training():
global model, label_encoder, model_metadata, _is_training
_is_training = True
try:
with _model_lock:
if len(training_data) < 5:
return False
X = [row["features"] for row in training_data]
y = [row["recommendation"] for row in training_data]
if len(set(y)) < 2:
return False
le = LabelEncoder()
y_encoded = le.fit_transform(y)
clf = RandomForestClassifier(
n_estimators=100, random_state=42, class_weight="balanced"
)
clf.fit(X, y_encoded)
cv_scores = []
if len(training_data) >= 10:
try:
cv_scores = cross_val_score(clf, X, y_encoded, cv=min(5, len(training_data)//2))
except: pass
model = clf
label_encoder = le
feature_names = ["cpu_percent", "memory_percent", "category", "num_threads", "user_label"]
importances = {name: round(float(imp), 4) for name, imp in zip(feature_names, model.feature_importances_)}
model_metadata = {
"trained_at": datetime.now().isoformat(),
"sample_count": len(training_data),
"label_count": len(user_labels),
"cv_accuracy": round(float(np.mean(cv_scores)), 3) if cv_scores else None,
"cv_std": round(float(np.std(cv_scores)), 3) if cv_scores else None,
"classes": label_encoder.classes_.tolist(),
"feature_importances": importances
}
with open(MODEL_FILE, "wb") as f:
pickle.dump({"model": model, "label_encoder": label_encoder}, f)
with open(METADATA_FILE, "w") as f:
json.dump(model_metadata, f, indent=2)
return True
except Exception as e:
print(f"[Auto-Train] Error: {e}")
return False
finally:
_is_training = False
# V2 addition
def derive_recommendation_from_label(label, cpu):
if label == "critical": return "prioritize"
if label == "expendable": return "terminate" if cpu < 10 else "pause"
return "monitor"
@app.route("/api/labels")
def get_labels():
"""Return all stored user labels."""
return jsonify(user_labels)
# ─────────────────────────────────────────────
# V2 Stubs — ML Training Endpoint
# ─────────────────────────────────────────────
@app.route("/api/train", methods=["POST"])
def train_model():
if len(training_data) < 5:
return jsonify({
"ok": False,
"message": f"Need at least 5 labeled samples. "
f"Have {len(training_data)}.",
"samples": len(training_data)
})
y = [row["recommendation"] for row in training_data]
if len(set(y)) < 2:
return jsonify({
"ok": False,
"message": f"Need at least 2 different recommendation types. "
f"Currently all samples are '{y[0]}'. "
f"Label some processes differently.",
"samples": len(training_data)
})
success = perform_training()
if success:
return jsonify({
"ok": True,
"message": f"Model trained successfully on {len(training_data)} samples.",
"metadata": model_metadata
})
else:
return jsonify({
"ok": False,
"message": "Training failed unexpectedly. Check backend logs.",
"samples": len(training_data)
})
# V2 addition
@app.route("/api/model/insights")
def model_insights():
if model is None:
return jsonify({"ok": False, "message": "Model not trained yet"})
return jsonify({
"ok": True,
"feature_importances": model_metadata.get("feature_importances", {}),
"cv_accuracy": model_metadata.get("cv_accuracy"),
"cv_std": model_metadata.get("cv_std"),
"classes": model_metadata.get("classes", []),
"sample_count": model_metadata.get("sample_count"),
"trained_at": model_metadata.get("trained_at")
})
# ─────────────────────────────────────────────
# Dashboard Serving
# ─────────────────────────────────────────────
@app.route("/")
def serve_dashboard():
"""Serve the React dashboard with JSX embedded inline — no second request needed."""
jsx_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "process_dashboard.jsx"
)
try:
with open(jsx_path, "r", encoding="utf-8") as f:
jsx_code = f.read()
except FileNotFoundError:
jsx_code = "const ProcessDashboard = () => React.createElement('div', null, 'Error: process_dashboard.jsx not found');"
html_head = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Process Manager — AI-Driven Recommendations</title>
<meta name="description" content="AI-driven process recommendation system that monitors CPU and memory usage and suggests actions using a rule-based engine.">
<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: #06060b;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
color: #e2e8f0;
-webkit-font-smoothing: antialiased;
}
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #475569; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
"""
html_tail = """
ReactDOM.createRoot(document.getElementById('root')).render(
React.createElement(ProcessDashboard)
);
</script>
</body>
</html>"""
return Response(html_head + jsx_code + html_tail, mimetype="text/html")
@app.route("/static/process_dashboard.jsx")
def serve_jsx():
"""Serve the React JSX dashboard file for Babel in-browser transpilation."""
jsx_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "process_dashboard.jsx"
)
try:
with open(jsx_path, "r", encoding="utf-8") as f:
return Response(f.read(), mimetype="application/javascript")
except FileNotFoundError:
return Response(
"// process_dashboard.jsx not found",
mimetype="application/javascript",
status=404,
)
# ─────────────────────────────────────────────
# Entry Point
# ─────────────────────────────────────────────
if __name__ == "__main__":
# Warm up psutil CPU measurement (needs a baseline interval)
psutil.cpu_percent(interval=0.1)
for proc in psutil.process_iter(["cpu_percent"]):
try:
proc.cpu_percent()
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
# V2 addition: Load persisted model on startup
def load_persisted_model():
global model, label_encoder, model_metadata
if os.path.exists(MODEL_FILE):
try:
with open(MODEL_FILE, "rb") as f:
data = pickle.load(f)
model = data["model"]
label_encoder = data["label_encoder"]
except Exception as e:
print(f"[Model] Error loading persisted model: {e}")
if os.path.exists(METADATA_FILE):
try:
with open(METADATA_FILE) as f:
model_metadata = json.load(f)
except Exception as e:
print(f"[Metadata] Error loading metadata: {e}")
if model:
print(f" [OK] Loaded persisted model - {model_metadata.get('sample_count')} samples")
load_persisted_model()
# Start background cache thread
_start_cache_thread()
print(" [OK] Background process monitor started")
# Wait for initial cache fill so first request has data
time.sleep(2)
print()
print()
print(" +--------------------------------------------------+")
print(" | AI Process Recommendation Engine v2.0 |")
print(" | Engine: Random Forest Support |")
print(" +--------------------------------------------------+")
print(" | Dashboard: http://localhost:5000 |")
print(" | API Base: http://localhost:5000/api |")
print(" | Processes: http://localhost:5000/api/processes |")
print(" +--------------------------------------------------+")
print()
print()
# use_reloader=False prevents Werkzeug from spawning a child process
# (the child wouldn't have the cache thread running)
app.run(host="0.0.0.0", port=5000, debug=False, threaded=True)