Text-to-World Map

pip install geopy folium nltk

import folium
from geopy.geocoders import Nominatim
import nltk
import re

from nltk import word_tokenize, pos_tag, ne_chunk
from nltk.tree import Tree

nltk.download("punkt")
nltk.download("averaged_perceptron_tagger")
nltk.download("maxent_ne_chunker")
nltk.download("words")


def extract_locations(text):
    """
    Extracts named entities (like countries/cities) using NLTK.
    """
    locations = set()
    tokens = word_tokenize(text)
    pos_tags = pos_tag(tokens)
    chunks = ne_chunk(pos_tags)

    for chunk in chunks:
        if isinstance(chunk, Tree) and chunk.label() == "GPE":
            name = " ".join(c[0] for c in chunk.leaves())
            locations.add(name)
    return list(locations)


def geocode_locations(location_names):
    """
    Uses geopy to convert place names into latitude and longitude.
    """
    geolocator = Nominatim(user_agent="world_map_app")
    geo_data = []

    for name in location_names:
        try:
            location = geolocator.geocode(name)
            if location:
                geo_data.append({
                    "name": name,
                    "lat": location.latitude,
                    "lon": location.longitude
                })
        except Exception as e:
            print(f"Geocoding error for {name}: {e}")

    return geo_data


def create_world_map(locations):
    """
    Create a world map using folium with markers on identified locations.
    """
    m = folium.Map(location=[20, 0], zoom_start=2)

    for loc in locations:
        folium.Marker(
            location=[loc["lat"], loc["lon"]],
            popup=loc["name"],
            icon=folium.Icon(color="blue", icon="info-sign")
        ).add_to(m)

    m.save("world_map.html")
    print("✅ Map saved to world_map.html")


# --------- MAIN FUNCTIONALITY ---------

if __name__ == "__main__":
    print("Paste your text below (press Enter twice to end input):")
    lines = []
    while True:
        line = input()
        if line.strip() == "":
            break
        lines.append(line)

    input_text = "\n".join(lines)

    places = extract_locations(input_text)
    print(f"📍 Places Found: {places}")

    coords = geocode_locations(places)
    create_world_map(coords)

Memory Trainer App

pip install playsound


import tkinter as tk
import random
import time
from threading import Thread
from playsound import playsound

# Constants
PATTERN_LENGTH = 5
DELAY_SECONDS = 3

class MemoryTrainer:
    def __init__(self, root):
        self.root = root
        self.root.title("🧠 Memory Trainer")
        self.root.geometry("400x300")
        self.pattern = []

        self.label = tk.Label(root, text="Click Start to Begin", font=("Arial", 16))
        self.label.pack(pady=30)

        self.start_button = tk.Button(root, text="Start", command=self.start_game, font=("Arial", 14))
        self.start_button.pack()

        self.input_entry = tk.Entry(root, font=("Arial", 14))
        self.submit_button = tk.Button(root, text="Submit", command=self.check_answer, font=("Arial", 12))

        self.feedback = tk.Label(root, text="", font=("Arial", 14), fg="blue")
        self.feedback.pack(pady=10)

    def start_game(self):
        self.pattern = [random.randint(0, 9) for _ in range(PATTERN_LENGTH)]
        self.label.config(text=f"Memorize: {' '.join(map(str, self.pattern))}")
        self.feedback.config(text="")
        self.start_button.config(state=tk.DISABLED)
        self.root.after(DELAY_SECONDS * 1000, self.show_input)

        # Optional sound cue
        Thread(target=lambda: playsound("ding.mp3")).start()  # Replace with a valid sound path

    def show_input(self):
        self.label.config(text="Now enter the pattern:")
        self.input_entry.pack()
        self.submit_button.pack()

    def check_answer(self):
        user_input = self.input_entry.get().strip().split()
        try:
            user_pattern = list(map(int, user_input))
            if user_pattern == self.pattern:
                self.feedback.config(text="✅ Correct!", fg="green")
            else:
                self.feedback.config(text=f"❌ Wrong! Pattern was: {' '.join(map(str, self.pattern))}", fg="red")
        except ValueError:
            self.feedback.config(text="⚠️ Please enter valid numbers.", fg="orange")

        self.input_entry.delete(0, tk.END)
        self.start_button.config(state=tk.NORMAL)
        self.input_entry.pack_forget()
        self.submit_button.pack_forget()

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

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