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()


AI Mood-Based Wallpaper Switcher (Windows)

import cv2

import mediapipe as mp

import numpy as np

import ctypes

import os

import time


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

# CONFIGURATION

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

WALLPAPER_DIR = "wallpapers"

DETECTION_INTERVAL = 5   # seconds between wallpaper changes


MOOD_WALLPAPERS = {

    "happy": "happy.jpg",

    "sad": "sad.jpg",

    "angry": "angry.jpg",

    "neutral": "neutral.jpg"

}


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

# Windows Wallpaper Setter

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

def set_wallpaper(image_path):

    ctypes.windll.user32.SystemParametersInfoW(

        20, 0, image_path, 3

    )


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

# Face & Landmark Setup

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

mp_face_mesh = mp.solutions.face_mesh

face_mesh = mp_face_mesh.FaceMesh(refine_landmarks=True)

mp_draw = mp.solutions.drawing_utils


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

# Simple Emotion Detection (Rule-Based)

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

def detect_emotion(landmarks):

    # Mouth & eyebrow points

    mouth_left = landmarks[61]

    mouth_right = landmarks[291]

    mouth_top = landmarks[13]

    mouth_bottom = landmarks[14]


    left_eyebrow = landmarks[70]

    right_eyebrow = landmarks[300]


    mouth_width = abs(mouth_right.x - mouth_left.x)

    mouth_height = abs(mouth_bottom.y - mouth_top.y)

    eyebrow_height = abs(left_eyebrow.y - right_eyebrow.y)


    # Heuristic rules

    if mouth_height > 0.035 and mouth_width > 0.04:

        return "happy"

    elif mouth_height < 0.015:

        return "sad"

    elif eyebrow_height < 0.01:

        return "angry"

    else:

        return "neutral"


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

# MAIN LOOP

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

def main():

    cap = cv2.VideoCapture(0)

    last_change = time.time()

    current_mood = None


    print("🎭 Mood-Based Wallpaper Switcher Started")

    print("Press 'Q' to quit.\n")


    while True:

        ret, frame = cap.read()

        if not ret:

            break


        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        results = face_mesh.process(rgb)


        if results.multi_face_landmarks:

            landmarks = results.multi_face_landmarks[0].landmark

            mood = detect_emotion(landmarks)


            cv2.putText(

                frame,

                f"Mood: {mood}",

                (30, 50),

                cv2.FONT_HERSHEY_SIMPLEX,

                1,

                (0, 255, 0),

                2

            )


            # Change wallpaper only after interval

            if mood != current_mood and time.time() - last_change > DETECTION_INTERVAL:

                wallpaper_path = os.path.join(WALLPAPER_DIR, MOOD_WALLPAPERS[mood])

                if os.path.exists(wallpaper_path):

                    set_wallpaper(os.path.abspath(wallpaper_path))

                    print(f"🖼️ Wallpaper changed → {mood}")

                    current_mood = mood

                    last_change = time.time()


        cv2.imshow("AI Mood Detector", frame)


        if cv2.waitKey(1) & 0xFF == ord("q"):

            break


    cap.release()

    cv2.destroyAllWindows()


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

# RUN

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

if __name__ == "__main__":

    main()


Python Audio Noise Cleaner

import librosa

import numpy as np

import noisereduce as nr

import soundfile as sf

import os


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

# CONFIG

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

NOISE_DURATION = 1.0   # seconds used to estimate noise

OUTPUT_SUFFIX = "_cleaned"


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

# Load audio

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

def load_audio(path):

    audio, sr = librosa.load(path, sr=None, mono=True)

    return audio, sr


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

# Noise reduction

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

def reduce_noise(audio, sr, noise_duration=NOISE_DURATION):

    noise_samples = int(noise_duration * sr)

    noise_clip = audio[:noise_samples]


    reduced = nr.reduce_noise(

        y=audio,

        sr=sr,

        y_noise=noise_clip,

        prop_decrease=1.0

    )

    return reduced


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

# Save cleaned audio

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

def save_audio(original_path, audio, sr):

    base, ext = os.path.splitext(original_path)

    output_path = f"{base}{OUTPUT_SUFFIX}.wav"

    sf.write(output_path, audio, sr)

    return output_path


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

# MAIN

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

if __name__ == "__main__":

    input_path = input("Enter audio file path (.wav/.mp3): ").strip()


    if not os.path.exists(input_path):

        print(" File not found.")

        exit()


    print(" Loading audio...")

    audio, sr = load_audio(input_path)


    print(" Reducing background noise...")

    cleaned_audio = reduce_noise(audio, sr)


    output = save_audio(input_path, cleaned_audio, sr)


    print("\n Noise reduction complete!")

    print(f" Cleaned file saved as: {output}")


Offline Barcode & QR Generator

import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image, ImageTk

import qrcode

from pyzbar.pyzbar import decode

import os


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

# MAIN APP

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

class BarcodeQRApp:

    def __init__(self, root):

        self.root = root

        self.root.title("Offline Barcode & QR Suite")

        self.root.geometry("520x520")


        self.build_ui()


    def build_ui(self):

        tk.Label(self.root, text="Barcode & QR Generator / Reader",

                 font=("Arial", 16, "bold")).pack(pady=10)


        self.text_entry = tk.Entry(self.root, width=45)

        self.text_entry.pack(pady=5)

        self.text_entry.insert(0, "Enter text or URL")


        tk.Button(self.root, text="Generate QR Code",

                  command=self.generate_qr).pack(pady=5)


        tk.Button(self.root, text="Read QR / Barcode from Image",

                  command=self.read_code).pack(pady=5)


        self.image_label = tk.Label(self.root)

        self.image_label.pack(pady=10)


        self.result_label = tk.Label(self.root, text="", wraplength=480)

        self.result_label.pack(pady=10)


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

    # Generate QR

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

    def generate_qr(self):

        text = self.text_entry.get().strip()

        if not text:

            messagebox.showerror("Error", "Enter some text!")

            return


        qr = qrcode.make(text)

        file = filedialog.asksaveasfilename(

            defaultextension=".png",

            filetypes=[("PNG Image", "*.png")]

        )


        if file:

            qr.save(file)

            self.display_image(file)

            messagebox.showinfo("Saved", f"QR saved at:\n{file}")


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

    # Read QR / Barcode

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

    def read_code(self):

        file = filedialog.askopenfilename(

            filetypes=[("Image Files", "*.png *.jpg *.jpeg")]

        )


        if not file:

            return


        img = Image.open(file)

        self.display_image(file)


        decoded = decode(img)

        if not decoded:

            self.result_label.config(text=" No QR or Barcode detected.")

            return


        result_text = ""

        for d in decoded:

            result_text += f"""

Type: {d.type}

Data: {d.data.decode('utf-8')}

---------------------

"""


        self.result_label.config(text=result_text)


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

    # Display image

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

    def display_image(self, path):

        img = Image.open(path)

        img.thumbnail((250, 250))

        self.tk_img = ImageTk.PhotoImage(img)

        self.image_label.config(image=self.tk_img)



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

# RUN

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

if __name__ == "__main__":

    root = tk.Tk()

    app = BarcodeQRApp(root)

    root.mainloop()