File Locker CLI

import argparse

import getpass

import os

from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives import hashes

from cryptography.fernet import Fernet

import base64


def derive_key(password: str, salt: bytes) -> bytes:

    kdf = PBKDF2HMAC(

        algorithm=hashes.SHA256(),

        length=32,

        salt=salt,

        iterations=390000,

        backend=default_backend()

    )

    return base64.urlsafe_b64encode(kdf.derive(password.encode()))


def encrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        data = file.read()


    salt = os.urandom(16)

    key = derive_key(password, salt)

    fernet = Fernet(key)

    encrypted_data = fernet.encrypt(data)


    with open(filepath + ".locked", 'wb') as file:

        file.write(salt + encrypted_data)


    os.remove(filepath)

    print(f"🔒 File encrypted as {filepath}.locked")


def decrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        content = file.read()


    salt = content[:16]

    encrypted_data = content[16:]

    key = derive_key(password, salt)

    fernet = Fernet(key)


    try:

        decrypted_data = fernet.decrypt(encrypted_data)

    except Exception:

        print("❌ Wrong password or corrupted file.")

        return


    original_path = filepath.replace(".locked", "")

    with open(original_path, 'wb') as file:

        file.write(decrypted_data)


    os.remove(filepath)

    print(f"🔓 File decrypted as {original_path}")


def main():

    parser = argparse.ArgumentParser(description="🔐 File Locker CLI")

    parser.add_argument("action", choices=["lock", "unlock"], help="Lock or unlock the file")

    parser.add_argument("filepath", help="Path to the file")


    args = parser.parse_args()

    password = getpass.getpass("Enter password: ")


    if args.action == "lock":

        encrypt_file(args.filepath, password)

    elif args.action == "unlock":

        decrypt_file(args.filepath, password)


if __name__ == "__main__":

    main()


Plagiarism Detector

 import difflib

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import cosine_similarity


def read_file(filename):

    with open(filename, 'r', encoding='utf-8') as file:

        return file.read()


def basic_diff_score(text1, text2):

    seq = difflib.SequenceMatcher(None, text1, text2)

    return round(seq.ratio() * 100, 2)


def nlp_cosine_similarity(text1, text2):

    tfidf = TfidfVectorizer().fit_transform([text1, text2])

    score = cosine_similarity(tfidf[0:1], tfidf[1:2])

    return round(score[0][0] * 100, 2)


def main():

    file1 = input("Enter path to first file: ")

    file2 = input("Enter path to second file: ")


    text1 = read_file(file1)

    text2 = read_file(file2)


    basic_score = basic_diff_score(text1, text2)

    nlp_score = nlp_cosine_similarity(text1, text2)


    print("\n--- Plagiarism Detection Result ---")

    print(f"Simple Match (difflib): {basic_score}%")

    print(f"Semantic Match (TF-IDF Cosine Similarity): {nlp_score}%")


    if nlp_score > 80:

        print("⚠️ High similarity detected. Possible plagiarism.")

    elif nlp_score > 50:

        print("⚠️ Moderate similarity. Review recommended.")

    else:

        print("✅ Low similarity. Likely original.")


if __name__ == "__main__":

    main()


Online Exam Proctoring Tool

import cv2

import face_recognition

import datetime


def log_alert(msg):

    with open("proctoring_log.txt", "a") as f:

        f.write(f"{datetime.datetime.now()} - {msg}\n")


def main():

    cap = cv2.VideoCapture(0)


    if not cap.isOpened():

        print("Could not access webcam.")

        return


    print("[INFO] Proctoring started. Press 'q' to quit.")


    while True:

        ret, frame = cap.read()

        if not ret:

            break


        # Resize frame for faster processing

        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

        rgb_small_frame = small_frame[:, :, ::-1]


        # Detect all faces

        face_locations = face_recognition.face_locations(rgb_small_frame)

        face_count = len(face_locations)


        # Draw rectangles around faces

        for (top, right, bottom, left) in face_locations:

            top, right, bottom, left = top*4, right*4, bottom*4, left*4

            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)


        # Check for multiple faces

        if face_count > 1:

            cv2.putText(frame, "ALERT: Multiple Faces Detected!", (10, 30),

                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

            log_alert("Multiple faces detected!")


        # Show output

        cv2.imshow("Exam Proctoring Feed", frame)


        # Break on 'q' key

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

            break


    cap.release()

    cv2.destroyAllWindows()

    print("[INFO] Proctoring ended.")


if __name__ == "__main__":

    main()


Budget Planner with Visualization

 import pandas as pd

import matplotlib.pyplot as plt

from tkinter import *

from tkinter import ttk, messagebox

import os

from datetime import datetime


# Create main window

root = Tk()

root.title("Budget Planner with Visualization")

root.geometry("800x600")


# CSV file name

filename = "budget_data.csv"


# Load existing data

if os.path.exists(filename):

    df = pd.read_csv(filename)

else:

    df = pd.DataFrame(columns=["Date", "Category", "Type", "Amount"])


# Function to add entry

def add_entry():

    date = date_entry.get()

    category = category_entry.get()

    ttype = type_combo.get()

    amount = amount_entry.get()


    if not date or not category or not ttype or not amount:

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

        return


    try:

        datetime.strptime(date, "%Y-%m-%d")

        amount = float(amount)

    except:

        messagebox.showerror("Input Error", "Invalid date or amount.")

        return


    new_entry = {"Date": date, "Category": category, "Type": ttype, "Amount": amount}

    global df

    df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)

    df.to_csv(filename, index=False)

    update_table()

    messagebox.showinfo("Success", "Entry added successfully!")


# Function to update table

def update_table():

    for row in tree.get_children():

        tree.delete(row)

    for index, row in df.iterrows():

        tree.insert("", "end", values=list(row))


# Function to show chart

def show_chart():

    try:

        expense_df = df[df["Type"] == "Expense"]

        summary = expense_df.groupby("Category")["Amount"].sum()

        summary.plot.pie(autopct="%1.1f%%", startangle=90)

        plt.title("Expenses by Category")

        plt.ylabel("")

        plt.show()

    except Exception as e:

        messagebox.showerror("Chart Error", str(e))


# Input Form

form_frame = Frame(root)

form_frame.pack(pady=10)


Label(form_frame, text="Date (YYYY-MM-DD)").grid(row=0, column=0, padx=5)

date_entry = Entry(form_frame)

date_entry.grid(row=0, column=1, padx=5)


Label(form_frame, text="Category").grid(row=0, column=2, padx=5)

category_entry = Entry(form_frame)

category_entry.grid(row=0, column=3, padx=5)


Label(form_frame, text="Type").grid(row=1, column=0, padx=5)

type_combo = ttk.Combobox(form_frame, values=["Income", "Expense"], state="readonly")

type_combo.grid(row=1, column=1, padx=5)


Label(form_frame, text="Amount").grid(row=1, column=2, padx=5)

amount_entry = Entry(form_frame)

amount_entry.grid(row=1, column=3, padx=5)


Button(form_frame, text="Add Entry", command=add_entry).grid(row=2, column=0, columnspan=4, pady=10)


# Treeview

tree = ttk.Treeview(root, columns=["Date", "Category", "Type", "Amount"], show="headings")

for col in ["Date", "Category", "Type", "Amount"]:

    tree.heading(col, text=col)

    tree.column(col, width=150)

tree.pack(fill=BOTH, expand=True, pady=10)


# Show chart button

Button(root, text="Show Expense Chart", command=show_chart).pack(pady=10)


# Load initial table

update_table()


root.mainloop()


Website Availability & Uptime Tracker

 import requests

import schedule

import time

import smtplib

from email.mime.text import MIMEText


# List of websites to track

websites = {

    "Google": "https://www.google.com",

    "My Portfolio": "https://yourportfolio.com"

}


# Email Config

EMAIL_ADDRESS = "your_email@gmail.com"

EMAIL_PASSWORD = "your_app_password"

TO_EMAIL = "recipient_email@example.com"


def send_email_alert(site):

    msg = MIMEText(f"Alert: {site} is DOWN!")

    msg["Subject"] = f"🚨 {site} is Down!"

    msg["From"] = EMAIL_ADDRESS

    msg["To"] = TO_EMAIL


    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:

        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

        smtp.send_message(msg)

        print(f"Email sent: {site} is down.")


def check_sites():

    for name, url in websites.items():

        try:

            response = requests.get(url, timeout=5)

            if response.status_code != 200:

                print(f"[{name}] Status: {response.status_code}")

                send_email_alert(name)

            else:

                print(f"[{name}] is up ✅")

        except requests.exceptions.RequestException:

            print(f"[{name}] is unreachable ❌")

            send_email_alert(name)


# Check every 5 minutes

schedule.every(5).minutes.do(check_sites)


print("🔍 Website Uptime Tracker Started...")

while True:

    schedule.run_pending()

    time.sleep(1)



Twilio SMS Integration


from twilio.rest import Client

account_sid = "your_sid"
auth_token = "your_token"
twilio_number = "+1234567890"
receiver_number = "+91999xxxxxxx"

def send_sms_alert(site):
    client = Client(account_sid, auth_token)
    client.messages.create(
        body=f"🚨 {site} is DOWN!",
        from_=twilio_number,
        to=receiver_number
    )