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

Image Duplicate Finder (Hash-Based)

import os

import tkinter as tk

from tkinter import filedialog, ttk, messagebox

from PIL import Image, ImageTk

import imagehash



class ImageDuplicateFinder:

    def __init__(self, root):

        self.root = root

        self.root.title("Image Duplicate Finder (Hash-Based)")

        self.root.geometry("900x600")


        self.image_hash_map = {}

        self.duplicates = []


        self.setup_ui()


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

    def setup_ui(self):

        top_frame = tk.Frame(self.root)

        top_frame.pack(fill=tk.X, pady=10)


        tk.Button(top_frame, text="Select Folder", command=self.select_folder).pack(side=tk.LEFT, padx=10)

        tk.Button(top_frame, text="Scan for Duplicates", command=self.scan_duplicates).pack(side=tk.LEFT, padx=10)


        self.result_tree = ttk.Treeview(self.root, columns=("img1", "img2"), show="headings")

        self.result_tree.heading("img1", text="Image 1")

        self.result_tree.heading("img2", text="Duplicate Image")

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


        self.result_tree.bind("<Double-1>", self.show_preview)


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

    def select_folder(self):

        self.folder_path = filedialog.askdirectory()

        if self.folder_path:

            messagebox.showinfo("Selected Folder", self.folder_path)


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

    def scan_duplicates(self):

        if not hasattr(self, "folder_path"):

            messagebox.showerror("Error", "Please select a folder first!")

            return


        self.image_hash_map = {}

        self.duplicates = []

        self.result_tree.delete(*self.result_tree.get_children())


        supported_ext = (".jpg", ".jpeg", ".png", ".bmp")


        for filename in os.listdir(self.folder_path):

            if filename.lower().endswith(supported_ext):

                full_path = os.path.join(self.folder_path, filename)


                try:

                    img = Image.open(full_path)

                    img_hash = imagehash.average_hash(img)


                    if img_hash in self.image_hash_map:

                        self.duplicates.append((self.image_hash_map[img_hash], full_path))


                    else:

                        self.image_hash_map[img_hash] = full_path


                except Exception as e:

                    print("Error loading:", filename, e)


        # Show results in table

        for dup in self.duplicates:

            self.result_tree.insert("", tk.END, values=dup)


        if not self.duplicates:

            messagebox.showinfo("Result", "No duplicates found!")

        else:

            messagebox.showinfo("Result", f"Found {len(self.duplicates)} duplicate pairs.")


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

    def show_preview(self, event):

        selected = self.result_tree.focus()

        if not selected:

            return


        img1_path, img2_path = self.result_tree.item(selected, "values")

        self.preview_window(img1_path, img2_path)


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

    def preview_window(self, img1_path, img2_path):

        win = tk.Toplevel(self.root)

        win.title("Duplicate Image Preview")

        win.geometry("850x450")


        tk.Label(win, text=f"Image 1: {os.path.basename(img1_path)}", font=("Arial", 10)).pack(pady=5)

        tk.Label(win, text=f"Image 2: {os.path.basename(img2_path)}", font=("Arial", 10)).pack(pady=5)


        frame = tk.Frame(win)

        frame.pack(expand=True)


        # Load images

        img1 = Image.open(img1_path).resize((350, 350))

        img2 = Image.open(img2_path).resize((350, 350))


        img1_tk = ImageTk.PhotoImage(img1)

        img2_tk = ImageTk.PhotoImage(img2)


        left_label = tk.Label(frame, image=img1_tk)

        left_label.image = img1_tk

        left_label.pack(side=tk.LEFT, padx=10)


        right_label = tk.Label(frame, image=img2_tk)

        right_label.image = img2_tk

        right_label.pack(side=tk.RIGHT, padx=10)



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

# RUN APP

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

root = tk.Tk()

app = ImageDuplicateFinder(root)

root.mainloop()

 

Smart PDF Page Extractor

import fitz  # PyMuPDF

import tkinter as tk

from tkinter import filedialog, messagebox, ttk

from PIL import Image, ImageTk



class PDFExtractorApp:

    def __init__(self, root):

        self.root = root

        self.root.title("Smart PDF Page Extractor")

        self.root.geometry("900x600")


        self.pdf_doc = None

        self.page_images = []

        self.selected_pages = []


        self.create_ui()


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

    # UI SETUP

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

    def create_ui(self):

        top_frame = tk.Frame(self.root)

        top_frame.pack(fill=tk.X, pady=10)


        tk.Button(top_frame, text="Open PDF", command=self.open_pdf).pack(side=tk.LEFT, padx=10)

        tk.Button(top_frame, text="Extract Selected", command=self.extract_pages).pack(side=tk.LEFT, padx=10)

        tk.Button(top_frame, text="Save New PDF", command=self.save_new_pdf).pack(side=tk.LEFT, padx=10)


        self.canvas = tk.Canvas(self.root, bg="white")

        self.scroll_y = tk.Scrollbar(self.root, orient="vertical", command=self.canvas.yview)

        self.canvas.configure(yscrollcommand=self.scroll_y.set)


        self.frame = tk.Frame(self.canvas)

        self.canvas.create_window((0, 0), window=self.frame, anchor="nw")


        self.canvas.pack(side=tk.LEFT, fill="both", expand=True)

        self.scroll_y.pack(side=tk.RIGHT, fill="y")


        self.frame.bind("<Configure>", lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))


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

    # OPEN PDF

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

    def open_pdf(self):

        filepath = filedialog.askopenfilename(

            filetypes=[("PDF Files", "*.pdf")],

            title="Choose a PDF"

        )

        if not filepath:

            return


        try:

            self.pdf_doc = fitz.open(filepath)

            self.load_pages()

        except Exception as e:

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


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

    # LOAD AND DISPLAY PAGE THUMBNAILS

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

    def load_pages(self):

        for widget in self.frame.winfo_children():

            widget.destroy()


        self.selected_pages = []

        self.page_images = []


        for page_num in range(len(self.pdf_doc)):

            page = self.pdf_doc.load_page(page_num)

            pix = page.get_pixmap(matrix=fitz.Matrix(0.3, 0.3))  # thumbnail scale


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

            img_tk = ImageTk.PhotoImage(image)


            self.page_images.append(img_tk)


            page_frame = tk.Frame(self.frame, bd=2, relief="groove")

            page_frame.pack(padx=10, pady=10, anchor="w")


            label = tk.Label(page_frame, image=img_tk)

            label.pack()


            tk.Label(page_frame, text=f"Page {page_num + 1}", font=("Arial", 12, "bold")).pack()


            btn = tk.Button(

                page_frame,

                text="Select",

                command=lambda n=page_num: self.toggle_page(n)

            )

            btn.pack(pady=5)


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

    # SELECT / UNSELECT PAGE

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

    def toggle_page(self, page_num):

        if page_num in self.selected_pages:

            self.selected_pages.remove(page_num)

            messagebox.showinfo("Page Unselected", f"Page {page_num + 1} removed.")

        else:

            self.selected_pages.append(page_num)

            messagebox.showinfo("Page Selected", f"Page {page_num + 1} selected.")


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

    # EXTRACT SELECTED PAGES

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

    def extract_pages(self):

        if not self.selected_pages:

            messagebox.showerror("Error", "No pages selected!")

            return


        self.selected_pages.sort()


        messagebox.showinfo("Selected Pages", f"Extracting pages: {[p+1 for p in self.selected_pages]}")


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

    # SAVE NEW PDF WITH SELECTED PAGES

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

    def save_new_pdf(self):

        if not self.selected_pages:

            messagebox.showerror("Error", "Select pages before saving!")

            return


        output_path = filedialog.asksaveasfilename(

            defaultextension=".pdf",

            filetypes=[("PDF Files", "*.pdf")],

            title="Save Extracted PDF"

        )


        if not output_path:

            return


        try:

            new_pdf = fitz.open()


            for page_num in self.selected_pages:

                new_pdf.insert_pdf(self.pdf_doc, from_page=page_num, to_page=page_num)


            new_pdf.save(output_path)

            new_pdf.close()


            messagebox.showinfo("Success", "New PDF saved successfully!")


        except Exception as e:

            messagebox.showerror("Error", f"Failed to save PDF:\n{e}")



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

# RUN APP

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

root = tk.Tk()

app = PDFExtractorApp(root)

root.mainloop()


Offline Travel Expense Splitter App

import tkinter as tk

from tkinter import ttk, messagebox

import sqlite3

from fpdf import FPDF


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

# DATABASE SETUP

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

conn = sqlite3.connect("travel_expenses.db")

cursor = conn.cursor()


cursor.execute("""

CREATE TABLE IF NOT EXISTS members (

    id INTEGER PRIMARY KEY AUTOINCREMENT,

    name TEXT NOT NULL

)

""")


cursor.execute("""

CREATE TABLE IF NOT EXISTS expenses (

    id INTEGER PRIMARY KEY AUTOINCREMENT,

    member_id INTEGER,

    description TEXT,

    amount REAL,

    FOREIGN KEY(member_id) REFERENCES members(id)

)

""")


conn.commit()


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

# MAIN APPLICATION

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

class TravelExpenseApp:


    def __init__(self, root):

        self.root = root

        self.root.title("Travel Expense Splitter")

        self.root.geometry("600x500")


        self.create_ui()


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

    def create_ui(self):

        tab_control = ttk.Notebook(self.root)


        self.tab_members = ttk.Frame(tab_control)

        self.tab_expenses = ttk.Frame(tab_control)

        self.tab_summary = ttk.Frame(tab_control)


        tab_control.add(self.tab_members, text="Members")

        tab_control.add(self.tab_expenses, text="Expenses")

        tab_control.add(self.tab_summary, text="Summary")

        tab_control.pack(expand=1, fill="both")


        self.setup_members_tab()

        self.setup_expenses_tab()

        self.setup_summary_tab()


    # ------------------------ MEMBERS TAB ------------------------

    def setup_members_tab(self):

        tk.Label(self.tab_members, text="Add Member", font=("Arial", 14)).pack(pady=10)


        self.member_entry = tk.Entry(self.tab_members, font=("Arial", 12))

        self.member_entry.pack(pady=5)


        tk.Button(self.tab_members, text="Add Member", command=self.add_member).pack(pady=10)


        self.members_list = tk.Listbox(self.tab_members, width=40, height=10)

        self.members_list.pack(pady=10)


        self.load_members()


    def add_member(self):

        name = self.member_entry.get()

        if not name:

            messagebox.showerror("Error", "Please enter a name!")

            return


        cursor.execute("INSERT INTO members (name) VALUES (?)", (name,))

        conn.commit()

        self.member_entry.delete(0, tk.END)

        self.load_members()


    def load_members(self):

        self.members_list.delete(0, tk.END)

        cursor.execute("SELECT name FROM members")

        for row in cursor.fetchall():

            self.members_list.insert(tk.END, row[0])


    # ------------------------ EXPENSE TAB ------------------------

    def setup_expenses_tab(self):

        tk.Label(self.tab_expenses, text="Add Expense", font=("Arial", 14)).pack(pady=10)


        tk.Label(self.tab_expenses, text="Select Member:").pack()

        self.member_dropdown = ttk.Combobox(self.tab_expenses, state="readonly")

        self.member_dropdown.pack(pady=5)


        self.load_member_dropdown()


        tk.Label(self.tab_expenses, text="Description:").pack()

        self.desc_entry = tk.Entry(self.tab_expenses, font=("Arial", 12))

        self.desc_entry.pack(pady=5)


        tk.Label(self.tab_expenses, text="Amount:").pack()

        self.amount_entry = tk.Entry(self.tab_expenses, font=("Arial", 12))

        self.amount_entry.pack(pady=5)


        tk.Button(self.tab_expenses, text="Add Expense", command=self.add_expense).pack(pady=10)


        self.expense_tree = ttk.Treeview(self.tab_expenses, columns=("member", "desc", "amount"), show="headings")

        self.expense_tree.heading("member", text="Member")

        self.expense_tree.heading("desc", text="Description")

        self.expense_tree.heading("amount", text="Amount")

        self.expense_tree.pack(fill="both", expand=True)


        self.load_expenses()


    def load_member_dropdown(self):

        cursor.execute("SELECT name FROM members")

        members = [row[0] for row in cursor.fetchall()]

        self.member_dropdown["values"] = members


    def add_expense(self):

        member = self.member_dropdown.get()

        desc = self.desc_entry.get()

        amount = self.amount_entry.get()


        if not member or not desc or not amount:

            messagebox.showerror("Error", "All fields are required!")

            return


        try:

            amount = float(amount)

        except:

            messagebox.showerror("Error", "Amount must be a number!")

            return


        cursor.execute("SELECT id FROM members WHERE name=?", (member,))

        member_id = cursor.fetchone()[0]


        cursor.execute("INSERT INTO expenses (member_id, description, amount) VALUES (?, ?, ?)",

                       (member_id, desc, amount))

        conn.commit()


        self.desc_entry.delete(0, tk.END)

        self.amount_entry.delete(0, tk.END)


        self.load_expenses()


    def load_expenses(self):

        for i in self.expense_tree.get_children():

            self.expense_tree.delete(i)


        cursor.execute("""

            SELECT members.name, expenses.description, expenses.amount

            FROM expenses

            JOIN members ON expenses.member_id = members.id

        """)


        for row in cursor.fetchall():

            self.expense_tree.insert("", tk.END, values=row)


    # ------------------------ SUMMARY TAB ------------------------

    def setup_summary_tab(self):

        tk.Label(self.tab_summary, text="Expense Summary", font=("Arial", 14)).pack(pady=10)


        tk.Button(self.tab_summary, text="Calculate Summary", command=self.calculate_summary).pack(pady=10)

        tk.Button(self.tab_summary, text="Export PDF", command=self.export_pdf).pack(pady=10)


        self.summary_box = tk.Text(self.tab_summary, height=20, width=70)

        self.summary_box.pack()


    def calculate_summary(self):

        cursor.execute("SELECT COUNT(*) FROM members")

        num_members = cursor.fetchone()[0]


        cursor.execute("SELECT SUM(amount) FROM expenses")

        total_expense = cursor.fetchone()[0] or 0


        split_amount = total_expense / num_members if num_members > 0 else 0


        self.summary_box.delete(1.0, tk.END)

        self.summary_box.insert(tk.END, f"Total Expense: ₹{total_expense:.2f}\n")

        self.summary_box.insert(tk.END, f"Each Person Should Pay: ₹{split_amount:.2f}\n\n")


        cursor.execute("""

            SELECT members.name, SUM(expenses.amount)

            FROM members

            LEFT JOIN expenses ON members.id = expenses.member_id

            GROUP BY members.name

        """)


        for name, paid in cursor.fetchall():

            paid = paid or 0

            diff = paid - split_amount

            status = "owes" if diff < 0 else "gets back"

            self.summary_box.insert(tk.END, f"{name}: Paid ₹{paid:.2f} → {status} ₹{abs(diff):.2f}\n")


    # ------------------------ PDF EXPORT ------------------------

    def export_pdf(self):

        pdf = FPDF()

        pdf.add_page()

        pdf.set_font("Arial", size=12)


        pdf.cell(200, 10, "Travel Expense Summary", ln=True, align="C")

        pdf.ln(10)


        summary_text = self.summary_box.get(1.0, tk.END).split("\n")

        for line in summary_text:

            pdf.cell(0, 10, txt=line, ln=True)


        pdf.output("Travel_Expense_Summary.pdf")

        messagebox.showinfo("Success", "PDF Exported Successfully!")


# ------------------------ RUN APP ------------------------

root = tk.Tk()

app = TravelExpenseApp(root)

root.mainloop()


AI-Focused Book Summarizer & Chapter Highlighter

import fitz  # PyMuPDF

import nltk

import re

from transformers import pipeline


# Load HuggingFace summarizer

summarizer = pipeline(

    "summarization", 

    model="facebook/bart-large-cnn"

)


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

# 1. Extract text from PDF

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

def extract_pdf_text(pdf_path):

    doc = fitz.open(pdf_path)

    full_text = ""


    for page in doc:

        full_text += page.get_text()


    return full_text



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

# 2. Split text into chapters

#    Uses patterns like:

#     - Chapter 1

#     - CHAPTER I

#     - CHAPTER ONE

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

def split_into_chapters(text):

    chapter_pattern = r"(chapter\s+\d+|chapter\s+[ivxlcdm]+|chapter\s+\w+)"

    found = re.split(chapter_pattern, text, flags=re.IGNORECASE)


    chapters = []

    for i in range(1, len(found), 2):

        title = found[i].strip()

        content = found[i + 1].strip()

        chapters.append((title, content))


    # If no chapters are detected → return full book as one chapter

    if not chapters:

        return [("Full Book", text)]


    return chapters



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

# 3. Summarize long text in safe chunks

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

def summarize_long_text(text, max_chunk=1500):

    nltk.download("punkt", quiet=True)


    sentences = nltk.sent_tokenize(text)

    chunks = []

    current_chunk = ""


    for sentence in sentences:

        if len(current_chunk) + len(sentence) <= max_chunk:

            current_chunk += " " + sentence

        else:

            chunks.append(current_chunk)

            current_chunk = sentence


    if current_chunk:

        chunks.append(current_chunk)


    # Summarize each chunk

    summaries = []

    for chunk in chunks:

        summary = summarizer(chunk, max_length=130, min_length=30, do_sample=False)[0]["summary_text"]

        summaries.append(summary)


    # Join all summaries

    return "\n".join(summaries)



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

# 4. Generate key points

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

def generate_key_points(summary):

    sentences = nltk.sent_tokenize(summary)

    key_points = sentences[:5]   # Top 5 key ideas

    return ["• " + s for s in key_points]



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

# 5. End-to-End Pipeline

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

def summarize_book(pdf_path):

    print("\nšŸ“˜ Extracting PDF text...")

    text = extract_pdf_text(pdf_path)


    print("✂ Splitting into chapters...")

    chapters = split_into_chapters(text)


    results = []


    for idx, (title, content) in enumerate(chapters, start=1):

        print(f"\nšŸ“ Summarizing {title}...")


        summary = summarize_long_text(content)

        key_points = generate_key_points(summary)


        results.append({

            "chapter_title": title,

            "summary": summary,

            "key_points": key_points

        })


    return results



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

# 6. Print Results Nicely

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

def display_results(results):

    print("\n============================")

    print("šŸ“š BOOK SUMMARY REPORT")

    print("============================\n")


    for item in results:

        print(f"\n===== {item['chapter_title']} =====\n")

        print("SUMMARY:\n")

        print(item["summary"])


        print("\nKEY POINTS:")

        for p in item["key_points"]:

            print(p)


        print("\n---------------------------")



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

# RUN

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

if __name__ == "__main__":

    pdf_path = input("Enter PDF file path: ").strip()


    results = summarize_book(pdf_path)

    display_results(results)


    print("\n✔ Done! All chapters processed.")


Backup Scheduler

import schedule

import shutil

import time

import os

from datetime import datetime


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

# CONFIGURATION

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

SOURCE_FOLDER = r"E:\MyData"           # Folder to back up

DESTINATION_FOLDER = r"F:\Backups"     # External drive / backup location


BACKUP_FREQUENCY = "hourly"            # options: hourly, daily, custom



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

# Create destination folder if missing

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

def ensure_destination():

    if not os.path.exists(DESTINATION_FOLDER):

        os.makedirs(DESTINATION_FOLDER)

        print(f"[INFO] Created backup directory: {DESTINATION_FOLDER}")



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

# Perform Backup

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

def perform_backup():

    ensure_destination()


    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

    backup_path = os.path.join(DESTINATION_FOLDER, f"backup_{timestamp}")


    try:

        print(f"[START] Backing up '{SOURCE_FOLDER}' → '{backup_path}'")

        shutil.copytree(SOURCE_FOLDER, backup_path)

        print(f"[DONE] Backup completed successfully! ✔️\n")

    except Exception as e:

        print(f"[ERROR] Backup failed: {e}\n")



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

# Schedule Backup

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

def schedule_backups():

    if BACKUP_FREQUENCY == "hourly":

        schedule.every().hour.do(perform_backup)

        print("[SCHEDULER] Backup scheduled: Every hour.")

    

    elif BACKUP_FREQUENCY == "daily":

        schedule.every().day.at("00:00").do(perform_backup)

        print("[SCHEDULER] Backup scheduled: Every day at 12:00 AM.")

    

    else:

        # custom frequency example: every 10 minutes

        schedule.every(10).minutes.do(perform_backup)

        print("[SCHEDULER] Backup scheduled: Every 10 minutes (custom).")



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

# MAIN LOOP

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

def main():

    print("===== Python Backup Scheduler Started =====")

    print(f"Source Folder:      {SOURCE_FOLDER}")

    print(f"Destination Folder: {DESTINATION_FOLDER}")

    print("=================================================\n")


    schedule_backups()


    # Continuous loop

    while True:

        schedule.run_pending()

        time.sleep(1)



if __name__ == "__main__":

    main()


Offline Dictionary App

import tkinter as tk

from tkinter import messagebox

import sqlite3

import pyttsx3


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

# Database Setup

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

def init_db():

    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()


    cur.execute("""

        CREATE TABLE IF NOT EXISTS words (

            word TEXT PRIMARY KEY,

            meaning TEXT

        );

    """)


    cur.execute("""

        CREATE TABLE IF NOT EXISTS favorites (

            word TEXT PRIMARY KEY

        );

    """)


    conn.commit()

    conn.close()


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

# Insert sample words (optional)

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

def insert_sample_words():

    sample_data = {

        "python": "A high-level programming language used for general-purpose programming.",

        "algorithm": "A step-by-step procedure for solving a problem or performing a task.",

        "variable": "A storage location paired with a name used to store values.",

        "database": "A structured collection of data stored electronically.",

    }


    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()

    

    for word, meaning in sample_data.items():

        cur.execute("INSERT OR IGNORE INTO words VALUES (?, ?)", (word, meaning))


    conn.commit()

    conn.close()


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

# Text-to-Speech

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

engine = pyttsx3.init()


def speak_word(word):

    engine.say(word)

    engine.runAndWait()


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

# Dictionary Operations

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

def search_word():

    word = entry_word.get().strip().lower()

    if not word:

        messagebox.showerror("Error", "Please enter a word to search.")

        return


    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()


    cur.execute("SELECT meaning FROM words WHERE word=?", (word,))

    result = cur.fetchone()


    if result:

        text_meaning.config(state="normal")

        text_meaning.delete(1.0, tk.END)

        text_meaning.insert(tk.END, result[0])

        text_meaning.config(state="disabled")

    else:

        messagebox.showinfo("Not Found", "Word not found in offline dictionary.")

    

    conn.close()


def add_word():

    word = entry_add_word.get().strip().lower()

    meaning = text_add_meaning.get(1.0, tk.END).strip()


    if not word or not meaning:

        messagebox.showerror("Error", "Both word and meaning are required.")

        return


    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()


    cur.execute("INSERT OR REPLACE INTO words VALUES (?, ?)", (word, meaning))

    conn.commit()

    conn.close()


    messagebox.showinfo("Success", f"'{word}' added to dictionary.")


def add_to_favorites():

    word = entry_word.get().strip().lower()


    if not word:

        messagebox.showerror("Error", "Search a word first before adding to favorites.")

        return


    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()

    cur.execute("INSERT OR IGNORE INTO favorites VALUES (?)", (word,))

    conn.commit()

    conn.close()


    messagebox.showinfo("Added", f"'{word}' added to favorites!")


def show_favorites():

    conn = sqlite3.connect("dictionary.db")

    cur = conn.cursor()

    cur.execute("SELECT word FROM favorites")

    favs = cur.fetchall()

    conn.close()


    fav_list = "\n".join([w[0] for w in favs]) if favs else "No favorites added yet."


    messagebox.showinfo("Favorite Words", fav_list)


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

# GUI Setup

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

root = tk.Tk()

root.title("Offline Dictionary App")

root.geometry("650x500")

root.resizable(False, False)


# Search section

tk.Label(root, text="Enter Word:", font=("Arial", 14)).pack(pady=5)

entry_word = tk.Entry(root, font=("Arial", 14), width=30)

entry_word.pack()


btn_search = tk.Button(root, text="Search", font=("Arial", 12), command=search_word)

btn_search.pack(pady=5)


btn_speak = tk.Button(root, text="šŸ”Š Speak", font=("Arial", 12), command=lambda: speak_word(entry_word.get()))

btn_speak.pack(pady=2)


btn_fav = tk.Button(root, text="⭐ Add to Favorites", font=("Arial", 12), command=add_to_favorites)

btn_fav.pack(pady=2)


# Meaning display

tk.Label(root, text="Meaning:", font=("Arial", 14)).pack()

text_meaning = tk.Text(root, height=6, width=60, font=("Arial", 12), state="disabled")

text_meaning.pack(pady=5)


# Add new word section

tk.Label(root, text="Add New Word:", font=("Arial", 14)).pack(pady=5)

entry_add_word = tk.Entry(root, font=("Arial", 12), width=30)

entry_add_word.pack()


tk.Label(root, text="Meaning:", font=("Arial", 14)).pack()

text_add_meaning = tk.Text(root, height=4, width=60, font=("Arial", 12))

text_add_meaning.pack()


btn_add = tk.Button(root, text="Add Word to Dictionary", font=("Arial", 12), command=add_word)

btn_add.pack(pady=5)


# favorites

btn_show_fav = tk.Button(root, text="šŸ“Œ Show Favorites", font=("Arial", 12), command=show_favorites)

btn_show_fav.pack(pady=5)


# Run

init_db()

insert_sample_words()

root.mainloop()


Resume ATS Scoring Tool

import fitz  # PyMuPDF

import spacy

import re

import pandas as pd


nlp = spacy.load("en_core_web_sm")


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

# Utility: Extract text from PDF or TXT

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

def extract_text(file_path):

    if file_path.lower().endswith(".pdf"):

        text = ""

        pdf = fitz.open(file_path)

        for page in pdf:

            text += page.get_text()

        return text

    else:

        # for .txt files

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

            return f.read()


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

# Clean & Normalize Text

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

def clean_text(text):

    text = text.lower()

    text = re.sub(r'[^a-zA-Z0-9\s]', ' ', text)

    text = re.sub(r'\s+', ' ', text)

    return text


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

# Extract Keywords Using spaCy

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

def extract_keywords(text):

    doc = nlp(text)

    keywords = []


    for token in doc:

        # Keep nouns, verbs, adjectives (important for ATS)

        if token.pos_ in ["NOUN", "PROPN", "VERB", "ADJ"]:

            if len(token.text) > 2:

                keywords.append(token.lemma_.lower())


    return list(set(keywords))


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

# ATS Scoring Logic

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

def calculate_ats_score(resume_text, jd_text):

    resume_clean = clean_text(resume_text)

    jd_clean = clean_text(jd_text)


    resume_keywords = extract_keywords(resume_clean)

    jd_keywords = extract_keywords(jd_clean)


    matched = [kw for kw in jd_keywords if kw in resume_keywords]

    missing = [kw for kw in jd_keywords if kw not in resume_keywords]


    score = (len(matched) / len(jd_keywords)) * 100 if jd_keywords else 0


    return {

        "ats_score": round(score, 2),

        "matched_keywords": matched,

        "missing_keywords": missing,

        "total_keywords": len(jd_keywords)

    }


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

# MAIN FUNCTION

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

def ats_tool(resume_file, jobdesc_file):

    resume_text = extract_text(resume_file)

    jd_text = extract_text(jobdesc_file)


    result = calculate_ats_score(resume_text, jd_text)


    print("\n ATS SCORING RESULTS")

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

    print(f"ATS Score: {result['ats_score']}%")

    print(f"Total Keywords in Job Description: {result['total_keywords']}")

    print(f"Matched Keywords ({len(result['matched_keywords'])}):")

    print(result["matched_keywords"])

    print("\nMissing Keywords:")

    print(result["missing_keywords"])


    # Export to CSV (optional)

    df = pd.DataFrame({

        "Matched Keywords": pd.Series(result["matched_keywords"]),

        "Missing Keywords": pd.Series(result["missing_keywords"])

    })

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

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


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

# RUN

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

if __name__ == "__main__":

    resume_path = input("Enter Resume File Path (.pdf/.txt): ")

    jd_path = input("Enter Job Description File Path (.pdf/.txt): ")


    ats_tool(resume_path, jd_path)


Command Palette Launcher (VS Code Style)

 """

Command Palette Launcher (VS Code style)

Tech: tkinter, os, keyboard, difflib


Features:

- Ctrl+P to open palette (global using 'keyboard', and also inside Tk window)

- Index files from a folder for quick search

- Fuzzy search using difflib

- Open files (os.startfile on Windows / xdg-open on Linux / open on macOS)

- Add custom commands (open app, shell command)

- Demo includes uploaded file path: /mnt/data/image.png

"""


import os

import sys

import threading

import platform

import subprocess

from pathlib import Path

import tkinter as tk

from tkinter import ttk, filedialog, messagebox

from difflib import get_close_matches


# Optional global hotkey package

try:

    import keyboard  # pip install keyboard

    KEYBOARD_AVAILABLE = True

except Exception:

    KEYBOARD_AVAILABLE = False


# Demo uploaded file path (from your session)

DEMO_FILE = "/mnt/data/image.png"


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

# Utility functions

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

def open_path(path):

    """Open a file or folder using the OS default application."""

    p = str(path)

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

        os.startfile(p)

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

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

    else:  # Linux and others

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


def is_executable_file(path):

    try:

        return os.access(path, os.X_OK) and Path(path).is_file()

    except Exception:

        return False


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

# Indexer

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

class FileIndexer:

    def __init__(self):

        self.items = []  # list of {"title": ..., "path": ..., "type": "file"|"cmd"}

        # preload demo item if exists

        if Path(DEMO_FILE).exists():

            self.add_item(title=Path(DEMO_FILE).name, path=str(DEMO_FILE), typ="file")


    def add_item(self, title, path, typ="file"):

        rec = {"title": title, "path": path, "type": typ}

        self.items.append(rec)


    def index_folder(self, folder, max_files=5000):

        """Recursively index a folder (stop at max_files)."""

        folder = Path(folder)

        count = 0

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

            for f in files:

                try:

                    fp = Path(root) / f

                    self.add_item(title=f, path=str(fp), typ="file")

                    count += 1

                    if count >= max_files:

                        return count

                except Exception:

                    continue

        return count


    def add_common_apps(self):

        """Add some common app commands (platform-specific)."""

        sysplat = platform.system()

        apps = []

        if sysplat == "Windows":

            # common Windows apps (paths may vary)

            apps = [

                ("Notepad", "notepad.exe"),

                ("Calculator", "calc.exe"),

                ("Paint", "mspaint.exe"),

            ]

        elif sysplat == "Darwin":

            apps = [

                ("TextEdit", "open -a TextEdit"),

                ("Calculator", "open -a Calculator"),

            ]

        else:  # Linux

            apps = [

                ("Gedit", "gedit"),

                ("Calculator", "gnome-calculator"),

            ]

        for name, cmd in apps:

            self.add_item(title=name, path=cmd, typ="cmd")


    def search(self, query, limit=15):

        """Simple fuzzy search: look for substrings first, then difflib matches."""

        q = query.strip().lower()

        if not q:

            # return top items

            return self.items[:limit]


        # substring matches (higher priority)

        substr_matches = [it for it in self.items if q in it["title"].lower() or q in it["path"].lower()]

        if len(substr_matches) >= limit:

            return substr_matches[:limit]


        # prepare list of titles for difflib

        titles = [it["title"] for it in self.items]

        close = get_close_matches(q, titles, n=limit, cutoff=0.4)

        # map back to records preserving order (titles may repeat)

        close_records = []

        for t in close:

            for it in self.items:

                if it["title"] == t and it not in close_records:

                    close_records.append(it)

                    break


        # combine substring + close matches, ensure uniqueness

        results = []

        seen = set()

        for it in substr_matches + close_records:

            key = (it["title"], it["path"])

            if key not in seen:

                results.append(it)

                seen.add(key)

            if len(results) >= limit:

                break

        return results


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

# GUI

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

class CommandPalette(tk.Toplevel):

    def __init__(self, master, indexer: FileIndexer):

        super().__init__(master)

        self.indexer = indexer

        self.title("Command Palette")

        self.geometry("700x380")

        self.transient(master)

        self.grab_set()  # modal

        self.resizable(False, False)


        # Styling

        self.configure(bg="#2b2b2b")


        # Search box

        self.search_var = tk.StringVar()

        search_entry = ttk.Entry(self, textvariable=self.search_var, font=("Consolas", 14), width=60)

        search_entry.pack(padx=12, pady=(12,6))

        search_entry.focus_set()

        search_entry.bind("<KeyRelease>", self.on_search_key)

        search_entry.bind("<Escape>", lambda e: self.close())

        search_entry.bind("<Return>", lambda e: self.open_selected())


        # Results list

        self.tree = ttk.Treeview(self, columns=("title","path","type"), show="headings", height=12)

        self.tree.heading("title", text="Title")

        self.tree.heading("path", text="Path / Command")

        self.tree.heading("type", text="Type")

        self.tree.column("title", width=250)

        self.tree.column("path", width=350)

        self.tree.column("type", width=80, anchor="center")

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

        self.tree.bind("<Double-1>", lambda e: self.open_selected())

        self.tree.bind("<Return>", lambda e: self.open_selected())


        # Bottom buttons

        btn_frame = ttk.Frame(self)

        btn_frame.pack(fill="x", padx=12, pady=(0,12))

        ttk.Button(btn_frame, text="Open Folder to Index", command=self.browse_and_index).pack(side="left")

        ttk.Button(btn_frame, text="Add Command", command=self.add_command_dialog).pack(side="left", padx=6)

        ttk.Button(btn_frame, text="Close (Esc)", command=self.close).pack(side="right")


        # initial populate

        self.update_results(self.indexer.items[:50])


    def on_search_key(self, event=None):

        q = self.search_var.get()

        results = self.indexer.search(q, limit=50)

        self.update_results(results)

        # keep the first row selected

        children = self.tree.get_children()

        if children:

            self.tree.selection_set(children[0])

            self.tree.focus(children[0])


    def update_results(self, records):

        # clear

        for r in self.tree.get_children():

            self.tree.delete(r)

        for rec in records:

            self.tree.insert("", "end", values=(rec["title"], rec["path"], rec["type"]))


    def open_selected(self):

        sel = self.tree.selection()

        if not sel:

            return

        vals = self.tree.item(sel[0])["values"]

        title, path, typ = vals

        try:

            if typ == "file":

                open_path(path)

            elif typ == "cmd":

                # if it's a shell command, run it

                # Allow both simple exe names and complex shell commands

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

                    subprocess.Popen(path, shell=True)

                else:

                    subprocess.Popen(path.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

            else:

                # fallback attempt

                open_path(path)

        except Exception as e:

            messagebox.showerror("Open failed", f"Could not open {path}\n\n{e}")

        finally:

            self.close()


    def browse_and_index(self):

        folder = filedialog.askdirectory()

        if not folder:

            return

        count = self.indexer.index_folder(folder)

        messagebox.showinfo("Indexed", f"Indexed approx {count} files from {folder}")

        # refresh results

        self.on_search_key()


    def add_command_dialog(self):

        dlg = tk.Toplevel(self)

        dlg.title("Add Command / App")

        dlg.geometry("500x150")

        tk.Label(dlg, text="Title:").pack(anchor="w", padx=8, pady=(8,0))

        title_e = ttk.Entry(dlg, width=60)

        title_e.pack(padx=8)

        tk.Label(dlg, text="Command or Path:").pack(anchor="w", padx=8, pady=(8,0))

        path_e = ttk.Entry(dlg, width=60)

        path_e.pack(padx=8)

        def add():

            t = title_e.get().strip() or Path(path_e.get()).name

            p = path_e.get().strip()

            if not p:

                messagebox.showwarning("Input", "Please provide a command or path")

                return

            typ = "cmd" if (" " in p or os.sep not in p and not Path(p).exists()) else "file"

            self.indexer.add_item(title=t, path=p, typ=typ)

            dlg.destroy()

            self.on_search_key()

        ttk.Button(dlg, text="Add", command=add).pack(pady=8)


    def close(self):

        try:

            self.grab_release()

        except:

            pass

        self.destroy()


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

# Main App Window

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

class PaletteApp:

    def __init__(self, root):

        self.root = root

        root.title("Command Palette Launcher")

        root.geometry("700x120")


        self.indexer = FileIndexer()

        self.indexer.add_common_apps()

        # Add a few demo entries (including uploaded file path)

        if Path(DEMO_FILE).exists():

            self.indexer.add_item(title=Path(DEMO_FILE).name, path=str(DEMO_FILE), typ="file")


        # Top UI

        frame = ttk.Frame(root, padding=12)

        frame.pack(fill="both", expand=True)


        ttk.Label(frame, text="Press Ctrl+P to open command palette", font=("Arial", 12)).pack(anchor="w")

        ttk.Button(frame, text="Open Palette (Ctrl+P)", command=self.open_palette).pack(pady=10, anchor="w")

        ttk.Button(frame, text="Index Folder", command=self.index_folder).pack(side="left")

        ttk.Button(frame, text="Exit", command=root.quit).pack(side="right")


        # register global hotkey in a background thread (if available)

        if KEYBOARD_AVAILABLE:

            t = threading.Thread(target=self.register_global_hotkey, daemon=True)

            t.start()

        else:

            print("keyboard package not available — global hotkey disabled. Use app's Ctrl+P instead.")


        # bind Ctrl+P inside the Tk window too

        root.bind_all("<Control-p>", lambda e: self.open_palette())


    def open_palette(self):

        # open modal CommandPalette

        cp = CommandPalette(self.root, self.indexer)


    def index_folder(self):

        folder = filedialog.askdirectory()

        if not folder:

            return

        count = self.indexer.index_folder(folder)

        messagebox.showinfo("Indexed", f"Indexed approx {count} files")


    def register_global_hotkey(self):

        """

        Register Ctrl+P as a global hotkey using keyboard module.

        When pressed, we must bring the Tk window to front and open palette.

        """

        try:

            # On some systems, keyboard requires admin privileges. If it fails, we catch and disable.

            keyboard.add_hotkey("ctrl+p", lambda: self.trigger_from_global())

            keyboard.wait()  # keep the listener alive

        except Exception as e:

            print("Global hotkey registration failed:", e)


    def trigger_from_global(self):

        # Because keyboard runs in another thread, schedule UI work in Tk mainloop

        try:

            self.root.after(0, self.open_palette)

            # Try to bring window to front

            try:

                self.root.lift()

                self.root.attributes("-topmost", True)

                self.root.after(500, lambda: self.root.attributes("-topmost", False))

            except Exception:

                pass

        except Exception as e:

            print("Error triggering palette:", e)


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

# Run

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

def main():

    root = tk.Tk()

    app = PaletteApp(root)

    root.mainloop()


if __name__ == "__main__":

    main()