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


Podcast Downloader & Organizer

import tkinter as tk

from tkinter import filedialog, messagebox, Listbox, Scrollbar

import feedparser

import requests

import os


def fetch_episodes():

    url = url_entry.get()

    if not url:

        messagebox.showerror("Error", "Please enter a podcast RSS feed URL.")

        return

    

    global feed

    feed = feedparser.parse(url)

    episodes_list.delete(0, tk.END)


    if not feed.entries:

        messagebox.showerror("Error", "No episodes found or invalid RSS URL.")

        return


    for i, entry in enumerate(feed.entries[:20]):

        title = entry.title

        episodes_list.insert(tk.END, f"{i+1}. {title}")


def download_selected():

    selected = episodes_list.curselection()

    if not selected:

        messagebox.showerror("Error", "Please select an episode to download.")

        return


    entry = feed.entries[selected[0]]

    title = feed.feed.title

    episode_title = entry.title

    audio_url = entry.enclosures[0].href if entry.enclosures else None


    if not audio_url:

        messagebox.showerror("Error", "No audio found in this episode.")

        return


    folder = os.path.join("Podcasts", title)

    os.makedirs(folder, exist_ok=True)

    filename = os.path.join(folder, f"{episode_title}.mp3")


    try:

        r = requests.get(audio_url, stream=True)

        with open(filename, 'wb') as f:

            for chunk in r.iter_content(1024):

                f.write(chunk)

        messagebox.showinfo("Success", f"Downloaded: {episode_title}")

    except Exception as e:

        messagebox.showerror("Download Failed", str(e))


# GUI setup

app = tk.Tk()

app.title("๐ŸŽ™️ Podcast Downloader & Organizer")

app.geometry("500x400")


tk.Label(app, text="Enter Podcast RSS Feed URL:").pack(pady=5)

url_entry = tk.Entry(app, width=60)

url_entry.pack(pady=5)


tk.Button(app, text="Fetch Episodes", command=fetch_episodes).pack(pady=5)


frame = tk.Frame(app)

frame.pack(pady=10, fill=tk.BOTH, expand=True)


scrollbar = Scrollbar(frame)

scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


episodes_list = Listbox(frame, yscrollcommand=scrollbar.set, width=80)

episodes_list.pack(padx=10, pady=10, expand=True)

scrollbar.config(command=episodes_list.yview)


tk.Button(app, text="Download Selected Episode", command=download_selected, bg="#4CAF50", fg="white").pack(pady=10)


app.mainloop()


Invoice Data Extractor

import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image

import pytesseract

from pdf2image import convert_from_path

import re

import os


# Optional: Set Tesseract path

# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'


def extract_text_from_file(file_path):

    if file_path.lower().endswith('.pdf'):

        images = convert_from_path(file_path, dpi=300)

        text = ""

        for image in images:

            text += pytesseract.image_to_string(image)

        return text

    elif file_path.lower().endswith(('.png', '.jpg', '.jpeg')):

        image = Image.open(file_path)

        return pytesseract.image_to_string(image)

    else:

        return ""


def extract_invoice_data(text):

    invoice_number = re.search(r'Invoice\s*#?:?\s*(\w+)', text, re.IGNORECASE)

    date = re.search(r'Date\s*:?(\s*\d{1,2}/\d{1,2}/\d{2,4})', text, re.IGNORECASE)

    total = re.search(r'Total\s*:?[\s$]*(\d+[\.,]?\d*)', text, re.IGNORECASE)


    return {

        "Invoice Number": invoice_number.group(1) if invoice_number else "Not Found",

        "Date": date.group(1).strip() if date else "Not Found",

        "Total Amount": total.group(1) if total else "Not Found"

    }


def process_invoice():

    file_path = filedialog.askopenfilename(title="Select Invoice", filetypes=[("PDF/Image Files", "*.pdf *.jpg *.png *.jpeg")])

    if not file_path:

        return


    text = extract_text_from_file(file_path)

    data = extract_invoice_data(text)


    result = f"""

    ๐Ÿ“„ File: {os.path.basename(file_path)}

    ๐Ÿงพ Invoice Number: {data['Invoice Number']}

    ๐Ÿ“… Date: {data['Date']}

    ๐Ÿ’ฐ Total: {data['Total Amount']}

    """

    messagebox.showinfo("Extracted Invoice Data", result)


# GUI Setup

app = tk.Tk()

app.title("๐Ÿงพ Invoice Data Extractor")

app.geometry("400x200")

app.configure(bg="#f9f9f9")


label = tk.Label(app, text="Click below to select an invoice PDF or image", bg="#f9f9f9", font=("Helvetica", 12))

label.pack(pady=20)


btn = tk.Button(app, text="Select Invoice", command=process_invoice, bg="#4CAF50", fg="white", font=("Helvetica", 12), padx=10, pady=5)

btn.pack()


app.mainloop()


File Locker CLI

import argparse

import getpass

import os

from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives import hashes

from cryptography.fernet import Fernet

import base64


def derive_key(password: str, salt: bytes) -> bytes:

    kdf = PBKDF2HMAC(

        algorithm=hashes.SHA256(),

        length=32,

        salt=salt,

        iterations=390000,

        backend=default_backend()

    )

    return base64.urlsafe_b64encode(kdf.derive(password.encode()))


def encrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        data = file.read()


    salt = os.urandom(16)

    key = derive_key(password, salt)

    fernet = Fernet(key)

    encrypted_data = fernet.encrypt(data)


    with open(filepath + ".locked", 'wb') as file:

        file.write(salt + encrypted_data)


    os.remove(filepath)

    print(f"๐Ÿ”’ File encrypted as {filepath}.locked")


def decrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        content = file.read()


    salt = content[:16]

    encrypted_data = content[16:]

    key = derive_key(password, salt)

    fernet = Fernet(key)


    try:

        decrypted_data = fernet.decrypt(encrypted_data)

    except Exception:

        print("❌ Wrong password or corrupted file.")

        return


    original_path = filepath.replace(".locked", "")

    with open(original_path, 'wb') as file:

        file.write(decrypted_data)


    os.remove(filepath)

    print(f"๐Ÿ”“ File decrypted as {original_path}")


def main():

    parser = argparse.ArgumentParser(description="๐Ÿ” File Locker CLI")

    parser.add_argument("action", choices=["lock", "unlock"], help="Lock or unlock the file")

    parser.add_argument("filepath", help="Path to the file")


    args = parser.parse_args()

    password = getpass.getpass("Enter password: ")


    if args.action == "lock":

        encrypt_file(args.filepath, password)

    elif args.action == "unlock":

        decrypt_file(args.filepath, password)


if __name__ == "__main__":

    main()