AI Chat Summarizer for WhatsApp

import re

import pandas as pd

import matplotlib.pyplot as plt

from textblob import TextBlob

from collections import Counter

from datetime import datetime

import os


# ========== CONFIG ==========

CHAT_FILE = "chat.txt"

PLOTS_FOLDER = "chat_analysis_plots"

os.makedirs(PLOTS_FOLDER, exist_ok=True)


# ========== 1. Parse WhatsApp Chat ==========

def parse_chat(file_path):

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

        raw_text = f.readlines()


    messages = []

    pattern = r'^(\d{1,2}/\d{1,2}/\d{2,4}), (\d{1,2}:\d{2}) (AM|PM|am|pm)? - ([^:]+): (.*)'


    for line in raw_text:

        match = re.match(pattern, line)

        if match:

            date, time, am_pm, sender, message = match.groups()

            dt = datetime.strptime(date + " " + time + (" " + am_pm if am_pm else ""), "%d/%m/%Y %I:%M %p")

            messages.append([dt, sender.strip(), message.strip()])

    

    df = pd.DataFrame(messages, columns=["datetime", "sender", "message"])

    return df


# ========== 2. Sentiment & Stats ==========

def analyze_sentiments(df):

    df['polarity'] = df['message'].apply(lambda x: TextBlob(x).sentiment.polarity)

    df['sentiment'] = df['polarity'].apply(lambda x: 'positive' if x > 0.1 else 'negative' if x < -0.1 else 'neutral')

    return df


def top_senders(df, top_n=5):

    return df['sender'].value_counts().head(top_n)


# ========== 3. Plotting Functions ==========

def plot_message_frequency(df):

    df['date'] = df['datetime'].dt.date

    daily_counts = df.groupby('date').size()


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

    daily_counts.plot(kind='line', color='teal')

    plt.title("Messages Per Day")

    plt.xlabel("Date")

    plt.ylabel("Number of Messages")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/messages_per_day.png")

    plt.close()


def plot_sender_activity(df):

    sender_counts = df['sender'].value_counts()

    sender_counts.plot(kind='bar', figsize=(10,5), color='orchid')

    plt.title("Messages by Sender")

    plt.ylabel("Message Count")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/messages_by_sender.png")

    plt.close()


def plot_sentiment_distribution(df):

    sentiment_counts = df['sentiment'].value_counts()

    sentiment_counts.plot(kind='pie', autopct='%1.1f%%', figsize=(6,6), colors=['lightgreen', 'lightcoral', 'lightgrey'])

    plt.title("Sentiment Distribution")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/sentiment_distribution.png")

    plt.close()


# ========== 4. Generate Summary ==========

def generate_summary(df):

    summary = []

    summary.append(f"Total messages: {len(df)}")

    summary.append(f"Total participants: {df['sender'].nunique()}")

    summary.append("Top 5 active senders:")

    summary.extend(top_senders(df).to_string().split('\n'))


    sentiment_split = df['sentiment'].value_counts(normalize=True) * 100

    summary.append("\nSentiment Breakdown:")

    summary.extend(sentiment_split.round(2).to_string().split('\n'))


    with open("summary_output.txt", "w") as f:

        f.write("\n".join(summary))

    

    return "\n".join(summary)


# ========== MAIN ==========

if __name__ == "__main__":

    print("šŸ“„ Parsing chat...")

    df = parse_chat(CHAT_FILE)


    print("🧠 Analyzing sentiments...")

    df = analyze_sentiments(df)


    print("šŸ“Š Generating plots...")

    plot_message_frequency(df)

    plot_sender_activity(df)

    plot_sentiment_distribution(df)


    print("šŸ“ Writing summary...")

    summary_text = generate_summary(df)

    print(summary_text)


    print("\n✅ Done! Plots saved to 'chat_analysis_plots' and summary to 'summary_output.txt'")


Auto Meeting Notes Generator

import os

import re

import pandas as pd

import whisper

from datetime import datetime


# Optional: For GPT-4 summarization

import openai

from dotenv import load_dotenv


load_dotenv()

openai.api_key = os.getenv("OPENAI_API_KEY")


# ========== CONFIG ==========

AUDIO_FOLDER = "audio"

TRANSCRIPT_FOLDER = "transcriptions"

NOTES_FOLDER = "notes_output"


# ========== SETUP ==========

os.makedirs(TRANSCRIPT_FOLDER, exist_ok=True)

os.makedirs(NOTES_FOLDER, exist_ok=True)


# ========== 1. Transcribe Audio ==========

def transcribe_audio(file_path, model_name="base"):

    model = whisper.load_model(model_name)

    result = model.transcribe(file_path)

    

    filename = os.path.basename(file_path).split('.')[0]

    output_path = os.path.join(TRANSCRIPT_FOLDER, f"{filename}.txt")

    

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

        f.write(result["text"])

    

    return result["text"]


# ========== 2. Extract Action Items ==========

def extract_action_items(text):

    bullet_pattern = r"(?:-|\*|\d\.)\s*(.+)"

    action_keywords = ["should", "need to", "must", "let's", "we will", "assign", "follow up", "due"]


    actions = []

    for line in text.split('\n'):

        line = line.strip()

        if any(keyword in line.lower() for keyword in action_keywords):

            actions.append(line)


    # Fallback: try extracting bullets

    bullets = re.findall(bullet_pattern, text)

    for b in bullets:

        if any(k in b.lower() for k in action_keywords):

            actions.append(b)

    

    return list(set(actions))


# ========== 3. Summarize with GPT (Optional) ==========

def summarize_with_gpt(transcript_text):

    response = openai.ChatCompletion.create(

        model="gpt-4-turbo",

        messages=[

            {"role": "system", "content": "You are an AI assistant that summarizes meeting transcripts."},

            {"role": "user", "content": f"Summarize this meeting:\n\n{transcript_text}"}

        ]

    )

    return response['choices'][0]['message']['content']


# ========== 4. Save Final Notes ==========

def save_notes(transcript, actions, summary=None, filename="meeting_notes"):

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

    csv_path = os.path.join(NOTES_FOLDER, f"{filename}_{now}.csv")


    df = pd.DataFrame({

        "Section": ["Transcript", "Action Items", "Summary"],

        "Content": [transcript, "\n".join(actions), summary or "Not generated"]

    })

    df.to_csv(csv_path, index=False)

    print(f"[✔] Notes saved to {csv_path}")


# ========== MAIN ==========

def process_meeting(file_path, use_gpt=False):

    print(f"šŸ”Š Transcribing: {file_path}")

    transcript = transcribe_audio(file_path)


    print("✅ Extracting action items...")

    actions = extract_action_items(transcript)


    summary = None

    if use_gpt:

        print("šŸ¤– Summarizing with GPT...")

        summary = summarize_with_gpt(transcript)


    file_name = os.path.basename(file_path).split('.')[0]

    save_notes(transcript, actions, summary, file_name)



# ========== RUN ==========

if __name__ == "__main__":

    audio_files = [f for f in os.listdir(AUDIO_FOLDER) if f.endswith(('.mp3', '.wav'))]


    if not audio_files:

        print("⚠️ No audio files found in /audio folder.")

    else:

        for file in audio_files:

            process_meeting(os.path.join(AUDIO_FOLDER, file), use_gpt=True)


Retro Arcade Game Emulator Launcher

import tkinter as tk

from tkinter import messagebox, filedialog

import os

import subprocess

import sqlite3


# ===== Emulator Configuration =====

EMULATOR_PATH = "emulator.exe"  # Update with actual emulator exe

ROMS_FOLDER = "roms"


# ===== Database Setup =====

def init_db():

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

    cur = conn.cursor()

    cur.execute('''

        CREATE TABLE IF NOT EXISTS favorites (

            id INTEGER PRIMARY KEY,

            rom TEXT UNIQUE

        )

    ''')

    conn.commit()

    conn.close()


def add_favorite(rom):

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

    cur = conn.cursor()

    try:

        cur.execute("INSERT INTO favorites (rom) VALUES (?)", (rom,))

        conn.commit()

    except sqlite3.IntegrityError:

        pass

    conn.close()


def remove_favorite(rom):

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

    cur = conn.cursor()

    cur.execute("DELETE FROM favorites WHERE rom=?", (rom,))

    conn.commit()

    conn.close()


def get_favorites():

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

    cur = conn.cursor()

    cur.execute("SELECT rom FROM favorites")

    favs = [row[0] for row in cur.fetchall()]

    conn.close()

    return favs


# ===== Launcher GUI =====

class GameLauncher:

    def __init__(self, root):

        self.root = root

        self.root.title("šŸŽ® Retro Arcade Launcher")

        self.root.geometry("500x500")


        self.favorites = get_favorites()


        self.label = tk.Label(root, text="Available Games", font=("Arial", 14, "bold"))

        self.label.pack(pady=10)


        self.listbox = tk.Listbox(root, width=50, height=20)

        self.populate_list()

        self.listbox.pack()


        btn_frame = tk.Frame(root)

        btn_frame.pack(pady=10)


        tk.Button(btn_frame, text="▶️ Play", command=self.launch_game).grid(row=0, column=0, padx=5)

        tk.Button(btn_frame, text="⭐ Add Fav", command=self.add_to_favorites).grid(row=0, column=1, padx=5)

        tk.Button(btn_frame, text="❌ Remove Fav", command=self.remove_from_favorites).grid(row=0, column=2, padx=5)

        tk.Button(btn_frame, text="šŸ” Refresh", command=self.refresh).grid(row=0, column=3, padx=5)


    def populate_list(self):

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

        if not os.path.exists(ROMS_FOLDER):

            os.makedirs(ROMS_FOLDER)


        files = [f for f in os.listdir(ROMS_FOLDER) if f.endswith((".nes", ".gba"))]

        for f in files:

            label = f + (" ⭐" if f in self.favorites else "")

            self.listbox.insert(tk.END, label)


    def get_selected_rom(self):

        try:

            selected = self.listbox.get(tk.ACTIVE)

            return selected.replace(" ⭐", "")

        except:

            return None


    def launch_game(self):

        rom = self.get_selected_rom()

        if not rom:

            messagebox.showwarning("No Selection", "Please select a game.")

            return


        rom_path = os.path.join(ROMS_FOLDER, rom)

        if not os.path.exists(EMULATOR_PATH):

            messagebox.showerror("Emulator Not Found", "Update the emulator path in the code.")

            return


        subprocess.Popen([EMULATOR_PATH, rom_path])

        print(f"Launching {rom}...")


    def add_to_favorites(self):

        rom = self.get_selected_rom()

        if rom:

            add_favorite(rom)

            self.refresh()


    def remove_from_favorites(self):

        rom = self.get_selected_rom()

        if rom:

            remove_favorite(rom)

            self.refresh()


    def refresh(self):

        self.favorites = get_favorites()

        self.populate_list()


# === Main ===

if __name__ == "__main__":

    init_db()

    root = tk.Tk()

    app = GameLauncher(root)

    root.mainloop()


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)