Blog Pages

Algorithm Performance Visualizer

import random

import time

import matplotlib.pyplot as plt


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

# Sorting Algorithms

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


def bubble_sort(arr):

    arr = arr.copy()

    n = len(arr)

    for i in range(n):

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr



def insertion_sort(arr):

    arr = arr.copy()

    for i in range(1, len(arr)):

        key = arr[i]

        j = i - 1

        while j >= 0 and key < arr[j]:

            arr[j + 1] = arr[j]

            j -= 1

        arr[j + 1] = key

    return arr



def merge_sort(arr):

    if len(arr) <= 1:

        return arr


    mid = len(arr) // 2

    left = merge_sort(arr[:mid])

    right = merge_sort(arr[mid:])


    return merge(left, right)



def merge(left, right):

    result = []

    i = j = 0


    while i < len(left) and j < len(right):

        if left[i] < right[j]:

            result.append(left[i])

            i += 1

        else:

            result.append(right[j])

            j += 1


    result.extend(left[i:])

    result.extend(right[j:])

    return result



def quick_sort(arr):

    if len(arr) <= 1:

        return arr

    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]

    middle = [x for x in arr if x == pivot]

    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)



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

# Benchmark Function

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


def measure_time(func, arr):

    start = time.time()

    func(arr)

    end = time.time()

    return end - start



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

# Main Visualization

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


if __name__ == "__main__":

    sizes = [100, 500, 1000, 2000]

    results = {

        "Bubble Sort": [],

        "Insertion Sort": [],

        "Merge Sort": [],

        "Quick Sort": []

    }


    for size in sizes:

        print(f"Testing size: {size}")

        data = [random.randint(1, 10000) for _ in range(size)]


        results["Bubble Sort"].append(measure_time(bubble_sort, data))

        results["Insertion Sort"].append(measure_time(insertion_sort, data))

        results["Merge Sort"].append(measure_time(merge_sort, data))

        results["Quick Sort"].append(measure_time(quick_sort, data))


    # Plot Results

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


    for algo, times in results.items():

        plt.plot(sizes, times, marker='o', label=algo)


    plt.xlabel("Input Size")

    plt.ylabel("Execution Time (seconds)")

    plt.title("Sorting Algorithm Performance Comparison")

    plt.legend()

    plt.grid(True)

    plt.show()

Local File Integrity Monitor

import os

import hashlib

import json

from watchdog.observers import Observer

from watchdog.events import FileSystemEventHandler

import time


HASH_DB = "file_hashes.json"



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

# Hash Function

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

def calculate_hash(file_path):

    sha256 = hashlib.sha256()


    try:

        with open(file_path, "rb") as f:

            while chunk := f.read(4096):

                sha256.update(chunk)

        return sha256.hexdigest()

    except:

        return None



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

# Load & Save Hash Database

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

def load_hash_db():

    if os.path.exists(HASH_DB):

        with open(HASH_DB, "r") as f:

            return json.load(f)

    return {}



def save_hash_db(db):

    with open(HASH_DB, "w") as f:

        json.dump(db, f, indent=4)



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

# Initial Scan

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

def initial_scan(folder_path):

    db = {}


    print(" Performing initial scan...\n")


    for root, dirs, files in os.walk(folder_path):

        for file in files:

            path = os.path.join(root, file)

            file_hash = calculate_hash(path)

            if file_hash:

                db[path] = file_hash


    save_hash_db(db)

    print(" Initial scan complete.")

    return db



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

# Event Handler

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

class IntegrityHandler(FileSystemEventHandler):

    def __init__(self, folder_path):

        self.folder_path = folder_path

        self.hash_db = load_hash_db()


        if not self.hash_db:

            self.hash_db = initial_scan(folder_path)


    def on_modified(self, event):

        if event.is_directory:

            return


        file_path = event.src_path

        new_hash = calculate_hash(file_path)


        if file_path in self.hash_db:

            if self.hash_db[file_path] != new_hash:

                print(f"⚠ ALERT: File modified → {file_path}")

                self.hash_db[file_path] = new_hash

                save_hash_db(self.hash_db)


        else:

            print(f" New file detected → {file_path}")

            self.hash_db[file_path] = new_hash

            save_hash_db(self.hash_db)


    def on_deleted(self, event):

        if event.src_path in self.hash_db:

            print(f" File deleted → {event.src_path}")

            del self.hash_db[event.src_path]

            save_hash_db(self.hash_db)



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

# MAIN

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

if __name__ == "__main__":

    folder = input("Enter folder path to monitor: ").strip()


    if not os.path.isdir(folder):

        print(" Invalid folder path.")

        exit()


    print("\n Monitoring started... (Press Ctrl+C to stop)\n")


    event_handler = IntegrityHandler(folder)

    observer = Observer()

    observer.schedule(event_handler, folder, recursive=True)

    observer.start()


    try:

        while True:

            time.sleep(1)

    except KeyboardInterrupt:

        observer.stop()


    observer.join()

DNA Sequence Pattern Finder

import matplotlib.pyplot as plt


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

# Basic DNA Validation

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

def validate_dna(sequence):

    sequence = sequence.upper()

    valid = set("ATCG")

    return all(base in valid for base in sequence)



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

# GC Content Calculation

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

def gc_content(sequence):

    gc_count = sequence.count("G") + sequence.count("C")

    return (gc_count / len(sequence)) * 100



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

# Motif Finder

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

def find_motif(sequence, motif):

    sequence = sequence.upper()

    motif = motif.upper()

    positions = []


    for i in range(len(sequence) - len(motif) + 1):

        if sequence[i:i+len(motif)] == motif:

            positions.append(i)


    return positions



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

# Mutation Comparison

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

def compare_sequences(seq1, seq2):

    mutations = []


    min_len = min(len(seq1), len(seq2))


    for i in range(min_len):

        if seq1[i] != seq2[i]:

            mutations.append((i, seq1[i], seq2[i]))


    return mutations



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

# GC Content Visualization (Sliding Window)

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

def gc_sliding_window(sequence, window_size=20):

    gc_values = []


    for i in range(len(sequence) - window_size + 1):

        window = sequence[i:i+window_size]

        gc_values.append(gc_content(window))


    return gc_values



def plot_gc_distribution(sequence):

    window_size = 20

    gc_values = gc_sliding_window(sequence, window_size)


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

    plt.plot(gc_values)

    plt.title("GC Content Distribution (Sliding Window)")

    plt.xlabel("Position")

    plt.ylabel("GC %")

    plt.show()



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

# MAIN

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

if __name__ == "__main__":

    dna = input("Enter DNA sequence: ").strip().upper()


    if not validate_dna(dna):

        print("❌ Invalid DNA sequence (Only A, T, C, G allowed)")

        exit()


    print("\n🧬 DNA Analysis Results\n")


    # GC Content

    gc = gc_content(dna)

    print(f"GC Content: {gc:.2f}%")


    # Motif Search

    motif = input("\nEnter motif to search (e.g., ATG): ").strip().upper()

    positions = find_motif(dna, motif)


    if positions:

        print(f"Motif '{motif}' found at positions: {positions}")

    else:

        print(f"Motif '{motif}' not found.")


    # Mutation Comparison

    compare = input("\nCompare with another sequence? (y/n): ").strip().lower()

    if compare == "y":

        dna2 = input("Enter second DNA sequence: ").strip().upper()


        if len(dna) != len(dna2):

            print("⚠ Sequences have different lengths. Comparing minimum length.")


        mutations = compare_sequences(dna, dna2)


        if mutations:

            print("\nMutations found:")

            for pos, base1, base2 in mutations:

                print(f"Position {pos}: {base1} → {base2}")

        else:

            print("No mutations detected.")


    # GC Distribution Plot

    plot = input("\nPlot GC content distribution? (y/n): ").strip().lower()

    if plot == "y":

        plot_gc_distribution(dna)


Color Contrast Accessibility Checker

import tkinter as tk

from tkinter import colorchooser

import math


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

# WCAG Calculation Functions

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


def hex_to_rgb(hex_color):

    hex_color = hex_color.lstrip("#")

    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))



def linearize(value):

    value = value / 255

    if value <= 0.03928:

        return value / 12.92

    else:

        return ((value + 0.055) / 1.055) ** 2.4



def relative_luminance(rgb):

    r, g, b = rgb

    r = linearize(r)

    g = linearize(g)

    b = linearize(b)


    return 0.2126 * r + 0.7152 * g + 0.0722 * b



def contrast_ratio(color1, color2):

    L1 = relative_luminance(color1)

    L2 = relative_luminance(color2)


    lighter = max(L1, L2)

    darker = min(L1, L2)


    return (lighter + 0.05) / (darker + 0.05)



def wcag_result(ratio):

    result = ""


    if ratio >= 7:

        result += "AAA (Normal Text) \n"

    elif ratio >= 4.5:

        result += "AA (Normal Text) \n"

    else:

        result += "Fails AA (Normal Text) \n"


    if ratio >= 4.5:

        result += "AAA (Large Text) \n"

    elif ratio >= 3:

        result += "AA (Large Text) \n"

    else:

        result += "Fails Large Text \n"


    return result



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

# GUI

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


class ContrastChecker:

    def __init__(self, root):

        self.root = root

        self.root.title("WCAG Color Contrast Checker")

        self.root.geometry("500x400")


        self.color1 = "#000000"

        self.color2 = "#FFFFFF"


        self.build_ui()


    def build_ui(self):

        tk.Label(self.root, text="Foreground Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 1",

                  command=self.pick_color1).pack()


        tk.Label(self.root, text="Background Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 2",

                  command=self.pick_color2).pack()


        tk.Button(self.root, text="Check Contrast",

                  command=self.check_contrast).pack(pady=15)


        self.preview = tk.Label(self.root, text="Preview Text",

                                font=("Arial", 16))

        self.preview.pack(pady=10)


        self.result_label = tk.Label(self.root, text="", justify="left")

        self.result_label.pack(pady=10)


    def pick_color1(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color1 = color


    def pick_color2(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color2 = color


    def check_contrast(self):

        rgb1 = hex_to_rgb(self.color1)

        rgb2 = hex_to_rgb(self.color2)


        ratio = contrast_ratio(rgb1, rgb2)


        self.preview.config(

            fg=self.color1,

            bg=self.color2

        )


        result = f"Contrast Ratio: {ratio:.2f}:1\n\n"

        result += wcag_result(ratio)


        self.result_label.config(text=result)



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

# RUN

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


if __name__ == "__main__":

    root = tk.Tk()

    app = ContrastChecker(root)

    root.mainloop()


Project Time Tracker with App Detection

import time

import sqlite3

import psutil

import win32gui

from datetime import datetime


DB_NAME = "time_tracker.db"

CHECK_INTERVAL = 1  # seconds



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

# Database Setup

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

def init_db():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        CREATE TABLE IF NOT EXISTS app_usage (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            app_name TEXT,

            window_title TEXT,

            start_time TEXT,

            end_time TEXT,

            duration REAL

        )

    """)


    conn.commit()

    conn.close()



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

# Get Active Window Info

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

def get_active_window():

    hwnd = win32gui.GetForegroundWindow()

    window_title = win32gui.GetWindowText(hwnd)


    try:

        pid = win32gui.GetWindowThreadProcessId(hwnd)[1]

        process = psutil.Process(pid)

        app_name = process.name()

    except:

        app_name = "Unknown"


    return app_name, window_title



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

# Save Session

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

def save_session(app_name, window_title, start_time, end_time):

    duration = (end_time - start_time).total_seconds()


    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        INSERT INTO app_usage (app_name, window_title, start_time, end_time, duration)

        VALUES (?, ?, ?, ?, ?)

    """, (

        app_name,

        window_title,

        start_time.strftime("%Y-%m-%d %H:%M:%S"),

        end_time.strftime("%Y-%m-%d %H:%M:%S"),

        duration

    ))


    conn.commit()

    conn.close()



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

# Tracking Loop

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

def track_time():

    print("šŸ—‚ Project Time Tracker Started (Press Ctrl+C to stop)\n")


    current_app, current_title = get_active_window()

    start_time = datetime.now()


    try:

        while True:

            time.sleep(CHECK_INTERVAL)

            new_app, new_title = get_active_window()


            if new_app != current_app or new_title != current_title:

                end_time = datetime.now()

                save_session(current_app, current_title, start_time, end_time)


                current_app, current_title = new_app, new_title

                start_time = datetime.now()


    except KeyboardInterrupt:

        print("\nStopping tracker...")

        end_time = datetime.now()

        save_session(current_app, current_title, start_time, end_time)

        print("Session saved.")



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

# Summary Report

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

def show_summary():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        SELECT app_name, SUM(duration)/60 as total_minutes

        FROM app_usage

        GROUP BY app_name

        ORDER BY total_minutes DESC

    """)


    results = cursor.fetchall()

    conn.close()


    print("\n Time Usage Summary (Minutes):\n")

    for app, minutes in results:

        print(f"{app:20} {minutes:.2f} min")



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

# MAIN

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

if __name__ == "__main__":

    init_db()


    print("1. Start Tracking")

    print("2. Show Summary")


    choice = input("Choose option: ").strip()


    if choice == "1":

        track_time()

    elif choice == "2":

        show_summary()

    else:

        print("Invalid choice.")


Smart Log File Analyzer

import re

import pandas as pd

import numpy as np

from sklearn.ensemble import IsolationForest

import matplotlib.pyplot as plt


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

# Log Pattern (Apache Common Log)

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

log_pattern = re.compile(

    r'(?P<ip>\S+) - - \[(?P<time>.*?)\] '

    r'"(?P<method>\S+) (?P<url>\S+) \S+" '

    r'(?P<status>\d+) (?P<size>\d+)'

)


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

# Parse Log File

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

def parse_log(file_path):

    data = []


    with open(file_path, "r", encoding="utf-8", errors="ignore") as f:

        for line in f:

            match = log_pattern.search(line)

            if match:

                data.append(match.groupdict())


    df = pd.DataFrame(data)


    df["status"] = df["status"].astype(int)

    df["size"] = df["size"].astype(int)


    return df



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

# Feature Engineering

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

def extract_features(df):

    ip_counts = df.groupby("ip").size().reset_index(name="request_count")

    status_4xx = df[df["status"].between(400, 499)].groupby("ip").size().reset_index(name="errors")

    status_5xx = df[df["status"].between(500, 599)].groupby("ip").size().reset_index(name="server_errors")


    features = ip_counts.merge(status_4xx, on="ip", how="left")

    features = features.merge(status_5xx, on="ip", how="left")


    features.fillna(0, inplace=True)


    return features



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

# Anomaly Detection

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

def detect_anomalies(features):

    model = IsolationForest(contamination=0.05, random_state=42)


    X = features[["request_count", "errors", "server_errors"]]


    features["anomaly_score"] = model.fit_predict(X)

    features["is_suspicious"] = features["anomaly_score"] == -1


    return features



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

# Visualization

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

def visualize(features):

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


    normal = features[features["is_suspicious"] == False]

    suspicious = features[features["is_suspicious"] == True]


    plt.scatter(normal["request_count"], normal["errors"], label="Normal")

    plt.scatter(suspicious["request_count"], suspicious["errors"], label="Suspicious", marker="x")


    plt.xlabel("Request Count")

    plt.ylabel("4xx Errors")

    plt.legend()

    plt.title("Log Anomaly Detection")

    plt.show()



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

# MAIN

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

if __name__ == "__main__":

    path = input("Enter log file path: ").strip()


    print("Parsing logs...")

    df = parse_log(path)


    print(f"Loaded {len(df)} log entries.")


    features = extract_features(df)


    print("Detecting anomalies...")

    analyzed = detect_anomalies(features)


    suspicious = analyzed[analyzed["is_suspicious"] == True]


    print("\n Suspicious IP Addresses:\n")

    print(suspicious[["ip", "request_count", "errors", "server_errors"]])


    visualize(analyzed)


    analyzed.to_csv("log_analysis_report.csv", index=False)

    print("\n Report saved as log_analysis_report.csv")


Image Perspective Corrector

import cv2

import numpy as np


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

# Order points correctly

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

def order_points(pts):

    rect = np.zeros((4, 2), dtype="float32")


    s = pts.sum(axis=1)

    rect[0] = pts[np.argmin(s)]   # top-left

    rect[2] = pts[np.argmax(s)]   # bottom-right


    diff = np.diff(pts, axis=1)

    rect[1] = pts[np.argmin(diff)]  # top-right

    rect[3] = pts[np.argmax(diff)]  # bottom-left


    return rect



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

# Perspective transform

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

def four_point_transform(image, pts):

    rect = order_points(pts)

    (tl, tr, br, bl) = rect


    widthA = np.linalg.norm(br - bl)

    widthB = np.linalg.norm(tr - tl)

    maxWidth = max(int(widthA), int(widthB))


    heightA = np.linalg.norm(tr - br)

    heightB = np.linalg.norm(tl - bl)

    maxHeight = max(int(heightA), int(heightB))


    dst = np.array([

        [0, 0],

        [maxWidth - 1, 0],

        [maxWidth - 1, maxHeight - 1],

        [0, maxHeight - 1]

    ], dtype="float32")


    M = cv2.getPerspectiveTransform(rect, dst)

    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))


    return warped



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

# Detect document contour

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

def detect_document(image):

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    blurred = cv2.GaussianBlur(gray, (5, 5), 0)


    edged = cv2.Canny(blurred, 75, 200)


    contours, _ = cv2.findContours(

        edged.copy(),

        cv2.RETR_LIST,

        cv2.CHAIN_APPROX_SIMPLE

    )


    contours = sorted(contours, key=cv2.contourArea, reverse=True)


    for contour in contours:

        peri = cv2.arcLength(contour, True)

        approx = cv2.approxPolyDP(contour, 0.02 * peri, True)


        if len(approx) == 4:

            return approx.reshape(4, 2)


    return None



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

# Main

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

if __name__ == "__main__":

    path = input("Enter image path: ").strip()


    image = cv2.imread(path)


    if image is None:

        print(" Could not load image.")

        exit()


    orig = image.copy()

    doc_cnt = detect_document(image)


    if doc_cnt is None:

        print(" Document edges not detected.")

        exit()


    warped = four_point_transform(orig, doc_cnt)


    # Convert to scanned look

    warped_gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

    warped_thresh = cv2.adaptiveThreshold(

        warped_gray, 255,

        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

        cv2.THRESH_BINARY,

        11, 2

    )


    cv2.imshow("Original", orig)

    cv2.imshow("Scanned Output", warped_thresh)


    cv2.imwrite("scanned_output.jpg", warped_thresh)

    print(" Saved as scanned_output.jpg")


    cv2.waitKey(0)

    cv2.destroyAllWindows()


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


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


Music Playlist Deduplicator

import os

import hashlib

import tkinter as tk

from tkinter import ttk, filedialog, messagebox

from tinytag import TinyTag


SUPPORTED_EXT = (".mp3", ".wav", ".flac", ".m4a")



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

# Helpers

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

def file_hash(path, block_size=65536):

    """Compute SHA256 hash of a file."""

    h = hashlib.sha256()

    with open(path, "rb") as f:

        for block in iter(lambda: f.read(block_size), b""):

            h.update(block)

    return h.hexdigest()



def get_metadata(path):

    """Extract audio metadata."""

    try:

        tag = TinyTag.get(path)

        return {

            "title": (tag.title or "").strip().lower(),

            "artist": (tag.artist or "").strip().lower(),

            "duration": round(tag.duration or 0, 1)

        }

    except Exception:

        return {"title": "", "artist": "", "duration": 0}



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

# Main App

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

class MusicDeduplicator:

    def __init__(self, root):

        self.root = root

        self.root.title("Music Playlist Deduplicator")

        self.root.geometry("900x520")


        self.files = []

        self.duplicates = []


        self.build_ui()


    # ---------------- UI ----------------

    def build_ui(self):

        top = ttk.Frame(self.root)

        top.pack(fill="x", padx=10, pady=10)


        ttk.Button(top, text="Select Music Folder", command=self.select_folder).pack(side="left")

        ttk.Button(top, text="Scan for Duplicates", command=self.scan).pack(side="left", padx=10)


        self.status = ttk.Label(top, text="No folder selected")

        self.status.pack(side="left", padx=10)


        self.tree = ttk.Treeview(

            self.root,

            columns=("method", "file1", "file2"),

            show="headings"

        )

        self.tree.heading("method", text="Duplicate Type")

        self.tree.heading("file1", text="Song A")

        self.tree.heading("file2", text="Song B")


        self.tree.column("method", width=140)

        self.tree.column("file1", width=360)

        self.tree.column("file2", width=360)


        self.tree.pack(fill="both", expand=True, padx=10, pady=10)


    # ---------------- Logic ----------------

    def select_folder(self):

        self.folder = filedialog.askdirectory()

        if self.folder:

            self.status.config(text=self.folder)


    def scan(self):

        if not hasattr(self, "folder"):

            messagebox.showerror("Error", "Select a music folder first!")

            return


        self.tree.delete(*self.tree.get_children())

        self.files = []

        self.duplicates = []


        for root, _, files in os.walk(self.folder):

            for f in files:

                if f.lower().endswith(SUPPORTED_EXT):

                    path = os.path.join(root, f)

                    self.files.append(path)


        self.find_duplicates()

        self.display_results()


    def find_duplicates(self):

        # --- 1. Exact file hash duplicates ---

        hash_map = {}

        for path in self.files:

            try:

                h = file_hash(path)

                if h in hash_map:

                    self.duplicates.append(("Exact File", hash_map[h], path))

                else:

                    hash_map[h] = path

            except Exception:

                pass


        # --- 2. Metadata duplicates ---

        meta_map = {}

        for path in self.files:

            meta = get_metadata(path)

            key = (meta["title"], meta["artist"], meta["duration"])


            if key != ("", "", 0):

                if key in meta_map:

                    self.duplicates.append(("Metadata Match", meta_map[key], path))

                else:

                    meta_map[key] = path


    def display_results(self):

        if not self.duplicates:

            messagebox.showinfo("Result", "No duplicate songs found!")

            return


        for method, f1, f2 in self.duplicates:

            self.tree.insert("", "end", values=(method, f1, f2))


        messagebox.showinfo(

            "Result",

            f"Found {len(self.duplicates)} duplicate pairs."

        )



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

# RUN

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

if __name__ == "__main__":

    root = tk.Tk()

    app = MusicDeduplicator(root)

    root.mainloop()


Smart Directory Visualizer

import os

import sys

import tkinter as tk

from tkinter import ttk, filedialog, messagebox

import subprocess

import platform


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

# Utility: Open files/folders with default app

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

def open_path(path):

    try:

        if platform.system() == "Windows":

            os.startfile(path)

        elif platform.system() == "Darwin":

            subprocess.Popen(["open", path])

        else:

            subprocess.Popen(["xdg-open", path])

    except Exception as e:

        messagebox.showerror("Error", f"Cannot open:\n{e}")


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

# Main App

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

class DirectoryVisualizer:

    def __init__(self, root):

        self.root = root

        self.root.title("Smart Directory Visualizer")

        self.root.geometry("800x500")


        self.create_ui()


    def create_ui(self):

        top = ttk.Frame(self.root)

        top.pack(fill="x", padx=10, pady=10)


        ttk.Button(top, text="Select Folder", command=self.choose_folder).pack(side="left")


        self.path_label = ttk.Label(top, text="No folder selected")

        self.path_label.pack(side="left", padx=10)


        # Treeview

        self.tree = ttk.Treeview(self.root)

        self.tree.pack(fill="both", expand=True, padx=10, pady=10)


        self.tree.heading("#0", text="Folder Structure", anchor="w")


        # Scrollbar

        scrollbar = ttk.Scrollbar(self.tree, orient="vertical", command=self.tree.yview)

        self.tree.configure(yscrollcommand=scrollbar.set)

        scrollbar.pack(side="right", fill="y")


        # Events

        self.tree.bind("<<TreeviewOpen>>", self.on_expand)

        self.tree.bind("<Double-1>", self.on_double_click)


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

    # Folder selection

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

    def choose_folder(self):

        folder = filedialog.askdirectory()

        if not folder:

            return


        self.path_label.config(text=folder)

        self.tree.delete(*self.tree.get_children())


        root_node = self.tree.insert("", "end", text=folder, open=False, values=[folder])

        self.tree.set(root_node, "fullpath", folder)

        self.add_dummy(root_node)


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

    # Lazy loading helpers

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

    def add_dummy(self, parent):

        self.tree.insert(parent, "end", text="Loading...")


    def on_expand(self, event):

        node = self.tree.focus()

        self.load_children(node)


    def load_children(self, parent):

        fullpath = self.get_fullpath(parent)


        # Remove dummy

        self.tree.delete(*self.tree.get_children(parent))


        try:

            for name in sorted(os.listdir(fullpath)):

                path = os.path.join(fullpath, name)

                node = self.tree.insert(parent, "end", text=name, open=False)

                self.tree.set(node, "fullpath", path)


                if os.path.isdir(path):

                    self.add_dummy(node)

        except PermissionError:

            pass


    def get_fullpath(self, item):

        parent = self.tree.parent(item)

        if parent:

            return os.path.join(self.get_fullpath(parent), self.tree.item(item, "text"))

        else:

            return self.tree.item(item, "text")


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

    # Open file/folder on double click

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

    def on_double_click(self, event):

        item = self.tree.focus()

        path = self.get_fullpath(item)

        if os.path.exists(path):

            open_path(path)


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

# RUN

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

if __name__ == "__main__":

    root = tk.Tk()

    app = DirectoryVisualizer(root)

    root.mainloop()


Typing Pattern Authentication (Keystroke Biometrics)

import keyboard

import time

import numpy as np

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

from sklearn.metrics import accuracy_score

import pickle


PHRASE = "securetyping"

MODEL_FILE = "keystroke_model.pkl"


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

# Capture keystroke timing

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

def capture_keystrokes(prompt):

    print("\n" + prompt)

    print(f"Type exactly: '{PHRASE}' and press Enter")


    timings = []

    press_times = {}


    def on_press(e):

        if e.name == "enter":

            return

        press_times[e.name] = time.time()


    def on_release(e):

        if e.name == "enter":

            return

        if e.name in press_times:

            dwell = time.time() - press_times[e.name]

            timings.append(dwell)


    keyboard.on_press(on_press)

    keyboard.on_release(on_release)


    typed = input("> ")


    keyboard.unhook_all()


    if typed != PHRASE:

        print(" Incorrect phrase typed.")

        return None


    return timings



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

# Collect training samples

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

def collect_samples(samples=10):

    data = []

    print("\n Training Phase")

    for i in range(samples):

        t = capture_keystrokes(f"Sample {i + 1}/{samples}")

        if t:

            data.append(t)


    min_len = min(len(x) for x in data)

    data = [x[:min_len] for x in data]


    return np.array(data)



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

# Train ML model

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

def train_model(data):

    X = data

    y = np.ones(len(X))  # Legitimate user = 1


    # Add fake impostor data (noise)

    impostor = np.random.uniform(0.05, 0.4, size=X.shape)

    X = np.vstack((X, impostor))

    y = np.hstack((y, np.zeros(len(impostor))))


    X_train, X_test, y_train, y_test = train_test_split(

        X, y, test_size=0.25, random_state=42

    )


    model = LogisticRegression()

    model.fit(X_train, y_train)


    acc = accuracy_score(y_test, model.predict(X_test))

    print(f"\nšŸ“Š Model Accuracy: {acc * 100:.2f}%")


    with open(MODEL_FILE, "wb") as f:

        pickle.dump(model, f)


    print("✅ Model saved.")



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

# Authenticate user

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

def authenticate():

    with open(MODEL_FILE, "rb") as f:

        model = pickle.load(f)


    t = capture_keystrokes("šŸ” Authentication Attempt")

    if not t:

        return


    t = np.array(t).reshape(1, -1)

    prediction = model.predict(t)[0]

    confidence = model.predict_proba(t)[0][1]


    if prediction == 1:

        print(f" Access Granted (Confidence: {confidence:.2f})")

    else:

        print(f" Access Denied (Confidence: {confidence:.2f})")



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

# MAIN

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

if __name__ == "__main__":

    print("""

Keystroke Biometrics Demo

1. Train new user

2. Authenticate

""")


    choice = input("Choose option (1/2): ").strip()


    if choice == "1":

        data = collect_samples(samples=8)

        train_model(data)


    elif choice == "2":

        authenticate()


    else:

        print("Invalid choice.")


PDF Page Comparison Tool

 import fitz  # PyMuPDF

from PIL import Image, ImageChops, ImageDraw

import difflib

import os


OUTPUT_DIR = "pdf_diff_output"

os.makedirs(OUTPUT_DIR, exist_ok=True)


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

# Extract text from a PDF page

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

def extract_text(pdf_path, page_num):

    doc = fitz.open(pdf_path)

    if page_num >= len(doc):

        return ""

    return doc[page_num].get_text()


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

# Render page as image

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

def render_page_image(pdf_path, page_num, zoom=2):

    doc = fitz.open(pdf_path)

    page = doc[page_num]

    mat = fitz.Matrix(zoom, zoom)

    pix = page.get_pixmap(matrix=mat)

    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

    return img


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

# Text Difference

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

def text_diff(text1, text2):

    diff = difflib.unified_diff(

        text1.splitlines(),

        text2.splitlines(),

        lineterm=""

    )

    return "\n".join(diff)


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

# Image Difference (highlight changes)

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

def image_diff(img1, img2):

    diff = ImageChops.difference(img1, img2)

    diff = diff.convert("RGB")


    # Highlight differences in red

    pixels = diff.load()

    for y in range(diff.height):

        for x in range(diff.width):

            r, g, b = pixels[x, y]

            if r + g + b > 50:

                pixels[x, y] = (255, 0, 0)


    return diff


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

# Compare PDFs

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

def compare_pdfs(pdf1, pdf2):

    doc1 = fitz.open(pdf1)

    doc2 = fitz.open(pdf2)


    total_pages = max(len(doc1), len(doc2))


    for page in range(total_pages):

        print(f"šŸ” Comparing page {page + 1}")


        # ----- TEXT COMPARISON -----

        text1 = extract_text(pdf1, page)

        text2 = extract_text(pdf2, page)

        diff_text = text_diff(text1, text2)


        text_output = os.path.join(

            OUTPUT_DIR, f"page_{page + 1}_text_diff.txt"

        )

        with open(text_output, "w", encoding="utf-8") as f:

            f.write(diff_text)


        # ----- IMAGE COMPARISON -----

        try:

            img1 = render_page_image(pdf1, page)

            img2 = render_page_image(pdf2, page)


            diff_img = image_diff(img1, img2)

            img_output = os.path.join(

                OUTPUT_DIR, f"page_{page + 1}_image_diff.png"

            )

            diff_img.save(img_output)


        except Exception as e:

            print(f"⚠️ Image diff skipped for page {page + 1}: {e}")


    print("\n✅ PDF comparison complete.")

    print(f"šŸ“ Results saved in: {OUTPUT_DIR}")


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

# RUN

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

if __name__ == "__main__":

    pdf_a = input("Enter first PDF path: ").strip()

    pdf_b = input("Enter second PDF path: ").strip()


    compare_pdfs(pdf_a, pdf_b)


Smart Screen Recorder with Auto-Pause

import cv2

import numpy as np

import mss

import time

from datetime import datetime


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

# CONFIGURATION

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

FPS = 10

MOTION_THRESHOLD = 50000   # Higher = less sensitive

NO_MOTION_TIME = 2         # seconds to auto pause


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

# Setup screen capture

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

sct = mss.mss()

monitor = sct.monitors[1]   # Primary screen


width = monitor["width"]

height = monitor["height"]


fourcc = cv2.VideoWriter_fourcc(*"XVID")

output_file = f"screen_record_{datetime.now().strftime('%Y%m%d_%H%M%S')}.avi"

out = cv2.VideoWriter(output_file, fourcc, FPS, (width, height))


print("šŸŽ„ Screen recording started...")

print("🟢 Recording will pause automatically when screen is idle.")

print("šŸ”“ Press 'Q' to stop recording.\n")


prev_frame = None

last_motion_time = time.time()

recording = True


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

# Recording Loop

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

while True:

    img = np.array(sct.grab(monitor))

    frame = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    gray = cv2.GaussianBlur(gray, (21, 21), 0)


    if prev_frame is None:

        prev_frame = gray

        continue


    # Frame difference

    frame_diff = cv2.absdiff(prev_frame, gray)

    thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)[1]

    motion_score = np.sum(thresh)


    if motion_score > MOTION_THRESHOLD:

        last_motion_time = time.time()

        recording = True

    else:

        if time.time() - last_motion_time > NO_MOTION_TIME:

            recording = False


    # Write frame only if motion exists

    if recording:

        out.write(frame)

        status_text = "RECORDING"

        color = (0, 255, 0)

    else:

        status_text = "PAUSED (No Motion)"

        color = (0, 0, 255)


    # Overlay status

    cv2.putText(

        frame,

        status_text,

        (20, 40),

        cv2.FONT_HERSHEY_SIMPLEX,

        1,

        color,

        2

    )


    cv2.imshow("Smart Screen Recorder", frame)

    prev_frame = gray


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

        break


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

# Cleanup

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

out.release()

cv2.destroyAllWindows()


print(f"\n✅ Recording saved as: {output_file}")


Daily Habit Forecasting Using Time-Series

import pandas as pd

import matplotlib.pyplot as plt

from statsmodels.tsa.holtwinters import ExponentialSmoothing


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

# Load & Prepare Data

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

def load_habit_data(csv_path, habit_name):

    df = pd.read_csv(csv_path)

    df["date"] = pd.to_datetime(df["date"])


    habit_df = df[df["habit"] == habit_name]

    habit_df = habit_df.sort_values("date")


    habit_df.set_index("date", inplace=True)

    ts = habit_df["completed"]


    return ts


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

# Forecast Habit Completion

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

def forecast_habit(ts, days=7):

    model = ExponentialSmoothing(

        ts,

        trend="add",

        seasonal=None,

        initialization_method="estimated"

    )


    fitted_model = model.fit()

    forecast = fitted_model.forecast(days)


    return fitted_model, forecast


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

# Risk Analysis

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

def habit_risk_score(forecast):

    avg_completion = forecast.mean()


    if avg_completion < 0.4:

        return "🚨 High Risk (likely to break)"

    elif avg_completion < 0.7:

        return "⚠️ Medium Risk"

    else:

        return "✅ Low Risk (stable habit)"


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

# Visualization

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

def plot_forecast(ts, forecast, habit_name):

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


    plt.plot(ts.index, ts.values, label="Past Completion", marker="o")

    plt.plot(forecast.index, forecast.values, label="Forecast", linestyle="--", marker="x")


    plt.ylim(-0.1, 1.1)

    plt.ylabel("Habit Completed (1=yes, 0=no)")

    plt.title(f"Habit Forecast: {habit_name}")

    plt.legend()

    plt.grid(True)


    plt.show()


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

# MAIN

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

if __name__ == "__main__":

    csv_file = input("Enter CSV file path: ").strip()

    habit = input("Enter habit name (case-sensitive): ").strip()


    ts = load_habit_data(csv_file, habit)


    model, forecast = forecast_habit(ts, days=7)


    risk = habit_risk_score(forecast)


    print("\nšŸ“Š HABIT FORECAST REPORT")

    print("------------------------")

    print(f"Habit: {habit}")

    print(f"Next 7-day average completion: {forecast.mean():.2f}")

    print(f"Risk Level: {risk}")


    plot_forecast(ts, forecast, habit)


Local Password Strength Analyzer

import tkinter as tk

from tkinter import ttk

import math

import re


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

# Heuristics & helpers

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


COMMON_PASSWORDS = {

    "password", "123456", "123456789", "qwerty", "abc123",

    "letmein", "welcome", "admin", "iloveyou", "monkey"

}


SEQUENCES = [

    "abcdefghijklmnopqrstuvwxyz",

    "ABCDEFGHIJKLMNOPQRSTUVWXYZ",

    "0123456789",

    "qwertyuiop", "asdfghjkl", "zxcvbnm"

]


def shannon_entropy(password: str) -> float:

    """Approximate entropy based on character sets used."""

    pool = 0

    if re.search(r"[a-z]", password): pool += 26

    if re.search(r"[A-Z]", password): pool += 26

    if re.search(r"\d", password):    pool += 10

    if re.search(r"[^\w\s]", password): pool += 32  # symbols

    if pool == 0:

        return 0.0

    return len(password) * math.log2(pool)


def has_repeats(password: str) -> bool:

    return bool(re.search(r"(.)\1{2,}", password))  # aaa, 111


def has_sequence(password: str) -> bool:

    p = password

    for seq in SEQUENCES:

        for i in range(len(seq) - 3):

            if seq[i:i+4] in p:

                return True

    return False


def keyboard_walk(password: str) -> bool:

    walks = ["qwerty", "asdf", "zxcv", "poiuy", "lkjhg", "mnbv"]

    p = password.lower()

    return any(w in p for w in walks)


def analyze_password(password: str):

    issues = []

    score = 0


    # Length

    if len(password) < 8:

        issues.append("Too short (minimum 8 characters).")

    else:

        score += min(20, (len(password) - 7) * 3)


    # Character classes

    classes = 0

    classes += bool(re.search(r"[a-z]", password))

    classes += bool(re.search(r"[A-Z]", password))

    classes += bool(re.search(r"\d", password))

    classes += bool(re.search(r"[^\w\s]", password))

    score += classes * 10


    if classes < 3:

        issues.append("Use at least 3 character types (upper/lower/digits/symbols).")


    # Entropy

    ent = shannon_entropy(password)

    score += min(30, int(ent / 3))  # cap contribution


    if ent < 40:

        issues.append("Low entropy. Add length and variety.")


    # Patterns

    if password.lower() in COMMON_PASSWORDS:

        issues.append("Common password detected.")

        score -= 30


    if has_repeats(password):

        issues.append("Repeated characters detected (e.g., 'aaa').")

        score -= 10


    if has_sequence(password):

        issues.append("Sequential pattern detected (e.g., 'abcd', '1234').")

        score -= 10


    if keyboard_walk(password):

        issues.append("Keyboard pattern detected (e.g., 'qwerty').")

        score -= 10


    score = max(0, min(100, score))


    if score >= 80:

        verdict = "Strong"

    elif score >= 60:

        verdict = "Good"

    elif score >= 40:

        verdict = "Weak"

    else:

        verdict = "Very Weak"


    return {

        "score": score,

        "verdict": verdict,

        "entropy": round(ent, 1),

        "issues": issues

    }


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

# GUI

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


class App(tk.Tk):

    def __init__(self):

        super().__init__()

        self.title("Local Password Strength Analyzer")

        self.geometry("520x420")

        self.resizable(False, False)


        ttk.Label(self, text="Enter Password:", font=("Arial", 12)).pack(pady=10)

        self.pw = ttk.Entry(self, show="*", width=40)

        self.pw.pack()


        self.show_var = tk.BooleanVar(value=False)

        ttk.Checkbutton(self, text="Show password", variable=self.show_var,

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


        ttk.Button(self, text="Analyze", command=self.run).pack(pady=10)


        self.score_lbl = ttk.Label(self, text="Score: —", font=("Arial", 12, "bold"))

        self.score_lbl.pack()


        self.ent_lbl = ttk.Label(self, text="Entropy: — bits")

        self.ent_lbl.pack(pady=5)


        self.verdict_lbl = ttk.Label(self, text="Verdict: —", font=("Arial", 12))

        self.verdict_lbl.pack(pady=5)


        ttk.Label(self, text="Feedback:", font=("Arial", 11, "bold")).pack(pady=8)

        self.feedback = tk.Text(self, height=8, width=60, wrap="word")

        self.feedback.pack(padx=10)


    def toggle_show(self):

        self.pw.config(show="" if self.show_var.get() else "*")


    def run(self):

        pwd = self.pw.get()

        res = analyze_password(pwd)


        self.score_lbl.config(text=f"Score: {res['score']}/100")

        self.ent_lbl.config(text=f"Entropy: {res['entropy']} bits")

        self.verdict_lbl.config(text=f"Verdict: {res['verdict']}")


        self.feedback.delete("1.0", "end")

        if res["issues"]:

            for i in res["issues"]:

                self.feedback.insert("end", f"• {i}\n")

        else:

            self.feedback.insert("end", "No issues found. Great password!")


if __name__ == "__main__":

    App().mainloop()