Sudoku Solver with Step Explanation

 import copy


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

# Helper Functions

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


def print_board(board):

    for i in range(9):

        row = ""

        for j in range(9):

            row += str(board[i][j]) + " "

            if j % 3 == 2 and j != 8:

                row += "| "

        print(row)

        if i % 3 == 2 and i != 8:

            print("-" * 21)

    print()



def find_empty(board):

    for r in range(9):

        for c in range(9):

            if board[r][c] == 0:

                return r, c

    return None



def is_valid(board, num, row, col):

    # Row

    if num in board[row]:

        return False


    # Column

    for r in range(9):

        if board[r][col] == num:

            return False


    # 3x3 box

    box_row = (row // 3) * 3

    box_col = (col // 3) * 3


    for r in range(box_row, box_row + 3):

        for c in range(box_col, box_col + 3):

            if board[r][c] == num:

                return False


    return True



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

# Constraint Propagation

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


def get_candidates(board, row, col):

    return [num for num in range(1, 10) if is_valid(board, num, row, col)]



def apply_constraint_propagation(board, steps):

    changed = True

    while changed:

        changed = False

        for r in range(9):

            for c in range(9):

                if board[r][c] == 0:

                    candidates = get_candidates(board, r, c)

                    if len(candidates) == 1:

                        board[r][c] = candidates[0]

                        steps.append(

                            f"Naked Single: Placed {candidates[0]} at ({r+1},{c+1})"

                        )

                        changed = True

    return board



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

# Backtracking with Explanation

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


def solve(board, steps):

    board = apply_constraint_propagation(board, steps)


    empty = find_empty(board)

    if not empty:

        return True


    row, col = empty

    candidates = get_candidates(board, row, col)


    for num in candidates:

        steps.append(f"Trying {num} at ({row+1},{col+1})")

        board[row][col] = num


        if solve(board, steps):

            return True


        steps.append(f"Backtracking from ({row+1},{col+1})")

        board[row][col] = 0


    return False



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

# Example Puzzle

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


if __name__ == "__main__":

    puzzle = [

        [5,3,0,0,7,0,0,0,0],

        [6,0,0,1,9,5,0,0,0],

        [0,9,8,0,0,0,0,6,0],

        [8,0,0,0,6,0,0,0,3],

        [4,0,0,8,0,3,0,0,1],

        [7,0,0,0,2,0,0,0,6],

        [0,6,0,0,0,0,2,8,0],

        [0,0,0,4,1,9,0,0,5],

        [0,0,0,0,8,0,0,7,9],

    ]


    print("Initial Puzzle:\n")

    print_board(puzzle)


    steps = []

    board_copy = copy.deepcopy(puzzle)


    if solve(board_copy, steps):

        print("Solved Puzzle:\n")

        print_board(board_copy)


        print("Step-by-Step Explanation:\n")

        for step in steps:

            print(step)

    else:

        print("No solution found.")


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}")