Website Availability & Uptime Tracker

 import requests

import schedule

import time

import smtplib

from email.mime.text import MIMEText


# List of websites to track

websites = {

    "Google": "https://www.google.com",

    "My Portfolio": "https://yourportfolio.com"

}


# Email Config

EMAIL_ADDRESS = "your_email@gmail.com"

EMAIL_PASSWORD = "your_app_password"

TO_EMAIL = "recipient_email@example.com"


def send_email_alert(site):

    msg = MIMEText(f"Alert: {site} is DOWN!")

    msg["Subject"] = f"๐Ÿšจ {site} is Down!"

    msg["From"] = EMAIL_ADDRESS

    msg["To"] = TO_EMAIL


    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:

        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

        smtp.send_message(msg)

        print(f"Email sent: {site} is down.")


def check_sites():

    for name, url in websites.items():

        try:

            response = requests.get(url, timeout=5)

            if response.status_code != 200:

                print(f"[{name}] Status: {response.status_code}")

                send_email_alert(name)

            else:

                print(f"[{name}] is up ✅")

        except requests.exceptions.RequestException:

            print(f"[{name}] is unreachable ❌")

            send_email_alert(name)


# Check every 5 minutes

schedule.every(5).minutes.do(check_sites)


print("๐Ÿ” Website Uptime Tracker Started...")

while True:

    schedule.run_pending()

    time.sleep(1)



Twilio SMS Integration


from twilio.rest import Client

account_sid = "your_sid"
auth_token = "your_token"
twilio_number = "+1234567890"
receiver_number = "+91999xxxxxxx"

def send_sms_alert(site):
    client = Client(account_sid, auth_token)
    client.messages.create(
        body=f"๐Ÿšจ {site} is DOWN!",
        from_=twilio_number,
        to=receiver_number
    )

Document Similarity Checker

 import streamlit as st

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import cosine_similarity

import spacy


nlp = spacy.load("en_core_web_sm")


st.title("๐Ÿ“„ Document Similarity Checker")


def preprocess(text):

    doc = nlp(text)

    return " ".join([token.lemma_ for token in doc if not token.is_stop and token.is_alpha])


file1 = st.file_uploader("Upload First Document", type=["txt"])

file2 = st.file_uploader("Upload Second Document", type=["txt"])


if file1 and file2:

    text1 = file1.read().decode("utf-8")

    text2 = file2.read().decode("utf-8")


    clean_text1 = preprocess(text1)

    clean_text2 = preprocess(text2)


    tfidf = TfidfVectorizer()

    tfidf_matrix = tfidf.fit_transform([clean_text1, clean_text2])

    sim_score = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]


    st.subheader("๐Ÿงฎ Similarity Score")

    st.write(f"**{sim_score:.2f}** (1 = identical, 0 = completely different)")


    if sim_score > 0.75:

        st.success("The documents are quite similar! ๐ŸŸข")

    elif sim_score > 0.4:

        st.info("The documents are moderately similar. ๐ŸŸก")

    else:

        st.warning("The documents are quite different. ๐Ÿ”ด")


Smart Calendar CLI App

 import click

import requests

from datetime import datetime, timedelta


# Placeholder for real GCal and weather integration

EVENTS = [

    {"title": "Standup Meeting", "time": "10:00", "date": "2025-04-16", "location": "Remote"},

    {"title": "Doctor Appointment", "time": "15:00", "date": "2025-04-16", "location": "City Clinic"},

]


@click.group()

def cli():

    pass


@cli.command()

def today():

    click.echo("๐Ÿ“… Today's Events:")

    today = datetime.today().strftime('%Y-%m-%d')

    for e in EVENTS:

        if e["date"] == today:

            click.echo(f"- {e['time']}: {e['title']} ๐Ÿ“ {e['location']}")


@cli.command()

@click.option('--title', prompt='Event title')

@click.option('--date', prompt='Event date (YYYY-MM-DD)')

@click.option('--time', prompt='Event time (HH:MM)')

@click.option('--location', prompt='Event location')

def add(title, date, time, location):

    EVENTS.append({"title": title, "date": date, "time": time, "location": location})

    click.echo("✅ Event created successfully!")


@cli.command()

def forecast():

    if not EVENTS:

        click.echo("No events to check weather for.")

        return

    event = EVENTS[-1]

    click.echo(f"๐ŸŒฆ Forecast for: {event['title']}")

    weather = get_weather(event['location'])

    click.echo(f"๐Ÿ“ Location: {event['location']} | Date: {event['date']}")

    click.echo(f"☁️ Weather Forecast: {weather}")


def get_weather(city):

    API_KEY = "your_openweathermap_api_key"

    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

    r = requests.get(url)

    if r.status_code == 200:

        data = r.json()

        return f"{data['weather'][0]['main']}, {data['main']['temp']}°C"

    return "Weather data unavailable"


if __name__ == '__main__':

    cli()


Voice-Controlled Notes App

import speech_recognition as sr

import pyttsx3

import os


notes = {}


engine = pyttsx3.init()


def speak(text):

    engine.say(text)

    engine.runAndWait()


def listen_command():

    r = sr.Recognizer()

    with sr.Microphone() as source:

        speak("Listening...")

        audio = r.listen(source)

    try:

        command = r.recognize_google(audio)

        return command.lower()

    except:

        speak("Sorry, I didn't catch that.")

        return ""


def create_note():

    speak("What should I name the note?")

    title = listen_command()

    speak("What is the content?")

    content = listen_command()

    notes[title] = content

    speak(f"Note '{title}' created.")


def read_notes():

    if notes:

        for title, content in notes.items():

            speak(f"{title}: {content}")

    else:

        speak("No notes found.")


def delete_note():

    speak("Which note should I delete?")

    title = listen_command()

    if title in notes:

        del notes[title]

        speak(f"Note '{title}' deleted.")

    else:

        speak("Note not found.")


def main():

    speak("Voice Notes App Started.")

    while True:

        speak("Say a command: create, read, delete, or exit.")

        command = listen_command()


        if "create" in command:

            create_note()

        elif "read" in command:

            read_notes()

        elif "delete" in command:

            delete_note()

        elif "exit" in command:

            speak("Goodbye!")

            break

        else:

            speak("Unknown command.")


if __name__ == "__main__":

    main()


Chemistry Molecule Visualizer

 import streamlit as st

from rdkit import Chem

from rdkit.Chem import Draw, Descriptors

import py3Dmol


def mol_to_3d_view(smiles):

    mol = Chem.MolFromSmiles(smiles)

    mb = Chem.AddHs(mol)

    Chem.EmbedMolecule(mb)

    mol_block = Chem.MolToMolBlock(mb)


    viewer = py3Dmol.view(width=400, height=400)

    viewer.addModel(mol_block, 'mol')

    viewer.setStyle({'stick': {}})

    viewer.zoomTo()

    return viewer


st.title("๐Ÿงช Chemistry Molecule Visualizer")


smiles = st.text_input("Enter SMILES string", "CC(=O)O")  # Acetic Acid


if smiles:

    mol = Chem.MolFromSmiles(smiles)

    

    if mol:

        st.subheader("๐Ÿ“Œ Molecular Structure (2D)")

        st.image(Draw.MolToImage(mol, size=(300, 300)))


        st.subheader("๐Ÿ”ฌ Properties")

        st.markdown(f"**Formula**: {Chem.rdMolDescriptors.CalcMolFormula(mol)}")

        st.markdown(f"**Molecular Weight**: {Descriptors.MolWt(mol):.2f} g/mol")


        st.subheader("๐Ÿงฌ 3D Structure")

        viewer = mol_to_3d_view(smiles)

        viewer_html = viewer._make_html()

        st.components.v1.html(viewer_html, height=450)

    else:

        st.error("Invalid SMILES string. Try again.")


Receipt Text Extractor & Analyzer

 OCR using pytesseract

from PIL import Image

import pytesseract


def extract_text_from_image(image_path):

    image = Image.open(image_path)

    text = pytesseract.image_to_string(image)

    return text

Parse Items and Prices with re

import re

def parse_items(raw_text):
    # Match lines like: "Bread 2.50" or "Milk ....... 1.25"
    pattern = r"([A-Za-z\s]+)\s+([\d]+\.\d{2})"
    matches = re.findall(pattern, raw_text)
    
    items = [{"item": item.strip(), "price": float(price)} for item, price in matches]
    
    total = sum(i["price"] for i in items)
    avg = total / len(items) if items else 0
    
    return items, total, avg

(Optional) Step 3: Streamlit Interface


import streamlit as st
from utils.text_parser import extract_text_from_image, parse_items
import tempfile
import pandas as pd

st.title("๐Ÿงพ Receipt Text Extractor & Analyzer")
uploaded_file = st.file_uploader("Upload Receipt Image", type=["jpg", "png", "jpeg"])

if uploaded_file:
    with tempfile.NamedTemporaryFile(delete=False) as tmp:
        tmp.write(uploaded_file.read())
        tmp_path = tmp.name

    raw_text = extract_text_from_image(tmp_path)
    items, total, avg = parse_items(raw_text)

    df = pd.DataFrame(items)
    st.subheader("๐Ÿ›’ Items Detected:")
    st.table(df)

    st.markdown(f"**Total Cost:** ₹{total:.2f}")
    st.markdown(f"**Average Item Cost:** ₹{avg:.2f}")

    # Download as CSV
    csv = df.to_csv(index=False).encode()
    st.download_button("๐Ÿ“ฅ Download CSV", csv, "receipt_data.csv", "text/csv")

Music Genre Classifier

 # utils/feature_extractor.py

import librosa

import numpy as np


def extract_features(file_path):

    y, sr = librosa.load(file_path, duration=30)

    mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)

    mfccs_mean = np.mean(mfccs.T, axis=0)

    return mfccs_mean


from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import joblib

# Load features (extracted previously)
df = pd.read_csv("features_dataset.csv")  # Your dataset with MFCC + genre
X = df.drop('genre', axis=1)
y = df['genre']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

clf = RandomForestClassifier()
clf.fit(X_train, y_train)

# Save model
joblib.dump(clf, "model/genre_model.pkl")


# app.py
import streamlit as st
import joblib
import numpy as np
from utils.feature_extractor import extract_features
import tempfile

# Load model
model = joblib.load("model/genre_model.pkl")

st.title("๐ŸŽต Music Genre Classifier")
st.write("Upload a music file to predict its genre")

uploaded_file = st.file_uploader("Choose a file", type=["mp3", "wav"])

if uploaded_file:
    # Save temporarily
    with tempfile.NamedTemporaryFile(delete=False) as tmp:
        tmp.write(uploaded_file.read())
        tmp_path = tmp.name

    # Extract features and predict
    features = extract_features(tmp_path)
    prediction = model.predict([features])[0]
    proba = model.predict_proba([features])

    st.success(f"Predicted Genre: **{prediction}**")
    st.bar_chart(proba[0])

Custom Dictionary Builder

 db.py

import sqlite3


def init_db():

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

    cursor = conn.cursor()

    cursor.execute('''CREATE TABLE IF NOT EXISTS dictionary (

                        id INTEGER PRIMARY KEY AUTOINCREMENT,

                        word TEXT,

                        language TEXT,

                        meaning TEXT,

                        synonyms TEXT,

                        audio_file TEXT)''')

    conn.commit()

    conn.close()


def add_word(word, lang, meaning, synonyms, audio_file):

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

    cursor = conn.cursor()

    cursor.execute("INSERT INTO dictionary (word, language, meaning, synonyms, audio_file) VALUES (?, ?, ?, ?, ?)",

                   (word, lang, meaning, synonyms, audio_file))

    conn.commit()

    conn.close()


def search_word(word):

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

    cursor = conn.cursor()

    cursor.execute("SELECT * FROM dictionary WHERE word = ?", (word,))

    result = cursor.fetchone()

    conn.close()

    return result

tts.py

from gtts import gTTS

import os


def generate_audio(word, lang='en'):

    tts = gTTS(text=word, lang=lang)

    audio_file = f"audio/{word}_{lang}.mp3"

    tts.save(audio_file)

    return audio_file

app.py

import tkinter as tk

from db import init_db, add_word, search_word

from tts import generate_audio

import os

from playsound import playsound


init_db()


def submit_word():

    word = entry_word.get()

    lang = entry_lang.get()

    meaning = entry_meaning.get()

    synonyms = entry_synonyms.get()

    audio_path = generate_audio(word, lang)

    add_word(word, lang, meaning, synonyms, audio_path)

    label_status.config(text="✅ Word added!")


def play_audio():

    word = entry_word.get()

    result = search_word(word)

    if result and os.path.exists(result[5]):

        playsound(result[5])

    else:

        label_status.config(text="❌ Audio not found.")


# GUI Setup

window = tk.Tk()

window.title("๐Ÿ“š Custom Dictionary Builder")

window.geometry("400x400")


entry_word = tk.Entry(window)

entry_word.insert(0, "Word")

entry_word.pack(pady=5)


entry_lang = tk.Entry(window)

entry_lang.insert(0, "Language Code (e.g., en, es)")

entry_lang.pack(pady=5)


entry_meaning = tk.Entry(window)

entry_meaning.insert(0, "Meaning")

entry_meaning.pack(pady=5)


entry_synonyms = tk.Entry(window)

entry_synonyms.insert(0, "Synonyms")

entry_synonyms.pack(pady=5)


tk.Button(window, text="Add Word", command=submit_word).pack(pady=10)

tk.Button(window, text="Play Pronunciation", command=play_audio).pack(pady=5)


label_status = tk.Label(window, text="")

label_status.pack(pady=10)


window.mainloop()



Language Codes for gTTS:

  • English: en

  • Hindi: hi

  • Spanish: es

  • French: fr

  • Malayalam: ml

  • Tamil: ta

Mindfulness & Focus Timer App

 main.py

import tkinter as tk

from timer import start_pomodoro

from breathing import start_breathing

from prompts import get_prompt


window = tk.Tk()

window.title("๐Ÿง  Mindfulness & Focus Timer")

window.geometry("400x300")


label = tk.Label(window, text="Welcome to Focus Time!", font=("Helvetica", 16))

label.pack(pady=10)


tk.Button(window, text="Start Pomodoro", command=start_pomodoro).pack(pady=10)

tk.Button(window, text="Breathing Exercise", command=start_breathing).pack(pady=10)

tk.Button(window, text="Get Mindfulness Prompt", command=lambda: label.config(text=get_prompt())).pack(pady=10)


window.mainloop()

timer.py

import time
import pygame
import threading

def play_sound():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("sounds/ding.wav")
    pygame.mixer.music.play()

def start_pomodoro():
    def run():
        print("Focus time started!")
        for i in range(25 * 60, 0, -1):
            mins, secs = divmod(i, 60)
            print(f"{mins:02d}:{secs:02d}", end='\r')
            time.sleep(1)
        play_sound()
        print("\nTime for a break!")

    threading.Thread(target=run).start()

breathing.py

import time
import threading

def start_breathing():
    def run():
        print("Follow the breathing pattern:")
        for _ in range(4):
            print("Inhale... ๐Ÿซ")
            time.sleep(4)
            print("Hold... ✋")
            time.sleep(4)
            print("Exhale... ๐Ÿ˜ฎ‍๐Ÿ’จ")
            time.sleep(4)
    threading.Thread(target=run).start()

prompts.py

import random

prompts = [
    "Breathe in clarity, breathe out stress.",
    "Focus on one thing at a time.",
    "You are in control of your day.",
    "Be here now. ๐ŸŒฑ",
    "Let go of what you can't control."
]

def get_prompt():
    return random.choice(prompts)


AI Image Caption Generator

 import numpy as np

import tensorflow as tf

from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input

from tensorflow.keras.preprocessing import image

from tensorflow.keras.models import Model, load_model

import pickle

import cv2

import streamlit as st

from PIL import Image


# Load Pretrained InceptionV3 Model for Image Feature Extraction

base_model = InceptionV3(weights='imagenet')

model = Model(inputs=base_model.input, outputs=base_model.layers[-2].output)


# Load Pretrained Captioning Model

captioning_model = load_model("image_captioning_model.h5")


# Load Tokenizer & Word Mappings

with open("tokenizer.pickle", "rb") as handle:

    tokenizer = pickle.load(handle)


max_length = 35  # Max caption length


# Extract Features from Image

def extract_features(img_path):

    img = image.load_img(img_path, target_size=(299, 299))

    img = image.img_to_array(img)

    img = np.expand_dims(img, axis=0)

    img = preprocess_input(img)

    feature_vector = model.predict(img)

    return feature_vector


# Generate Caption

def generate_caption(img_path):

    image_features = extract_features(img_path)

    caption = "startseq"

    

    for i in range(max_length):

        sequence = [tokenizer.word_index[word] for word in caption.split() if word in tokenizer.word_index]

        sequence = tf.keras.preprocessing.sequence.pad_sequences([sequence], maxlen=max_length)

        predicted_index = np.argmax(captioning_model.predict([image_features, sequence]), axis=-1)

        word = tokenizer.index_word.get(predicted_index[0], "")

        if word == "endseq":

            break

        caption += " " + word

    

    return caption.replace("startseq", "").replace("endseq", "").strip()


# Streamlit Web Interface

st.title("๐Ÿ–ผ️ AI Image Caption Generator")

uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "png", "jpeg"])


if uploaded_file is not None:

    img = Image.open(uploaded_file)

    st.image(img, caption="Uploaded Image", use_column_width=True)

    

    # Save the uploaded image temporarily

    img_path = "temp.jpg"

    img.save(img_path)

    

    # Generate Caption

    with st.spinner("Generating Caption..."):

        caption_text = generate_caption(img_path)

    

    st.subheader("๐Ÿ“ Generated Caption:")

    st.write(caption_text)


AI Resume Scorer

 import fitz  # PyMuPDF for PDF parsing

import docx2txt

import spacy

import re

from collections import Counter

import tkinter as tk

from tkinter import filedialog, messagebox


# Load NLP Model (English)

nlp = spacy.load("en_core_web_sm")


# Job Description (Example)

job_description = """

We are looking for a Data Scientist with expertise in Python, Machine Learning, and Data Analysis.

Candidates must have experience with Pandas, NumPy, and Scikit-learn.

Strong communication and teamwork skills are required.

"""


# Function to extract text from PDF

def extract_text_from_pdf(pdf_path):

    text = ""

    doc = fitz.open(pdf_path)

    for page in doc:

        text += page.get_text()

    return text


# Function to extract text from DOCX

def extract_text_from_docx(docx_path):

    return docx2txt.process(docx_path)


# Function to clean and preprocess text

def clean_text(text):

    text = re.sub(r"\s+", " ", text)  # Remove extra spaces

    text = text.lower()  # Convert to lowercase

    return text


# Function to extract keywords using NLP

def extract_keywords(text):

    doc = nlp(text)

    keywords = [token.text for token in doc if token.is_alpha and not token.is_stop]

    return Counter(keywords)


# Function to score the resume

def score_resume(resume_text, job_description):

    resume_keywords = extract_keywords(resume_text)

    job_keywords = extract_keywords(job_description)


    # Calculate Keyword Match Score

    matched_keywords = sum((resume_keywords & job_keywords).values())

    total_keywords = sum(job_keywords.values())

    keyword_score = (matched_keywords / total_keywords) * 100 if total_keywords else 0


    # Readability Score (Basic: Word Count / Sentence Count)

    sentence_count = len(re.findall(r"[.!?]", resume_text))

    word_count = len(resume_text.split())

    readability_score = (word_count / (sentence_count + 1)) * 2  # Simplified readability measure


    # Final Score Calculation (Weighted Average)

    final_score = (keyword_score * 0.7) + (readability_score * 0.3)

    return round(final_score, 2), keyword_score, readability_score


# GUI for File Upload

def upload_file():

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

    

    if file_path:

        if file_path.endswith(".pdf"):

            resume_text = extract_text_from_pdf(file_path)

        elif file_path.endswith(".docx"):

            resume_text = extract_text_from_docx(file_path)

        else:

            messagebox.showerror("Error", "Unsupported file format!")

            return

        

        # Clean and score resume

        cleaned_resume = clean_text(resume_text)

        final_score, keyword_score, readability_score = score_resume(cleaned_resume, job_description)

        

        # Show results

        messagebox.showinfo("Resume Score", f"๐Ÿ“„ Resume Score: {final_score}%\n\n"

                                             f"๐Ÿ”‘ Keyword Match: {keyword_score:.2f}%\n"

                                             f"๐Ÿ“– Readability Score: {readability_score:.2f}%")


# GUI Setup

root = tk.Tk()

root.title("AI Resume Scorer")

root.geometry("300x200")


upload_btn = tk.Button(root, text="Upload Resume", command=upload_file, padx=10, pady=5)

upload_btn.pack(pady=20)


root.mainloop()


Job Application Tracker

 import tkinter as tk

from tkinter import ttk, messagebox

import sqlite3

import pandas as pd

import smtplib


# Database Setup

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

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS jobs (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        company TEXT,

        role TEXT,

        date_applied TEXT,

        status TEXT

    )

""")

conn.commit()


# GUI Application

class JobTrackerApp:

    def __init__(self, root):

        self.root = root

        self.root.title("Job Application Tracker")

        self.root.geometry("600x400")


        # Labels

        ttk.Label(root, text="Company:").grid(row=0, column=0)

        ttk.Label(root, text="Role:").grid(row=1, column=0)

        ttk.Label(root, text="Date Applied:").grid(row=2, column=0)

        ttk.Label(root, text="Status:").grid(row=3, column=0)


        # Entry Fields

        self.company_entry = ttk.Entry(root)

        self.role_entry = ttk.Entry(root)

        self.date_entry = ttk.Entry(root)

        self.status_combo = ttk.Combobox(root, values=["Pending", "Interview", "Rejected", "Hired"])

        

        self.company_entry.grid(row=0, column=1)

        self.role_entry.grid(row=1, column=1)

        self.date_entry.grid(row=2, column=1)

        self.status_combo.grid(row=3, column=1)


        # Buttons

        ttk.Button(root, text="Add Job", command=self.add_job).grid(row=4, column=0)

        ttk.Button(root, text="Show Jobs", command=self.show_jobs).grid(row=4, column=1)

        ttk.Button(root, text="Export to CSV", command=self.export_csv).grid(row=5, column=0)

        ttk.Button(root, text="Send Follow-up", command=self.send_followup).grid(row=5, column=1)


    def add_job(self):

        company = self.company_entry.get()

        role = self.role_entry.get()

        date = self.date_entry.get()

        status = self.status_combo.get()


        if not company or not role or not date or not status:

            messagebox.showerror("Error", "All fields are required!")

            return

        

        cursor.execute("INSERT INTO jobs (company, role, date_applied, status) VALUES (?, ?, ?, ?)", 

                       (company, role, date, status))

        conn.commit()

        messagebox.showinfo("Success", "Job Application Added!")


    def show_jobs(self):

        jobs_window = tk.Toplevel(self.root)

        jobs_window.title("Job Applications")

        tree = ttk.Treeview(jobs_window, columns=("ID", "Company", "Role", "Date", "Status"), show="headings")

        tree.heading("ID", text="ID")

        tree.heading("Company", text="Company")

        tree.heading("Role", text="Role")

        tree.heading("Date", text="Date Applied")

        tree.heading("Status", text="Status")

        tree.pack(fill="both", expand=True)


        cursor.execute("SELECT * FROM jobs")

        for row in cursor.fetchall():

            tree.insert("", "end", values=row)


    def export_csv(self):

        cursor.execute("SELECT * FROM jobs")

        data = cursor.fetchall()

        df = pd.DataFrame(data, columns=["ID", "Company", "Role", "Date Applied", "Status"])

        df.to_csv("job_applications.csv", index=False)

        messagebox.showinfo("Exported", "Job Applications saved as CSV!")


    def send_followup(self):

        email = "your-email@gmail.com"  # Change to your email

        password = "your-password"  # Use App Password for security


        cursor.execute("SELECT company, role FROM jobs WHERE status='Pending'")

        pending_jobs = cursor.fetchall()


        if not pending_jobs:

            messagebox.showinfo("No Follow-ups", "No pending applications to follow up on.")

            return

        

        msg = "Subject: Follow-up on Job Applications\n\n"

        msg += "Here are your pending job applications:\n"

        for company, role in pending_jobs:

            msg += f"- {role} at {company}\n"


        try:

            server = smtplib.SMTP("smtp.gmail.com", 587)

            server.starttls()

            server.login(email, password)

            server.sendmail(email, email, msg)

            server.quit()

            messagebox.showinfo("Email Sent", "Follow-up email sent successfully!")

        except Exception as e:

            messagebox.showerror("Error", f"Failed to send email: {e}")


# Run App

root = tk.Tk()

app = JobTrackerApp(root)

root.mainloop()


Automated Email Responder

 import imaplib

import smtplib

import email

from email.mime.text import MIMEText

import openai


# Gmail Credentials

EMAIL_USER = "your_email@gmail.com"

EMAIL_PASS = "your_app_password"


# OpenAI API Key (Optional)

OPENAI_API_KEY = "your_openai_api_key"

openai.api_key = OPENAI_API_KEY


# Connect to Gmail Inbox

def check_inbox():

    mail = imaplib.IMAP4_SSL("imap.gmail.com")

    mail.login(EMAIL_USER, EMAIL_PASS)

    mail.select("inbox")


    _, messages = mail.search(None, "UNSEEN")

    email_ids = messages[0].split()


    for email_id in email_ids:

        _, msg_data = mail.fetch(email_id, "(RFC822)")

        for response_part in msg_data:

            if isinstance(response_part, tuple):

                msg = email.message_from_bytes(response_part[1])

                sender = msg["From"]

                subject = msg["Subject"]

                body = extract_body(msg)


                print(f"New Email from: {sender}")

                print(f"Subject: {subject}")

                print(f"Body: {body}")


                reply_message = generate_reply(body)

                send_email(sender, reply_message)


    mail.logout()


# Extract Email Body

def extract_body(msg):

    if msg.is_multipart():

        for part in msg.walk():

            if part.get_content_type() == "text/plain":

                return part.get_payload(decode=True).decode()

    return msg.get_payload(decode=True).decode()


# Generate AI-Based Response (Optional)

def generate_reply(user_query):

    prompt = f"Reply professionally to this email: {user_query}"

    response = openai.ChatCompletion.create(

        model="gpt-3.5-turbo",

        messages=[{"role": "system", "content": "You are a professional email assistant."},

                  {"role": "user", "content": prompt}]

    )

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


# Send Email Response

def send_email(to_email, message):

    smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)

    smtp_server.login(EMAIL_USER, EMAIL_PASS)


    msg = MIMEText(message)

    msg["Subject"] = "Re: Your Inquiry"

    msg["From"] = EMAIL_USER

    msg["To"] = to_email


    smtp_server.sendmail(EMAIL_USER, to_email, msg.as_string())

    smtp_server.quit()

    print(f"Auto-reply sent to {to_email}")


# Run the Email Bot

if __name__ == "__main__":

    check_inbox()


YouTube Video Summarizer

 pip install youtube-transcript-api nltk sumy


import tkinter as tk
from tkinter import messagebox
from youtube_transcript_api import YouTubeTranscriptApi
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer

# Function to extract video ID from URL
def extract_video_id(url):
    if "youtube.com/watch?v=" in url:
        return url.split("v=")[1].split("&")[0]
    elif "youtu.be/" in url:
        return url.split("youtu.be/")[1].split("?")[0]
    else:
        return None

# Function to fetch transcript
def get_transcript(video_url):
    video_id = extract_video_id(video_url)
    if not video_id:
        messagebox.showerror("Error", "Invalid YouTube URL")
        return None

    try:
        transcript = YouTubeTranscriptApi.get_transcript(video_id)
        full_text = " ".join([entry["text"] for entry in transcript])
        return full_text
    except Exception as e:
        messagebox.showerror("Error", f"Could not fetch transcript: {str(e)}")
        return None

# Function to summarize text
def summarize_text(text, num_sentences=3):
    parser = PlaintextParser.from_string(text, Tokenizer("english"))
    summarizer = LsaSummarizer()
    summary = summarizer(parser.document, num_sentences)
    return " ".join(str(sentence) for sentence in summary)

# Function to fetch and summarize
def summarize_video():
    video_url = url_entry.get()
    transcript = get_transcript(video_url)
    
    if transcript:
        summary = summarize_text(transcript)
        output_text.delete("1.0", tk.END)
        output_text.insert(tk.END, summary)

# GUI
root = tk.Tk()
root.title("YouTube Video Summarizer")

tk.Label(root, text="Enter YouTube Video URL:").pack()
url_entry = tk.Entry(root, width=50)
url_entry.pack()

tk.Button(root, text="Summarize", command=summarize_video).pack()

output_text = tk.Text(root, height=10, width=60)
output_text.pack()

root.mainloop()

Automated Screenshot Tool

 pip install pyautogui


import pyautogui
import time
import os
import tkinter as tk
from tkinter import messagebox

# Folder to save screenshots
screenshot_folder = "screenshots"
if not os.path.exists(screenshot_folder):
    os.makedirs(screenshot_folder)

# Function to take a screenshot
def take_screenshot():
    timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
    filename = os.path.join(screenshot_folder, f"screenshot_{timestamp}.png")
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)
    print(f"✅ Screenshot saved: {filename}")

# Function to start auto screenshots
def start_screenshot():
    try:
        interval = int(entry.get())
        messagebox.showinfo("Started", f"Taking screenshots every {interval} seconds.")
        
        while True:
            take_screenshot()
            time.sleep(interval)
    except ValueError:
        messagebox.showerror("Error", "Please enter a valid number.")

# GUI with Tkinter
root = tk.Tk()
root.title("Automated Screenshot Tool")

tk.Label(root, text="Enter Screenshot Interval (seconds):").pack()
entry = tk.Entry(root)
entry.pack()

tk.Button(root, text="Start Screenshot Capture", command=start_screenshot).pack()
tk.Button(root, text="Exit", command=root.quit).pack()

root.mainloop()

Invoice Generator

 pip install reportlab


from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def generate_invoice(client_name, items, tax_rate=0.05, filename="invoice.pdf"):
    c = canvas.Canvas(filename, pagesize=letter)
    width, height = letter

    # Title
    c.setFont("Helvetica-Bold", 16)
    c.drawString(50, height - 50, "INVOICE")

    # Client Details
    c.setFont("Helvetica", 12)
    c.drawString(50, height - 80, f"Client: {client_name}")

    # Table Headers
    c.setFont("Helvetica-Bold", 12)
    c.drawString(50, height - 120, "Item")
    c.drawString(250, height - 120, "Quantity")
    c.drawString(350, height - 120, "Price")
    c.drawString(450, height - 120, "Total")

    # Invoice Items
    c.setFont("Helvetica", 12)
    y_position = height - 140
    total_cost = 0

    for item, details in items.items():
        quantity, price = details
        total = quantity * price
        total_cost += total

        c.drawString(50, y_position, item)
        c.drawString(250, y_position, str(quantity))
        c.drawString(350, y_position, f"${price:.2f}")
        c.drawString(450, y_position, f"${total:.2f}")
        y_position -= 20

    # Tax and Total Calculation
    tax_amount = total_cost * tax_rate
    grand_total = total_cost + tax_amount

    c.setFont("Helvetica-Bold", 12)
    c.drawString(350, y_position - 20, "Subtotal:")
    c.drawString(450, y_position - 20, f"${total_cost:.2f}")

    c.drawString(350, y_position - 40, f"Tax ({tax_rate * 100}%):")
    c.drawString(450, y_position - 40, f"${tax_amount:.2f}")

    c.drawString(350, y_position - 60, "Grand Total:")
    c.drawString(450, y_position - 60, f"${grand_total:.2f}")

    # Save PDF
    c.save()
    print(f"✅ Invoice saved as {filename}")

PDF to Audio Converter

 pip install PyMuPDF gtts tk


import fitz  # PyMuPDF
from gtts import gTTS
import tkinter as tk
from tkinter import filedialog, messagebox
import os

# Function to extract text from PDF
def extract_text_from_pdf(pdf_path):
    doc = fitz.open(pdf_path)
    text = ""
    for page in doc:
        text += page.get_text("text") + "\n"
    return text

# Function to convert text to speech
def convert_text_to_audio(text, output_file):
    if text.strip():
        tts = gTTS(text=text, lang='en')
        tts.save(output_file)
        messagebox.showinfo("Success", f"Audio file saved as {output_file}")
        os.system(f"start {output_file}")  # Opens the audio file
    else:
        messagebox.showwarning("Warning", "No text found in PDF.")

# Function to open file dialog
def select_pdf():
    file_path = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
    if file_path:
        text = extract_text_from_pdf(file_path)
        if text:
            convert_text_to_audio(text, "output_audio.mp3")

# Tkinter GUI Setup
root = tk.Tk()
root.title("PDF to Audio Converter ๐Ÿ”Š")
root.geometry("400x200")

lbl_title = tk.Label(root, text="๐Ÿ“„ PDF to Audio Converter ๐Ÿ”Š", font=("Arial", 14, "bold"))
lbl_title.pack(pady=10)

btn_select_pdf = tk.Button(root, text="Select PDF & Convert", command=select_pdf, font=("Arial", 12))
btn_select_pdf.pack(pady=20)

root.mainloop()

Network Speed Monitor

 pip install speedtest-cli matplotlib tk


import speedtest
import tkinter as tk
from tkinter import ttk
import threading
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Function to test internet speed
def test_speed():
    st = speedtest.Speedtest()
    st.get_best_server()
    
    download_speed = round(st.download() / 1_000_000, 2)  # Convert to Mbps
    upload_speed = round(st.upload() / 1_000_000, 2)  # Convert to Mbps

    return download_speed, upload_speed

# Function to update the speed in GUI
def update_speed():
    global speeds_download, speeds_upload
    
    while True:
        download, upload = test_speed()
        speeds_download.append(download)
        speeds_upload.append(upload)

        lbl_download.config(text=f"Download Speed: {download} Mbps")
        lbl_upload.config(text=f"Upload Speed: {upload} Mbps")

        update_graph()
        root.update_idletasks()

# Function to update the speed graph
def update_graph():
    ax.clear()
    ax.plot(speeds_download, label="Download Speed (Mbps)", color="blue")
    ax.plot(speeds_upload, label="Upload Speed (Mbps)", color="red")
    
    ax.set_title("Network Speed Over Time")
    ax.set_xlabel("Test Count")
    ax.set_ylabel("Speed (Mbps)")
    ax.legend()
    ax.grid()

    canvas.draw()

# Tkinter GUI setup
root = tk.Tk()
root.title("Network Speed Monitor ๐ŸŒ")
root.geometry("500x500")

lbl_title = tk.Label(root, text="๐Ÿ“ก Network Speed Monitor", font=("Arial", 14, "bold"))
lbl_title.pack(pady=10)

lbl_download = tk.Label(root, text="Download Speed: -- Mbps", font=("Arial", 12))
lbl_download.pack(pady=5)

lbl_upload = tk.Label(root, text="Upload Speed: -- Mbps", font=("Arial", 12))
lbl_upload.pack(pady=5)

# Matplotlib graph setup
fig, ax = plt.subplots(figsize=(5, 3))
speeds_download = []
speeds_upload = []

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

# Run speed test in a separate thread
threading.Thread(target=update_speed, daemon=True).start()

root.mainloop()

Code Syntax Highlighter

 pip install pygments


from pygments import highlight
from pygments.lexers import guess_lexer, PythonLexer, JavascriptLexer, CLexer
from pygments.formatters import TerminalFormatter, HtmlFormatter

# Function to highlight code in terminal
def highlight_code_terminal(code, language="python"):
    # Choose lexer based on language
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    highlighted_code = highlight(code, lexer, TerminalFormatter())
    return highlighted_code


# Function to highlight code and save as HTML
def highlight_code_html(code, language="python", output_file="highlighted_code.html"):
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    formatter = HtmlFormatter(full=True, style="monokai")
    highlighted_code = highlight(code, lexer, formatter)

    # Save to an HTML file
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(highlighted_code)
    
    print(f"✅ Highlighted code saved to {output_file}")

from pygments import highlight
from pygments.lexers import guess_lexer, PythonLexer, JavascriptLexer, CLexer
from pygments.formatters import TerminalFormatter, HtmlFormatter

# Function to highlight code in terminal
def highlight_code_terminal(code, language="python"):
    # Choose lexer based on language
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    highlighted_code = highlight(code, lexer, TerminalFormatter())
    return highlighted_code


# Function to highlight code and save as HTML
def highlight_code_html(code, language="python", output_file="highlighted_code.html"):
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    formatter = HtmlFormatter(full=True, style="monokai")
    highlighted_code = highlight(code, lexer, formatter)

    # Save to an HTML file
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(highlighted_code)
    
    print(f"✅ Highlighted code saved to {output_file}")


# Example usage
if __name__ == "__main__":
    code_sample = """
    def greet(name):
        print(f"Hello, {name}!")
    
    greet("abc")
    """

    print("๐ŸŽจ Terminal Highlighted Code:")
    print(highlight_code_terminal(code_sample, "python"))

    highlight_code_html(code_sample, "python")


Resume Parser & Analyzer


pip install spacy pdfminer.six python-docx pandas nltk

python -m spacy download en_core_web_sm


import re

import spacy

import pdfminer.high_level

import docx

import nltk

from collections import Counter


nltk.download("stopwords")

from nltk.corpus import stopwords


# Load spaCy NLP model

nlp = spacy.load("en_core_web_sm")



# Function to extract text from PDF

def extract_text_from_pdf(pdf_path):

    return pdfminer.high_level.extract_text(pdf_path)



# Function to extract text from DOCX

def extract_text_from_docx(docx_path):

    doc = docx.Document(docx_path)

    return "\n".join([para.text for para in doc.paragraphs])



# Function to extract email from text

def extract_email(text):

    email_pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"

    emails = re.findall(email_pattern, text)

    return emails[0] if emails else None



# Function to extract phone number from text

def extract_phone(text):

    phone_pattern = r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}"

    phones = re.findall(phone_pattern, text)

    return phones[0] if phones else None



# Function to extract skills from text

def extract_skills(text):

    skills_list = ["Python", "Java", "C++", "Machine Learning", "Data Science", "SQL", "Django", "React", "Flask"]

    found_skills = [skill for skill in skills_list if skill.lower() in text.lower()]

    return found_skills



# Function to extract name using NLP

def extract_name(text):

    doc = nlp(text)

    for ent in doc.ents:

        if ent.label_ == "PERSON":

            return ent.text

    return None



# Function to match skills with a job description

def match_skills(resume_skills, job_description):

    job_tokens = nltk.word_tokenize(job_description.lower())

    stop_words = set(stopwords.words("english"))

    filtered_job_tokens = [word for word in job_tokens if word not in stop_words]


    skill_match_count = sum(1 for skill in resume_skills if skill.lower() in filtered_job_tokens)

    match_percentage = (skill_match_count / len(resume_skills)) * 100 if resume_skills else 0

    return round(match_percentage, 2)



# Main function

def analyze_resume(file_path, job_description):

    # Extract text

    text = extract_text_from_pdf(file_path) if file_path.endswith(".pdf") else extract_text_from_docx(file_path)


    # Extract details

    name = extract_name(text)

    email = extract_email(text)

    phone = extract_phone(text)

    skills = extract_skills(text)

    match_percentage = match_skills(skills, job_description)


    # Display results

    print("\n๐Ÿ“„ Resume Analysis Results:")

    print(f"๐Ÿ‘ค Name: {name}")

    print(f"๐Ÿ“ง Email: {email}")

    print(f"๐Ÿ“ž Phone: {phone}")

    print(f"๐Ÿ›  Skills: {', '.join(skills)}")

    print(f"✅ Skill Match with Job: {match_percentage}%")


    return {"name": name, "email": email, "phone": phone, "skills": skills, "match_percentage": match_percentage}


Automated File Organizer

 import os

import shutil


# Define file categories with their extensions

FILE_CATEGORIES = {

    "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg"],

    "Documents": [".pdf", ".docx", ".txt", ".xlsx", ".pptx", ".csv"],

    "Videos": [".mp4", ".avi", ".mkv", ".mov"],

    "Music": [".mp3", ".wav", ".flac"],

    "Archives": [".zip", ".rar", ".tar", ".gz"],

    "Programs": [".exe", ".msi", ".dmg"],

    "Others": []

}


def organize_files(folder_path):

    """Organizes files into categorized folders based on extensions."""

    

    if not os.path.exists(folder_path):

        print(f"Error: The folder '{folder_path}' does not exist.")

        return

    

    # Create folders if they don't exist

    for category in FILE_CATEGORIES.keys():

        category_path = os.path.join(folder_path, category)

        os.makedirs(category_path, exist_ok=True)


    # Iterate through all files in the folder

    for file_name in os.listdir(folder_path):

        file_path = os.path.join(folder_path, file_name)

        

        # Skip directories

        if os.path.isdir(file_path):

            continue

        

        # Get file extension

        file_ext = os.path.splitext(file_name)[1].lower()


        # Determine the correct category for the file

        destination_folder = "Others"  # Default category

        for category, extensions in FILE_CATEGORIES.items():

            if file_ext in extensions:

                destination_folder = category

                break


        # Move the file to the correct folder

        shutil.move(file_path, os.path.join(folder_path, destination_folder, file_name))

        print(f"Moved: {file_name} → {destination_folder}")


    print("✅ File organization completed successfully!")


# Run the script

if __name__ == "__main__":

    folder_to_organize = input("Enter the folder path to organize: ")

    organize_files(folder_to_organize)


Face Attendance System

 import cv2

import numpy as np

import face_recognition

import os

import csv

from datetime import datetime


# Folder containing images of known faces

KNOWN_FACES_DIR = "known_faces"

ATTENDANCE_FILE = "attendance.csv"


# Load known face encodings and names

known_encodings = []

known_names = []


for filename in os.listdir(KNOWN_FACES_DIR):

    image_path = os.path.join(KNOWN_FACES_DIR, filename)

    image = face_recognition.load_image_file(image_path)

    encoding = face_recognition.face_encodings(image)[0]

    known_encodings.append(encoding)

    known_names.append(os.path.splitext(filename)[0])  # Remove file extension


# Initialize webcam

video_capture = cv2.VideoCapture(0)


# Function to mark attendance

def mark_attendance(name):

    with open(ATTENDANCE_FILE, "a", newline="") as file:

        writer = csv.writer(file)

        now = datetime.now()

        time_str = now.strftime("%H:%M:%S")

        date_str = now.strftime("%Y-%m-%d")

        writer.writerow([name, date_str, time_str])


# Create CSV file with headers if it doesn't exist

if not os.path.exists(ATTENDANCE_FILE):

    with open(ATTENDANCE_FILE, "w", newline="") as file:

        writer = csv.writer(file)

        writer.writerow(["Name", "Date", "Time"])


# Process video stream

while True:

    ret, frame = video_capture.read()

    if not ret:

        break


    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)  # Optimize performance

    rgb_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)


    # Detect faces in the frame

    face_locations = face_recognition.face_locations(rgb_frame)

    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)


    for encoding, location in zip(face_encodings, face_locations):

        matches = face_recognition.compare_faces(known_encodings, encoding)

        name = "Unknown"


        if True in matches:

            index = matches.index(True)

            name = known_names[index]

            mark_attendance(name)  # Mark attendance in CSV


        # Draw bounding box around detected face

        top, right, bottom, left = [v * 4 for v in location]

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)

        cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)


    cv2.imshow("Face Attendance System", frame)


    if cv2.waitKey(1) & 0xFF == ord("q"):

        break


video_capture.release()

cv2.destroyAllWindows()


Music Playlist Manager

import os

import tkinter as tk

from tkinter import filedialog, messagebox

import pygame


class MusicPlayer:

    def __init__(self, root):

        self.root = root

        self.root.title("Music Playlist Manager ๐ŸŽต")

        self.root.geometry("500x400")

        

        pygame.init()

        pygame.mixer.init()

        

        self.playlist = []

        self.current_song_index = -1

        self.is_paused = False

        

        # GUI Components

        self.playlist_box = tk.Listbox(root, selectmode=tk.SINGLE, bg="white", fg="black", width=60, height=15)

        self.playlist_box.pack(pady=10)


        btn_frame = tk.Frame(root)

        btn_frame.pack()


        tk.Button(btn_frame, text="Add Song", command=self.add_song).grid(row=0, column=0, padx=5)

        tk.Button(btn_frame, text="Remove Song", command=self.remove_song).grid(row=0, column=1, padx=5)

        tk.Button(btn_frame, text="Play", command=self.play_song).grid(row=0, column=2, padx=5)

        tk.Button(btn_frame, text="Pause", command=self.pause_song).grid(row=0, column=3, padx=5)

        tk.Button(btn_frame, text="Resume", command=self.resume_song).grid(row=0, column=4, padx=5)

        tk.Button(btn_frame, text="Stop", command=self.stop_song).grid(row=0, column=5, padx=5)


        self.current_song_label = tk.Label(root, text="Now Playing: None", fg="blue", font=("Arial", 10, "bold"))

        self.current_song_label.pack(pady=10)


    def add_song(self):

        file_path = filedialog.askopenfilename(filetypes=[("MP3 Files", "*.mp3")])

        if file_path:

            self.playlist.append(file_path)

            self.playlist_box.insert(tk.END, os.path.basename(file_path))


    def remove_song(self):

        selected_index = self.playlist_box.curselection()

        if selected_index:

            index = selected_index[0]

            self.playlist_box.delete(index)

            del self.playlist[index]


    def play_song(self):

        selected_index = self.playlist_box.curselection()

        if selected_index:

            index = selected_index[0]

            self.current_song_index = index

            song_path = self.playlist[index]

            

            pygame.mixer.music.load(song_path)

            pygame.mixer.music.play()

            self.is_paused = False


            self.current_song_label.config(text=f"Now Playing: {os.path.basename(song_path)}")


    def pause_song(self):

        if not self.is_paused:

            pygame.mixer.music.pause()

            self.is_paused = True


    def resume_song(self):

        if self.is_paused:

            pygame.mixer.music.unpause()

            self.is_paused = False


    def stop_song(self):

        pygame.mixer.music.stop()

        self.current_song_label.config(text="Now Playing: None")


# Run the application

if __name__ == "__main__":

    root = tk.Tk()

    app = MusicPlayer(root)

    root.mainloop()


Personal Finance Tracker

 import tkinter as tk

from tkinter import ttk, messagebox

import sqlite3

import matplotlib.pyplot as plt


# Database Setup

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

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS transactions (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        date TEXT,

        category TEXT,

        amount REAL,

        type TEXT

    )

""")

conn.commit()


class FinanceTracker:

    def __init__(self, root):

        self.root = root

        self.root.title("Personal Finance Tracker ๐Ÿ’ฐ")

        self.root.geometry("600x500")


        # UI Components

        tk.Label(root, text="Date (YYYY-MM-DD):").grid(row=0, column=0, padx=10, pady=5, sticky="w")

        self.date_entry = tk.Entry(root, width=30)

        self.date_entry.grid(row=0, column=1, padx=10, pady=5)


        tk.Label(root, text="Category:").grid(row=1, column=0, padx=10, pady=5, sticky="w")

        self.category_entry = tk.Entry(root, width=30)

        self.category_entry.grid(row=1, column=1, padx=10, pady=5)


        tk.Label(root, text="Amount:").grid(row=2, column=0, padx=10, pady=5, sticky="w")

        self.amount_entry = tk.Entry(root, width=30)

        self.amount_entry.grid(row=2, column=1, padx=10, pady=5)


        tk.Label(root, text="Transaction Type:").grid(row=3, column=0, padx=10, pady=5, sticky="w")

        self.type_var = tk.StringVar(value="Expense")  

        self.type_dropdown = ttk.Combobox(root, textvariable=self.type_var, values=["Expense", "Income"], width=28)

        self.type_dropdown.grid(row=3, column=1, padx=10, pady=5)

        self.type_dropdown.current(0)


        # Buttons - Expanded Width

        tk.Button(root, text="Add Transaction", command=self.add_transaction, width=20).grid(row=4, column=0, columnspan=2, pady=10)

        tk.Button(root, text="Show Transactions", command=self.show_transactions, width=20).grid(row=5, column=0, columnspan=2, pady=5)

        tk.Button(root, text="View Report", command=self.view_report, width=20).grid(row=6, column=0, columnspan=2, pady=5)


        # Transaction List Display

        self.tree = ttk.Treeview(root, columns=("ID", "Date", "Category", "Amount", "Type"), show="headings")

        self.tree.heading("ID", text="ID")

        self.tree.heading("Date", text="Date")

        self.tree.heading("Category", text="Category")

        self.tree.heading("Amount", text="Amount")

        self.tree.heading("Type", text="Type")

        self.tree.column("ID", width=30)

        self.tree.column("Date", width=100)

        self.tree.column("Category", width=100)

        self.tree.column("Amount", width=80)

        self.tree.column("Type", width=80)

        self.tree.grid(row=7, column=0, columnspan=2, padx=10, pady=10)


    def add_transaction(self):

        date = self.date_entry.get()

        category = self.category_entry.get()

        amount = self.amount_entry.get()

        trans_type = self.type_var.get()


        if not date or not category or not amount or not trans_type:

            messagebox.showerror("Error", "All fields are required!")

            return

        

        try:

            amount = float(amount)

            cursor.execute("INSERT INTO transactions (date, category, amount, type) VALUES (?, ?, ?, ?)", 

                           (date, category, amount, trans_type))

            conn.commit()

            messagebox.showinfo("Success", "Transaction added successfully!")

            self.clear_entries()

        except ValueError:

            messagebox.showerror("Error", "Amount must be a number!")


    def show_transactions(self):

        for item in self.tree.get_children():

            self.tree.delete(item)


        cursor.execute("SELECT * FROM transactions")

        for row in cursor.fetchall():

            self.tree.insert("", "end", values=row)


    def view_report(self):

        cursor.execute("SELECT category, SUM(amount) FROM transactions WHERE type='Expense' GROUP BY category")

        data = cursor.fetchall()


        if not data:

            messagebox.showinfo("Report", "No expenses recorded.")

            return


        categories, amounts = zip(*data)

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

        plt.pie(amounts, labels=categories, autopct="%1.1f%%", startangle=140)

        plt.title("Expense Breakdown")

        plt.show()


    def clear_entries(self):

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

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

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

        self.type_var.set("Expense")


# Run the application

if __name__ == "__main__":

    root = tk.Tk()

    app = FinanceTracker(root)

    root.mainloop()

Real-Time Weather Dashboard

 Get an API Key from OpenWeather


import tkinter as tk

from tkinter import messagebox

import requests


# OpenWeather API Key (Replace with your own key)

API_KEY = "YOUR_OPENWEATHER_API_KEY"

BASE_URL = "http://api.openweathermap.org/data/2.5/weather"


# Function to fetch weather data

def get_weather():

    city = city_entry.get()

    if not city:

        messagebox.showerror("Error", "Please enter a city name!")

        return


    params = {"q": city, "appid": API_KEY, "units": "metric"}

    response = requests.get(BASE_URL, params=params)


    if response.status_code == 200:

        data = response.json()

        weather = data["weather"][0]["description"].capitalize()

        temp = data["main"]["temp"]

        humidity = data["main"]["humidity"]

        

        result_label.config(text=f"๐ŸŒ City: {city}\n๐ŸŒก️ Temperature: {temp}°C\n๐Ÿ’ง Humidity: {humidity}%\n☁️ Condition: {weather}")

    else:

        messagebox.showerror("Error", "City not found! Please try again.")


# GUI setup

root = tk.Tk()

root.title("Real-Time Weather Dashboard")

root.geometry("400x350")


tk.Label(root, text="Enter City Name:", font=("Arial", 14)).pack(pady=10)

city_entry = tk.Entry(root, font=("Arial", 12), width=25)

city_entry.pack(pady=5)


tk.Button(root, text="Get Weather", font=("Arial", 12), command=get_weather).pack(pady=10)


result_label = tk.Label(root, text="", font=("Arial", 14), justify="left")

result_label.pack(pady=20)


# Run GUI

root.mainloop()


Online Python Compiler ๐Ÿ’ป

 pip install flask


app.py

from flask import Flask, render_template, request, jsonify
import subprocess

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/run", methods=["POST"])
def run_code():
    code = request.json.get("code", "")

    try:
        # Run the code in a restricted subprocess
        result = subprocess.run(
            ["python", "-c", code],
            capture_output=True,
            text=True,
            timeout=5
        )
        output = result.stdout if result.stdout else result.stderr
    except Exception as e:
        output = str(e)

    return jsonify({"output": output})

if __name__ == "__main__":
    app.run(debug=True)


templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Python Compiler</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; }
        #editor { width: 80%; height: 300px; margin: auto; border: 1px solid #ddd; }
        #output { white-space: pre-wrap; background: #f4f4f4; padding: 10px; margin-top: 10px; width: 80%; }
    </style>
</head>
<body>
    <h1>Online Python Compiler ๐Ÿ’ป</h1>
    <div id="editor">print("Hello, World!")</div>
    <button onclick="runCode()">Run Code</button>
    <pre id="output">Output will appear here...</pre>

    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/python");

        function runCode() {
            let code = editor.getValue();
            fetch("/run", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ code: code })
            })
            .then(response => response.json())
            .then(data => document.getElementById("output").innerText = data.output);
        }
    </script>
</body>
</html>


Flashcard App for Learning

 import tkinter as tk

import json

import random


# File to store flashcards

FLASHCARDS_FILE = "flashcards.json"


class FlashcardApp:

    def __init__(self, root):

        self.root = root

        self.root.title("Flashcard App")

        self.root.geometry("400x300")


        self.flashcards = self.load_flashcards()

        self.current_flashcard = {}


        # UI Elements

        self.label = tk.Label(root, text="Press 'Next' to start!", font=("Arial", 14), wraplength=350)

        self.label.pack(pady=20)


        self.flip_button = tk.Button(root, text="Flip", command=self.flip_card)

        self.flip_button.pack()


        self.next_button = tk.Button(root, text="Next", command=self.next_card)

        self.next_button.pack()


        self.add_button = tk.Button(root, text="Add Flashcard", command=self.add_flashcard)

        self.add_button.pack()


    def load_flashcards(self):

        try:

            with open(FLASHCARDS_FILE, "r") as file:

                return json.load(file)

        except FileNotFoundError:

            return []


    def save_flashcards(self):

        with open(FLASHCARDS_FILE, "w") as file:

            json.dump(self.flashcards, file)


    def next_card(self):

        if not self.flashcards:

            self.label.config(text="No flashcards available. Add some!")

        else:

            self.current_flashcard = random.choice(self.flashcards)

            self.label.config(text=f"Q: {self.current_flashcard['question']}")


    def flip_card(self):

        if self.current_flashcard:

            self.label.config(text=f"A: {self.current_flashcard['answer']}")


    def add_flashcard(self):

        add_window = tk.Toplevel(self.root)

        add_window.title("Add Flashcard")

        add_window.geometry("300x200")


        tk.Label(add_window, text="Question:").pack()

        question_entry = tk.Entry(add_window, width=40)

        question_entry.pack()


        tk.Label(add_window, text="Answer:").pack()

        answer_entry = tk.Entry(add_window, width=40)

        answer_entry.pack()


        def save_new_flashcard():

            question = question_entry.get()

            answer = answer_entry.get()

            if question and answer:

                self.flashcards.append({"question": question, "answer": answer})

                self.save_flashcards()

                add_window.destroy()

        

        save_button = tk.Button(add_window, text="Save", command=save_new_flashcard)

        save_button.pack()


# Run the app

root = tk.Tk()

app = FlashcardApp(root)

root.mainloop()

Quiz Game with Leaderboard ๐ŸŽฎ

import tkinter as tk

from tkinter import messagebox

import random

import json


# Load questions from a JSON file or use a dictionary

questions = [

    {"question": "What keyword is used to define a function in Python?", 

     "options": ["func", "define", "def", "function"], 

     "answer": "def"},

    

    {"question": "Which of the following is used to create a loop in Python?", 

     "options": ["for", "while", "do-while", "Both A and B"], 

     "answer": "Both A and B"},

    

    {"question": "What is the correct way to open a file in read mode?", 

     "options": ["open('file.txt', 'r')", "open('file.txt', 'w')", "open('file.txt', 'rw')", "open('file.txt')"], 

     "answer": "open('file.txt', 'r')"},

    

    {"question": "Which data structure follows the Last In, First Out (LIFO) principle?", 

     "options": ["Queue", "Stack", "List", "Dictionary"], 

     "answer": "Stack"},

    

    {"question": "Which method is used to add an element to a list?", 

     "options": ["append()", "insert()", "extend()", "add()"], 

     "answer": "append()"},

    

    {"question": "Which library is commonly used for data analysis in Python?", 

     "options": ["NumPy", "Pandas", "Matplotlib", "Seaborn"], 

     "answer": "Pandas"},

    

    {"question": "Which symbol is used to comment a single line in Python?", 

     "options": ["//", "#", "/*", "--"], 

     "answer": "#"},

    

    {"question": "What will be the output of `len(['Python', 'Java', 'C++'])`?", 

     "options": ["2", "3", "4", "Error"], 

     "answer": "3"},

    

    {"question": "What does the `range(5)` function return?", 

     "options": ["[1,2,3,4,5]", "[0,1,2,3,4]", "(0,1,2,3,4)", "None"], 

     "answer": "[0,1,2,3,4]"},

    

    {"question": "Which of the following is a mutable data type in Python?", 

     "options": ["Tuple", "String", "List", "Integer"], 

     "answer": "List"}

]



# Load leaderboard from file

def load_leaderboard():

    try:

        with open("leaderboard.json", "r") as f:

            return json.load(f)

    except FileNotFoundError:

        return {}


# Save leaderboard to file

def save_leaderboard(leaderboard):

    with open("leaderboard.json", "w") as f:

        json.dump(leaderboard, f, indent=4)


class QuizGame:

    def __init__(self, root):

        self.root = root

        self.root.title("Quiz Game with Leaderboard")

        self.root.geometry("500x400")


        self.score = 0

        self.current_question = 0

        self.username = ""


        self.start_screen()


    def start_screen(self):

        """Start screen to enter player's name."""

        self.clear_window()

        

        tk.Label(self.root, text="Enter Your Name:", font=("Arial", 14)).pack(pady=10)

        self.name_entry = tk.Entry(self.root, font=("Arial", 12))

        self.name_entry.pack(pady=5)

        

        tk.Button(self.root, text="Start Quiz", command=self.start_quiz, font=("Arial", 12)).pack(pady=20)


    def start_quiz(self):

        """Start the quiz after getting the user's name."""

        self.username = self.name_entry.get()

        if not self.username:

            messagebox.showerror("Error", "Please enter your name!")

            return

        

        random.shuffle(questions)

        self.score = 0

        self.current_question = 0

        self.show_question()


    def show_question(self):

        """Display a question and answer options."""

        self.clear_window()

        

        if self.current_question < len(questions):

            q_data = questions[self.current_question]

            self.correct_answer = q_data["answer"]


            tk.Label(self.root, text=f"Q{self.current_question + 1}: {q_data['question']}", font=("Arial", 14), wraplength=400).pack(pady=10)

            

            self.answer_var = tk.StringVar()


            for option in q_data["options"]:

                tk.Radiobutton(self.root, text=option, variable=self.answer_var, value=option, font=("Arial", 12)).pack(anchor="w", padx=20)

            

            tk.Button(self.root, text="Submit", command=self.check_answer, font=("Arial", 12)).pack(pady=10)

        

        else:

            self.show_result()


    def check_answer(self):

        """Check the selected answer."""

        selected_answer = self.answer_var.get()

        

        if not selected_answer:

            messagebox.showerror("Error", "Please select an answer!")

            return

        

        if selected_answer == self.correct_answer:

            self.score += 1

        

        self.current_question += 1

        self.show_question()


    def show_result(self):

        """Display the final score and update leaderboard."""

        self.clear_window()

        

        leaderboard = load_leaderboard()

        leaderboard[self.username] = self.score

        save_leaderboard(leaderboard)


        tk.Label(self.root, text=f"Quiz Over! {self.username}, your score: {self.score}/{len(questions)}", font=("Arial", 14)).pack(pady=10)


        tk.Button(self.root, text="View Leaderboard", command=self.show_leaderboard, font=("Arial", 12)).pack(pady=10)

        tk.Button(self.root, text="Play Again", command=self.start_screen, font=("Arial", 12)).pack(pady=5)

        tk.Button(self.root, text="Exit", command=self.root.quit, font=("Arial", 12)).pack(pady=5)


    def show_leaderboard(self):

        """Display the leaderboard."""

        self.clear_window()

        leaderboard = load_leaderboard()

        sorted_leaderboard = sorted(leaderboard.items(), key=lambda x: x[1], reverse=True)


        tk.Label(self.root, text="๐Ÿ† Leaderboard ๐Ÿ†", font=("Arial", 16, "bold")).pack(pady=10)


        for rank, (player, high_score) in enumerate(sorted_leaderboard, start=1):

            tk.Label(self.root, text=f"{rank}. {player} - {high_score}", font=("Arial", 12)).pack()


        tk.Button(self.root, text="Back to Menu", command=self.start_screen, font=("Arial", 12)).pack(pady=10)


    def clear_window(self):

        """Clear the window for new content."""

        for widget in self.root.winfo_children():

            widget.destroy()


# Run the application

if __name__ == "__main__":

    root = tk.Tk()

    app = QuizGame(root)

    root.mainloop()