System Cleanup Scheduler

import os

import shutil

import hashlib

import schedule

import time

from datetime import datetime, timedelta


# === CONFIG ===

TEMP_DIRS = ["temp"]

LOG_DIRS = ["logs"]

DUPLICATE_SCAN_DIRS = ["temp", "logs"]

LOG_EXPIRY_DAYS = 7


# === 1. Delete temp files ===

def clean_temp_folders():

    print("๐Ÿงน Cleaning temp folders...")

    for folder in TEMP_DIRS:

        for filename in os.listdir(folder):

            file_path = os.path.join(folder, filename)

            try:

                if os.path.isfile(file_path) or os.path.islink(file_path):

                    os.remove(file_path)

                    print(f"Deleted file: {file_path}")

                elif os.path.isdir(file_path):

                    shutil.rmtree(file_path)

                    print(f"Deleted folder: {file_path}")

            except Exception as e:

                print(f"❌ Failed to delete {file_path}: {e}")


# === 2. Delete old logs ===

def delete_old_logs():

    print("๐Ÿ“ Deleting old logs...")

    for folder in LOG_DIRS:

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

            for file in files:

                file_path = os.path.join(root, file)

                try:

                    file_time = datetime.fromtimestamp(os.path.getmtime(file_path))

                    if datetime.now() - file_time > timedelta(days=LOG_EXPIRY_DAYS):

                        os.remove(file_path)

                        print(f"๐Ÿ—‘️ Removed old log: {file_path}")

                except Exception as e:

                    print(f"❌ Error checking {file_path}: {e}")


# === 3. Delete duplicate files ===

def delete_duplicates():

    print("๐Ÿ” Searching for duplicates...")

    hashes = {}

    for folder in DUPLICATE_SCAN_DIRS:

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

            for file in files:

                path = os.path.join(root, file)

                try:

                    with open(path, 'rb') as f:

                        file_hash = hashlib.md5(f.read()).hexdigest()

                    if file_hash in hashes:

                        os.remove(path)

                        print(f"❌ Duplicate removed: {path}")

                    else:

                        hashes[file_hash] = path

                except Exception as e:

                    print(f"❌ Error reading {path}: {e}")


# === 4. Master cleanup function ===

def run_cleanup():

    print(f"\n๐Ÿ”ง Running system cleanup @ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    clean_temp_folders()

    delete_old_logs()

    delete_duplicates()

    print("✅ Cleanup complete.")


# === 5. Scheduler ===

schedule.every().sunday.at("08:00").do(run_cleanup)


print("๐Ÿ•’ System Cleanup Scheduler started... (Press Ctrl+C to exit)")

run_cleanup()  # Run once on start


while True:

    schedule.run_pending()

    time.sleep(60)


Book Cover & Title Generator

import random

from faker import Faker

from PIL import Image, ImageDraw, ImageFont

import os

import openai


# === CONFIG ===

OUTPUT_FOLDER = "covers"

os.makedirs(OUTPUT_FOLDER, exist_ok=True)

fake = Faker()


# Optional: Set your OpenAI API Key

openai.api_key = "YOUR_API_KEY"  # Replace with your key


# === 1. Generate Book Title ===

def generate_book_title(prompt=None):

    if prompt:

        response = openai.ChatCompletion.create(

            model="gpt-4",

            messages=[{"role": "user", "content": prompt}],

            max_tokens=30

        )

        return response['choices'][0]['message']['content'].strip()

    else:

        adjectives = ["Lost", "Silent", "Hidden", "Broken", "Eternal"]

        nouns = ["Dream", "Kingdom", "Secret", "Shadow", "Memory"]

        return f"The {random.choice(adjectives)} {random.choice(nouns)}"


# === 2. Generate Author Name ===

def generate_author_name():

    return fake.name()


# === 3. Generate Cover Image ===

def generate_cover_image(title, author, background="background.jpg"):

    WIDTH, HEIGHT = 600, 900

    cover = Image.new("RGB", (WIDTH, HEIGHT), "white")


    try:

        bg = Image.open(background).resize((WIDTH, HEIGHT))

        cover.paste(bg)

    except:

        print("⚠️ No background image found. Using plain white.")


    draw = ImageDraw.Draw(cover)


    try:

        title_font = ImageFont.truetype("arial.ttf", 40)

        author_font = ImageFont.truetype("arial.ttf", 30)

    except:

        title_font = ImageFont.load_default()

        author_font = ImageFont.load_default()


    # Draw title

    draw.text((40, HEIGHT // 3), title, font=title_font, fill="black", spacing=2)


    # Draw author

    draw.text((40, HEIGHT // 3 + 100), f"by {author}", font=author_font, fill="darkgray")


    filename = os.path.join(OUTPUT_FOLDER, f"{title[:20].replace(' ', '_')}.png")

    cover.save(filename)

    print(f"✅ Cover saved to: {filename}")


# === MAIN ===

if __name__ == "__main__":

    print("๐Ÿ“š Generating random book cover...")

    # title = generate_book_title("Suggest a fantasy book title")

    title = generate_book_title()

    author = generate_author_name()


    print(f"Title: {title}")

    print(f"Author: {author}")


    generate_cover_image(title, author)


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