Secure Diary with Face Unlock

 Install Requirements

pip install face_recognition opencv-python cryptography

Capture Reference Face

# Optional: capture face from webcam and save as known_face.jpg
import cv2
cam = cv2.VideoCapture(0)
ret, frame = cam.read()
cv2.imwrite("known_face.jpg", frame)
cam.release()
print("Reference face saved.")

Secure Diary Code

import face_recognition
import cv2
import os
from cryptography.fernet import Fernet
from getpass import getpass
import base64

KEY_FILE = "secret.key"
ENC_FILE = "diary.enc"
KNOWN_FACE_FILE = "known_face.jpg"

# === Face Unlock ===
def verify_face():
    if not os.path.exists(KNOWN_FACE_FILE):
        print("Known face image not found.")
        return False

    known_image = face_recognition.load_image_file(KNOWN_FACE_FILE)
    known_encoding = face_recognition.face_encodings(known_image)[0]

    cam = cv2.VideoCapture(0)
    print("Looking for face...")
    ret, frame = cam.read()
    cam.release()

    try:
        unknown_encoding = face_recognition.face_encodings(frame)[0]
        result = face_recognition.compare_faces([known_encoding], unknown_encoding)[0]
        return result
    except IndexError:
        print("No face detected.")
        return False

# === Encryption Helpers ===
def generate_key(password):
    return base64.urlsafe_b64encode(password.encode().ljust(32)[:32])

def encrypt_diary(content, key):
    f = Fernet(key)
    with open(ENC_FILE, "wb") as file:
        file.write(f.encrypt(content.encode()))
    print("Diary encrypted & saved.")

def decrypt_diary(key):
    f = Fernet(key)
    with open(ENC_FILE, "rb") as file:
        data = file.read()
    return f.decrypt(data).decode()

# === Main Diary App ===
def diary_app():
    print("šŸ” Secure Diary Access")

    if not verify_face():
        print("Face verification failed. Access denied.")
        return

    password = getpass("Enter your diary password: ")
    key = generate_key(password)

    if os.path.exists(ENC_FILE):
        try:
            decrypted = decrypt_diary(key)
            print("\nšŸ“– Your Diary:\n", decrypted)
        except:
            print("Failed to decrypt. Wrong password?")
            return
    else:
        print("No diary found. Creating new one...")

    new_entry = input("\n✍️ Write new entry (append to diary):\n> ")
    combined = decrypted + "\n\n" + new_entry if 'decrypted' in locals() else new_entry
    encrypt_diary(combined, key)

if __name__ == "__main__":
    diary_app()

Screen Time Tracker

import time

import pandas as pd

import matplotlib.pyplot as plt

from datetime import datetime

import win32gui  # Windows-only; use AppKit for Mac


LOG_FILE = "screen_time_log.csv"

TRACK_DURATION_MINUTES = 1  # Change as needed

INTERVAL_SECONDS = 5


def get_active_window_title():

    try:

        return win32gui.GetWindowText(win32gui.GetForegroundWindow())

    except:

        return "Unknown"


def track_screen_time(duration_minutes=1, interval=5):

    end_time = time.time() + (duration_minutes * 60)

    usage_log = []


    print("Tracking started... Press Ctrl+C to stop early.")

    while time.time() < end_time:

        window = get_active_window_title()

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

        usage_log.append((timestamp, window))

        time.sleep(interval)


    # Save to CSV

    df = pd.DataFrame(usage_log, columns=["Timestamp", "Window"])

    df.to_csv(LOG_FILE, index=False)

    print(f"Tracking complete. Data saved to {LOG_FILE}")

    return df


def generate_report(csv_file):

    df = pd.read_csv(csv_file)

    df["Window"] = df["Window"].fillna("Unknown")


    # Count frequency of window usage

    summary = df["Window"].value_counts().head(10)  # Top 10 apps/windows


    # Plot

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

    summary.plot(kind="bar", color="skyblue")

    plt.title("Most Used Windows/Apps")

    plt.xlabel("Window Title")

    plt.ylabel("Active Window Count")

    plt.xticks(rotation=45, ha="right")

    plt.tight_layout()

    plt.show()


if __name__ == "__main__":

    df = track_screen_time(TRACK_DURATION_MINUTES, INTERVAL_SECONDS)

    generate_report(LOG_FILE)


News Authenticity Checker

import tkinter as tk

from tkinter import messagebox

from newspaper import Article

from sklearn.feature_extraction.text import TfidfVectorizer

import requests


NEWS_API_KEY = 'your_newsapi_key_here'  # Replace with your NewsAPI key


# ---------- News Verifier Logic ----------

def extract_keywords(text, top_n=10):

    vectorizer = TfidfVectorizer(stop_words='english')

    X = vectorizer.fit_transform([text])

    keywords = sorted(zip(vectorizer.get_feature_names_out(), X.toarray()[0]), key=lambda x: -x[1])

    return [k[0] for k in keywords[:top_n]]


def fetch_related_news(keywords):

    query = ' OR '.join(keywords[:3])  # Limit to top 3

    url = f'https://newsapi.org/v2/everything?q={query}&language=en&apiKey={NEWS_API_KEY}'

    res = requests.get(url)

    if res.status_code != 200:

        return []

    return [a['title'] + ' ' + a['description'] for a in res.json().get('articles', [])]


def calculate_authenticity(article_keywords, related_news):

    related_text = ' '.join(related_news)

    matches = [kw for kw in article_keywords if kw.lower() in related_text.lower()]

    return int((len(matches) / len(article_keywords)) * 100) if article_keywords else 0


# ---------- GUI ----------

class NewsCheckerApp:

    def __init__(self, root):

        self.root = root

        self.root.title("šŸ•µ️ News Authenticity Checker")


        tk.Label(root, text="Paste News Article URL:").pack()

        self.url_entry = tk.Entry(root, width=60)

        self.url_entry.pack(pady=5)


        tk.Button(root, text="šŸ” Check Authenticity", command=self.check_news).pack(pady=10)


        self.result_label = tk.Label(root, text="", font=("Arial", 12, "bold"))

        self.result_label.pack(pady=20)


    def check_news(self):

        url = self.url_entry.get().strip()

        if not url:

            messagebox.showerror("Error", "Please enter a news URL.")

            return


        try:

            article = Article(url)

            article.download()

            article.parse()

            content = article.text


            article_keywords = extract_keywords(content)

            related_news = fetch_related_news(article_keywords)

            score = calculate_authenticity(article_keywords, related_news)


            result = f"✅ Authenticity Score: {score}%"

            if score < 40:

                result += "\n⚠️ This article may not be widely reported."

            else:

                result += "\nšŸ‘ Seems consistent with other sources."


            self.result_label.config(text=result)


        except Exception as e:

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


# ---------- Run App ----------

if __name__ == "__main__":

    root = tk.Tk()

    app = NewsCheckerApp(root)

    root.mainloop()


PDF Bill Splitter App

 import tkinter as tk

from tkinter import filedialog, messagebox

import fitz  # PyMuPDF

import re

import sqlite3

import os


# ---------- Database Setup ----------

conn = sqlite3.connect('bill_splitter.db')

cursor = conn.cursor()

cursor.execute('''

CREATE TABLE IF NOT EXISTS bills (

    id INTEGER PRIMARY KEY AUTOINCREMENT,

    filename TEXT,

    total_amount REAL,

    per_person REAL,

    roommates TEXT

)

''')

conn.commit()


# ---------- PDF Total Extractor ----------

def extract_total_from_pdf(file_path):

    try:

        doc = fitz.open(file_path)

        text = ""

        for page in doc:

            text += page.get_text()

        doc.close()


        # Try finding the largest ₹/$/Rs. number

        amounts = re.findall(r'[\₹\$\₹Rs\. ]?(\d+[,.]?\d*)', text)

        float_amounts = [float(a.replace(',', '')) for a in amounts]

        return max(float_amounts) if float_amounts else 0.0


    except Exception as e:

        messagebox.showerror("Error", f"Failed to extract total: {str(e)}")

        return 0.0


# ---------- GUI ----------

class BillSplitterApp:

    def __init__(self, root):

        self.root = root

        self.root.title("šŸ“„ PDF Bill Splitter")

        self.filename = None


        # UI Layout

        tk.Button(root, text="šŸ“‚ Upload PDF Bill", command=self.upload_pdf).pack(pady=10)


        self.total_var = tk.StringVar()

        tk.Label(root, text="šŸ’° Total Amount:").pack()

        tk.Entry(root, textvariable=self.total_var, state="readonly").pack(pady=5)


        self.roommates_entry = tk.Entry(root)

        self.roommates_entry.pack(pady=5)

        self.roommates_entry.insert(0, "Enter emails/names comma-separated")


        tk.Button(root, text="➗ Split Bill", command=self.split_bill).pack(pady=10)


    def upload_pdf(self):

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

        if file_path:

            self.filename = os.path.basename(file_path)

            total = extract_total_from_pdf(file_path)

            self.total_var.set(f"{total:.2f}")


    def split_bill(self):

        total = self.total_var.get()

        roommates = self.roommates_entry.get().split(',')


        if not total or not roommates or len(roommates) < 1:

            messagebox.showerror("Error", "Please upload a PDF and enter roommates.")

            return


        try:

            total = float(total)

            per_person = total / len(roommates)

            roommates_clean = [r.strip() for r in roommates]


            # Save to DB

            cursor.execute('''

                INSERT INTO bills (filename, total_amount, per_person, roommates)

                VALUES (?, ?, ?, ?)

            ''', (self.filename, total, per_person, ", ".join(roommates_clean)))

            conn.commit()


            messagebox.showinfo("Success", f"Each roommate pays: ₹{per_person:.2f}")

            self.email_roommates(roommates_clean, per_person)


        except Exception as e:

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


    def email_roommates(self, roommates, amount):

        # Mock email reminder

        for r in roommates:

            print(f"[Email to {r}] Your share: ₹{amount:.2f}")


# ---------- Run ----------

if __name__ == "__main__":

    root = tk.Tk()

    app = BillSplitterApp(root)

    root.mainloop()


Mental Health Journal Analyzer

 import streamlit as st

from textblob import TextBlob

import pandas as pd

import matplotlib.pyplot as plt

from datetime import datetime, timedelta

import os


# CSV to store journal data

DATA_FILE = "journal_data.csv"


# Function to analyze sentiment

def analyze_sentiment(text):

    blob = TextBlob(text)

    return blob.sentiment.polarity  # -1 to 1


# Load data

def load_data():

    if os.path.exists(DATA_FILE):

        return pd.read_csv(DATA_FILE, parse_dates=['date'])

    else:

        return pd.DataFrame(columns=["date", "entry", "sentiment"])


# Save data

def save_data(entry, sentiment):

    new_data = pd.DataFrame({

        "date": [datetime.now().date()],

        "entry": [entry],

        "sentiment": [sentiment]

    })

    data = load_data()

    data = pd.concat([data, new_data], ignore_index=True)

    data.to_csv(DATA_FILE, index=False)


# Weekly sentiment plot

def plot_sentiment(data):

    recent = data[data['date'] >= (datetime.now().date() - timedelta(days=6))]

    daily_avg = recent.groupby('date')['sentiment'].mean().reset_index()


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

    plt.plot(daily_avg['date'], daily_avg['sentiment'], marker='o', linestyle='-')

    plt.title("🧠 Weekly Mental Wellness Trend")

    plt.xlabel("Date")

    plt.ylabel("Sentiment Score")

    plt.ylim(-1, 1)

    plt.axhline(0, color='gray', linestyle='--')

    plt.grid(True)

    st.pyplot(plt)


# ---------------- STREAMLIT APP ----------------


st.set_page_config(page_title="Mental Health Journal Analyzer", layout="centered")

st.title("🧠 Mental Health Journal Analyzer")

st.markdown("Write your daily mood journal and analyze your wellness trend.")


# Input

journal_entry = st.text_area("Write today's journal entry:", height=150)


if st.button("Analyze & Save"):

    if journal_entry.strip():

        sentiment = analyze_sentiment(journal_entry)

        save_data(journal_entry, sentiment)

        st.success(f"Entry saved! Sentiment Score: {sentiment:.2f}")

    else:

        st.warning("Please write something in your journal.")


# Load and plot

data = load_data()

if not data.empty:

    st.subheader("šŸ“Š Weekly Sentiment Trend")

    plot_sentiment(data)