Job Description Keyword Extractor

pip install pymupdf nltk wordcloud

import nltk
nltk.download('punkt')
nltk.download('stopwords')


import fitz  # PyMuPDF
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from wordcloud import WordCloud
import tkinter as tk
from tkinter import filedialog
import matplotlib.pyplot as plt
import string

def extract_text_from_pdf(pdf_path):
    doc = fitz.open(pdf_path)
    text = ""
    for page in doc:
        text += page.get_text()
    return text

def clean_and_tokenize(text):
    # Lowercase, remove punctuation
    text = text.lower().translate(str.maketrans("", "", string.punctuation))
    tokens = word_tokenize(text)

    # Remove stopwords & short words
    stop_words = set(stopwords.words("english"))
    keywords = [word for word in tokens if word not in stop_words and len(word) > 2]
    return keywords

def generate_wordcloud(keywords):
    word_freq = nltk.FreqDist(keywords)
    wordcloud = WordCloud(width=800, height=400, background_color='white').generate_from_frequencies(word_freq)

    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation="bilinear")
    plt.axis("off")
    plt.title("Top Keywords in Job Description", fontsize=16)
    plt.show()

def main():
    # Open file dialog
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(title="Select Job Description PDF", filetypes=[("PDF Files", "*.pdf")])

    if not file_path:
        print("No file selected.")
        return

    print("Processing...")
    text = extract_text_from_pdf(file_path)
    keywords = clean_and_tokenize(text)
    generate_wordcloud(keywords)

    print("\nTop 20 Keywords:")
    for word, freq in nltk.FreqDist(keywords).most_common(20):
        print(f"{word} - {freq}")

if __name__ == "__main__":
    main()

Custom Retro Snake Game with Skins

import pygame

import tkinter as tk

from tkinter import filedialog, simpledialog

from PIL import Image

import os

import random

import sys


# === Constants ===

TILE_SIZE = 20

DEFAULT_GRID = 20

FPS = 10


# === Globals (updated via GUI) ===

snake_head_img_path = "assets/default_head.png"

snake_body_img_path = "assets/default_body.png"

GRID_SIZE = DEFAULT_GRID



def load_skin(path, size):

    img = Image.open(path).resize((size, size)).convert("RGBA")

    return pygame.image.fromstring(img.tobytes(), img.size, img.mode)



def ask_user_inputs():

    global snake_head_img_path, snake_body_img_path, GRID_SIZE


    root = tk.Tk()

    root.withdraw()


    if filedialog.askyesno("Snake Skin", "Do you want to upload custom snake head image?"):

        snake_head_img_path = filedialog.askopenfilename(title="Select Head Image")


    if filedialog.askyesno("Snake Skin", "Do you want to upload custom snake body image?"):

        snake_body_img_path = filedialog.askopenfilename(title="Select Body Image")


    try:

        GRID_SIZE = int(simpledialog.askstring("Grid Size", "Enter grid size (e.g., 20 for 20x20):") or DEFAULT_GRID)

    except:

        GRID_SIZE = DEFAULT_GRID



def draw_grid(screen, color=(40, 40, 40)):

    for x in range(0, GRID_SIZE * TILE_SIZE, TILE_SIZE):

        for y in range(0, GRID_SIZE * TILE_SIZE, TILE_SIZE):

            rect = pygame.Rect(x, y, TILE_SIZE, TILE_SIZE)

            pygame.draw.rect(screen, color, rect, 1)



class Snake:

    def __init__(self):

        self.body = [(5, 5), (4, 5), (3, 5)]

        self.direction = (1, 0)

        self.grow = False


    def move(self):

        head = self.body[0]

        new_head = (head[0] + self.direction[0], head[1] + self.direction[1])

        self.body.insert(0, new_head)

        if not self.grow:

            self.body.pop()

        else:

            self.grow = False


    def change_direction(self, new_dir):

        # Prevent reversing

        if (new_dir[0] * -1, new_dir[1] * -1) != self.direction:

            self.direction = new_dir


    def draw(self, screen, head_img, body_img):

        for i, segment in enumerate(self.body):

            x, y = segment[0] * TILE_SIZE, segment[1] * TILE_SIZE

            if i == 0:

                screen.blit(head_img, (x, y))

            else:

                screen.blit(body_img, (x, y))


    def check_collision(self):

        head = self.body[0]

        return (

            head in self.body[1:] or

            head[0] < 0 or head[1] < 0 or

            head[0] >= GRID_SIZE or head[1] >= GRID_SIZE

        )



def generate_food(snake):

    while True:

        pos = (random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1))

        if pos not in snake.body:

            return pos



def main():

    ask_user_inputs()


    pygame.init()

    screen = pygame.display.set_mode((GRID_SIZE * TILE_SIZE, GRID_SIZE * TILE_SIZE))

    pygame.display.set_caption("šŸ Custom Snake Game")

    clock = pygame.time.Clock()


    head_img = load_skin(snake_head_img_path, TILE_SIZE)

    body_img = load_skin(snake_body_img_path, TILE_SIZE)


    snake = Snake()

    food = generate_food(snake)


    running = True

    while running:

        clock.tick(FPS)

        screen.fill((0, 0, 0))

        draw_grid(screen)


        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                running = False

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_UP:

                    snake.change_direction((0, -1))

                elif event.key == pygame.K_DOWN:

                    snake.change_direction((0, 1))

                elif event.key == pygame.K_LEFT:

                    snake.change_direction((-1, 0))

                elif event.key == pygame.K_RIGHT:

                    snake.change_direction((1, 0))


        snake.move()


        if snake.body[0] == food:

            snake.grow = True

            food = generate_food(snake)


        if snake.check_collision():

            print("Game Over!")

            pygame.quit()

            sys.exit()


        snake.draw(screen, head_img, body_img)

        fx, fy = food[0] * TILE_SIZE, food[1] * TILE_SIZE

        pygame.draw.rect(screen, (255, 0, 0), (fx, fy, TILE_SIZE, TILE_SIZE))


        pygame.display.flip()



if __name__ == "__main__":

    main()


Telegram Bot File Vault

 pip install python-telegram-bot==13.15


import os
import sqlite3
import uuid
import logging
from telegram import Update, File
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

# === Config ===
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
FILES_DIR = "files"
os.makedirs(FILES_DIR, exist_ok=True)

# === Logger ===
logging.basicConfig(level=logging.INFO)

# === Database ===
conn = sqlite3.connect("vault.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
    id TEXT PRIMARY KEY,
    user_id INTEGER,
    file_name TEXT,
    file_path TEXT,
    tags TEXT
)
''')
conn.commit()

# === Command Handlers ===

def start(update: Update, context: CallbackContext):
    update.message.reply_text("šŸ“ Welcome to File Vault Bot!\nSend me a file and add tags in the caption.")

def handle_file(update: Update, context: CallbackContext):
    file = update.message.document or update.message.photo[-1] if update.message.photo else None
    caption = update.message.caption or ""
    tags = caption.strip() if caption else "untagged"
    
    if not file:
        update.message.reply_text("❌ Unsupported file type.")
        return

    file_id = str(uuid.uuid4())
    file_name = file.file_name if hasattr(file, 'file_name') else f"{file_id}.jpg"
    file_path = os.path.join(FILES_DIR, file_name)

    telegram_file: File = context.bot.get_file(file.file_id)
    telegram_file.download(file_path)

    cursor.execute("INSERT INTO files VALUES (?, ?, ?, ?, ?)",
                   (file_id, update.message.from_user.id, file_name, file_path, tags))
    conn.commit()

    update.message.reply_text(f"✅ File saved with ID: {file_id} and tags: {tags}")

def get_file(update: Update, context: CallbackContext):
    if not context.args:
        update.message.reply_text("Usage: /get filename")
        return

    file_name = " ".join(context.args)
    cursor.execute("SELECT file_path FROM files WHERE file_name=?", (file_name,))
    result = cursor.fetchone()

    if result:
        update.message.reply_document(open(result[0], "rb"))
    else:
        update.message.reply_text("❌ File not found.")

def search_by_tag(update: Update, context: CallbackContext):
    if not context.args:
        update.message.reply_text("Usage: /search tag")
        return

    tag = " ".join(context.args)
    cursor.execute("SELECT file_name, tags FROM files")
    results = cursor.fetchall()

    found = [name for name, tags in results if tag.lower() in tags.lower()]
    if found:
        update.message.reply_text("šŸ” Matching files:\n" + "\n".join(found))
    else:
        update.message.reply_text("❌ No matching files.")

# === Main Bot ===

def main():
    updater = Updater(BOT_TOKEN)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("get", get_file))
    dp.add_handler(CommandHandler("search", search_by_tag))
    dp.add_handler(MessageHandler(Filters.document | Filters.photo, handle_file))

    updater.start_polling()
    print("Bot started.")
    updater.idle()

if __name__ == '__main__':
    main()

WhatsApp Chat Analyzer

pip install pandas matplotlib emoji


import re

import emoji

import pandas as pd

import matplotlib.pyplot as plt

from collections import Counter


# Define anger and happy keywords

anger_keywords = ['angry', 'hate', 'stupid', 'idiot', 'mad', 'annoy', 'fight']

happy_keywords = ['happy', 'love', 'joy', 'awesome', 'great', '😊', '😁', 'šŸ˜']


def extract_chat_data(chat_file):

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

        lines = f.readlines()


    chat_data = []

    for line in lines:

        # Match typical WhatsApp line format

        match = re.match(r'^(\d{1,2}/\d{1,2}/\d{2,4}),\s(\d{1,2}:\d{2})\s[-–]\s(.+?):\s(.+)', line)

        if match:

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

            chat_data.append([date, time, sender, message])

    return pd.DataFrame(chat_data, columns=['Date', 'Time', 'Sender', 'Message'])


def count_emojis(text):

    return [char for char in text if char in emoji.EMOJI_DATA]


def analyze_emojis(df):

    emoji_counter = Counter()

    sender_emoji = {}


    for _, row in df.iterrows():

        emojis = count_emojis(row['Message'])

        emoji_counter.update(emojis)

        sender = row['Sender']

        if sender not in sender_emoji:

            sender_emoji[sender] = Counter()

        sender_emoji[sender].update(emojis)

    

    return emoji_counter.most_common(10), sender_emoji


def analyze_mood(df):

    mood_scores = []

    for _, row in df.iterrows():

        message = row['Message'].lower()

        mood = 0

        mood += sum(word in message for word in happy_keywords)

        mood -= sum(word in message for word in anger_keywords)

        mood_scores.append(mood)

    df['MoodScore'] = mood_scores

    return df


def plot_top_emoji_users(sender_emoji):

    emoji_counts = {sender: sum(emojis.values()) for sender, emojis in sender_emoji.items()}

    users = list(emoji_counts.keys())

    counts = list(emoji_counts.values())


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

    plt.bar(users, counts, color='teal')

    plt.title("Emoji Usage by User")

    plt.ylabel("Total Emojis Used")

    plt.xticks(rotation=45)

    plt.tight_layout()

    plt.show()


def plot_mood_over_time(df):

    mood_by_day = df.groupby("Date")["MoodScore"].sum()

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

    mood_by_day.plot(kind="line", marker="o", color="purple")

    plt.title("Mood Trend Over Time")

    plt.xlabel("Date")

    plt.ylabel("Mood Score")

    plt.xticks(rotation=45)

    plt.tight_layout()

    plt.show()


if __name__ == "__main__":

    chat_file = "chat.txt"  # exported WhatsApp chat file

    df = extract_chat_data(chat_file)


    df = analyze_mood(df)

    top_emojis, sender_emoji = analyze_emojis(df)


    print("\nšŸ” Top Emojis Used:")

    for emo, count in top_emojis:

        print(f"{emo}: {count}")


    print("\nšŸ™‹‍♂️ Emoji Usage by Users:")

    for sender, emojis in sender_emoji.items():

        print(f"{sender}: {sum(emojis.values())} emojis")


    plot_top_emoji_users(sender_emoji)

    plot_mood_over_time(df)

 

File Compression Tool

pip install pyminizip

import tkinter as tk
from tkinter import filedialog, messagebox
import os
import zipfile
import pyminizip

class FileCompressorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("File Compression Tool šŸ—œ️")
        self.root.geometry("450x300")
        self.files = []

        self.label = tk.Label(root, text="Drag and Drop Files or Use 'Browse'", font=("Helvetica", 12))
        self.label.pack(pady=10)

        self.file_listbox = tk.Listbox(root, width=50, height=8)
        self.file_listbox.pack()

        self.browse_button = tk.Button(root, text="Browse Files", command=self.browse_files)
        self.browse_button.pack(pady=5)

        self.password_label = tk.Label(root, text="Password (optional):")
        self.password_label.pack()
        self.password_entry = tk.Entry(root, show="*")
        self.password_entry.pack(pady=2)

        self.compress_button = tk.Button(root, text="Compress to ZIP", command=self.compress_files)
        self.compress_button.pack(pady=10)

    def browse_files(self):
        paths = filedialog.askopenfilenames()
        for path in paths:
            if path not in self.files:
                self.files.append(path)
                self.file_listbox.insert(tk.END, path)

    def compress_files(self):
        if not self.files:
            messagebox.showerror("No Files", "Please select files to compress.")
            return

        zip_path = filedialog.asksaveasfilename(defaultextension=".zip", filetypes=[("ZIP files", "*.zip")])
        if not zip_path:
            return

        password = self.password_entry.get()

        try:
            if password:
                # Use pyminizip for password protection
                compression_level = 5
                pyminizip.compress_multiple(self.files, [], zip_path, password, compression_level)
            else:
                # Use zipfile for normal compression
                with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
                    for file in self.files:
                        arcname = os.path.basename(file)
                        zipf.write(file, arcname)

            messagebox.showinfo("Success", f"Files compressed successfully to:\n{zip_path}")
        except Exception as e:
            messagebox.showerror("Error", f"Compression failed:\n{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = FileCompressorApp(root)
    root.mainloop()