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