Blog Pages

Real-Time CPU Thermal Visualizer

import psutil

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import random


# -----------------------------

# CONFIG

# -----------------------------

GRID_SIZE = 4   # 4x4 grid heat map

UPDATE_INTERVAL = 1000  # milliseconds



# -----------------------------

# Get CPU Temperature

# -----------------------------

def get_cpu_temp():

    temps = psutil.sensors_temperatures()


    # Try common sensor labels

    for name in temps:

        for entry in temps[name]:

            if "cpu" in entry.label.lower() or "package" in entry.label.lower():

                return entry.current


    return None



# -----------------------------

# Generate Heat Map Data

# -----------------------------

def generate_heat_data():

    temp = get_cpu_temp()


    if temp is None:

        # Simulate realistic CPU temperature (for unsupported systems)

        base_temp = random.uniform(40, 70)

    else:

        base_temp = temp


    # Create per-core variation

    heat_map = np.random.normal(loc=base_temp, scale=2.0, size=(GRID_SIZE, GRID_SIZE))


    return heat_map



# -----------------------------

# Visualization Setup

# -----------------------------

fig, ax = plt.subplots()

heat_data = generate_heat_data()


heatmap = ax.imshow(

    heat_data,

    cmap="inferno",

    vmin=30,

    vmax=90

)


cbar = plt.colorbar(heatmap)

cbar.set_label("CPU Temperature (°C)")


ax.set_title("Real-Time CPU Thermal Heat Map")



# -----------------------------

# Animation Update Function

# -----------------------------

def update(frame):

    new_data = generate_heat_data()

    heatmap.set_data(new_data)


    avg_temp = np.mean(new_data)

    ax.set_title(f"Real-Time CPU Thermal Heat Map | Avg Temp: {avg_temp:.2f}°C")


    return [heatmap]



# -----------------------------

# Run Animation

# -----------------------------

ani = animation.FuncAnimation(

    fig,

    update,

    interval=UPDATE_INTERVAL

)


plt.show()


Cognitive Load Tracker

 import time

import threading

import psutil

import pandas as pd

import matplotlib.pyplot as plt

from pynput import keyboard, mouse

import win32gui


# -------------------------------

# GLOBAL METRICS

# -------------------------------

keystrokes = 0

mouse_moves = 0

window_switches = 0


current_window = None

data_log = []


TRACK_DURATION = 120  # seconds (change if needed)

INTERVAL = 5          # log every 5 seconds



# -------------------------------

# Keyboard Listener

# -------------------------------

def on_key_press(key):

    global keystrokes

    keystrokes += 1



# -------------------------------

# Mouse Listener

# -------------------------------

def on_move(x, y):

    global mouse_moves

    mouse_moves += 1



# -------------------------------

# Window Change Detection

# -------------------------------

def track_active_window():

    global current_window, window_switches


    while True:

        try:

            window = win32gui.GetForegroundWindow()

            title = win32gui.GetWindowText(window)


            if current_window and title != current_window:

                window_switches += 1


            current_window = title

        except:

            pass


        time.sleep(1)



# -------------------------------

# Logging Thread

# -------------------------------

def log_metrics():

    global keystrokes, mouse_moves, window_switches


    start_time = time.time()


    while time.time() - start_time < TRACK_DURATION:

        time.sleep(INTERVAL)


        fatigue_score = calculate_fatigue(

            keystrokes, mouse_moves, window_switches

        )


        data_log.append({

            "time": time.time() - start_time,

            "keystrokes": keystrokes,

            "mouse_moves": mouse_moves,

            "window_switches": window_switches,

            "fatigue_score": fatigue_score

        })


        print(f"Logged: KS={keystrokes}, MM={mouse_moves}, WS={window_switches}, Fatigue={fatigue_score:.2f}")


        keystrokes = 0

        mouse_moves = 0

        window_switches = 0


    print("\nTracking Complete.")

    visualize_results()



# -------------------------------

# Fatigue Calculation Logic

# -------------------------------

def calculate_fatigue(ks, mm, ws):

    """

    Heuristic logic:

    - High window switching → distraction

    - Low typing speed → fatigue

    - Erratic mouse movement → overload

    """


    fatigue = 0


    if ks < 20:

        fatigue += 30

    if ws > 5:

        fatigue += 40

    if mm > 500:

        fatigue += 20


    return min(fatigue, 100)



# -------------------------------

# Visualization

# -------------------------------

def visualize_results():

    df = pd.DataFrame(data_log)


    plt.figure(figsize=(10, 5))

    plt.plot(df["time"], df["fatigue_score"], marker="o")

    plt.xlabel("Time (seconds)")

    plt.ylabel("Estimated Cognitive Load")

    plt.title("Cognitive Load Over Time")

    plt.grid(True)

    plt.show()


    df.to_csv("cognitive_load_report.csv", index=False)

    print(" Report saved as cognitive_load_report.csv")



# -------------------------------

# MAIN

# -------------------------------

if __name__ == "__main__":

    print("Cognitive Load Tracker Started")

    print(f"Tracking for {TRACK_DURATION} seconds...\n")


    keyboard_listener = keyboard.Listener(on_press=on_key_press)

    mouse_listener = mouse.Listener(on_move=on_move)


    keyboard_listener.start()

    mouse_listener.start()


    window_thread = threading.Thread(target=track_active_window, daemon=True)

    window_thread.start()


    log_metrics()