PDF Bill Splitter App

 import tkinter as tk

from tkinter import filedialog, messagebox

import fitz  # PyMuPDF

import re

import sqlite3

import os


# ---------- Database Setup ----------

conn = sqlite3.connect('bill_splitter.db')

cursor = conn.cursor()

cursor.execute('''

CREATE TABLE IF NOT EXISTS bills (

    id INTEGER PRIMARY KEY AUTOINCREMENT,

    filename TEXT,

    total_amount REAL,

    per_person REAL,

    roommates TEXT

)

''')

conn.commit()


# ---------- PDF Total Extractor ----------

def extract_total_from_pdf(file_path):

    try:

        doc = fitz.open(file_path)

        text = ""

        for page in doc:

            text += page.get_text()

        doc.close()


        # Try finding the largest ₹/$/Rs. number

        amounts = re.findall(r'[\₹\$\₹Rs\. ]?(\d+[,.]?\d*)', text)

        float_amounts = [float(a.replace(',', '')) for a in amounts]

        return max(float_amounts) if float_amounts else 0.0


    except Exception as e:

        messagebox.showerror("Error", f"Failed to extract total: {str(e)}")

        return 0.0


# ---------- GUI ----------

class BillSplitterApp:

    def __init__(self, root):

        self.root = root

        self.root.title("📄 PDF Bill Splitter")

        self.filename = None


        # UI Layout

        tk.Button(root, text="📂 Upload PDF Bill", command=self.upload_pdf).pack(pady=10)


        self.total_var = tk.StringVar()

        tk.Label(root, text="💰 Total Amount:").pack()

        tk.Entry(root, textvariable=self.total_var, state="readonly").pack(pady=5)


        self.roommates_entry = tk.Entry(root)

        self.roommates_entry.pack(pady=5)

        self.roommates_entry.insert(0, "Enter emails/names comma-separated")


        tk.Button(root, text="➗ Split Bill", command=self.split_bill).pack(pady=10)


    def upload_pdf(self):

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

        if file_path:

            self.filename = os.path.basename(file_path)

            total = extract_total_from_pdf(file_path)

            self.total_var.set(f"{total:.2f}")


    def split_bill(self):

        total = self.total_var.get()

        roommates = self.roommates_entry.get().split(',')


        if not total or not roommates or len(roommates) < 1:

            messagebox.showerror("Error", "Please upload a PDF and enter roommates.")

            return


        try:

            total = float(total)

            per_person = total / len(roommates)

            roommates_clean = [r.strip() for r in roommates]


            # Save to DB

            cursor.execute('''

                INSERT INTO bills (filename, total_amount, per_person, roommates)

                VALUES (?, ?, ?, ?)

            ''', (self.filename, total, per_person, ", ".join(roommates_clean)))

            conn.commit()


            messagebox.showinfo("Success", f"Each roommate pays: ₹{per_person:.2f}")

            self.email_roommates(roommates_clean, per_person)


        except Exception as e:

            messagebox.showerror("Error", str(e))


    def email_roommates(self, roommates, amount):

        # Mock email reminder

        for r in roommates:

            print(f"[Email to {r}] Your share: ₹{amount:.2f}")


# ---------- Run ----------

if __name__ == "__main__":

    root = tk.Tk()

    app = BillSplitterApp(root)

    root.mainloop()


Mental Health Journal Analyzer

 import streamlit as st

from textblob import TextBlob

import pandas as pd

import matplotlib.pyplot as plt

from datetime import datetime, timedelta

import os


# CSV to store journal data

DATA_FILE = "journal_data.csv"


# Function to analyze sentiment

def analyze_sentiment(text):

    blob = TextBlob(text)

    return blob.sentiment.polarity  # -1 to 1


# Load data

def load_data():

    if os.path.exists(DATA_FILE):

        return pd.read_csv(DATA_FILE, parse_dates=['date'])

    else:

        return pd.DataFrame(columns=["date", "entry", "sentiment"])


# Save data

def save_data(entry, sentiment):

    new_data = pd.DataFrame({

        "date": [datetime.now().date()],

        "entry": [entry],

        "sentiment": [sentiment]

    })

    data = load_data()

    data = pd.concat([data, new_data], ignore_index=True)

    data.to_csv(DATA_FILE, index=False)


# Weekly sentiment plot

def plot_sentiment(data):

    recent = data[data['date'] >= (datetime.now().date() - timedelta(days=6))]

    daily_avg = recent.groupby('date')['sentiment'].mean().reset_index()


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

    plt.plot(daily_avg['date'], daily_avg['sentiment'], marker='o', linestyle='-')

    plt.title("🧠 Weekly Mental Wellness Trend")

    plt.xlabel("Date")

    plt.ylabel("Sentiment Score")

    plt.ylim(-1, 1)

    plt.axhline(0, color='gray', linestyle='--')

    plt.grid(True)

    st.pyplot(plt)


# ---------------- STREAMLIT APP ----------------


st.set_page_config(page_title="Mental Health Journal Analyzer", layout="centered")

st.title("🧠 Mental Health Journal Analyzer")

st.markdown("Write your daily mood journal and analyze your wellness trend.")


# Input

journal_entry = st.text_area("Write today's journal entry:", height=150)


if st.button("Analyze & Save"):

    if journal_entry.strip():

        sentiment = analyze_sentiment(journal_entry)

        save_data(journal_entry, sentiment)

        st.success(f"Entry saved! Sentiment Score: {sentiment:.2f}")

    else:

        st.warning("Please write something in your journal.")


# Load and plot

data = load_data()

if not data.empty:

    st.subheader("📊 Weekly Sentiment Trend")

    plot_sentiment(data)


Code-Based Game Launcher

 import tkinter as tk

from tkinter import filedialog, messagebox

import os

import subprocess


class GameLauncher:

    def __init__(self, root):

        self.root = root

        self.root.title("🕹️ Python Game Launcher")

        self.root.geometry("500x400")

        self.root.config(bg="#1e1e1e")


        self.games = []


        self.label = tk.Label(root, text="🎮 Your Python Games", font=("Helvetica", 16), fg="white", bg="#1e1e1e")

        self.label.pack(pady=10)


        self.game_listbox = tk.Listbox(root, width=50, height=15, font=("Courier", 10))

        self.game_listbox.pack(pady=10)


        self.launch_button = tk.Button(root, text="🚀 Launch Game", command=self.launch_game, bg="#28a745", fg="white", font=("Helvetica", 12))

        self.launch_button.pack(pady=5)


        self.load_button = tk.Button(root, text="📂 Load Games Folder", command=self.load_games, bg="#007bff", fg="white", font=("Helvetica", 12))

        self.load_button.pack(pady=5)


    def load_games(self):

        folder_path = filedialog.askdirectory(title="Select Game Folder")

        if not folder_path:

            return


        self.games = []

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


        for file in os.listdir(folder_path):

            if file.endswith(".py"):

                self.games.append(os.path.join(folder_path, file))

                self.game_listbox.insert(tk.END, file)


        if not self.games:

            messagebox.showinfo("No Games Found", "No Python (.py) files found in the selected folder.")


    def launch_game(self):

        selected_index = self.game_listbox.curselection()

        if not selected_index:

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

            return


        game_path = self.games[selected_index[0]]

        try:

            subprocess.Popen(["python", game_path], shell=True)

        except Exception as e:

            messagebox.showerror("Error", f"Failed to launch the game:\n{e}")



# Run the launcher

if __name__ == "__main__":

    root = tk.Tk()

    app = GameLauncher(root)

    root.mainloop()


PDF Translator

 import fitz  # PyMuPDF

from googletrans import Translator

from reportlab.pdfgen import canvas

from reportlab.lib.pagesizes import A4

import tkinter as tk

from tkinter import filedialog, simpledialog, messagebox



def extract_text_from_pdf(pdf_path):

    doc = fitz.open(pdf_path)

    full_text = ""

    for page in doc:

        full_text += page.get_text()

    doc.close()

    return full_text



def translate_text(text, dest_lang='fr'):

    translator = Translator()

    try:

        translated = translator.translate(text, dest=dest_lang)

        return translated.text

    except Exception as e:

        print("Translation error:", e)

        return None



def save_text_as_pdf(text, output_path):

    c = canvas.Canvas(output_path, pagesize=A4)

    width, height = A4

    lines = text.split('\n')

    y = height - 40


    for line in lines:

        if y < 40:  # new page

            c.showPage()

            y = height - 40

        c.drawString(40, y, line)

        y -= 15


    c.save()



def run_translator():

    pdf_path = filedialog.askopenfilename(title="Select PDF", filetypes=[("PDF files", "*.pdf")])

    if not pdf_path:

        return


    lang_code = simpledialog.askstring("Language Code", "Enter target language code (e.g., 'es' for Spanish, 'de' for German):")

    if not lang_code:

        return


    try:

        extracted_text = extract_text_from_pdf(pdf_path)

        messagebox.showinfo("Info", "Text extracted. Translating...")


        translated_text = translate_text(extracted_text, dest_lang=lang_code)

        if not translated_text:

            messagebox.showerror("Error", "Translation failed.")

            return


        save_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")])

        if not save_path:

            return


        save_text_as_pdf(translated_text, save_path)

        messagebox.showinfo("Success", f"Translated PDF saved at:\n{save_path}")

    except Exception as e:

        messagebox.showerror("Error", str(e))



# GUI

root = tk.Tk()

root.title(" PDF Translator")

root.geometry("400x200")


label = tk.Label(root, text="PDF Translator", font=("Arial", 16))

label.pack(pady=20)


translate_btn = tk.Button(root, text="Select and Translate PDF", command=run_translator, bg="#007BFF", fg="white", font=("Arial", 12))

translate_btn.pack(pady=10)


root.mainloop()


Real-Time Location Tracker

 import tkinter as tk

from tkinter import messagebox

import requests

import folium

import webbrowser

from geopy.geocoders import Nominatim

import os


def get_location():

    try:

        response = requests.get("https://ipinfo.io/json")

        data = response.json()

        loc = data['loc'].split(',')

        latitude = float(loc[0])

        longitude = float(loc[1])

        city = data.get('city', 'Unknown')

        return latitude, longitude, city

    except Exception as e:

        messagebox.showerror("Error", f"Could not get location.\n{str(e)}")

        return None, None, None


def show_location():

    lat, lon, city = get_location()

    if lat is None or lon is None:

        return


    # Reverse geocode to get address

    geolocator = Nominatim(user_agent="geoapiExercises")

    location = geolocator.reverse((lat, lon), language="en")

    address = location.address if location else "Address not found"


    # Show location on map

    map_obj = folium.Map(location=[lat, lon], zoom_start=14)

    folium.Marker([lat, lon], popup=f"{address}", tooltip="You are here").add_to(map_obj)


    map_file = "real_time_location.html"

    map_obj.save(map_file)

    webbrowser.open(f"file://{os.path.abspath(map_file)}")


    location_label.config(text=f"City: {city}\nLatitude: {lat}\nLongitude: {lon}\n\n{address}")


# GUI

app = tk.Tk()

app.title("📍 Real-Time Location Tracker")

app.geometry("500x300")


tk.Label(app, text="Click the button to track your location", font=("Arial", 14)).pack(pady=20)


tk.Button(app, text="Track My Location", command=show_location, bg="#1E90FF", fg="white", font=("Arial", 12)).pack(pady=10)


location_label = tk.Label(app, text="", font=("Arial", 10), justify="left", wraplength=450)

location_label.pack(pady=20)


app.mainloop()